Merge lp:~1chb1n/charms/trusty/ubuntu/simplify-and-test into lp:charms/trusty/ubuntu
- Trusty Tahr (14.04)
- simplify-and-test
- Merge into trunk
Status: | Merged |
---|---|
Merged at revision: | 11 |
Proposed branch: | lp:~1chb1n/charms/trusty/ubuntu/simplify-and-test |
Merge into: | lp:charms/trusty/ubuntu |
Diff against target: |
4371 lines (+655/-3480) 41 files modified
Makefile (+57/-0) README.md (+5/-21) charm-helpers-hooks.yaml (+0/-5) charm-helpers-tests.yaml (+4/-0) config.yaml (+0/-8) files/bundle-example.yaml (+14/-0) hooks/charmhelpers/core/__init__.py (+0/-15) hooks/charmhelpers/core/decorators.py (+0/-57) hooks/charmhelpers/core/fstab.py (+0/-134) hooks/charmhelpers/core/hookenv.py (+0/-568) hooks/charmhelpers/core/host.py (+0/-446) hooks/charmhelpers/core/services/__init__.py (+0/-18) hooks/charmhelpers/core/services/base.py (+0/-329) hooks/charmhelpers/core/services/helpers.py (+0/-259) hooks/charmhelpers/core/strutils.py (+0/-42) hooks/charmhelpers/core/sysctl.py (+0/-56) hooks/charmhelpers/core/templating.py (+0/-68) hooks/charmhelpers/core/unitdata.py (+0/-477) hooks/charmhelpers/fetch/__init__.py (+0/-439) hooks/charmhelpers/fetch/archiveurl.py (+0/-161) hooks/charmhelpers/fetch/bzrurl.py (+0/-78) hooks/charmhelpers/fetch/giturl.py (+0/-71) hooks/config-changed (+0/-43) hooks/hooks.py (+0/-45) hooks/install (+0/-2) hooks/utils.py (+0/-27) metadata.yaml (+1/-1) templates/lxc-bridge.conf (+0/-10) tests/00-setup.sh (+4/-10) tests/010_basic_precise (+7/-0) tests/015_basic_trusty (+7/-0) tests/020_basic_utopic (+7/-0) tests/025_basic_vivid (+7/-0) tests/10-deploy-test.py (+0/-90) tests/basic_deployment.py (+49/-0) tests/charmhelpers/__init__.py (+38/-0) tests/charmhelpers/contrib/__init__.py (+15/-0) tests/charmhelpers/contrib/amulet/__init__.py (+15/-0) tests/charmhelpers/contrib/amulet/deployment.py (+93/-0) tests/charmhelpers/contrib/amulet/utils.py (+323/-0) tests/tests.yaml (+9/-0) |
To merge this branch: | bzr merge lp:~1chb1n/charms/trusty/ubuntu/simplify-and-test |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Tim Van Steenburgh (community) | Approve | ||
Review via email: mp+257773@code.launchpad.net |
Commit message
Revert charm to have no hooks and no config options; add functional tests for all currently-supported Ubuntu releases; add bundletester usage examples.
Charm is now compatible with both 'juju test' and bundletester.
Description of the change
Revert charm to have no hooks and no config options; add functional tests for all currently-supported Ubuntu releases; add bundletester usage examples.
Charm is now compatible with both 'juju test' and bundletester.
Ryan Beisner (1chb1n) wrote : | # |
Marco Ceppi (marcoceppi) wrote : | # |
See below
Ryan Beisner (1chb1n) wrote : | # |
Thank you for the review. The bundle file is an example which won't be exercised in automation unless explicitly called. It accompanies the bundletester usage examples in the Makefile, which a user or charmer can optionally fire.
The juju-gui is present as a general use example, and as a handy way to fire up the most basic juju canvas. I think the Ubuntu charm is a good place for that, as well as these other usage examples which encourage easily adding functional test coverage. ;-)
To clarify, this MP aims to address 3 things:
1) Return the charm to a functional state on all supported releases.
2) Add test coverage for all supported releases, detect future breakage re: bug 1447765.
3) Add bundletester usage examples since we don't have that in one place anywhere else.
Tim Van Steenburgh (tvansteenburgh) wrote : | # |
+1 LGTM, thanks Ryan.
Preview Diff
1 | === added file 'Makefile' | |||
2 | --- Makefile 1970-01-01 00:00:00 +0000 | |||
3 | +++ Makefile 2015-04-30 13:14:23 +0000 | |||
4 | @@ -0,0 +1,57 @@ | |||
5 | 1 | #!/usr/bin/make | ||
6 | 2 | PYTHON := /usr/bin/env python | ||
7 | 3 | |||
8 | 4 | virtualenv: | ||
9 | 5 | @echo Setting up python virtual env... | ||
10 | 6 | virtualenv .venv | ||
11 | 7 | .venv/bin/pip install flake8 charm-tools bundletester | ||
12 | 8 | |||
13 | 9 | lint: virtualenv | ||
14 | 10 | @echo Lint inspections and charm proof... | ||
15 | 11 | .venv/bin/flake8 --exclude hooks/charmhelpers tests | ||
16 | 12 | .venv/bin/charm proof | ||
17 | 13 | |||
18 | 14 | test: virtualenv | ||
19 | 15 | @echo No unit tests defined. This is an example placeholder. | ||
20 | 16 | |||
21 | 17 | functional_test: virtualenv | ||
22 | 18 | # Consume ./tests/tests.yaml to determine the tests to run, | ||
23 | 19 | # in addition to functional tests in the ./tests dir. | ||
24 | 20 | @echo Starting functional, lint and unit tests... | ||
25 | 21 | .venv/bin/bundletester -v -F -l DEBUG -r dot -o results-all.dot | ||
26 | 22 | |||
27 | 23 | test_example: virtualenv | ||
28 | 24 | # A bundletester usage example to run only the matching tests. | ||
29 | 25 | @echo Starting a subset of tests... | ||
30 | 26 | .venv/bin/bundletester -v -F -l DEBUG -r json -o results-ex.json \ | ||
31 | 27 | --test-pattern 02* | ||
32 | 28 | |||
33 | 29 | test_example2: virtualenv | ||
34 | 30 | # A bundletester usage example to run only the specified tests, | ||
35 | 31 | # with a different output format. | ||
36 | 32 | @echo Starting a subset of tests... | ||
37 | 33 | .venv/bin/bundletester -v -F -l DEBUG -r spec -o results-ex2.spec \ | ||
38 | 34 | 010_basic_precise 015_basic_trusty | ||
39 | 35 | |||
40 | 36 | test_example3: virtualenv | ||
41 | 37 | # A bundletester bundle usage example. | ||
42 | 38 | @echo Starting a subset of tests... | ||
43 | 39 | .venv/bin/bundletester -v -F -l DEBUG -r dot -o results-ex3.dot \ | ||
44 | 40 | -b files/bundle-example.yaml | ||
45 | 41 | |||
46 | 42 | bin/charm_helpers_sync.py: | ||
47 | 43 | @mkdir -p bin | ||
48 | 44 | @bzr cat lp:charm-helpers/tools/charm_helpers_sync/charm_helpers_sync.py \ | ||
49 | 45 | > bin/charm_helpers_sync.py | ||
50 | 46 | |||
51 | 47 | sync: bin/charm_helpers_sync.py | ||
52 | 48 | @echo Syncing charm helpers for functional tests... | ||
53 | 49 | @$(PYTHON) bin/charm_helpers_sync.py -c charm-helpers-tests.yaml | ||
54 | 50 | |||
55 | 51 | publish: clean lint | ||
56 | 52 | bzr push lp:charms/trusty/ubuntu | ||
57 | 53 | |||
58 | 54 | clean: | ||
59 | 55 | @ echo Cleaning up venvs and pyc files... | ||
60 | 56 | rm -rf .venv | ||
61 | 57 | find -name *.pyc -delete | ||
62 | 0 | 58 | ||
63 | === modified file 'README.md' | |||
64 | --- README.md 2015-03-25 19:59:09 +0000 | |||
65 | +++ README.md 2015-04-30 13:14:23 +0000 | |||
66 | @@ -25,32 +25,16 @@ | |||
67 | 25 | juju deploy ubuntu mytestmachine1 | 25 | juju deploy ubuntu mytestmachine1 |
68 | 26 | juju deploy ubuntu mytestmachine2 | 26 | juju deploy ubuntu mytestmachine2 |
69 | 27 | 27 | ||
91 | 28 | and so on. | 28 | and so on. |
71 | 29 | |||
72 | 30 | # Configuration | ||
73 | 31 | |||
74 | 32 | A configuration option to create a new network for LXC containers is provided via a boolean config option, 'new-lxc-network.' | ||
75 | 33 | The default is set to false indicating the same network of the node will also be used for LXC containers. | ||
76 | 34 | |||
77 | 35 | To use a new network for LXC containers post juju deploy, issue: | ||
78 | 36 | |||
79 | 37 | juju set ubuntu new-lxc-network=true | ||
80 | 38 | |||
81 | 39 | If you want to have a new network for LXC containers on deploy set up a lxc-config.yaml: | ||
82 | 40 | |||
83 | 41 | ubuntu: | ||
84 | 42 | new-lxc-network: true | ||
85 | 43 | |||
86 | 44 | and pass that as an arugment to deploy: | ||
87 | 45 | |||
88 | 46 | juju deploy --config lxc-config.yaml ubuntu | ||
89 | 47 | |||
90 | 48 | For further information on setting configuration with Juju see https://jujucharms.com/docs/latest/charms-config | ||
92 | 49 | 29 | ||
93 | 50 | ## Known Limitations and Issues | 30 | ## Known Limitations and Issues |
94 | 51 | 31 | ||
95 | 52 | This charm does not provide anything other than a blank server, so it does not relate to other charms. | 32 | This charm does not provide anything other than a blank server, so it does not relate to other charms. |
96 | 53 | 33 | ||
97 | 34 | # Configuration | ||
98 | 35 | |||
99 | 36 | This charm has no configuration options. | ||
100 | 37 | |||
101 | 54 | # Contact Information | 38 | # Contact Information |
102 | 55 | 39 | ||
103 | 56 | 40 | ||
104 | 57 | 41 | ||
105 | === removed file 'charm-helpers-hooks.yaml' | |||
106 | --- charm-helpers-hooks.yaml 2015-02-19 16:21:31 +0000 | |||
107 | +++ charm-helpers-hooks.yaml 1970-01-01 00:00:00 +0000 | |||
108 | @@ -1,5 +0,0 @@ | |||
109 | 1 | branch: lp:charm-helpers | ||
110 | 2 | destination: hooks/charmhelpers | ||
111 | 3 | include: | ||
112 | 4 | - core | ||
113 | 5 | - fetch | ||
114 | 6 | 0 | ||
115 | === added file 'charm-helpers-tests.yaml' | |||
116 | --- charm-helpers-tests.yaml 1970-01-01 00:00:00 +0000 | |||
117 | +++ charm-helpers-tests.yaml 2015-04-30 13:14:23 +0000 | |||
118 | @@ -0,0 +1,4 @@ | |||
119 | 1 | branch: lp:charm-helpers | ||
120 | 2 | destination: tests/charmhelpers | ||
121 | 3 | include: | ||
122 | 4 | - contrib.amulet | ||
123 | 0 | 5 | ||
124 | === removed file 'config.yaml' | |||
125 | --- config.yaml 2015-03-25 19:59:09 +0000 | |||
126 | +++ config.yaml 1970-01-01 00:00:00 +0000 | |||
127 | @@ -1,8 +0,0 @@ | |||
128 | 1 | options: | ||
129 | 2 | new-lxc-network: | ||
130 | 3 | type: boolean | ||
131 | 4 | default: False | ||
132 | 5 | description: | | ||
133 | 6 | If True creates new network for lxc containers, otherwise using the | ||
134 | 7 | same network of the node for lxc containers. | ||
135 | 8 | |||
136 | 9 | 0 | ||
137 | === added directory 'files' | |||
138 | === added file 'files/bundle-example.yaml' | |||
139 | --- files/bundle-example.yaml 1970-01-01 00:00:00 +0000 | |||
140 | +++ files/bundle-example.yaml 2015-04-30 13:14:23 +0000 | |||
141 | @@ -0,0 +1,14 @@ | |||
142 | 1 | "ubuntu-example-bundle": | ||
143 | 2 | services: | ||
144 | 3 | "ubuntu": | ||
145 | 4 | charm: cs:trusty/ubuntu | ||
146 | 5 | num_units: 1 | ||
147 | 6 | annotations: | ||
148 | 7 | "gui-x": "0" | ||
149 | 8 | "gui-y": "0" | ||
150 | 9 | "juju-gui": | ||
151 | 10 | charm: "cs:trusty/juju-gui" | ||
152 | 11 | num_units: 1 | ||
153 | 12 | annotations: | ||
154 | 13 | "gui-x": "500" | ||
155 | 14 | "gui-y": "0" | ||
156 | 0 | 15 | ||
157 | === removed directory 'hooks' | |||
158 | === removed file 'hooks/__init__.py' | |||
159 | === removed directory 'hooks/charmhelpers' | |||
160 | === removed file 'hooks/charmhelpers/__init__.py' | |||
161 | === removed directory 'hooks/charmhelpers/core' | |||
162 | === removed file 'hooks/charmhelpers/core/__init__.py' | |||
163 | --- hooks/charmhelpers/core/__init__.py 2015-02-19 16:21:31 +0000 | |||
164 | +++ hooks/charmhelpers/core/__init__.py 1970-01-01 00:00:00 +0000 | |||
165 | @@ -1,15 +0,0 @@ | |||
166 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
167 | 2 | # | ||
168 | 3 | # This file is part of charm-helpers. | ||
169 | 4 | # | ||
170 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
171 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
172 | 7 | # published by the Free Software Foundation. | ||
173 | 8 | # | ||
174 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
175 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
176 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
177 | 12 | # GNU Lesser General Public License for more details. | ||
178 | 13 | # | ||
179 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
180 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
181 | 16 | 0 | ||
182 | === removed file 'hooks/charmhelpers/core/decorators.py' | |||
183 | --- hooks/charmhelpers/core/decorators.py 2015-02-19 16:21:31 +0000 | |||
184 | +++ hooks/charmhelpers/core/decorators.py 1970-01-01 00:00:00 +0000 | |||
185 | @@ -1,57 +0,0 @@ | |||
186 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
187 | 2 | # | ||
188 | 3 | # This file is part of charm-helpers. | ||
189 | 4 | # | ||
190 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
191 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
192 | 7 | # published by the Free Software Foundation. | ||
193 | 8 | # | ||
194 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
195 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
196 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
197 | 12 | # GNU Lesser General Public License for more details. | ||
198 | 13 | # | ||
199 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
200 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
201 | 16 | |||
202 | 17 | # | ||
203 | 18 | # Copyright 2014 Canonical Ltd. | ||
204 | 19 | # | ||
205 | 20 | # Authors: | ||
206 | 21 | # Edward Hope-Morley <opentastic@gmail.com> | ||
207 | 22 | # | ||
208 | 23 | |||
209 | 24 | import time | ||
210 | 25 | |||
211 | 26 | from charmhelpers.core.hookenv import ( | ||
212 | 27 | log, | ||
213 | 28 | INFO, | ||
214 | 29 | ) | ||
215 | 30 | |||
216 | 31 | |||
217 | 32 | def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): | ||
218 | 33 | """If the decorated function raises exception exc_type, allow num_retries | ||
219 | 34 | retry attempts before raise the exception. | ||
220 | 35 | """ | ||
221 | 36 | def _retry_on_exception_inner_1(f): | ||
222 | 37 | def _retry_on_exception_inner_2(*args, **kwargs): | ||
223 | 38 | retries = num_retries | ||
224 | 39 | multiplier = 1 | ||
225 | 40 | while True: | ||
226 | 41 | try: | ||
227 | 42 | return f(*args, **kwargs) | ||
228 | 43 | except exc_type: | ||
229 | 44 | if not retries: | ||
230 | 45 | raise | ||
231 | 46 | |||
232 | 47 | delay = base_delay * multiplier | ||
233 | 48 | multiplier += 1 | ||
234 | 49 | log("Retrying '%s' %d more times (delay=%s)" % | ||
235 | 50 | (f.__name__, retries, delay), level=INFO) | ||
236 | 51 | retries -= 1 | ||
237 | 52 | if delay: | ||
238 | 53 | time.sleep(delay) | ||
239 | 54 | |||
240 | 55 | return _retry_on_exception_inner_2 | ||
241 | 56 | |||
242 | 57 | return _retry_on_exception_inner_1 | ||
243 | 58 | 0 | ||
244 | === removed file 'hooks/charmhelpers/core/fstab.py' | |||
245 | --- hooks/charmhelpers/core/fstab.py 2015-02-19 16:21:31 +0000 | |||
246 | +++ hooks/charmhelpers/core/fstab.py 1970-01-01 00:00:00 +0000 | |||
247 | @@ -1,134 +0,0 @@ | |||
248 | 1 | #!/usr/bin/env python | ||
249 | 2 | # -*- coding: utf-8 -*- | ||
250 | 3 | |||
251 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
252 | 5 | # | ||
253 | 6 | # This file is part of charm-helpers. | ||
254 | 7 | # | ||
255 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
256 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
257 | 10 | # published by the Free Software Foundation. | ||
258 | 11 | # | ||
259 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
260 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
261 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
262 | 15 | # GNU Lesser General Public License for more details. | ||
263 | 16 | # | ||
264 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
265 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
266 | 19 | |||
267 | 20 | import io | ||
268 | 21 | import os | ||
269 | 22 | |||
270 | 23 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
271 | 24 | |||
272 | 25 | |||
273 | 26 | class Fstab(io.FileIO): | ||
274 | 27 | """This class extends file in order to implement a file reader/writer | ||
275 | 28 | for file `/etc/fstab` | ||
276 | 29 | """ | ||
277 | 30 | |||
278 | 31 | class Entry(object): | ||
279 | 32 | """Entry class represents a non-comment line on the `/etc/fstab` file | ||
280 | 33 | """ | ||
281 | 34 | def __init__(self, device, mountpoint, filesystem, | ||
282 | 35 | options, d=0, p=0): | ||
283 | 36 | self.device = device | ||
284 | 37 | self.mountpoint = mountpoint | ||
285 | 38 | self.filesystem = filesystem | ||
286 | 39 | |||
287 | 40 | if not options: | ||
288 | 41 | options = "defaults" | ||
289 | 42 | |||
290 | 43 | self.options = options | ||
291 | 44 | self.d = int(d) | ||
292 | 45 | self.p = int(p) | ||
293 | 46 | |||
294 | 47 | def __eq__(self, o): | ||
295 | 48 | return str(self) == str(o) | ||
296 | 49 | |||
297 | 50 | def __str__(self): | ||
298 | 51 | return "{} {} {} {} {} {}".format(self.device, | ||
299 | 52 | self.mountpoint, | ||
300 | 53 | self.filesystem, | ||
301 | 54 | self.options, | ||
302 | 55 | self.d, | ||
303 | 56 | self.p) | ||
304 | 57 | |||
305 | 58 | DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab') | ||
306 | 59 | |||
307 | 60 | def __init__(self, path=None): | ||
308 | 61 | if path: | ||
309 | 62 | self._path = path | ||
310 | 63 | else: | ||
311 | 64 | self._path = self.DEFAULT_PATH | ||
312 | 65 | super(Fstab, self).__init__(self._path, 'rb+') | ||
313 | 66 | |||
314 | 67 | def _hydrate_entry(self, line): | ||
315 | 68 | # NOTE: use split with no arguments to split on any | ||
316 | 69 | # whitespace including tabs | ||
317 | 70 | return Fstab.Entry(*filter( | ||
318 | 71 | lambda x: x not in ('', None), | ||
319 | 72 | line.strip("\n").split())) | ||
320 | 73 | |||
321 | 74 | @property | ||
322 | 75 | def entries(self): | ||
323 | 76 | self.seek(0) | ||
324 | 77 | for line in self.readlines(): | ||
325 | 78 | line = line.decode('us-ascii') | ||
326 | 79 | try: | ||
327 | 80 | if line.strip() and not line.strip().startswith("#"): | ||
328 | 81 | yield self._hydrate_entry(line) | ||
329 | 82 | except ValueError: | ||
330 | 83 | pass | ||
331 | 84 | |||
332 | 85 | def get_entry_by_attr(self, attr, value): | ||
333 | 86 | for entry in self.entries: | ||
334 | 87 | e_attr = getattr(entry, attr) | ||
335 | 88 | if e_attr == value: | ||
336 | 89 | return entry | ||
337 | 90 | return None | ||
338 | 91 | |||
339 | 92 | def add_entry(self, entry): | ||
340 | 93 | if self.get_entry_by_attr('device', entry.device): | ||
341 | 94 | return False | ||
342 | 95 | |||
343 | 96 | self.write((str(entry) + '\n').encode('us-ascii')) | ||
344 | 97 | self.truncate() | ||
345 | 98 | return entry | ||
346 | 99 | |||
347 | 100 | def remove_entry(self, entry): | ||
348 | 101 | self.seek(0) | ||
349 | 102 | |||
350 | 103 | lines = [l.decode('us-ascii') for l in self.readlines()] | ||
351 | 104 | |||
352 | 105 | found = False | ||
353 | 106 | for index, line in enumerate(lines): | ||
354 | 107 | if line.strip() and not line.strip().startswith("#"): | ||
355 | 108 | if self._hydrate_entry(line) == entry: | ||
356 | 109 | found = True | ||
357 | 110 | break | ||
358 | 111 | |||
359 | 112 | if not found: | ||
360 | 113 | return False | ||
361 | 114 | |||
362 | 115 | lines.remove(line) | ||
363 | 116 | |||
364 | 117 | self.seek(0) | ||
365 | 118 | self.write(''.join(lines).encode('us-ascii')) | ||
366 | 119 | self.truncate() | ||
367 | 120 | return True | ||
368 | 121 | |||
369 | 122 | @classmethod | ||
370 | 123 | def remove_by_mountpoint(cls, mountpoint, path=None): | ||
371 | 124 | fstab = cls(path=path) | ||
372 | 125 | entry = fstab.get_entry_by_attr('mountpoint', mountpoint) | ||
373 | 126 | if entry: | ||
374 | 127 | return fstab.remove_entry(entry) | ||
375 | 128 | return False | ||
376 | 129 | |||
377 | 130 | @classmethod | ||
378 | 131 | def add(cls, device, mountpoint, filesystem, options=None, path=None): | ||
379 | 132 | return cls(path=path).add_entry(Fstab.Entry(device, | ||
380 | 133 | mountpoint, filesystem, | ||
381 | 134 | options=options)) | ||
382 | 135 | 0 | ||
383 | === removed file 'hooks/charmhelpers/core/hookenv.py' | |||
384 | --- hooks/charmhelpers/core/hookenv.py 2015-02-19 16:21:31 +0000 | |||
385 | +++ hooks/charmhelpers/core/hookenv.py 1970-01-01 00:00:00 +0000 | |||
386 | @@ -1,568 +0,0 @@ | |||
387 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
388 | 2 | # | ||
389 | 3 | # This file is part of charm-helpers. | ||
390 | 4 | # | ||
391 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
392 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
393 | 7 | # published by the Free Software Foundation. | ||
394 | 8 | # | ||
395 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
396 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
397 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
398 | 12 | # GNU Lesser General Public License for more details. | ||
399 | 13 | # | ||
400 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
401 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
402 | 16 | |||
403 | 17 | "Interactions with the Juju environment" | ||
404 | 18 | # Copyright 2013 Canonical Ltd. | ||
405 | 19 | # | ||
406 | 20 | # Authors: | ||
407 | 21 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
408 | 22 | |||
409 | 23 | import os | ||
410 | 24 | import json | ||
411 | 25 | import yaml | ||
412 | 26 | import subprocess | ||
413 | 27 | import sys | ||
414 | 28 | from subprocess import CalledProcessError | ||
415 | 29 | |||
416 | 30 | import six | ||
417 | 31 | if not six.PY3: | ||
418 | 32 | from UserDict import UserDict | ||
419 | 33 | else: | ||
420 | 34 | from collections import UserDict | ||
421 | 35 | |||
422 | 36 | CRITICAL = "CRITICAL" | ||
423 | 37 | ERROR = "ERROR" | ||
424 | 38 | WARNING = "WARNING" | ||
425 | 39 | INFO = "INFO" | ||
426 | 40 | DEBUG = "DEBUG" | ||
427 | 41 | MARKER = object() | ||
428 | 42 | |||
429 | 43 | cache = {} | ||
430 | 44 | |||
431 | 45 | |||
432 | 46 | def cached(func): | ||
433 | 47 | """Cache return values for multiple executions of func + args | ||
434 | 48 | |||
435 | 49 | For example:: | ||
436 | 50 | |||
437 | 51 | @cached | ||
438 | 52 | def unit_get(attribute): | ||
439 | 53 | pass | ||
440 | 54 | |||
441 | 55 | unit_get('test') | ||
442 | 56 | |||
443 | 57 | will cache the result of unit_get + 'test' for future calls. | ||
444 | 58 | """ | ||
445 | 59 | def wrapper(*args, **kwargs): | ||
446 | 60 | global cache | ||
447 | 61 | key = str((func, args, kwargs)) | ||
448 | 62 | try: | ||
449 | 63 | return cache[key] | ||
450 | 64 | except KeyError: | ||
451 | 65 | res = func(*args, **kwargs) | ||
452 | 66 | cache[key] = res | ||
453 | 67 | return res | ||
454 | 68 | return wrapper | ||
455 | 69 | |||
456 | 70 | |||
457 | 71 | def flush(key): | ||
458 | 72 | """Flushes any entries from function cache where the | ||
459 | 73 | key is found in the function+args """ | ||
460 | 74 | flush_list = [] | ||
461 | 75 | for item in cache: | ||
462 | 76 | if key in item: | ||
463 | 77 | flush_list.append(item) | ||
464 | 78 | for item in flush_list: | ||
465 | 79 | del cache[item] | ||
466 | 80 | |||
467 | 81 | |||
468 | 82 | def log(message, level=None): | ||
469 | 83 | """Write a message to the juju log""" | ||
470 | 84 | command = ['juju-log'] | ||
471 | 85 | if level: | ||
472 | 86 | command += ['-l', level] | ||
473 | 87 | if not isinstance(message, six.string_types): | ||
474 | 88 | message = repr(message) | ||
475 | 89 | command += [message] | ||
476 | 90 | subprocess.call(command) | ||
477 | 91 | |||
478 | 92 | |||
479 | 93 | class Serializable(UserDict): | ||
480 | 94 | """Wrapper, an object that can be serialized to yaml or json""" | ||
481 | 95 | |||
482 | 96 | def __init__(self, obj): | ||
483 | 97 | # wrap the object | ||
484 | 98 | UserDict.__init__(self) | ||
485 | 99 | self.data = obj | ||
486 | 100 | |||
487 | 101 | def __getattr__(self, attr): | ||
488 | 102 | # See if this object has attribute. | ||
489 | 103 | if attr in ("json", "yaml", "data"): | ||
490 | 104 | return self.__dict__[attr] | ||
491 | 105 | # Check for attribute in wrapped object. | ||
492 | 106 | got = getattr(self.data, attr, MARKER) | ||
493 | 107 | if got is not MARKER: | ||
494 | 108 | return got | ||
495 | 109 | # Proxy to the wrapped object via dict interface. | ||
496 | 110 | try: | ||
497 | 111 | return self.data[attr] | ||
498 | 112 | except KeyError: | ||
499 | 113 | raise AttributeError(attr) | ||
500 | 114 | |||
501 | 115 | def __getstate__(self): | ||
502 | 116 | # Pickle as a standard dictionary. | ||
503 | 117 | return self.data | ||
504 | 118 | |||
505 | 119 | def __setstate__(self, state): | ||
506 | 120 | # Unpickle into our wrapper. | ||
507 | 121 | self.data = state | ||
508 | 122 | |||
509 | 123 | def json(self): | ||
510 | 124 | """Serialize the object to json""" | ||
511 | 125 | return json.dumps(self.data) | ||
512 | 126 | |||
513 | 127 | def yaml(self): | ||
514 | 128 | """Serialize the object to yaml""" | ||
515 | 129 | return yaml.dump(self.data) | ||
516 | 130 | |||
517 | 131 | |||
518 | 132 | def execution_environment(): | ||
519 | 133 | """A convenient bundling of the current execution context""" | ||
520 | 134 | context = {} | ||
521 | 135 | context['conf'] = config() | ||
522 | 136 | if relation_id(): | ||
523 | 137 | context['reltype'] = relation_type() | ||
524 | 138 | context['relid'] = relation_id() | ||
525 | 139 | context['rel'] = relation_get() | ||
526 | 140 | context['unit'] = local_unit() | ||
527 | 141 | context['rels'] = relations() | ||
528 | 142 | context['env'] = os.environ | ||
529 | 143 | return context | ||
530 | 144 | |||
531 | 145 | |||
532 | 146 | def in_relation_hook(): | ||
533 | 147 | """Determine whether we're running in a relation hook""" | ||
534 | 148 | return 'JUJU_RELATION' in os.environ | ||
535 | 149 | |||
536 | 150 | |||
537 | 151 | def relation_type(): | ||
538 | 152 | """The scope for the current relation hook""" | ||
539 | 153 | return os.environ.get('JUJU_RELATION', None) | ||
540 | 154 | |||
541 | 155 | |||
542 | 156 | def relation_id(): | ||
543 | 157 | """The relation ID for the current relation hook""" | ||
544 | 158 | return os.environ.get('JUJU_RELATION_ID', None) | ||
545 | 159 | |||
546 | 160 | |||
547 | 161 | def local_unit(): | ||
548 | 162 | """Local unit ID""" | ||
549 | 163 | return os.environ['JUJU_UNIT_NAME'] | ||
550 | 164 | |||
551 | 165 | |||
552 | 166 | def remote_unit(): | ||
553 | 167 | """The remote unit for the current relation hook""" | ||
554 | 168 | return os.environ['JUJU_REMOTE_UNIT'] | ||
555 | 169 | |||
556 | 170 | |||
557 | 171 | def service_name(): | ||
558 | 172 | """The name service group this unit belongs to""" | ||
559 | 173 | return local_unit().split('/')[0] | ||
560 | 174 | |||
561 | 175 | |||
562 | 176 | def hook_name(): | ||
563 | 177 | """The name of the currently executing hook""" | ||
564 | 178 | return os.path.basename(sys.argv[0]) | ||
565 | 179 | |||
566 | 180 | |||
567 | 181 | class Config(dict): | ||
568 | 182 | """A dictionary representation of the charm's config.yaml, with some | ||
569 | 183 | extra features: | ||
570 | 184 | |||
571 | 185 | - See which values in the dictionary have changed since the previous hook. | ||
572 | 186 | - For values that have changed, see what the previous value was. | ||
573 | 187 | - Store arbitrary data for use in a later hook. | ||
574 | 188 | |||
575 | 189 | NOTE: Do not instantiate this object directly - instead call | ||
576 | 190 | ``hookenv.config()``, which will return an instance of :class:`Config`. | ||
577 | 191 | |||
578 | 192 | Example usage:: | ||
579 | 193 | |||
580 | 194 | >>> # inside a hook | ||
581 | 195 | >>> from charmhelpers.core import hookenv | ||
582 | 196 | >>> config = hookenv.config() | ||
583 | 197 | >>> config['foo'] | ||
584 | 198 | 'bar' | ||
585 | 199 | >>> # store a new key/value for later use | ||
586 | 200 | >>> config['mykey'] = 'myval' | ||
587 | 201 | |||
588 | 202 | |||
589 | 203 | >>> # user runs `juju set mycharm foo=baz` | ||
590 | 204 | >>> # now we're inside subsequent config-changed hook | ||
591 | 205 | >>> config = hookenv.config() | ||
592 | 206 | >>> config['foo'] | ||
593 | 207 | 'baz' | ||
594 | 208 | >>> # test to see if this val has changed since last hook | ||
595 | 209 | >>> config.changed('foo') | ||
596 | 210 | True | ||
597 | 211 | >>> # what was the previous value? | ||
598 | 212 | >>> config.previous('foo') | ||
599 | 213 | 'bar' | ||
600 | 214 | >>> # keys/values that we add are preserved across hooks | ||
601 | 215 | >>> config['mykey'] | ||
602 | 216 | 'myval' | ||
603 | 217 | |||
604 | 218 | """ | ||
605 | 219 | CONFIG_FILE_NAME = '.juju-persistent-config' | ||
606 | 220 | |||
607 | 221 | def __init__(self, *args, **kw): | ||
608 | 222 | super(Config, self).__init__(*args, **kw) | ||
609 | 223 | self.implicit_save = True | ||
610 | 224 | self._prev_dict = None | ||
611 | 225 | self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME) | ||
612 | 226 | if os.path.exists(self.path): | ||
613 | 227 | self.load_previous() | ||
614 | 228 | |||
615 | 229 | def __getitem__(self, key): | ||
616 | 230 | """For regular dict lookups, check the current juju config first, | ||
617 | 231 | then the previous (saved) copy. This ensures that user-saved values | ||
618 | 232 | will be returned by a dict lookup. | ||
619 | 233 | |||
620 | 234 | """ | ||
621 | 235 | try: | ||
622 | 236 | return dict.__getitem__(self, key) | ||
623 | 237 | except KeyError: | ||
624 | 238 | return (self._prev_dict or {})[key] | ||
625 | 239 | |||
626 | 240 | def keys(self): | ||
627 | 241 | prev_keys = [] | ||
628 | 242 | if self._prev_dict is not None: | ||
629 | 243 | prev_keys = self._prev_dict.keys() | ||
630 | 244 | return list(set(prev_keys + list(dict.keys(self)))) | ||
631 | 245 | |||
632 | 246 | def load_previous(self, path=None): | ||
633 | 247 | """Load previous copy of config from disk. | ||
634 | 248 | |||
635 | 249 | In normal usage you don't need to call this method directly - it | ||
636 | 250 | is called automatically at object initialization. | ||
637 | 251 | |||
638 | 252 | :param path: | ||
639 | 253 | |||
640 | 254 | File path from which to load the previous config. If `None`, | ||
641 | 255 | config is loaded from the default location. If `path` is | ||
642 | 256 | specified, subsequent `save()` calls will write to the same | ||
643 | 257 | path. | ||
644 | 258 | |||
645 | 259 | """ | ||
646 | 260 | self.path = path or self.path | ||
647 | 261 | with open(self.path) as f: | ||
648 | 262 | self._prev_dict = json.load(f) | ||
649 | 263 | |||
650 | 264 | def changed(self, key): | ||
651 | 265 | """Return True if the current value for this key is different from | ||
652 | 266 | the previous value. | ||
653 | 267 | |||
654 | 268 | """ | ||
655 | 269 | if self._prev_dict is None: | ||
656 | 270 | return True | ||
657 | 271 | return self.previous(key) != self.get(key) | ||
658 | 272 | |||
659 | 273 | def previous(self, key): | ||
660 | 274 | """Return previous value for this key, or None if there | ||
661 | 275 | is no previous value. | ||
662 | 276 | |||
663 | 277 | """ | ||
664 | 278 | if self._prev_dict: | ||
665 | 279 | return self._prev_dict.get(key) | ||
666 | 280 | return None | ||
667 | 281 | |||
668 | 282 | def save(self): | ||
669 | 283 | """Save this config to disk. | ||
670 | 284 | |||
671 | 285 | If the charm is using the :mod:`Services Framework <services.base>` | ||
672 | 286 | or :meth:'@hook <Hooks.hook>' decorator, this | ||
673 | 287 | is called automatically at the end of successful hook execution. | ||
674 | 288 | Otherwise, it should be called directly by user code. | ||
675 | 289 | |||
676 | 290 | To disable automatic saves, set ``implicit_save=False`` on this | ||
677 | 291 | instance. | ||
678 | 292 | |||
679 | 293 | """ | ||
680 | 294 | if self._prev_dict: | ||
681 | 295 | for k, v in six.iteritems(self._prev_dict): | ||
682 | 296 | if k not in self: | ||
683 | 297 | self[k] = v | ||
684 | 298 | with open(self.path, 'w') as f: | ||
685 | 299 | json.dump(self, f) | ||
686 | 300 | |||
687 | 301 | |||
688 | 302 | @cached | ||
689 | 303 | def config(scope=None): | ||
690 | 304 | """Juju charm configuration""" | ||
691 | 305 | config_cmd_line = ['config-get'] | ||
692 | 306 | if scope is not None: | ||
693 | 307 | config_cmd_line.append(scope) | ||
694 | 308 | config_cmd_line.append('--format=json') | ||
695 | 309 | try: | ||
696 | 310 | config_data = json.loads( | ||
697 | 311 | subprocess.check_output(config_cmd_line).decode('UTF-8')) | ||
698 | 312 | if scope is not None: | ||
699 | 313 | return config_data | ||
700 | 314 | return Config(config_data) | ||
701 | 315 | except ValueError: | ||
702 | 316 | return None | ||
703 | 317 | |||
704 | 318 | |||
705 | 319 | @cached | ||
706 | 320 | def relation_get(attribute=None, unit=None, rid=None): | ||
707 | 321 | """Get relation information""" | ||
708 | 322 | _args = ['relation-get', '--format=json'] | ||
709 | 323 | if rid: | ||
710 | 324 | _args.append('-r') | ||
711 | 325 | _args.append(rid) | ||
712 | 326 | _args.append(attribute or '-') | ||
713 | 327 | if unit: | ||
714 | 328 | _args.append(unit) | ||
715 | 329 | try: | ||
716 | 330 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
717 | 331 | except ValueError: | ||
718 | 332 | return None | ||
719 | 333 | except CalledProcessError as e: | ||
720 | 334 | if e.returncode == 2: | ||
721 | 335 | return None | ||
722 | 336 | raise | ||
723 | 337 | |||
724 | 338 | |||
725 | 339 | def relation_set(relation_id=None, relation_settings=None, **kwargs): | ||
726 | 340 | """Set relation information for the current unit""" | ||
727 | 341 | relation_settings = relation_settings if relation_settings else {} | ||
728 | 342 | relation_cmd_line = ['relation-set'] | ||
729 | 343 | if relation_id is not None: | ||
730 | 344 | relation_cmd_line.extend(('-r', relation_id)) | ||
731 | 345 | for k, v in (list(relation_settings.items()) + list(kwargs.items())): | ||
732 | 346 | if v is None: | ||
733 | 347 | relation_cmd_line.append('{}='.format(k)) | ||
734 | 348 | else: | ||
735 | 349 | relation_cmd_line.append('{}={}'.format(k, v)) | ||
736 | 350 | subprocess.check_call(relation_cmd_line) | ||
737 | 351 | # Flush cache of any relation-gets for local unit | ||
738 | 352 | flush(local_unit()) | ||
739 | 353 | |||
740 | 354 | |||
741 | 355 | @cached | ||
742 | 356 | def relation_ids(reltype=None): | ||
743 | 357 | """A list of relation_ids""" | ||
744 | 358 | reltype = reltype or relation_type() | ||
745 | 359 | relid_cmd_line = ['relation-ids', '--format=json'] | ||
746 | 360 | if reltype is not None: | ||
747 | 361 | relid_cmd_line.append(reltype) | ||
748 | 362 | return json.loads( | ||
749 | 363 | subprocess.check_output(relid_cmd_line).decode('UTF-8')) or [] | ||
750 | 364 | return [] | ||
751 | 365 | |||
752 | 366 | |||
753 | 367 | @cached | ||
754 | 368 | def related_units(relid=None): | ||
755 | 369 | """A list of related units""" | ||
756 | 370 | relid = relid or relation_id() | ||
757 | 371 | units_cmd_line = ['relation-list', '--format=json'] | ||
758 | 372 | if relid is not None: | ||
759 | 373 | units_cmd_line.extend(('-r', relid)) | ||
760 | 374 | return json.loads( | ||
761 | 375 | subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | ||
762 | 376 | |||
763 | 377 | |||
764 | 378 | @cached | ||
765 | 379 | def relation_for_unit(unit=None, rid=None): | ||
766 | 380 | """Get the json represenation of a unit's relation""" | ||
767 | 381 | unit = unit or remote_unit() | ||
768 | 382 | relation = relation_get(unit=unit, rid=rid) | ||
769 | 383 | for key in relation: | ||
770 | 384 | if key.endswith('-list'): | ||
771 | 385 | relation[key] = relation[key].split() | ||
772 | 386 | relation['__unit__'] = unit | ||
773 | 387 | return relation | ||
774 | 388 | |||
775 | 389 | |||
776 | 390 | @cached | ||
777 | 391 | def relations_for_id(relid=None): | ||
778 | 392 | """Get relations of a specific relation ID""" | ||
779 | 393 | relation_data = [] | ||
780 | 394 | relid = relid or relation_ids() | ||
781 | 395 | for unit in related_units(relid): | ||
782 | 396 | unit_data = relation_for_unit(unit, relid) | ||
783 | 397 | unit_data['__relid__'] = relid | ||
784 | 398 | relation_data.append(unit_data) | ||
785 | 399 | return relation_data | ||
786 | 400 | |||
787 | 401 | |||
788 | 402 | @cached | ||
789 | 403 | def relations_of_type(reltype=None): | ||
790 | 404 | """Get relations of a specific type""" | ||
791 | 405 | relation_data = [] | ||
792 | 406 | reltype = reltype or relation_type() | ||
793 | 407 | for relid in relation_ids(reltype): | ||
794 | 408 | for relation in relations_for_id(relid): | ||
795 | 409 | relation['__relid__'] = relid | ||
796 | 410 | relation_data.append(relation) | ||
797 | 411 | return relation_data | ||
798 | 412 | |||
799 | 413 | |||
800 | 414 | @cached | ||
801 | 415 | def metadata(): | ||
802 | 416 | """Get the current charm metadata.yaml contents as a python object""" | ||
803 | 417 | with open(os.path.join(charm_dir(), 'metadata.yaml')) as md: | ||
804 | 418 | return yaml.safe_load(md) | ||
805 | 419 | |||
806 | 420 | |||
807 | 421 | @cached | ||
808 | 422 | def relation_types(): | ||
809 | 423 | """Get a list of relation types supported by this charm""" | ||
810 | 424 | rel_types = [] | ||
811 | 425 | md = metadata() | ||
812 | 426 | for key in ('provides', 'requires', 'peers'): | ||
813 | 427 | section = md.get(key) | ||
814 | 428 | if section: | ||
815 | 429 | rel_types.extend(section.keys()) | ||
816 | 430 | return rel_types | ||
817 | 431 | |||
818 | 432 | |||
819 | 433 | @cached | ||
820 | 434 | def charm_name(): | ||
821 | 435 | """Get the name of the current charm as is specified on metadata.yaml""" | ||
822 | 436 | return metadata().get('name') | ||
823 | 437 | |||
824 | 438 | |||
825 | 439 | @cached | ||
826 | 440 | def relations(): | ||
827 | 441 | """Get a nested dictionary of relation data for all related units""" | ||
828 | 442 | rels = {} | ||
829 | 443 | for reltype in relation_types(): | ||
830 | 444 | relids = {} | ||
831 | 445 | for relid in relation_ids(reltype): | ||
832 | 446 | units = {local_unit(): relation_get(unit=local_unit(), rid=relid)} | ||
833 | 447 | for unit in related_units(relid): | ||
834 | 448 | reldata = relation_get(unit=unit, rid=relid) | ||
835 | 449 | units[unit] = reldata | ||
836 | 450 | relids[relid] = units | ||
837 | 451 | rels[reltype] = relids | ||
838 | 452 | return rels | ||
839 | 453 | |||
840 | 454 | |||
841 | 455 | @cached | ||
842 | 456 | def is_relation_made(relation, keys='private-address'): | ||
843 | 457 | ''' | ||
844 | 458 | Determine whether a relation is established by checking for | ||
845 | 459 | presence of key(s). If a list of keys is provided, they | ||
846 | 460 | must all be present for the relation to be identified as made | ||
847 | 461 | ''' | ||
848 | 462 | if isinstance(keys, str): | ||
849 | 463 | keys = [keys] | ||
850 | 464 | for r_id in relation_ids(relation): | ||
851 | 465 | for unit in related_units(r_id): | ||
852 | 466 | context = {} | ||
853 | 467 | for k in keys: | ||
854 | 468 | context[k] = relation_get(k, rid=r_id, | ||
855 | 469 | unit=unit) | ||
856 | 470 | if None not in context.values(): | ||
857 | 471 | return True | ||
858 | 472 | return False | ||
859 | 473 | |||
860 | 474 | |||
861 | 475 | def open_port(port, protocol="TCP"): | ||
862 | 476 | """Open a service network port""" | ||
863 | 477 | _args = ['open-port'] | ||
864 | 478 | _args.append('{}/{}'.format(port, protocol)) | ||
865 | 479 | subprocess.check_call(_args) | ||
866 | 480 | |||
867 | 481 | |||
868 | 482 | def close_port(port, protocol="TCP"): | ||
869 | 483 | """Close a service network port""" | ||
870 | 484 | _args = ['close-port'] | ||
871 | 485 | _args.append('{}/{}'.format(port, protocol)) | ||
872 | 486 | subprocess.check_call(_args) | ||
873 | 487 | |||
874 | 488 | |||
875 | 489 | @cached | ||
876 | 490 | def unit_get(attribute): | ||
877 | 491 | """Get the unit ID for the remote unit""" | ||
878 | 492 | _args = ['unit-get', '--format=json', attribute] | ||
879 | 493 | try: | ||
880 | 494 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
881 | 495 | except ValueError: | ||
882 | 496 | return None | ||
883 | 497 | |||
884 | 498 | |||
885 | 499 | def unit_private_ip(): | ||
886 | 500 | """Get this unit's private IP address""" | ||
887 | 501 | return unit_get('private-address') | ||
888 | 502 | |||
889 | 503 | |||
890 | 504 | class UnregisteredHookError(Exception): | ||
891 | 505 | """Raised when an undefined hook is called""" | ||
892 | 506 | pass | ||
893 | 507 | |||
894 | 508 | |||
895 | 509 | class Hooks(object): | ||
896 | 510 | """A convenient handler for hook functions. | ||
897 | 511 | |||
898 | 512 | Example:: | ||
899 | 513 | |||
900 | 514 | hooks = Hooks() | ||
901 | 515 | |||
902 | 516 | # register a hook, taking its name from the function name | ||
903 | 517 | @hooks.hook() | ||
904 | 518 | def install(): | ||
905 | 519 | pass # your code here | ||
906 | 520 | |||
907 | 521 | # register a hook, providing a custom hook name | ||
908 | 522 | @hooks.hook("config-changed") | ||
909 | 523 | def config_changed(): | ||
910 | 524 | pass # your code here | ||
911 | 525 | |||
912 | 526 | if __name__ == "__main__": | ||
913 | 527 | # execute a hook based on the name the program is called by | ||
914 | 528 | hooks.execute(sys.argv) | ||
915 | 529 | """ | ||
916 | 530 | |||
917 | 531 | def __init__(self, config_save=True): | ||
918 | 532 | super(Hooks, self).__init__() | ||
919 | 533 | self._hooks = {} | ||
920 | 534 | self._config_save = config_save | ||
921 | 535 | |||
922 | 536 | def register(self, name, function): | ||
923 | 537 | """Register a hook""" | ||
924 | 538 | self._hooks[name] = function | ||
925 | 539 | |||
926 | 540 | def execute(self, args): | ||
927 | 541 | """Execute a registered hook based on args[0]""" | ||
928 | 542 | hook_name = os.path.basename(args[0]) | ||
929 | 543 | if hook_name in self._hooks: | ||
930 | 544 | self._hooks[hook_name]() | ||
931 | 545 | if self._config_save: | ||
932 | 546 | cfg = config() | ||
933 | 547 | if cfg.implicit_save: | ||
934 | 548 | cfg.save() | ||
935 | 549 | else: | ||
936 | 550 | raise UnregisteredHookError(hook_name) | ||
937 | 551 | |||
938 | 552 | def hook(self, *hook_names): | ||
939 | 553 | """Decorator, registering them as hooks""" | ||
940 | 554 | def wrapper(decorated): | ||
941 | 555 | for hook_name in hook_names: | ||
942 | 556 | self.register(hook_name, decorated) | ||
943 | 557 | else: | ||
944 | 558 | self.register(decorated.__name__, decorated) | ||
945 | 559 | if '_' in decorated.__name__: | ||
946 | 560 | self.register( | ||
947 | 561 | decorated.__name__.replace('_', '-'), decorated) | ||
948 | 562 | return decorated | ||
949 | 563 | return wrapper | ||
950 | 564 | |||
951 | 565 | |||
952 | 566 | def charm_dir(): | ||
953 | 567 | """Return the root directory of the current charm""" | ||
954 | 568 | return os.environ.get('CHARM_DIR') | ||
955 | 569 | 0 | ||
956 | === removed file 'hooks/charmhelpers/core/host.py' | |||
957 | --- hooks/charmhelpers/core/host.py 2015-02-19 16:21:31 +0000 | |||
958 | +++ hooks/charmhelpers/core/host.py 1970-01-01 00:00:00 +0000 | |||
959 | @@ -1,446 +0,0 @@ | |||
960 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
961 | 2 | # | ||
962 | 3 | # This file is part of charm-helpers. | ||
963 | 4 | # | ||
964 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
965 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
966 | 7 | # published by the Free Software Foundation. | ||
967 | 8 | # | ||
968 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
969 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
970 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
971 | 12 | # GNU Lesser General Public License for more details. | ||
972 | 13 | # | ||
973 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
974 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
975 | 16 | |||
976 | 17 | """Tools for working with the host system""" | ||
977 | 18 | # Copyright 2012 Canonical Ltd. | ||
978 | 19 | # | ||
979 | 20 | # Authors: | ||
980 | 21 | # Nick Moffitt <nick.moffitt@canonical.com> | ||
981 | 22 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | ||
982 | 23 | |||
983 | 24 | import os | ||
984 | 25 | import re | ||
985 | 26 | import pwd | ||
986 | 27 | import grp | ||
987 | 28 | import random | ||
988 | 29 | import string | ||
989 | 30 | import subprocess | ||
990 | 31 | import hashlib | ||
991 | 32 | from contextlib import contextmanager | ||
992 | 33 | from collections import OrderedDict | ||
993 | 34 | |||
994 | 35 | import six | ||
995 | 36 | |||
996 | 37 | from .hookenv import log | ||
997 | 38 | from .fstab import Fstab | ||
998 | 39 | |||
999 | 40 | |||
1000 | 41 | def service_start(service_name): | ||
1001 | 42 | """Start a system service""" | ||
1002 | 43 | return service('start', service_name) | ||
1003 | 44 | |||
1004 | 45 | |||
1005 | 46 | def service_stop(service_name): | ||
1006 | 47 | """Stop a system service""" | ||
1007 | 48 | return service('stop', service_name) | ||
1008 | 49 | |||
1009 | 50 | |||
1010 | 51 | def service_restart(service_name): | ||
1011 | 52 | """Restart a system service""" | ||
1012 | 53 | return service('restart', service_name) | ||
1013 | 54 | |||
1014 | 55 | |||
1015 | 56 | def service_reload(service_name, restart_on_failure=False): | ||
1016 | 57 | """Reload a system service, optionally falling back to restart if | ||
1017 | 58 | reload fails""" | ||
1018 | 59 | service_result = service('reload', service_name) | ||
1019 | 60 | if not service_result and restart_on_failure: | ||
1020 | 61 | service_result = service('restart', service_name) | ||
1021 | 62 | return service_result | ||
1022 | 63 | |||
1023 | 64 | |||
1024 | 65 | def service(action, service_name): | ||
1025 | 66 | """Control a system service""" | ||
1026 | 67 | cmd = ['service', service_name, action] | ||
1027 | 68 | return subprocess.call(cmd) == 0 | ||
1028 | 69 | |||
1029 | 70 | |||
1030 | 71 | def service_running(service): | ||
1031 | 72 | """Determine whether a system service is running""" | ||
1032 | 73 | try: | ||
1033 | 74 | output = subprocess.check_output( | ||
1034 | 75 | ['service', service, 'status'], | ||
1035 | 76 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1036 | 77 | except subprocess.CalledProcessError: | ||
1037 | 78 | return False | ||
1038 | 79 | else: | ||
1039 | 80 | if ("start/running" in output or "is running" in output): | ||
1040 | 81 | return True | ||
1041 | 82 | else: | ||
1042 | 83 | return False | ||
1043 | 84 | |||
1044 | 85 | |||
1045 | 86 | def service_available(service_name): | ||
1046 | 87 | """Determine whether a system service is available""" | ||
1047 | 88 | try: | ||
1048 | 89 | subprocess.check_output( | ||
1049 | 90 | ['service', service_name, 'status'], | ||
1050 | 91 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1051 | 92 | except subprocess.CalledProcessError as e: | ||
1052 | 93 | return 'unrecognized service' not in e.output | ||
1053 | 94 | else: | ||
1054 | 95 | return True | ||
1055 | 96 | |||
1056 | 97 | |||
1057 | 98 | def adduser(username, password=None, shell='/bin/bash', system_user=False): | ||
1058 | 99 | """Add a user to the system""" | ||
1059 | 100 | try: | ||
1060 | 101 | user_info = pwd.getpwnam(username) | ||
1061 | 102 | log('user {0} already exists!'.format(username)) | ||
1062 | 103 | except KeyError: | ||
1063 | 104 | log('creating user {0}'.format(username)) | ||
1064 | 105 | cmd = ['useradd'] | ||
1065 | 106 | if system_user or password is None: | ||
1066 | 107 | cmd.append('--system') | ||
1067 | 108 | else: | ||
1068 | 109 | cmd.extend([ | ||
1069 | 110 | '--create-home', | ||
1070 | 111 | '--shell', shell, | ||
1071 | 112 | '--password', password, | ||
1072 | 113 | ]) | ||
1073 | 114 | cmd.append(username) | ||
1074 | 115 | subprocess.check_call(cmd) | ||
1075 | 116 | user_info = pwd.getpwnam(username) | ||
1076 | 117 | return user_info | ||
1077 | 118 | |||
1078 | 119 | |||
1079 | 120 | def add_group(group_name, system_group=False): | ||
1080 | 121 | """Add a group to the system""" | ||
1081 | 122 | try: | ||
1082 | 123 | group_info = grp.getgrnam(group_name) | ||
1083 | 124 | log('group {0} already exists!'.format(group_name)) | ||
1084 | 125 | except KeyError: | ||
1085 | 126 | log('creating group {0}'.format(group_name)) | ||
1086 | 127 | cmd = ['addgroup'] | ||
1087 | 128 | if system_group: | ||
1088 | 129 | cmd.append('--system') | ||
1089 | 130 | else: | ||
1090 | 131 | cmd.extend([ | ||
1091 | 132 | '--group', | ||
1092 | 133 | ]) | ||
1093 | 134 | cmd.append(group_name) | ||
1094 | 135 | subprocess.check_call(cmd) | ||
1095 | 136 | group_info = grp.getgrnam(group_name) | ||
1096 | 137 | return group_info | ||
1097 | 138 | |||
1098 | 139 | |||
1099 | 140 | def add_user_to_group(username, group): | ||
1100 | 141 | """Add a user to a group""" | ||
1101 | 142 | cmd = [ | ||
1102 | 143 | 'gpasswd', '-a', | ||
1103 | 144 | username, | ||
1104 | 145 | group | ||
1105 | 146 | ] | ||
1106 | 147 | log("Adding user {} to group {}".format(username, group)) | ||
1107 | 148 | subprocess.check_call(cmd) | ||
1108 | 149 | |||
1109 | 150 | |||
1110 | 151 | def rsync(from_path, to_path, flags='-r', options=None): | ||
1111 | 152 | """Replicate the contents of a path""" | ||
1112 | 153 | options = options or ['--delete', '--executability'] | ||
1113 | 154 | cmd = ['/usr/bin/rsync', flags] | ||
1114 | 155 | cmd.extend(options) | ||
1115 | 156 | cmd.append(from_path) | ||
1116 | 157 | cmd.append(to_path) | ||
1117 | 158 | log(" ".join(cmd)) | ||
1118 | 159 | return subprocess.check_output(cmd).decode('UTF-8').strip() | ||
1119 | 160 | |||
1120 | 161 | |||
1121 | 162 | def symlink(source, destination): | ||
1122 | 163 | """Create a symbolic link""" | ||
1123 | 164 | log("Symlinking {} as {}".format(source, destination)) | ||
1124 | 165 | cmd = [ | ||
1125 | 166 | 'ln', | ||
1126 | 167 | '-sf', | ||
1127 | 168 | source, | ||
1128 | 169 | destination, | ||
1129 | 170 | ] | ||
1130 | 171 | subprocess.check_call(cmd) | ||
1131 | 172 | |||
1132 | 173 | |||
1133 | 174 | def mkdir(path, owner='root', group='root', perms=0o555, force=False): | ||
1134 | 175 | """Create a directory""" | ||
1135 | 176 | log("Making dir {} {}:{} {:o}".format(path, owner, group, | ||
1136 | 177 | perms)) | ||
1137 | 178 | uid = pwd.getpwnam(owner).pw_uid | ||
1138 | 179 | gid = grp.getgrnam(group).gr_gid | ||
1139 | 180 | realpath = os.path.abspath(path) | ||
1140 | 181 | path_exists = os.path.exists(realpath) | ||
1141 | 182 | if path_exists and force: | ||
1142 | 183 | if not os.path.isdir(realpath): | ||
1143 | 184 | log("Removing non-directory file {} prior to mkdir()".format(path)) | ||
1144 | 185 | os.unlink(realpath) | ||
1145 | 186 | os.makedirs(realpath, perms) | ||
1146 | 187 | elif not path_exists: | ||
1147 | 188 | os.makedirs(realpath, perms) | ||
1148 | 189 | os.chown(realpath, uid, gid) | ||
1149 | 190 | os.chmod(realpath, perms) | ||
1150 | 191 | |||
1151 | 192 | |||
1152 | 193 | def write_file(path, content, owner='root', group='root', perms=0o444): | ||
1153 | 194 | """Create or overwrite a file with the contents of a byte string.""" | ||
1154 | 195 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) | ||
1155 | 196 | uid = pwd.getpwnam(owner).pw_uid | ||
1156 | 197 | gid = grp.getgrnam(group).gr_gid | ||
1157 | 198 | with open(path, 'wb') as target: | ||
1158 | 199 | os.fchown(target.fileno(), uid, gid) | ||
1159 | 200 | os.fchmod(target.fileno(), perms) | ||
1160 | 201 | target.write(content) | ||
1161 | 202 | |||
1162 | 203 | |||
1163 | 204 | def fstab_remove(mp): | ||
1164 | 205 | """Remove the given mountpoint entry from /etc/fstab | ||
1165 | 206 | """ | ||
1166 | 207 | return Fstab.remove_by_mountpoint(mp) | ||
1167 | 208 | |||
1168 | 209 | |||
1169 | 210 | def fstab_add(dev, mp, fs, options=None): | ||
1170 | 211 | """Adds the given device entry to the /etc/fstab file | ||
1171 | 212 | """ | ||
1172 | 213 | return Fstab.add(dev, mp, fs, options=options) | ||
1173 | 214 | |||
1174 | 215 | |||
1175 | 216 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): | ||
1176 | 217 | """Mount a filesystem at a particular mountpoint""" | ||
1177 | 218 | cmd_args = ['mount'] | ||
1178 | 219 | if options is not None: | ||
1179 | 220 | cmd_args.extend(['-o', options]) | ||
1180 | 221 | cmd_args.extend([device, mountpoint]) | ||
1181 | 222 | try: | ||
1182 | 223 | subprocess.check_output(cmd_args) | ||
1183 | 224 | except subprocess.CalledProcessError as e: | ||
1184 | 225 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | ||
1185 | 226 | return False | ||
1186 | 227 | |||
1187 | 228 | if persist: | ||
1188 | 229 | return fstab_add(device, mountpoint, filesystem, options=options) | ||
1189 | 230 | return True | ||
1190 | 231 | |||
1191 | 232 | |||
1192 | 233 | def umount(mountpoint, persist=False): | ||
1193 | 234 | """Unmount a filesystem""" | ||
1194 | 235 | cmd_args = ['umount', mountpoint] | ||
1195 | 236 | try: | ||
1196 | 237 | subprocess.check_output(cmd_args) | ||
1197 | 238 | except subprocess.CalledProcessError as e: | ||
1198 | 239 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | ||
1199 | 240 | return False | ||
1200 | 241 | |||
1201 | 242 | if persist: | ||
1202 | 243 | return fstab_remove(mountpoint) | ||
1203 | 244 | return True | ||
1204 | 245 | |||
1205 | 246 | |||
1206 | 247 | def mounts(): | ||
1207 | 248 | """Get a list of all mounted volumes as [[mountpoint,device],[...]]""" | ||
1208 | 249 | with open('/proc/mounts') as f: | ||
1209 | 250 | # [['/mount/point','/dev/path'],[...]] | ||
1210 | 251 | system_mounts = [m[1::-1] for m in [l.strip().split() | ||
1211 | 252 | for l in f.readlines()]] | ||
1212 | 253 | return system_mounts | ||
1213 | 254 | |||
1214 | 255 | |||
1215 | 256 | def file_hash(path, hash_type='md5'): | ||
1216 | 257 | """ | ||
1217 | 258 | Generate a hash checksum of the contents of 'path' or None if not found. | ||
1218 | 259 | |||
1219 | 260 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
1220 | 261 | such as md5, sha1, sha256, sha512, etc. | ||
1221 | 262 | """ | ||
1222 | 263 | if os.path.exists(path): | ||
1223 | 264 | h = getattr(hashlib, hash_type)() | ||
1224 | 265 | with open(path, 'rb') as source: | ||
1225 | 266 | h.update(source.read()) | ||
1226 | 267 | return h.hexdigest() | ||
1227 | 268 | else: | ||
1228 | 269 | return None | ||
1229 | 270 | |||
1230 | 271 | |||
1231 | 272 | def check_hash(path, checksum, hash_type='md5'): | ||
1232 | 273 | """ | ||
1233 | 274 | Validate a file using a cryptographic checksum. | ||
1234 | 275 | |||
1235 | 276 | :param str checksum: Value of the checksum used to validate the file. | ||
1236 | 277 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
1237 | 278 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
1238 | 279 | such as md5, sha1, sha256, sha512, etc. | ||
1239 | 280 | :raises ChecksumError: If the file fails the checksum | ||
1240 | 281 | |||
1241 | 282 | """ | ||
1242 | 283 | actual_checksum = file_hash(path, hash_type) | ||
1243 | 284 | if checksum != actual_checksum: | ||
1244 | 285 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
1245 | 286 | |||
1246 | 287 | |||
1247 | 288 | class ChecksumError(ValueError): | ||
1248 | 289 | pass | ||
1249 | 290 | |||
1250 | 291 | |||
1251 | 292 | def restart_on_change(restart_map, stopstart=False): | ||
1252 | 293 | """Restart services based on configuration files changing | ||
1253 | 294 | |||
1254 | 295 | This function is used a decorator, for example:: | ||
1255 | 296 | |||
1256 | 297 | @restart_on_change({ | ||
1257 | 298 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] | ||
1258 | 299 | }) | ||
1259 | 300 | def ceph_client_changed(): | ||
1260 | 301 | pass # your code here | ||
1261 | 302 | |||
1262 | 303 | In this example, the cinder-api and cinder-volume services | ||
1263 | 304 | would be restarted if /etc/ceph/ceph.conf is changed by the | ||
1264 | 305 | ceph_client_changed function. | ||
1265 | 306 | """ | ||
1266 | 307 | def wrap(f): | ||
1267 | 308 | def wrapped_f(*args, **kwargs): | ||
1268 | 309 | checksums = {} | ||
1269 | 310 | for path in restart_map: | ||
1270 | 311 | checksums[path] = file_hash(path) | ||
1271 | 312 | f(*args, **kwargs) | ||
1272 | 313 | restarts = [] | ||
1273 | 314 | for path in restart_map: | ||
1274 | 315 | if checksums[path] != file_hash(path): | ||
1275 | 316 | restarts += restart_map[path] | ||
1276 | 317 | services_list = list(OrderedDict.fromkeys(restarts)) | ||
1277 | 318 | if not stopstart: | ||
1278 | 319 | for service_name in services_list: | ||
1279 | 320 | service('restart', service_name) | ||
1280 | 321 | else: | ||
1281 | 322 | for action in ['stop', 'start']: | ||
1282 | 323 | for service_name in services_list: | ||
1283 | 324 | service(action, service_name) | ||
1284 | 325 | return wrapped_f | ||
1285 | 326 | return wrap | ||
1286 | 327 | |||
1287 | 328 | |||
1288 | 329 | def lsb_release(): | ||
1289 | 330 | """Return /etc/lsb-release in a dict""" | ||
1290 | 331 | d = {} | ||
1291 | 332 | with open('/etc/lsb-release', 'r') as lsb: | ||
1292 | 333 | for l in lsb: | ||
1293 | 334 | k, v = l.split('=') | ||
1294 | 335 | d[k.strip()] = v.strip() | ||
1295 | 336 | return d | ||
1296 | 337 | |||
1297 | 338 | |||
1298 | 339 | def pwgen(length=None): | ||
1299 | 340 | """Generate a random pasword.""" | ||
1300 | 341 | if length is None: | ||
1301 | 342 | length = random.choice(range(35, 45)) | ||
1302 | 343 | alphanumeric_chars = [ | ||
1303 | 344 | l for l in (string.ascii_letters + string.digits) | ||
1304 | 345 | if l not in 'l0QD1vAEIOUaeiou'] | ||
1305 | 346 | random_chars = [ | ||
1306 | 347 | random.choice(alphanumeric_chars) for _ in range(length)] | ||
1307 | 348 | return(''.join(random_chars)) | ||
1308 | 349 | |||
1309 | 350 | |||
1310 | 351 | def list_nics(nic_type): | ||
1311 | 352 | '''Return a list of nics of given type(s)''' | ||
1312 | 353 | if isinstance(nic_type, six.string_types): | ||
1313 | 354 | int_types = [nic_type] | ||
1314 | 355 | else: | ||
1315 | 356 | int_types = nic_type | ||
1316 | 357 | interfaces = [] | ||
1317 | 358 | for int_type in int_types: | ||
1318 | 359 | cmd = ['ip', 'addr', 'show', 'label', int_type + '*'] | ||
1319 | 360 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
1320 | 361 | ip_output = (line for line in ip_output if line) | ||
1321 | 362 | for line in ip_output: | ||
1322 | 363 | if line.split()[1].startswith(int_type): | ||
1323 | 364 | matched = re.search('.*: (' + int_type + r'[0-9]+\.[0-9]+)@.*', line) | ||
1324 | 365 | if matched: | ||
1325 | 366 | interface = matched.groups()[0] | ||
1326 | 367 | else: | ||
1327 | 368 | interface = line.split()[1].replace(":", "") | ||
1328 | 369 | interfaces.append(interface) | ||
1329 | 370 | |||
1330 | 371 | return interfaces | ||
1331 | 372 | |||
1332 | 373 | |||
1333 | 374 | def set_nic_mtu(nic, mtu): | ||
1334 | 375 | '''Set MTU on a network interface''' | ||
1335 | 376 | cmd = ['ip', 'link', 'set', nic, 'mtu', mtu] | ||
1336 | 377 | subprocess.check_call(cmd) | ||
1337 | 378 | |||
1338 | 379 | |||
1339 | 380 | def get_nic_mtu(nic): | ||
1340 | 381 | cmd = ['ip', 'addr', 'show', nic] | ||
1341 | 382 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
1342 | 383 | mtu = "" | ||
1343 | 384 | for line in ip_output: | ||
1344 | 385 | words = line.split() | ||
1345 | 386 | if 'mtu' in words: | ||
1346 | 387 | mtu = words[words.index("mtu") + 1] | ||
1347 | 388 | return mtu | ||
1348 | 389 | |||
1349 | 390 | |||
1350 | 391 | def get_nic_hwaddr(nic): | ||
1351 | 392 | cmd = ['ip', '-o', '-0', 'addr', 'show', nic] | ||
1352 | 393 | ip_output = subprocess.check_output(cmd).decode('UTF-8') | ||
1353 | 394 | hwaddr = "" | ||
1354 | 395 | words = ip_output.split() | ||
1355 | 396 | if 'link/ether' in words: | ||
1356 | 397 | hwaddr = words[words.index('link/ether') + 1] | ||
1357 | 398 | return hwaddr | ||
1358 | 399 | |||
1359 | 400 | |||
1360 | 401 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
1361 | 402 | '''Compare supplied revno with the revno of the installed package | ||
1362 | 403 | |||
1363 | 404 | * 1 => Installed revno is greater than supplied arg | ||
1364 | 405 | * 0 => Installed revno is the same as supplied arg | ||
1365 | 406 | * -1 => Installed revno is less than supplied arg | ||
1366 | 407 | |||
1367 | 408 | This function imports apt_cache function from charmhelpers.fetch if | ||
1368 | 409 | the pkgcache argument is None. Be sure to add charmhelpers.fetch if | ||
1369 | 410 | you call this function, or pass an apt_pkg.Cache() instance. | ||
1370 | 411 | ''' | ||
1371 | 412 | import apt_pkg | ||
1372 | 413 | if not pkgcache: | ||
1373 | 414 | from charmhelpers.fetch import apt_cache | ||
1374 | 415 | pkgcache = apt_cache() | ||
1375 | 416 | pkg = pkgcache[package] | ||
1376 | 417 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | ||
1377 | 418 | |||
1378 | 419 | |||
1379 | 420 | @contextmanager | ||
1380 | 421 | def chdir(d): | ||
1381 | 422 | cur = os.getcwd() | ||
1382 | 423 | try: | ||
1383 | 424 | yield os.chdir(d) | ||
1384 | 425 | finally: | ||
1385 | 426 | os.chdir(cur) | ||
1386 | 427 | |||
1387 | 428 | |||
1388 | 429 | def chownr(path, owner, group, follow_links=True): | ||
1389 | 430 | uid = pwd.getpwnam(owner).pw_uid | ||
1390 | 431 | gid = grp.getgrnam(group).gr_gid | ||
1391 | 432 | if follow_links: | ||
1392 | 433 | chown = os.chown | ||
1393 | 434 | else: | ||
1394 | 435 | chown = os.lchown | ||
1395 | 436 | |||
1396 | 437 | for root, dirs, files in os.walk(path): | ||
1397 | 438 | for name in dirs + files: | ||
1398 | 439 | full = os.path.join(root, name) | ||
1399 | 440 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | ||
1400 | 441 | if not broken_symlink: | ||
1401 | 442 | chown(full, uid, gid) | ||
1402 | 443 | |||
1403 | 444 | |||
1404 | 445 | def lchownr(path, owner, group): | ||
1405 | 446 | chownr(path, owner, group, follow_links=False) | ||
1406 | 447 | 0 | ||
1407 | === removed directory 'hooks/charmhelpers/core/services' | |||
1408 | === removed file 'hooks/charmhelpers/core/services/__init__.py' | |||
1409 | --- hooks/charmhelpers/core/services/__init__.py 2015-02-19 16:21:31 +0000 | |||
1410 | +++ hooks/charmhelpers/core/services/__init__.py 1970-01-01 00:00:00 +0000 | |||
1411 | @@ -1,18 +0,0 @@ | |||
1412 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1413 | 2 | # | ||
1414 | 3 | # This file is part of charm-helpers. | ||
1415 | 4 | # | ||
1416 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1417 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1418 | 7 | # published by the Free Software Foundation. | ||
1419 | 8 | # | ||
1420 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1421 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1422 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1423 | 12 | # GNU Lesser General Public License for more details. | ||
1424 | 13 | # | ||
1425 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1426 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1427 | 16 | |||
1428 | 17 | from .base import * # NOQA | ||
1429 | 18 | from .helpers import * # NOQA | ||
1430 | 19 | 0 | ||
1431 | === removed file 'hooks/charmhelpers/core/services/base.py' | |||
1432 | --- hooks/charmhelpers/core/services/base.py 2015-02-19 16:21:31 +0000 | |||
1433 | +++ hooks/charmhelpers/core/services/base.py 1970-01-01 00:00:00 +0000 | |||
1434 | @@ -1,329 +0,0 @@ | |||
1435 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1436 | 2 | # | ||
1437 | 3 | # This file is part of charm-helpers. | ||
1438 | 4 | # | ||
1439 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1440 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1441 | 7 | # published by the Free Software Foundation. | ||
1442 | 8 | # | ||
1443 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1444 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1445 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1446 | 12 | # GNU Lesser General Public License for more details. | ||
1447 | 13 | # | ||
1448 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1449 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1450 | 16 | |||
1451 | 17 | import os | ||
1452 | 18 | import re | ||
1453 | 19 | import json | ||
1454 | 20 | from collections import Iterable | ||
1455 | 21 | |||
1456 | 22 | from charmhelpers.core import host | ||
1457 | 23 | from charmhelpers.core import hookenv | ||
1458 | 24 | |||
1459 | 25 | |||
1460 | 26 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
1461 | 27 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
1462 | 28 | 'service_restart', 'service_stop'] | ||
1463 | 29 | |||
1464 | 30 | |||
1465 | 31 | class ServiceManager(object): | ||
1466 | 32 | def __init__(self, services=None): | ||
1467 | 33 | """ | ||
1468 | 34 | Register a list of services, given their definitions. | ||
1469 | 35 | |||
1470 | 36 | Service definitions are dicts in the following formats (all keys except | ||
1471 | 37 | 'service' are optional):: | ||
1472 | 38 | |||
1473 | 39 | { | ||
1474 | 40 | "service": <service name>, | ||
1475 | 41 | "required_data": <list of required data contexts>, | ||
1476 | 42 | "provided_data": <list of provided data contexts>, | ||
1477 | 43 | "data_ready": <one or more callbacks>, | ||
1478 | 44 | "data_lost": <one or more callbacks>, | ||
1479 | 45 | "start": <one or more callbacks>, | ||
1480 | 46 | "stop": <one or more callbacks>, | ||
1481 | 47 | "ports": <list of ports to manage>, | ||
1482 | 48 | } | ||
1483 | 49 | |||
1484 | 50 | The 'required_data' list should contain dicts of required data (or | ||
1485 | 51 | dependency managers that act like dicts and know how to collect the data). | ||
1486 | 52 | Only when all items in the 'required_data' list are populated are the list | ||
1487 | 53 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
1488 | 54 | information. | ||
1489 | 55 | |||
1490 | 56 | The 'provided_data' list should contain relation data providers, most likely | ||
1491 | 57 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
1492 | 58 | that will indicate a set of data to set on a given relation. | ||
1493 | 59 | |||
1494 | 60 | The 'data_ready' value should be either a single callback, or a list of | ||
1495 | 61 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
1496 | 62 | Each callback will be called with the service name as the only parameter. | ||
1497 | 63 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
1498 | 64 | are fired. | ||
1499 | 65 | |||
1500 | 66 | The 'data_lost' value should be either a single callback, or a list of | ||
1501 | 67 | callbacks, to be called when a 'required_data' item no longer passes | ||
1502 | 68 | `is_ready()`. Each callback will be called with the service name as the | ||
1503 | 69 | only parameter. After all of the 'data_lost' callbacks are called, | ||
1504 | 70 | the 'stop' callbacks are fired. | ||
1505 | 71 | |||
1506 | 72 | The 'start' value should be either a single callback, or a list of | ||
1507 | 73 | callbacks, to be called when starting the service, after the 'data_ready' | ||
1508 | 74 | callbacks are complete. Each callback will be called with the service | ||
1509 | 75 | name as the only parameter. This defaults to | ||
1510 | 76 | `[host.service_start, services.open_ports]`. | ||
1511 | 77 | |||
1512 | 78 | The 'stop' value should be either a single callback, or a list of | ||
1513 | 79 | callbacks, to be called when stopping the service. If the service is | ||
1514 | 80 | being stopped because it no longer has all of its 'required_data', this | ||
1515 | 81 | will be called after all of the 'data_lost' callbacks are complete. | ||
1516 | 82 | Each callback will be called with the service name as the only parameter. | ||
1517 | 83 | This defaults to `[services.close_ports, host.service_stop]`. | ||
1518 | 84 | |||
1519 | 85 | The 'ports' value should be a list of ports to manage. The default | ||
1520 | 86 | 'start' handler will open the ports after the service is started, | ||
1521 | 87 | and the default 'stop' handler will close the ports prior to stopping | ||
1522 | 88 | the service. | ||
1523 | 89 | |||
1524 | 90 | |||
1525 | 91 | Examples: | ||
1526 | 92 | |||
1527 | 93 | The following registers an Upstart service called bingod that depends on | ||
1528 | 94 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
1529 | 95 | restarting the service, and a Runit service called spadesd:: | ||
1530 | 96 | |||
1531 | 97 | manager = services.ServiceManager([ | ||
1532 | 98 | { | ||
1533 | 99 | 'service': 'bingod', | ||
1534 | 100 | 'ports': [80, 443], | ||
1535 | 101 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
1536 | 102 | 'data_ready': [ | ||
1537 | 103 | services.template(source='bingod.conf'), | ||
1538 | 104 | services.template(source='bingod.ini', | ||
1539 | 105 | target='/etc/bingod.ini', | ||
1540 | 106 | owner='bingo', perms=0400), | ||
1541 | 107 | ], | ||
1542 | 108 | }, | ||
1543 | 109 | { | ||
1544 | 110 | 'service': 'spadesd', | ||
1545 | 111 | 'data_ready': services.template(source='spadesd_run.j2', | ||
1546 | 112 | target='/etc/sv/spadesd/run', | ||
1547 | 113 | perms=0555), | ||
1548 | 114 | 'start': runit_start, | ||
1549 | 115 | 'stop': runit_stop, | ||
1550 | 116 | }, | ||
1551 | 117 | ]) | ||
1552 | 118 | manager.manage() | ||
1553 | 119 | """ | ||
1554 | 120 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
1555 | 121 | self._ready = None | ||
1556 | 122 | self.services = {} | ||
1557 | 123 | for service in services or []: | ||
1558 | 124 | service_name = service['service'] | ||
1559 | 125 | self.services[service_name] = service | ||
1560 | 126 | |||
1561 | 127 | def manage(self): | ||
1562 | 128 | """ | ||
1563 | 129 | Handle the current hook by doing The Right Thing with the registered services. | ||
1564 | 130 | """ | ||
1565 | 131 | hook_name = hookenv.hook_name() | ||
1566 | 132 | if hook_name == 'stop': | ||
1567 | 133 | self.stop_services() | ||
1568 | 134 | else: | ||
1569 | 135 | self.provide_data() | ||
1570 | 136 | self.reconfigure_services() | ||
1571 | 137 | cfg = hookenv.config() | ||
1572 | 138 | if cfg.implicit_save: | ||
1573 | 139 | cfg.save() | ||
1574 | 140 | |||
1575 | 141 | def provide_data(self): | ||
1576 | 142 | """ | ||
1577 | 143 | Set the relation data for each provider in the ``provided_data`` list. | ||
1578 | 144 | |||
1579 | 145 | A provider must have a `name` attribute, which indicates which relation | ||
1580 | 146 | to set data on, and a `provide_data()` method, which returns a dict of | ||
1581 | 147 | data to set. | ||
1582 | 148 | """ | ||
1583 | 149 | hook_name = hookenv.hook_name() | ||
1584 | 150 | for service in self.services.values(): | ||
1585 | 151 | for provider in service.get('provided_data', []): | ||
1586 | 152 | if re.match(r'{}-relation-(joined|changed)'.format(provider.name), hook_name): | ||
1587 | 153 | data = provider.provide_data() | ||
1588 | 154 | _ready = provider._is_ready(data) if hasattr(provider, '_is_ready') else data | ||
1589 | 155 | if _ready: | ||
1590 | 156 | hookenv.relation_set(None, data) | ||
1591 | 157 | |||
1592 | 158 | def reconfigure_services(self, *service_names): | ||
1593 | 159 | """ | ||
1594 | 160 | Update all files for one or more registered services, and, | ||
1595 | 161 | if ready, optionally restart them. | ||
1596 | 162 | |||
1597 | 163 | If no service names are given, reconfigures all registered services. | ||
1598 | 164 | """ | ||
1599 | 165 | for service_name in service_names or self.services.keys(): | ||
1600 | 166 | if self.is_ready(service_name): | ||
1601 | 167 | self.fire_event('data_ready', service_name) | ||
1602 | 168 | self.fire_event('start', service_name, default=[ | ||
1603 | 169 | service_restart, | ||
1604 | 170 | manage_ports]) | ||
1605 | 171 | self.save_ready(service_name) | ||
1606 | 172 | else: | ||
1607 | 173 | if self.was_ready(service_name): | ||
1608 | 174 | self.fire_event('data_lost', service_name) | ||
1609 | 175 | self.fire_event('stop', service_name, default=[ | ||
1610 | 176 | manage_ports, | ||
1611 | 177 | service_stop]) | ||
1612 | 178 | self.save_lost(service_name) | ||
1613 | 179 | |||
1614 | 180 | def stop_services(self, *service_names): | ||
1615 | 181 | """ | ||
1616 | 182 | Stop one or more registered services, by name. | ||
1617 | 183 | |||
1618 | 184 | If no service names are given, stops all registered services. | ||
1619 | 185 | """ | ||
1620 | 186 | for service_name in service_names or self.services.keys(): | ||
1621 | 187 | self.fire_event('stop', service_name, default=[ | ||
1622 | 188 | manage_ports, | ||
1623 | 189 | service_stop]) | ||
1624 | 190 | |||
1625 | 191 | def get_service(self, service_name): | ||
1626 | 192 | """ | ||
1627 | 193 | Given the name of a registered service, return its service definition. | ||
1628 | 194 | """ | ||
1629 | 195 | service = self.services.get(service_name) | ||
1630 | 196 | if not service: | ||
1631 | 197 | raise KeyError('Service not registered: %s' % service_name) | ||
1632 | 198 | return service | ||
1633 | 199 | |||
1634 | 200 | def fire_event(self, event_name, service_name, default=None): | ||
1635 | 201 | """ | ||
1636 | 202 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
1637 | 203 | """ | ||
1638 | 204 | service = self.get_service(service_name) | ||
1639 | 205 | callbacks = service.get(event_name, default) | ||
1640 | 206 | if not callbacks: | ||
1641 | 207 | return | ||
1642 | 208 | if not isinstance(callbacks, Iterable): | ||
1643 | 209 | callbacks = [callbacks] | ||
1644 | 210 | for callback in callbacks: | ||
1645 | 211 | if isinstance(callback, ManagerCallback): | ||
1646 | 212 | callback(self, service_name, event_name) | ||
1647 | 213 | else: | ||
1648 | 214 | callback(service_name) | ||
1649 | 215 | |||
1650 | 216 | def is_ready(self, service_name): | ||
1651 | 217 | """ | ||
1652 | 218 | Determine if a registered service is ready, by checking its 'required_data'. | ||
1653 | 219 | |||
1654 | 220 | A 'required_data' item can be any mapping type, and is considered ready | ||
1655 | 221 | if `bool(item)` evaluates as True. | ||
1656 | 222 | """ | ||
1657 | 223 | service = self.get_service(service_name) | ||
1658 | 224 | reqs = service.get('required_data', []) | ||
1659 | 225 | return all(bool(req) for req in reqs) | ||
1660 | 226 | |||
1661 | 227 | def _load_ready_file(self): | ||
1662 | 228 | if self._ready is not None: | ||
1663 | 229 | return | ||
1664 | 230 | if os.path.exists(self._ready_file): | ||
1665 | 231 | with open(self._ready_file) as fp: | ||
1666 | 232 | self._ready = set(json.load(fp)) | ||
1667 | 233 | else: | ||
1668 | 234 | self._ready = set() | ||
1669 | 235 | |||
1670 | 236 | def _save_ready_file(self): | ||
1671 | 237 | if self._ready is None: | ||
1672 | 238 | return | ||
1673 | 239 | with open(self._ready_file, 'w') as fp: | ||
1674 | 240 | json.dump(list(self._ready), fp) | ||
1675 | 241 | |||
1676 | 242 | def save_ready(self, service_name): | ||
1677 | 243 | """ | ||
1678 | 244 | Save an indicator that the given service is now data_ready. | ||
1679 | 245 | """ | ||
1680 | 246 | self._load_ready_file() | ||
1681 | 247 | self._ready.add(service_name) | ||
1682 | 248 | self._save_ready_file() | ||
1683 | 249 | |||
1684 | 250 | def save_lost(self, service_name): | ||
1685 | 251 | """ | ||
1686 | 252 | Save an indicator that the given service is no longer data_ready. | ||
1687 | 253 | """ | ||
1688 | 254 | self._load_ready_file() | ||
1689 | 255 | self._ready.discard(service_name) | ||
1690 | 256 | self._save_ready_file() | ||
1691 | 257 | |||
1692 | 258 | def was_ready(self, service_name): | ||
1693 | 259 | """ | ||
1694 | 260 | Determine if the given service was previously data_ready. | ||
1695 | 261 | """ | ||
1696 | 262 | self._load_ready_file() | ||
1697 | 263 | return service_name in self._ready | ||
1698 | 264 | |||
1699 | 265 | |||
1700 | 266 | class ManagerCallback(object): | ||
1701 | 267 | """ | ||
1702 | 268 | Special case of a callback that takes the `ServiceManager` instance | ||
1703 | 269 | in addition to the service name. | ||
1704 | 270 | |||
1705 | 271 | Subclasses should implement `__call__` which should accept three parameters: | ||
1706 | 272 | |||
1707 | 273 | * `manager` The `ServiceManager` instance | ||
1708 | 274 | * `service_name` The name of the service it's being triggered for | ||
1709 | 275 | * `event_name` The name of the event that this callback is handling | ||
1710 | 276 | """ | ||
1711 | 277 | def __call__(self, manager, service_name, event_name): | ||
1712 | 278 | raise NotImplementedError() | ||
1713 | 279 | |||
1714 | 280 | |||
1715 | 281 | class PortManagerCallback(ManagerCallback): | ||
1716 | 282 | """ | ||
1717 | 283 | Callback class that will open or close ports, for use as either | ||
1718 | 284 | a start or stop action. | ||
1719 | 285 | """ | ||
1720 | 286 | def __call__(self, manager, service_name, event_name): | ||
1721 | 287 | service = manager.get_service(service_name) | ||
1722 | 288 | new_ports = service.get('ports', []) | ||
1723 | 289 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
1724 | 290 | if os.path.exists(port_file): | ||
1725 | 291 | with open(port_file) as fp: | ||
1726 | 292 | old_ports = fp.read().split(',') | ||
1727 | 293 | for old_port in old_ports: | ||
1728 | 294 | if bool(old_port): | ||
1729 | 295 | old_port = int(old_port) | ||
1730 | 296 | if old_port not in new_ports: | ||
1731 | 297 | hookenv.close_port(old_port) | ||
1732 | 298 | with open(port_file, 'w') as fp: | ||
1733 | 299 | fp.write(','.join(str(port) for port in new_ports)) | ||
1734 | 300 | for port in new_ports: | ||
1735 | 301 | if event_name == 'start': | ||
1736 | 302 | hookenv.open_port(port) | ||
1737 | 303 | elif event_name == 'stop': | ||
1738 | 304 | hookenv.close_port(port) | ||
1739 | 305 | |||
1740 | 306 | |||
1741 | 307 | def service_stop(service_name): | ||
1742 | 308 | """ | ||
1743 | 309 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
1744 | 310 | messages in the logs. | ||
1745 | 311 | """ | ||
1746 | 312 | if host.service_running(service_name): | ||
1747 | 313 | host.service_stop(service_name) | ||
1748 | 314 | |||
1749 | 315 | |||
1750 | 316 | def service_restart(service_name): | ||
1751 | 317 | """ | ||
1752 | 318 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
1753 | 319 | messages in the logs. | ||
1754 | 320 | """ | ||
1755 | 321 | if host.service_available(service_name): | ||
1756 | 322 | if host.service_running(service_name): | ||
1757 | 323 | host.service_restart(service_name) | ||
1758 | 324 | else: | ||
1759 | 325 | host.service_start(service_name) | ||
1760 | 326 | |||
1761 | 327 | |||
1762 | 328 | # Convenience aliases | ||
1763 | 329 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
1764 | 330 | 0 | ||
1765 | === removed file 'hooks/charmhelpers/core/services/helpers.py' | |||
1766 | --- hooks/charmhelpers/core/services/helpers.py 2015-02-19 16:21:31 +0000 | |||
1767 | +++ hooks/charmhelpers/core/services/helpers.py 1970-01-01 00:00:00 +0000 | |||
1768 | @@ -1,259 +0,0 @@ | |||
1769 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1770 | 2 | # | ||
1771 | 3 | # This file is part of charm-helpers. | ||
1772 | 4 | # | ||
1773 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1774 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1775 | 7 | # published by the Free Software Foundation. | ||
1776 | 8 | # | ||
1777 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1778 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1779 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1780 | 12 | # GNU Lesser General Public License for more details. | ||
1781 | 13 | # | ||
1782 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1783 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1784 | 16 | |||
1785 | 17 | import os | ||
1786 | 18 | import yaml | ||
1787 | 19 | from charmhelpers.core import hookenv | ||
1788 | 20 | from charmhelpers.core import templating | ||
1789 | 21 | |||
1790 | 22 | from charmhelpers.core.services.base import ManagerCallback | ||
1791 | 23 | |||
1792 | 24 | |||
1793 | 25 | __all__ = ['RelationContext', 'TemplateCallback', | ||
1794 | 26 | 'render_template', 'template'] | ||
1795 | 27 | |||
1796 | 28 | |||
1797 | 29 | class RelationContext(dict): | ||
1798 | 30 | """ | ||
1799 | 31 | Base class for a context generator that gets relation data from juju. | ||
1800 | 32 | |||
1801 | 33 | Subclasses must provide the attributes `name`, which is the name of the | ||
1802 | 34 | interface of interest, `interface`, which is the type of the interface of | ||
1803 | 35 | interest, and `required_keys`, which is the set of keys required for the | ||
1804 | 36 | relation to be considered complete. The data for all interfaces matching | ||
1805 | 37 | the `name` attribute that are complete will used to populate the dictionary | ||
1806 | 38 | values (see `get_data`, below). | ||
1807 | 39 | |||
1808 | 40 | The generated context will be namespaced under the relation :attr:`name`, | ||
1809 | 41 | to prevent potential naming conflicts. | ||
1810 | 42 | |||
1811 | 43 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1812 | 44 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1813 | 45 | """ | ||
1814 | 46 | name = None | ||
1815 | 47 | interface = None | ||
1816 | 48 | required_keys = [] | ||
1817 | 49 | |||
1818 | 50 | def __init__(self, name=None, additional_required_keys=None): | ||
1819 | 51 | if name is not None: | ||
1820 | 52 | self.name = name | ||
1821 | 53 | if additional_required_keys is not None: | ||
1822 | 54 | self.required_keys.extend(additional_required_keys) | ||
1823 | 55 | self.get_data() | ||
1824 | 56 | |||
1825 | 57 | def __bool__(self): | ||
1826 | 58 | """ | ||
1827 | 59 | Returns True if all of the required_keys are available. | ||
1828 | 60 | """ | ||
1829 | 61 | return self.is_ready() | ||
1830 | 62 | |||
1831 | 63 | __nonzero__ = __bool__ | ||
1832 | 64 | |||
1833 | 65 | def __repr__(self): | ||
1834 | 66 | return super(RelationContext, self).__repr__() | ||
1835 | 67 | |||
1836 | 68 | def is_ready(self): | ||
1837 | 69 | """ | ||
1838 | 70 | Returns True if all of the `required_keys` are available from any units. | ||
1839 | 71 | """ | ||
1840 | 72 | ready = len(self.get(self.name, [])) > 0 | ||
1841 | 73 | if not ready: | ||
1842 | 74 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
1843 | 75 | return ready | ||
1844 | 76 | |||
1845 | 77 | def _is_ready(self, unit_data): | ||
1846 | 78 | """ | ||
1847 | 79 | Helper method that tests a set of relation data and returns True if | ||
1848 | 80 | all of the `required_keys` are present. | ||
1849 | 81 | """ | ||
1850 | 82 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
1851 | 83 | |||
1852 | 84 | def get_data(self): | ||
1853 | 85 | """ | ||
1854 | 86 | Retrieve the relation data for each unit involved in a relation and, | ||
1855 | 87 | if complete, store it in a list under `self[self.name]`. This | ||
1856 | 88 | is automatically called when the RelationContext is instantiated. | ||
1857 | 89 | |||
1858 | 90 | The units are sorted lexographically first by the service ID, then by | ||
1859 | 91 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
1860 | 92 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
1861 | 93 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
1862 | 94 | set of data, the relation data for the units will be stored in the | ||
1863 | 95 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
1864 | 96 | |||
1865 | 97 | If you only care about a single unit on the relation, you can just | ||
1866 | 98 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
1867 | 99 | support multiple units on a relation, you should iterate over the list, | ||
1868 | 100 | like:: | ||
1869 | 101 | |||
1870 | 102 | {% for unit in interface -%} | ||
1871 | 103 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
1872 | 104 | {%- endfor %} | ||
1873 | 105 | |||
1874 | 106 | Note that since all sets of relation data from all related services and | ||
1875 | 107 | units are in a single list, if you need to know which service or unit a | ||
1876 | 108 | set of data came from, you'll need to extend this class to preserve | ||
1877 | 109 | that information. | ||
1878 | 110 | """ | ||
1879 | 111 | if not hookenv.relation_ids(self.name): | ||
1880 | 112 | return | ||
1881 | 113 | |||
1882 | 114 | ns = self.setdefault(self.name, []) | ||
1883 | 115 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
1884 | 116 | for unit in sorted(hookenv.related_units(rid)): | ||
1885 | 117 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
1886 | 118 | if self._is_ready(reldata): | ||
1887 | 119 | ns.append(reldata) | ||
1888 | 120 | |||
1889 | 121 | def provide_data(self): | ||
1890 | 122 | """ | ||
1891 | 123 | Return data to be relation_set for this interface. | ||
1892 | 124 | """ | ||
1893 | 125 | return {} | ||
1894 | 126 | |||
1895 | 127 | |||
1896 | 128 | class MysqlRelation(RelationContext): | ||
1897 | 129 | """ | ||
1898 | 130 | Relation context for the `mysql` interface. | ||
1899 | 131 | |||
1900 | 132 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1901 | 133 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1902 | 134 | """ | ||
1903 | 135 | name = 'db' | ||
1904 | 136 | interface = 'mysql' | ||
1905 | 137 | required_keys = ['host', 'user', 'password', 'database'] | ||
1906 | 138 | |||
1907 | 139 | |||
1908 | 140 | class HttpRelation(RelationContext): | ||
1909 | 141 | """ | ||
1910 | 142 | Relation context for the `http` interface. | ||
1911 | 143 | |||
1912 | 144 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1913 | 145 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1914 | 146 | """ | ||
1915 | 147 | name = 'website' | ||
1916 | 148 | interface = 'http' | ||
1917 | 149 | required_keys = ['host', 'port'] | ||
1918 | 150 | |||
1919 | 151 | def provide_data(self): | ||
1920 | 152 | return { | ||
1921 | 153 | 'host': hookenv.unit_get('private-address'), | ||
1922 | 154 | 'port': 80, | ||
1923 | 155 | } | ||
1924 | 156 | |||
1925 | 157 | |||
1926 | 158 | class RequiredConfig(dict): | ||
1927 | 159 | """ | ||
1928 | 160 | Data context that loads config options with one or more mandatory options. | ||
1929 | 161 | |||
1930 | 162 | Once the required options have been changed from their default values, all | ||
1931 | 163 | config options will be available, namespaced under `config` to prevent | ||
1932 | 164 | potential naming conflicts (for example, between a config option and a | ||
1933 | 165 | relation property). | ||
1934 | 166 | |||
1935 | 167 | :param list *args: List of options that must be changed from their default values. | ||
1936 | 168 | """ | ||
1937 | 169 | |||
1938 | 170 | def __init__(self, *args): | ||
1939 | 171 | self.required_options = args | ||
1940 | 172 | self['config'] = hookenv.config() | ||
1941 | 173 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
1942 | 174 | self.config = yaml.load(fp).get('options', {}) | ||
1943 | 175 | |||
1944 | 176 | def __bool__(self): | ||
1945 | 177 | for option in self.required_options: | ||
1946 | 178 | if option not in self['config']: | ||
1947 | 179 | return False | ||
1948 | 180 | current_value = self['config'][option] | ||
1949 | 181 | default_value = self.config[option].get('default') | ||
1950 | 182 | if current_value == default_value: | ||
1951 | 183 | return False | ||
1952 | 184 | if current_value in (None, '') and default_value in (None, ''): | ||
1953 | 185 | return False | ||
1954 | 186 | return True | ||
1955 | 187 | |||
1956 | 188 | def __nonzero__(self): | ||
1957 | 189 | return self.__bool__() | ||
1958 | 190 | |||
1959 | 191 | |||
1960 | 192 | class StoredContext(dict): | ||
1961 | 193 | """ | ||
1962 | 194 | A data context that always returns the data that it was first created with. | ||
1963 | 195 | |||
1964 | 196 | This is useful to do a one-time generation of things like passwords, that | ||
1965 | 197 | will thereafter use the same value that was originally generated, instead | ||
1966 | 198 | of generating a new value each time it is run. | ||
1967 | 199 | """ | ||
1968 | 200 | def __init__(self, file_name, config_data): | ||
1969 | 201 | """ | ||
1970 | 202 | If the file exists, populate `self` with the data from the file. | ||
1971 | 203 | Otherwise, populate with the given data and persist it to the file. | ||
1972 | 204 | """ | ||
1973 | 205 | if os.path.exists(file_name): | ||
1974 | 206 | self.update(self.read_context(file_name)) | ||
1975 | 207 | else: | ||
1976 | 208 | self.store_context(file_name, config_data) | ||
1977 | 209 | self.update(config_data) | ||
1978 | 210 | |||
1979 | 211 | def store_context(self, file_name, config_data): | ||
1980 | 212 | if not os.path.isabs(file_name): | ||
1981 | 213 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
1982 | 214 | with open(file_name, 'w') as file_stream: | ||
1983 | 215 | os.fchmod(file_stream.fileno(), 0o600) | ||
1984 | 216 | yaml.dump(config_data, file_stream) | ||
1985 | 217 | |||
1986 | 218 | def read_context(self, file_name): | ||
1987 | 219 | if not os.path.isabs(file_name): | ||
1988 | 220 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
1989 | 221 | with open(file_name, 'r') as file_stream: | ||
1990 | 222 | data = yaml.load(file_stream) | ||
1991 | 223 | if not data: | ||
1992 | 224 | raise OSError("%s is empty" % file_name) | ||
1993 | 225 | return data | ||
1994 | 226 | |||
1995 | 227 | |||
1996 | 228 | class TemplateCallback(ManagerCallback): | ||
1997 | 229 | """ | ||
1998 | 230 | Callback class that will render a Jinja2 template, for use as a ready | ||
1999 | 231 | action. | ||
2000 | 232 | |||
2001 | 233 | :param str source: The template source file, relative to | ||
2002 | 234 | `$CHARM_DIR/templates` | ||
2003 | 235 | |||
2004 | 236 | :param str target: The target to write the rendered template to | ||
2005 | 237 | :param str owner: The owner of the rendered file | ||
2006 | 238 | :param str group: The group of the rendered file | ||
2007 | 239 | :param int perms: The permissions of the rendered file | ||
2008 | 240 | """ | ||
2009 | 241 | def __init__(self, source, target, | ||
2010 | 242 | owner='root', group='root', perms=0o444): | ||
2011 | 243 | self.source = source | ||
2012 | 244 | self.target = target | ||
2013 | 245 | self.owner = owner | ||
2014 | 246 | self.group = group | ||
2015 | 247 | self.perms = perms | ||
2016 | 248 | |||
2017 | 249 | def __call__(self, manager, service_name, event_name): | ||
2018 | 250 | service = manager.get_service(service_name) | ||
2019 | 251 | context = {} | ||
2020 | 252 | for ctx in service.get('required_data', []): | ||
2021 | 253 | context.update(ctx) | ||
2022 | 254 | templating.render(self.source, self.target, context, | ||
2023 | 255 | self.owner, self.group, self.perms) | ||
2024 | 256 | |||
2025 | 257 | |||
2026 | 258 | # Convenience aliases for templates | ||
2027 | 259 | render_template = template = TemplateCallback | ||
2028 | 260 | 0 | ||
2029 | === removed file 'hooks/charmhelpers/core/strutils.py' | |||
2030 | --- hooks/charmhelpers/core/strutils.py 2015-02-19 16:21:31 +0000 | |||
2031 | +++ hooks/charmhelpers/core/strutils.py 1970-01-01 00:00:00 +0000 | |||
2032 | @@ -1,42 +0,0 @@ | |||
2033 | 1 | #!/usr/bin/env python | ||
2034 | 2 | # -*- coding: utf-8 -*- | ||
2035 | 3 | |||
2036 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
2037 | 5 | # | ||
2038 | 6 | # This file is part of charm-helpers. | ||
2039 | 7 | # | ||
2040 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2041 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2042 | 10 | # published by the Free Software Foundation. | ||
2043 | 11 | # | ||
2044 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
2045 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2046 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2047 | 15 | # GNU Lesser General Public License for more details. | ||
2048 | 16 | # | ||
2049 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
2050 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2051 | 19 | |||
2052 | 20 | import six | ||
2053 | 21 | |||
2054 | 22 | |||
2055 | 23 | def bool_from_string(value): | ||
2056 | 24 | """Interpret string value as boolean. | ||
2057 | 25 | |||
2058 | 26 | Returns True if value translates to True otherwise False. | ||
2059 | 27 | """ | ||
2060 | 28 | if isinstance(value, six.string_types): | ||
2061 | 29 | value = six.text_type(value) | ||
2062 | 30 | else: | ||
2063 | 31 | msg = "Unable to interpret non-string value '%s' as boolean" % (value) | ||
2064 | 32 | raise ValueError(msg) | ||
2065 | 33 | |||
2066 | 34 | value = value.strip().lower() | ||
2067 | 35 | |||
2068 | 36 | if value in ['y', 'yes', 'true', 't']: | ||
2069 | 37 | return True | ||
2070 | 38 | elif value in ['n', 'no', 'false', 'f']: | ||
2071 | 39 | return False | ||
2072 | 40 | |||
2073 | 41 | msg = "Unable to interpret string value '%s' as boolean" % (value) | ||
2074 | 42 | raise ValueError(msg) | ||
2075 | 43 | 0 | ||
2076 | === removed file 'hooks/charmhelpers/core/sysctl.py' | |||
2077 | --- hooks/charmhelpers/core/sysctl.py 2015-02-19 16:21:31 +0000 | |||
2078 | +++ hooks/charmhelpers/core/sysctl.py 1970-01-01 00:00:00 +0000 | |||
2079 | @@ -1,56 +0,0 @@ | |||
2080 | 1 | #!/usr/bin/env python | ||
2081 | 2 | # -*- coding: utf-8 -*- | ||
2082 | 3 | |||
2083 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
2084 | 5 | # | ||
2085 | 6 | # This file is part of charm-helpers. | ||
2086 | 7 | # | ||
2087 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2088 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2089 | 10 | # published by the Free Software Foundation. | ||
2090 | 11 | # | ||
2091 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
2092 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2093 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2094 | 15 | # GNU Lesser General Public License for more details. | ||
2095 | 16 | # | ||
2096 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
2097 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2098 | 19 | |||
2099 | 20 | import yaml | ||
2100 | 21 | |||
2101 | 22 | from subprocess import check_call | ||
2102 | 23 | |||
2103 | 24 | from charmhelpers.core.hookenv import ( | ||
2104 | 25 | log, | ||
2105 | 26 | DEBUG, | ||
2106 | 27 | ERROR, | ||
2107 | 28 | ) | ||
2108 | 29 | |||
2109 | 30 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
2110 | 31 | |||
2111 | 32 | |||
2112 | 33 | def create(sysctl_dict, sysctl_file): | ||
2113 | 34 | """Creates a sysctl.conf file from a YAML associative array | ||
2114 | 35 | |||
2115 | 36 | :param sysctl_dict: a YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" | ||
2116 | 37 | :type sysctl_dict: str | ||
2117 | 38 | :param sysctl_file: path to the sysctl file to be saved | ||
2118 | 39 | :type sysctl_file: str or unicode | ||
2119 | 40 | :returns: None | ||
2120 | 41 | """ | ||
2121 | 42 | try: | ||
2122 | 43 | sysctl_dict_parsed = yaml.safe_load(sysctl_dict) | ||
2123 | 44 | except yaml.YAMLError: | ||
2124 | 45 | log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict), | ||
2125 | 46 | level=ERROR) | ||
2126 | 47 | return | ||
2127 | 48 | |||
2128 | 49 | with open(sysctl_file, "w") as fd: | ||
2129 | 50 | for key, value in sysctl_dict_parsed.items(): | ||
2130 | 51 | fd.write("{}={}\n".format(key, value)) | ||
2131 | 52 | |||
2132 | 53 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict_parsed), | ||
2133 | 54 | level=DEBUG) | ||
2134 | 55 | |||
2135 | 56 | check_call(["sysctl", "-p", sysctl_file]) | ||
2136 | 57 | 0 | ||
2137 | === removed file 'hooks/charmhelpers/core/templating.py' | |||
2138 | --- hooks/charmhelpers/core/templating.py 2015-02-19 16:21:31 +0000 | |||
2139 | +++ hooks/charmhelpers/core/templating.py 1970-01-01 00:00:00 +0000 | |||
2140 | @@ -1,68 +0,0 @@ | |||
2141 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2142 | 2 | # | ||
2143 | 3 | # This file is part of charm-helpers. | ||
2144 | 4 | # | ||
2145 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2146 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2147 | 7 | # published by the Free Software Foundation. | ||
2148 | 8 | # | ||
2149 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2150 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2151 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2152 | 12 | # GNU Lesser General Public License for more details. | ||
2153 | 13 | # | ||
2154 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2155 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2156 | 16 | |||
2157 | 17 | import os | ||
2158 | 18 | |||
2159 | 19 | from charmhelpers.core import host | ||
2160 | 20 | from charmhelpers.core import hookenv | ||
2161 | 21 | |||
2162 | 22 | |||
2163 | 23 | def render(source, target, context, owner='root', group='root', | ||
2164 | 24 | perms=0o444, templates_dir=None, encoding='UTF-8'): | ||
2165 | 25 | """ | ||
2166 | 26 | Render a template. | ||
2167 | 27 | |||
2168 | 28 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
2169 | 29 | |||
2170 | 30 | The `target` path should be absolute. | ||
2171 | 31 | |||
2172 | 32 | The context should be a dict containing the values to be replaced in the | ||
2173 | 33 | template. | ||
2174 | 34 | |||
2175 | 35 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
2176 | 36 | |||
2177 | 37 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
2178 | 38 | |||
2179 | 39 | Note: Using this requires python-jinja2; if it is not installed, calling | ||
2180 | 40 | this will attempt to use charmhelpers.fetch.apt_install to install it. | ||
2181 | 41 | """ | ||
2182 | 42 | try: | ||
2183 | 43 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2184 | 44 | except ImportError: | ||
2185 | 45 | try: | ||
2186 | 46 | from charmhelpers.fetch import apt_install | ||
2187 | 47 | except ImportError: | ||
2188 | 48 | hookenv.log('Could not import jinja2, and could not import ' | ||
2189 | 49 | 'charmhelpers.fetch to install it', | ||
2190 | 50 | level=hookenv.ERROR) | ||
2191 | 51 | raise | ||
2192 | 52 | apt_install('python-jinja2', fatal=True) | ||
2193 | 53 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2194 | 54 | |||
2195 | 55 | if templates_dir is None: | ||
2196 | 56 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
2197 | 57 | loader = Environment(loader=FileSystemLoader(templates_dir)) | ||
2198 | 58 | try: | ||
2199 | 59 | source = source | ||
2200 | 60 | template = loader.get_template(source) | ||
2201 | 61 | except exceptions.TemplateNotFound as e: | ||
2202 | 62 | hookenv.log('Could not load template %s from %s.' % | ||
2203 | 63 | (source, templates_dir), | ||
2204 | 64 | level=hookenv.ERROR) | ||
2205 | 65 | raise e | ||
2206 | 66 | content = template.render(context) | ||
2207 | 67 | host.mkdir(os.path.dirname(target), owner, group, perms=0o755) | ||
2208 | 68 | host.write_file(target, content.encode(encoding), owner, group, perms) | ||
2209 | 69 | 0 | ||
2210 | === removed file 'hooks/charmhelpers/core/unitdata.py' | |||
2211 | --- hooks/charmhelpers/core/unitdata.py 2015-02-19 16:21:31 +0000 | |||
2212 | +++ hooks/charmhelpers/core/unitdata.py 1970-01-01 00:00:00 +0000 | |||
2213 | @@ -1,477 +0,0 @@ | |||
2214 | 1 | #!/usr/bin/env python | ||
2215 | 2 | # -*- coding: utf-8 -*- | ||
2216 | 3 | # | ||
2217 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
2218 | 5 | # | ||
2219 | 6 | # This file is part of charm-helpers. | ||
2220 | 7 | # | ||
2221 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2222 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2223 | 10 | # published by the Free Software Foundation. | ||
2224 | 11 | # | ||
2225 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
2226 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2227 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2228 | 15 | # GNU Lesser General Public License for more details. | ||
2229 | 16 | # | ||
2230 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
2231 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2232 | 19 | # | ||
2233 | 20 | # | ||
2234 | 21 | # Authors: | ||
2235 | 22 | # Kapil Thangavelu <kapil.foss@gmail.com> | ||
2236 | 23 | # | ||
2237 | 24 | """ | ||
2238 | 25 | Intro | ||
2239 | 26 | ----- | ||
2240 | 27 | |||
2241 | 28 | A simple way to store state in units. This provides a key value | ||
2242 | 29 | storage with support for versioned, transactional operation, | ||
2243 | 30 | and can calculate deltas from previous values to simplify unit logic | ||
2244 | 31 | when processing changes. | ||
2245 | 32 | |||
2246 | 33 | |||
2247 | 34 | Hook Integration | ||
2248 | 35 | ---------------- | ||
2249 | 36 | |||
2250 | 37 | There are several extant frameworks for hook execution, including | ||
2251 | 38 | |||
2252 | 39 | - charmhelpers.core.hookenv.Hooks | ||
2253 | 40 | - charmhelpers.core.services.ServiceManager | ||
2254 | 41 | |||
2255 | 42 | The storage classes are framework agnostic, one simple integration is | ||
2256 | 43 | via the HookData contextmanager. It will record the current hook | ||
2257 | 44 | execution environment (including relation data, config data, etc.), | ||
2258 | 45 | setup a transaction and allow easy access to the changes from | ||
2259 | 46 | previously seen values. One consequence of the integration is the | ||
2260 | 47 | reservation of particular keys ('rels', 'unit', 'env', 'config', | ||
2261 | 48 | 'charm_revisions') for their respective values. | ||
2262 | 49 | |||
2263 | 50 | Here's a fully worked integration example using hookenv.Hooks:: | ||
2264 | 51 | |||
2265 | 52 | from charmhelper.core import hookenv, unitdata | ||
2266 | 53 | |||
2267 | 54 | hook_data = unitdata.HookData() | ||
2268 | 55 | db = unitdata.kv() | ||
2269 | 56 | hooks = hookenv.Hooks() | ||
2270 | 57 | |||
2271 | 58 | @hooks.hook | ||
2272 | 59 | def config_changed(): | ||
2273 | 60 | # Print all changes to configuration from previously seen | ||
2274 | 61 | # values. | ||
2275 | 62 | for changed, (prev, cur) in hook_data.conf.items(): | ||
2276 | 63 | print('config changed', changed, | ||
2277 | 64 | 'previous value', prev, | ||
2278 | 65 | 'current value', cur) | ||
2279 | 66 | |||
2280 | 67 | # Get some unit specific bookeeping | ||
2281 | 68 | if not db.get('pkg_key'): | ||
2282 | 69 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
2283 | 70 | db.set('pkg_key', key) | ||
2284 | 71 | |||
2285 | 72 | # Directly access all charm config as a mapping. | ||
2286 | 73 | conf = db.getrange('config', True) | ||
2287 | 74 | |||
2288 | 75 | # Directly access all relation data as a mapping | ||
2289 | 76 | rels = db.getrange('rels', True) | ||
2290 | 77 | |||
2291 | 78 | if __name__ == '__main__': | ||
2292 | 79 | with hook_data(): | ||
2293 | 80 | hook.execute() | ||
2294 | 81 | |||
2295 | 82 | |||
2296 | 83 | A more basic integration is via the hook_scope context manager which simply | ||
2297 | 84 | manages transaction scope (and records hook name, and timestamp):: | ||
2298 | 85 | |||
2299 | 86 | >>> from unitdata import kv | ||
2300 | 87 | >>> db = kv() | ||
2301 | 88 | >>> with db.hook_scope('install'): | ||
2302 | 89 | ... # do work, in transactional scope. | ||
2303 | 90 | ... db.set('x', 1) | ||
2304 | 91 | >>> db.get('x') | ||
2305 | 92 | 1 | ||
2306 | 93 | |||
2307 | 94 | |||
2308 | 95 | Usage | ||
2309 | 96 | ----- | ||
2310 | 97 | |||
2311 | 98 | Values are automatically json de/serialized to preserve basic typing | ||
2312 | 99 | and complex data struct capabilities (dicts, lists, ints, booleans, etc). | ||
2313 | 100 | |||
2314 | 101 | Individual values can be manipulated via get/set:: | ||
2315 | 102 | |||
2316 | 103 | >>> kv.set('y', True) | ||
2317 | 104 | >>> kv.get('y') | ||
2318 | 105 | True | ||
2319 | 106 | |||
2320 | 107 | # We can set complex values (dicts, lists) as a single key. | ||
2321 | 108 | >>> kv.set('config', {'a': 1, 'b': True'}) | ||
2322 | 109 | |||
2323 | 110 | # Also supports returning dictionaries as a record which | ||
2324 | 111 | # provides attribute access. | ||
2325 | 112 | >>> config = kv.get('config', record=True) | ||
2326 | 113 | >>> config.b | ||
2327 | 114 | True | ||
2328 | 115 | |||
2329 | 116 | |||
2330 | 117 | Groups of keys can be manipulated with update/getrange:: | ||
2331 | 118 | |||
2332 | 119 | >>> kv.update({'z': 1, 'y': 2}, prefix="gui.") | ||
2333 | 120 | >>> kv.getrange('gui.', strip=True) | ||
2334 | 121 | {'z': 1, 'y': 2} | ||
2335 | 122 | |||
2336 | 123 | When updating values, its very helpful to understand which values | ||
2337 | 124 | have actually changed and how have they changed. The storage | ||
2338 | 125 | provides a delta method to provide for this:: | ||
2339 | 126 | |||
2340 | 127 | >>> data = {'debug': True, 'option': 2} | ||
2341 | 128 | >>> delta = kv.delta(data, 'config.') | ||
2342 | 129 | >>> delta.debug.previous | ||
2343 | 130 | None | ||
2344 | 131 | >>> delta.debug.current | ||
2345 | 132 | True | ||
2346 | 133 | >>> delta | ||
2347 | 134 | {'debug': (None, True), 'option': (None, 2)} | ||
2348 | 135 | |||
2349 | 136 | Note the delta method does not persist the actual change, it needs to | ||
2350 | 137 | be explicitly saved via 'update' method:: | ||
2351 | 138 | |||
2352 | 139 | >>> kv.update(data, 'config.') | ||
2353 | 140 | |||
2354 | 141 | Values modified in the context of a hook scope retain historical values | ||
2355 | 142 | associated to the hookname. | ||
2356 | 143 | |||
2357 | 144 | >>> with db.hook_scope('config-changed'): | ||
2358 | 145 | ... db.set('x', 42) | ||
2359 | 146 | >>> db.gethistory('x') | ||
2360 | 147 | [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'), | ||
2361 | 148 | (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')] | ||
2362 | 149 | |||
2363 | 150 | """ | ||
2364 | 151 | |||
2365 | 152 | import collections | ||
2366 | 153 | import contextlib | ||
2367 | 154 | import datetime | ||
2368 | 155 | import json | ||
2369 | 156 | import os | ||
2370 | 157 | import pprint | ||
2371 | 158 | import sqlite3 | ||
2372 | 159 | import sys | ||
2373 | 160 | |||
2374 | 161 | __author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>' | ||
2375 | 162 | |||
2376 | 163 | |||
2377 | 164 | class Storage(object): | ||
2378 | 165 | """Simple key value database for local unit state within charms. | ||
2379 | 166 | |||
2380 | 167 | Modifications are automatically committed at hook exit. That's | ||
2381 | 168 | currently regardless of exit code. | ||
2382 | 169 | |||
2383 | 170 | To support dicts, lists, integer, floats, and booleans values | ||
2384 | 171 | are automatically json encoded/decoded. | ||
2385 | 172 | """ | ||
2386 | 173 | def __init__(self, path=None): | ||
2387 | 174 | self.db_path = path | ||
2388 | 175 | if path is None: | ||
2389 | 176 | self.db_path = os.path.join( | ||
2390 | 177 | os.environ.get('CHARM_DIR', ''), '.unit-state.db') | ||
2391 | 178 | self.conn = sqlite3.connect('%s' % self.db_path) | ||
2392 | 179 | self.cursor = self.conn.cursor() | ||
2393 | 180 | self.revision = None | ||
2394 | 181 | self._closed = False | ||
2395 | 182 | self._init() | ||
2396 | 183 | |||
2397 | 184 | def close(self): | ||
2398 | 185 | if self._closed: | ||
2399 | 186 | return | ||
2400 | 187 | self.flush(False) | ||
2401 | 188 | self.cursor.close() | ||
2402 | 189 | self.conn.close() | ||
2403 | 190 | self._closed = True | ||
2404 | 191 | |||
2405 | 192 | def _scoped_query(self, stmt, params=None): | ||
2406 | 193 | if params is None: | ||
2407 | 194 | params = [] | ||
2408 | 195 | return stmt, params | ||
2409 | 196 | |||
2410 | 197 | def get(self, key, default=None, record=False): | ||
2411 | 198 | self.cursor.execute( | ||
2412 | 199 | *self._scoped_query( | ||
2413 | 200 | 'select data from kv where key=?', [key])) | ||
2414 | 201 | result = self.cursor.fetchone() | ||
2415 | 202 | if not result: | ||
2416 | 203 | return default | ||
2417 | 204 | if record: | ||
2418 | 205 | return Record(json.loads(result[0])) | ||
2419 | 206 | return json.loads(result[0]) | ||
2420 | 207 | |||
2421 | 208 | def getrange(self, key_prefix, strip=False): | ||
2422 | 209 | stmt = "select key, data from kv where key like '%s%%'" % key_prefix | ||
2423 | 210 | self.cursor.execute(*self._scoped_query(stmt)) | ||
2424 | 211 | result = self.cursor.fetchall() | ||
2425 | 212 | |||
2426 | 213 | if not result: | ||
2427 | 214 | return None | ||
2428 | 215 | if not strip: | ||
2429 | 216 | key_prefix = '' | ||
2430 | 217 | return dict([ | ||
2431 | 218 | (k[len(key_prefix):], json.loads(v)) for k, v in result]) | ||
2432 | 219 | |||
2433 | 220 | def update(self, mapping, prefix=""): | ||
2434 | 221 | for k, v in mapping.items(): | ||
2435 | 222 | self.set("%s%s" % (prefix, k), v) | ||
2436 | 223 | |||
2437 | 224 | def unset(self, key): | ||
2438 | 225 | self.cursor.execute('delete from kv where key=?', [key]) | ||
2439 | 226 | if self.revision and self.cursor.rowcount: | ||
2440 | 227 | self.cursor.execute( | ||
2441 | 228 | 'insert into kv_revisions values (?, ?, ?)', | ||
2442 | 229 | [key, self.revision, json.dumps('DELETED')]) | ||
2443 | 230 | |||
2444 | 231 | def set(self, key, value): | ||
2445 | 232 | serialized = json.dumps(value) | ||
2446 | 233 | |||
2447 | 234 | self.cursor.execute( | ||
2448 | 235 | 'select data from kv where key=?', [key]) | ||
2449 | 236 | exists = self.cursor.fetchone() | ||
2450 | 237 | |||
2451 | 238 | # Skip mutations to the same value | ||
2452 | 239 | if exists: | ||
2453 | 240 | if exists[0] == serialized: | ||
2454 | 241 | return value | ||
2455 | 242 | |||
2456 | 243 | if not exists: | ||
2457 | 244 | self.cursor.execute( | ||
2458 | 245 | 'insert into kv (key, data) values (?, ?)', | ||
2459 | 246 | (key, serialized)) | ||
2460 | 247 | else: | ||
2461 | 248 | self.cursor.execute(''' | ||
2462 | 249 | update kv | ||
2463 | 250 | set data = ? | ||
2464 | 251 | where key = ?''', [serialized, key]) | ||
2465 | 252 | |||
2466 | 253 | # Save | ||
2467 | 254 | if not self.revision: | ||
2468 | 255 | return value | ||
2469 | 256 | |||
2470 | 257 | self.cursor.execute( | ||
2471 | 258 | 'select 1 from kv_revisions where key=? and revision=?', | ||
2472 | 259 | [key, self.revision]) | ||
2473 | 260 | exists = self.cursor.fetchone() | ||
2474 | 261 | |||
2475 | 262 | if not exists: | ||
2476 | 263 | self.cursor.execute( | ||
2477 | 264 | '''insert into kv_revisions ( | ||
2478 | 265 | revision, key, data) values (?, ?, ?)''', | ||
2479 | 266 | (self.revision, key, serialized)) | ||
2480 | 267 | else: | ||
2481 | 268 | self.cursor.execute( | ||
2482 | 269 | ''' | ||
2483 | 270 | update kv_revisions | ||
2484 | 271 | set data = ? | ||
2485 | 272 | where key = ? | ||
2486 | 273 | and revision = ?''', | ||
2487 | 274 | [serialized, key, self.revision]) | ||
2488 | 275 | |||
2489 | 276 | return value | ||
2490 | 277 | |||
2491 | 278 | def delta(self, mapping, prefix): | ||
2492 | 279 | """ | ||
2493 | 280 | return a delta containing values that have changed. | ||
2494 | 281 | """ | ||
2495 | 282 | previous = self.getrange(prefix, strip=True) | ||
2496 | 283 | if not previous: | ||
2497 | 284 | pk = set() | ||
2498 | 285 | else: | ||
2499 | 286 | pk = set(previous.keys()) | ||
2500 | 287 | ck = set(mapping.keys()) | ||
2501 | 288 | delta = DeltaSet() | ||
2502 | 289 | |||
2503 | 290 | # added | ||
2504 | 291 | for k in ck.difference(pk): | ||
2505 | 292 | delta[k] = Delta(None, mapping[k]) | ||
2506 | 293 | |||
2507 | 294 | # removed | ||
2508 | 295 | for k in pk.difference(ck): | ||
2509 | 296 | delta[k] = Delta(previous[k], None) | ||
2510 | 297 | |||
2511 | 298 | # changed | ||
2512 | 299 | for k in pk.intersection(ck): | ||
2513 | 300 | c = mapping[k] | ||
2514 | 301 | p = previous[k] | ||
2515 | 302 | if c != p: | ||
2516 | 303 | delta[k] = Delta(p, c) | ||
2517 | 304 | |||
2518 | 305 | return delta | ||
2519 | 306 | |||
2520 | 307 | @contextlib.contextmanager | ||
2521 | 308 | def hook_scope(self, name=""): | ||
2522 | 309 | """Scope all future interactions to the current hook execution | ||
2523 | 310 | revision.""" | ||
2524 | 311 | assert not self.revision | ||
2525 | 312 | self.cursor.execute( | ||
2526 | 313 | 'insert into hooks (hook, date) values (?, ?)', | ||
2527 | 314 | (name or sys.argv[0], | ||
2528 | 315 | datetime.datetime.utcnow().isoformat())) | ||
2529 | 316 | self.revision = self.cursor.lastrowid | ||
2530 | 317 | try: | ||
2531 | 318 | yield self.revision | ||
2532 | 319 | self.revision = None | ||
2533 | 320 | except: | ||
2534 | 321 | self.flush(False) | ||
2535 | 322 | self.revision = None | ||
2536 | 323 | raise | ||
2537 | 324 | else: | ||
2538 | 325 | self.flush() | ||
2539 | 326 | |||
2540 | 327 | def flush(self, save=True): | ||
2541 | 328 | if save: | ||
2542 | 329 | self.conn.commit() | ||
2543 | 330 | elif self._closed: | ||
2544 | 331 | return | ||
2545 | 332 | else: | ||
2546 | 333 | self.conn.rollback() | ||
2547 | 334 | |||
2548 | 335 | def _init(self): | ||
2549 | 336 | self.cursor.execute(''' | ||
2550 | 337 | create table if not exists kv ( | ||
2551 | 338 | key text, | ||
2552 | 339 | data text, | ||
2553 | 340 | primary key (key) | ||
2554 | 341 | )''') | ||
2555 | 342 | self.cursor.execute(''' | ||
2556 | 343 | create table if not exists kv_revisions ( | ||
2557 | 344 | key text, | ||
2558 | 345 | revision integer, | ||
2559 | 346 | data text, | ||
2560 | 347 | primary key (key, revision) | ||
2561 | 348 | )''') | ||
2562 | 349 | self.cursor.execute(''' | ||
2563 | 350 | create table if not exists hooks ( | ||
2564 | 351 | version integer primary key autoincrement, | ||
2565 | 352 | hook text, | ||
2566 | 353 | date text | ||
2567 | 354 | )''') | ||
2568 | 355 | self.conn.commit() | ||
2569 | 356 | |||
2570 | 357 | def gethistory(self, key, deserialize=False): | ||
2571 | 358 | self.cursor.execute( | ||
2572 | 359 | ''' | ||
2573 | 360 | select kv.revision, kv.key, kv.data, h.hook, h.date | ||
2574 | 361 | from kv_revisions kv, | ||
2575 | 362 | hooks h | ||
2576 | 363 | where kv.key=? | ||
2577 | 364 | and kv.revision = h.version | ||
2578 | 365 | ''', [key]) | ||
2579 | 366 | if deserialize is False: | ||
2580 | 367 | return self.cursor.fetchall() | ||
2581 | 368 | return map(_parse_history, self.cursor.fetchall()) | ||
2582 | 369 | |||
2583 | 370 | def debug(self, fh=sys.stderr): | ||
2584 | 371 | self.cursor.execute('select * from kv') | ||
2585 | 372 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
2586 | 373 | self.cursor.execute('select * from kv_revisions') | ||
2587 | 374 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
2588 | 375 | |||
2589 | 376 | |||
2590 | 377 | def _parse_history(d): | ||
2591 | 378 | return (d[0], d[1], json.loads(d[2]), d[3], | ||
2592 | 379 | datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f")) | ||
2593 | 380 | |||
2594 | 381 | |||
2595 | 382 | class HookData(object): | ||
2596 | 383 | """Simple integration for existing hook exec frameworks. | ||
2597 | 384 | |||
2598 | 385 | Records all unit information, and stores deltas for processing | ||
2599 | 386 | by the hook. | ||
2600 | 387 | |||
2601 | 388 | Sample:: | ||
2602 | 389 | |||
2603 | 390 | from charmhelper.core import hookenv, unitdata | ||
2604 | 391 | |||
2605 | 392 | changes = unitdata.HookData() | ||
2606 | 393 | db = unitdata.kv() | ||
2607 | 394 | hooks = hookenv.Hooks() | ||
2608 | 395 | |||
2609 | 396 | @hooks.hook | ||
2610 | 397 | def config_changed(): | ||
2611 | 398 | # View all changes to configuration | ||
2612 | 399 | for changed, (prev, cur) in changes.conf.items(): | ||
2613 | 400 | print('config changed', changed, | ||
2614 | 401 | 'previous value', prev, | ||
2615 | 402 | 'current value', cur) | ||
2616 | 403 | |||
2617 | 404 | # Get some unit specific bookeeping | ||
2618 | 405 | if not db.get('pkg_key'): | ||
2619 | 406 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
2620 | 407 | db.set('pkg_key', key) | ||
2621 | 408 | |||
2622 | 409 | if __name__ == '__main__': | ||
2623 | 410 | with changes(): | ||
2624 | 411 | hook.execute() | ||
2625 | 412 | |||
2626 | 413 | """ | ||
2627 | 414 | def __init__(self): | ||
2628 | 415 | self.kv = kv() | ||
2629 | 416 | self.conf = None | ||
2630 | 417 | self.rels = None | ||
2631 | 418 | |||
2632 | 419 | @contextlib.contextmanager | ||
2633 | 420 | def __call__(self): | ||
2634 | 421 | from charmhelpers.core import hookenv | ||
2635 | 422 | hook_name = hookenv.hook_name() | ||
2636 | 423 | |||
2637 | 424 | with self.kv.hook_scope(hook_name): | ||
2638 | 425 | self._record_charm_version(hookenv.charm_dir()) | ||
2639 | 426 | delta_config, delta_relation = self._record_hook(hookenv) | ||
2640 | 427 | yield self.kv, delta_config, delta_relation | ||
2641 | 428 | |||
2642 | 429 | def _record_charm_version(self, charm_dir): | ||
2643 | 430 | # Record revisions.. charm revisions are meaningless | ||
2644 | 431 | # to charm authors as they don't control the revision. | ||
2645 | 432 | # so logic dependnent on revision is not particularly | ||
2646 | 433 | # useful, however it is useful for debugging analysis. | ||
2647 | 434 | charm_rev = open( | ||
2648 | 435 | os.path.join(charm_dir, 'revision')).read().strip() | ||
2649 | 436 | charm_rev = charm_rev or '0' | ||
2650 | 437 | revs = self.kv.get('charm_revisions', []) | ||
2651 | 438 | if charm_rev not in revs: | ||
2652 | 439 | revs.append(charm_rev.strip() or '0') | ||
2653 | 440 | self.kv.set('charm_revisions', revs) | ||
2654 | 441 | |||
2655 | 442 | def _record_hook(self, hookenv): | ||
2656 | 443 | data = hookenv.execution_environment() | ||
2657 | 444 | self.conf = conf_delta = self.kv.delta(data['conf'], 'config') | ||
2658 | 445 | self.rels = rels_delta = self.kv.delta(data['rels'], 'rels') | ||
2659 | 446 | self.kv.set('env', data['env']) | ||
2660 | 447 | self.kv.set('unit', data['unit']) | ||
2661 | 448 | self.kv.set('relid', data.get('relid')) | ||
2662 | 449 | return conf_delta, rels_delta | ||
2663 | 450 | |||
2664 | 451 | |||
2665 | 452 | class Record(dict): | ||
2666 | 453 | |||
2667 | 454 | __slots__ = () | ||
2668 | 455 | |||
2669 | 456 | def __getattr__(self, k): | ||
2670 | 457 | if k in self: | ||
2671 | 458 | return self[k] | ||
2672 | 459 | raise AttributeError(k) | ||
2673 | 460 | |||
2674 | 461 | |||
2675 | 462 | class DeltaSet(Record): | ||
2676 | 463 | |||
2677 | 464 | __slots__ = () | ||
2678 | 465 | |||
2679 | 466 | |||
2680 | 467 | Delta = collections.namedtuple('Delta', ['previous', 'current']) | ||
2681 | 468 | |||
2682 | 469 | |||
2683 | 470 | _KV = None | ||
2684 | 471 | |||
2685 | 472 | |||
2686 | 473 | def kv(): | ||
2687 | 474 | global _KV | ||
2688 | 475 | if _KV is None: | ||
2689 | 476 | _KV = Storage() | ||
2690 | 477 | return _KV | ||
2691 | 478 | 0 | ||
2692 | === removed directory 'hooks/charmhelpers/fetch' | |||
2693 | === removed file 'hooks/charmhelpers/fetch/__init__.py' | |||
2694 | --- hooks/charmhelpers/fetch/__init__.py 2015-02-19 16:21:31 +0000 | |||
2695 | +++ hooks/charmhelpers/fetch/__init__.py 1970-01-01 00:00:00 +0000 | |||
2696 | @@ -1,439 +0,0 @@ | |||
2697 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2698 | 2 | # | ||
2699 | 3 | # This file is part of charm-helpers. | ||
2700 | 4 | # | ||
2701 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2702 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2703 | 7 | # published by the Free Software Foundation. | ||
2704 | 8 | # | ||
2705 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2706 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2707 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2708 | 12 | # GNU Lesser General Public License for more details. | ||
2709 | 13 | # | ||
2710 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2711 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2712 | 16 | |||
2713 | 17 | import importlib | ||
2714 | 18 | from tempfile import NamedTemporaryFile | ||
2715 | 19 | import time | ||
2716 | 20 | from yaml import safe_load | ||
2717 | 21 | from charmhelpers.core.host import ( | ||
2718 | 22 | lsb_release | ||
2719 | 23 | ) | ||
2720 | 24 | import subprocess | ||
2721 | 25 | from charmhelpers.core.hookenv import ( | ||
2722 | 26 | config, | ||
2723 | 27 | log, | ||
2724 | 28 | ) | ||
2725 | 29 | import os | ||
2726 | 30 | |||
2727 | 31 | import six | ||
2728 | 32 | if six.PY3: | ||
2729 | 33 | from urllib.parse import urlparse, urlunparse | ||
2730 | 34 | else: | ||
2731 | 35 | from urlparse import urlparse, urlunparse | ||
2732 | 36 | |||
2733 | 37 | |||
2734 | 38 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive | ||
2735 | 39 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main | ||
2736 | 40 | """ | ||
2737 | 41 | PROPOSED_POCKET = """# Proposed | ||
2738 | 42 | deb http://archive.ubuntu.com/ubuntu {}-proposed main universe multiverse restricted | ||
2739 | 43 | """ | ||
2740 | 44 | CLOUD_ARCHIVE_POCKETS = { | ||
2741 | 45 | # Folsom | ||
2742 | 46 | 'folsom': 'precise-updates/folsom', | ||
2743 | 47 | 'precise-folsom': 'precise-updates/folsom', | ||
2744 | 48 | 'precise-folsom/updates': 'precise-updates/folsom', | ||
2745 | 49 | 'precise-updates/folsom': 'precise-updates/folsom', | ||
2746 | 50 | 'folsom/proposed': 'precise-proposed/folsom', | ||
2747 | 51 | 'precise-folsom/proposed': 'precise-proposed/folsom', | ||
2748 | 52 | 'precise-proposed/folsom': 'precise-proposed/folsom', | ||
2749 | 53 | # Grizzly | ||
2750 | 54 | 'grizzly': 'precise-updates/grizzly', | ||
2751 | 55 | 'precise-grizzly': 'precise-updates/grizzly', | ||
2752 | 56 | 'precise-grizzly/updates': 'precise-updates/grizzly', | ||
2753 | 57 | 'precise-updates/grizzly': 'precise-updates/grizzly', | ||
2754 | 58 | 'grizzly/proposed': 'precise-proposed/grizzly', | ||
2755 | 59 | 'precise-grizzly/proposed': 'precise-proposed/grizzly', | ||
2756 | 60 | 'precise-proposed/grizzly': 'precise-proposed/grizzly', | ||
2757 | 61 | # Havana | ||
2758 | 62 | 'havana': 'precise-updates/havana', | ||
2759 | 63 | 'precise-havana': 'precise-updates/havana', | ||
2760 | 64 | 'precise-havana/updates': 'precise-updates/havana', | ||
2761 | 65 | 'precise-updates/havana': 'precise-updates/havana', | ||
2762 | 66 | 'havana/proposed': 'precise-proposed/havana', | ||
2763 | 67 | 'precise-havana/proposed': 'precise-proposed/havana', | ||
2764 | 68 | 'precise-proposed/havana': 'precise-proposed/havana', | ||
2765 | 69 | # Icehouse | ||
2766 | 70 | 'icehouse': 'precise-updates/icehouse', | ||
2767 | 71 | 'precise-icehouse': 'precise-updates/icehouse', | ||
2768 | 72 | 'precise-icehouse/updates': 'precise-updates/icehouse', | ||
2769 | 73 | 'precise-updates/icehouse': 'precise-updates/icehouse', | ||
2770 | 74 | 'icehouse/proposed': 'precise-proposed/icehouse', | ||
2771 | 75 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', | ||
2772 | 76 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', | ||
2773 | 77 | # Juno | ||
2774 | 78 | 'juno': 'trusty-updates/juno', | ||
2775 | 79 | 'trusty-juno': 'trusty-updates/juno', | ||
2776 | 80 | 'trusty-juno/updates': 'trusty-updates/juno', | ||
2777 | 81 | 'trusty-updates/juno': 'trusty-updates/juno', | ||
2778 | 82 | 'juno/proposed': 'trusty-proposed/juno', | ||
2779 | 83 | 'trusty-juno/proposed': 'trusty-proposed/juno', | ||
2780 | 84 | 'trusty-proposed/juno': 'trusty-proposed/juno', | ||
2781 | 85 | # Kilo | ||
2782 | 86 | 'kilo': 'trusty-updates/kilo', | ||
2783 | 87 | 'trusty-kilo': 'trusty-updates/kilo', | ||
2784 | 88 | 'trusty-kilo/updates': 'trusty-updates/kilo', | ||
2785 | 89 | 'trusty-updates/kilo': 'trusty-updates/kilo', | ||
2786 | 90 | 'kilo/proposed': 'trusty-proposed/kilo', | ||
2787 | 91 | 'trusty-kilo/proposed': 'trusty-proposed/kilo', | ||
2788 | 92 | 'trusty-proposed/kilo': 'trusty-proposed/kilo', | ||
2789 | 93 | } | ||
2790 | 94 | |||
2791 | 95 | # The order of this list is very important. Handlers should be listed in from | ||
2792 | 96 | # least- to most-specific URL matching. | ||
2793 | 97 | FETCH_HANDLERS = ( | ||
2794 | 98 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
2795 | 99 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
2796 | 100 | 'charmhelpers.fetch.giturl.GitUrlFetchHandler', | ||
2797 | 101 | ) | ||
2798 | 102 | |||
2799 | 103 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. | ||
2800 | 104 | APT_NO_LOCK_RETRY_DELAY = 10 # Wait 10 seconds between apt lock checks. | ||
2801 | 105 | APT_NO_LOCK_RETRY_COUNT = 30 # Retry to acquire the lock X times. | ||
2802 | 106 | |||
2803 | 107 | |||
2804 | 108 | class SourceConfigError(Exception): | ||
2805 | 109 | pass | ||
2806 | 110 | |||
2807 | 111 | |||
2808 | 112 | class UnhandledSource(Exception): | ||
2809 | 113 | pass | ||
2810 | 114 | |||
2811 | 115 | |||
2812 | 116 | class AptLockError(Exception): | ||
2813 | 117 | pass | ||
2814 | 118 | |||
2815 | 119 | |||
2816 | 120 | class BaseFetchHandler(object): | ||
2817 | 121 | |||
2818 | 122 | """Base class for FetchHandler implementations in fetch plugins""" | ||
2819 | 123 | |||
2820 | 124 | def can_handle(self, source): | ||
2821 | 125 | """Returns True if the source can be handled. Otherwise returns | ||
2822 | 126 | a string explaining why it cannot""" | ||
2823 | 127 | return "Wrong source type" | ||
2824 | 128 | |||
2825 | 129 | def install(self, source): | ||
2826 | 130 | """Try to download and unpack the source. Return the path to the | ||
2827 | 131 | unpacked files or raise UnhandledSource.""" | ||
2828 | 132 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
2829 | 133 | |||
2830 | 134 | def parse_url(self, url): | ||
2831 | 135 | return urlparse(url) | ||
2832 | 136 | |||
2833 | 137 | def base_url(self, url): | ||
2834 | 138 | """Return url without querystring or fragment""" | ||
2835 | 139 | parts = list(self.parse_url(url)) | ||
2836 | 140 | parts[4:] = ['' for i in parts[4:]] | ||
2837 | 141 | return urlunparse(parts) | ||
2838 | 142 | |||
2839 | 143 | |||
2840 | 144 | def filter_installed_packages(packages): | ||
2841 | 145 | """Returns a list of packages that require installation""" | ||
2842 | 146 | cache = apt_cache() | ||
2843 | 147 | _pkgs = [] | ||
2844 | 148 | for package in packages: | ||
2845 | 149 | try: | ||
2846 | 150 | p = cache[package] | ||
2847 | 151 | p.current_ver or _pkgs.append(package) | ||
2848 | 152 | except KeyError: | ||
2849 | 153 | log('Package {} has no installation candidate.'.format(package), | ||
2850 | 154 | level='WARNING') | ||
2851 | 155 | _pkgs.append(package) | ||
2852 | 156 | return _pkgs | ||
2853 | 157 | |||
2854 | 158 | |||
2855 | 159 | def apt_cache(in_memory=True): | ||
2856 | 160 | """Build and return an apt cache""" | ||
2857 | 161 | import apt_pkg | ||
2858 | 162 | apt_pkg.init() | ||
2859 | 163 | if in_memory: | ||
2860 | 164 | apt_pkg.config.set("Dir::Cache::pkgcache", "") | ||
2861 | 165 | apt_pkg.config.set("Dir::Cache::srcpkgcache", "") | ||
2862 | 166 | return apt_pkg.Cache() | ||
2863 | 167 | |||
2864 | 168 | |||
2865 | 169 | def apt_install(packages, options=None, fatal=False): | ||
2866 | 170 | """Install one or more packages""" | ||
2867 | 171 | if options is None: | ||
2868 | 172 | options = ['--option=Dpkg::Options::=--force-confold'] | ||
2869 | 173 | |||
2870 | 174 | cmd = ['apt-get', '--assume-yes'] | ||
2871 | 175 | cmd.extend(options) | ||
2872 | 176 | cmd.append('install') | ||
2873 | 177 | if isinstance(packages, six.string_types): | ||
2874 | 178 | cmd.append(packages) | ||
2875 | 179 | else: | ||
2876 | 180 | cmd.extend(packages) | ||
2877 | 181 | log("Installing {} with options: {}".format(packages, | ||
2878 | 182 | options)) | ||
2879 | 183 | _run_apt_command(cmd, fatal) | ||
2880 | 184 | |||
2881 | 185 | |||
2882 | 186 | def apt_upgrade(options=None, fatal=False, dist=False): | ||
2883 | 187 | """Upgrade all packages""" | ||
2884 | 188 | if options is None: | ||
2885 | 189 | options = ['--option=Dpkg::Options::=--force-confold'] | ||
2886 | 190 | |||
2887 | 191 | cmd = ['apt-get', '--assume-yes'] | ||
2888 | 192 | cmd.extend(options) | ||
2889 | 193 | if dist: | ||
2890 | 194 | cmd.append('dist-upgrade') | ||
2891 | 195 | else: | ||
2892 | 196 | cmd.append('upgrade') | ||
2893 | 197 | log("Upgrading with options: {}".format(options)) | ||
2894 | 198 | _run_apt_command(cmd, fatal) | ||
2895 | 199 | |||
2896 | 200 | |||
2897 | 201 | def apt_update(fatal=False): | ||
2898 | 202 | """Update local apt cache""" | ||
2899 | 203 | cmd = ['apt-get', 'update'] | ||
2900 | 204 | _run_apt_command(cmd, fatal) | ||
2901 | 205 | |||
2902 | 206 | |||
2903 | 207 | def apt_purge(packages, fatal=False): | ||
2904 | 208 | """Purge one or more packages""" | ||
2905 | 209 | cmd = ['apt-get', '--assume-yes', 'purge'] | ||
2906 | 210 | if isinstance(packages, six.string_types): | ||
2907 | 211 | cmd.append(packages) | ||
2908 | 212 | else: | ||
2909 | 213 | cmd.extend(packages) | ||
2910 | 214 | log("Purging {}".format(packages)) | ||
2911 | 215 | _run_apt_command(cmd, fatal) | ||
2912 | 216 | |||
2913 | 217 | |||
2914 | 218 | def apt_hold(packages, fatal=False): | ||
2915 | 219 | """Hold one or more packages""" | ||
2916 | 220 | cmd = ['apt-mark', 'hold'] | ||
2917 | 221 | if isinstance(packages, six.string_types): | ||
2918 | 222 | cmd.append(packages) | ||
2919 | 223 | else: | ||
2920 | 224 | cmd.extend(packages) | ||
2921 | 225 | log("Holding {}".format(packages)) | ||
2922 | 226 | |||
2923 | 227 | if fatal: | ||
2924 | 228 | subprocess.check_call(cmd) | ||
2925 | 229 | else: | ||
2926 | 230 | subprocess.call(cmd) | ||
2927 | 231 | |||
2928 | 232 | |||
2929 | 233 | def add_source(source, key=None): | ||
2930 | 234 | """Add a package source to this system. | ||
2931 | 235 | |||
2932 | 236 | @param source: a URL or sources.list entry, as supported by | ||
2933 | 237 | add-apt-repository(1). Examples:: | ||
2934 | 238 | |||
2935 | 239 | ppa:charmers/example | ||
2936 | 240 | deb https://stub:key@private.example.com/ubuntu trusty main | ||
2937 | 241 | |||
2938 | 242 | In addition: | ||
2939 | 243 | 'proposed:' may be used to enable the standard 'proposed' | ||
2940 | 244 | pocket for the release. | ||
2941 | 245 | 'cloud:' may be used to activate official cloud archive pockets, | ||
2942 | 246 | such as 'cloud:icehouse' | ||
2943 | 247 | 'distro' may be used as a noop | ||
2944 | 248 | |||
2945 | 249 | @param key: A key to be added to the system's APT keyring and used | ||
2946 | 250 | to verify the signatures on packages. Ideally, this should be an | ||
2947 | 251 | ASCII format GPG public key including the block headers. A GPG key | ||
2948 | 252 | id may also be used, but be aware that only insecure protocols are | ||
2949 | 253 | available to retrieve the actual public key from a public keyserver | ||
2950 | 254 | placing your Juju environment at risk. ppa and cloud archive keys | ||
2951 | 255 | are securely added automtically, so sould not be provided. | ||
2952 | 256 | """ | ||
2953 | 257 | if source is None: | ||
2954 | 258 | log('Source is not present. Skipping') | ||
2955 | 259 | return | ||
2956 | 260 | |||
2957 | 261 | if (source.startswith('ppa:') or | ||
2958 | 262 | source.startswith('http') or | ||
2959 | 263 | source.startswith('deb ') or | ||
2960 | 264 | source.startswith('cloud-archive:')): | ||
2961 | 265 | subprocess.check_call(['add-apt-repository', '--yes', source]) | ||
2962 | 266 | elif source.startswith('cloud:'): | ||
2963 | 267 | apt_install(filter_installed_packages(['ubuntu-cloud-keyring']), | ||
2964 | 268 | fatal=True) | ||
2965 | 269 | pocket = source.split(':')[-1] | ||
2966 | 270 | if pocket not in CLOUD_ARCHIVE_POCKETS: | ||
2967 | 271 | raise SourceConfigError( | ||
2968 | 272 | 'Unsupported cloud: source option %s' % | ||
2969 | 273 | pocket) | ||
2970 | 274 | actual_pocket = CLOUD_ARCHIVE_POCKETS[pocket] | ||
2971 | 275 | with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as apt: | ||
2972 | 276 | apt.write(CLOUD_ARCHIVE.format(actual_pocket)) | ||
2973 | 277 | elif source == 'proposed': | ||
2974 | 278 | release = lsb_release()['DISTRIB_CODENAME'] | ||
2975 | 279 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: | ||
2976 | 280 | apt.write(PROPOSED_POCKET.format(release)) | ||
2977 | 281 | elif source == 'distro': | ||
2978 | 282 | pass | ||
2979 | 283 | else: | ||
2980 | 284 | log("Unknown source: {!r}".format(source)) | ||
2981 | 285 | |||
2982 | 286 | if key: | ||
2983 | 287 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: | ||
2984 | 288 | with NamedTemporaryFile('w+') as key_file: | ||
2985 | 289 | key_file.write(key) | ||
2986 | 290 | key_file.flush() | ||
2987 | 291 | key_file.seek(0) | ||
2988 | 292 | subprocess.check_call(['apt-key', 'add', '-'], stdin=key_file) | ||
2989 | 293 | else: | ||
2990 | 294 | # Note that hkp: is in no way a secure protocol. Using a | ||
2991 | 295 | # GPG key id is pointless from a security POV unless you | ||
2992 | 296 | # absolutely trust your network and DNS. | ||
2993 | 297 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | ||
2994 | 298 | 'hkp://keyserver.ubuntu.com:80', '--recv', | ||
2995 | 299 | key]) | ||
2996 | 300 | |||
2997 | 301 | |||
2998 | 302 | def configure_sources(update=False, | ||
2999 | 303 | sources_var='install_sources', | ||
3000 | 304 | keys_var='install_keys'): | ||
3001 | 305 | """ | ||
3002 | 306 | Configure multiple sources from charm configuration. | ||
3003 | 307 | |||
3004 | 308 | The lists are encoded as yaml fragments in the configuration. | ||
3005 | 309 | The frament needs to be included as a string. Sources and their | ||
3006 | 310 | corresponding keys are of the types supported by add_source(). | ||
3007 | 311 | |||
3008 | 312 | Example config: | ||
3009 | 313 | install_sources: | | ||
3010 | 314 | - "ppa:foo" | ||
3011 | 315 | - "http://example.com/repo precise main" | ||
3012 | 316 | install_keys: | | ||
3013 | 317 | - null | ||
3014 | 318 | - "a1b2c3d4" | ||
3015 | 319 | |||
3016 | 320 | Note that 'null' (a.k.a. None) should not be quoted. | ||
3017 | 321 | """ | ||
3018 | 322 | sources = safe_load((config(sources_var) or '').strip()) or [] | ||
3019 | 323 | keys = safe_load((config(keys_var) or '').strip()) or None | ||
3020 | 324 | |||
3021 | 325 | if isinstance(sources, six.string_types): | ||
3022 | 326 | sources = [sources] | ||
3023 | 327 | |||
3024 | 328 | if keys is None: | ||
3025 | 329 | for source in sources: | ||
3026 | 330 | add_source(source, None) | ||
3027 | 331 | else: | ||
3028 | 332 | if isinstance(keys, six.string_types): | ||
3029 | 333 | keys = [keys] | ||
3030 | 334 | |||
3031 | 335 | if len(sources) != len(keys): | ||
3032 | 336 | raise SourceConfigError( | ||
3033 | 337 | 'Install sources and keys lists are different lengths') | ||
3034 | 338 | for source, key in zip(sources, keys): | ||
3035 | 339 | add_source(source, key) | ||
3036 | 340 | if update: | ||
3037 | 341 | apt_update(fatal=True) | ||
3038 | 342 | |||
3039 | 343 | |||
3040 | 344 | def install_remote(source, *args, **kwargs): | ||
3041 | 345 | """ | ||
3042 | 346 | Install a file tree from a remote source | ||
3043 | 347 | |||
3044 | 348 | The specified source should be a url of the form: | ||
3045 | 349 | scheme://[host]/path[#[option=value][&...]] | ||
3046 | 350 | |||
3047 | 351 | Schemes supported are based on this modules submodules. | ||
3048 | 352 | Options supported are submodule-specific. | ||
3049 | 353 | Additional arguments are passed through to the submodule. | ||
3050 | 354 | |||
3051 | 355 | For example:: | ||
3052 | 356 | |||
3053 | 357 | dest = install_remote('http://example.com/archive.tgz', | ||
3054 | 358 | checksum='deadbeef', | ||
3055 | 359 | hash_type='sha1') | ||
3056 | 360 | |||
3057 | 361 | This will download `archive.tgz`, validate it using SHA1 and, if | ||
3058 | 362 | the file is ok, extract it and return the directory in which it | ||
3059 | 363 | was extracted. If the checksum fails, it will raise | ||
3060 | 364 | :class:`charmhelpers.core.host.ChecksumError`. | ||
3061 | 365 | """ | ||
3062 | 366 | # We ONLY check for True here because can_handle may return a string | ||
3063 | 367 | # explaining why it can't handle a given source. | ||
3064 | 368 | handlers = [h for h in plugins() if h.can_handle(source) is True] | ||
3065 | 369 | installed_to = None | ||
3066 | 370 | for handler in handlers: | ||
3067 | 371 | try: | ||
3068 | 372 | installed_to = handler.install(source, *args, **kwargs) | ||
3069 | 373 | except UnhandledSource: | ||
3070 | 374 | pass | ||
3071 | 375 | if not installed_to: | ||
3072 | 376 | raise UnhandledSource("No handler found for source {}".format(source)) | ||
3073 | 377 | return installed_to | ||
3074 | 378 | |||
3075 | 379 | |||
3076 | 380 | def install_from_config(config_var_name): | ||
3077 | 381 | charm_config = config() | ||
3078 | 382 | source = charm_config[config_var_name] | ||
3079 | 383 | return install_remote(source) | ||
3080 | 384 | |||
3081 | 385 | |||
3082 | 386 | def plugins(fetch_handlers=None): | ||
3083 | 387 | if not fetch_handlers: | ||
3084 | 388 | fetch_handlers = FETCH_HANDLERS | ||
3085 | 389 | plugin_list = [] | ||
3086 | 390 | for handler_name in fetch_handlers: | ||
3087 | 391 | package, classname = handler_name.rsplit('.', 1) | ||
3088 | 392 | try: | ||
3089 | 393 | handler_class = getattr( | ||
3090 | 394 | importlib.import_module(package), | ||
3091 | 395 | classname) | ||
3092 | 396 | plugin_list.append(handler_class()) | ||
3093 | 397 | except (ImportError, AttributeError): | ||
3094 | 398 | # Skip missing plugins so that they can be ommitted from | ||
3095 | 399 | # installation if desired | ||
3096 | 400 | log("FetchHandler {} not found, skipping plugin".format( | ||
3097 | 401 | handler_name)) | ||
3098 | 402 | return plugin_list | ||
3099 | 403 | |||
3100 | 404 | |||
3101 | 405 | def _run_apt_command(cmd, fatal=False): | ||
3102 | 406 | """ | ||
3103 | 407 | Run an APT command, checking output and retrying if the fatal flag is set | ||
3104 | 408 | to True. | ||
3105 | 409 | |||
3106 | 410 | :param: cmd: str: The apt command to run. | ||
3107 | 411 | :param: fatal: bool: Whether the command's output should be checked and | ||
3108 | 412 | retried. | ||
3109 | 413 | """ | ||
3110 | 414 | env = os.environ.copy() | ||
3111 | 415 | |||
3112 | 416 | if 'DEBIAN_FRONTEND' not in env: | ||
3113 | 417 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
3114 | 418 | |||
3115 | 419 | if fatal: | ||
3116 | 420 | retry_count = 0 | ||
3117 | 421 | result = None | ||
3118 | 422 | |||
3119 | 423 | # If the command is considered "fatal", we need to retry if the apt | ||
3120 | 424 | # lock was not acquired. | ||
3121 | 425 | |||
3122 | 426 | while result is None or result == APT_NO_LOCK: | ||
3123 | 427 | try: | ||
3124 | 428 | result = subprocess.check_call(cmd, env=env) | ||
3125 | 429 | except subprocess.CalledProcessError as e: | ||
3126 | 430 | retry_count = retry_count + 1 | ||
3127 | 431 | if retry_count > APT_NO_LOCK_RETRY_COUNT: | ||
3128 | 432 | raise | ||
3129 | 433 | result = e.returncode | ||
3130 | 434 | log("Couldn't acquire DPKG lock. Will retry in {} seconds." | ||
3131 | 435 | "".format(APT_NO_LOCK_RETRY_DELAY)) | ||
3132 | 436 | time.sleep(APT_NO_LOCK_RETRY_DELAY) | ||
3133 | 437 | |||
3134 | 438 | else: | ||
3135 | 439 | subprocess.call(cmd, env=env) | ||
3136 | 440 | 0 | ||
3137 | === removed file 'hooks/charmhelpers/fetch/archiveurl.py' | |||
3138 | --- hooks/charmhelpers/fetch/archiveurl.py 2015-02-19 16:21:31 +0000 | |||
3139 | +++ hooks/charmhelpers/fetch/archiveurl.py 1970-01-01 00:00:00 +0000 | |||
3140 | @@ -1,161 +0,0 @@ | |||
3141 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3142 | 2 | # | ||
3143 | 3 | # This file is part of charm-helpers. | ||
3144 | 4 | # | ||
3145 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3146 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3147 | 7 | # published by the Free Software Foundation. | ||
3148 | 8 | # | ||
3149 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3150 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3151 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3152 | 12 | # GNU Lesser General Public License for more details. | ||
3153 | 13 | # | ||
3154 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3155 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3156 | 16 | |||
3157 | 17 | import os | ||
3158 | 18 | import hashlib | ||
3159 | 19 | import re | ||
3160 | 20 | |||
3161 | 21 | from charmhelpers.fetch import ( | ||
3162 | 22 | BaseFetchHandler, | ||
3163 | 23 | UnhandledSource | ||
3164 | 24 | ) | ||
3165 | 25 | from charmhelpers.payload.archive import ( | ||
3166 | 26 | get_archive_handler, | ||
3167 | 27 | extract, | ||
3168 | 28 | ) | ||
3169 | 29 | from charmhelpers.core.host import mkdir, check_hash | ||
3170 | 30 | |||
3171 | 31 | import six | ||
3172 | 32 | if six.PY3: | ||
3173 | 33 | from urllib.request import ( | ||
3174 | 34 | build_opener, install_opener, urlopen, urlretrieve, | ||
3175 | 35 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
3176 | 36 | ) | ||
3177 | 37 | from urllib.parse import urlparse, urlunparse, parse_qs | ||
3178 | 38 | from urllib.error import URLError | ||
3179 | 39 | else: | ||
3180 | 40 | from urllib import urlretrieve | ||
3181 | 41 | from urllib2 import ( | ||
3182 | 42 | build_opener, install_opener, urlopen, | ||
3183 | 43 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
3184 | 44 | URLError | ||
3185 | 45 | ) | ||
3186 | 46 | from urlparse import urlparse, urlunparse, parse_qs | ||
3187 | 47 | |||
3188 | 48 | |||
3189 | 49 | def splituser(host): | ||
3190 | 50 | '''urllib.splituser(), but six's support of this seems broken''' | ||
3191 | 51 | _userprog = re.compile('^(.*)@(.*)$') | ||
3192 | 52 | match = _userprog.match(host) | ||
3193 | 53 | if match: | ||
3194 | 54 | return match.group(1, 2) | ||
3195 | 55 | return None, host | ||
3196 | 56 | |||
3197 | 57 | |||
3198 | 58 | def splitpasswd(user): | ||
3199 | 59 | '''urllib.splitpasswd(), but six's support of this is missing''' | ||
3200 | 60 | _passwdprog = re.compile('^([^:]*):(.*)$', re.S) | ||
3201 | 61 | match = _passwdprog.match(user) | ||
3202 | 62 | if match: | ||
3203 | 63 | return match.group(1, 2) | ||
3204 | 64 | return user, None | ||
3205 | 65 | |||
3206 | 66 | |||
3207 | 67 | class ArchiveUrlFetchHandler(BaseFetchHandler): | ||
3208 | 68 | """ | ||
3209 | 69 | Handler to download archive files from arbitrary URLs. | ||
3210 | 70 | |||
3211 | 71 | Can fetch from http, https, ftp, and file URLs. | ||
3212 | 72 | |||
3213 | 73 | Can install either tarballs (.tar, .tgz, .tbz2, etc) or zip files. | ||
3214 | 74 | |||
3215 | 75 | Installs the contents of the archive in $CHARM_DIR/fetched/. | ||
3216 | 76 | """ | ||
3217 | 77 | def can_handle(self, source): | ||
3218 | 78 | url_parts = self.parse_url(source) | ||
3219 | 79 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): | ||
3220 | 80 | return "Wrong source type" | ||
3221 | 81 | if get_archive_handler(self.base_url(source)): | ||
3222 | 82 | return True | ||
3223 | 83 | return False | ||
3224 | 84 | |||
3225 | 85 | def download(self, source, dest): | ||
3226 | 86 | """ | ||
3227 | 87 | Download an archive file. | ||
3228 | 88 | |||
3229 | 89 | :param str source: URL pointing to an archive file. | ||
3230 | 90 | :param str dest: Local path location to download archive file to. | ||
3231 | 91 | """ | ||
3232 | 92 | # propogate all exceptions | ||
3233 | 93 | # URLError, OSError, etc | ||
3234 | 94 | proto, netloc, path, params, query, fragment = urlparse(source) | ||
3235 | 95 | if proto in ('http', 'https'): | ||
3236 | 96 | auth, barehost = splituser(netloc) | ||
3237 | 97 | if auth is not None: | ||
3238 | 98 | source = urlunparse((proto, barehost, path, params, query, fragment)) | ||
3239 | 99 | username, password = splitpasswd(auth) | ||
3240 | 100 | passman = HTTPPasswordMgrWithDefaultRealm() | ||
3241 | 101 | # Realm is set to None in add_password to force the username and password | ||
3242 | 102 | # to be used whatever the realm | ||
3243 | 103 | passman.add_password(None, source, username, password) | ||
3244 | 104 | authhandler = HTTPBasicAuthHandler(passman) | ||
3245 | 105 | opener = build_opener(authhandler) | ||
3246 | 106 | install_opener(opener) | ||
3247 | 107 | response = urlopen(source) | ||
3248 | 108 | try: | ||
3249 | 109 | with open(dest, 'w') as dest_file: | ||
3250 | 110 | dest_file.write(response.read()) | ||
3251 | 111 | except Exception as e: | ||
3252 | 112 | if os.path.isfile(dest): | ||
3253 | 113 | os.unlink(dest) | ||
3254 | 114 | raise e | ||
3255 | 115 | |||
3256 | 116 | # Mandatory file validation via Sha1 or MD5 hashing. | ||
3257 | 117 | def download_and_validate(self, url, hashsum, validate="sha1"): | ||
3258 | 118 | tempfile, headers = urlretrieve(url) | ||
3259 | 119 | check_hash(tempfile, hashsum, validate) | ||
3260 | 120 | return tempfile | ||
3261 | 121 | |||
3262 | 122 | def install(self, source, dest=None, checksum=None, hash_type='sha1'): | ||
3263 | 123 | """ | ||
3264 | 124 | Download and install an archive file, with optional checksum validation. | ||
3265 | 125 | |||
3266 | 126 | The checksum can also be given on the `source` URL's fragment. | ||
3267 | 127 | For example:: | ||
3268 | 128 | |||
3269 | 129 | handler.install('http://example.com/file.tgz#sha1=deadbeef') | ||
3270 | 130 | |||
3271 | 131 | :param str source: URL pointing to an archive file. | ||
3272 | 132 | :param str dest: Local destination path to install to. If not given, | ||
3273 | 133 | installs to `$CHARM_DIR/archives/archive_file_name`. | ||
3274 | 134 | :param str checksum: If given, validate the archive file after download. | ||
3275 | 135 | :param str hash_type: Algorithm used to generate `checksum`. | ||
3276 | 136 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
3277 | 137 | such as md5, sha1, sha256, sha512, etc. | ||
3278 | 138 | |||
3279 | 139 | """ | ||
3280 | 140 | url_parts = self.parse_url(source) | ||
3281 | 141 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') | ||
3282 | 142 | if not os.path.exists(dest_dir): | ||
3283 | 143 | mkdir(dest_dir, perms=0o755) | ||
3284 | 144 | dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path)) | ||
3285 | 145 | try: | ||
3286 | 146 | self.download(source, dld_file) | ||
3287 | 147 | except URLError as e: | ||
3288 | 148 | raise UnhandledSource(e.reason) | ||
3289 | 149 | except OSError as e: | ||
3290 | 150 | raise UnhandledSource(e.strerror) | ||
3291 | 151 | options = parse_qs(url_parts.fragment) | ||
3292 | 152 | for key, value in options.items(): | ||
3293 | 153 | if not six.PY3: | ||
3294 | 154 | algorithms = hashlib.algorithms | ||
3295 | 155 | else: | ||
3296 | 156 | algorithms = hashlib.algorithms_available | ||
3297 | 157 | if key in algorithms: | ||
3298 | 158 | check_hash(dld_file, value, key) | ||
3299 | 159 | if checksum: | ||
3300 | 160 | check_hash(dld_file, checksum, hash_type) | ||
3301 | 161 | return extract(dld_file, dest) | ||
3302 | 162 | 0 | ||
3303 | === removed file 'hooks/charmhelpers/fetch/bzrurl.py' | |||
3304 | --- hooks/charmhelpers/fetch/bzrurl.py 2015-02-19 16:21:31 +0000 | |||
3305 | +++ hooks/charmhelpers/fetch/bzrurl.py 1970-01-01 00:00:00 +0000 | |||
3306 | @@ -1,78 +0,0 @@ | |||
3307 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3308 | 2 | # | ||
3309 | 3 | # This file is part of charm-helpers. | ||
3310 | 4 | # | ||
3311 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3312 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3313 | 7 | # published by the Free Software Foundation. | ||
3314 | 8 | # | ||
3315 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3316 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3317 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3318 | 12 | # GNU Lesser General Public License for more details. | ||
3319 | 13 | # | ||
3320 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3321 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3322 | 16 | |||
3323 | 17 | import os | ||
3324 | 18 | from charmhelpers.fetch import ( | ||
3325 | 19 | BaseFetchHandler, | ||
3326 | 20 | UnhandledSource | ||
3327 | 21 | ) | ||
3328 | 22 | from charmhelpers.core.host import mkdir | ||
3329 | 23 | |||
3330 | 24 | import six | ||
3331 | 25 | if six.PY3: | ||
3332 | 26 | raise ImportError('bzrlib does not support Python3') | ||
3333 | 27 | |||
3334 | 28 | try: | ||
3335 | 29 | from bzrlib.branch import Branch | ||
3336 | 30 | from bzrlib import bzrdir, workingtree, errors | ||
3337 | 31 | except ImportError: | ||
3338 | 32 | from charmhelpers.fetch import apt_install | ||
3339 | 33 | apt_install("python-bzrlib") | ||
3340 | 34 | from bzrlib.branch import Branch | ||
3341 | 35 | from bzrlib import bzrdir, workingtree, errors | ||
3342 | 36 | |||
3343 | 37 | |||
3344 | 38 | class BzrUrlFetchHandler(BaseFetchHandler): | ||
3345 | 39 | """Handler for bazaar branches via generic and lp URLs""" | ||
3346 | 40 | def can_handle(self, source): | ||
3347 | 41 | url_parts = self.parse_url(source) | ||
3348 | 42 | if url_parts.scheme not in ('bzr+ssh', 'lp'): | ||
3349 | 43 | return False | ||
3350 | 44 | else: | ||
3351 | 45 | return True | ||
3352 | 46 | |||
3353 | 47 | def branch(self, source, dest): | ||
3354 | 48 | url_parts = self.parse_url(source) | ||
3355 | 49 | # If we use lp:branchname scheme we need to load plugins | ||
3356 | 50 | if not self.can_handle(source): | ||
3357 | 51 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
3358 | 52 | if url_parts.scheme == "lp": | ||
3359 | 53 | from bzrlib.plugin import load_plugins | ||
3360 | 54 | load_plugins() | ||
3361 | 55 | try: | ||
3362 | 56 | local_branch = bzrdir.BzrDir.create_branch_convenience(dest) | ||
3363 | 57 | except errors.AlreadyControlDirError: | ||
3364 | 58 | local_branch = Branch.open(dest) | ||
3365 | 59 | try: | ||
3366 | 60 | remote_branch = Branch.open(source) | ||
3367 | 61 | remote_branch.push(local_branch) | ||
3368 | 62 | tree = workingtree.WorkingTree.open(dest) | ||
3369 | 63 | tree.update() | ||
3370 | 64 | except Exception as e: | ||
3371 | 65 | raise e | ||
3372 | 66 | |||
3373 | 67 | def install(self, source): | ||
3374 | 68 | url_parts = self.parse_url(source) | ||
3375 | 69 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
3376 | 70 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
3377 | 71 | branch_name) | ||
3378 | 72 | if not os.path.exists(dest_dir): | ||
3379 | 73 | mkdir(dest_dir, perms=0o755) | ||
3380 | 74 | try: | ||
3381 | 75 | self.branch(source, dest_dir) | ||
3382 | 76 | except OSError as e: | ||
3383 | 77 | raise UnhandledSource(e.strerror) | ||
3384 | 78 | return dest_dir | ||
3385 | 79 | 0 | ||
3386 | === removed file 'hooks/charmhelpers/fetch/giturl.py' | |||
3387 | --- hooks/charmhelpers/fetch/giturl.py 2015-02-19 16:21:31 +0000 | |||
3388 | +++ hooks/charmhelpers/fetch/giturl.py 1970-01-01 00:00:00 +0000 | |||
3389 | @@ -1,71 +0,0 @@ | |||
3390 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3391 | 2 | # | ||
3392 | 3 | # This file is part of charm-helpers. | ||
3393 | 4 | # | ||
3394 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3395 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3396 | 7 | # published by the Free Software Foundation. | ||
3397 | 8 | # | ||
3398 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3399 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3400 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3401 | 12 | # GNU Lesser General Public License for more details. | ||
3402 | 13 | # | ||
3403 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3404 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3405 | 16 | |||
3406 | 17 | import os | ||
3407 | 18 | from charmhelpers.fetch import ( | ||
3408 | 19 | BaseFetchHandler, | ||
3409 | 20 | UnhandledSource | ||
3410 | 21 | ) | ||
3411 | 22 | from charmhelpers.core.host import mkdir | ||
3412 | 23 | |||
3413 | 24 | import six | ||
3414 | 25 | if six.PY3: | ||
3415 | 26 | raise ImportError('GitPython does not support Python 3') | ||
3416 | 27 | |||
3417 | 28 | try: | ||
3418 | 29 | from git import Repo | ||
3419 | 30 | except ImportError: | ||
3420 | 31 | from charmhelpers.fetch import apt_install | ||
3421 | 32 | apt_install("python-git") | ||
3422 | 33 | from git import Repo | ||
3423 | 34 | |||
3424 | 35 | from git.exc import GitCommandError # noqa E402 | ||
3425 | 36 | |||
3426 | 37 | |||
3427 | 38 | class GitUrlFetchHandler(BaseFetchHandler): | ||
3428 | 39 | """Handler for git branches via generic and github URLs""" | ||
3429 | 40 | def can_handle(self, source): | ||
3430 | 41 | url_parts = self.parse_url(source) | ||
3431 | 42 | # TODO (mattyw) no support for ssh git@ yet | ||
3432 | 43 | if url_parts.scheme not in ('http', 'https', 'git'): | ||
3433 | 44 | return False | ||
3434 | 45 | else: | ||
3435 | 46 | return True | ||
3436 | 47 | |||
3437 | 48 | def clone(self, source, dest, branch): | ||
3438 | 49 | if not self.can_handle(source): | ||
3439 | 50 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
3440 | 51 | |||
3441 | 52 | repo = Repo.clone_from(source, dest) | ||
3442 | 53 | repo.git.checkout(branch) | ||
3443 | 54 | |||
3444 | 55 | def install(self, source, branch="master", dest=None): | ||
3445 | 56 | url_parts = self.parse_url(source) | ||
3446 | 57 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
3447 | 58 | if dest: | ||
3448 | 59 | dest_dir = os.path.join(dest, branch_name) | ||
3449 | 60 | else: | ||
3450 | 61 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
3451 | 62 | branch_name) | ||
3452 | 63 | if not os.path.exists(dest_dir): | ||
3453 | 64 | mkdir(dest_dir, perms=0o755) | ||
3454 | 65 | try: | ||
3455 | 66 | self.clone(source, dest_dir, branch) | ||
3456 | 67 | except GitCommandError as e: | ||
3457 | 68 | raise UnhandledSource(e.message) | ||
3458 | 69 | except OSError as e: | ||
3459 | 70 | raise UnhandledSource(e.strerror) | ||
3460 | 71 | return dest_dir | ||
3461 | 72 | 0 | ||
3462 | === removed file 'hooks/config-changed' | |||
3463 | --- hooks/config-changed 2015-02-19 21:19:01 +0000 | |||
3464 | +++ hooks/config-changed 1970-01-01 00:00:00 +0000 | |||
3465 | @@ -1,43 +0,0 @@ | |||
3466 | 1 | #!/usr/bin/python | ||
3467 | 2 | |||
3468 | 3 | # | ||
3469 | 4 | # Copyright 2015 Canonical Ltd. | ||
3470 | 5 | # | ||
3471 | 6 | # Authors: | ||
3472 | 7 | # Liang Chen <liang.chen@ubuntu.com> | ||
3473 | 8 | # | ||
3474 | 9 | import subprocess | ||
3475 | 10 | import sys | ||
3476 | 11 | |||
3477 | 12 | from charmhelpers.core.hookenv import ( | ||
3478 | 13 | config, | ||
3479 | 14 | Hooks, UnregisteredHookError, | ||
3480 | 15 | log, ERROR, | ||
3481 | 16 | ) | ||
3482 | 17 | |||
3483 | 18 | from utils import render_template | ||
3484 | 19 | |||
3485 | 20 | hooks = Hooks() | ||
3486 | 21 | |||
3487 | 22 | |||
3488 | 23 | def emit_lxc_br_conf(): | ||
3489 | 24 | lxc_context = {} | ||
3490 | 25 | if config('new-lxc-network'): | ||
3491 | 26 | lxc_context['new_network'] = True | ||
3492 | 27 | |||
3493 | 28 | lxc_bridge_conf = "/etc/network/interfaces.d/lxcbr0.cfg" | ||
3494 | 29 | with open(lxc_bridge_conf, 'w') as lxc_br_conf: | ||
3495 | 30 | lxc_br_conf.write(render_template('lxc-bridge.conf', lxc_context)) | ||
3496 | 31 | |||
3497 | 32 | |||
3498 | 33 | @hooks.hook('config-changed') | ||
3499 | 34 | def config_changed(): | ||
3500 | 35 | emit_lxc_br_conf() | ||
3501 | 36 | cmd = ['ifup', 'lxcbr0'] | ||
3502 | 37 | subprocess.check_call(cmd) | ||
3503 | 38 | |||
3504 | 39 | if __name__ == '__main__': | ||
3505 | 40 | try: | ||
3506 | 41 | hooks.execute(sys.argv) | ||
3507 | 42 | except UnregisteredHookError as e: | ||
3508 | 43 | log('Unknown hook {} - skipping.'.format(e)) | ||
3509 | 44 | 0 | ||
3510 | === removed file 'hooks/hooks.py' | |||
3511 | --- hooks/hooks.py 2015-02-19 21:19:01 +0000 | |||
3512 | +++ hooks/hooks.py 1970-01-01 00:00:00 +0000 | |||
3513 | @@ -1,45 +0,0 @@ | |||
3514 | 1 | #!/usr/bin/python | ||
3515 | 2 | |||
3516 | 3 | # | ||
3517 | 4 | # Copyright 2015 Canonical Ltd. | ||
3518 | 5 | # | ||
3519 | 6 | # Authors: | ||
3520 | 7 | # Liang Chen <liang.chen@ubuntu.com> | ||
3521 | 8 | # | ||
3522 | 9 | |||
3523 | 10 | import subprocess | ||
3524 | 11 | import sys | ||
3525 | 12 | |||
3526 | 13 | from charmhelpers.core.hookenv import ( | ||
3527 | 14 | config, | ||
3528 | 15 | Hooks, UnregisteredHookError, | ||
3529 | 16 | log, | ||
3530 | 17 | ) | ||
3531 | 18 | |||
3532 | 19 | from utils import render_template | ||
3533 | 20 | |||
3534 | 21 | hooks = Hooks() | ||
3535 | 22 | |||
3536 | 23 | |||
3537 | 24 | def emit_lxc_br_conf(): | ||
3538 | 25 | lxc_context = {} | ||
3539 | 26 | if config('new-lxc-network'): | ||
3540 | 27 | lxc_context['new_network'] = True | ||
3541 | 28 | |||
3542 | 29 | lxc_bridge_conf = "/etc/network/interfaces.d/lxcbr0.cfg" | ||
3543 | 30 | with open(lxc_bridge_conf, 'w') as lxc_br_conf: | ||
3544 | 31 | lxc_br_conf.write(render_template('lxc-bridge.conf', lxc_context)) | ||
3545 | 32 | |||
3546 | 33 | |||
3547 | 34 | @hooks.hook('config-changed') | ||
3548 | 35 | def config_changed(): | ||
3549 | 36 | emit_lxc_br_conf() | ||
3550 | 37 | cmd = ['ifup', 'lxcbr0'] | ||
3551 | 38 | subprocess.check_call(cmd) | ||
3552 | 39 | |||
3553 | 40 | |||
3554 | 41 | if __name__ == '__main__': | ||
3555 | 42 | try: | ||
3556 | 43 | hooks.execute(sys.argv) | ||
3557 | 44 | except UnregisteredHookError as e: | ||
3558 | 45 | log('Unknown hook {} - skipping.'.format(e)) | ||
3559 | 46 | 0 | ||
3560 | === removed file 'hooks/install' | |||
3561 | --- hooks/install 2012-05-03 22:17:19 +0000 | |||
3562 | +++ hooks/install 1970-01-01 00:00:00 +0000 | |||
3563 | @@ -1,2 +0,0 @@ | |||
3564 | 1 | #!/bin/bash | ||
3565 | 2 | # Does nothing. - charm proof requires an install hook. | ||
3566 | 3 | 0 | ||
3567 | === removed file 'hooks/utils.py' | |||
3568 | --- hooks/utils.py 2015-02-19 21:19:01 +0000 | |||
3569 | +++ hooks/utils.py 1970-01-01 00:00:00 +0000 | |||
3570 | @@ -1,27 +0,0 @@ | |||
3571 | 1 | # | ||
3572 | 2 | # Copyright 2015 Canonical Ltd. | ||
3573 | 3 | # | ||
3574 | 4 | # Authors: | ||
3575 | 5 | # Liang Chen <liang.chen@ubuntu.com> | ||
3576 | 6 | # | ||
3577 | 7 | |||
3578 | 8 | TEMPLATES_DIR = 'templates' | ||
3579 | 9 | |||
3580 | 10 | from charmhelpers.fetch import ( | ||
3581 | 11 | apt_install, | ||
3582 | 12 | filter_installed_packages | ||
3583 | 13 | ) | ||
3584 | 14 | |||
3585 | 15 | try: | ||
3586 | 16 | import jinja2 | ||
3587 | 17 | except ImportError: | ||
3588 | 18 | apt_install(filter_installed_packages(['python-jinja2']), | ||
3589 | 19 | fatal=True) | ||
3590 | 20 | import jinja2 | ||
3591 | 21 | |||
3592 | 22 | |||
3593 | 23 | def render_template(template_name, context, template_dir=TEMPLATES_DIR): | ||
3594 | 24 | templates = jinja2.Environment( | ||
3595 | 25 | loader=jinja2.FileSystemLoader(template_dir)) | ||
3596 | 26 | template = templates.get_template(template_name) | ||
3597 | 27 | return template.render(context) | ||
3598 | 28 | 0 | ||
3599 | === modified file 'metadata.yaml' | |||
3600 | --- metadata.yaml 2013-12-11 21:28:41 +0000 | |||
3601 | +++ metadata.yaml 2015-04-30 13:14:23 +0000 | |||
3602 | @@ -3,5 +3,5 @@ | |||
3603 | 3 | maintainer: Charmers <juju@lists.ubuntu.com> | 3 | maintainer: Charmers <juju@lists.ubuntu.com> |
3604 | 4 | description: | | 4 | description: | |
3605 | 5 | This simply deploys Ubuntu Server. | 5 | This simply deploys Ubuntu Server. |
3607 | 6 | categories: | 6 | tags: |
3608 | 7 | - misc | 7 | - misc |
3609 | 8 | 8 | ||
3610 | === removed directory 'templates' | |||
3611 | === removed file 'templates/lxc-bridge.conf' | |||
3612 | --- templates/lxc-bridge.conf 2015-02-19 21:19:01 +0000 | |||
3613 | +++ templates/lxc-bridge.conf 1970-01-01 00:00:00 +0000 | |||
3614 | @@ -1,10 +0,0 @@ | |||
3615 | 1 | |||
3616 | 2 | {% if new_network -%} | ||
3617 | 3 | auto eth0 | ||
3618 | 4 | iface eth0 inet manual | ||
3619 | 5 | |||
3620 | 6 | auto lxcbr0 | ||
3621 | 7 | iface lxcbr0 inet dhcp | ||
3622 | 8 | bridge_ports eth0 | ||
3623 | 9 | |||
3624 | 10 | {% endif -%} | ||
3625 | 11 | 0 | ||
3626 | === modified file 'tests/00-setup.sh' | |||
3627 | --- tests/00-setup.sh 2015-02-19 17:29:32 +0000 | |||
3628 | +++ tests/00-setup.sh 2015-04-30 13:14:23 +0000 | |||
3629 | @@ -1,15 +1,9 @@ | |||
3637 | 1 | #!/bin/bash | 1 | #!/bin/bash -x |
3638 | 2 | 2 | ||
3639 | 3 | # This script runs first to set up the environment for the tests. | 3 | # Install amulet if not already installed. |
3633 | 4 | |||
3634 | 5 | set -x | ||
3635 | 6 | |||
3636 | 7 | # Check if amulet is installed before adding repository and updating apt-get. | ||
3640 | 8 | dpkg -s amulet | 4 | dpkg -s amulet |
3641 | 9 | if [ $? -ne 0 ]; then | 5 | if [ $? -ne 0 ]; then |
3642 | 10 | sudo add-apt-repository -y ppa:juju/stable | 6 | sudo add-apt-repository -y ppa:juju/stable |
3644 | 11 | sudo apt-get update -qq | 7 | sudo apt-get update -qq |
3645 | 12 | sudo apt-get install -y amulet | 8 | sudo apt-get install -y amulet |
3646 | 13 | fi | 9 | fi |
3647 | 14 | # Install any additional packages needed for tests here. | ||
3648 | 15 | |||
3649 | 16 | 10 | ||
3650 | === added file 'tests/010_basic_precise' | |||
3651 | --- tests/010_basic_precise 1970-01-01 00:00:00 +0000 | |||
3652 | +++ tests/010_basic_precise 2015-04-30 13:14:23 +0000 | |||
3653 | @@ -0,0 +1,7 @@ | |||
3654 | 1 | #!/usr/bin/python | ||
3655 | 2 | """Amulet tests on a basic ubuntu charm deployment on precise.""" | ||
3656 | 3 | |||
3657 | 4 | from basic_deployment import ubuntu_basic_deployment | ||
3658 | 5 | |||
3659 | 6 | if __name__ == '__main__': | ||
3660 | 7 | ubuntu_basic_deployment(series='precise') | ||
3661 | 0 | 8 | ||
3662 | === added file 'tests/015_basic_trusty' | |||
3663 | --- tests/015_basic_trusty 1970-01-01 00:00:00 +0000 | |||
3664 | +++ tests/015_basic_trusty 2015-04-30 13:14:23 +0000 | |||
3665 | @@ -0,0 +1,7 @@ | |||
3666 | 1 | #!/usr/bin/python | ||
3667 | 2 | """Amulet tests on a basic ubuntu charm deployment on trusty.""" | ||
3668 | 3 | |||
3669 | 4 | from basic_deployment import ubuntu_basic_deployment | ||
3670 | 5 | |||
3671 | 6 | if __name__ == '__main__': | ||
3672 | 7 | ubuntu_basic_deployment(series='trusty') | ||
3673 | 0 | 8 | ||
3674 | === added file 'tests/020_basic_utopic' | |||
3675 | --- tests/020_basic_utopic 1970-01-01 00:00:00 +0000 | |||
3676 | +++ tests/020_basic_utopic 2015-04-30 13:14:23 +0000 | |||
3677 | @@ -0,0 +1,7 @@ | |||
3678 | 1 | #!/usr/bin/python | ||
3679 | 2 | """Amulet tests on a basic ubuntu charm deployment on utopic.""" | ||
3680 | 3 | |||
3681 | 4 | from basic_deployment import ubuntu_basic_deployment | ||
3682 | 5 | |||
3683 | 6 | if __name__ == '__main__': | ||
3684 | 7 | ubuntu_basic_deployment(series='utopic') | ||
3685 | 0 | 8 | ||
3686 | === added file 'tests/025_basic_vivid' | |||
3687 | --- tests/025_basic_vivid 1970-01-01 00:00:00 +0000 | |||
3688 | +++ tests/025_basic_vivid 2015-04-30 13:14:23 +0000 | |||
3689 | @@ -0,0 +1,7 @@ | |||
3690 | 1 | #!/usr/bin/python | ||
3691 | 2 | """Amulet tests on a basic ubuntu charm deployment on trusty.""" | ||
3692 | 3 | |||
3693 | 4 | from basic_deployment import ubuntu_basic_deployment | ||
3694 | 5 | |||
3695 | 6 | if __name__ == '__main__': | ||
3696 | 7 | ubuntu_basic_deployment(series='vivid') | ||
3697 | 0 | 8 | ||
3698 | === removed file 'tests/10-deploy-test.py' | |||
3699 | --- tests/10-deploy-test.py 2015-03-27 15:26:53 +0000 | |||
3700 | +++ tests/10-deploy-test.py 1970-01-01 00:00:00 +0000 | |||
3701 | @@ -1,90 +0,0 @@ | |||
3702 | 1 | #!/usr/bin/python3 | ||
3703 | 2 | |||
3704 | 3 | # This Amulet based tests | ||
3705 | 4 | # The goal is to ensure the Ubuntu charm | ||
3706 | 5 | # sucessfully deploys and can be accessed. | ||
3707 | 6 | # Note the Ubuntu charm does not have any | ||
3708 | 7 | # relations or config options. | ||
3709 | 8 | |||
3710 | 9 | import amulet | ||
3711 | 10 | |||
3712 | 11 | # Timeout value, in seconds to deploy the environment | ||
3713 | 12 | seconds = 900 | ||
3714 | 13 | series = 'trusty' | ||
3715 | 14 | |||
3716 | 15 | # Set up the deployer module to interact and set up the environment. | ||
3717 | 16 | d = amulet.Deployment(series=series) | ||
3718 | 17 | |||
3719 | 18 | # Define the environment in terms of charms, their config, and relations. | ||
3720 | 19 | |||
3721 | 20 | # Add the Ubuntu charm to the deployment. | ||
3722 | 21 | d.add('ubuntu') | ||
3723 | 22 | |||
3724 | 23 | # Deploy the environment currently defined | ||
3725 | 24 | try: | ||
3726 | 25 | # Wait the defined about amount of time to deploy the environment. | ||
3727 | 26 | # Setup makes sure the services are deployed, related, and in a | ||
3728 | 27 | # "started" state. | ||
3729 | 28 | d.setup(timeout=seconds) | ||
3730 | 29 | # Use a sentry to ensure there are no remaining hooks being execute | ||
3731 | 30 | # on any of the nodes | ||
3732 | 31 | except amulet.helpers.TimeoutError: | ||
3733 | 32 | # Pending the configuration the test will fail or be skipped | ||
3734 | 33 | # if not deployed properly. | ||
3735 | 34 | error_message = 'The environment did not deploy in %d seconds.' % seconds | ||
3736 | 35 | amulet.raise_status(amulet.SKIP, msg=error_message) | ||
3737 | 36 | except: | ||
3738 | 37 | # Something else has gone wrong, raise the error so we can see it and this | ||
3739 | 38 | # will automatically "FAIL" the test. | ||
3740 | 39 | raise | ||
3741 | 40 | |||
3742 | 41 | # Access the Ubuntu instance to ensure it has been deployed correctly | ||
3743 | 42 | |||
3744 | 43 | # Define the commands to be ran | ||
3745 | 44 | lsb_command = 'lsb_release -cs' | ||
3746 | 45 | uname_command = 'uname -a' | ||
3747 | 46 | lxc_interface_command = 'ifconfig -s lxcbr0' | ||
3748 | 47 | |||
3749 | 48 | print(lsb_command) | ||
3750 | 49 | # Print the release information | ||
3751 | 50 | output, code = d.sentry.unit['ubuntu/0'].run(lsb_command) | ||
3752 | 51 | print(output) | ||
3753 | 52 | # Confirm the lsb_release command ran successfully | ||
3754 | 53 | if (code != 0): | ||
3755 | 54 | message = 'The ' + lsb_command + ' did not return the expected return code of 0.' | ||
3756 | 55 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3757 | 56 | else: | ||
3758 | 57 | if series in output: | ||
3759 | 58 | print('The series is correct.') | ||
3760 | 59 | else: | ||
3761 | 60 | message = 'The series is not correct.' | ||
3762 | 61 | print(message) | ||
3763 | 62 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3764 | 63 | |||
3765 | 64 | print(uname_command) | ||
3766 | 65 | |||
3767 | 66 | # Get the uname -a output | ||
3768 | 67 | output, code = d.sentry.unit['ubuntu/0'].run(uname_command) | ||
3769 | 68 | print(output) | ||
3770 | 69 | # Confirm the uname command was ran successfully | ||
3771 | 70 | if (code != 0): | ||
3772 | 71 | message = 'The ' + uname_command + ' did not return the expected return code of 0.' | ||
3773 | 72 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3774 | 73 | else: | ||
3775 | 74 | message = 'The ' + uname_command + ' successfully executed.' | ||
3776 | 75 | print(output) | ||
3777 | 76 | print(message) | ||
3778 | 77 | |||
3779 | 78 | # Test creating a new network for LXC via new-lxc-network config option. | ||
3780 | 79 | # Set the new-lxc-network config option to create a new network for LXC. | ||
3781 | 80 | d.configure('ubuntu', {'new-lxc-network': 'true'}) | ||
3782 | 81 | # Confirm the the lxc bridge interface was sucessfully created | ||
3783 | 82 | output, code = d.sentry.unit['ubuntu/0'].run(lxc_interface_command) | ||
3784 | 83 | if (code != 0): | ||
3785 | 84 | error_message = 'The lxcbr0 interface was not created.' | ||
3786 | 85 | print(output) | ||
3787 | 86 | amulet.raise_status(amulet.FAIL, msg=error_message) | ||
3788 | 87 | else: | ||
3789 | 88 | message = 'The lxcbr0 interface sucessfully created.' | ||
3790 | 89 | print(output) | ||
3791 | 90 | print(message) | ||
3792 | 91 | 0 | ||
3793 | === added file 'tests/basic_deployment.py' | |||
3794 | --- tests/basic_deployment.py 1970-01-01 00:00:00 +0000 | |||
3795 | +++ tests/basic_deployment.py 2015-04-30 13:14:23 +0000 | |||
3796 | @@ -0,0 +1,49 @@ | |||
3797 | 1 | #!/usr/bin/python3 | ||
3798 | 2 | """ | ||
3799 | 3 | Ubuntu charm functional test. Take note that the Ubuntu | ||
3800 | 4 | charm does not have any relations or config options | ||
3801 | 5 | to exercise. | ||
3802 | 6 | """ | ||
3803 | 7 | |||
3804 | 8 | import amulet | ||
3805 | 9 | from charmhelpers.contrib.amulet.utils import AmuletUtils | ||
3806 | 10 | import logging | ||
3807 | 11 | |||
3808 | 12 | |||
3809 | 13 | def ubuntu_basic_deployment(series): | ||
3810 | 14 | """ Common test routines to run per-series. """ | ||
3811 | 15 | |||
3812 | 16 | # Initialize | ||
3813 | 17 | seconds = 900 | ||
3814 | 18 | u = AmuletUtils(logging.DEBUG) | ||
3815 | 19 | d = amulet.Deployment(series=series) | ||
3816 | 20 | d.add('ubuntu') | ||
3817 | 21 | unit = 'ubuntu/0' | ||
3818 | 22 | lsb_command = 'lsb_release -cs' | ||
3819 | 23 | |||
3820 | 24 | # Deploy services, wait for started state. Fail or skip on timeout. | ||
3821 | 25 | try: | ||
3822 | 26 | d.setup(timeout=seconds) | ||
3823 | 27 | except amulet.helpers.TimeoutError: | ||
3824 | 28 | message = 'Deployment timed out ({}s)'.format(seconds) | ||
3825 | 29 | amulet.raise_status(amulet.SKIP, msg=message) | ||
3826 | 30 | except: | ||
3827 | 31 | raise | ||
3828 | 32 | |||
3829 | 33 | # Confirm Ubuntu release name from the unit. | ||
3830 | 34 | u.log.debug('Command: {}'.format(lsb_command)) | ||
3831 | 35 | output, code = d.sentry.unit[unit].run(lsb_command) | ||
3832 | 36 | u.log.debug('Output: {}'.format(output)) | ||
3833 | 37 | |||
3834 | 38 | if (code != 0): | ||
3835 | 39 | message = 'Command FAIL: {}'.format(lsb_command) | ||
3836 | 40 | u.log.error(message) | ||
3837 | 41 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3838 | 42 | else: | ||
3839 | 43 | if series in output: | ||
3840 | 44 | message = 'Series: OK' | ||
3841 | 45 | u.log.info(message) | ||
3842 | 46 | else: | ||
3843 | 47 | message = 'Series: FAIL ({})'.format(output) | ||
3844 | 48 | u.log.error(message) | ||
3845 | 49 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3846 | 0 | 50 | ||
3847 | === added directory 'tests/charmhelpers' | |||
3848 | === added file 'tests/charmhelpers/__init__.py' | |||
3849 | --- tests/charmhelpers/__init__.py 1970-01-01 00:00:00 +0000 | |||
3850 | +++ tests/charmhelpers/__init__.py 2015-04-30 13:14:23 +0000 | |||
3851 | @@ -0,0 +1,38 @@ | |||
3852 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3853 | 2 | # | ||
3854 | 3 | # This file is part of charm-helpers. | ||
3855 | 4 | # | ||
3856 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3857 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3858 | 7 | # published by the Free Software Foundation. | ||
3859 | 8 | # | ||
3860 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3861 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3862 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3863 | 12 | # GNU Lesser General Public License for more details. | ||
3864 | 13 | # | ||
3865 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3866 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3867 | 16 | |||
3868 | 17 | # Bootstrap charm-helpers, installing its dependencies if necessary using | ||
3869 | 18 | # only standard libraries. | ||
3870 | 19 | import subprocess | ||
3871 | 20 | import sys | ||
3872 | 21 | |||
3873 | 22 | try: | ||
3874 | 23 | import six # flake8: noqa | ||
3875 | 24 | except ImportError: | ||
3876 | 25 | if sys.version_info.major == 2: | ||
3877 | 26 | subprocess.check_call(['apt-get', 'install', '-y', 'python-six']) | ||
3878 | 27 | else: | ||
3879 | 28 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-six']) | ||
3880 | 29 | import six # flake8: noqa | ||
3881 | 30 | |||
3882 | 31 | try: | ||
3883 | 32 | import yaml # flake8: noqa | ||
3884 | 33 | except ImportError: | ||
3885 | 34 | if sys.version_info.major == 2: | ||
3886 | 35 | subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml']) | ||
3887 | 36 | else: | ||
3888 | 37 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml']) | ||
3889 | 38 | import yaml # flake8: noqa | ||
3890 | 0 | 39 | ||
3891 | === added directory 'tests/charmhelpers/contrib' | |||
3892 | === added file 'tests/charmhelpers/contrib/__init__.py' | |||
3893 | --- tests/charmhelpers/contrib/__init__.py 1970-01-01 00:00:00 +0000 | |||
3894 | +++ tests/charmhelpers/contrib/__init__.py 2015-04-30 13:14:23 +0000 | |||
3895 | @@ -0,0 +1,15 @@ | |||
3896 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3897 | 2 | # | ||
3898 | 3 | # This file is part of charm-helpers. | ||
3899 | 4 | # | ||
3900 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3901 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3902 | 7 | # published by the Free Software Foundation. | ||
3903 | 8 | # | ||
3904 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3905 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3906 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3907 | 12 | # GNU Lesser General Public License for more details. | ||
3908 | 13 | # | ||
3909 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3910 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3911 | 0 | 16 | ||
3912 | === added directory 'tests/charmhelpers/contrib/amulet' | |||
3913 | === added file 'tests/charmhelpers/contrib/amulet/__init__.py' | |||
3914 | --- tests/charmhelpers/contrib/amulet/__init__.py 1970-01-01 00:00:00 +0000 | |||
3915 | +++ tests/charmhelpers/contrib/amulet/__init__.py 2015-04-30 13:14:23 +0000 | |||
3916 | @@ -0,0 +1,15 @@ | |||
3917 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3918 | 2 | # | ||
3919 | 3 | # This file is part of charm-helpers. | ||
3920 | 4 | # | ||
3921 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3922 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3923 | 7 | # published by the Free Software Foundation. | ||
3924 | 8 | # | ||
3925 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3926 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3927 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3928 | 12 | # GNU Lesser General Public License for more details. | ||
3929 | 13 | # | ||
3930 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3931 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3932 | 0 | 16 | ||
3933 | === added file 'tests/charmhelpers/contrib/amulet/deployment.py' | |||
3934 | --- tests/charmhelpers/contrib/amulet/deployment.py 1970-01-01 00:00:00 +0000 | |||
3935 | +++ tests/charmhelpers/contrib/amulet/deployment.py 2015-04-30 13:14:23 +0000 | |||
3936 | @@ -0,0 +1,93 @@ | |||
3937 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3938 | 2 | # | ||
3939 | 3 | # This file is part of charm-helpers. | ||
3940 | 4 | # | ||
3941 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3942 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3943 | 7 | # published by the Free Software Foundation. | ||
3944 | 8 | # | ||
3945 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3946 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3947 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3948 | 12 | # GNU Lesser General Public License for more details. | ||
3949 | 13 | # | ||
3950 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3951 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3952 | 16 | |||
3953 | 17 | import amulet | ||
3954 | 18 | import os | ||
3955 | 19 | import six | ||
3956 | 20 | |||
3957 | 21 | |||
3958 | 22 | class AmuletDeployment(object): | ||
3959 | 23 | """Amulet deployment. | ||
3960 | 24 | |||
3961 | 25 | This class provides generic Amulet deployment and test runner | ||
3962 | 26 | methods. | ||
3963 | 27 | """ | ||
3964 | 28 | |||
3965 | 29 | def __init__(self, series=None): | ||
3966 | 30 | """Initialize the deployment environment.""" | ||
3967 | 31 | self.series = None | ||
3968 | 32 | |||
3969 | 33 | if series: | ||
3970 | 34 | self.series = series | ||
3971 | 35 | self.d = amulet.Deployment(series=self.series) | ||
3972 | 36 | else: | ||
3973 | 37 | self.d = amulet.Deployment() | ||
3974 | 38 | |||
3975 | 39 | def _add_services(self, this_service, other_services): | ||
3976 | 40 | """Add services. | ||
3977 | 41 | |||
3978 | 42 | Add services to the deployment where this_service is the local charm | ||
3979 | 43 | that we're testing and other_services are the other services that | ||
3980 | 44 | are being used in the local amulet tests. | ||
3981 | 45 | """ | ||
3982 | 46 | if this_service['name'] != os.path.basename(os.getcwd()): | ||
3983 | 47 | s = this_service['name'] | ||
3984 | 48 | msg = "The charm's root directory name needs to be {}".format(s) | ||
3985 | 49 | amulet.raise_status(amulet.FAIL, msg=msg) | ||
3986 | 50 | |||
3987 | 51 | if 'units' not in this_service: | ||
3988 | 52 | this_service['units'] = 1 | ||
3989 | 53 | |||
3990 | 54 | self.d.add(this_service['name'], units=this_service['units']) | ||
3991 | 55 | |||
3992 | 56 | for svc in other_services: | ||
3993 | 57 | if 'location' in svc: | ||
3994 | 58 | branch_location = svc['location'] | ||
3995 | 59 | elif self.series: | ||
3996 | 60 | branch_location = 'cs:{}/{}'.format(self.series, svc['name']), | ||
3997 | 61 | else: | ||
3998 | 62 | branch_location = None | ||
3999 | 63 | |||
4000 | 64 | if 'units' not in svc: | ||
4001 | 65 | svc['units'] = 1 | ||
4002 | 66 | |||
4003 | 67 | self.d.add(svc['name'], charm=branch_location, units=svc['units']) | ||
4004 | 68 | |||
4005 | 69 | def _add_relations(self, relations): | ||
4006 | 70 | """Add all of the relations for the services.""" | ||
4007 | 71 | for k, v in six.iteritems(relations): | ||
4008 | 72 | self.d.relate(k, v) | ||
4009 | 73 | |||
4010 | 74 | def _configure_services(self, configs): | ||
4011 | 75 | """Configure all of the services.""" | ||
4012 | 76 | for service, config in six.iteritems(configs): | ||
4013 | 77 | self.d.configure(service, config) | ||
4014 | 78 | |||
4015 | 79 | def _deploy(self): | ||
4016 | 80 | """Deploy environment and wait for all hooks to finish executing.""" | ||
4017 | 81 | try: | ||
4018 | 82 | self.d.setup(timeout=900) | ||
4019 | 83 | self.d.sentry.wait(timeout=900) | ||
4020 | 84 | except amulet.helpers.TimeoutError: | ||
4021 | 85 | amulet.raise_status(amulet.FAIL, msg="Deployment timed out") | ||
4022 | 86 | except Exception: | ||
4023 | 87 | raise | ||
4024 | 88 | |||
4025 | 89 | def run_tests(self): | ||
4026 | 90 | """Run all of the methods that are prefixed with 'test_'.""" | ||
4027 | 91 | for test in dir(self): | ||
4028 | 92 | if test.startswith('test_'): | ||
4029 | 93 | getattr(self, test)() | ||
4030 | 0 | 94 | ||
4031 | === added file 'tests/charmhelpers/contrib/amulet/utils.py' | |||
4032 | --- tests/charmhelpers/contrib/amulet/utils.py 1970-01-01 00:00:00 +0000 | |||
4033 | +++ tests/charmhelpers/contrib/amulet/utils.py 2015-04-30 13:14:23 +0000 | |||
4034 | @@ -0,0 +1,323 @@ | |||
4035 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4036 | 2 | # | ||
4037 | 3 | # This file is part of charm-helpers. | ||
4038 | 4 | # | ||
4039 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
4040 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
4041 | 7 | # published by the Free Software Foundation. | ||
4042 | 8 | # | ||
4043 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
4044 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
4045 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
4046 | 12 | # GNU Lesser General Public License for more details. | ||
4047 | 13 | # | ||
4048 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
4049 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
4050 | 16 | |||
4051 | 17 | import ConfigParser | ||
4052 | 18 | import io | ||
4053 | 19 | import logging | ||
4054 | 20 | import re | ||
4055 | 21 | import sys | ||
4056 | 22 | import time | ||
4057 | 23 | |||
4058 | 24 | import six | ||
4059 | 25 | |||
4060 | 26 | |||
4061 | 27 | class AmuletUtils(object): | ||
4062 | 28 | """Amulet utilities. | ||
4063 | 29 | |||
4064 | 30 | This class provides common utility functions that are used by Amulet | ||
4065 | 31 | tests. | ||
4066 | 32 | """ | ||
4067 | 33 | |||
4068 | 34 | def __init__(self, log_level=logging.ERROR): | ||
4069 | 35 | self.log = self.get_logger(level=log_level) | ||
4070 | 36 | |||
4071 | 37 | def get_logger(self, name="amulet-logger", level=logging.DEBUG): | ||
4072 | 38 | """Get a logger object that will log to stdout.""" | ||
4073 | 39 | log = logging | ||
4074 | 40 | logger = log.getLogger(name) | ||
4075 | 41 | fmt = log.Formatter("%(asctime)s %(funcName)s " | ||
4076 | 42 | "%(levelname)s: %(message)s") | ||
4077 | 43 | |||
4078 | 44 | handler = log.StreamHandler(stream=sys.stdout) | ||
4079 | 45 | handler.setLevel(level) | ||
4080 | 46 | handler.setFormatter(fmt) | ||
4081 | 47 | |||
4082 | 48 | logger.addHandler(handler) | ||
4083 | 49 | logger.setLevel(level) | ||
4084 | 50 | |||
4085 | 51 | return logger | ||
4086 | 52 | |||
4087 | 53 | def valid_ip(self, ip): | ||
4088 | 54 | if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip): | ||
4089 | 55 | return True | ||
4090 | 56 | else: | ||
4091 | 57 | return False | ||
4092 | 58 | |||
4093 | 59 | def valid_url(self, url): | ||
4094 | 60 | p = re.compile( | ||
4095 | 61 | r'^(?:http|ftp)s?://' | ||
4096 | 62 | r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # noqa | ||
4097 | 63 | r'localhost|' | ||
4098 | 64 | r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' | ||
4099 | 65 | r'(?::\d+)?' | ||
4100 | 66 | r'(?:/?|[/?]\S+)$', | ||
4101 | 67 | re.IGNORECASE) | ||
4102 | 68 | if p.match(url): | ||
4103 | 69 | return True | ||
4104 | 70 | else: | ||
4105 | 71 | return False | ||
4106 | 72 | |||
4107 | 73 | def validate_services(self, commands): | ||
4108 | 74 | """Validate services. | ||
4109 | 75 | |||
4110 | 76 | Verify the specified services are running on the corresponding | ||
4111 | 77 | service units. | ||
4112 | 78 | """ | ||
4113 | 79 | for k, v in six.iteritems(commands): | ||
4114 | 80 | for cmd in v: | ||
4115 | 81 | output, code = k.run(cmd) | ||
4116 | 82 | self.log.debug('{} `{}` returned ' | ||
4117 | 83 | '{}'.format(k.info['unit_name'], | ||
4118 | 84 | cmd, code)) | ||
4119 | 85 | if code != 0: | ||
4120 | 86 | return "command `{}` returned {}".format(cmd, str(code)) | ||
4121 | 87 | return None | ||
4122 | 88 | |||
4123 | 89 | def _get_config(self, unit, filename): | ||
4124 | 90 | """Get a ConfigParser object for parsing a unit's config file.""" | ||
4125 | 91 | file_contents = unit.file_contents(filename) | ||
4126 | 92 | |||
4127 | 93 | # NOTE(beisner): by default, ConfigParser does not handle options | ||
4128 | 94 | # with no value, such as the flags used in the mysql my.cnf file. | ||
4129 | 95 | # https://bugs.python.org/issue7005 | ||
4130 | 96 | config = ConfigParser.ConfigParser(allow_no_value=True) | ||
4131 | 97 | config.readfp(io.StringIO(file_contents)) | ||
4132 | 98 | return config | ||
4133 | 99 | |||
4134 | 100 | def validate_config_data(self, sentry_unit, config_file, section, | ||
4135 | 101 | expected): | ||
4136 | 102 | """Validate config file data. | ||
4137 | 103 | |||
4138 | 104 | Verify that the specified section of the config file contains | ||
4139 | 105 | the expected option key:value pairs. | ||
4140 | 106 | """ | ||
4141 | 107 | config = self._get_config(sentry_unit, config_file) | ||
4142 | 108 | |||
4143 | 109 | if section != 'DEFAULT' and not config.has_section(section): | ||
4144 | 110 | return "section [{}] does not exist".format(section) | ||
4145 | 111 | |||
4146 | 112 | for k in expected.keys(): | ||
4147 | 113 | if not config.has_option(section, k): | ||
4148 | 114 | return "section [{}] is missing option {}".format(section, k) | ||
4149 | 115 | if config.get(section, k) != expected[k]: | ||
4150 | 116 | return "section [{}] {}:{} != expected {}:{}".format( | ||
4151 | 117 | section, k, config.get(section, k), k, expected[k]) | ||
4152 | 118 | return None | ||
4153 | 119 | |||
4154 | 120 | def _validate_dict_data(self, expected, actual): | ||
4155 | 121 | """Validate dictionary data. | ||
4156 | 122 | |||
4157 | 123 | Compare expected dictionary data vs actual dictionary data. | ||
4158 | 124 | The values in the 'expected' dictionary can be strings, bools, ints, | ||
4159 | 125 | longs, or can be a function that evaluate a variable and returns a | ||
4160 | 126 | bool. | ||
4161 | 127 | """ | ||
4162 | 128 | self.log.debug('actual: {}'.format(repr(actual))) | ||
4163 | 129 | self.log.debug('expected: {}'.format(repr(expected))) | ||
4164 | 130 | |||
4165 | 131 | for k, v in six.iteritems(expected): | ||
4166 | 132 | if k in actual: | ||
4167 | 133 | if (isinstance(v, six.string_types) or | ||
4168 | 134 | isinstance(v, bool) or | ||
4169 | 135 | isinstance(v, six.integer_types)): | ||
4170 | 136 | if v != actual[k]: | ||
4171 | 137 | return "{}:{}".format(k, actual[k]) | ||
4172 | 138 | elif not v(actual[k]): | ||
4173 | 139 | return "{}:{}".format(k, actual[k]) | ||
4174 | 140 | else: | ||
4175 | 141 | return "key '{}' does not exist".format(k) | ||
4176 | 142 | return None | ||
4177 | 143 | |||
4178 | 144 | def validate_relation_data(self, sentry_unit, relation, expected): | ||
4179 | 145 | """Validate actual relation data based on expected relation data.""" | ||
4180 | 146 | actual = sentry_unit.relation(relation[0], relation[1]) | ||
4181 | 147 | return self._validate_dict_data(expected, actual) | ||
4182 | 148 | |||
4183 | 149 | def _validate_list_data(self, expected, actual): | ||
4184 | 150 | """Compare expected list vs actual list data.""" | ||
4185 | 151 | for e in expected: | ||
4186 | 152 | if e not in actual: | ||
4187 | 153 | return "expected item {} not found in actual list".format(e) | ||
4188 | 154 | return None | ||
4189 | 155 | |||
4190 | 156 | def not_null(self, string): | ||
4191 | 157 | if string is not None: | ||
4192 | 158 | return True | ||
4193 | 159 | else: | ||
4194 | 160 | return False | ||
4195 | 161 | |||
4196 | 162 | def _get_file_mtime(self, sentry_unit, filename): | ||
4197 | 163 | """Get last modification time of file.""" | ||
4198 | 164 | return sentry_unit.file_stat(filename)['mtime'] | ||
4199 | 165 | |||
4200 | 166 | def _get_dir_mtime(self, sentry_unit, directory): | ||
4201 | 167 | """Get last modification time of directory.""" | ||
4202 | 168 | return sentry_unit.directory_stat(directory)['mtime'] | ||
4203 | 169 | |||
4204 | 170 | def _get_proc_start_time(self, sentry_unit, service, pgrep_full=False): | ||
4205 | 171 | """Get process' start time. | ||
4206 | 172 | |||
4207 | 173 | Determine start time of the process based on the last modification | ||
4208 | 174 | time of the /proc/pid directory. If pgrep_full is True, the process | ||
4209 | 175 | name is matched against the full command line. | ||
4210 | 176 | """ | ||
4211 | 177 | if pgrep_full: | ||
4212 | 178 | cmd = 'pgrep -o -f {}'.format(service) | ||
4213 | 179 | else: | ||
4214 | 180 | cmd = 'pgrep -o {}'.format(service) | ||
4215 | 181 | cmd = cmd + ' | grep -v pgrep || exit 0' | ||
4216 | 182 | cmd_out = sentry_unit.run(cmd) | ||
4217 | 183 | self.log.debug('CMDout: ' + str(cmd_out)) | ||
4218 | 184 | if cmd_out[0]: | ||
4219 | 185 | self.log.debug('Pid for %s %s' % (service, str(cmd_out[0]))) | ||
4220 | 186 | proc_dir = '/proc/{}'.format(cmd_out[0].strip()) | ||
4221 | 187 | return self._get_dir_mtime(sentry_unit, proc_dir) | ||
4222 | 188 | |||
4223 | 189 | def service_restarted(self, sentry_unit, service, filename, | ||
4224 | 190 | pgrep_full=False, sleep_time=20): | ||
4225 | 191 | """Check if service was restarted. | ||
4226 | 192 | |||
4227 | 193 | Compare a service's start time vs a file's last modification time | ||
4228 | 194 | (such as a config file for that service) to determine if the service | ||
4229 | 195 | has been restarted. | ||
4230 | 196 | """ | ||
4231 | 197 | time.sleep(sleep_time) | ||
4232 | 198 | if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >= | ||
4233 | 199 | self._get_file_mtime(sentry_unit, filename)): | ||
4234 | 200 | return True | ||
4235 | 201 | else: | ||
4236 | 202 | return False | ||
4237 | 203 | |||
4238 | 204 | def service_restarted_since(self, sentry_unit, mtime, service, | ||
4239 | 205 | pgrep_full=False, sleep_time=20, | ||
4240 | 206 | retry_count=2): | ||
4241 | 207 | """Check if service was been started after a given time. | ||
4242 | 208 | |||
4243 | 209 | Args: | ||
4244 | 210 | sentry_unit (sentry): The sentry unit to check for the service on | ||
4245 | 211 | mtime (float): The epoch time to check against | ||
4246 | 212 | service (string): service name to look for in process table | ||
4247 | 213 | pgrep_full (boolean): Use full command line search mode with pgrep | ||
4248 | 214 | sleep_time (int): Seconds to sleep before looking for process | ||
4249 | 215 | retry_count (int): If service is not found, how many times to retry | ||
4250 | 216 | |||
4251 | 217 | Returns: | ||
4252 | 218 | bool: True if service found and its start time it newer than mtime, | ||
4253 | 219 | False if service is older than mtime or if service was | ||
4254 | 220 | not found. | ||
4255 | 221 | """ | ||
4256 | 222 | self.log.debug('Checking %s restarted since %s' % (service, mtime)) | ||
4257 | 223 | time.sleep(sleep_time) | ||
4258 | 224 | proc_start_time = self._get_proc_start_time(sentry_unit, service, | ||
4259 | 225 | pgrep_full) | ||
4260 | 226 | while retry_count > 0 and not proc_start_time: | ||
4261 | 227 | self.log.debug('No pid file found for service %s, will retry %i ' | ||
4262 | 228 | 'more times' % (service, retry_count)) | ||
4263 | 229 | time.sleep(30) | ||
4264 | 230 | proc_start_time = self._get_proc_start_time(sentry_unit, service, | ||
4265 | 231 | pgrep_full) | ||
4266 | 232 | retry_count = retry_count - 1 | ||
4267 | 233 | |||
4268 | 234 | if not proc_start_time: | ||
4269 | 235 | self.log.warn('No proc start time found, assuming service did ' | ||
4270 | 236 | 'not start') | ||
4271 | 237 | return False | ||
4272 | 238 | if proc_start_time >= mtime: | ||
4273 | 239 | self.log.debug('proc start time is newer than provided mtime' | ||
4274 | 240 | '(%s >= %s)' % (proc_start_time, mtime)) | ||
4275 | 241 | return True | ||
4276 | 242 | else: | ||
4277 | 243 | self.log.warn('proc start time (%s) is older than provided mtime ' | ||
4278 | 244 | '(%s), service did not restart' % (proc_start_time, | ||
4279 | 245 | mtime)) | ||
4280 | 246 | return False | ||
4281 | 247 | |||
4282 | 248 | def config_updated_since(self, sentry_unit, filename, mtime, | ||
4283 | 249 | sleep_time=20): | ||
4284 | 250 | """Check if file was modified after a given time. | ||
4285 | 251 | |||
4286 | 252 | Args: | ||
4287 | 253 | sentry_unit (sentry): The sentry unit to check the file mtime on | ||
4288 | 254 | filename (string): The file to check mtime of | ||
4289 | 255 | mtime (float): The epoch time to check against | ||
4290 | 256 | sleep_time (int): Seconds to sleep before looking for process | ||
4291 | 257 | |||
4292 | 258 | Returns: | ||
4293 | 259 | bool: True if file was modified more recently than mtime, False if | ||
4294 | 260 | file was modified before mtime, | ||
4295 | 261 | """ | ||
4296 | 262 | self.log.debug('Checking %s updated since %s' % (filename, mtime)) | ||
4297 | 263 | time.sleep(sleep_time) | ||
4298 | 264 | file_mtime = self._get_file_mtime(sentry_unit, filename) | ||
4299 | 265 | if file_mtime >= mtime: | ||
4300 | 266 | self.log.debug('File mtime is newer than provided mtime ' | ||
4301 | 267 | '(%s >= %s)' % (file_mtime, mtime)) | ||
4302 | 268 | return True | ||
4303 | 269 | else: | ||
4304 | 270 | self.log.warn('File mtime %s is older than provided mtime %s' | ||
4305 | 271 | % (file_mtime, mtime)) | ||
4306 | 272 | return False | ||
4307 | 273 | |||
4308 | 274 | def validate_service_config_changed(self, sentry_unit, mtime, service, | ||
4309 | 275 | filename, pgrep_full=False, | ||
4310 | 276 | sleep_time=20, retry_count=2): | ||
4311 | 277 | """Check service and file were updated after mtime | ||
4312 | 278 | |||
4313 | 279 | Args: | ||
4314 | 280 | sentry_unit (sentry): The sentry unit to check for the service on | ||
4315 | 281 | mtime (float): The epoch time to check against | ||
4316 | 282 | service (string): service name to look for in process table | ||
4317 | 283 | filename (string): The file to check mtime of | ||
4318 | 284 | pgrep_full (boolean): Use full command line search mode with pgrep | ||
4319 | 285 | sleep_time (int): Seconds to sleep before looking for process | ||
4320 | 286 | retry_count (int): If service is not found, how many times to retry | ||
4321 | 287 | |||
4322 | 288 | Typical Usage: | ||
4323 | 289 | u = OpenStackAmuletUtils(ERROR) | ||
4324 | 290 | ... | ||
4325 | 291 | mtime = u.get_sentry_time(self.cinder_sentry) | ||
4326 | 292 | self.d.configure('cinder', {'verbose': 'True', 'debug': 'True'}) | ||
4327 | 293 | if not u.validate_service_config_changed(self.cinder_sentry, | ||
4328 | 294 | mtime, | ||
4329 | 295 | 'cinder-api', | ||
4330 | 296 | '/etc/cinder/cinder.conf') | ||
4331 | 297 | amulet.raise_status(amulet.FAIL, msg='update failed') | ||
4332 | 298 | Returns: | ||
4333 | 299 | bool: True if both service and file where updated/restarted after | ||
4334 | 300 | mtime, False if service is older than mtime or if service was | ||
4335 | 301 | not found or if filename was modified before mtime. | ||
4336 | 302 | """ | ||
4337 | 303 | self.log.debug('Checking %s restarted since %s' % (service, mtime)) | ||
4338 | 304 | time.sleep(sleep_time) | ||
4339 | 305 | service_restart = self.service_restarted_since(sentry_unit, mtime, | ||
4340 | 306 | service, | ||
4341 | 307 | pgrep_full=pgrep_full, | ||
4342 | 308 | sleep_time=0, | ||
4343 | 309 | retry_count=retry_count) | ||
4344 | 310 | config_update = self.config_updated_since(sentry_unit, filename, mtime, | ||
4345 | 311 | sleep_time=0) | ||
4346 | 312 | return service_restart and config_update | ||
4347 | 313 | |||
4348 | 314 | def get_sentry_time(self, sentry_unit): | ||
4349 | 315 | """Return current epoch time on a sentry""" | ||
4350 | 316 | cmd = "date +'%s'" | ||
4351 | 317 | return float(sentry_unit.run(cmd)[0]) | ||
4352 | 318 | |||
4353 | 319 | def relation_error(self, name, data): | ||
4354 | 320 | return 'unexpected relation data in {} - {}'.format(name, data) | ||
4355 | 321 | |||
4356 | 322 | def endpoint_error(self, name, data): | ||
4357 | 323 | return 'unexpected endpoint data in {} - {}'.format(name, data) | ||
4358 | 0 | 324 | ||
4359 | === added file 'tests/tests.yaml' | |||
4360 | --- tests/tests.yaml 1970-01-01 00:00:00 +0000 | |||
4361 | +++ tests/tests.yaml 2015-04-30 13:14:23 +0000 | |||
4362 | @@ -0,0 +1,9 @@ | |||
4363 | 1 | bootstrap: true | ||
4364 | 2 | reset: true | ||
4365 | 3 | virtualenv: true | ||
4366 | 4 | makefile: | ||
4367 | 5 | - lint | ||
4368 | 6 | sources: | ||
4369 | 7 | - ppa:juju/stable | ||
4370 | 8 | packages: | ||
4371 | 9 | - amulet |
Tested via bundletester / amulet on Precise, Trusty, Utopic, Vivid. Ready for review.
Results: http:// paste.ubuntu. com/10952530/