Merge ~xavpaice/charm-nagios:blacken-20.08 into ~nagios-charmers/charm-nagios:master
- Git
- lp:~xavpaice/charm-nagios
- blacken-20.08
- Merge into master
Proposed by
Xav Paice
Status: | Merged |
---|---|
Merged at revision: | b27a20af88bd66c4c5d43b0903b30fa69fd6abd5 |
Proposed branch: | ~xavpaice/charm-nagios:blacken-20.08 |
Merge into: | ~nagios-charmers/charm-nagios:master |
Prerequisite: | ~xavpaice/charm-nagios:makefile-20.08 |
Diff against target: |
1898 lines (+498/-462) 11 files modified
hooks/common.py (+126/-126) hooks/monitors_relation_changed.py (+37/-39) hooks/upgrade_charm.py (+203/-184) hooks/website_relation_joined.py (+7/-7) tests/functional/conftest.py (+56/-43) tests/functional/test_config.py (+46/-41) tests/functional/test_deploy.py (+7/-8) tests/unit/conftest.py (+1/-1) tests/unit/test_monitor_relation_changed.py (+1/-1) tests/unit/test_website_relation_joined.py (+11/-11) tox.ini (+3/-1) |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Alvaro Uria (community) | Approve | ||
Paul Goins | Approve | ||
Xav Paice (community) | Needs Resubmitting | ||
Drew Freiberger (community) | Needs Fixing | ||
Review via email: mp+388626@code.launchpad.net |
Commit message
Blackened repository, fix tests
Description of the change
To post a comment you must log in.
Revision history for this message
Xav Paice (xavpaice) wrote : | # |
suspect that the concatenated strings were prior to https:/
review:
Needs Resubmitting
Revision history for this message
Alvaro Uria (aluria) wrote : | # |
+1 this and the other 2 related MPs (makefile and linting)
review:
Approve
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | diff --git a/hooks/common.py b/hooks/common.py |
2 | index ec34670..3bff942 100644 |
3 | --- a/hooks/common.py |
4 | +++ b/hooks/common.py |
5 | @@ -16,19 +16,19 @@ from charmhelpers.core.hookenv import ( |
6 | |
7 | from pynag import Model |
8 | |
9 | -INPROGRESS_DIR = '/etc/nagios3-inprogress' |
10 | -INPROGRESS_CFG = '/etc/nagios3-inprogress/nagios.cfg' |
11 | -INPROGRESS_CONF_D = '/etc/nagios3-inprogress/conf.d' |
12 | -CHARM_CFG = '/etc/nagios3-inprogress/conf.d/charm.cfg' |
13 | -MAIN_NAGIOS_BAK = '/etc/nagios3.bak' |
14 | -MAIN_NAGIOS_DIR = '/etc/nagios3' |
15 | -MAIN_NAGIOS_CFG = '/etc/nagios3/nagios.cfg' |
16 | -PLUGIN_PATH = '/usr/lib/nagios/plugins' |
17 | +INPROGRESS_DIR = "/etc/nagios3-inprogress" |
18 | +INPROGRESS_CFG = "/etc/nagios3-inprogress/nagios.cfg" |
19 | +INPROGRESS_CONF_D = "/etc/nagios3-inprogress/conf.d" |
20 | +CHARM_CFG = "/etc/nagios3-inprogress/conf.d/charm.cfg" |
21 | +MAIN_NAGIOS_BAK = "/etc/nagios3.bak" |
22 | +MAIN_NAGIOS_DIR = "/etc/nagios3" |
23 | +MAIN_NAGIOS_CFG = "/etc/nagios3/nagios.cfg" |
24 | +PLUGIN_PATH = "/usr/lib/nagios/plugins" |
25 | |
26 | Model.cfg_file = INPROGRESS_CFG |
27 | Model.pynag_directory = INPROGRESS_CONF_D |
28 | |
29 | -reduce_RE = re.compile(r'[\W_]') |
30 | +reduce_RE = re.compile(r"[\W_]") |
31 | |
32 | |
33 | def check_ip(n): |
34 | @@ -43,14 +43,14 @@ def check_ip(n): |
35 | return False |
36 | |
37 | |
38 | -def get_local_ingress_address(binding='website'): |
39 | +def get_local_ingress_address(binding="website"): |
40 | # using network-get to retrieve the address details if available. |
41 | - log('Getting hostname for binding %s' % binding) |
42 | + log("Getting hostname for binding %s" % binding) |
43 | try: |
44 | network_info = network_get(binding) |
45 | - if network_info is not None and 'ingress-addresses' in network_info: |
46 | - log('Using ingress-addresses') |
47 | - hostname = network_info['ingress-addresses'][0] |
48 | + if network_info is not None and "ingress-addresses" in network_info: |
49 | + log("Using ingress-addresses") |
50 | + hostname = network_info["ingress-addresses"][0] |
51 | log(hostname) |
52 | return hostname |
53 | except NotImplementedError: |
54 | @@ -60,11 +60,11 @@ def get_local_ingress_address(binding='website'): |
55 | # Pre 2.3 output |
56 | try: |
57 | hostname = network_get_primary_address(binding) |
58 | - log('Using primary-addresses') |
59 | + log("Using primary-addresses") |
60 | except NotImplementedError: |
61 | # pre Juju 2.0 |
62 | - hostname = unit_get('private-address') |
63 | - log('Using unit_get private address') |
64 | + hostname = unit_get("private-address") |
65 | + log("Using unit_get private address") |
66 | log(hostname) |
67 | return hostname |
68 | |
69 | @@ -72,14 +72,14 @@ def get_local_ingress_address(binding='website'): |
70 | def get_remote_relation_attr(remote_unit, attr_name, relation_id=None): |
71 | args = ["relation-get", attr_name, remote_unit] |
72 | if relation_id is not None: |
73 | - args.extend(['-r', relation_id]) |
74 | + args.extend(["-r", relation_id]) |
75 | return subprocess.check_output(args).strip() |
76 | |
77 | |
78 | def get_ip_and_hostname(remote_unit, relation_id=None): |
79 | - hostname = get_remote_relation_attr(remote_unit, 'ingress-address', relation_id) |
80 | + hostname = get_remote_relation_attr(remote_unit, "ingress-address", relation_id) |
81 | if hostname is None or not len(hostname): |
82 | - hostname = get_remote_relation_attr(remote_unit, 'private-address', relation_id) |
83 | + hostname = get_remote_relation_attr(remote_unit, "private-address", relation_id) |
84 | |
85 | if hostname is None or not len(hostname): |
86 | log("relation-get failed") |
87 | @@ -89,18 +89,18 @@ def get_ip_and_hostname(remote_unit, relation_id=None): |
88 | ip_address = hostname |
89 | else: |
90 | ip_address = socket.getaddrinfo(hostname, None)[0][4][0] |
91 | - return (ip_address, remote_unit.replace('/', '-')) |
92 | + return (ip_address, remote_unit.replace("/", "-")) |
93 | |
94 | |
95 | def refresh_hostgroups(): # noqa:C901 |
96 | """ Not the most efficient thing but since we're only |
97 | parsing what is already on disk here its not too bad """ |
98 | - hosts = [x['host_name'] for x in Model.Host.objects.all if x['host_name']] |
99 | + hosts = [x["host_name"] for x in Model.Host.objects.all if x["host_name"]] |
100 | |
101 | hgroups = {} |
102 | for host in hosts: |
103 | try: |
104 | - (service, unit_id) = host.rsplit('-', 1) |
105 | + (service, unit_id) = host.rsplit("-", 1) |
106 | except ValueError: |
107 | continue |
108 | if service in hgroups: |
109 | @@ -109,8 +109,8 @@ def refresh_hostgroups(): # noqa:C901 |
110 | hgroups[service] = [host] |
111 | |
112 | # Find existing autogenerated |
113 | - auto_hgroups = Model.Hostgroup.objects.filter(notes__contains='#autogenerated#') |
114 | - auto_hgroups = [x.get_attribute('hostgroup_name') for x in auto_hgroups] |
115 | + auto_hgroups = Model.Hostgroup.objects.filter(notes__contains="#autogenerated#") |
116 | + auto_hgroups = [x.get_attribute("hostgroup_name") for x in auto_hgroups] |
117 | |
118 | # Delete the ones not in hgroups |
119 | to_delete = set(auto_hgroups).difference(set(hgroups.keys())) |
120 | @@ -127,10 +127,10 @@ def refresh_hostgroups(): # noqa:C901 |
121 | except (ValueError, KeyError): |
122 | hgroup = Model.Hostgroup() |
123 | hgroup.set_filename(CHARM_CFG) |
124 | - hgroup.set_attribute('hostgroup_name', hgroup_name) |
125 | - hgroup.set_attribute('notes', '#autogenerated#') |
126 | + hgroup.set_attribute("hostgroup_name", hgroup_name) |
127 | + hgroup.set_attribute("notes", "#autogenerated#") |
128 | |
129 | - hgroup.set_attribute('members', ','.join(members)) |
130 | + hgroup.set_attribute("members", ",".join(members)) |
131 | hgroup.save() |
132 | |
133 | |
134 | @@ -138,15 +138,14 @@ def _make_check_command(args): |
135 | args = [str(arg) for arg in args] |
136 | # There is some worry of collision, but the uniqueness of the initial |
137 | # command should be enough. |
138 | - signature = reduce_RE.sub('_', ''.join( |
139 | - [os.path.basename(arg) for arg in args])) |
140 | + signature = reduce_RE.sub("_", "".join([os.path.basename(arg) for arg in args])) |
141 | Model.Command.objects.reload_cache() |
142 | try: |
143 | cmd = Model.Command.objects.get_by_shortname(signature) |
144 | except (ValueError, KeyError): |
145 | cmd = Model.Command() |
146 | - cmd.set_attribute('command_name', signature) |
147 | - cmd.set_attribute('command_line', ' '.join(args)) |
148 | + cmd.set_attribute("command_name", signature) |
149 | + cmd.set_attribute("command_line", " ".join(args)) |
150 | cmd.save() |
151 | return signature |
152 | |
153 | @@ -159,130 +158,131 @@ def _extend_args(args, cmd_args, switch, value): |
154 | def customize_http(service, name, extra): |
155 | args = [] |
156 | cmd_args = [] |
157 | - plugin = os.path.join(PLUGIN_PATH, 'check_http') |
158 | - port = extra.get('port', 80) |
159 | - path = extra.get('path', '/') |
160 | + plugin = os.path.join(PLUGIN_PATH, "check_http") |
161 | + port = extra.get("port", 80) |
162 | + path = extra.get("path", "/") |
163 | args = [port, path] |
164 | - cmd_args = [plugin, '-p', '"$ARG1$"', '-u', '"$ARG2$"'] |
165 | - if 'status' in extra: |
166 | - _extend_args(args, cmd_args, '-e', extra['status']) |
167 | - if 'host' in extra: |
168 | - _extend_args(args, cmd_args, '-H', extra['host']) |
169 | - cmd_args.extend(('-I', '$HOSTADDRESS$')) |
170 | + cmd_args = [plugin, "-p", '"$ARG1$"', "-u", '"$ARG2$"'] |
171 | + if "status" in extra: |
172 | + _extend_args(args, cmd_args, "-e", extra["status"]) |
173 | + if "host" in extra: |
174 | + _extend_args(args, cmd_args, "-H", extra["host"]) |
175 | + cmd_args.extend(("-I", "$HOSTADDRESS$")) |
176 | else: |
177 | - cmd_args.extend(('-H', '$HOSTADDRESS$')) |
178 | - check_timeout = config('check_timeout') |
179 | + cmd_args.extend(("-H", "$HOSTADDRESS$")) |
180 | + check_timeout = config("check_timeout") |
181 | if check_timeout is not None: |
182 | - cmd_args.extend(('-t', check_timeout)) |
183 | + cmd_args.extend(("-t", check_timeout)) |
184 | check_command = _make_check_command(cmd_args) |
185 | - cmd = '%s!%s' % (check_command, '!'.join([str(x) for x in args])) |
186 | - service.set_attribute('check_command', cmd) |
187 | + cmd = "%s!%s" % (check_command, "!".join([str(x) for x in args])) |
188 | + service.set_attribute("check_command", cmd) |
189 | return True |
190 | |
191 | |
192 | def customize_mysql(service, name, extra): |
193 | - plugin = os.path.join(PLUGIN_PATH, 'check_mysql') |
194 | + plugin = os.path.join(PLUGIN_PATH, "check_mysql") |
195 | args = [] |
196 | - cmd_args = [plugin, '-H', '$HOSTADDRESS$'] |
197 | - if 'user' in extra: |
198 | - _extend_args(args, cmd_args, '-u', extra['user']) |
199 | - if 'password' in extra: |
200 | - _extend_args(args, cmd_args, '-p', extra['password']) |
201 | - check_timeout = config('check_timeout') |
202 | + cmd_args = [plugin, "-H", "$HOSTADDRESS$"] |
203 | + if "user" in extra: |
204 | + _extend_args(args, cmd_args, "-u", extra["user"]) |
205 | + if "password" in extra: |
206 | + _extend_args(args, cmd_args, "-p", extra["password"]) |
207 | + check_timeout = config("check_timeout") |
208 | if check_timeout is not None: |
209 | - cmd_args.extend(('-t', check_timeout)) |
210 | + cmd_args.extend(("-t", check_timeout)) |
211 | check_command = _make_check_command(cmd_args) |
212 | - cmd = '%s!%s' % (check_command, '!'.join([str(x) for x in args])) |
213 | - service.set_attribute('check_command', cmd) |
214 | + cmd = "%s!%s" % (check_command, "!".join([str(x) for x in args])) |
215 | + service.set_attribute("check_command", cmd) |
216 | return True |
217 | |
218 | |
219 | def customize_pgsql(service, name, extra): |
220 | - plugin = os.path.join(PLUGIN_PATH, 'check_pgsql') |
221 | + plugin = os.path.join(PLUGIN_PATH, "check_pgsql") |
222 | args = [] |
223 | - cmd_args = [plugin, '-H', '$HOSTADDRESS$'] |
224 | - check_timeout = config('check_timeout') |
225 | + cmd_args = [plugin, "-H", "$HOSTADDRESS$"] |
226 | + check_timeout = config("check_timeout") |
227 | if check_timeout is not None: |
228 | - cmd_args.extend(('-t', check_timeout)) |
229 | + cmd_args.extend(("-t", check_timeout)) |
230 | check_command = _make_check_command(cmd_args) |
231 | - cmd = '%s!%s' % (check_command, '!'.join([str(x) for x in args])) |
232 | - service.set_attribute('check_command', cmd) |
233 | + cmd = "%s!%s" % (check_command, "!".join([str(x) for x in args])) |
234 | + service.set_attribute("check_command", cmd) |
235 | return True |
236 | |
237 | |
238 | def customize_nrpe(service, name, extra): |
239 | - plugin = os.path.join(PLUGIN_PATH, 'check_nrpe') |
240 | + plugin = os.path.join(PLUGIN_PATH, "check_nrpe") |
241 | args = [] |
242 | - cmd_args = [plugin, '-H', '$HOSTADDRESS$'] |
243 | - if name in ('mem', 'swap'): |
244 | - cmd_args.extend(('-c', 'check_%s' % name)) |
245 | - elif 'command' in extra: |
246 | - cmd_args.extend(('-c', extra['command'])) |
247 | + cmd_args = [plugin, "-H", "$HOSTADDRESS$"] |
248 | + if name in ("mem", "swap"): |
249 | + cmd_args.extend(("-c", "check_%s" % name)) |
250 | + elif "command" in extra: |
251 | + cmd_args.extend(("-c", extra["command"])) |
252 | else: |
253 | - cmd_args.extend(('-c', extra)) |
254 | - check_timeout = config('check_timeout') |
255 | + cmd_args.extend(("-c", extra)) |
256 | + check_timeout = config("check_timeout") |
257 | if check_timeout is not None: |
258 | - cmd_args.extend(('-t', check_timeout)) |
259 | + cmd_args.extend(("-t", check_timeout)) |
260 | check_command = _make_check_command(cmd_args) |
261 | - cmd = '%s!%s' % (check_command, '!'.join([str(x) for x in args])) |
262 | - service.set_attribute('check_command', cmd) |
263 | + cmd = "%s!%s" % (check_command, "!".join([str(x) for x in args])) |
264 | + service.set_attribute("check_command", cmd) |
265 | return True |
266 | |
267 | |
268 | def customize_rpc(service, name, extra): |
269 | """ Customize the check_rpc plugin to check things like nfs.""" |
270 | - plugin = os.path.join(PLUGIN_PATH, 'check_rpc') |
271 | + plugin = os.path.join(PLUGIN_PATH, "check_rpc") |
272 | args = [] |
273 | # /usr/lib/nagios/plugins/check_rpc -H <host> -C <rpc_command> |
274 | - cmd_args = [plugin, '-H', '$HOSTADDRESS$'] |
275 | - if 'rpc_command' in extra: |
276 | - cmd_args.extend(('-C', extra['rpc_command'])) |
277 | - if 'program_version' in extra: |
278 | - cmd_args.extend(('-c', extra['program_version'])) |
279 | + cmd_args = [plugin, "-H", "$HOSTADDRESS$"] |
280 | + if "rpc_command" in extra: |
281 | + cmd_args.extend(("-C", extra["rpc_command"])) |
282 | + if "program_version" in extra: |
283 | + cmd_args.extend(("-c", extra["program_version"])) |
284 | |
285 | check_command = _make_check_command(cmd_args) |
286 | - cmd = '%s!%s' % (check_command, '!'.join([str(x) for x in args])) |
287 | - service.set_attribute('check_command', cmd) |
288 | + cmd = "%s!%s" % (check_command, "!".join([str(x) for x in args])) |
289 | + service.set_attribute("check_command", cmd) |
290 | return True |
291 | |
292 | |
293 | def customize_tcp(service, name, extra): |
294 | """ Customize tcp can be used to check things like memcached. """ |
295 | - plugin = os.path.join(PLUGIN_PATH, 'check_tcp') |
296 | + plugin = os.path.join(PLUGIN_PATH, "check_tcp") |
297 | args = [] |
298 | # /usr/lib/nagios/plugins/check_tcp -H <host> -E |
299 | - cmd_args = [plugin, '-H', '$HOSTADDRESS$', '-E'] |
300 | - if 'port' in extra: |
301 | - cmd_args.extend(('-p', extra['port'])) |
302 | - if 'string' in extra: |
303 | - cmd_args.extend(('-s', "'{}'".format(extra['string']))) |
304 | - if 'expect' in extra: |
305 | - cmd_args.extend(('-e', extra['expect'])) |
306 | - if 'warning' in extra: |
307 | - cmd_args.extend(('-w', extra['warning'])) |
308 | - if 'critical' in extra: |
309 | - cmd_args.extend(('-c', extra['critical'])) |
310 | - if 'timeout' in extra: |
311 | - cmd_args.extend(('-t', extra['timeout'])) |
312 | - check_timeout = config('check_timeout') |
313 | + cmd_args = [plugin, "-H", "$HOSTADDRESS$", "-E"] |
314 | + if "port" in extra: |
315 | + cmd_args.extend(("-p", extra["port"])) |
316 | + if "string" in extra: |
317 | + cmd_args.extend(("-s", "'{}'".format(extra["string"]))) |
318 | + if "expect" in extra: |
319 | + cmd_args.extend(("-e", extra["expect"])) |
320 | + if "warning" in extra: |
321 | + cmd_args.extend(("-w", extra["warning"])) |
322 | + if "critical" in extra: |
323 | + cmd_args.extend(("-c", extra["critical"])) |
324 | + if "timeout" in extra: |
325 | + cmd_args.extend(("-t", extra["timeout"])) |
326 | + check_timeout = config("check_timeout") |
327 | if check_timeout is not None: |
328 | - cmd_args.extend(('-t', check_timeout)) |
329 | + cmd_args.extend(("-t", check_timeout)) |
330 | |
331 | check_command = _make_check_command(cmd_args) |
332 | - cmd = '%s!%s' % (check_command, '!'.join([str(x) for x in args])) |
333 | - service.set_attribute('check_command', cmd) |
334 | + cmd = "%s!%s" % (check_command, "!".join([str(x) for x in args])) |
335 | + service.set_attribute("check_command", cmd) |
336 | return True |
337 | |
338 | |
339 | def customize_service(service, family, name, extra): |
340 | """ The monitors.yaml names are mapped to methods that customize services. """ |
341 | - customs = {'http': customize_http, |
342 | - 'mysql': customize_mysql, |
343 | - 'nrpe': customize_nrpe, |
344 | - 'tcp': customize_tcp, |
345 | - 'rpc': customize_rpc, |
346 | - 'pgsql': customize_pgsql, |
347 | - } |
348 | + customs = { |
349 | + "http": customize_http, |
350 | + "mysql": customize_mysql, |
351 | + "nrpe": customize_nrpe, |
352 | + "tcp": customize_tcp, |
353 | + "rpc": customize_rpc, |
354 | + "pgsql": customize_pgsql, |
355 | + } |
356 | if family in customs: |
357 | return customs[family](service, name, extra) |
358 | return False |
359 | @@ -292,14 +292,13 @@ def update_localhost(): |
360 | """ Update the localhost definition to use the ubuntu icons.""" |
361 | |
362 | Model.cfg_file = MAIN_NAGIOS_CFG |
363 | - Model.pynag_directory = os.path.join(MAIN_NAGIOS_DIR, 'conf.d') |
364 | - hosts = Model.Host.objects.filter(host_name='localhost', |
365 | - object_type='host') |
366 | + Model.pynag_directory = os.path.join(MAIN_NAGIOS_DIR, "conf.d") |
367 | + hosts = Model.Host.objects.filter(host_name="localhost", object_type="host") |
368 | for host in hosts: |
369 | - host.icon_image = 'base/ubuntu.png' |
370 | - host.icon_image_alt = 'Ubuntu Linux' |
371 | - host.vrml_image = 'ubuntu.png' |
372 | - host.statusmap_image = 'base/ubuntu.gd2' |
373 | + host.icon_image = "base/ubuntu.png" |
374 | + host.icon_image_alt = "Ubuntu Linux" |
375 | + host.vrml_image = "ubuntu.png" |
376 | + host.statusmap_image = "base/ubuntu.gd2" |
377 | host.save() |
378 | |
379 | |
380 | @@ -309,13 +308,13 @@ def get_pynag_host(target_id, owner_unit=None, owner_relation=None): |
381 | except (ValueError, KeyError): |
382 | host = Model.Host() |
383 | host.set_filename(CHARM_CFG) |
384 | - host.set_attribute('host_name', target_id) |
385 | - host.set_attribute('use', 'generic-host') |
386 | + host.set_attribute("host_name", target_id) |
387 | + host.set_attribute("use", "generic-host") |
388 | # Adding the ubuntu icon image definitions to the host. |
389 | - host.set_attribute('icon_image', 'base/ubuntu.png') |
390 | - host.set_attribute('icon_image_alt', 'Ubuntu Linux') |
391 | - host.set_attribute('vrml_image', 'ubuntu.png') |
392 | - host.set_attribute('statusmap_image', 'base/ubuntu.gd2') |
393 | + host.set_attribute("icon_image", "base/ubuntu.png") |
394 | + host.set_attribute("icon_image_alt", "Ubuntu Linux") |
395 | + host.set_attribute("vrml_image", "ubuntu.png") |
396 | + host.set_attribute("statusmap_image", "base/ubuntu.gd2") |
397 | host.save() |
398 | host = Model.Host.objects.get_by_shortname(target_id) |
399 | apply_host_policy(target_id, owner_unit, owner_relation) |
400 | @@ -323,22 +322,23 @@ def get_pynag_host(target_id, owner_unit=None, owner_relation=None): |
401 | |
402 | |
403 | def get_pynag_service(target_id, service_name): |
404 | - services = Model.Service.objects.filter(host_name=target_id, |
405 | - service_description=service_name) |
406 | + services = Model.Service.objects.filter( |
407 | + host_name=target_id, service_description=service_name |
408 | + ) |
409 | if len(services) == 0: |
410 | service = Model.Service() |
411 | service.set_filename(CHARM_CFG) |
412 | - service.set_attribute('service_description', service_name) |
413 | - service.set_attribute('host_name', target_id) |
414 | - service.set_attribute('use', 'generic-service') |
415 | + service.set_attribute("service_description", service_name) |
416 | + service.set_attribute("host_name", target_id) |
417 | + service.set_attribute("use", "generic-service") |
418 | else: |
419 | service = services[0] |
420 | return service |
421 | |
422 | |
423 | def apply_host_policy(target_id, owner_unit, owner_relation): |
424 | - ssh_service = get_pynag_service(target_id, 'SSH') |
425 | - ssh_service.set_attribute('check_command', 'check_ssh') |
426 | + ssh_service = get_pynag_service(target_id, "SSH") |
427 | + ssh_service.set_attribute("check_command", "check_ssh") |
428 | ssh_service.save() |
429 | |
430 | |
431 | diff --git a/hooks/monitors_relation_changed.py b/hooks/monitors_relation_changed.py |
432 | index 5e4f664..e3d5a5a 100755 |
433 | --- a/hooks/monitors_relation_changed.py |
434 | +++ b/hooks/monitors_relation_changed.py |
435 | @@ -28,7 +28,7 @@ from charmhelpers.core.hookenv import ( |
436 | related_units, |
437 | relation_ids, |
438 | log, |
439 | - DEBUG |
440 | + DEBUG, |
441 | ) |
442 | |
443 | from common import ( |
444 | @@ -37,14 +37,14 @@ from common import ( |
445 | get_pynag_service, |
446 | refresh_hostgroups, |
447 | initialize_inprogress_config, |
448 | - flush_inprogress_config |
449 | + flush_inprogress_config, |
450 | ) |
451 | |
452 | |
453 | REQUIRED_REL_DATA_KEYS = [ |
454 | - 'target-address', |
455 | - 'monitors', |
456 | - 'target-id', |
457 | + "target-address", |
458 | + "monitors", |
459 | + "target-id", |
460 | ] |
461 | |
462 | |
463 | @@ -52,20 +52,19 @@ def _prepare_relation_data(unit, rid): |
464 | relation_data = relation_get(unit=unit, rid=rid) |
465 | |
466 | if not relation_data: |
467 | - msg = ( |
468 | - 'no relation data found for unit {} in relation {} - ' |
469 | - 'skipping'.format(unit, rid) |
470 | + msg = "no relation data found for unit {} in relation {} - skipping".format( |
471 | + unit, rid |
472 | ) |
473 | log(msg, level=DEBUG) |
474 | return {} |
475 | |
476 | - if rid.split(':')[0] == 'nagios': |
477 | + if rid.split(":")[0] == "nagios": |
478 | # Fake it for the more generic 'nagios' relation |
479 | - relation_data['target-id'] = unit.replace('/', '-') |
480 | - relation_data['monitors'] = {'monitors': {'remote': {}}} |
481 | + relation_data["target-id"] = unit.replace("/", "-") |
482 | + relation_data["monitors"] = {"monitors": {"remote": {}}} |
483 | |
484 | - if not relation_data.get('target-address'): |
485 | - relation_data['target-address'] = ingress_address(unit=unit, rid=rid) |
486 | + if not relation_data.get("target-address"): |
487 | + relation_data["target-address"] = ingress_address(unit=unit, rid=rid) |
488 | |
489 | for key in REQUIRED_REL_DATA_KEYS: |
490 | if not relation_data.get(key): |
491 | @@ -73,9 +72,8 @@ def _prepare_relation_data(unit, rid): |
492 | # the relation at first (e.g. gnocchi). After a few hook runs, |
493 | # though, they add the key. For this reason I think using a logging |
494 | # level higher than DEBUG could be misleading |
495 | - msg = ( |
496 | - '{} not found for unit {} in relation {} - ' |
497 | - 'skipping'.format(key, unit, rid) |
498 | + msg = "{} not found for unit {} in relation {} - skipping".format( |
499 | + key, unit, rid |
500 | ) |
501 | log(msg, level=DEBUG) |
502 | return {} |
503 | @@ -85,7 +83,7 @@ def _prepare_relation_data(unit, rid): |
504 | |
505 | def _collect_relation_data(): |
506 | all_relations = defaultdict(dict) |
507 | - for relname in ['nagios', 'monitors']: |
508 | + for relname in ["nagios", "monitors"]: |
509 | for relid in relation_ids(relname): |
510 | for unit in related_units(relid): |
511 | relation_data = _prepare_relation_data(unit=unit, rid=relid) |
512 | @@ -101,11 +99,10 @@ def main(argv): # noqa: C901 |
513 | # context. |
514 | # |
515 | if len(argv) > 1: |
516 | - relation_settings = {'monitors': open(argv[1]).read(), |
517 | - 'target-id': argv[2]} |
518 | + relation_settings = {"monitors": open(argv[1]).read(), "target-id": argv[2]} |
519 | if len(argv) > 3: |
520 | - relation_settings['target-address'] = argv[3] |
521 | - all_relations = {'monitors:99': {'testing/0': relation_settings}} |
522 | + relation_settings["target-address"] = argv[3] |
523 | + all_relations = {"monitors:99": {"testing/0": relation_settings}} |
524 | else: |
525 | all_relations = _collect_relation_data() |
526 | |
527 | @@ -113,12 +110,12 @@ def main(argv): # noqa: C901 |
528 | targets_with_addresses = set() |
529 | for relid, units in all_relations.iteritems(): |
530 | for unit, relation_settings in units.items(): |
531 | - if 'target-id' in relation_settings: |
532 | - targets_with_addresses.add(relation_settings['target-id']) |
533 | + if "target-id" in relation_settings: |
534 | + targets_with_addresses.add(relation_settings["target-id"]) |
535 | new_all_relations = {} |
536 | for relid, units in all_relations.iteritems(): |
537 | for unit, relation_settings in units.items(): |
538 | - if relation_settings['target-id'] in targets_with_addresses: |
539 | + if relation_settings["target-id"] in targets_with_addresses: |
540 | if relid not in new_all_relations: |
541 | new_all_relations[relid] = {} |
542 | new_all_relations[relid][unit] = relation_settings |
543 | @@ -129,21 +126,21 @@ def main(argv): # noqa: C901 |
544 | all_hosts = {} |
545 | for relid, units in all_relations.items(): |
546 | for unit, relation_settings in units.iteritems(): |
547 | - machine_id = relation_settings.get('machine_id', None) |
548 | + machine_id = relation_settings.get("machine_id", None) |
549 | if machine_id: |
550 | - all_hosts[machine_id] = relation_settings['target-id'] |
551 | + all_hosts[machine_id] = relation_settings["target-id"] |
552 | for relid, units in all_relations.items(): |
553 | apply_relation_config(relid, units, all_hosts) |
554 | refresh_hostgroups() |
555 | flush_inprogress_config() |
556 | - os.system('service nagios3 reload') |
557 | + os.system("service nagios3 reload") |
558 | |
559 | |
560 | -def apply_relation_config(relid, units, all_hosts): # noqa: C901 |
561 | +def apply_relation_config(relid, units, all_hosts): # noqa: C901 |
562 | for unit, relation_settings in units.iteritems(): |
563 | - monitors = relation_settings['monitors'] |
564 | - target_id = relation_settings['target-id'] |
565 | - machine_id = relation_settings.get('machine_id', None) |
566 | + monitors = relation_settings["monitors"] |
567 | + target_id = relation_settings["target-id"] |
568 | + machine_id = relation_settings.get("machine_id", None) |
569 | parent_host = None |
570 | if machine_id: |
571 | container_regex = re.compile(r"(\d+)/lx[cd]/\d+") |
572 | @@ -155,7 +152,7 @@ def apply_relation_config(relid, units, all_hosts): # noqa: C901 |
573 | # If not set, we don't mess with it, as multiple services may feed |
574 | # monitors in for a particular address. Generally a primary will set |
575 | # this to its own private-address |
576 | - target_address = relation_settings.get('target-address', None) |
577 | + target_address = relation_settings.get("target-address", None) |
578 | |
579 | if type(monitors) != dict: |
580 | monitors = yaml.safe_load(monitors) |
581 | @@ -164,23 +161,24 @@ def apply_relation_config(relid, units, all_hosts): # noqa: C901 |
582 | host = get_pynag_host(target_id) |
583 | if not target_address: |
584 | raise Exception("No Target Address provied by NRPE service!") |
585 | - host.set_attribute('address', target_address) |
586 | + host.set_attribute("address", target_address) |
587 | if parent_host: |
588 | # We assume that we only want one parent and will overwrite any |
589 | # existing parents for this host. |
590 | - host.set_attribute('parents', parent_host) |
591 | + host.set_attribute("parents", parent_host) |
592 | host.save() |
593 | |
594 | - for mon_family, mons in monitors['monitors']['remote'].iteritems(): |
595 | + for mon_family, mons in monitors["monitors"]["remote"].iteritems(): |
596 | for mon_name, mon in mons.iteritems(): |
597 | - service_name = '%s-%s' % (target_id, mon_name) |
598 | + service_name = "%s-%s" % (target_id, mon_name) |
599 | service = get_pynag_service(target_id, service_name) |
600 | if customize_service(service, mon_family, mon_name, mon): |
601 | service.save() |
602 | else: |
603 | - print('Ignoring %s due to unknown family %s' % (mon_name, |
604 | - mon_family)) |
605 | + print( |
606 | + "Ignoring %s due to unknown family %s" % (mon_name, mon_family) |
607 | + ) |
608 | |
609 | |
610 | -if __name__ == '__main__': |
611 | +if __name__ == "__main__": |
612 | main(sys.argv) |
613 | diff --git a/hooks/upgrade_charm.py b/hooks/upgrade_charm.py |
614 | index 20957ba..5091f9a 100755 |
615 | --- a/hooks/upgrade_charm.py |
616 | +++ b/hooks/upgrade_charm.py |
617 | @@ -6,6 +6,7 @@ import base64 |
618 | from jinja2 import Template |
619 | import glob |
620 | import os |
621 | + |
622 | # import re |
623 | import pwd |
624 | import grp |
625 | @@ -22,27 +23,27 @@ from charmhelpers import fetch |
626 | from common import update_localhost |
627 | |
628 | # Gather facts |
629 | -legacy_relations = hookenv.config('legacy') |
630 | -extra_config = hookenv.config('extraconfig') |
631 | -enable_livestatus = hookenv.config('enable_livestatus') |
632 | -livestatus_path = hookenv.config('livestatus_path') |
633 | -enable_pagerduty = hookenv.config('enable_pagerduty') |
634 | -pagerduty_key = hookenv.config('pagerduty_key') |
635 | -pagerduty_path = hookenv.config('pagerduty_path') |
636 | -notification_levels = hookenv.config('pagerduty_notification_levels') |
637 | -nagios_user = hookenv.config('nagios_user') |
638 | -nagios_group = hookenv.config('nagios_group') |
639 | -ssl_config = str(hookenv.config('ssl')).lower() |
640 | -charm_dir = os.environ['CHARM_DIR'] |
641 | -cert_domain = hookenv.unit_get('public-address') |
642 | +legacy_relations = hookenv.config("legacy") |
643 | +extra_config = hookenv.config("extraconfig") |
644 | +enable_livestatus = hookenv.config("enable_livestatus") |
645 | +livestatus_path = hookenv.config("livestatus_path") |
646 | +enable_pagerduty = hookenv.config("enable_pagerduty") |
647 | +pagerduty_key = hookenv.config("pagerduty_key") |
648 | +pagerduty_path = hookenv.config("pagerduty_path") |
649 | +notification_levels = hookenv.config("pagerduty_notification_levels") |
650 | +nagios_user = hookenv.config("nagios_user") |
651 | +nagios_group = hookenv.config("nagios_group") |
652 | +ssl_config = str(hookenv.config("ssl")).lower() |
653 | +charm_dir = os.environ["CHARM_DIR"] |
654 | +cert_domain = hookenv.unit_get("public-address") |
655 | nagios_cfg = "/etc/nagios3/nagios.cfg" |
656 | nagios_cgi_cfg = "/etc/nagios3/cgi.cfg" |
657 | pagerduty_cfg = "/etc/nagios3/conf.d/pagerduty_nagios.cfg" |
658 | traps_cfg = "/etc/nagios3/conf.d/traps.cfg" |
659 | pagerduty_cron = "/etc/cron.d/nagios-pagerduty-flush" |
660 | -password = hookenv.config('password') |
661 | -ro_password = hookenv.config('ro-password') |
662 | -nagiosadmin = hookenv.config('nagiosadmin') or 'nagiosadmin' |
663 | +password = hookenv.config("password") |
664 | +ro_password = hookenv.config("ro-password") |
665 | +nagiosadmin = hookenv.config("nagiosadmin") or "nagiosadmin" |
666 | contactgroup_members = hookenv.config("contactgroup-members") |
667 | |
668 | # this global var will collect contactgroup members that must be forced |
669 | @@ -60,11 +61,12 @@ def warn_legacy_relations(): |
670 | in the future |
671 | """ |
672 | if legacy_relations is not None: |
673 | - hookenv.log("Relations have been radically changed." |
674 | - " The monitoring interface is not supported anymore.", |
675 | - "WARNING") |
676 | - hookenv.log("Please use the generic juju-info or the monitors interface", |
677 | - "WARNING") |
678 | + hookenv.log( |
679 | + "Relations have been radically changed." |
680 | + " The monitoring interface is not supported anymore.", |
681 | + "WARNING", |
682 | + ) |
683 | + hookenv.log("Please use the generic juju-info or the monitors interface", "WARNING") |
684 | |
685 | |
686 | def parse_extra_contacts(yaml_string): |
687 | @@ -76,40 +78,44 @@ def parse_extra_contacts(yaml_string): |
688 | extra_contacts = [] |
689 | |
690 | # Valid characters for contact names |
691 | - valid_name_chars = string.ascii_letters + string.digits + '_-' |
692 | + valid_name_chars = string.ascii_letters + string.digits + "_-" |
693 | |
694 | try: |
695 | extra_contacts_raw = yaml.load(yaml_string, Loader=yaml.SafeLoader) or [] |
696 | if not isinstance(extra_contacts_raw, list): |
697 | - raise ValueError('not a list') |
698 | + raise ValueError("not a list") |
699 | |
700 | for contact in extra_contacts_raw: |
701 | - if {'name', 'host', 'service'} > set(contact.keys()): |
702 | - hookenv.log('Contact {} is missing fields.'.format(contact), |
703 | - hookenv.WARNING) |
704 | + if {"name", "host", "service"} > set(contact.keys()): |
705 | + hookenv.log( |
706 | + "Contact {} is missing fields.".format(contact), hookenv.WARNING |
707 | + ) |
708 | continue |
709 | |
710 | - if set(contact['name']) > set(valid_name_chars): |
711 | - hookenv.log('Contact name {} is illegal'.format(contact['name']), |
712 | - hookenv.WARNING) |
713 | + if set(contact["name"]) > set(valid_name_chars): |
714 | + hookenv.log( |
715 | + "Contact name {} is illegal".format(contact["name"]), |
716 | + hookenv.WARNING, |
717 | + ) |
718 | continue |
719 | |
720 | - if '\n' in (contact['host'] + contact['service']): |
721 | - hookenv.log('Line breaks not allowed in commands', hookenv.WARNING) |
722 | + if "\n" in (contact["host"] + contact["service"]): |
723 | + hookenv.log("Line breaks not allowed in commands", hookenv.WARNING) |
724 | continue |
725 | |
726 | - contact['name'] = contact['name'].lower() |
727 | - contact['alias'] = contact['name'].capitalize() |
728 | + contact["name"] = contact["name"].lower() |
729 | + contact["alias"] = contact["name"].capitalize() |
730 | extra_contacts.append(contact) |
731 | |
732 | except (ValueError, yaml.error.YAMLError) as e: |
733 | - hookenv.log('Invalid "extra_contacts" configuration: {}'.format(e), |
734 | - hookenv.WARNING) |
735 | + hookenv.log( |
736 | + 'Invalid "extra_contacts" configuration: {}'.format(e), hookenv.WARNING |
737 | + ) |
738 | if len(extra_contacts_raw) != len(extra_contacts): |
739 | hookenv.log( |
740 | - 'Invalid extra_contacts config, found {} contacts defined, ' |
741 | - 'only {} were valid, check unit logs for ' |
742 | - 'detailed errors'.format(len(extra_contacts_raw), len(extra_contacts)) |
743 | + "Invalid extra_contacts config, found {} contacts defined, " |
744 | + "only {} were valid, check unit logs for " |
745 | + "detailed errors".format(len(extra_contacts_raw), len(extra_contacts)) |
746 | ) |
747 | |
748 | return extra_contacts |
749 | @@ -119,12 +125,12 @@ def parse_extra_contacts(yaml_string): |
750 | # proper nagios3 configuration file, otherwise remove the config |
751 | def write_extra_config(): |
752 | # Be predjudice about this - remove the file always. |
753 | - if host.file_hash('/etc/nagios3/conf.d/extra.cfg') is not None: |
754 | - os.remove('/etc/nagios3/conf.d/extra.cfg') |
755 | + if host.file_hash("/etc/nagios3/conf.d/extra.cfg") is not None: |
756 | + os.remove("/etc/nagios3/conf.d/extra.cfg") |
757 | # If we have a config, then write it. the hook reconfiguration will |
758 | # handle the details |
759 | if extra_config is not None: |
760 | - host.write_file('/etc/nagios3/conf.d/extra.cfg', extra_config) |
761 | + host.write_file("/etc/nagios3/conf.d/extra.cfg", extra_config) |
762 | |
763 | |
764 | # Equivalent of mkdir -p, since we can't rely on |
765 | @@ -152,7 +158,7 @@ def enable_livestatus_config(): |
766 | if enable_livestatus: |
767 | hookenv.log("Livestatus is enabled") |
768 | fetch.apt_update() |
769 | - fetch.apt_install('check-mk-livestatus') |
770 | + fetch.apt_install("check-mk-livestatus") |
771 | |
772 | # Make the directory and fix perms on it |
773 | hookenv.log("Fixing perms on livestatus_path") |
774 | @@ -170,8 +176,10 @@ def enable_livestatus_config(): |
775 | os.chown(livestatus_dir, uid, gid) |
776 | st = os.stat(livestatus_path) |
777 | os.chmod(livestatus_path, st.st_mode | stat.S_IRGRP) |
778 | - os.chmod(livestatus_dir, st.st_mode | stat.S_IRGRP | |
779 | - stat.S_ISGID | stat.S_IXUSR | stat.S_IXGRP) |
780 | + os.chmod( |
781 | + livestatus_dir, |
782 | + st.st_mode | stat.S_IRGRP | stat.S_ISGID | stat.S_IXUSR | stat.S_IXGRP, |
783 | + ) |
784 | |
785 | |
786 | def enable_pagerduty_config(): |
787 | @@ -180,34 +188,35 @@ def enable_pagerduty_config(): |
788 | if enable_pagerduty: |
789 | hookenv.log("Pagerduty is enabled") |
790 | fetch.apt_update() |
791 | - fetch.apt_install('libhttp-parser-perl') |
792 | + fetch.apt_install("libhttp-parser-perl") |
793 | env = os.environ |
794 | - proxy = env.get('JUJU_CHARM_HTTPS_PROXY') or env.get('https_proxy') |
795 | - proxy_switch = '--proxy {}'.format(proxy) if proxy else '' |
796 | + proxy = env.get("JUJU_CHARM_HTTPS_PROXY") or env.get("https_proxy") |
797 | + proxy_switch = "--proxy {}".format(proxy) if proxy else "" |
798 | |
799 | # Ship the pagerduty_nagios.cfg file |
800 | - template_values = {'pagerduty_key': pagerduty_key, |
801 | - 'pagerduty_path': pagerduty_path, |
802 | - 'proxy_switch': proxy_switch, |
803 | - 'notification_levels': notification_levels} |
804 | - |
805 | - with open('hooks/templates/pagerduty_nagios_cfg.tmpl', 'r') as f: |
806 | + template_values = { |
807 | + "pagerduty_key": pagerduty_key, |
808 | + "pagerduty_path": pagerduty_path, |
809 | + "proxy_switch": proxy_switch, |
810 | + "notification_levels": notification_levels, |
811 | + } |
812 | + |
813 | + with open("hooks/templates/pagerduty_nagios_cfg.tmpl", "r") as f: |
814 | templateDef = f.read() |
815 | |
816 | t = Template(templateDef) |
817 | - with open(pagerduty_cfg, 'w') as f: |
818 | + with open(pagerduty_cfg, "w") as f: |
819 | f.write(t.render(template_values)) |
820 | |
821 | - with open('hooks/templates/nagios-pagerduty-flush-cron.tmpl', 'r') as f2: |
822 | + with open("hooks/templates/nagios-pagerduty-flush-cron.tmpl", "r") as f2: |
823 | templateDef = f2.read() |
824 | |
825 | t2 = Template(templateDef) |
826 | - with open(pagerduty_cron, 'w') as f2: |
827 | + with open(pagerduty_cron, "w") as f2: |
828 | f2.write(t2.render(template_values)) |
829 | |
830 | # Ship the pagerduty_nagios.pl script |
831 | - shutil.copy('files/pagerduty_nagios.pl', |
832 | - '/usr/local/bin/pagerduty_nagios.pl') |
833 | + shutil.copy("files/pagerduty_nagios.pl", "/usr/local/bin/pagerduty_nagios.pl") |
834 | |
835 | # Create the pagerduty queue dir |
836 | if not os.path.isdir(pagerduty_path): |
837 | @@ -228,13 +237,13 @@ def enable_pagerduty_config(): |
838 | if enable_pagerduty: |
839 | # avoid duplicates |
840 | if "pagerduty" not in contactgroup_members: |
841 | - forced_contactgroup_members.append('pagerduty') |
842 | + forced_contactgroup_members.append("pagerduty") |
843 | |
844 | |
845 | def enable_traps_config(): |
846 | global forced_contactgroup_members |
847 | |
848 | - send_traps_to = hookenv.config('send_traps_to') |
849 | + send_traps_to = hookenv.config("send_traps_to") |
850 | |
851 | if not send_traps_to: |
852 | if os.path.isfile(traps_cfg): |
853 | @@ -245,25 +254,23 @@ def enable_traps_config(): |
854 | hookenv.log("Send traps feature is enabled, target address is %s" % send_traps_to) |
855 | |
856 | if "managementstation" not in contactgroup_members: |
857 | - forced_contactgroup_members.append('managementstation') |
858 | + forced_contactgroup_members.append("managementstation") |
859 | |
860 | - template_values = { 'send_traps_to': send_traps_to } |
861 | + template_values = {"send_traps_to": send_traps_to} |
862 | |
863 | - with open('hooks/templates/traps.tmpl','r') as f: |
864 | + with open("hooks/templates/traps.tmpl", "r") as f: |
865 | templateDef = f.read() |
866 | |
867 | t = Template(templateDef) |
868 | - with open(traps_cfg, 'w') as f: |
869 | + with open(traps_cfg, "w") as f: |
870 | f.write(t.render(template_values)) |
871 | |
872 | |
873 | def update_contacts(): |
874 | # Multiple Email Contacts |
875 | - admin_members = '' |
876 | + admin_members = "" |
877 | contacts = [] |
878 | - admin_email = list( |
879 | - filter(None, set(hookenv.config('admin_email').split(','))) |
880 | - ) |
881 | + admin_email = list(filter(None, set(hookenv.config("admin_email").split(",")))) |
882 | if len(admin_email) == 0: |
883 | hookenv.log("admin_email is unset, this isn't valid config") |
884 | hookenv.status_set("blocked", "admin_email is not configured") |
885 | @@ -271,26 +278,18 @@ def update_contacts(): |
886 | hookenv.status_set("active", "ready") |
887 | if len(admin_email) == 1: |
888 | hookenv.log("Setting one admin email address '%s'" % admin_email[0]) |
889 | - contacts = [{ |
890 | - 'contact_name': 'root', |
891 | - 'alias': 'Root', |
892 | - 'email': admin_email[0] |
893 | - }] |
894 | + contacts = [{"contact_name": "root", "alias": "Root", "email": admin_email[0]}] |
895 | elif len(admin_email) > 1: |
896 | hookenv.log("Setting %d admin email addresses" % len(admin_email)) |
897 | contacts = [] |
898 | for email in admin_email: |
899 | - contact_name = email.replace('@', '').replace('.','').lower() |
900 | + contact_name = email.replace("@", "").replace(".", "").lower() |
901 | contact_alias = contact_name.capitalize() |
902 | - contacts.append({ |
903 | - 'contact_name': contact_name, |
904 | - 'alias': contact_alias, |
905 | - 'email': email |
906 | - }) |
907 | + contacts.append( |
908 | + {"contact_name": contact_name, "alias": contact_alias, "email": email} |
909 | + ) |
910 | |
911 | - admin_members = ', '.join([ |
912 | - c['contact_name'] for c in contacts |
913 | - ]) |
914 | + admin_members = ", ".join([c["contact_name"] for c in contacts]) |
915 | |
916 | resulting_members = contactgroup_members |
917 | if admin_members: |
918 | @@ -301,26 +300,40 @@ def update_contacts(): |
919 | resulting_members = ",".join([resulting_members] + forced_contactgroup_members) |
920 | |
921 | # Parse extra_contacts |
922 | - extra_contacts = parse_extra_contacts(hookenv.config('extra_contacts')) |
923 | - |
924 | - template_values = {'admin_service_notification_period': hookenv.config('admin_service_notification_period'), |
925 | - 'admin_host_notification_period': hookenv.config('admin_host_notification_period'), |
926 | - 'admin_service_notification_options': hookenv.config('admin_service_notification_options'), |
927 | - 'admin_host_notification_options': hookenv.config('admin_host_notification_options'), |
928 | - 'admin_service_notification_commands': hookenv.config('admin_service_notification_commands'), |
929 | - 'admin_host_notification_commands': hookenv.config('admin_host_notification_commands'), |
930 | - 'contacts': contacts, |
931 | - 'contactgroup_members': resulting_members, |
932 | - 'extra_contacts': extra_contacts} |
933 | - |
934 | - with open('hooks/templates/contacts-cfg.tmpl', 'r') as f: |
935 | + extra_contacts = parse_extra_contacts(hookenv.config("extra_contacts")) |
936 | + |
937 | + template_values = { |
938 | + "admin_service_notification_period": hookenv.config( |
939 | + "admin_service_notification_period" |
940 | + ), |
941 | + "admin_host_notification_period": hookenv.config( |
942 | + "admin_host_notification_period" |
943 | + ), |
944 | + "admin_service_notification_options": hookenv.config( |
945 | + "admin_service_notification_options" |
946 | + ), |
947 | + "admin_host_notification_options": hookenv.config( |
948 | + "admin_host_notification_options" |
949 | + ), |
950 | + "admin_service_notification_commands": hookenv.config( |
951 | + "admin_service_notification_commands" |
952 | + ), |
953 | + "admin_host_notification_commands": hookenv.config( |
954 | + "admin_host_notification_commands" |
955 | + ), |
956 | + "contacts": contacts, |
957 | + "contactgroup_members": resulting_members, |
958 | + "extra_contacts": extra_contacts, |
959 | + } |
960 | + |
961 | + with open("hooks/templates/contacts-cfg.tmpl", "r") as f: |
962 | template_def = f.read() |
963 | |
964 | t = Template(template_def) |
965 | - with open('/etc/nagios3/conf.d/contacts_nagios2.cfg', 'w') as f: |
966 | + with open("/etc/nagios3/conf.d/contacts_nagios2.cfg", "w") as f: |
967 | f.write(t.render(template_values)) |
968 | |
969 | - host.service_reload('nagios3') |
970 | + host.service_reload("nagios3") |
971 | |
972 | |
973 | def ssl_configured(): |
974 | @@ -331,13 +344,13 @@ def ssl_configured(): |
975 | |
976 | |
977 | # Gather local facts for SSL deployment |
978 | -deploy_key_path = os.path.join(charm_dir, 'data', '%s.key' % (cert_domain)) |
979 | -deploy_cert_path = os.path.join(charm_dir, 'data', '%s.crt' % (cert_domain)) |
980 | -deploy_csr_path = os.path.join(charm_dir, 'data', '%s.csr' % (cert_domain)) |
981 | +deploy_key_path = os.path.join(charm_dir, "data", "%s.key" % (cert_domain)) |
982 | +deploy_cert_path = os.path.join(charm_dir, "data", "%s.crt" % (cert_domain)) |
983 | +deploy_csr_path = os.path.join(charm_dir, "data", "%s.csr" % (cert_domain)) |
984 | # set basename for SSL key locations |
985 | -cert_file = '/etc/ssl/certs/%s.pem' % (cert_domain) |
986 | -key_file = '/etc/ssl/private/%s.key' % (cert_domain) |
987 | -chain_file = '/etc/ssl/certs/%s.csr' % (cert_domain) |
988 | +cert_file = "/etc/ssl/certs/%s.pem" % (cert_domain) |
989 | +key_file = "/etc/ssl/private/%s.key" % (cert_domain) |
990 | +chain_file = "/etc/ssl/certs/%s.csr" % (cert_domain) |
991 | |
992 | |
993 | # Check for key and certificate, since the CSR is optional |
994 | @@ -353,23 +366,23 @@ def check_ssl_files(): |
995 | |
996 | # Decode the SSL keys from their base64 encoded values in the configuration |
997 | def decode_ssl_keys(): |
998 | - if hookenv.config('ssl_key'): |
999 | + if hookenv.config("ssl_key"): |
1000 | hookenv.log("Writing key from config ssl_key: %s" % key_file) |
1001 | - with open(key_file, 'w') as f: |
1002 | - f.write(str(base64.b64decode(hookenv.config('ssl_key')))) |
1003 | - if hookenv.config('ssl_cert'): |
1004 | - with open(cert_file, 'w') as f: |
1005 | - f.write(str(base64.b64decode(hookenv.config('ssl_cert')))) |
1006 | - if hookenv.config('ssl_chain'): |
1007 | - with open(chain_file, 'w') as f: |
1008 | - f.write(str(base64.b64decode(hookenv.config('ssl_cert')))) |
1009 | + with open(key_file, "w") as f: |
1010 | + f.write(str(base64.b64decode(hookenv.config("ssl_key")))) |
1011 | + if hookenv.config("ssl_cert"): |
1012 | + with open(cert_file, "w") as f: |
1013 | + f.write(str(base64.b64decode(hookenv.config("ssl_cert")))) |
1014 | + if hookenv.config("ssl_chain"): |
1015 | + with open(chain_file, "w") as f: |
1016 | + f.write(str(base64.b64decode(hookenv.config("ssl_cert")))) |
1017 | |
1018 | |
1019 | def enable_ssl(): |
1020 | # Set the basename of all ssl files |
1021 | |
1022 | # Validate that we have configs, and generate a self signed certificate. |
1023 | - if not hookenv.config('ssl_cert'): |
1024 | + if not hookenv.config("ssl_cert"): |
1025 | # bail if keys already exist |
1026 | if os.path.exists(cert_file): |
1027 | hookenv.log("Keys exist, not creating keys!", "WARNING") |
1028 | @@ -388,69 +401,69 @@ def nagios_bool(value): |
1029 | |
1030 | |
1031 | def update_config(): |
1032 | - host_context = hookenv.config('nagios_host_context') |
1033 | - local_host_name = 'nagios' |
1034 | + host_context = hookenv.config("nagios_host_context") |
1035 | + local_host_name = "nagios" |
1036 | principal_unitname = hookenv.principal_unit() |
1037 | # Fallback to using "primary" if it exists. |
1038 | if principal_unitname: |
1039 | local_host_name = principal_unitname |
1040 | else: |
1041 | - local_host_name = hookenv.local_unit().replace('/', '-') |
1042 | - template_values = {'nagios_user': nagios_user, |
1043 | - 'nagios_group': nagios_group, |
1044 | - 'enable_livestatus': enable_livestatus, |
1045 | - 'livestatus_path': livestatus_path, |
1046 | - 'livestatus_args': hookenv.config('livestatus_args'), |
1047 | - 'check_external_commands': hookenv.config('check_external_commands'), |
1048 | - 'command_check_interval': hookenv.config('command_check_interval'), |
1049 | - 'command_file': hookenv.config('command_file'), |
1050 | - 'debug_file': hookenv.config('debug_file'), |
1051 | - 'debug_verbosity': hookenv.config('debug_verbosity'), |
1052 | - 'debug_level': hookenv.config('debug_level'), |
1053 | - 'daemon_dumps_core': hookenv.config('daemon_dumps_core'), |
1054 | - 'flap_detection': nagios_bool(hookenv.config('flap_detection')), |
1055 | - 'admin_email': hookenv.config('admin_email'), |
1056 | - 'admin_pager': hookenv.config('admin_pager'), |
1057 | - 'log_rotation_method': hookenv.config('log_rotation_method'), |
1058 | - 'log_archive_path': hookenv.config('log_archive_path'), |
1059 | - 'use_syslog': hookenv.config('use_syslog'), |
1060 | - 'monitor_self': hookenv.config('monitor_self'), |
1061 | - 'nagios_hostname': "{}-{}".format(host_context, local_host_name), |
1062 | - 'load_monitor': hookenv.config('load_monitor'), |
1063 | - 'is_container': host.is_container(), |
1064 | - 'service_check_timeout': hookenv.config('service_check_timeout'), |
1065 | - 'service_check_timeout_state': hookenv.config('service_check_timeout_state'), |
1066 | - } |
1067 | - |
1068 | - with open('hooks/templates/nagios-cfg.tmpl', 'r') as f: |
1069 | + local_host_name = hookenv.local_unit().replace("/", "-") |
1070 | + template_values = { |
1071 | + "nagios_user": nagios_user, |
1072 | + "nagios_group": nagios_group, |
1073 | + "enable_livestatus": enable_livestatus, |
1074 | + "livestatus_path": livestatus_path, |
1075 | + "livestatus_args": hookenv.config("livestatus_args"), |
1076 | + "check_external_commands": hookenv.config("check_external_commands"), |
1077 | + "command_check_interval": hookenv.config("command_check_interval"), |
1078 | + "command_file": hookenv.config("command_file"), |
1079 | + "debug_file": hookenv.config("debug_file"), |
1080 | + "debug_verbosity": hookenv.config("debug_verbosity"), |
1081 | + "debug_level": hookenv.config("debug_level"), |
1082 | + "daemon_dumps_core": hookenv.config("daemon_dumps_core"), |
1083 | + "flap_detection": nagios_bool(hookenv.config("flap_detection")), |
1084 | + "admin_email": hookenv.config("admin_email"), |
1085 | + "admin_pager": hookenv.config("admin_pager"), |
1086 | + "log_rotation_method": hookenv.config("log_rotation_method"), |
1087 | + "log_archive_path": hookenv.config("log_archive_path"), |
1088 | + "use_syslog": hookenv.config("use_syslog"), |
1089 | + "monitor_self": hookenv.config("monitor_self"), |
1090 | + "nagios_hostname": "{}-{}".format(host_context, local_host_name), |
1091 | + "load_monitor": hookenv.config("load_monitor"), |
1092 | + "is_container": host.is_container(), |
1093 | + "service_check_timeout": hookenv.config("service_check_timeout"), |
1094 | + "service_check_timeout_state": hookenv.config("service_check_timeout_state"), |
1095 | + } |
1096 | + |
1097 | + with open("hooks/templates/nagios-cfg.tmpl", "r") as f: |
1098 | templateDef = f.read() |
1099 | |
1100 | t = Template(templateDef) |
1101 | - with open(nagios_cfg, 'w') as f: |
1102 | + with open(nagios_cfg, "w") as f: |
1103 | f.write(t.render(template_values)) |
1104 | |
1105 | - with open('hooks/templates/localhost_nagios2.cfg.tmpl', 'r') as f: |
1106 | + with open("hooks/templates/localhost_nagios2.cfg.tmpl", "r") as f: |
1107 | templateDef = f.read() |
1108 | |
1109 | t = Template(templateDef) |
1110 | - with open('/etc/nagios3/conf.d/localhost_nagios2.cfg', 'w') as f: |
1111 | + with open("/etc/nagios3/conf.d/localhost_nagios2.cfg", "w") as f: |
1112 | f.write(t.render(template_values)) |
1113 | |
1114 | - host.service_reload('nagios3') |
1115 | + host.service_reload("nagios3") |
1116 | |
1117 | |
1118 | def update_cgi_config(): |
1119 | - template_values = {'nagiosadmin': nagiosadmin, |
1120 | - 'ro_password': ro_password} |
1121 | - with open('hooks/templates/nagios-cgi.tmpl', 'r') as f: |
1122 | + template_values = {"nagiosadmin": nagiosadmin, "ro_password": ro_password} |
1123 | + with open("hooks/templates/nagios-cgi.tmpl", "r") as f: |
1124 | templateDef = f.read() |
1125 | |
1126 | t = Template(templateDef) |
1127 | - with open(nagios_cgi_cfg, 'w') as f: |
1128 | + with open(nagios_cgi_cfg, "w") as f: |
1129 | f.write(t.render(template_values)) |
1130 | |
1131 | - host.service_reload('nagios3') |
1132 | - host.service_reload('apache2') |
1133 | + host.service_reload("nagios3") |
1134 | + host.service_reload("apache2") |
1135 | |
1136 | |
1137 | # Nagios3 is deployed as a global apache application from the archive. |
1138 | @@ -467,33 +480,35 @@ def update_apache(): |
1139 | |
1140 | # Start by Setting the ports.conf |
1141 | |
1142 | - with open('hooks/templates/ports-cfg.jinja2', 'r') as f: |
1143 | + with open("hooks/templates/ports-cfg.jinja2", "r") as f: |
1144 | template_def = f.read() |
1145 | t = Template(template_def) |
1146 | - ports_conf = '/etc/apache2/ports.conf' |
1147 | + ports_conf = "/etc/apache2/ports.conf" |
1148 | |
1149 | - with open(ports_conf, 'w') as f: |
1150 | - f.write(t.render({'enable_http': HTTP_ENABLED})) |
1151 | + with open(ports_conf, "w") as f: |
1152 | + f.write(t.render({"enable_http": HTTP_ENABLED})) |
1153 | |
1154 | # Next setup the default-ssl.conf |
1155 | if os.path.exists(chain_file) and os.path.getsize(chain_file) > 0: |
1156 | ssl_chain = chain_file |
1157 | else: |
1158 | ssl_chain = None |
1159 | - template_values = {'ssl_key': key_file, |
1160 | - 'ssl_cert': cert_file, |
1161 | - 'ssl_chain': ssl_chain} |
1162 | - with open('hooks/templates/default-ssl.tmpl', 'r') as f: |
1163 | + template_values = { |
1164 | + "ssl_key": key_file, |
1165 | + "ssl_cert": cert_file, |
1166 | + "ssl_chain": ssl_chain, |
1167 | + } |
1168 | + with open("hooks/templates/default-ssl.tmpl", "r") as f: |
1169 | template_def = f.read() |
1170 | |
1171 | t = Template(template_def) |
1172 | - ssl_conf = '/etc/apache2/sites-available/default-ssl.conf' |
1173 | - with open(ssl_conf, 'w') as f: |
1174 | + ssl_conf = "/etc/apache2/sites-available/default-ssl.conf" |
1175 | + with open(ssl_conf, "w") as f: |
1176 | f.write(t.render(template_values)) |
1177 | |
1178 | # Create directory for extra *.include files installed by subordinates |
1179 | try: |
1180 | - os.makedirs('/etc/apache2/vhost.d/') |
1181 | + os.makedirs("/etc/apache2/vhost.d/") |
1182 | except OSError: |
1183 | pass |
1184 | |
1185 | @@ -501,20 +516,20 @@ def update_apache(): |
1186 | sites = glob.glob("/etc/apache2/sites-available/*.conf") |
1187 | non_ssl = set(sites) - {ssl_conf} |
1188 | for each in non_ssl: |
1189 | - site = os.path.basename(each).rsplit('.', 1)[0] |
1190 | + site = os.path.basename(each).rsplit(".", 1)[0] |
1191 | Apache2Site(site).action(enabled=HTTP_ENABLED) |
1192 | |
1193 | # Configure the behavior of https site |
1194 | Apache2Site("default-ssl").action(enabled=SSL_CONFIGURED) |
1195 | |
1196 | # Finally, restart apache2 |
1197 | - host.service_reload('apache2') |
1198 | + host.service_reload("apache2") |
1199 | |
1200 | |
1201 | class Apache2Site: |
1202 | def __init__(self, site): |
1203 | self.site = site |
1204 | - self.is_ssl = 'ssl' in site.lower() |
1205 | + self.is_ssl = "ssl" in site.lower() |
1206 | self.port = 443 if self.is_ssl else 80 |
1207 | |
1208 | def action(self, enabled): |
1209 | @@ -524,36 +539,40 @@ class Apache2Site: |
1210 | try: |
1211 | subprocess.check_output(args, stderr=subprocess.STDOUT) |
1212 | except subprocess.CalledProcessError as e: |
1213 | - hookenv.log("Apache2Site: `{}`, returned {}, stdout:\n{}" |
1214 | - .format(e.cmd, e.returncode, e.output), "ERROR") |
1215 | + hookenv.log( |
1216 | + "Apache2Site: `{}`, returned {}, stdout:\n{}".format( |
1217 | + e.cmd, e.returncode, e.output |
1218 | + ), |
1219 | + "ERROR", |
1220 | + ) |
1221 | |
1222 | def _enable(self): |
1223 | hookenv.log("Apache2Site: Enabling %s..." % self.site, "INFO") |
1224 | - self._call(['a2ensite', self.site]) |
1225 | + self._call(["a2ensite", self.site]) |
1226 | if self.port == 443: |
1227 | - self._call(['a2enmod', 'ssl']) |
1228 | + self._call(["a2enmod", "ssl"]) |
1229 | hookenv.open_port(self.port) |
1230 | |
1231 | def _disable(self): |
1232 | hookenv.log("Apache2Site: Disabling %s..." % self.site, "INFO") |
1233 | - self._call(['a2dissite', self.site]) |
1234 | + self._call(["a2dissite", self.site]) |
1235 | hookenv.close_port(self.port) |
1236 | |
1237 | |
1238 | def update_password(account, password): |
1239 | """Update the charm and Apache's record of the password for the supplied account.""" |
1240 | - account_file = ''.join(['/var/lib/juju/nagios.', account, '.passwd']) |
1241 | + account_file = "".join(["/var/lib/juju/nagios.", account, ".passwd"]) |
1242 | if password: |
1243 | - with open(account_file, 'w') as f: |
1244 | + with open(account_file, "w") as f: |
1245 | f.write(password) |
1246 | os.fchmod(f.fileno(), 0o0400) |
1247 | - subprocess.call(['htpasswd', '-b', '/etc/nagios3/htpasswd.users', |
1248 | - account, password]) |
1249 | + subprocess.call( |
1250 | + ["htpasswd", "-b", "/etc/nagios3/htpasswd.users", account, password] |
1251 | + ) |
1252 | else: |
1253 | """ password was empty, it has been removed. We should delete the account """ |
1254 | os.path.isfile(account_file) and os.remove(account_file) |
1255 | - subprocess.call(['htpasswd', '-D', '/etc/nagios3/htpasswd.users', |
1256 | - account]) |
1257 | + subprocess.call(["htpasswd", "-D", "/etc/nagios3/htpasswd.users", account]) |
1258 | |
1259 | |
1260 | warn_legacy_relations() |
1261 | @@ -571,12 +590,12 @@ update_apache() |
1262 | update_localhost() |
1263 | update_cgi_config() |
1264 | update_contacts() |
1265 | -update_password('nagiosro', ro_password) |
1266 | +update_password("nagiosro", ro_password) |
1267 | if password: |
1268 | update_password(nagiosadmin, password) |
1269 | -if nagiosadmin != 'nagiosadmin': |
1270 | - update_password('nagiosadmin', False) |
1271 | +if nagiosadmin != "nagiosadmin": |
1272 | + update_password("nagiosadmin", False) |
1273 | |
1274 | -subprocess.call(['scripts/postfix_loopback_only.sh']) |
1275 | -subprocess.call(['hooks/mymonitors-relation-joined']) |
1276 | -subprocess.call(['hooks/monitors-relation-changed']) |
1277 | +subprocess.call(["scripts/postfix_loopback_only.sh"]) |
1278 | +subprocess.call(["hooks/mymonitors-relation-joined"]) |
1279 | +subprocess.call(["hooks/monitors-relation-changed"]) |
1280 | diff --git a/hooks/website_relation_joined.py b/hooks/website_relation_joined.py |
1281 | index 984ae80..706a561 100755 |
1282 | --- a/hooks/website_relation_joined.py |
1283 | +++ b/hooks/website_relation_joined.py |
1284 | @@ -25,15 +25,15 @@ from charmhelpers.core.hookenv import ( |
1285 | |
1286 | |
1287 | def main(): |
1288 | - relation_data = {'hostname': common.get_local_ingress_address()} |
1289 | - sslcfg = config()['ssl'] |
1290 | - if sslcfg == 'only': |
1291 | - relation_data['port'] = 443 |
1292 | + relation_data = {"hostname": common.get_local_ingress_address()} |
1293 | + sslcfg = config()["ssl"] |
1294 | + if sslcfg == "only": |
1295 | + relation_data["port"] = 443 |
1296 | else: |
1297 | - relation_data['port'] = 80 |
1298 | - log('website-relation-joined data %s' % relation_data) |
1299 | + relation_data["port"] = 80 |
1300 | + log("website-relation-joined data %s" % relation_data) |
1301 | relation_set(None, **relation_data) |
1302 | |
1303 | |
1304 | -if __name__ == '__main__': # pragma: no cover |
1305 | +if __name__ == "__main__": # pragma: no cover |
1306 | main() |
1307 | diff --git a/tests/functional/conftest.py b/tests/functional/conftest.py |
1308 | index 484e3a4..a31034c 100644 |
1309 | --- a/tests/functional/conftest.py |
1310 | +++ b/tests/functional/conftest.py |
1311 | @@ -15,7 +15,7 @@ import pytest |
1312 | STAT_FILE = "python3 -c \"import json; import os; s=os.stat('%s'); print(json.dumps({'uid': s.st_uid, 'gid': s.st_gid, 'mode': oct(s.st_mode), 'size': s.st_size}))\"" # noqa: E501 |
1313 | |
1314 | |
1315 | -@pytest.yield_fixture(scope='session') |
1316 | +@pytest.yield_fixture(scope="session") |
1317 | def event_loop(request): |
1318 | """Override the default pytest event loop to allow for broaded scopedv fixtures.""" |
1319 | loop = asyncio.get_event_loop_policy().new_event_loop() |
1320 | @@ -26,7 +26,7 @@ def event_loop(request): |
1321 | asyncio.set_event_loop(None) |
1322 | |
1323 | |
1324 | -@pytest.fixture(scope='session') |
1325 | +@pytest.fixture(scope="session") |
1326 | async def controller(): |
1327 | """Connect to the current controller.""" |
1328 | controller = Controller() |
1329 | @@ -35,21 +35,21 @@ async def controller(): |
1330 | await controller.disconnect() |
1331 | |
1332 | |
1333 | -@pytest.fixture(scope='session') |
1334 | +@pytest.fixture(scope="session") |
1335 | async def model(controller): |
1336 | """Create a model that lives only for the duration of the test.""" |
1337 | model_name = "functest-{}".format(uuid.uuid4()) |
1338 | model = await controller.add_model(model_name) |
1339 | yield model |
1340 | await model.disconnect() |
1341 | - if os.getenv('PYTEST_KEEP_MODEL'): |
1342 | + if os.getenv("PYTEST_KEEP_MODEL"): |
1343 | return |
1344 | await controller.destroy_model(model_name) |
1345 | while model_name in await controller.list_models(): |
1346 | await asyncio.sleep(1) |
1347 | |
1348 | |
1349 | -@pytest.fixture(scope='session') |
1350 | +@pytest.fixture(scope="session") |
1351 | async def current_model(): |
1352 | """Return the current model, does not create or destroy it.""" |
1353 | model = Model() |
1354 | @@ -61,29 +61,34 @@ async def current_model(): |
1355 | @pytest.fixture |
1356 | async def get_app(model): |
1357 | """Return the application requested.""" |
1358 | + |
1359 | async def _get_app(name): |
1360 | try: |
1361 | return model.applications[name] |
1362 | except KeyError: |
1363 | raise JujuError("Cannot find application {}".format(name)) |
1364 | + |
1365 | return _get_app |
1366 | |
1367 | |
1368 | @pytest.fixture |
1369 | async def get_unit(model): |
1370 | """Return the requested <app_name>/<unit_number> unit.""" |
1371 | + |
1372 | async def _get_unit(name): |
1373 | try: |
1374 | - (app_name, unit_number) = name.split('/') |
1375 | + (app_name, unit_number) = name.split("/") |
1376 | return model.applications[app_name].units[unit_number] |
1377 | except (KeyError, ValueError): |
1378 | raise JujuError("Cannot find unit {}".format(name)) |
1379 | + |
1380 | return _get_unit |
1381 | |
1382 | |
1383 | @pytest.fixture |
1384 | async def get_entity(model, get_unit, get_app): |
1385 | """Return a unit or an application.""" |
1386 | + |
1387 | async def _get_entity(name): |
1388 | try: |
1389 | return await get_unit(name) |
1390 | @@ -92,12 +97,14 @@ async def get_entity(model, get_unit, get_app): |
1391 | return await get_app(name) |
1392 | except JujuError: |
1393 | raise JujuError("Cannot find entity {}".format(name)) |
1394 | + |
1395 | return _get_entity |
1396 | |
1397 | |
1398 | @pytest.fixture |
1399 | async def run_command(get_unit): |
1400 | """Run a command on a unit.""" |
1401 | + |
1402 | async def _run_command(cmd, target): |
1403 | """ |
1404 | Run a command on a unit. |
1405 | @@ -105,13 +112,10 @@ async def run_command(get_unit): |
1406 | :param cmd: Command to be run |
1407 | :param target: Unit object or unit name string |
1408 | """ |
1409 | - unit = ( |
1410 | - target |
1411 | - if type(target) is juju.unit.Unit |
1412 | - else await get_unit(target) |
1413 | - ) |
1414 | + unit = target if type(target) is juju.unit.Unit else await get_unit(target) |
1415 | action = await unit.run(cmd) |
1416 | return action.results |
1417 | + |
1418 | return _run_command |
1419 | |
1420 | |
1421 | @@ -123,31 +127,36 @@ async def file_stat(run_command): |
1422 | :param path: File path |
1423 | :param target: Unit object or unit name string |
1424 | """ |
1425 | + |
1426 | async def _file_stat(path, target): |
1427 | cmd = STAT_FILE % path |
1428 | results = await run_command(cmd, target) |
1429 | - return json.loads(results['Stdout']) |
1430 | + return json.loads(results["Stdout"]) |
1431 | + |
1432 | return _file_stat |
1433 | |
1434 | |
1435 | @pytest.fixture |
1436 | async def file_contents(run_command): |
1437 | """Return the contents of a file.""" |
1438 | + |
1439 | async def _file_contents(path, target): |
1440 | """Return the contents of a file. |
1441 | |
1442 | :param path: File path |
1443 | :param target: Unit object or unit name string |
1444 | """ |
1445 | - cmd = 'cat {}'.format(path) |
1446 | + cmd = "cat {}".format(path) |
1447 | results = await run_command(cmd, target) |
1448 | - return results['Stdout'] |
1449 | + return results["Stdout"] |
1450 | + |
1451 | return _file_contents |
1452 | |
1453 | |
1454 | @pytest.fixture |
1455 | async def reconfigure_app(get_app, model): |
1456 | """Apply a different config to the requested app.""" |
1457 | + |
1458 | async def _reconfigure_app(cfg, target): |
1459 | application = ( |
1460 | target |
1461 | @@ -156,16 +165,19 @@ async def reconfigure_app(get_app, model): |
1462 | ) |
1463 | await application.set_config(cfg) |
1464 | await application.get_config() |
1465 | - await model.block_until(lambda: application.status == 'active') |
1466 | + await model.block_until(lambda: application.status == "active") |
1467 | + |
1468 | return _reconfigure_app |
1469 | |
1470 | |
1471 | @pytest.fixture |
1472 | async def create_group(run_command): |
1473 | """Create the UNIX group specified.""" |
1474 | + |
1475 | async def _create_group(group_name, target): |
1476 | cmd = "sudo groupadd %s" % group_name |
1477 | await run_command(cmd, target) |
1478 | + |
1479 | return _create_group |
1480 | |
1481 | |
1482 | @@ -183,20 +195,18 @@ SERIES = [ |
1483 | ############ |
1484 | # FIXTURES # |
1485 | ############ |
1486 | -@pytest.fixture(scope='session', params=SERIES) |
1487 | +@pytest.fixture(scope="session", params=SERIES) |
1488 | def series(request): |
1489 | """Return ubuntu version (i.e. xenial) in use in the test.""" |
1490 | return request.param |
1491 | |
1492 | |
1493 | -@pytest.fixture(scope='session') |
1494 | +@pytest.fixture(scope="session") |
1495 | async def relatives(model, series): |
1496 | nrpe = "nrpe" |
1497 | nrpe_name = "nrpe-{}".format(series) |
1498 | nrpe_app = await model.deploy( |
1499 | - 'cs:' + nrpe, application_name=nrpe_name, |
1500 | - series=series, config={}, |
1501 | - num_units=0 |
1502 | + "cs:" + nrpe, application_name=nrpe_name, series=series, config={}, num_units=0 |
1503 | ) |
1504 | |
1505 | mysql = "mysql" |
1506 | @@ -205,50 +215,52 @@ async def relatives(model, series): |
1507 | |
1508 | mysql_name = "mysql-{}".format(series) |
1509 | mysql_app = await model.deploy( |
1510 | - 'cs:' + mysql, application_name=mysql_name, |
1511 | - series=series, config={} |
1512 | + "cs:" + mysql, application_name=mysql_name, series=series, config={} |
1513 | ) |
1514 | |
1515 | - await model.add_relation('{}:nrpe-external-master'.format(mysql_name), |
1516 | - '{}:nrpe-external-master'.format(nrpe_name)) |
1517 | + await model.add_relation( |
1518 | + "{}:nrpe-external-master".format(mysql_name), |
1519 | + "{}:nrpe-external-master".format(nrpe_name), |
1520 | + ) |
1521 | await model.block_until( |
1522 | - lambda: mysql_app.units[0].workload_status == "active" and |
1523 | - mysql_app.units[0].agent_status == "idle" |
1524 | + lambda: mysql_app.units[0].workload_status == "active" |
1525 | + and mysql_app.units[0].agent_status == "idle" |
1526 | ) |
1527 | |
1528 | yield { |
1529 | "mysql": {"name": mysql_name, "app": mysql_app}, |
1530 | - "nrpe": {"name": nrpe_name, "app": nrpe_app} |
1531 | + "nrpe": {"name": nrpe_name, "app": nrpe_app}, |
1532 | } |
1533 | |
1534 | |
1535 | -@pytest.fixture(scope='session') |
1536 | +@pytest.fixture(scope="session") |
1537 | async def deploy_app(relatives, model, series): |
1538 | """Return application of the charm under test.""" |
1539 | app_name = "nagios-{}".format(series) |
1540 | |
1541 | """Deploy the nagios app.""" |
1542 | nagios_app = await model.deploy( |
1543 | - os.path.join(CHARM_BUILD_DIR, 'nagios'), |
1544 | + os.path.join(CHARM_BUILD_DIR, "nagios"), |
1545 | application_name=app_name, |
1546 | series=series, |
1547 | config={ |
1548 | - 'enable_livestatus': False, |
1549 | - 'ssl': 'off', |
1550 | - 'extraconfig': '', |
1551 | - 'enable_pagerduty': False |
1552 | - } |
1553 | + "enable_livestatus": False, |
1554 | + "ssl": "off", |
1555 | + "extraconfig": "", |
1556 | + "enable_pagerduty": False, |
1557 | + }, |
1558 | ) |
1559 | |
1560 | - await model.add_relation('{}:monitors'.format(relatives["nrpe"]["name"]), |
1561 | - '{}:monitors'.format(app_name)) |
1562 | + await model.add_relation( |
1563 | + "{}:monitors".format(relatives["nrpe"]["name"]), "{}:monitors".format(app_name) |
1564 | + ) |
1565 | await model.block_until( |
1566 | - lambda: nagios_app.units[0].agent_status == "idle" and |
1567 | - relatives["mysql"]["app"].units[0].agent_status == "idle" |
1568 | + lambda: nagios_app.units[0].agent_status == "idle" |
1569 | + and relatives["mysql"]["app"].units[0].agent_status == "idle" |
1570 | ) |
1571 | |
1572 | yield nagios_app |
1573 | - if os.getenv('PYTEST_KEEP_MODEL'): |
1574 | + if os.getenv("PYTEST_KEEP_MODEL"): |
1575 | return |
1576 | |
1577 | for relative in list(relatives.values()): |
1578 | @@ -270,8 +282,9 @@ class Agent: |
1579 | async def block_until_or_timeout(self, lambda_f, **kwargs): |
1580 | await self.block_until(lambda_f, ignore_timeout=True, **kwargs) |
1581 | |
1582 | - async def block_until(self, lambda_f, timeout=120, wait_period=5, |
1583 | - ignore_timeout=False): |
1584 | + async def block_until( |
1585 | + self, lambda_f, timeout=120, wait_period=5, ignore_timeout=False |
1586 | + ): |
1587 | try: |
1588 | await self.model.block_until( |
1589 | lambda_f, timeout=timeout, wait_period=wait_period |
1590 | @@ -285,7 +298,7 @@ class Agent: |
1591 | async def unit(model, deploy_app): |
1592 | """Return the unit we've deployed.""" |
1593 | unit = Agent(deploy_app.units[0], deploy_app) |
1594 | - await unit.block_until(lambda: unit.is_active('idle')) |
1595 | + await unit.block_until(lambda: unit.is_active("idle")) |
1596 | return unit |
1597 | |
1598 | |
1599 | @@ -293,4 +306,4 @@ async def unit(model, deploy_app): |
1600 | async def auth(file_contents, unit): |
1601 | """Return the basic auth credentials.""" |
1602 | nagiospwd = await file_contents("/var/lib/juju/nagios.passwd", unit.u) |
1603 | - return 'nagiosadmin', nagiospwd.strip() |
1604 | + return "nagiosadmin", nagiospwd.strip() |
1605 | diff --git a/tests/functional/test_config.py b/tests/functional/test_config.py |
1606 | index b64f8a6..1b9310a 100644 |
1607 | --- a/tests/functional/test_config.py |
1608 | +++ b/tests/functional/test_config.py |
1609 | @@ -1,25 +1,22 @@ |
1610 | from async_generator import asynccontextmanager |
1611 | import pytest |
1612 | import requests |
1613 | + |
1614 | pytestmark = pytest.mark.asyncio |
1615 | |
1616 | |
1617 | @asynccontextmanager |
1618 | async def config(unit, item, test_value, post_test): |
1619 | await unit.application.set_config({item: test_value}) |
1620 | - await unit.block_until_or_timeout( |
1621 | - lambda: unit.is_active('executing'), timeout=5, |
1622 | - ) |
1623 | - await unit.block_until(lambda: unit.is_active('idle')) |
1624 | + await unit.block_until_or_timeout(lambda: unit.is_active("executing"), timeout=5) |
1625 | + await unit.block_until(lambda: unit.is_active("idle")) |
1626 | yield test_value |
1627 | await unit.application.set_config({item: post_test}) |
1628 | - await unit.block_until_or_timeout( |
1629 | - lambda: unit.is_active('executing'), timeout=5, |
1630 | - ) |
1631 | - await unit.block_until(lambda: unit.is_active('idle')) |
1632 | + await unit.block_until_or_timeout(lambda: unit.is_active("executing"), timeout=5) |
1633 | + await unit.block_until(lambda: unit.is_active("idle")) |
1634 | |
1635 | |
1636 | -@pytest.fixture(params=['on', 'only']) |
1637 | +@pytest.fixture(params=["on", "only"]) |
1638 | async def ssl(unit, request): |
1639 | """ |
1640 | Enable SSL before a test, then disable after test |
1641 | @@ -27,7 +24,7 @@ async def ssl(unit, request): |
1642 | :param Agent unit: unit from the fixture |
1643 | :param request: test parameters |
1644 | """ |
1645 | - async with config(unit, 'ssl', request.param, 'off') as value: |
1646 | + async with config(unit, "ssl", request.param, "off") as value: |
1647 | yield value |
1648 | |
1649 | |
1650 | @@ -58,7 +55,7 @@ async def livestatus_path(unit): |
1651 | """ |
1652 | async with config(unit, "enable_livestatus", "true", "false"): |
1653 | app_config = await unit.application.get_config() |
1654 | - yield app_config['livestatus_path']['value'] |
1655 | + yield app_config["livestatus_path"]["value"] |
1656 | |
1657 | |
1658 | @pytest.fixture() |
1659 | @@ -70,20 +67,24 @@ async def enable_pagerduty(unit): |
1660 | """ |
1661 | async with config(unit, "enable_pagerduty", "true", "false"): |
1662 | app_config = await unit.application.get_config() |
1663 | - yield app_config['pagerduty_path']['value'] |
1664 | + yield app_config["pagerduty_path"]["value"] |
1665 | + |
1666 | |
1667 | @pytest.fixture |
1668 | async def set_extra_contacts(unit): |
1669 | """Set extra contacts.""" |
1670 | name = "contact_name_1" |
1671 | - extra_contacts = ''' |
1672 | + extra_contacts = """ |
1673 | - name: {} |
1674 | host: /custom/command/for/host $HOSTNAME$ |
1675 | service: /custom/command/for/service $SERVICENAME$ |
1676 | - '''.format(name) |
1677 | + """.format( |
1678 | + name |
1679 | + ) |
1680 | async with config(unit, "extra_contacts", extra_contacts, ""): |
1681 | yield name |
1682 | |
1683 | + |
1684 | @pytest.fixture |
1685 | async def set_multiple_admins(unit): |
1686 | admins = "admin1@localhost,admin2@localhost" |
1687 | @@ -96,7 +97,7 @@ async def set_multiple_admins(unit): |
1688 | ######### |
1689 | async def test_web_interface_with_ssl(auth, unit, ssl): |
1690 | http_url = "http://%s/nagios3/" % unit.u.public_address |
1691 | - if ssl == 'only': |
1692 | + if ssl == "only": |
1693 | with pytest.raises(requests.ConnectionError): |
1694 | requests.get(http_url, auth=auth) |
1695 | else: |
1696 | @@ -108,57 +109,61 @@ async def test_web_interface_with_ssl(auth, unit, ssl): |
1697 | assert r.status_code == 200, "HTTPs Admin login failed" |
1698 | |
1699 | |
1700 | -@pytest.mark.usefixtures('extra_config') |
1701 | +@pytest.mark.usefixtures("extra_config") |
1702 | async def test_extra_config(auth, unit): |
1703 | - host_url = "http://%s/cgi-bin/nagios3/status.cgi?" \ |
1704 | - "hostgroup=all&style=hostdetail" % unit.u.public_address |
1705 | + host_url = ( |
1706 | + "http://%s/cgi-bin/nagios3/status.cgi?" |
1707 | + "hostgroup=all&style=hostdetail" % unit.u.public_address |
1708 | + ) |
1709 | r = requests.get(host_url, auth=auth) |
1710 | - assert 'extra_config' in r.text, "Nagios is not monitoring extra_config" |
1711 | + assert "extra_config" in r.text, "Nagios is not monitoring extra_config" |
1712 | |
1713 | |
1714 | async def test_live_status(unit, livestatus_path, file_stat): |
1715 | stat = await file_stat(livestatus_path, unit.u) |
1716 | - assert stat['size'] == 0, ( |
1717 | - "File %s didn't match expected size" % livestatus_path |
1718 | - ) |
1719 | + assert stat["size"] == 0, "File %s didn't match expected size" % livestatus_path |
1720 | |
1721 | |
1722 | async def test_pager_duty(unit, enable_pagerduty, file_stat): |
1723 | stat = await file_stat(enable_pagerduty, unit.u) |
1724 | - assert stat['size'] != 0, ( |
1725 | - "Directory %s wasn't a non-zero size" % enable_pagerduty |
1726 | - ) |
1727 | - stat = await file_stat('/etc/nagios3/conf.d/pagerduty_nagios.cfg', unit.u) |
1728 | - assert stat['size'] != 0, "pagerduty_config wasn't a non-zero sized file" |
1729 | + assert stat["size"] != 0, "Directory %s wasn't a non-zero size" % enable_pagerduty |
1730 | + stat = await file_stat("/etc/nagios3/conf.d/pagerduty_nagios.cfg", unit.u) |
1731 | + assert stat["size"] != 0, "pagerduty_config wasn't a non-zero sized file" |
1732 | |
1733 | |
1734 | async def test_extra_contacts(auth, unit, set_extra_contacts): |
1735 | - contancts_url = "http://%s/cgi-bin/nagios3/config.cgi?" \ |
1736 | - "type=contacts" % unit.u.public_address |
1737 | + contancts_url = ( |
1738 | + "http://%s/cgi-bin/nagios3/config.cgi?type=contacts" % unit.u.public_address |
1739 | + ) |
1740 | contact_name = set_extra_contacts |
1741 | r = requests.get(contancts_url, auth=auth) |
1742 | assert r.status_code == 200, "Get Nagios config request failed" |
1743 | assert contact_name in r.text, "Nagios is not loading the extra contact." |
1744 | - assert contact_name.capitalize() in r.text, "Contact name alias is not " \ |
1745 | - "the capitalized name." |
1746 | - contactgroups_url = "http://%s/cgi-bin/nagios3/config.cgi" \ |
1747 | - "?type=contactgroups" % unit.u.public_address |
1748 | + assert ( |
1749 | + contact_name.capitalize() in r.text |
1750 | + ), "Contact name alias is not the capitalized name." |
1751 | + contactgroups_url = ( |
1752 | + "http://%s/cgi-bin/nagios3/config.cgi" |
1753 | + "?type=contactgroups" % unit.u.public_address |
1754 | + ) |
1755 | |
1756 | r = requests.get(contactgroups_url, auth=auth) |
1757 | assert r.status_code == 200, "Get Nagios config request failed" |
1758 | - assert contact_name in r.text, "Extra contact is not " \ |
1759 | - "added to the contact groups." |
1760 | + assert contact_name in r.text, "Extra contact is not added to the contact groups." |
1761 | + |
1762 | |
1763 | async def test_multiple_admin_contacts(auth, unit, set_multiple_admins): |
1764 | - contancts_url = "http://%s/cgi-bin/nagios3/config.cgi?" \ |
1765 | - "type=contacts" % unit.u.public_address |
1766 | + contancts_url = ( |
1767 | + "http://%s/cgi-bin/nagios3/config.cgi?type=contacts" % unit.u.public_address |
1768 | + ) |
1769 | admins = set_multiple_admins |
1770 | r = requests.get(contancts_url, auth=auth) |
1771 | assert r.status_code == 200, "Get Nagios config request failed" |
1772 | - admins = admins.split(',') |
1773 | + admins = admins.split(",") |
1774 | for admin in admins: |
1775 | - admin = admin.replace('@', '').replace('.', '').lower() |
1776 | + admin = admin.replace("@", "").replace(".", "").lower() |
1777 | admin_alias = admin.capitalize() |
1778 | assert admin in r.text, "Nagios is not loading contact {}.".format(admin) |
1779 | - assert admin_alias in r.text, "Nagios is not loading alias " \ |
1780 | - "for contact {}.".format(admin) |
1781 | + assert ( |
1782 | + admin_alias in r.text |
1783 | + ), "Nagios is not loading alias for contact {}.".format(admin) |
1784 | diff --git a/tests/functional/test_deploy.py b/tests/functional/test_deploy.py |
1785 | index b8e9f40..32503c2 100644 |
1786 | --- a/tests/functional/test_deploy.py |
1787 | +++ b/tests/functional/test_deploy.py |
1788 | @@ -1,5 +1,6 @@ |
1789 | import pytest |
1790 | import requests |
1791 | + |
1792 | pytestmark = pytest.mark.asyncio |
1793 | |
1794 | |
1795 | @@ -22,17 +23,15 @@ async def test_web_interface_is_protected(auth, unit): |
1796 | |
1797 | |
1798 | async def test_hosts_being_monitored(auth, unit): |
1799 | - host_url = ("http://%s/cgi-bin/nagios3/status.cgi?" |
1800 | - "hostgroup=all&style=hostdetail") % unit.u.public_address |
1801 | + host_url = ( |
1802 | + "http://%s/cgi-bin/nagios3/status.cgi?hostgroup=all&style=hostdetail" |
1803 | + ) % unit.u.public_address |
1804 | r = requests.get(host_url, auth=auth) |
1805 | - assert 'mysql' in r.text, "Nagios is not monitoring the hosts it supposed to." |
1806 | + assert "mysql" in r.text, "Nagios is not monitoring the hosts it supposed to." |
1807 | |
1808 | |
1809 | async def test_nrpe_monitors_config(relatives, unit, file_contents): |
1810 | # look for disk root check in nrpe config |
1811 | - mysql_unit = relatives['mysql']['app'].units[0] |
1812 | - contents = await file_contents( |
1813 | - '/etc/nagios/nrpe.d/check_disk_root.cfg', |
1814 | - mysql_unit |
1815 | - ) |
1816 | + mysql_unit = relatives["mysql"]["app"].units[0] |
1817 | + contents = await file_contents("/etc/nagios/nrpe.d/check_disk_root.cfg", mysql_unit) |
1818 | assert contents, "disk root check config not found." |
1819 | diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py |
1820 | index f6fceac..0c6a597 100644 |
1821 | --- a/tests/unit/conftest.py |
1822 | +++ b/tests/unit/conftest.py |
1823 | @@ -1,5 +1,5 @@ |
1824 | import os |
1825 | import sys |
1826 | |
1827 | -HOOKS = os.path.join(os.path.dirname(__file__), '..', '..', 'hooks') |
1828 | +HOOKS = os.path.join(os.path.dirname(__file__), "..", "..", "hooks") |
1829 | sys.path.append(HOOKS) |
1830 | diff --git a/tests/unit/test_monitor_relation_changed.py b/tests/unit/test_monitor_relation_changed.py |
1831 | index 3a7f5d6..f2f0e1d 100644 |
1832 | --- a/tests/unit/test_monitor_relation_changed.py |
1833 | +++ b/tests/unit/test_monitor_relation_changed.py |
1834 | @@ -4,4 +4,4 @@ import monitors_relation_changed |
1835 | def test_has_main(): |
1836 | # THIS IS A REALLY LAME TEST -- but it's a start for where there was nothing |
1837 | # if you add tests later, please do better than me |
1838 | - assert hasattr(monitors_relation_changed, 'main') |
1839 | + assert hasattr(monitors_relation_changed, "main") |
1840 | diff --git a/tests/unit/test_website_relation_joined.py b/tests/unit/test_website_relation_joined.py |
1841 | index 3164428..b4ca91a 100644 |
1842 | --- a/tests/unit/test_website_relation_joined.py |
1843 | +++ b/tests/unit/test_website_relation_joined.py |
1844 | @@ -4,16 +4,16 @@ import pytest |
1845 | import website_relation_joined |
1846 | |
1847 | |
1848 | -@mock.patch('common.get_local_ingress_address') |
1849 | -@mock.patch('website_relation_joined.config') |
1850 | -@mock.patch('website_relation_joined.relation_set') |
1851 | -@pytest.mark.parametrize('ssl', [ |
1852 | - ('only', 443), |
1853 | - ('on', 80), |
1854 | - ('off', 80) |
1855 | -], ids=['ssl=only', 'ssl=on', 'ssl=off']) |
1856 | +@mock.patch("common.get_local_ingress_address") |
1857 | +@mock.patch("website_relation_joined.config") |
1858 | +@mock.patch("website_relation_joined.relation_set") |
1859 | +@pytest.mark.parametrize( |
1860 | + "ssl", |
1861 | + [("only", 443), ("on", 80), ("off", 80)], |
1862 | + ids=["ssl=only", "ssl=on", "ssl=off"], |
1863 | +) |
1864 | def test_main(relation_set, config, get_local_ingress_address, ssl): |
1865 | - get_local_ingress_address.return_value = 'example.com' |
1866 | - config.return_value = {'ssl': ssl[0]} |
1867 | + get_local_ingress_address.return_value = "example.com" |
1868 | + config.return_value = {"ssl": ssl[0]} |
1869 | website_relation_joined.main() |
1870 | - relation_set.assert_called_with(None, port=ssl[1], hostname='example.com') |
1871 | + relation_set.assert_called_with(None, port=ssl[1], hostname="example.com") |
1872 | diff --git a/tox.ini b/tox.ini |
1873 | index a98700a..8f1b11b 100644 |
1874 | --- a/tox.ini |
1875 | +++ b/tox.ini |
1876 | @@ -25,7 +25,7 @@ passenv = |
1877 | [testenv:lint] |
1878 | commands = |
1879 | flake8 |
1880 | -# TODO black --check --exclude "/(\.eggs|\.git|\.tox|\.venv|\.build|dist|charmhelpers|mod|bin)/" . |
1881 | + black --check --exclude "/(\.eggs|\.git|\.tox|\.venv|\.build|dist|charmhelpers|mod|bin)/" . |
1882 | deps = |
1883 | black |
1884 | flake8 |
1885 | @@ -59,6 +59,7 @@ ignore = # TODO remove most of these |
1886 | I100, |
1887 | I101, |
1888 | I201, |
1889 | + I202, |
1890 | E201, |
1891 | E202, |
1892 | E231, |
1893 | @@ -70,6 +71,7 @@ ignore = # TODO remove most of these |
1894 | E501, |
1895 | N806, |
1896 | N816, |
1897 | + W503, |
1898 | W504 |
1899 | |
1900 |
a number of black concatenated line strings still hanging out. see inline comments for locations.