In this post, I want to explore a way to establish 100,000 connections to MySQL. Not just idle connections, but executing queries.

100,000 connections. Is that really needed for MySQL, you may ask? Although it may seem excessive, I have seen a lot of different setups in customer deployments. Some deploy an application connection pool, with 100 application servers and 1,000 connections in each pool. Some applications use a “re-connect and repeat if the query is too slow” technique, which is a terrible practice. It can lead to a snowball effect, and could establish thousands of connections to MySQL in a matter of seconds.

So now I want to set an overachieving goal and see if we can achieve it.

Setup

For this I will use the following hardware:

Bare metal server provided by packet.net, instance size: c2.medium.x86
 Physical Cores @ 2.2 GHz
 (1 X AMD EPYC 7401P)
 Memory: 64 GB of ECC RAM
 Storage : INTEL® SSD DC S4500, 480GB

This is a server grade SATA SSD.

I will use five of these boxes, for the reason explained below. One box for the MySQL server and four boxes for client connections.

For the server I will use Percona  Server for MySQL 8.0.13-4 with the thread pool plugin. The plugin will be required to support the thousands of connections.

 

Initial server setup

Network settings (Ansible format):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- { name: 'net.core.somaxconn', value: 32768 }
- { name: 'net.core.rmem_max', value: 134217728 }
- { name: 'net.core.wmem_max', value: 134217728 }
- { name: 'net.ipv4.tcp_rmem', value: '4096 87380 134217728' }
- { name: 'net.ipv4.tcp_wmem', value: '4096 87380 134217728' }
- { name: 'net.core.netdev_max_backlog', value: 300000 }
- { name: 'net.ipv4.tcp_moderate_rcvbuf', value: 1 }
- { name: 'net.ipv4.tcp_no_metrics_save', value: 1 }
- { name: 'net.ipv4.tcp_congestion_control', value: 'htcp' }
- { name: 'net.ipv4.tcp_mtu_probing', value: 1 }
- { name: 'net.ipv4.tcp_timestamps', value: 0 }
- { name: 'net.ipv4.tcp_sack', value: 0 }
- { name: 'net.ipv4.tcp_syncookies', value: 1 }
- { name: 'net.ipv4.tcp_max_syn_backlog', value: 4096 }
- { name: 'net.ipv4.tcp_mem', value: '50576   64768 98152' }
- { name: 'net.ipv4.ip_local_port_range', value: '4000 65000' }
- { name: 'net.ipv4.netdev_max_backlog', value: 2500 }
- { name: 'net.ipv4.tcp_tw_reuse', value: 1 }
- { name: 'net.ipv4.tcp_fin_timeout', value: 5 }
These are the typical settings recommended for 10Gb networks and high concurrent workloads.

Limits settings for systemd:

1
2
3
[Service]
LimitNOFILE=1000000
LimitNPROC=500000

And the relevant setting for MySQL in my.cnf:

1
2
back_log=3500
max_connections=110000

For the client I will use sysbench version 0.5 and not 1.0.x, for the reasons explained below.

The workload is 

sysbench --test=sysbench/tests/db/select.lua --mysql-host=139.178.82.47 --mysql-user=sbtest --mysql-password=sbtest --oltp-tables-count=10 --report-interval=1 --num-threads=10000 --max-time=300 --max-requests=0 --oltp-table-size=10000000 --rand-type=uniform --rand-init=on run

 

Step 1. 10,000 connections

This one is very easy, as there is not much to do to achieve this. We can do this with only one client. But you may face the following error on the client side:

 FATAL: error 2004: Can't create TCP/IP socket (24)

This is caused by the open file limit, which is also a limit of TCP/IP sockets. This can be fixed by setting

ulimit -n 100000  on the client.

The performance we observe:

 
1
2
[  26s] threads: 10000, tps: 0.00, reads: 33367.48, writes: 0.00, response time: 3681.42ms (95%), errors: 0.00, reconnects:  0.00
[  27s] threads: 10000, tps: 0.00, reads: 33289.74, writes: 0.00, response time: 3690.25ms (95%), errors: 0.00, reconnects:  0.00
Step 2. 25,000 connections

With 25,000 connections, we hit an error on MySQL side:

Can't create a new thread (errno 11); if you are not out of available memory, you can consult the manual for a possible OS-dependent bug

 

If you try to lookup information on this error you might find the following article:  

https://www.percona.com/blog/2013/02/04/cant_create_thread_errno_11/

 

But it does not help in our case, as we have all limits set high enough:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
cat /proc/`pidof mysqld`/limits
Limit                     Soft Limit Hard Limit           Units
Max cpu time              unlimited  unlimited            seconds
Max file size             unlimited  unlimited            bytes
Max data size             unlimited  unlimited            bytes
Max stack size            8388608    unlimited            bytes
Max core file size        0          unlimited            bytes
Max resident set          unlimited  unlimited            bytes
Max processes             500000     500000               processes
Max open files            1000000    1000000              files
Max locked memory         16777216   16777216             bytes
Max address space         unlimited  unlimited            bytes
Max file locks            unlimited  unlimited            locks
Max pending signals       255051     255051               signals
Max msgqueue size         819200     819200               bytes
Max nice priority         0          0
Max realtime priority     0          0
Max realtime timeout      unlimited unlimited            us

This is where we start using the thread pool feature:  https://www.percona.com/doc/percona-server/8.0/performance/threadpool.html">https://www.percona.com/doc/percona-server/8.0/performance/threadpool.html

Add:

 thread_handling=pool-of-threads

to the my.cnf and restart Percona Server

The results:

 
 
1
2
[   7s] threads: 25000, tps: 0.00, reads: 33332.57, writes: 0.00, response time: 974.56ms (95%), errors: 0.00, reconnects:  0.00
[   8s] threads: 25000, tps: 0.00, reads: 33187.01, writes: 0.00, response time: 979.24ms (95%), errors: 0.00, reconnects:  0.00
We have the same throughput, but actually the 95% response time has improved (thanks to the thread pool) from 3690 ms to 979 ms.

Step 3. 50,000 connections

This is where we encountered the biggest challenge. At first, trying to get 50,000 connections in sysbench we hit the following error:

 FATAL: error 2003: Can't connect to MySQL server on '139.178.82.47' (99)

Error (99) is cryptic and it means: Cannot assign requested address.

It comes from the limit of ports an application can open. By default on my system it is

 cat /proc/sys/net/ipv4/ip_local_port_range : 32768   60999

This says there are only 28,231 available ports — 60999 minus 32768 — or the limit of TCP connections you can establish from or to the given IP address.

You can extend this using a wider range, on both the client and the server:

 echo 4000 65000 > /proc/sys/net/ipv4/ip_local_port_range

This will give us 61,000 connections, but this is very close to the limit for one IP address (maximal port is 65535). The key takeaway from here is that if we want more connections we need to allocate more IP addresses for MySQL server. In order to achieve 100,000 connections, I will use two IP addresses on the server running MySQL.

After sorting out the port ranges, we hit the following problem with sysbench:

1
2
3
4
5
6
sysbench 0.5:  multi-threaded system evaluation benchmark
 
Running the test with following options:
Number of threads: 50000
 
FATAL: pthread_create() for thread #32352 failed. errno = 12 (Cannot allocate memory)
In this case, it’s a problem with sysbench memory allocation (namely lua subsystem). Sysbench can allocate memory for only 32,351 connections. This is a problem which is even more severe in sysbench 1.0.x.

Sysbench 1.0.x limitation

Sysbench 1.0.x uses a different Lua JIT, which hits memory problems even with 4000 connections, so it is impossible to go over 4000 connection in sysbench 1.0.x

So it seems we hit a limit with sysbench sooner than with Percona Server. In order to use more connections, we need to use multiple sysbench clients, and if 32,351 connections is the limit for sysbench, we have to use at least four sysbench clients to get up to 100,000 connections.

For 50,000 connections I will use 2 servers (each running separate sysbench), each running 25,000 threads from sysbench.

The results for each sysbench looks like:

1
2
[  29s] threads: 25000, tps: 0.00, reads: 16794.09, writes: 0.00, response time: 1799.63ms (95%), errors: 0.00, reconnects:  0.00
[  30s] threads: 25000, tps: 0.00, reads: 16491.03, writes: 0.00, response time: 1800.70ms (95%), errors: 0.00, reconnects:  0.00
So we have about the same throughput (16794*2 = 33588 tps in total), however the 95% response time doubled. This is to be expected as we are using twice as many connections compared to the 25,000 connections benchmark.

Step 3. 75,000 connections

To achieve 75,000 connections we will use three servers with sysbench, each running 25,000 threads.

The results for each sysbench:

 
 
1
2
[ 157s] threads: 25000, tps: 0.00, reads: 11633.87, writes: 0.00, response time: 2651.76ms (95%), errors: 0.00, reconnects:  0.00
[ 158s] threads: 25000, tps: 0.00, reads: 10783.09, writes: 0.00, response time: 2601.44ms (95%), errors: 0.00, reconnects:  0.00

Step 4. 100,000 connections

There is nothing eventful to achieve75k and 100k connections. We just spin up an additional server and start sysbench. For 100,000 connections we need four servers for sysbench, each shows:

1
2
[ 101s] threads: 25000, tps: 0.00, reads: 8033.83, writes: 0.00, response time: 3320.21ms (95%), errors: 0.00, reconnects:  0.00
[ 102s] threads: 25000, tps: 0.00, reads: 8065.02, writes: 0.00, response time: 3405.77ms (95%), errors: 0.00, reconnects:  0.00
 

So we have the same throughput (8065*4=32260 tps in total) with 3405ms 95% response time.

A very important takeaway from this: with 100k connections and using a thread pool, the 95% response time is even better than for 10k connections without a thread pool. The thread pool allows Percona Server to manage resources more efficiently and provides better response times.

Conclusions

100k connections is quite achievable for MySQL, and I am sure we could go even further. There are three components to achieve this:

  • Thread pool in Percona Server
  • Proper tuning of network limits
  • Using multiple IP addresses on the server box (one IP address per approximately 60k connections)

Appendix: full my.cnf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
[mysqld]
datadir {{ mysqldir }}
ssl=0
 
skip-log-bin
log-error=error.log
 
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
character_set_server=latin1
collation_server=latin1_swedish_ci
skip-character-set-client-handshake
 
innodb_undo_log_truncate=off
 
# general
table_open_cache = 200000
table_open_cache_instances=64
back_log=3500
max_connections=110000
 
# files
innodb_file_per_table
innodb_log_file_size=15G
innodb_log_files_in_group=2
innodb_open_files=4000
 
# buffers
innodb_buffer_pool_size= 40G
innodb_buffer_pool_instances=8
innodb_log_buffer_size=64M
 
# tune
innodb_doublewrite= 1
innodb_thread_concurrency=0
innodb_flush_log_at_trx_commit= 0
innodb_flush_method=O_DIRECT_NO_FSYNC
innodb_max_dirty_pages_pct=90
innodb_max_dirty_pages_pct_lwm=10
innodb_lru_scan_depth=2048
innodb_page_cleaners=4
join_buffer_size=256K
sort_buffer_size=256K
innodb_use_native_aio=1
innodb_stats_persistent = 1
 
#innodb_spin_wait_delay=96
innodb_adaptive_flushing = 1
innodb_flush_neighbors = 0
innodb_read_io_threads = 16
innodb_write_io_threads = 16
innodb_io_capacity=1500
innodb_io_capacity_max=2500
innodb_purge_threads=4
innodb_adaptive_hash_index=0
max_prepared_stmt_count=1000000
innodb_monitor_enable = '%'
performance_schema = ON

- Tomcat8 과 MariaDB 방화벽 해제

1. vi /etc/sysconfig/iptables   (2,3,4 가가 에디터에 입력안될 경우 패스합니다. 저는 기본적으로 열려있었습니다.)

2. -A INPUT -p tcp -dprot 8080 -j ACCEPT

3. -A INPUT -p tcp -dprot 8443 -j ACCEPT

4. -A INPUT -p tcp -dprot 3306 -j ACCEPT

5. service iptables save

6. service iptables restart

 

- JAVA 1.8.192 설치

- RPM 위치: /download/jdk-8u192-linux-x64.rpm

- 설치 명령어

1. cd /download

2. rpm -Uvh jdk-8u192-linux-x64.rpm

3. export JAVA_HOME=/usr/java/jdk1.8.0_192-amd64/

4. export PATH=$PATH:$JAVA_HOME/bin

5. vi /ect/profile

6. 맨 마지막 줄에 export JAVA_HOME=/usr/java/jdk1.8.0_192-amd64/ 와 export PATH=$PATH:$JAVA_HOME/bin 추가 한다.

7. 저장 후 source /etc/profile

 

- Tomcat 8 설치

- ZIP 파일 위치: /download/apache-tomcat-8.5.41.zip

- 설치 명령어

1. /data/ 폴더를 먼저 생성한다.

2. cd /download

3. unzip ./apache-tomcat-8.5.41.zip -d /data/

4. /data/apache-tomcat-8.5.41 라는 폴더안에 압축히 해제되어있다.

5. apache-tomcat-8.5.41 폴더명을 원하는 폴더명으로 변경한다.

(현재 tomcat8 로 변경함)

6. /data/tomcat8/conf 의 server.xml 에서 8080 포트에 URIEncoding="UTF-8" 를 추가한다.

7. /data/tomcat8/bin 으로 이동한다.

8. chmod 700 *.sh 명령어 실행한다(startup.sh 를 실행하면 명령거부가 나오기 때문이다.)

9. ./startup.sh 명령어 실행하면 시작된다.

 

- 서비스 등록

1. 톰캣을 먼저 종료 한다.

2. vi /etc/init.d/tomcat 에 아래의 내용을 입력한다.

```

#!/bin/bash

# description: tomcat start stop restart

# proccessname: tomcat

# chkconfig: 234 20 80

 

export JAVA_HOME=/usr/java/jdk1.8.0_192-amd64/

export CATALINA_HOME=/data/tomcat

 

case $1 in

start)

echo “Start tomcat “

sh $CATALINA_HOME/bin/startup.sh

;;

stop)

echo “shutdown tomcat “

sh $CATALINA_HOME/bin/shutdown.sh

;;

restart)

echo “restart tomcat “

sh $CATALINA_HOME/bin/shutdown.sh

sh $CATALINA_HOME/bin/startup.sh

;;

*)

echo “Usage: service tomcat {start|stop|restart}”

exit 1

esac

exit 0

```

3. chmod 755 /etc/init.d/tomcat

4. 시작 service tomcat start / 종료 service tomcat stop

 

- MariaDB 설치

- 설치 명령어

1. yum remove mysql-*

2. rm /etc/my.cnf (참고: No surch file or directory 가 나와도 당황하지말고 4번까지 진행한다.)

3. rm -r /var/log/mysql

4. rm -r /var/lib/mysql

5. vi /etc/yum.repos.d/MariaDB.repo

```

# MariaDB 10.3 CentOS repository list - created 2019-05-30 09:07 UTC

# http://downloads.mariadb.org/mariadb/repositories/

[mariadb]

name = MariaDB

baseurl = http://yum.mariadb.org/10.3/centos6-amd64

gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB

gpgcheck=1

```

6. yum install MariaDB-server MariaDB-client

7. mysql_install_db --defaults-file=/etc/my.cnf

8. service mysql start

9. mysql -u root -p

(비밀번호 입력하라고 나오지만 초기에는 없으므로 그냥 엔터 친다.)

10. 이제 아래의 쿼리문으로 비밀번호도 지정하고 외부 접속 및 계정을 생성하면되니다.

```

# root 계정 비밀번호 지정

use mysql

update user set password=password('비밀번호') where user='root';

FLUSH PRIVILEGES;

 

# root 계정 외부 접속

use mysql

grant all privileges on *.* to 'root'@'%' identified by '비밀번호';

FLUSH PRIVILEGES;

 

# 타 계정 외부 접속 및 생성 설정

use mysql

grant all privileges on *.* to '아이디'@'%' identified by '비밀번호';

FLUSH PRIVILEGES;

 

grant all privileges on *.* to '아이디'@'%';

flush privileges;

 

타 계정 내부 접속 및 생성 설정

use mysql

grant all privileges on *.* to '아이디'@'localhost' identified by '비밀번호';

FLUSH PRIVILEGES;

 

grant all privileges on *.* to '아이디'@'localhost';

flush privileges;

```

 

- Master Slave 설정

1. 마스터 서버의 설정 파일을 변경해줍니다.

```

1. vi /etc/mysql/my.cnf 로 vi 에디터를 엽니다.

2. 맨 아래 줄에 아래의 내용을 입력 후 저장 후 MYSQL 을 재시작합니다.

server_id = 1

log_bin = mysql.bin

3. mysql 로 접속하여 슬레이브들이 사용할 계정을 생성합니다.

- grant replication slave,replication client on *.* to repl@'%' identified by 'slave@1039';

- FLUSH PRIVILEGES;

4. 간혹 위와 같이 수정해도 적용이 안되는 현상이 있으므로 msql에 접속하여 다시한번더 설정을 해봅니다.

- show variables like 'server_id';

- SET GLOBAL server_id = 1;

5. server_id 가 1이 나오면 정상적으로 설정이 된것입니다.

6. mysql에 아래의 명령어를 입력하여 fil, position 컬럼의 값을 확인합니다.

- show master status;

```

2. 슬레이브 서버의 설정 파일을 변경해줍니다.

```

1. vi /etc/mysql/my.cnf 로 vi 에디터로 엽니다

2. 맨 아래 줄에 아래의 내용을 입력 후 저장 후 MYSQL 을 재시작합니다.

server_id = 2

log_bin = mysql.bin

relay_log = mysql-relay-bin

log_slave_updates=1

read_only=1

3. 간혹 위와 같이 수정해도 적용이 안되는 현상이 있으므로 msql에 접속하여 다시한번더 설정을 해봅니다.

- show variables like 'server_id';

- SET GLOBAL server_id = 1;

4. server_id 가 1이 나오면 정상적으로 설정이 된것입니다.

5. 아래의 쿼리문을 실행하여 마스터 정보를 입력합니다.

(아이디 패스워드, 로그파일은 위 마스터 에서 설정한것으로 사용합니다.)

- CHANGE MASTER TO MASTER_HOST='master서버IP', MASTER_USER='repl', MASTER_PASSWORD='password',MASTER_PORT=3306,MASTER_LOG_FILE='mariadb-bin.000226,MASTER_CONNECT_RETRY=10;

6. 슬래이브를 시작하는 쿼리문을 실행합니다.

- start slave;

7. 슬래이브 동작 확인 쿼리는 아래와 같습니다.

- show slave status;

8. 7번 쿼리에서 Slave_IO_Running, Slave_SQL_Running 가 YES 이면 정상적으로 구동되는것입니다,.

```




리눅스 CentOS 7 버전에서 도커를 이용하여 모니터링을 구축하여 사용하기



1. CentOS 7에 도커를 설치합니다.

 - 명령어: sudo yum install docker


2. 도커 설치가 완료 되었으면 도커 서비스를 실행합니다.

 - 명령어: sudo service docker start


※ 그 외의 도커 명령어

- 부팅시 도커 자동으로 실행하기: sudo chkconfig docker on

- 도커 버전 확인 하기: sudo docker version

- 도커 실행 명령어: docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

옵션 설명

    -d detached mode 흔히 말하는 백그라운드 모드

    -p 호스트와 컨테이너의 포트를 연결 (포워딩)

    -v 호스트와 컨테이너의 디렉토리를 연결 (마운트)

    -e 컨테이너 내에서 사용할 환경변수 설정

    –name 컨테이너 이름 설정

    –rm 프로세스 종료시 컨테이너 자동 제거

    -it -i와 -t를 동시에 사용한 것으로 터미널 입력을 위한 옵션

    –link 컨테이너 연결 [컨테이너명:별칭]

- 도커 이미지 찾기(Name에 찾을 이미지를 입력하면 됩니다.): sudo docker search <Name>

- 다운받은 이미지 확인: sudo docker images

- 도커 컨테이너 확인하기: sudo docker ps -a

- 도커 컨테이너 삭제하기: sudo docker rm <컨테이너ID>

- 도커 컨테니어 접속(컨테이너명은 컨테이너 확인하기로 이름을 알아낸다.): sudo docker exec -it <컨테이너 이름> /bin/bash

- 그외의 자세한 사항: https://docs.docker.com/ 에서 확인해주세요.


3. 모니터링을 위해 Grafana, Telegraf, Influxdb를 설치해야 합니다. 하지만 도커에서 찾아보니 docker-statsd-influxdb-grafana 이 존재하여 이 이미지를 설치 합니다.

- 명령어: sudo docker pull samuelebistoletti/docker-statsd-influxdb-grafana

- 도커 이미지명: docker-statsd-influxdb-grafana

- 해당 도커 Git URL: https://github.com/samuelebistoletti/docker-statsd-influxdb-grafana


4. 설치가 완료되었으면 해당 이미지로 컨테이너로 만들어 실행합니다.

- 명령어: docker run --ulimit nofile=66000:66000 -d -it --name docker-statsd-influxdb-grafana -p 3003:3003 -p 3004:8888 -p 8086:8086 -p 22022:22 -p 8125:8125/udp samuelebistoletti/docker-statsd-influxdb-grafana:latest


5. 도커를 실행하였으면 이제 브라우저에서 그라파나를 접속 합니다.

- URL: http://localhost:3003

- 기본 그라파나 계정 및 비밀번호: root/root (추후 그라파나 관리자에서 계정 및 비밀번호를 변경해주세요.)



6. 그라파나에 접속하면 기본적으로 influxdb 데이터소스까지 설정이 되어있을 것입니다. 

  이제 우리가 할 일은 telegraf에서 수집한 정보를 그래프로 만들기만 하면 됩니다.


7. 이제 그래프를 만들기 시작합니다. cpu, mem, disk, processes, diskio 등등.. 저는 제가 필요한 cpu, mem, disk, prrocesses 만 만들어봤습니다.


8. 만약 Mysql 혹은 그외의 다른것들을 Telegraf를 통해서 수집을 하고 싶은 경우 docker 에서 해당 컨테이너로 접속 후

   /etc/telegraf/telegraf.conf 파일을 vim 으로 여신 후 설정을 변경하여 컨테이너를 재시작하면 다른 정보도 수집을 할 수 있습니다.

   자세한것은 Telegraf 공식 홈페이지를 참고해 주세요.



9. CPU 그래프 만들기






10. Disk 그래프 만들기



11. 메모리 그래프 만들기




12. 프로세스 그래프 만들기



13. 원하는 그래프를 완성하였다면 각 그래프마다 Share 기능을 통해서 URL, IFRAME, SnapShot 을 통해서 해당 그래프를 원하는 위치에 공유를 하면 됩니다.


그리고 Share시 파라미터 값에 from=now-1h&to=now&refresh=10s 이렇게 넣어주면 현재 시간에 1시간 전 부터 지금까지, 10초 마다 자동으로 리프레쉬가 됩니다.




14. 그리고 그래프를 다른사람이 만든것을 사용하고 싶으시면 https://grafana.com/dashboards/ 여기에서 json 파일을 다운 받아서

     그라파나에서 import를 통해서 json 파일을 그래프로 추가 할 수 있습니다.

아래 2개의 JSON은 해당 사이트에서 받은 파일 입니다.



linux-system-overview_rev1.json

service-mysql-metrics_rev1.json





1. https://grafana.com/get 사이트에서 Grafana를 다운로드 합니다.


2. 원하는 위치에 다운로드한 grafana를 압축 해제 합니다.


3. CMD 명령프롬프트를 실행 후 압축을 해제한 곳으로 이동 후 bin/폴더로 이동 후 grafana-server 명령어를 실행하면


grafana가 실행이 됩니다.


4. 브라우저를 실행 후 localhost:3000 으로 접속하면 아래와 같이 grafana 사이트가 열립니다.


최초 접속시 admin 계정의 비밀번호는 admin 입니다. 로그인을 하면 비밀번호를 변경할것이냐고 묻는데 이때 admin 비밀번호를 변경하면 됩니다.



InfluxDB CLI 에서 Database를 생성하여 사용하고 데이터를 넣어보겠습니다.


- Database 생성 CLI 명령어: CREATE DATABASE <database name>


- 생성한 Database 사용 명령어: use <database name>


데이터베이스를 생성하고 사용하기 까지 완료하였으면 이제 데이터를 넣을 차례입니다.


보통의 RDBMS에서는 이 다음에 해야할 일은 테이블을 생성하는 것이지만 InfluxDB는 테이블을 생성하지 않고 measurment를 생성하여


 바로 Insert문을 실행합니다.


- 데이터 Insert 명령어: insert monitoring,cpu=i5,core=5 memory=600,disk=50000


이렇게 하면 데이터가 Insert 됩니다. 해당 Insert문의 설명은 아래와 같습니다.



measurement(저장되는 값의 성격) : RDBMS에서의 table을 말합니다.

tag : 인덱스되는 컬럼

field : 인덱스가 되지 않는 컬럼


measurement : monitoring

TAG 키 : cpu, core

TAG 값 : i5, 5

FIELD 키 : memory, disk

FIELD 값 : 600, 50000



- 입력된 값을 조회하려면: SELECT * FROM <measurement name> 


이상입니다.

InfluxDB를 사용할때 사용자 인증설정 즉 influxdb.conf 파일에서 


auth-enable = true 로 설정하게 되면 InfluxDB를 사용할 때 로그인을 해야 해당 기능을 사용 할 수 있습니다.


우선 해당 설정을 true로 해놓고 InfluxDB에 접근하여 사용자 생성을 해보겠습니다.


먼저 사용자 생성시 auth-enable = false 로 해두고 InfluxDB CLI로 접근하였습니다.



- 사용자 생성


1. CREATE USER <username> WITH PASSWORD '<password>' WITH ALL PRIVILEGES


해당 명령어는 사용자를 생성합니다. InfluxDB에는 기본적으로 admin 계정이 생성되어있는데 여기에 username을 admin으로하고 비밀번호를 설정하면


admin 계정의 비밀번호가 변경 됩니다.


2. GRANT ALL PRIVILEGES TO <username>


 해당 계정에 권한을 주는 역활을 합니다.



이렇게 하면 완료가 됩니다. 만약에 데이터베이스 별로 사용자 권한을 주고 싶은 경우


GRANT [READ,WRITE,ALL] ON <database_name> TO <username>


이 명령어를 사용하면 됩니다.



그리고 이렇게 사용자 계정을 전부 만들고 난 후 다시 conf 파일에서 auth-enable = true 로 변경하고 InfluxDB를 재시작 후


InfluxDB CLI 접속 시 


influx.exe -username "username" -password "password" 명령어로 CLI에 접속을 하면 됩니다.



마지막으로 해당 내용은 공식 문서 있습니다.( https://docs.influxdata.com/influxdb/v1.7/administration/authentication_and_authorization/#set-up-authentication )

해당글은 InfluxDB 1.7 기준으로 작성하였습니다.




InfluxDB를 사용하기 위해 윈도우 10에서 설치를 진행하였습니다.


1. InfluxDB 공식 사이트에서 InfluxDB 윈도우 버전을 다운로드 합니다.


2. 적절한 위치에 다운받은 InfluxDB의 압축을 해제 합니다.


3. 압축을 해제 한 뒤 해당 폴더의 influxdb.conf의 파일을 수정합니다.


이 파일을 열어보시면 대부분 주석이 되어있는데 저는 기본으로 설정하여 사용 테스트를 하였습니다.


아래의 첨부파일에 conf 파일을 첨부하였습니다.


influxdb.conf



4. CMD 명령프롬프트 창을 실행 후 압축을 해제한 InfluxDB 폴더로 이동 후


influxd -config influxed.conf 라고 명령을 실행하면 InfluxDB가 실행이 됩니다.


5. 이제 쿼리문을 날려봐야하는데 1.3 버전 이후로는 InfluxDB Admin 웹 페이지가 있었는데 사라진걸로 알고 있습니다. 


그래서 우리는 CMD 명령프롬프트 창에서 명령을 날려보겠습니다.(chrongraf 로 대체 되었습니다.)


6. CMD 명령프롬프트 창을 실행 후 압축을 해제한 InfluxDB 폴더로 이동 후


influx.exe 를 실행하면 쿼리를 실행 할 수 있는  CLI로 접근 할 수 있습니다.

Elasticsearch와 Logstash, Kibana 를 사용할때 아무래도 기본 Defualt 설정보다 Security를 이용해서


계정, 비밀번호를 셋팅해서 사용하면 더 안전하지 않을까 하고 알아보던 중 해당 기능은 X-pack으로 설정을 해야되는데


6.3 이후로 X-pack과 통합되면서 라이센스 부분이 걸려서 Security를 사용하지 못하하네요.


골드부터 Security를 사용 가능하다고 나오니.. 모니터링 시스템도 일부 지원하지만 제대로 사용하라면 라이센스가 필요하군요.


우선은 기본으로만 설정해서 외부접근이 안되게 사용해야 될거같습니다.


출처: https://www.elastic.co/subscriptions

+ Recent posts