~cjwatson/charms/trusty/logstash-forwarder/fix-logrotate-perms

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/python
#
# Copyright 2014 Canonical Ltd.  All rights reserved
# Author: Chris Stratford <chris.stratford@canonical.com>

import sys
import os
import os.path
import subprocess
import json
import base64
import shutil
import collections
import socket
sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib'))
from charmhelpers.core.hookenv import (
    Hooks, log, charm_dir, relations_of_type
)
from charmhelpers.core import host, hookenv
from charmhelpers.core.host import mkdir, service_start, service_stop, service_restart
from charmhelpers.core.services import RelationContext
from charmhelpers.fetch import apt_install, apt_update, add_source
from Cheetah.Template import Template
from Config import Config
#from nrpe import update_nrpe_checks
from charmhelpers.contrib.charmsupport import nrpe

hooks = Hooks()
conf = Config()

def jujuHeader():
    header = ("#-------------------------------------------------#\n"
              "# This file is Juju managed - do not edit by hand #\n"
              "#-------------------------------------------------#\n")
    return header

def installPackages():
    if conf.packageName():
        pkgFile = os.path.join(charm_dir(), "files", conf.packageName())
        if os.path.exists(pkgFile):
            if subprocess.call(["dpkg", "-i", pkgFile]) != 0:
                log("CHARM: Error installing logstash-forwarder package")
                sys.exit(1)
        else:
            if conf.aptRepository() and conf.aptRepository_key():
                add_source(conf.aptRepository(), conf.aptRepositoryKey())
                apt_update()
            apt_install(conf.packageName(), options=['--force-yes'])


def replaceInitScript():
    src = os.path.join(charm_dir(), "files", "init.sh")
    dest = "/etc/init.d/logstash-forwarder"
    shutil.copyfile(src, dest)
    os.chmod(dest, 0755)


def writeEtcDefault():
    tmplData = {}
    tmplData["config_file"] = conf.configFile()
    tmplData["spool_size"] = conf.spoolSize()
    templateFile = os.path.join(charm_dir(), "templates", "etcdefault.tmpl")
    t = Template(file=templateFile, searchList=tmplData)
    with open("/etc/default/logstash-forwarder", "w") as f:
        os.chmod("/etc/default/logstash-forwarder", 0644)
        f.write(jujuHeader())
        f.write(str(t))

def writeLogrotate():
    src = os.path.join(charm_dir(), "files", "logstash-forwarder.logrotate")
    dest = "/etc/logrotate.d/logstash-forwarder"
    shutil.copyfile(src, dest)
    os.chmod(dest, 0755)

def writeSSL():
    if not os.path.exists(conf.configDir()):
        mkdir(conf.configDir())
    if conf.sslCert():
        with open(conf.sslCertFile(), "w") as f:
            os.chmod(conf.sslCertFile(), 0644)
            f.write(base64.b64decode(conf.sslCert()))
    if conf.sslKey():
        with open(conf.sslKeyFile(), "w") as f:
            os.chmod(conf.sslKeyFile(), 0600)
            f.write(base64.b64decode(conf.sslKey()))
    if conf.sslCACert():
        with open(conf.sslCACertFile(), "w") as f:
            os.chmod(conf.sslCACertFile(), 0644)
            f.write(base64.b64decode(conf.sslCACert()))


def writeConfig():
    config = {}
    servers = []
    files = []
    logs_relation_data = logs_relation()
    if not os.path.exists(conf.configDir()):
        mkdir(conf.configDir())
    serverPort = conf.serverPort()
    for server in conf.servers():
        servers.append(server + ":" + str(serverPort))
    config["network"] = {}
    config["network"]["servers"] = servers
    if conf.sslCert():
        config["network"]["ssl certificate"] = conf.sslCertFile()
    if conf.sslKey():
        config["network"]["ssl key"] = conf.sslKeyFile()
    if conf.sslCACert():
        config["network"]["ssl ca"] = conf.sslCACertFile()
    if conf.timeout():
        config["network"]["timeout"] = conf.timeout()

    config["files"] = []
    fileSpec = conf.files()
    if fileSpec is not None:
        if isinstance(fileSpec, list):
            # The files option is a list of hashes, as per the definition
            # of the files attribute of the logstash-forwarder config at:
            # https://github.com/elastic/logstash-forwarder
            config["files"] = fileSpec
        else:
            for logType in fileSpec:
                files.append({
                    "paths": fileSpec[logType],
                    "fields": {"type": logType}
                })
            config["files"] = files

    default_fields = {'hostname': socket.gethostname()}
    model = os.environ.get('JUJU_MODEL_NAME', os.environ.get('JUJU_ENV_NAME'))
    if model:
        default_fields['juju_model'] = model

    unit = None
    logs = hookenv.relations_of_type('logs')
    if logs:
        unit = logs[0]['__unit__']
    else:
        juju_info = hookenv.relations_of_type('juju-info')
        if juju_info:
            unit = juju_info[0]['__unit__']

    if unit:
        default_fields['juju_unit'] = unit.replace('/', '-')
        default_fields['juju_service'] = unit.split('/')[0]

    for file in config["files"]:
        for default, value in default_fields.items():
            file["fields"].setdefault(default, value)

    if logs_relation_data is not None:
        for path, rel_fields in logs_relation_data.items():
            fields = default_fields.copy()
            fields.update(rel_fields)
            config["files"].append({"paths": [path], "fields": fields})

    host.write_file(
        conf.configFile(), json.dumps(config, sort_keys=True, indent=4))


def writeEtcHosts():
    log("CHARM: updating /etc/hosts with logstash servers name mapping")
    name_map = conf.serversNameMap()
    servers = conf.servers()
    if not name_map:
        return
    new_hosts = []
    for server in servers:
        ipaddr = name_map[server]
        new_hosts.append('{} {}'.format(ipaddr.strip(), server.strip()))
    # update /etc/hosts
    with open('/etc/hosts') as f:
        current_hosts = f.readlines()
    section_start = "### logstash-forwarder start ###\n"
    section_end = "### logstash-forwarder end ###\n"
    with open('/tmp/new_hosts', 'w') as f:
        ignore_lines = False
        for host_line in current_hosts:
            if host_line == section_start:
                ignore_lines = True
            elif host_line == section_end:
                ignore_lines = False
            elif not ignore_lines:
                f.write(host_line)
        # now write a new section for our hosts
        f.write("### logstash-forwarder start ###\n")
        for new_host_line in new_hosts:
            f.write("{}\n".format(new_host_line))
        f.write("### logstash-forwarder end ###\n")
    os.rename('/tmp/new_hosts', '/etc/hosts')


@hooks.hook('nrpe-external-master-relation-changed')
def update_nrpe_checks():
    rels = relations_of_type('nrpe-external-master')
    if not rels:
        log("No nrpe-external-master relations found, skipping update_nrpe_checks")
        return
    if 'nagios_hostname' not in rels[0]:
        log("No nagios_hostname in nrpe-external-master relations found, "
            "skipping update_nrpe_checks")
        return
    # only use the first relation in the list...we should have a single nrpe
    nrpe_compat = nrpe.NRPE(hostname=rels[0]['nagios_hostname'])
    conf = nrpe_compat.config
    check_procs_params = conf.get('nagios_check_procs_params')
    if check_procs_params:
        nrpe_compat.add_check(
            shortname='logstashforwarder_process',
            description='Check logstash-forwarder process running',
            check_cmd='check_procs %s' % check_procs_params
        )
    nrpe_compat.add_check(
        shortname='logstashforwarder_sending',
        description='Check logstash-forwarder is sending by tailing logfile',
        check_cmd="/usr/local/lib/nagios/plugins/check-logstashforwarder-sending.sh"
        )
    nrpe_compat.write()
    copy_check_files()


def copy_check_files():
    script_dir = "/usr/local/lib/nagios/plugins"
    mkdir(script_dir)
    for script in ["check-logstashforwarder-sending.sh"]:
        src = os.path.join(charm_dir(), "files", script)
        dest = os.path.join(script_dir, script)
        shutil.copyfile(src, dest)
        os.chmod(dest, 0755)


@hooks.hook("install.real")
def install():
    log("CHARM: Installing {}".format(conf.appName()))
    installPackages()
    replaceInitScript()
    writeLogrotate()


@hooks.hook("upgrade-charm")
def upgrade_charm():
    log("CHARM: Upgrading {}".format(conf.appName()))
    writeLogrotate()


@hooks.hook("config-changed")
def config_changed():
    log("CHARM: Configuring {}".format(conf.appName()))
    installPackages()
    replaceInitScript()
    writeEtcDefault()
    writeSSL()
    writeEtcHosts()
    writeConfig()
    service_restart("logstash-forwarder")
    update_nrpe_checks()


@hooks.hook("start")
def start():
    log("CHARM: Starting {}".format(conf.appName()))
    service_start("logstash-forwarder")


@hooks.hook("stop")
def stop():
    log("CHARM: Stopping {}".format(conf.appName()))
    service_stop("logstash-forwarder")


@hooks.hook("logs-relation-joined")
@hooks.hook('logs-relation-changed')
@hooks.hook('logs-relation-departed')
@hooks.hook('logs-relation-broken')
@hooks.hook("juju-info-relation-joined")
@hooks.hook("juju-info-relation-departed")
def logs_relation_hooks():
    log('logs relation')
    writeConfig()
    service_restart("logstash-forwarder")



def logs_relation():
    lsr = LogsRelation()
    log("LogsRelation: {}".format(lsr))
    if 'logs' not in lsr:
        return
    logs_relation_data = lsr['logs']
    if (not logs_relation_data or
        'types' not in logs_relation_data[0] or
        'files' not in logs_relation_data[0]):
        return None

    reldata = {k: v.split() for k, v in logs_relation_data[0].items()}
    reldata.pop('private-address', None)
    reldata.pop('public-address', None)
    paths = reldata.pop('files')
    types = reldata.pop('types')
    config = collections.OrderedDict()
    for i, (path, type_) in enumerate(zip(paths, types)):
        fields = {k: v[i] for k, v in reldata.items()
                  if i < len(v) and v[i] != 'SKIP'}
        fields['type'] = type_
        config[path] = fields

    return config


class LogsRelation(RelationContext):
    name = 'logs'
    interface = 'logs'
    required_keys = ['types', 'files']


if __name__ == "__main__":
    hooks.execute(sys.argv)