---
# file: roles/fluentd-client/tasks/fluentd-client.yml

- name: Configure SysCtl
  sysctl:
    name: '{{ item.key }}'
    value: '{{ item.value }}'
    reload: yes
  with_dict:
    net.core.somaxconn: 1024
    net.core.netdev_max_backlog: 5000
    net.core.rmem_max: 16777216
    net.core.wmem_max: 16777216
    net.ipv4.tcp_wmem: 4096 12582912 16777216
    net.ipv4.tcp_rmem: 4096 12582912 16777216
    net.ipv4.tcp_max_syn_backlog: 8096
    net.ipv4.tcp_slow_start_after_idle: 0
    net.ipv4.tcp_tw_reuse: 1
    net.ipv4.ip_local_port_range: 10240 65535

- name: Apt Key
  apt_key:
    url: '{{ (ansible_distribution_major_version == "16")|ternary("https","http") }}://packages.treasuredata.com/GPG-KEY-td-agent'
    state: present

- name: Apt Repository
  apt_repository:
    repo: 'deb [arch=amd64] http://packages.treasuredata.com/4/ubuntu/{{ ansible_distribution_release }}/ {{ ansible_distribution_release }} contrib'
    state: present
    mode: 0644

- name: Install Agent
  apt:
    pkg: td-agent
    state: latest
    update_cache: yes

- name: Install Plugins
  command: td-agent-gem install {{ item }}
  with_items:
    - fluent-plugin-secure-forward
    - fluent-plugin-multi-format-parser
    - fluent-plugin-record-modifier
    - fluent-plugin-mail
    - fluent-plugin-beats
    - fluent-plugin-td-monitoring

- name: Ensure SSL Directory
  file:
    path: /etc/ssl/td-agent
    state: directory
    owner: root
    group: root
    mode: 0755

- name: Copy SSL Certificate
  copy:
    src: '{{ inventory_dir }}/files/ssl/td-agent/cert.pem'
    dest: /etc/ssl/td-agent/cert.pem
    owner: root
    group: root
    mode: 0644

- name: Configure td-agent
  template:
    src: td-agent.conf
    dest: /etc/td-agent/td-agent.conf
    owner: root
    group: root
    mode: 0644
  tags:
    - Config
  notify:
    - Restart td-agent

- name: Copy script to post Alerta
  template:
    src: alertalerta.py
    dest: /usr/local/bin/alertalerta.py
    owner: root
    group: root
    mode: 0755
  tags:
    - Config

- name: Add td-agent user to adm groups
  user:
    name: td-agent
    groups: adm,root,netdata
    append: yes
  tags:
    - Config
  ignore_errors: yes
  notify:
    - Restart td-agent

- name: Add td-agent user to mattermost group
  user:
    name: td-agent
    groups: mattermost
    append: yes
  tags:
    - Config
  when: groups and 'gitlabserver' in groups and inventory_hostname in groups.gitlabserver
  ignore_errors: yes
  notify:
    - Restart td-agent

- name: Add td-agent user to redis group
  user:
    name: td-agent
    groups: redis
    append: yes
  tags:
    - Config
  when: groups and 'webserver' in groups and inventory_hostname in groups.webserver
  ignore_errors: yes
  notify:
    - Restart td-agent
