Merge lp:~brad-marshall/charms/trusty/quantum-gateway/add-nrpe-checks into lp:charms/trusty/quantum-gateway

Proposed by Brad Marshall
Status: Merged
Merged at revision: 81
Proposed branch: lp:~brad-marshall/charms/trusty/quantum-gateway/add-nrpe-checks
Merge into: lp:charms/trusty/quantum-gateway
Diff against target: 568 lines (+468/-0)
7 files modified
charm-helpers-hooks.yaml (+1/-0)
config.yaml (+10/-0)
hooks/charmhelpers/contrib/charmsupport/nrpe.py (+222/-0)
hooks/charmhelpers/contrib/charmsupport/volumes.py (+156/-0)
hooks/quantum_hooks.py (+68/-0)
hooks/quantum_utils.py (+8/-0)
metadata.yaml (+3/-0)
To merge this branch: bzr merge lp:~brad-marshall/charms/trusty/quantum-gateway/add-nrpe-checks
Reviewer Review Type Date Requested Status
Liam Young (community) Disapprove
Review via email: mp+241486@code.launchpad.net

Description of the change

Adds nrpe-external-master interface and adds basic nrpe checks.

To post a comment you must log in.
Revision history for this message
Ryan Beisner (1chb1n) wrote :

UOSCI bot says:
charm_lint_check #994 trusty-quantum-gateway for brad-marshall mp241486
    LINT FAIL: lint-test failed

LINT Results (max last 5 lines):
ERROR:root:Make target returned non-zero.
  hooks/quantum_hooks.py:205:80: E501 line too long (92 > 79 characters)
  hooks/quantum_hooks.py:236:22: E251 unexpected spaces around keyword / parameter equals
  hooks/quantum_hooks.py:236:24: E251 unexpected spaces around keyword / parameter equals
  make: *** [lint] Error 1

Full lint test output: http://paste.ubuntu.com/8955761/
Build: http://10.98.191.181:8080/job/charm_lint_check/994/

Revision history for this message
Ryan Beisner (1chb1n) wrote :

UOSCI bot says:
charm_unit_test #829 trusty-quantum-gateway for brad-marshall mp241486
    UNIT FAIL: unit-test failed

UNIT Results (max last 5 lines):
  hooks/quantum_utils 199 1 99% 354
  TOTAL 442 31 93%
  Ran 82 tests in 3.414s
  FAILED (errors=3)
  make: *** [unit_test] Error 1

Full unit test output: http://paste.ubuntu.com/8955779/
Build: http://10.98.191.181:8080/job/charm_unit_test/829/

Revision history for this message
Ryan Beisner (1chb1n) wrote :

UOSCI bot says:
charm_amulet_test #374 trusty-quantum-gateway for brad-marshall mp241486
    AMULET FAIL: amulet-test failed

AMULET Results (max last 5 lines):
  juju-test.conductor DEBUG : Calling "juju destroy-environment -y osci-sv05"
  WARNING cannot delete security group "juju-osci-sv05-0". Used by another environment?
  juju-test INFO : Results: 1 passed, 2 failed, 0 errored
  ERROR subprocess encountered error code 2
  make: *** [test] Error 2

Full amulet test output: http://paste.ubuntu.com/8955979/
Build: http://10.98.191.181:8080/job/charm_amulet_test/374/

79. By Brad Marshall

[bradm] Added sysvinit daemon monitoring, use services() instead of hard coded daemon list, pep8 fixes

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_lint_check #1085 trusty-quantum-gateway for brad-marshall mp241486
    LINT FAIL: lint-test failed

LINT Results (max last 5 lines):
INFO:root:Searching for: ['@flake8']
INFO:root:command: make -f Makefile lint
ERROR:root:Make target returned non-zero.
  hooks/quantum_utils.py:501:1: F811 redefinition of unused 'services' from line 405
  make: *** [lint] Error 1

Full lint test output: http://paste.ubuntu.com/9052126/
Build: http://10.98.191.181:8080/job/charm_lint_check/1085/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_unit_test #919 trusty-quantum-gateway for brad-marshall mp241486
    UNIT FAIL: unit-test failed

UNIT Results (max last 5 lines):
  hooks/quantum_utils 204 5 98% 354, 407-410
  TOTAL 459 47 90%
  Ran 82 tests in 3.445s
  FAILED (errors=3)
  make: *** [unit_test] Error 1

Full unit test output: http://paste.ubuntu.com/9052128/
Build: http://10.98.191.181:8080/job/charm_unit_test/919/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_amulet_test #427 trusty-quantum-gateway for brad-marshall mp241486
    AMULET FAIL: amulet-test failed

AMULET Results (max last 5 lines):
  juju-test.conductor DEBUG : Calling "juju destroy-environment -y osci-sv05"
  WARNING cannot delete security group "juju-osci-sv05-0". Used by another environment?
  juju-test INFO : Results: 1 passed, 2 failed, 0 errored
  ERROR subprocess encountered error code 2
  make: *** [test] Error 2

Full amulet test output: http://paste.ubuntu.com/9052219/
Build: http://10.98.191.181:8080/job/charm_amulet_test/427/

80. By Brad Marshall

[bradm] Removed puppet header from nagios_plugin module

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_lint_check #1097 trusty-quantum-gateway for brad-marshall mp241486
    LINT FAIL: lint-test failed

LINT Results (max last 5 lines):
INFO:root:Searching for: ['@flake8']
INFO:root:command: make -f Makefile lint
ERROR:root:Make target returned non-zero.
  hooks/quantum_utils.py:501:1: F811 redefinition of unused 'services' from line 405
  make: *** [lint] Error 1

Full lint test output: http://paste.ubuntu.com/9052970/
Build: http://10.98.191.181:8080/job/charm_lint_check/1097/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_unit_test #931 trusty-quantum-gateway for brad-marshall mp241486
    UNIT FAIL: unit-test failed

UNIT Results (max last 5 lines):
  hooks/quantum_utils 204 5 98% 354, 407-410
  TOTAL 459 47 90%
  Ran 82 tests in 3.640s
  FAILED (errors=3)
  make: *** [unit_test] Error 1

Full unit test output: http://paste.ubuntu.com/9052973/
Build: http://10.98.191.181:8080/job/charm_unit_test/931/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_amulet_test #439 trusty-quantum-gateway for brad-marshall mp241486
    AMULET FAIL: amulet-test failed

AMULET Results (max last 5 lines):
  juju-test.conductor DEBUG : Calling "juju destroy-environment -y osci-sv05"
  WARNING cannot delete security group "juju-osci-sv05-0". Used by another environment?
  juju-test INFO : Results: 1 passed, 2 failed, 0 errored
  ERROR subprocess encountered error code 2
  make: *** [test] Error 2

Full amulet test output: http://paste.ubuntu.com/9053032/
Build: http://10.98.191.181:8080/job/charm_amulet_test/439/

81. By Brad Marshall

[bradm] Removed nagios check files that were moved to nrpe-external-master charm

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_lint_check #1113 trusty-quantum-gateway for brad-marshall mp241486
    LINT FAIL: lint-test failed

LINT Results (max last 5 lines):
INFO:root:command: make -f Makefile lint
ERROR:root:Make target returned non-zero.
  hooks/quantum_hooks.py:239:13: F841 local variable 'checkpath' is assigned to but never used
  hooks/quantum_utils.py:501:1: F811 redefinition of unused 'services' from line 405
  make: *** [lint] Error 1

Full lint test output: http://paste.ubuntu.com/9063849/
Build: http://10.98.191.181:8080/job/charm_lint_check/1113/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_unit_test #947 trusty-quantum-gateway for brad-marshall mp241486
    UNIT FAIL: unit-test failed

UNIT Results (max last 5 lines):
  hooks/quantum_utils 204 5 98% 354, 407-410
  TOTAL 459 47 90%
  Ran 82 tests in 3.301s
  FAILED (errors=3)
  make: *** [unit_test] Error 1

Full unit test output: http://paste.ubuntu.com/9063851/
Build: http://10.98.191.181:8080/job/charm_unit_test/947/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_amulet_test #455 trusty-quantum-gateway for brad-marshall mp241486
    AMULET FAIL: amulet-test failed

AMULET Results (max last 5 lines):
  WARNING cannot delete security group "juju-osci-sv05". Used by another environment?
  WARNING cannot delete security group "juju-osci-sv05-0". Used by another environment?
  juju-test INFO : Results: 0 passed, 2 failed, 1 errored
  ERROR subprocess encountered error code 2
  make: *** [test] Error 2

Full amulet test output: http://paste.ubuntu.com/9064090/
Build: http://10.98.191.181:8080/job/charm_amulet_test/455/

82. By Brad Marshall

[bradm] Add network namespace checks

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_lint_check #1141 trusty-quantum-gateway for brad-marshall mp241486
    LINT FAIL: lint-test failed

LINT Results (max last 5 lines):
INFO:root:Searching for: ['@flake8']
INFO:root:command: make -f Makefile lint
ERROR:root:Make target returned non-zero.
  hooks/quantum_utils.py:501:1: F811 redefinition of unused 'services' from line 405
  make: *** [lint] Error 1

Full lint test output: http://paste.ubuntu.com/9110737/
Build: http://10.98.191.181:8080/job/charm_lint_check/1141/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_unit_test #975 trusty-quantum-gateway for brad-marshall mp241486
    UNIT FAIL: unit-test failed

UNIT Results (max last 5 lines):
  hooks/quantum_utils 204 5 98% 354, 407-410
  TOTAL 464 52 89%
  Ran 82 tests in 3.753s
  FAILED (errors=3)
  make: *** [unit_test] Error 1

Full unit test output: http://paste.ubuntu.com/9110750/
Build: http://10.98.191.181:8080/job/charm_unit_test/975/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_amulet_test #483 trusty-quantum-gateway for brad-marshall mp241486
    AMULET FAIL: amulet-test failed

AMULET Results (max last 5 lines):
  juju-test.conductor DEBUG : Calling "juju destroy-environment -y osci-sv07"
  WARNING cannot delete security group "juju-osci-sv07-0". Used by another environment?
  juju-test INFO : Results: 1 passed, 2 failed, 0 errored
  ERROR subprocess encountered error code 2
  make: *** [test] Error 2

Full amulet test output: http://paste.ubuntu.com/9110796/
Build: http://10.98.191.181:8080/job/charm_amulet_test/483/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_lint_check #1247 trusty-quantum-gateway for brad-marshall mp241486
    LINT FAIL: lint-test failed

LINT Results (max last 5 lines):
INFO:root:Searching for: ['@flake8']
INFO:root:command: make -f Makefile lint
ERROR:root:Make target returned non-zero.
  hooks/quantum_utils.py:501:1: F811 redefinition of unused 'services' from line 405
  make: *** [lint] Error 1

Full lint test output: http://paste.ubuntu.com/9281278/
Build: http://10.98.191.181:8080/job/charm_lint_check/1247/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_unit_test #1081 trusty-quantum-gateway for brad-marshall mp241486
    UNIT FAIL: unit-test failed

UNIT Results (max last 5 lines):
  hooks/quantum_utils 204 5 98% 354, 407-410
  TOTAL 464 52 89%
  Ran 82 tests in 3.144s
  FAILED (errors=3)
  make: *** [unit_test] Error 1

Full unit test output: http://paste.ubuntu.com/9281281/
Build: http://10.98.191.181:8080/job/charm_unit_test/1081/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

UOSCI bot says:
charm_amulet_test #550 trusty-quantum-gateway for brad-marshall mp241486
    AMULET FAIL: amulet-test failed

AMULET Results (max last 5 lines):
  juju-test.conductor DEBUG : Calling "juju destroy-environment -y osci-sv05"
  WARNING cannot delete security group "juju-osci-sv05-0". Used by another environment?
  juju-test INFO : Results: 1 passed, 2 failed, 0 errored
  ERROR subprocess encountered error code 2
  make: *** [test] Error 2

Full amulet test output: http://paste.ubuntu.com/9281399/
Build: http://10.98.191.181:8080/job/charm_amulet_test/550/

Revision history for this message
Liam Young (gnuoy) wrote :

Thank for the mp. The new nrpe support is very gratefully received !

I've taken this branch and centralised the common code between this and the other nrpe branches and moved it to charm-helpers. To land it I created a new branch from this one which has now been merged into the 'next' charm. The 'next' charms will overwrite the stable ones in a couple of weeks.

review: Disapprove

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'charm-helpers-hooks.yaml'
--- charm-helpers-hooks.yaml 2014-07-28 12:07:31 +0000
+++ charm-helpers-hooks.yaml 2014-11-20 02:17:21 +0000
@@ -8,3 +8,4 @@
8 - contrib.network8 - contrib.network
9 - contrib.storage.linux9 - contrib.storage.linux
10 - payload.execd10 - payload.execd
11 - contrib.charmsupport
1112
=== modified file 'config.yaml'
--- config.yaml 2014-09-30 14:12:10 +0000
+++ config.yaml 2014-11-20 02:17:21 +0000
@@ -91,6 +91,16 @@
91 default: nova91 default: nova
92 type: string92 type: string
93 description: Database name93 description: Database name
94 nagios_context:
95 default: "juju"
96 type: string
97 description: |
98 Used by the nrpe-external-master subordinate charm.
99 A string that will be prepended to instance name to set the host name
100 in nagios. So for instance the hostname would be something like:
101 juju-myservice-0
102 If you're running multiple environments with the same services in them
103 this allows you to differentiate between them.
94 # Network configuration options104 # Network configuration options
95 # by default all access is over 'private-address'105 # by default all access is over 'private-address'
96 os-data-network:106 os-data-network:
97107
=== added directory 'files'
=== added directory 'hooks/charmhelpers/contrib/charmsupport'
=== added file 'hooks/charmhelpers/contrib/charmsupport/__init__.py'
=== added file 'hooks/charmhelpers/contrib/charmsupport/nrpe.py'
--- hooks/charmhelpers/contrib/charmsupport/nrpe.py 1970-01-01 00:00:00 +0000
+++ hooks/charmhelpers/contrib/charmsupport/nrpe.py 2014-11-20 02:17:21 +0000
@@ -0,0 +1,222 @@
1"""Compatibility with the nrpe-external-master charm"""
2# Copyright 2012 Canonical Ltd.
3#
4# Authors:
5# Matthew Wedgwood <matthew.wedgwood@canonical.com>
6
7import subprocess
8import pwd
9import grp
10import os
11import re
12import shlex
13import yaml
14
15from charmhelpers.core.hookenv import (
16 config,
17 local_unit,
18 log,
19 relation_ids,
20 relation_set,
21)
22
23from charmhelpers.core.host import service
24
25# This module adds compatibility with the nrpe-external-master and plain nrpe
26# subordinate charms. To use it in your charm:
27#
28# 1. Update metadata.yaml
29#
30# provides:
31# (...)
32# nrpe-external-master:
33# interface: nrpe-external-master
34# scope: container
35#
36# and/or
37#
38# provides:
39# (...)
40# local-monitors:
41# interface: local-monitors
42# scope: container
43
44#
45# 2. Add the following to config.yaml
46#
47# nagios_context:
48# default: "juju"
49# type: string
50# description: |
51# Used by the nrpe subordinate charms.
52# A string that will be prepended to instance name to set the host name
53# in nagios. So for instance the hostname would be something like:
54# juju-myservice-0
55# If you're running multiple environments with the same services in them
56# this allows you to differentiate between them.
57#
58# 3. Add custom checks (Nagios plugins) to files/nrpe-external-master
59#
60# 4. Update your hooks.py with something like this:
61#
62# from charmsupport.nrpe import NRPE
63# (...)
64# def update_nrpe_config():
65# nrpe_compat = NRPE()
66# nrpe_compat.add_check(
67# shortname = "myservice",
68# description = "Check MyService",
69# check_cmd = "check_http -w 2 -c 10 http://localhost"
70# )
71# nrpe_compat.add_check(
72# "myservice_other",
73# "Check for widget failures",
74# check_cmd = "/srv/myapp/scripts/widget_check"
75# )
76# nrpe_compat.write()
77#
78# def config_changed():
79# (...)
80# update_nrpe_config()
81#
82# def nrpe_external_master_relation_changed():
83# update_nrpe_config()
84#
85# def local_monitors_relation_changed():
86# update_nrpe_config()
87#
88# 5. ln -s hooks.py nrpe-external-master-relation-changed
89# ln -s hooks.py local-monitors-relation-changed
90
91
92class CheckException(Exception):
93 pass
94
95
96class Check(object):
97 shortname_re = '[A-Za-z0-9-_]+$'
98 service_template = ("""
99#---------------------------------------------------
100# This file is Juju managed
101#---------------------------------------------------
102define service {{
103 use active-service
104 host_name {nagios_hostname}
105 service_description {nagios_hostname}[{shortname}] """
106 """{description}
107 check_command check_nrpe!{command}
108 servicegroups {nagios_servicegroup}
109}}
110""")
111
112 def __init__(self, shortname, description, check_cmd):
113 super(Check, self).__init__()
114 # XXX: could be better to calculate this from the service name
115 if not re.match(self.shortname_re, shortname):
116 raise CheckException("shortname must match {}".format(
117 Check.shortname_re))
118 self.shortname = shortname
119 self.command = "check_{}".format(shortname)
120 # Note: a set of invalid characters is defined by the
121 # Nagios server config
122 # The default is: illegal_object_name_chars=`~!$%^&*"|'<>?,()=
123 self.description = description
124 self.check_cmd = self._locate_cmd(check_cmd)
125
126 def _locate_cmd(self, check_cmd):
127 search_path = (
128 '/',
129 os.path.join(os.environ['CHARM_DIR'],
130 'files/nrpe-external-master'),
131 '/usr/lib/nagios/plugins',
132 '/usr/local/lib/nagios/plugins',
133 )
134 parts = shlex.split(check_cmd)
135 for path in search_path:
136 if os.path.exists(os.path.join(path, parts[0])):
137 command = os.path.join(path, parts[0])
138 if len(parts) > 1:
139 command += " " + " ".join(parts[1:])
140 return command
141 log('Check command not found: {}'.format(parts[0]))
142 return ''
143
144 def write(self, nagios_context, hostname):
145 nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format(
146 self.command)
147 with open(nrpe_check_file, 'w') as nrpe_check_config:
148 nrpe_check_config.write("# check {}\n".format(self.shortname))
149 nrpe_check_config.write("command[{}]={}\n".format(
150 self.command, self.check_cmd))
151
152 if not os.path.exists(NRPE.nagios_exportdir):
153 log('Not writing service config as {} is not accessible'.format(
154 NRPE.nagios_exportdir))
155 else:
156 self.write_service_config(nagios_context, hostname)
157
158 def write_service_config(self, nagios_context, hostname):
159 for f in os.listdir(NRPE.nagios_exportdir):
160 if re.search('.*{}.cfg'.format(self.command), f):
161 os.remove(os.path.join(NRPE.nagios_exportdir, f))
162
163 templ_vars = {
164 'nagios_hostname': hostname,
165 'nagios_servicegroup': nagios_context,
166 'description': self.description,
167 'shortname': self.shortname,
168 'command': self.command,
169 }
170 nrpe_service_text = Check.service_template.format(**templ_vars)
171 nrpe_service_file = '{}/service__{}_{}.cfg'.format(
172 NRPE.nagios_exportdir, hostname, self.command)
173 with open(nrpe_service_file, 'w') as nrpe_service_config:
174 nrpe_service_config.write(str(nrpe_service_text))
175
176 def run(self):
177 subprocess.call(self.check_cmd)
178
179
180class NRPE(object):
181 nagios_logdir = '/var/log/nagios'
182 nagios_exportdir = '/var/lib/nagios/export'
183 nrpe_confdir = '/etc/nagios/nrpe.d'
184
185 def __init__(self, hostname=None):
186 super(NRPE, self).__init__()
187 self.config = config()
188 self.nagios_context = self.config['nagios_context']
189 self.unit_name = local_unit().replace('/', '-')
190 if hostname:
191 self.hostname = hostname
192 else:
193 self.hostname = "{}-{}".format(self.nagios_context, self.unit_name)
194 self.checks = []
195
196 def add_check(self, *args, **kwargs):
197 self.checks.append(Check(*args, **kwargs))
198
199 def write(self):
200 try:
201 nagios_uid = pwd.getpwnam('nagios').pw_uid
202 nagios_gid = grp.getgrnam('nagios').gr_gid
203 except:
204 log("Nagios user not set up, nrpe checks not updated")
205 return
206
207 if not os.path.exists(NRPE.nagios_logdir):
208 os.mkdir(NRPE.nagios_logdir)
209 os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid)
210
211 nrpe_monitors = {}
212 monitors = {"monitors": {"remote": {"nrpe": nrpe_monitors}}}
213 for nrpecheck in self.checks:
214 nrpecheck.write(self.nagios_context, self.hostname)
215 nrpe_monitors[nrpecheck.shortname] = {
216 "command": nrpecheck.command,
217 }
218
219 service('restart', 'nagios-nrpe-server')
220
221 for rid in relation_ids("local-monitors"):
222 relation_set(relation_id=rid, monitors=yaml.dump(monitors))
0223
=== added file 'hooks/charmhelpers/contrib/charmsupport/volumes.py'
--- hooks/charmhelpers/contrib/charmsupport/volumes.py 1970-01-01 00:00:00 +0000
+++ hooks/charmhelpers/contrib/charmsupport/volumes.py 2014-11-20 02:17:21 +0000
@@ -0,0 +1,156 @@
1'''
2Functions for managing volumes in juju units. One volume is supported per unit.
3Subordinates may have their own storage, provided it is on its own partition.
4
5Configuration stanzas:
6 volume-ephemeral:
7 type: boolean
8 default: true
9 description: >
10 If false, a volume is mounted as sepecified in "volume-map"
11 If true, ephemeral storage will be used, meaning that log data
12 will only exist as long as the machine. YOU HAVE BEEN WARNED.
13 volume-map:
14 type: string
15 default: {}
16 description: >
17 YAML map of units to device names, e.g:
18 "{ rsyslog/0: /dev/vdb, rsyslog/1: /dev/vdb }"
19 Service units will raise a configure-error if volume-ephemeral
20 is 'true' and no volume-map value is set. Use 'juju set' to set a
21 value and 'juju resolved' to complete configuration.
22
23Usage:
24 from charmsupport.volumes import configure_volume, VolumeConfigurationError
25 from charmsupport.hookenv import log, ERROR
26 def post_mount_hook():
27 stop_service('myservice')
28 def post_mount_hook():
29 start_service('myservice')
30
31 if __name__ == '__main__':
32 try:
33 configure_volume(before_change=pre_mount_hook,
34 after_change=post_mount_hook)
35 except VolumeConfigurationError:
36 log('Storage could not be configured', ERROR)
37'''
38
39# XXX: Known limitations
40# - fstab is neither consulted nor updated
41
42import os
43from charmhelpers.core import hookenv
44from charmhelpers.core import host
45import yaml
46
47
48MOUNT_BASE = '/srv/juju/volumes'
49
50
51class VolumeConfigurationError(Exception):
52 '''Volume configuration data is missing or invalid'''
53 pass
54
55
56def get_config():
57 '''Gather and sanity-check volume configuration data'''
58 volume_config = {}
59 config = hookenv.config()
60
61 errors = False
62
63 if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'):
64 volume_config['ephemeral'] = True
65 else:
66 volume_config['ephemeral'] = False
67
68 try:
69 volume_map = yaml.safe_load(config.get('volume-map', '{}'))
70 except yaml.YAMLError as e:
71 hookenv.log("Error parsing YAML volume-map: {}".format(e),
72 hookenv.ERROR)
73 errors = True
74 if volume_map is None:
75 # probably an empty string
76 volume_map = {}
77 elif not isinstance(volume_map, dict):
78 hookenv.log("Volume-map should be a dictionary, not {}".format(
79 type(volume_map)))
80 errors = True
81
82 volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME'])
83 if volume_config['device'] and volume_config['ephemeral']:
84 # asked for ephemeral storage but also defined a volume ID
85 hookenv.log('A volume is defined for this unit, but ephemeral '
86 'storage was requested', hookenv.ERROR)
87 errors = True
88 elif not volume_config['device'] and not volume_config['ephemeral']:
89 # asked for permanent storage but did not define volume ID
90 hookenv.log('Ephemeral storage was requested, but there is no volume '
91 'defined for this unit.', hookenv.ERROR)
92 errors = True
93
94 unit_mount_name = hookenv.local_unit().replace('/', '-')
95 volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name)
96
97 if errors:
98 return None
99 return volume_config
100
101
102def mount_volume(config):
103 if os.path.exists(config['mountpoint']):
104 if not os.path.isdir(config['mountpoint']):
105 hookenv.log('Not a directory: {}'.format(config['mountpoint']))
106 raise VolumeConfigurationError()
107 else:
108 host.mkdir(config['mountpoint'])
109 if os.path.ismount(config['mountpoint']):
110 unmount_volume(config)
111 if not host.mount(config['device'], config['mountpoint'], persist=True):
112 raise VolumeConfigurationError()
113
114
115def unmount_volume(config):
116 if os.path.ismount(config['mountpoint']):
117 if not host.umount(config['mountpoint'], persist=True):
118 raise VolumeConfigurationError()
119
120
121def managed_mounts():
122 '''List of all mounted managed volumes'''
123 return filter(lambda mount: mount[0].startswith(MOUNT_BASE), host.mounts())
124
125
126def configure_volume(before_change=lambda: None, after_change=lambda: None):
127 '''Set up storage (or don't) according to the charm's volume configuration.
128 Returns the mount point or "ephemeral". before_change and after_change
129 are optional functions to be called if the volume configuration changes.
130 '''
131
132 config = get_config()
133 if not config:
134 hookenv.log('Failed to read volume configuration', hookenv.CRITICAL)
135 raise VolumeConfigurationError()
136
137 if config['ephemeral']:
138 if os.path.ismount(config['mountpoint']):
139 before_change()
140 unmount_volume(config)
141 after_change()
142 return 'ephemeral'
143 else:
144 # persistent storage
145 if os.path.ismount(config['mountpoint']):
146 mounts = dict(managed_mounts())
147 if mounts.get(config['mountpoint']) != config['device']:
148 before_change()
149 unmount_volume(config)
150 mount_volume(config)
151 after_change()
152 else:
153 before_change()
154 mount_volume(config)
155 after_change()
156 return config['mountpoint']
0157
=== added symlink 'hooks/nrpe-external-master-relation-changed'
=== target is u'quantum_hooks.py'
=== added symlink 'hooks/nrpe-external-master-relation-joined'
=== target is u'quantum_hooks.py'
=== modified file 'hooks/quantum_hooks.py'
--- hooks/quantum_hooks.py 2014-09-30 14:12:10 +0000
+++ hooks/quantum_hooks.py 2014-11-20 02:17:21 +0000
@@ -1,6 +1,7 @@
1#!/usr/bin/python1#!/usr/bin/python
22
3from base64 import b64decode3from base64 import b64decode
4import os
45
5from charmhelpers.core.hookenv import (6from charmhelpers.core.hookenv import (
6 log, ERROR, WARNING,7 log, ERROR, WARNING,
@@ -9,6 +10,8 @@
9 relation_get,10 relation_get,
10 relation_set,11 relation_set,
11 relation_ids,12 relation_ids,
13 relations_of_type,
14 local_unit,
12 unit_get,15 unit_get,
13 Hooks, UnregisteredHookError16 Hooks, UnregisteredHookError
14)17)
@@ -33,10 +36,13 @@
33)36)
34from charmhelpers.payload.execd import execd_preinstall37from charmhelpers.payload.execd import execd_preinstall
3538
39from charmhelpers.contrib.charmsupport.nrpe import NRPE
40
36import sys41import sys
37from quantum_utils import (42from quantum_utils import (
38 register_configs,43 register_configs,
39 restart_map,44 restart_map,
45 services,
40 do_openstack_upgrade,46 do_openstack_upgrade,
41 get_packages,47 get_packages,
42 get_early_packages,48 get_early_packages,
@@ -76,6 +82,7 @@
76 global CONFIGS82 global CONFIGS
77 if openstack_upgrade_available(get_common_package()):83 if openstack_upgrade_available(get_common_package()):
78 CONFIGS = do_openstack_upgrade()84 CONFIGS = do_openstack_upgrade()
85 update_nrpe_config()
79 # Re-run joined hooks as config might have changed86 # Re-run joined hooks as config might have changed
80 for r_id in relation_ids('shared-db'):87 for r_id in relation_ids('shared-db'):
81 db_joined(relation_id=r_id)88 db_joined(relation_id=r_id)
@@ -196,6 +203,67 @@
196def stop():203def stop():
197 stop_services()204 stop_services()
198205
206
207@hooks.hook('nrpe-external-master-relation-joined',
208 'nrpe-external-master-relation-changed')
209def update_nrpe_config():
210 # Find out if nrpe set nagios_hostname
211 hostname = None
212 host_context = None
213 for rel in relations_of_type('nrpe-external-master'):
214 if 'nagios_hostname' in rel:
215 hostname = rel['nagios_hostname']
216 host_context = rel['nagios_host_context']
217 break
218 nrpe = NRPE(hostname=hostname)
219 apt_install('python-dbus')
220
221 if host_context:
222 current_unit = "%s:%s" % (host_context, local_unit())
223 else:
224 current_unit = local_unit()
225
226 services_to_monitor = services()
227 for service in services_to_monitor:
228 upstart_init = '/etc/init/%s.conf' % service
229 sysv_init = '/etc/init.d/%s' % service
230
231 if os.path.exists(upstart_init):
232 nrpe.add_check(
233 shortname=service,
234 description='process check {%s}' % current_unit,
235 check_cmd='check_upstart_job %s' % service,
236 )
237 elif os.path.exists(sysv_init):
238 cronpath = '/etc/cron.d/nagios-service-check-%s' % service
239 cron_template = '*/5 * * * * root \
240/usr/local/lib/nagios/plugins/check_exit_status.pl -s /etc/init.d/%s \
241status > /var/lib/nagios/service-check-%s.txt\n' % (service, service)
242 f = open(cronpath, 'w')
243 f.write(cron_template)
244 f.close()
245 nrpe.add_check(
246 shortname=service,
247 description='process check {%s}' % current_unit,
248 check_cmd='check_status_file.py -f \
249/var/lib/nagios/service-check-%s.txt' % service,
250 )
251
252 cronpath = '/etc/cron.d/nagios-netns-check'
253 cron_template = '*/5 * * * * root \
254/usr/local/lib/nagios/plugins/check_netns.sh \
255> /var/lib/nagios/netns-check.txt\n'
256 f = open(cronpath, 'w')
257 f.write(cron_template)
258 f.close()
259 nrpe.add_check(
260 shortname="netns",
261 description='Network Namespace check {%s}' % current_unit,
262 check_cmd='check_status_file.py -f /var/lib/nagios/netns-check.txt'
263 )
264 nrpe.write()
265
266
199if __name__ == '__main__':267if __name__ == '__main__':
200 try:268 try:
201 hooks.execute(sys.argv)269 hooks.execute(sys.argv)
202270
=== modified file 'hooks/quantum_utils.py'
--- hooks/quantum_utils.py 2014-09-19 09:18:01 +0000
+++ hooks/quantum_utils.py 2014-11-20 02:17:21 +0000
@@ -402,6 +402,14 @@
402 return _map402 return _map
403403
404404
405def services():
406 ''' Returns a list of services associate with this charm '''
407 _services = []
408 for v in restart_map().values():
409 _services = _services + v
410 return list(set(_services))
411
412
405INT_BRIDGE = "br-int"413INT_BRIDGE = "br-int"
406EXT_BRIDGE = "br-ex"414EXT_BRIDGE = "br-ex"
407415
408416
=== modified file 'metadata.yaml'
--- metadata.yaml 2014-09-30 14:12:10 +0000
+++ metadata.yaml 2014-11-20 02:17:21 +0000
@@ -16,6 +16,9 @@
16categories:16categories:
17 - openstack17 - openstack
18provides:18provides:
19 nrpe-external-master:
20 interface: nrpe-external-master
21 scope: container
19 quantum-network-service:22 quantum-network-service:
20 interface: quantum23 interface: quantum
21requires:24requires:

Subscribers

People subscribed via source and target branches