~michael.nelson/charms/trusty/logstash/trunk

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
59
#!/usr/bin/python

import os
import sys

sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib'))

from charmhelpers.core import (
    hookenv,
    host
)
from charmhelpers.contrib.templating.jinja import render


hooks = hookenv.Hooks()
log = hookenv.log

SERVICE = 'logstash-indexer'
BASEPATH = os.path.join(os.path.sep, 'opt', 'logstash')


@hooks.hook('client-relation-changed')
def rest_changed():
    cache_hosts()
    write_config()
    host.service_restart(SERVICE) or host.service_start(SERVICE)


def write_config():
    with open('host_cache', 'r') as f:
        hosts = f.readlines()

    opts = {'hosts': hosts[0].rstrip()}

    out = os.path.join(BASEPATH, 'conf.d', 'output-elasticsearch.conf')
    with open(out, 'w') as p:
      p.write(render(os.path.basename(out), opts))



def cache_hosts():
    host = hookenv.relation_get('host')
    if not host:
      log('No host received. Assuming nothing to do.')
      sys.exit(0)

    if not os.path.exists('host_cache'):
        open('host_cache', 'a').close()

    with open('host_cache', 'r') as f:
        hosts = f.readlines()
    if not host in hosts:
        with open('host_cache', 'a') as f:
            f.write('{}\n'.format(host))


if __name__ == "__main__":
    # execute a hook based on the name the program is called by
    hooks.execute(sys.argv)