Elasticsearch  node.js를 이용해서 데이터 입력(PUT) 하기


logstash이 잘되어있어서 패턴 잘구성해서 logstash을 이용해도 되지만 logstash패턴 사용하는 법을 좀 봐야되고...

잘 사용법도 모르는 환경에서 계속 서비스 RDBMS에 커넥션 유지하는 것도 부담스러워서 따로 node.js로 짜기로함 


기본적으로 콘솔에서 curl 날리는 예시는 아래와 같음

$ curl -XPUT 'http://localhost:9200/logstash-2015.03.06/access_log/1' -d '{ > "host": "web01", > "http_host": "192.168.1.123", > "clientip": "192.2.3.55", > "timestamp": "Fri Feb 06 2015 14:04:22 GMT+0900 (KST)", > "verb": "GET", > "request": "/css/comm.css", > "httpversion": "1.1", > "response": "304", > "bytes": "0", > "referrer": "http://192.168.1.124/", > "agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17", > "request_time": 0 > }'


등록 결과  아래와 같이 나온걸 볼 수 있다

{"_index":"logstash-2015.03.06","_type":"access_log","_id":"1","_version":1,"created":true}


브라우져에서 head 들어가보면 확인 가능하다.

http://localhost:9200/_plugin/head/


이걸 node.js http라이브러리이용하면 간단하다.

var http = require('http'); function elasticsearchPut(index,type,id,put_data){ var option = { hostname: 'localhost', port: 9200, path: '/'+index+'/'+type+'/'+id, method: 'PUT' }; var req = http.request(option, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log(chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // DATA PUT req.write(JSON.stringify(put_data)); req.end(); } var index = 'logstash-2015.03.06'; var type = 'access_log'; var id = 2; var data = { "host": "web01", "http_host": "192.168.1.123", "clientip": "192.2.3.55", "timestamp": "Fri Feb 06 2015 14:04:22 GMT+0900 (KST)", "verb": "GET", "request": "/css/comm.css", "httpversion": "1.1", "response": "304", "bytes": "0", "referrer": "http://192.168.1.124/", "agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17", "request_time": 0 }; elasticsearchPut(index,type,id,data);


콘솔에서 실행하면 아래와 같이 결과 메세지를 동일하게 볼 수 있다.

$ node test.js 
STATUS: 201
HEADERS: {"content-type":"application/json; charset=UTF-8","content-length":"91"}
{"_index":"logstash-2015.03.06","_type":"access_log","_id":"2","_version":1,"created":true}


예시로 nginx access_log로 했는데 실제 사용하는데는 이벤트나 구매내역등 실제 서비스로그를 RDBMS에서 주기적으로 가져와서 분석하는 용도로 사용함


추가적 node.js 라이브러리 및 Bulk insert 참고

elasticsearch Bulk insert(put) 대량 데이터 입력하기


Posted by 시니^^

각 툴에 대한 설명

1) elasticsearch => JAVA Lucene기반의 검색엔진

   URL : http://www.elasticsearch.org/

   Github : https://github.com/elasticsearch/elasticsearch


2) logstash => 실시간으로 다양한 로그를 가져와서 elasticsearch 넣어주는 역할

   URL :  http://logstash.net/

   Github : https://github.com/elasticsearch/logstash

   ※ logstash 경우 꼭 elasticsearch와 연동하지 않더라도 다양한 어플리케이션 로그를 input으로 받아서 다른 저장소로 전달하는 ouput 작업을 하기 위해서 쓰기 좋은 듯하다.


3) Kibana => elasticsearch와 연동해서 시각적으로 볼 수 있게 해주는 툴 node.js기반임

   URL :  http://www.elasticsearch.org/overview/kibana/

   Github : https://github.com/elasticsearch/kibana


설치 및 실행가이드

1. JAVA설치 - elasticsearch 사용하기 위해서 필요

$ yum install java
==================================================
 Package                              Arch        
==================================================
Installing:
 java-1.7.0-openjdk                   x86_64      
Installing for dependencies:
 flac                                 x86_64      
 giflib                               x86_64      
 jpackage-utils                       noarch      
 libasyncns                           x86_64      
 libsndfile                           x86_64      
 pulseaudio-libs                      x86_64      
 ttmkfdir                             x86_64      
 tzdata-java                          noarch      
 xorg-x11-fonts-Type1                 noarch      
Transaction Summary
==================================================
Install      10 Package(s)


2. elasticsearch 설치 및 실행

$ wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.4.4.tar.gz
$ tar xvfz elasticsearch-1.4.4.tar.gz
$ cd elasticsearch-1.4.4/bin
$ ./elasticsearch -d
$ ps aux | grep elasticsearch 

※ 옵션 -d 데몬으로 백그라운드실행


※ ElasticSearch 모니터링 추가 Plugin 설치 

$ ./plugin -install mobz/elasticsearch-head

=> URL : http://localhost:9200/_plugin/head/


$ ./plugin -install lukas-vlcek/bigdesk 

=> URL :  http://localhost:9200/_plugin/bigdesk/


$ ./plugin -install lmenezes/elasticsearch-kopf

=> URL :  http://localhost:9200/_plugin/kopf/


3. Logstash 설치

$ wget https://download.elasticsearch.org/logstash/logstash/logstash-1.4.2.tar.gz
$ tar xvfz logstash-1.4.2.tar.gz


※ 테스트 Nginx Access Log 추가

  참고사이트 : http://www.bravo-kernel.com/2014/12/setting-up-logstash-1-4-2-to-forward-nginx-logs-to-elasticsearch/


1) nginx.conf 로그구조 수정 후 Nginx 재시작

http {
    log_format main '$http_host '
                    '$remote_addr [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    '$request_time '
                    '$upstream_response_time';
    access_log  /var/log/nginx/access.log  main;
}


2) nginx 패턴 추가

$ vi ./logstash-1.4.2/patterns/nginx 
NGUSERNAME [a-zA-Z\.\@\-\+_%]+
NGUSER %{NGUSERNAME}
NGINXACCESS %{IPORHOST:http_host} %{IPORHOST:clientip} \[%{HTTPDATE:timestamp}\] \"(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion})?|%{DATA:rawrequest})\" %{NUMBER:response} (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent} %{NUMBER:request_time:float} %{NUMBER:upstream_time:float}
NGINXACCESS %{IPORHOST:http_host} %{IPORHOST:clientip} \[%{HTTPDATE:timestamp}\] \"(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpversion})?|%{DATA:rawrequest})\" %{NUMBER:response} (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:agent} %{NUMBER:request_time:float

3) Nginx logstash conf 생성

$ vi ./logstash-1.4.2/log_list/nginx.conf

====================================================== input { file { path => "/var/log/nginx/access.log" } } filter { mutate { replace => { "type" => "nginx_access" } } grok { match => { "message" => "%{NGINXACCESS}" } } date { match => [ "timestamp" , "dd/MMM/YYYY:HH:mm:ss Z" ] } geoip { source => "clientip" } } output { elasticsearch { host => localhost port => 9200 protocol => http } stdout { codec => rubydebug } }

※ 데이터 읽어와서 NGINXACCESS 매칭해서 elasticsearch로 보내는 설정정보이다

   elasticsearch 외에도 logstash의 경우 다양한 input output방식으로 데이터를 실시간 전달가능하다.

※ protocol 디폴트가 node이므로 버젼에 따라서 Kibana 사용할려면 http 설정해줘야될 경우도 있다

자세한 내용 참고 : http://logstash.net/docs/1.4.2/outputs/elasticsearch


4) conf TEST 옵션으로 확인
$ ../bin/logstash -f nginx.conf -t
Configuration OK


5) logstash 실행

$ ../bin/logstash -f nginx.conf
{
         "message" => "192.168.25.111 192.0.0.30 [02/Mar/2015:15:10:37 +0900] \"GET /favicon.ico HTTP/1.1\" 404 3652 \"-\" \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17\" 0.000 -",
        "@version" => "1",
      "@timestamp" => "2015-03-02T06:10:37.000Z",
            "host" => "testServer01",
            "path" => "/var/log/nginx/access.log",
            "type" => "nginx_access",
       "http_host" => "192.168.25.111",
        "clientip" => "192.0.0.30",
       "timestamp" => "02/Mar/2015:15:10:37 +0900",
            "verb" => "GET",
         "request" => "/favicon.ico",
     "httpversion" => "1.1",
        "response" => "404",
           "bytes" => "3652",
        "referrer" => "\"-\"",
           "agent" => "\"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17\"",
    "request_time" => 0.0
}


※ elasticsearch-head 설치했다면 http://localhost:9200/_plugin/head/ 데이터 확인


4. Kibana 설치

$ wget https://download.elasticsearch.org/kibana/kibana/kibana-4.0.0-linux-x64.tar.gz
$ tar xvfz kibana-4.0.0-linux-x64.tar.gz 
$ cd kibana-4.0.0-linux-x64

1) config 수정 ( port 및 elasticsearch_url 등)

$ vi config/kibana.yml ====================================================== # Kibana is served by a back end server. This controls which port to use. port: 5601 # The Elasticsearch instance to use for all your queries. elasticsearch_url: "http://localhost:9200"

※ 설치법 찾아보면 kibana_index: "logstash-*" 인덱스 수정하라고 하는 듯한데 logstash-*로 인덱스 잡아주면 아래 에러 나면서 사이트 접속이 안됨.....

Fatal Error Courier Fetch Error: unhandled error Error: Request to Elasticsearch failed: {"_index":"logstash-*","_type":"config","_id":"4.0.0","error":"[logstash-*] missing"}

   그래서 kibana_index: ".kibana" 그대로 유지하였더니 잘됨... 보니까 kibana_index란 셋팅하는 대쉬보드 정보 저장하는 저장소의 정보인듯함... 검색 인덱스 셋팅은 kibana 접속후에 아래와같이 Configure an index pattern에서 index 추가하면됨

2) 최종적으로 웹브라우져 켜서 config 에 설정한 port 로 접속하면됨

 - http://server_ip:5601 


※ visualization 과 Dashboard 설정하는 부분은 나중에 시간있을때 추가하는걸로~!!




Posted by 시니^^