viernes, 11 de noviembre de 2016

Asterisk CDR a ELK 5

Hola

Este manual se trata de enviar los eventos del Master.csv hacia el Elasticsearch con Kibana

Toda la informacion sobre Elasticsearch lo pueden encontrar en la documentacion oficial https://www.elastic.co/learn

La figura seria la siguiente

Asterisk --> Filebeat --> Logstash --> ElasticSearch --> Kibana

Filebeat envia los eventos del servidor hacia el servidor de logstash.
Logstash recibe los eventos, procesa y envia la informacion a ElasticSearch
Kibana es una interface grafica donde se visualiza los eventos que esta en ElasticSearch

El laboratorio es sobre un Server Centos 7 ELK 5 y otro Server Asterisk con Filebeat como agente.

IPV6 esta deshabilitado solo trabaje con IPV4
Selinux dehabilitado
# sestatus
SELinux status:                 disabled

Server ELK
# cat /etc/centos-release
CentOS Linux release 7.2.1511 (Core)
instalar:
yum install java-1.8.0-openjdk-devel java java-1.8.0-openjdk

# java -version
openjdk version "1.8.0_111"
OpenJDK Runtime Environment (build 1.8.0_111-b15)
OpenJDK 64-Bit Server VM (build 25.111-b15, mixed mode)

Procedemos a instalar el stack ELK

Elasticsearch
https://www.elastic.co/guide/en/elasticsearch/reference/5.0/rpm.html

Habilitamos el repositorio de Elasticsearch

Bajamos e instalamos la llave publica GPG
# rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch

Creamos el archivo elasticsearch.repo en /etc/yum.repos.d/

[elasticsearch-5.x]
name=Elasticsearch repository for 5.x packages
baseurl=https://artifacts.elastic.co/packages/5.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md

luego procedemos a instalar el elasticsearch
yum install elasticsearch

# systemctl daemon-reload
# systemctl enable elasticsearch
# systemctl start elasticsearch

Validar que los puertos 9200 y 9300 esten en escucha



Tambien hacemos un
# systemctl status elasticsearch


Vemos si elasticsearch responde los request sobre http
# curl -X GET http://localhost:9200
{
  "name" : "bhcsJV7",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "rD_lJLSkQFKcvae6xtCsGQ",
  "version" : {
    "number" : "5.0.0",
    "build_hash" : "253032b",
    "build_date" : "2016-10-26T04:37:51.531Z",
    "build_snapshot" : false,
    "lucene_version" : "6.2.0"
  },
  "tagline" : "You Know, for Search"
}

Con esto validamos el funcionamiento de elasticsearch

Logstash
https://www.elastic.co/guide/en/logstash/current/installing-logstash.html

Creamos el archivo logstash.repo en /etc/yum.repos.d/

 [logstash-5.x]
name=Elastic repository for 5.x packages
baseurl=https://artifacts.elastic.co/packages/5.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md

Instalamos logstash
yum install logstash

Añadimos un certificado ssl del servidor ELK basado en su propia ip
 Modificamos el archivo /etc/pki/tls/openssl.conf y agregamos la linea subjectAltName ... debajo de v3_ca
 
[ v3_ca ]
subjectAltName = IP: X.X.X.X

Generamos un certificado por 365 dias
#cd /etc/pki/tls
# openssl req -config /etc/pki/tls/openssl.cnf -x509 -days 3650 -batch -nodes -newkey rsa:2048 -keyout private/logstash-forwarder.key -out certs/logstash-forwarder.crt

Copiamos el archivo logstash-forwarder.cdr desde el Servidor ELK hacia el servidor asterisk
# scp /etc/pki/tls/certs/logstash-forwarder.crt root@IPasterisk:/etc/pki/tls/certs/

Creamos los archivos
# vim /etc/logstash/conf.d/input.conf

input {
        beats {
        port => 5044
        ssl => true
        ssl_certificate => "/etc/pki/tls/certs/logstash-forwarder.crt"
        ssl_key => "/etc/pki/tls/private/logstash-forwarder.key"
        }
}


El puerto 5043 es el que se va habilitar para que filebeat envie la informacion desde el cliente

# vim /etc/logstash/conf.d/output.conf
output {
        elasticsearch {
        hosts => ["localhost:9200"]
        manage_template => false
        index => "%{[@metadata][beat]}-%{+YYYY.MM.dd}"
        document_type => "%{[@metadata][type]}"
        }
}

logstash se comunica con el elastic por "localhost:9200"

# vim /etc/logstash/conf.d/filter.conf
filter {
   if [fields][log_type] == "cdr" {
       csv {
        columns => [
            "accountcode",
            "src", "dst", "dcontext",
            "clid", "channel", "dstchannel",
            "lastapp", "lastdata",
            "start", "answer", "end", "duration", "billsec",
            "disposition", "amaflags", "uniqueid", "userfield"
                   ]
          }

    # if dstchannel is present, split tech, name and id into 3 separate fields
    if [dstchannel] == "" {
        mutate { remove_field => ["dstchannel"] }
    } else {
        grok {
            match => ["dstchannel", "%{DATA:dstchannel_tech}/%{DATA:dstchannel_name}-%{BASE16NUM:dstchannel_id}"]
        }
    }

    # do the same to channel
    grok {
        match => ["channel", "%{DATA:channel_tech}/%{DATA:channel_name}-%{BASE16NUM:channel_id}"]
    }
     # duration and billsec are integers, message is not needed anymore (just plain CSV anyway)
    mutate {
        convert => [
            "duration", "integer",
            "billsec", "integer"
        ]
        remove_field => ["message"]
    }
  }
}

El archivo filter es donde procemos el "log" que es enviado por el filebeat, en este caso Logstash procesa el archivo Master.csv y se envia al elasticsearch para ver visualizado en kibana.

Una vez tengamos eso configurado
# systemctl daemon-reload
# systemctl start logstash
# systemctl enable logstash

validamos que el puerto 5044 este en listening y que este funcionando con normalidad

vemos que el servicio esta up and running


Kibana
https://www.elastic.co/guide/en/kibana/current/rpm.html

Creamos el archivo kibana.repo en /etc/yum.repos.d/

[kibana-5.x]
name=Kibana repository for 5.x packages
baseurl=https://artifacts.elastic.co/packages/5.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md

Instalamos Kibana
# yum install kibana

Modificamos el archivo /etc/kibana/kibana.yml
En la linea de server.host descomentar y poner:

server.host: "0.0.0.0"

Iniciamos el servicio
# systemctl daemon-reload
# systemctl start kibana
# systemctl enable kibana
 
Validamos el puerto
Tambien validamos el servicio kibana

Ahora vamos a instalar filebeat en el servidor cliente en este caso en el servidor asterisk
Asterisk Server (Filebeat) --> ELK Server


Filebeat
https://www.elastic.co/guide/en/beats/libbeat/5.0/setup-repositories.html

Creamos el archivo filebeat.repo en /etc/yum.repos.d

[elastic-5.x]
name=Elastic repository for 5.x packages
baseurl=https://artifacts.elastic.co/packages/5.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md

Bajamos e instalamos la llave GPG
#rpm --import https://packages.elastic.co/GPG-KEY-elasticsearch

Instalamos filebeat
# yum install filebeat


Modificamos el archivo /etc/filebeat/filebeat.yml

- input_type: log
  paths:
    - /var/log/asterisk/cdr-csv/Master.csv
  fields: {log_type: cdr}


Comentar estas lineas porque usaremos logstash
#output.elasticsearch:
 #hosts: ["localhost:9200"]

output.logstash:
  # The Logstash hosts
  hosts: ["IPServerELK:5044"]
  ssl.certificate_authorities: ["/etc/pki/tls/certs/logstash-forwarder.crt"]


Estamos enviando el master.csv al logstash por el puerto 5044.

Iniciamos el servicio filebeat
# systemctl start filebeat
# systemctl enable filebeat


Una prueba breve es hacer un telnet hacia el ELK Server por el puerto 5044 deberia contestar
Otra cosa muy importante es revisar los logs
podemos habilitarlo en el archivo filebeat.yml
descomentando la linea
logging.level: debug

Y hacemos un tail para ver que se este procesando el archivo
# tail -f /var/log/filebeat/filebeat

Una vez todo este funcionando

Vamos al servidor ELK y ejecutamos

# curl -XGET 'http://localhost:9200/filebeat-*/_search?pretty'

Debemos ver los datos del master.csv esten siendo procesados por el logtassh

Algunos detalles a tener en cuenta
No debe salirnos el "_grokparsefailure" en el tags
debe salir:
"tags" : [
            "beats_input_codec_plain_applied"
          ],

En caso salga hay que revisar la sintaxis en el archivo filter.conf

Habiendo validado que filebeat este procesando el archivo master.csv
, logstash este procesando la informacion y la este enviando al elasticsearch
Validamos que elasticsearch esta recibiendo esa informacion entonces vamos a kibana

http://IPServerELK:5601

Como index pattern ponemos filebeat-*
y luego le damos en create


Seleccionamos el indice creado filebeat y veremos los campos asociados   

Hacemos click en la pantalla izquierda "Discover", y vemos como los datos estan siendo procesados


Una vez dentro y con los datos vamos a visualize y empezamos a crear nuestros graficos
En la documentacion oficial estan los pasos a seguir 
https://www.elastic.co/guide/en/kibana/current/createvis.html

Referencias:

https://www.elastic.co/guide/index.html

http://www.tecmint.com/install-elasticsearch-logstash-and-kibana-elk-stack-on-centos-rhel-7/
https://discuss.elastic.co/t/how-to-tag-log-files-in-filebeat-for-logstash-ingestion/44713/4
https://clutterbox.de/2014/03/asterisk-pushing-cdrs-into-elasticsearch-using-logstash/