Merge lp:~tribaal/charms/trusty/mysql/charm-helpers-sync into lp:charms/trusty/mysql
- Trusty Tahr (14.04)
- charm-helpers-sync
- Merge into trunk
Proposed by
Chris Glass
Status: | Merged |
---|---|
Approved by: | David Britton |
Approved revision: | 127 |
Merge reported by: | David Britton |
Merged at revision: | not available |
Proposed branch: | lp:~tribaal/charms/trusty/mysql/charm-helpers-sync |
Merge into: | lp:charms/trusty/mysql |
Diff against target: |
1685 lines (+1204/-116) 12 files modified
.bzrignore (+1/-0) Makefile (+7/-2) hooks/charmhelpers/core/fstab.py (+116/-0) hooks/charmhelpers/core/hookenv.py (+132/-7) hooks/charmhelpers/core/host.py (+100/-12) hooks/charmhelpers/core/services/__init__.py (+2/-0) hooks/charmhelpers/core/services/base.py (+313/-0) hooks/charmhelpers/core/services/helpers.py (+239/-0) hooks/charmhelpers/core/templating.py (+51/-0) hooks/charmhelpers/fetch/__init__.py (+192/-90) hooks/charmhelpers/fetch/archiveurl.py (+49/-4) hooks/charmhelpers/fetch/bzrurl.py (+2/-1) |
To merge this branch: | bzr merge lp:~tribaal/charms/trusty/mysql/charm-helpers-sync |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
David Britton (community) | Approve | ||
Review Queue (community) | automated testing | Needs Fixing | |
Review via email: mp+236067@code.launchpad.net |
Commit message
Description of the change
This branch updates charm-helpers so that the charm take advantage of the new in-memory apt-cache building (fixes race conditions).
To post a comment you must log in.
Revision history for this message
Review Queue (review-queue) wrote : | # |
review:
Needs Fixing
(automated testing)
Revision history for this message
David Britton (dpb) wrote : | # |
Look great Chris, Thanks! -- I checked the automated test results, the error was from hpcloud and was spurious.
review:
Approve
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === added file '.bzrignore' | |||
2 | --- .bzrignore 1970-01-01 00:00:00 +0000 | |||
3 | +++ .bzrignore 2014-09-26 07:21:45 +0000 | |||
4 | @@ -0,0 +1,1 @@ | |||
5 | 1 | bin/ | ||
6 | 0 | 2 | ||
7 | === modified file 'Makefile' | |||
8 | --- Makefile 2014-03-04 17:28:10 +0000 | |||
9 | +++ Makefile 2014-09-26 07:21:45 +0000 | |||
10 | @@ -11,5 +11,10 @@ | |||
11 | 11 | # @echo Starting tests... | 11 | # @echo Starting tests... |
12 | 12 | # @$(PYTHON) /usr/bin/nosetests --nologcapture unit_tests | 12 | # @$(PYTHON) /usr/bin/nosetests --nologcapture unit_tests |
13 | 13 | 13 | ||
16 | 14 | sync: | 14 | bin/charm_helpers_sync.py: |
17 | 15 | @charm-helper-sync -c charm-helpers.yaml | 15 | @mkdir -p bin |
18 | 16 | @bzr cat lp:charm-helpers/tools/charm_helpers_sync/charm_helpers_sync.py \ | ||
19 | 17 | > bin/charm_helpers_sync.py | ||
20 | 18 | |||
21 | 19 | sync: bin/charm_helpers_sync.py | ||
22 | 20 | $(PYTHON) bin/charm_helpers_sync.py -c charm-helpers.yaml | ||
23 | 16 | 21 | ||
24 | === added file 'hooks/charmhelpers/core/fstab.py' | |||
25 | --- hooks/charmhelpers/core/fstab.py 1970-01-01 00:00:00 +0000 | |||
26 | +++ hooks/charmhelpers/core/fstab.py 2014-09-26 07:21:45 +0000 | |||
27 | @@ -0,0 +1,116 @@ | |||
28 | 1 | #!/usr/bin/env python | ||
29 | 2 | # -*- coding: utf-8 -*- | ||
30 | 3 | |||
31 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
32 | 5 | |||
33 | 6 | import os | ||
34 | 7 | |||
35 | 8 | |||
36 | 9 | class Fstab(file): | ||
37 | 10 | """This class extends file in order to implement a file reader/writer | ||
38 | 11 | for file `/etc/fstab` | ||
39 | 12 | """ | ||
40 | 13 | |||
41 | 14 | class Entry(object): | ||
42 | 15 | """Entry class represents a non-comment line on the `/etc/fstab` file | ||
43 | 16 | """ | ||
44 | 17 | def __init__(self, device, mountpoint, filesystem, | ||
45 | 18 | options, d=0, p=0): | ||
46 | 19 | self.device = device | ||
47 | 20 | self.mountpoint = mountpoint | ||
48 | 21 | self.filesystem = filesystem | ||
49 | 22 | |||
50 | 23 | if not options: | ||
51 | 24 | options = "defaults" | ||
52 | 25 | |||
53 | 26 | self.options = options | ||
54 | 27 | self.d = d | ||
55 | 28 | self.p = p | ||
56 | 29 | |||
57 | 30 | def __eq__(self, o): | ||
58 | 31 | return str(self) == str(o) | ||
59 | 32 | |||
60 | 33 | def __str__(self): | ||
61 | 34 | return "{} {} {} {} {} {}".format(self.device, | ||
62 | 35 | self.mountpoint, | ||
63 | 36 | self.filesystem, | ||
64 | 37 | self.options, | ||
65 | 38 | self.d, | ||
66 | 39 | self.p) | ||
67 | 40 | |||
68 | 41 | DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab') | ||
69 | 42 | |||
70 | 43 | def __init__(self, path=None): | ||
71 | 44 | if path: | ||
72 | 45 | self._path = path | ||
73 | 46 | else: | ||
74 | 47 | self._path = self.DEFAULT_PATH | ||
75 | 48 | file.__init__(self, self._path, 'r+') | ||
76 | 49 | |||
77 | 50 | def _hydrate_entry(self, line): | ||
78 | 51 | # NOTE: use split with no arguments to split on any | ||
79 | 52 | # whitespace including tabs | ||
80 | 53 | return Fstab.Entry(*filter( | ||
81 | 54 | lambda x: x not in ('', None), | ||
82 | 55 | line.strip("\n").split())) | ||
83 | 56 | |||
84 | 57 | @property | ||
85 | 58 | def entries(self): | ||
86 | 59 | self.seek(0) | ||
87 | 60 | for line in self.readlines(): | ||
88 | 61 | try: | ||
89 | 62 | if not line.startswith("#"): | ||
90 | 63 | yield self._hydrate_entry(line) | ||
91 | 64 | except ValueError: | ||
92 | 65 | pass | ||
93 | 66 | |||
94 | 67 | def get_entry_by_attr(self, attr, value): | ||
95 | 68 | for entry in self.entries: | ||
96 | 69 | e_attr = getattr(entry, attr) | ||
97 | 70 | if e_attr == value: | ||
98 | 71 | return entry | ||
99 | 72 | return None | ||
100 | 73 | |||
101 | 74 | def add_entry(self, entry): | ||
102 | 75 | if self.get_entry_by_attr('device', entry.device): | ||
103 | 76 | return False | ||
104 | 77 | |||
105 | 78 | self.write(str(entry) + '\n') | ||
106 | 79 | self.truncate() | ||
107 | 80 | return entry | ||
108 | 81 | |||
109 | 82 | def remove_entry(self, entry): | ||
110 | 83 | self.seek(0) | ||
111 | 84 | |||
112 | 85 | lines = self.readlines() | ||
113 | 86 | |||
114 | 87 | found = False | ||
115 | 88 | for index, line in enumerate(lines): | ||
116 | 89 | if not line.startswith("#"): | ||
117 | 90 | if self._hydrate_entry(line) == entry: | ||
118 | 91 | found = True | ||
119 | 92 | break | ||
120 | 93 | |||
121 | 94 | if not found: | ||
122 | 95 | return False | ||
123 | 96 | |||
124 | 97 | lines.remove(line) | ||
125 | 98 | |||
126 | 99 | self.seek(0) | ||
127 | 100 | self.write(''.join(lines)) | ||
128 | 101 | self.truncate() | ||
129 | 102 | return True | ||
130 | 103 | |||
131 | 104 | @classmethod | ||
132 | 105 | def remove_by_mountpoint(cls, mountpoint, path=None): | ||
133 | 106 | fstab = cls(path=path) | ||
134 | 107 | entry = fstab.get_entry_by_attr('mountpoint', mountpoint) | ||
135 | 108 | if entry: | ||
136 | 109 | return fstab.remove_entry(entry) | ||
137 | 110 | return False | ||
138 | 111 | |||
139 | 112 | @classmethod | ||
140 | 113 | def add(cls, device, mountpoint, filesystem, options=None, path=None): | ||
141 | 114 | return cls(path=path).add_entry(Fstab.Entry(device, | ||
142 | 115 | mountpoint, filesystem, | ||
143 | 116 | options=options)) | ||
144 | 0 | 117 | ||
145 | === modified file 'hooks/charmhelpers/core/hookenv.py' | |||
146 | --- hooks/charmhelpers/core/hookenv.py 2014-02-19 14:49:31 +0000 | |||
147 | +++ hooks/charmhelpers/core/hookenv.py 2014-09-26 07:21:45 +0000 | |||
148 | @@ -25,7 +25,7 @@ | |||
149 | 25 | def cached(func): | 25 | def cached(func): |
150 | 26 | """Cache return values for multiple executions of func + args | 26 | """Cache return values for multiple executions of func + args |
151 | 27 | 27 | ||
153 | 28 | For example: | 28 | For example:: |
154 | 29 | 29 | ||
155 | 30 | @cached | 30 | @cached |
156 | 31 | def unit_get(attribute): | 31 | def unit_get(attribute): |
157 | @@ -155,6 +155,121 @@ | |||
158 | 155 | return os.path.basename(sys.argv[0]) | 155 | return os.path.basename(sys.argv[0]) |
159 | 156 | 156 | ||
160 | 157 | 157 | ||
161 | 158 | class Config(dict): | ||
162 | 159 | """A dictionary representation of the charm's config.yaml, with some | ||
163 | 160 | extra features: | ||
164 | 161 | |||
165 | 162 | - See which values in the dictionary have changed since the previous hook. | ||
166 | 163 | - For values that have changed, see what the previous value was. | ||
167 | 164 | - Store arbitrary data for use in a later hook. | ||
168 | 165 | |||
169 | 166 | NOTE: Do not instantiate this object directly - instead call | ||
170 | 167 | ``hookenv.config()``, which will return an instance of :class:`Config`. | ||
171 | 168 | |||
172 | 169 | Example usage:: | ||
173 | 170 | |||
174 | 171 | >>> # inside a hook | ||
175 | 172 | >>> from charmhelpers.core import hookenv | ||
176 | 173 | >>> config = hookenv.config() | ||
177 | 174 | >>> config['foo'] | ||
178 | 175 | 'bar' | ||
179 | 176 | >>> # store a new key/value for later use | ||
180 | 177 | >>> config['mykey'] = 'myval' | ||
181 | 178 | |||
182 | 179 | |||
183 | 180 | >>> # user runs `juju set mycharm foo=baz` | ||
184 | 181 | >>> # now we're inside subsequent config-changed hook | ||
185 | 182 | >>> config = hookenv.config() | ||
186 | 183 | >>> config['foo'] | ||
187 | 184 | 'baz' | ||
188 | 185 | >>> # test to see if this val has changed since last hook | ||
189 | 186 | >>> config.changed('foo') | ||
190 | 187 | True | ||
191 | 188 | >>> # what was the previous value? | ||
192 | 189 | >>> config.previous('foo') | ||
193 | 190 | 'bar' | ||
194 | 191 | >>> # keys/values that we add are preserved across hooks | ||
195 | 192 | >>> config['mykey'] | ||
196 | 193 | 'myval' | ||
197 | 194 | |||
198 | 195 | """ | ||
199 | 196 | CONFIG_FILE_NAME = '.juju-persistent-config' | ||
200 | 197 | |||
201 | 198 | def __init__(self, *args, **kw): | ||
202 | 199 | super(Config, self).__init__(*args, **kw) | ||
203 | 200 | self.implicit_save = True | ||
204 | 201 | self._prev_dict = None | ||
205 | 202 | self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME) | ||
206 | 203 | if os.path.exists(self.path): | ||
207 | 204 | self.load_previous() | ||
208 | 205 | |||
209 | 206 | def __getitem__(self, key): | ||
210 | 207 | """For regular dict lookups, check the current juju config first, | ||
211 | 208 | then the previous (saved) copy. This ensures that user-saved values | ||
212 | 209 | will be returned by a dict lookup. | ||
213 | 210 | |||
214 | 211 | """ | ||
215 | 212 | try: | ||
216 | 213 | return dict.__getitem__(self, key) | ||
217 | 214 | except KeyError: | ||
218 | 215 | return (self._prev_dict or {})[key] | ||
219 | 216 | |||
220 | 217 | def load_previous(self, path=None): | ||
221 | 218 | """Load previous copy of config from disk. | ||
222 | 219 | |||
223 | 220 | In normal usage you don't need to call this method directly - it | ||
224 | 221 | is called automatically at object initialization. | ||
225 | 222 | |||
226 | 223 | :param path: | ||
227 | 224 | |||
228 | 225 | File path from which to load the previous config. If `None`, | ||
229 | 226 | config is loaded from the default location. If `path` is | ||
230 | 227 | specified, subsequent `save()` calls will write to the same | ||
231 | 228 | path. | ||
232 | 229 | |||
233 | 230 | """ | ||
234 | 231 | self.path = path or self.path | ||
235 | 232 | with open(self.path) as f: | ||
236 | 233 | self._prev_dict = json.load(f) | ||
237 | 234 | |||
238 | 235 | def changed(self, key): | ||
239 | 236 | """Return True if the current value for this key is different from | ||
240 | 237 | the previous value. | ||
241 | 238 | |||
242 | 239 | """ | ||
243 | 240 | if self._prev_dict is None: | ||
244 | 241 | return True | ||
245 | 242 | return self.previous(key) != self.get(key) | ||
246 | 243 | |||
247 | 244 | def previous(self, key): | ||
248 | 245 | """Return previous value for this key, or None if there | ||
249 | 246 | is no previous value. | ||
250 | 247 | |||
251 | 248 | """ | ||
252 | 249 | if self._prev_dict: | ||
253 | 250 | return self._prev_dict.get(key) | ||
254 | 251 | return None | ||
255 | 252 | |||
256 | 253 | def save(self): | ||
257 | 254 | """Save this config to disk. | ||
258 | 255 | |||
259 | 256 | If the charm is using the :mod:`Services Framework <services.base>` | ||
260 | 257 | or :meth:'@hook <Hooks.hook>' decorator, this | ||
261 | 258 | is called automatically at the end of successful hook execution. | ||
262 | 259 | Otherwise, it should be called directly by user code. | ||
263 | 260 | |||
264 | 261 | To disable automatic saves, set ``implicit_save=False`` on this | ||
265 | 262 | instance. | ||
266 | 263 | |||
267 | 264 | """ | ||
268 | 265 | if self._prev_dict: | ||
269 | 266 | for k, v in self._prev_dict.iteritems(): | ||
270 | 267 | if k not in self: | ||
271 | 268 | self[k] = v | ||
272 | 269 | with open(self.path, 'w') as f: | ||
273 | 270 | json.dump(self, f) | ||
274 | 271 | |||
275 | 272 | |||
276 | 158 | @cached | 273 | @cached |
277 | 159 | def config(scope=None): | 274 | def config(scope=None): |
278 | 160 | """Juju charm configuration""" | 275 | """Juju charm configuration""" |
279 | @@ -163,7 +278,10 @@ | |||
280 | 163 | config_cmd_line.append(scope) | 278 | config_cmd_line.append(scope) |
281 | 164 | config_cmd_line.append('--format=json') | 279 | config_cmd_line.append('--format=json') |
282 | 165 | try: | 280 | try: |
284 | 166 | return json.loads(subprocess.check_output(config_cmd_line)) | 281 | config_data = json.loads(subprocess.check_output(config_cmd_line)) |
285 | 282 | if scope is not None: | ||
286 | 283 | return config_data | ||
287 | 284 | return Config(config_data) | ||
288 | 167 | except ValueError: | 285 | except ValueError: |
289 | 168 | return None | 286 | return None |
290 | 169 | 287 | ||
291 | @@ -188,8 +306,9 @@ | |||
292 | 188 | raise | 306 | raise |
293 | 189 | 307 | ||
294 | 190 | 308 | ||
296 | 191 | def relation_set(relation_id=None, relation_settings={}, **kwargs): | 309 | def relation_set(relation_id=None, relation_settings=None, **kwargs): |
297 | 192 | """Set relation information for the current unit""" | 310 | """Set relation information for the current unit""" |
298 | 311 | relation_settings = relation_settings if relation_settings else {} | ||
299 | 193 | relation_cmd_line = ['relation-set'] | 312 | relation_cmd_line = ['relation-set'] |
300 | 194 | if relation_id is not None: | 313 | if relation_id is not None: |
301 | 195 | relation_cmd_line.extend(('-r', relation_id)) | 314 | relation_cmd_line.extend(('-r', relation_id)) |
302 | @@ -348,27 +467,29 @@ | |||
303 | 348 | class Hooks(object): | 467 | class Hooks(object): |
304 | 349 | """A convenient handler for hook functions. | 468 | """A convenient handler for hook functions. |
305 | 350 | 469 | ||
307 | 351 | Example: | 470 | Example:: |
308 | 471 | |||
309 | 352 | hooks = Hooks() | 472 | hooks = Hooks() |
310 | 353 | 473 | ||
311 | 354 | # register a hook, taking its name from the function name | 474 | # register a hook, taking its name from the function name |
312 | 355 | @hooks.hook() | 475 | @hooks.hook() |
313 | 356 | def install(): | 476 | def install(): |
315 | 357 | ... | 477 | pass # your code here |
316 | 358 | 478 | ||
317 | 359 | # register a hook, providing a custom hook name | 479 | # register a hook, providing a custom hook name |
318 | 360 | @hooks.hook("config-changed") | 480 | @hooks.hook("config-changed") |
319 | 361 | def config_changed(): | 481 | def config_changed(): |
321 | 362 | ... | 482 | pass # your code here |
322 | 363 | 483 | ||
323 | 364 | if __name__ == "__main__": | 484 | if __name__ == "__main__": |
324 | 365 | # execute a hook based on the name the program is called by | 485 | # execute a hook based on the name the program is called by |
325 | 366 | hooks.execute(sys.argv) | 486 | hooks.execute(sys.argv) |
326 | 367 | """ | 487 | """ |
327 | 368 | 488 | ||
329 | 369 | def __init__(self): | 489 | def __init__(self, config_save=True): |
330 | 370 | super(Hooks, self).__init__() | 490 | super(Hooks, self).__init__() |
331 | 371 | self._hooks = {} | 491 | self._hooks = {} |
332 | 492 | self._config_save = config_save | ||
333 | 372 | 493 | ||
334 | 373 | def register(self, name, function): | 494 | def register(self, name, function): |
335 | 374 | """Register a hook""" | 495 | """Register a hook""" |
336 | @@ -379,6 +500,10 @@ | |||
337 | 379 | hook_name = os.path.basename(args[0]) | 500 | hook_name = os.path.basename(args[0]) |
338 | 380 | if hook_name in self._hooks: | 501 | if hook_name in self._hooks: |
339 | 381 | self._hooks[hook_name]() | 502 | self._hooks[hook_name]() |
340 | 503 | if self._config_save: | ||
341 | 504 | cfg = config() | ||
342 | 505 | if cfg.implicit_save: | ||
343 | 506 | cfg.save() | ||
344 | 382 | else: | 507 | else: |
345 | 383 | raise UnregisteredHookError(hook_name) | 508 | raise UnregisteredHookError(hook_name) |
346 | 384 | 509 | ||
347 | 385 | 510 | ||
348 | === modified file 'hooks/charmhelpers/core/host.py' | |||
349 | --- hooks/charmhelpers/core/host.py 2014-02-19 14:49:31 +0000 | |||
350 | +++ hooks/charmhelpers/core/host.py 2014-09-26 07:21:45 +0000 | |||
351 | @@ -12,10 +12,13 @@ | |||
352 | 12 | import string | 12 | import string |
353 | 13 | import subprocess | 13 | import subprocess |
354 | 14 | import hashlib | 14 | import hashlib |
355 | 15 | import shutil | ||
356 | 16 | from contextlib import contextmanager | ||
357 | 15 | 17 | ||
358 | 16 | from collections import OrderedDict | 18 | from collections import OrderedDict |
359 | 17 | 19 | ||
360 | 18 | from hookenv import log | 20 | from hookenv import log |
361 | 21 | from fstab import Fstab | ||
362 | 19 | 22 | ||
363 | 20 | 23 | ||
364 | 21 | def service_start(service_name): | 24 | def service_start(service_name): |
365 | @@ -34,7 +37,8 @@ | |||
366 | 34 | 37 | ||
367 | 35 | 38 | ||
368 | 36 | def service_reload(service_name, restart_on_failure=False): | 39 | def service_reload(service_name, restart_on_failure=False): |
370 | 37 | """Reload a system service, optionally falling back to restart if reload fails""" | 40 | """Reload a system service, optionally falling back to restart if |
371 | 41 | reload fails""" | ||
372 | 38 | service_result = service('reload', service_name) | 42 | service_result = service('reload', service_name) |
373 | 39 | if not service_result and restart_on_failure: | 43 | if not service_result and restart_on_failure: |
374 | 40 | service_result = service('restart', service_name) | 44 | service_result = service('restart', service_name) |
375 | @@ -50,7 +54,7 @@ | |||
376 | 50 | def service_running(service): | 54 | def service_running(service): |
377 | 51 | """Determine whether a system service is running""" | 55 | """Determine whether a system service is running""" |
378 | 52 | try: | 56 | try: |
380 | 53 | output = subprocess.check_output(['service', service, 'status']) | 57 | output = subprocess.check_output(['service', service, 'status'], stderr=subprocess.STDOUT) |
381 | 54 | except subprocess.CalledProcessError: | 58 | except subprocess.CalledProcessError: |
382 | 55 | return False | 59 | return False |
383 | 56 | else: | 60 | else: |
384 | @@ -60,6 +64,16 @@ | |||
385 | 60 | return False | 64 | return False |
386 | 61 | 65 | ||
387 | 62 | 66 | ||
388 | 67 | def service_available(service_name): | ||
389 | 68 | """Determine whether a system service is available""" | ||
390 | 69 | try: | ||
391 | 70 | subprocess.check_output(['service', service_name, 'status'], stderr=subprocess.STDOUT) | ||
392 | 71 | except subprocess.CalledProcessError as e: | ||
393 | 72 | return 'unrecognized service' not in e.output | ||
394 | 73 | else: | ||
395 | 74 | return True | ||
396 | 75 | |||
397 | 76 | |||
398 | 63 | def adduser(username, password=None, shell='/bin/bash', system_user=False): | 77 | def adduser(username, password=None, shell='/bin/bash', system_user=False): |
399 | 64 | """Add a user to the system""" | 78 | """Add a user to the system""" |
400 | 65 | try: | 79 | try: |
401 | @@ -143,7 +157,19 @@ | |||
402 | 143 | target.write(content) | 157 | target.write(content) |
403 | 144 | 158 | ||
404 | 145 | 159 | ||
406 | 146 | def mount(device, mountpoint, options=None, persist=False): | 160 | def fstab_remove(mp): |
407 | 161 | """Remove the given mountpoint entry from /etc/fstab | ||
408 | 162 | """ | ||
409 | 163 | return Fstab.remove_by_mountpoint(mp) | ||
410 | 164 | |||
411 | 165 | |||
412 | 166 | def fstab_add(dev, mp, fs, options=None): | ||
413 | 167 | """Adds the given device entry to the /etc/fstab file | ||
414 | 168 | """ | ||
415 | 169 | return Fstab.add(dev, mp, fs, options=options) | ||
416 | 170 | |||
417 | 171 | |||
418 | 172 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): | ||
419 | 147 | """Mount a filesystem at a particular mountpoint""" | 173 | """Mount a filesystem at a particular mountpoint""" |
420 | 148 | cmd_args = ['mount'] | 174 | cmd_args = ['mount'] |
421 | 149 | if options is not None: | 175 | if options is not None: |
422 | @@ -154,9 +180,9 @@ | |||
423 | 154 | except subprocess.CalledProcessError, e: | 180 | except subprocess.CalledProcessError, e: |
424 | 155 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | 181 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) |
425 | 156 | return False | 182 | return False |
426 | 183 | |||
427 | 157 | if persist: | 184 | if persist: |
430 | 158 | # TODO: update fstab | 185 | return fstab_add(device, mountpoint, filesystem, options=options) |
429 | 159 | pass | ||
431 | 160 | return True | 186 | return True |
432 | 161 | 187 | ||
433 | 162 | 188 | ||
434 | @@ -168,9 +194,9 @@ | |||
435 | 168 | except subprocess.CalledProcessError, e: | 194 | except subprocess.CalledProcessError, e: |
436 | 169 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | 195 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) |
437 | 170 | return False | 196 | return False |
438 | 197 | |||
439 | 171 | if persist: | 198 | if persist: |
442 | 172 | # TODO: update fstab | 199 | return fstab_remove(mountpoint) |
441 | 173 | pass | ||
443 | 174 | return True | 200 | return True |
444 | 175 | 201 | ||
445 | 176 | 202 | ||
446 | @@ -183,10 +209,15 @@ | |||
447 | 183 | return system_mounts | 209 | return system_mounts |
448 | 184 | 210 | ||
449 | 185 | 211 | ||
452 | 186 | def file_hash(path): | 212 | def file_hash(path, hash_type='md5'): |
453 | 187 | """Generate a md5 hash of the contents of 'path' or None if not found """ | 213 | """ |
454 | 214 | Generate a hash checksum of the contents of 'path' or None if not found. | ||
455 | 215 | |||
456 | 216 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
457 | 217 | such as md5, sha1, sha256, sha512, etc. | ||
458 | 218 | """ | ||
459 | 188 | if os.path.exists(path): | 219 | if os.path.exists(path): |
461 | 189 | h = hashlib.md5() | 220 | h = getattr(hashlib, hash_type)() |
462 | 190 | with open(path, 'r') as source: | 221 | with open(path, 'r') as source: |
463 | 191 | h.update(source.read()) # IGNORE:E1101 - it does have update | 222 | h.update(source.read()) # IGNORE:E1101 - it does have update |
464 | 192 | return h.hexdigest() | 223 | return h.hexdigest() |
465 | @@ -194,16 +225,36 @@ | |||
466 | 194 | return None | 225 | return None |
467 | 195 | 226 | ||
468 | 196 | 227 | ||
469 | 228 | def check_hash(path, checksum, hash_type='md5'): | ||
470 | 229 | """ | ||
471 | 230 | Validate a file using a cryptographic checksum. | ||
472 | 231 | |||
473 | 232 | :param str checksum: Value of the checksum used to validate the file. | ||
474 | 233 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
475 | 234 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
476 | 235 | such as md5, sha1, sha256, sha512, etc. | ||
477 | 236 | :raises ChecksumError: If the file fails the checksum | ||
478 | 237 | |||
479 | 238 | """ | ||
480 | 239 | actual_checksum = file_hash(path, hash_type) | ||
481 | 240 | if checksum != actual_checksum: | ||
482 | 241 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
483 | 242 | |||
484 | 243 | |||
485 | 244 | class ChecksumError(ValueError): | ||
486 | 245 | pass | ||
487 | 246 | |||
488 | 247 | |||
489 | 197 | def restart_on_change(restart_map, stopstart=False): | 248 | def restart_on_change(restart_map, stopstart=False): |
490 | 198 | """Restart services based on configuration files changing | 249 | """Restart services based on configuration files changing |
491 | 199 | 250 | ||
493 | 200 | This function is used a decorator, for example | 251 | This function is used a decorator, for example:: |
494 | 201 | 252 | ||
495 | 202 | @restart_on_change({ | 253 | @restart_on_change({ |
496 | 203 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] | 254 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] |
497 | 204 | }) | 255 | }) |
498 | 205 | def ceph_client_changed(): | 256 | def ceph_client_changed(): |
500 | 206 | ... | 257 | pass # your code here |
501 | 207 | 258 | ||
502 | 208 | In this example, the cinder-api and cinder-volume services | 259 | In this example, the cinder-api and cinder-volume services |
503 | 209 | would be restarted if /etc/ceph/ceph.conf is changed by the | 260 | would be restarted if /etc/ceph/ceph.conf is changed by the |
504 | @@ -295,3 +346,40 @@ | |||
505 | 295 | if 'link/ether' in words: | 346 | if 'link/ether' in words: |
506 | 296 | hwaddr = words[words.index('link/ether') + 1] | 347 | hwaddr = words[words.index('link/ether') + 1] |
507 | 297 | return hwaddr | 348 | return hwaddr |
508 | 349 | |||
509 | 350 | |||
510 | 351 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
511 | 352 | '''Compare supplied revno with the revno of the installed package | ||
512 | 353 | |||
513 | 354 | * 1 => Installed revno is greater than supplied arg | ||
514 | 355 | * 0 => Installed revno is the same as supplied arg | ||
515 | 356 | * -1 => Installed revno is less than supplied arg | ||
516 | 357 | |||
517 | 358 | ''' | ||
518 | 359 | import apt_pkg | ||
519 | 360 | from charmhelpers.fetch import apt_cache | ||
520 | 361 | if not pkgcache: | ||
521 | 362 | pkgcache = apt_cache() | ||
522 | 363 | pkg = pkgcache[package] | ||
523 | 364 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | ||
524 | 365 | |||
525 | 366 | |||
526 | 367 | @contextmanager | ||
527 | 368 | def chdir(d): | ||
528 | 369 | cur = os.getcwd() | ||
529 | 370 | try: | ||
530 | 371 | yield os.chdir(d) | ||
531 | 372 | finally: | ||
532 | 373 | os.chdir(cur) | ||
533 | 374 | |||
534 | 375 | |||
535 | 376 | def chownr(path, owner, group): | ||
536 | 377 | uid = pwd.getpwnam(owner).pw_uid | ||
537 | 378 | gid = grp.getgrnam(group).gr_gid | ||
538 | 379 | |||
539 | 380 | for root, dirs, files in os.walk(path): | ||
540 | 381 | for name in dirs + files: | ||
541 | 382 | full = os.path.join(root, name) | ||
542 | 383 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | ||
543 | 384 | if not broken_symlink: | ||
544 | 385 | os.chown(full, uid, gid) | ||
545 | 298 | 386 | ||
546 | === added directory 'hooks/charmhelpers/core/services' | |||
547 | === added file 'hooks/charmhelpers/core/services/__init__.py' | |||
548 | --- hooks/charmhelpers/core/services/__init__.py 1970-01-01 00:00:00 +0000 | |||
549 | +++ hooks/charmhelpers/core/services/__init__.py 2014-09-26 07:21:45 +0000 | |||
550 | @@ -0,0 +1,2 @@ | |||
551 | 1 | from .base import * | ||
552 | 2 | from .helpers import * | ||
553 | 0 | 3 | ||
554 | === added file 'hooks/charmhelpers/core/services/base.py' | |||
555 | --- hooks/charmhelpers/core/services/base.py 1970-01-01 00:00:00 +0000 | |||
556 | +++ hooks/charmhelpers/core/services/base.py 2014-09-26 07:21:45 +0000 | |||
557 | @@ -0,0 +1,313 @@ | |||
558 | 1 | import os | ||
559 | 2 | import re | ||
560 | 3 | import json | ||
561 | 4 | from collections import Iterable | ||
562 | 5 | |||
563 | 6 | from charmhelpers.core import host | ||
564 | 7 | from charmhelpers.core import hookenv | ||
565 | 8 | |||
566 | 9 | |||
567 | 10 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
568 | 11 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
569 | 12 | 'service_restart', 'service_stop'] | ||
570 | 13 | |||
571 | 14 | |||
572 | 15 | class ServiceManager(object): | ||
573 | 16 | def __init__(self, services=None): | ||
574 | 17 | """ | ||
575 | 18 | Register a list of services, given their definitions. | ||
576 | 19 | |||
577 | 20 | Service definitions are dicts in the following formats (all keys except | ||
578 | 21 | 'service' are optional):: | ||
579 | 22 | |||
580 | 23 | { | ||
581 | 24 | "service": <service name>, | ||
582 | 25 | "required_data": <list of required data contexts>, | ||
583 | 26 | "provided_data": <list of provided data contexts>, | ||
584 | 27 | "data_ready": <one or more callbacks>, | ||
585 | 28 | "data_lost": <one or more callbacks>, | ||
586 | 29 | "start": <one or more callbacks>, | ||
587 | 30 | "stop": <one or more callbacks>, | ||
588 | 31 | "ports": <list of ports to manage>, | ||
589 | 32 | } | ||
590 | 33 | |||
591 | 34 | The 'required_data' list should contain dicts of required data (or | ||
592 | 35 | dependency managers that act like dicts and know how to collect the data). | ||
593 | 36 | Only when all items in the 'required_data' list are populated are the list | ||
594 | 37 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
595 | 38 | information. | ||
596 | 39 | |||
597 | 40 | The 'provided_data' list should contain relation data providers, most likely | ||
598 | 41 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
599 | 42 | that will indicate a set of data to set on a given relation. | ||
600 | 43 | |||
601 | 44 | The 'data_ready' value should be either a single callback, or a list of | ||
602 | 45 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
603 | 46 | Each callback will be called with the service name as the only parameter. | ||
604 | 47 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
605 | 48 | are fired. | ||
606 | 49 | |||
607 | 50 | The 'data_lost' value should be either a single callback, or a list of | ||
608 | 51 | callbacks, to be called when a 'required_data' item no longer passes | ||
609 | 52 | `is_ready()`. Each callback will be called with the service name as the | ||
610 | 53 | only parameter. After all of the 'data_lost' callbacks are called, | ||
611 | 54 | the 'stop' callbacks are fired. | ||
612 | 55 | |||
613 | 56 | The 'start' value should be either a single callback, or a list of | ||
614 | 57 | callbacks, to be called when starting the service, after the 'data_ready' | ||
615 | 58 | callbacks are complete. Each callback will be called with the service | ||
616 | 59 | name as the only parameter. This defaults to | ||
617 | 60 | `[host.service_start, services.open_ports]`. | ||
618 | 61 | |||
619 | 62 | The 'stop' value should be either a single callback, or a list of | ||
620 | 63 | callbacks, to be called when stopping the service. If the service is | ||
621 | 64 | being stopped because it no longer has all of its 'required_data', this | ||
622 | 65 | will be called after all of the 'data_lost' callbacks are complete. | ||
623 | 66 | Each callback will be called with the service name as the only parameter. | ||
624 | 67 | This defaults to `[services.close_ports, host.service_stop]`. | ||
625 | 68 | |||
626 | 69 | The 'ports' value should be a list of ports to manage. The default | ||
627 | 70 | 'start' handler will open the ports after the service is started, | ||
628 | 71 | and the default 'stop' handler will close the ports prior to stopping | ||
629 | 72 | the service. | ||
630 | 73 | |||
631 | 74 | |||
632 | 75 | Examples: | ||
633 | 76 | |||
634 | 77 | The following registers an Upstart service called bingod that depends on | ||
635 | 78 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
636 | 79 | restarting the service, and a Runit service called spadesd:: | ||
637 | 80 | |||
638 | 81 | manager = services.ServiceManager([ | ||
639 | 82 | { | ||
640 | 83 | 'service': 'bingod', | ||
641 | 84 | 'ports': [80, 443], | ||
642 | 85 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
643 | 86 | 'data_ready': [ | ||
644 | 87 | services.template(source='bingod.conf'), | ||
645 | 88 | services.template(source='bingod.ini', | ||
646 | 89 | target='/etc/bingod.ini', | ||
647 | 90 | owner='bingo', perms=0400), | ||
648 | 91 | ], | ||
649 | 92 | }, | ||
650 | 93 | { | ||
651 | 94 | 'service': 'spadesd', | ||
652 | 95 | 'data_ready': services.template(source='spadesd_run.j2', | ||
653 | 96 | target='/etc/sv/spadesd/run', | ||
654 | 97 | perms=0555), | ||
655 | 98 | 'start': runit_start, | ||
656 | 99 | 'stop': runit_stop, | ||
657 | 100 | }, | ||
658 | 101 | ]) | ||
659 | 102 | manager.manage() | ||
660 | 103 | """ | ||
661 | 104 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
662 | 105 | self._ready = None | ||
663 | 106 | self.services = {} | ||
664 | 107 | for service in services or []: | ||
665 | 108 | service_name = service['service'] | ||
666 | 109 | self.services[service_name] = service | ||
667 | 110 | |||
668 | 111 | def manage(self): | ||
669 | 112 | """ | ||
670 | 113 | Handle the current hook by doing The Right Thing with the registered services. | ||
671 | 114 | """ | ||
672 | 115 | hook_name = hookenv.hook_name() | ||
673 | 116 | if hook_name == 'stop': | ||
674 | 117 | self.stop_services() | ||
675 | 118 | else: | ||
676 | 119 | self.provide_data() | ||
677 | 120 | self.reconfigure_services() | ||
678 | 121 | cfg = hookenv.config() | ||
679 | 122 | if cfg.implicit_save: | ||
680 | 123 | cfg.save() | ||
681 | 124 | |||
682 | 125 | def provide_data(self): | ||
683 | 126 | """ | ||
684 | 127 | Set the relation data for each provider in the ``provided_data`` list. | ||
685 | 128 | |||
686 | 129 | A provider must have a `name` attribute, which indicates which relation | ||
687 | 130 | to set data on, and a `provide_data()` method, which returns a dict of | ||
688 | 131 | data to set. | ||
689 | 132 | """ | ||
690 | 133 | hook_name = hookenv.hook_name() | ||
691 | 134 | for service in self.services.values(): | ||
692 | 135 | for provider in service.get('provided_data', []): | ||
693 | 136 | if re.match(r'{}-relation-(joined|changed)'.format(provider.name), hook_name): | ||
694 | 137 | data = provider.provide_data() | ||
695 | 138 | _ready = provider._is_ready(data) if hasattr(provider, '_is_ready') else data | ||
696 | 139 | if _ready: | ||
697 | 140 | hookenv.relation_set(None, data) | ||
698 | 141 | |||
699 | 142 | def reconfigure_services(self, *service_names): | ||
700 | 143 | """ | ||
701 | 144 | Update all files for one or more registered services, and, | ||
702 | 145 | if ready, optionally restart them. | ||
703 | 146 | |||
704 | 147 | If no service names are given, reconfigures all registered services. | ||
705 | 148 | """ | ||
706 | 149 | for service_name in service_names or self.services.keys(): | ||
707 | 150 | if self.is_ready(service_name): | ||
708 | 151 | self.fire_event('data_ready', service_name) | ||
709 | 152 | self.fire_event('start', service_name, default=[ | ||
710 | 153 | service_restart, | ||
711 | 154 | manage_ports]) | ||
712 | 155 | self.save_ready(service_name) | ||
713 | 156 | else: | ||
714 | 157 | if self.was_ready(service_name): | ||
715 | 158 | self.fire_event('data_lost', service_name) | ||
716 | 159 | self.fire_event('stop', service_name, default=[ | ||
717 | 160 | manage_ports, | ||
718 | 161 | service_stop]) | ||
719 | 162 | self.save_lost(service_name) | ||
720 | 163 | |||
721 | 164 | def stop_services(self, *service_names): | ||
722 | 165 | """ | ||
723 | 166 | Stop one or more registered services, by name. | ||
724 | 167 | |||
725 | 168 | If no service names are given, stops all registered services. | ||
726 | 169 | """ | ||
727 | 170 | for service_name in service_names or self.services.keys(): | ||
728 | 171 | self.fire_event('stop', service_name, default=[ | ||
729 | 172 | manage_ports, | ||
730 | 173 | service_stop]) | ||
731 | 174 | |||
732 | 175 | def get_service(self, service_name): | ||
733 | 176 | """ | ||
734 | 177 | Given the name of a registered service, return its service definition. | ||
735 | 178 | """ | ||
736 | 179 | service = self.services.get(service_name) | ||
737 | 180 | if not service: | ||
738 | 181 | raise KeyError('Service not registered: %s' % service_name) | ||
739 | 182 | return service | ||
740 | 183 | |||
741 | 184 | def fire_event(self, event_name, service_name, default=None): | ||
742 | 185 | """ | ||
743 | 186 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
744 | 187 | """ | ||
745 | 188 | service = self.get_service(service_name) | ||
746 | 189 | callbacks = service.get(event_name, default) | ||
747 | 190 | if not callbacks: | ||
748 | 191 | return | ||
749 | 192 | if not isinstance(callbacks, Iterable): | ||
750 | 193 | callbacks = [callbacks] | ||
751 | 194 | for callback in callbacks: | ||
752 | 195 | if isinstance(callback, ManagerCallback): | ||
753 | 196 | callback(self, service_name, event_name) | ||
754 | 197 | else: | ||
755 | 198 | callback(service_name) | ||
756 | 199 | |||
757 | 200 | def is_ready(self, service_name): | ||
758 | 201 | """ | ||
759 | 202 | Determine if a registered service is ready, by checking its 'required_data'. | ||
760 | 203 | |||
761 | 204 | A 'required_data' item can be any mapping type, and is considered ready | ||
762 | 205 | if `bool(item)` evaluates as True. | ||
763 | 206 | """ | ||
764 | 207 | service = self.get_service(service_name) | ||
765 | 208 | reqs = service.get('required_data', []) | ||
766 | 209 | return all(bool(req) for req in reqs) | ||
767 | 210 | |||
768 | 211 | def _load_ready_file(self): | ||
769 | 212 | if self._ready is not None: | ||
770 | 213 | return | ||
771 | 214 | if os.path.exists(self._ready_file): | ||
772 | 215 | with open(self._ready_file) as fp: | ||
773 | 216 | self._ready = set(json.load(fp)) | ||
774 | 217 | else: | ||
775 | 218 | self._ready = set() | ||
776 | 219 | |||
777 | 220 | def _save_ready_file(self): | ||
778 | 221 | if self._ready is None: | ||
779 | 222 | return | ||
780 | 223 | with open(self._ready_file, 'w') as fp: | ||
781 | 224 | json.dump(list(self._ready), fp) | ||
782 | 225 | |||
783 | 226 | def save_ready(self, service_name): | ||
784 | 227 | """ | ||
785 | 228 | Save an indicator that the given service is now data_ready. | ||
786 | 229 | """ | ||
787 | 230 | self._load_ready_file() | ||
788 | 231 | self._ready.add(service_name) | ||
789 | 232 | self._save_ready_file() | ||
790 | 233 | |||
791 | 234 | def save_lost(self, service_name): | ||
792 | 235 | """ | ||
793 | 236 | Save an indicator that the given service is no longer data_ready. | ||
794 | 237 | """ | ||
795 | 238 | self._load_ready_file() | ||
796 | 239 | self._ready.discard(service_name) | ||
797 | 240 | self._save_ready_file() | ||
798 | 241 | |||
799 | 242 | def was_ready(self, service_name): | ||
800 | 243 | """ | ||
801 | 244 | Determine if the given service was previously data_ready. | ||
802 | 245 | """ | ||
803 | 246 | self._load_ready_file() | ||
804 | 247 | return service_name in self._ready | ||
805 | 248 | |||
806 | 249 | |||
807 | 250 | class ManagerCallback(object): | ||
808 | 251 | """ | ||
809 | 252 | Special case of a callback that takes the `ServiceManager` instance | ||
810 | 253 | in addition to the service name. | ||
811 | 254 | |||
812 | 255 | Subclasses should implement `__call__` which should accept three parameters: | ||
813 | 256 | |||
814 | 257 | * `manager` The `ServiceManager` instance | ||
815 | 258 | * `service_name` The name of the service it's being triggered for | ||
816 | 259 | * `event_name` The name of the event that this callback is handling | ||
817 | 260 | """ | ||
818 | 261 | def __call__(self, manager, service_name, event_name): | ||
819 | 262 | raise NotImplementedError() | ||
820 | 263 | |||
821 | 264 | |||
822 | 265 | class PortManagerCallback(ManagerCallback): | ||
823 | 266 | """ | ||
824 | 267 | Callback class that will open or close ports, for use as either | ||
825 | 268 | a start or stop action. | ||
826 | 269 | """ | ||
827 | 270 | def __call__(self, manager, service_name, event_name): | ||
828 | 271 | service = manager.get_service(service_name) | ||
829 | 272 | new_ports = service.get('ports', []) | ||
830 | 273 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
831 | 274 | if os.path.exists(port_file): | ||
832 | 275 | with open(port_file) as fp: | ||
833 | 276 | old_ports = fp.read().split(',') | ||
834 | 277 | for old_port in old_ports: | ||
835 | 278 | if bool(old_port): | ||
836 | 279 | old_port = int(old_port) | ||
837 | 280 | if old_port not in new_ports: | ||
838 | 281 | hookenv.close_port(old_port) | ||
839 | 282 | with open(port_file, 'w') as fp: | ||
840 | 283 | fp.write(','.join(str(port) for port in new_ports)) | ||
841 | 284 | for port in new_ports: | ||
842 | 285 | if event_name == 'start': | ||
843 | 286 | hookenv.open_port(port) | ||
844 | 287 | elif event_name == 'stop': | ||
845 | 288 | hookenv.close_port(port) | ||
846 | 289 | |||
847 | 290 | |||
848 | 291 | def service_stop(service_name): | ||
849 | 292 | """ | ||
850 | 293 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
851 | 294 | messages in the logs. | ||
852 | 295 | """ | ||
853 | 296 | if host.service_running(service_name): | ||
854 | 297 | host.service_stop(service_name) | ||
855 | 298 | |||
856 | 299 | |||
857 | 300 | def service_restart(service_name): | ||
858 | 301 | """ | ||
859 | 302 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
860 | 303 | messages in the logs. | ||
861 | 304 | """ | ||
862 | 305 | if host.service_available(service_name): | ||
863 | 306 | if host.service_running(service_name): | ||
864 | 307 | host.service_restart(service_name) | ||
865 | 308 | else: | ||
866 | 309 | host.service_start(service_name) | ||
867 | 310 | |||
868 | 311 | |||
869 | 312 | # Convenience aliases | ||
870 | 313 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
871 | 0 | 314 | ||
872 | === added file 'hooks/charmhelpers/core/services/helpers.py' | |||
873 | --- hooks/charmhelpers/core/services/helpers.py 1970-01-01 00:00:00 +0000 | |||
874 | +++ hooks/charmhelpers/core/services/helpers.py 2014-09-26 07:21:45 +0000 | |||
875 | @@ -0,0 +1,239 @@ | |||
876 | 1 | import os | ||
877 | 2 | import yaml | ||
878 | 3 | from charmhelpers.core import hookenv | ||
879 | 4 | from charmhelpers.core import templating | ||
880 | 5 | |||
881 | 6 | from charmhelpers.core.services.base import ManagerCallback | ||
882 | 7 | |||
883 | 8 | |||
884 | 9 | __all__ = ['RelationContext', 'TemplateCallback', | ||
885 | 10 | 'render_template', 'template'] | ||
886 | 11 | |||
887 | 12 | |||
888 | 13 | class RelationContext(dict): | ||
889 | 14 | """ | ||
890 | 15 | Base class for a context generator that gets relation data from juju. | ||
891 | 16 | |||
892 | 17 | Subclasses must provide the attributes `name`, which is the name of the | ||
893 | 18 | interface of interest, `interface`, which is the type of the interface of | ||
894 | 19 | interest, and `required_keys`, which is the set of keys required for the | ||
895 | 20 | relation to be considered complete. The data for all interfaces matching | ||
896 | 21 | the `name` attribute that are complete will used to populate the dictionary | ||
897 | 22 | values (see `get_data`, below). | ||
898 | 23 | |||
899 | 24 | The generated context will be namespaced under the relation :attr:`name`, | ||
900 | 25 | to prevent potential naming conflicts. | ||
901 | 26 | |||
902 | 27 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
903 | 28 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
904 | 29 | """ | ||
905 | 30 | name = None | ||
906 | 31 | interface = None | ||
907 | 32 | required_keys = [] | ||
908 | 33 | |||
909 | 34 | def __init__(self, name=None, additional_required_keys=None): | ||
910 | 35 | if name is not None: | ||
911 | 36 | self.name = name | ||
912 | 37 | if additional_required_keys is not None: | ||
913 | 38 | self.required_keys.extend(additional_required_keys) | ||
914 | 39 | self.get_data() | ||
915 | 40 | |||
916 | 41 | def __bool__(self): | ||
917 | 42 | """ | ||
918 | 43 | Returns True if all of the required_keys are available. | ||
919 | 44 | """ | ||
920 | 45 | return self.is_ready() | ||
921 | 46 | |||
922 | 47 | __nonzero__ = __bool__ | ||
923 | 48 | |||
924 | 49 | def __repr__(self): | ||
925 | 50 | return super(RelationContext, self).__repr__() | ||
926 | 51 | |||
927 | 52 | def is_ready(self): | ||
928 | 53 | """ | ||
929 | 54 | Returns True if all of the `required_keys` are available from any units. | ||
930 | 55 | """ | ||
931 | 56 | ready = len(self.get(self.name, [])) > 0 | ||
932 | 57 | if not ready: | ||
933 | 58 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
934 | 59 | return ready | ||
935 | 60 | |||
936 | 61 | def _is_ready(self, unit_data): | ||
937 | 62 | """ | ||
938 | 63 | Helper method that tests a set of relation data and returns True if | ||
939 | 64 | all of the `required_keys` are present. | ||
940 | 65 | """ | ||
941 | 66 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
942 | 67 | |||
943 | 68 | def get_data(self): | ||
944 | 69 | """ | ||
945 | 70 | Retrieve the relation data for each unit involved in a relation and, | ||
946 | 71 | if complete, store it in a list under `self[self.name]`. This | ||
947 | 72 | is automatically called when the RelationContext is instantiated. | ||
948 | 73 | |||
949 | 74 | The units are sorted lexographically first by the service ID, then by | ||
950 | 75 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
951 | 76 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
952 | 77 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
953 | 78 | set of data, the relation data for the units will be stored in the | ||
954 | 79 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
955 | 80 | |||
956 | 81 | If you only care about a single unit on the relation, you can just | ||
957 | 82 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
958 | 83 | support multiple units on a relation, you should iterate over the list, | ||
959 | 84 | like:: | ||
960 | 85 | |||
961 | 86 | {% for unit in interface -%} | ||
962 | 87 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
963 | 88 | {%- endfor %} | ||
964 | 89 | |||
965 | 90 | Note that since all sets of relation data from all related services and | ||
966 | 91 | units are in a single list, if you need to know which service or unit a | ||
967 | 92 | set of data came from, you'll need to extend this class to preserve | ||
968 | 93 | that information. | ||
969 | 94 | """ | ||
970 | 95 | if not hookenv.relation_ids(self.name): | ||
971 | 96 | return | ||
972 | 97 | |||
973 | 98 | ns = self.setdefault(self.name, []) | ||
974 | 99 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
975 | 100 | for unit in sorted(hookenv.related_units(rid)): | ||
976 | 101 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
977 | 102 | if self._is_ready(reldata): | ||
978 | 103 | ns.append(reldata) | ||
979 | 104 | |||
980 | 105 | def provide_data(self): | ||
981 | 106 | """ | ||
982 | 107 | Return data to be relation_set for this interface. | ||
983 | 108 | """ | ||
984 | 109 | return {} | ||
985 | 110 | |||
986 | 111 | |||
987 | 112 | class MysqlRelation(RelationContext): | ||
988 | 113 | """ | ||
989 | 114 | Relation context for the `mysql` interface. | ||
990 | 115 | |||
991 | 116 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
992 | 117 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
993 | 118 | """ | ||
994 | 119 | name = 'db' | ||
995 | 120 | interface = 'mysql' | ||
996 | 121 | required_keys = ['host', 'user', 'password', 'database'] | ||
997 | 122 | |||
998 | 123 | |||
999 | 124 | class HttpRelation(RelationContext): | ||
1000 | 125 | """ | ||
1001 | 126 | Relation context for the `http` interface. | ||
1002 | 127 | |||
1003 | 128 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1004 | 129 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1005 | 130 | """ | ||
1006 | 131 | name = 'website' | ||
1007 | 132 | interface = 'http' | ||
1008 | 133 | required_keys = ['host', 'port'] | ||
1009 | 134 | |||
1010 | 135 | def provide_data(self): | ||
1011 | 136 | return { | ||
1012 | 137 | 'host': hookenv.unit_get('private-address'), | ||
1013 | 138 | 'port': 80, | ||
1014 | 139 | } | ||
1015 | 140 | |||
1016 | 141 | |||
1017 | 142 | class RequiredConfig(dict): | ||
1018 | 143 | """ | ||
1019 | 144 | Data context that loads config options with one or more mandatory options. | ||
1020 | 145 | |||
1021 | 146 | Once the required options have been changed from their default values, all | ||
1022 | 147 | config options will be available, namespaced under `config` to prevent | ||
1023 | 148 | potential naming conflicts (for example, between a config option and a | ||
1024 | 149 | relation property). | ||
1025 | 150 | |||
1026 | 151 | :param list *args: List of options that must be changed from their default values. | ||
1027 | 152 | """ | ||
1028 | 153 | |||
1029 | 154 | def __init__(self, *args): | ||
1030 | 155 | self.required_options = args | ||
1031 | 156 | self['config'] = hookenv.config() | ||
1032 | 157 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
1033 | 158 | self.config = yaml.load(fp).get('options', {}) | ||
1034 | 159 | |||
1035 | 160 | def __bool__(self): | ||
1036 | 161 | for option in self.required_options: | ||
1037 | 162 | if option not in self['config']: | ||
1038 | 163 | return False | ||
1039 | 164 | current_value = self['config'][option] | ||
1040 | 165 | default_value = self.config[option].get('default') | ||
1041 | 166 | if current_value == default_value: | ||
1042 | 167 | return False | ||
1043 | 168 | if current_value in (None, '') and default_value in (None, ''): | ||
1044 | 169 | return False | ||
1045 | 170 | return True | ||
1046 | 171 | |||
1047 | 172 | def __nonzero__(self): | ||
1048 | 173 | return self.__bool__() | ||
1049 | 174 | |||
1050 | 175 | |||
1051 | 176 | class StoredContext(dict): | ||
1052 | 177 | """ | ||
1053 | 178 | A data context that always returns the data that it was first created with. | ||
1054 | 179 | |||
1055 | 180 | This is useful to do a one-time generation of things like passwords, that | ||
1056 | 181 | will thereafter use the same value that was originally generated, instead | ||
1057 | 182 | of generating a new value each time it is run. | ||
1058 | 183 | """ | ||
1059 | 184 | def __init__(self, file_name, config_data): | ||
1060 | 185 | """ | ||
1061 | 186 | If the file exists, populate `self` with the data from the file. | ||
1062 | 187 | Otherwise, populate with the given data and persist it to the file. | ||
1063 | 188 | """ | ||
1064 | 189 | if os.path.exists(file_name): | ||
1065 | 190 | self.update(self.read_context(file_name)) | ||
1066 | 191 | else: | ||
1067 | 192 | self.store_context(file_name, config_data) | ||
1068 | 193 | self.update(config_data) | ||
1069 | 194 | |||
1070 | 195 | def store_context(self, file_name, config_data): | ||
1071 | 196 | if not os.path.isabs(file_name): | ||
1072 | 197 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
1073 | 198 | with open(file_name, 'w') as file_stream: | ||
1074 | 199 | os.fchmod(file_stream.fileno(), 0600) | ||
1075 | 200 | yaml.dump(config_data, file_stream) | ||
1076 | 201 | |||
1077 | 202 | def read_context(self, file_name): | ||
1078 | 203 | if not os.path.isabs(file_name): | ||
1079 | 204 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
1080 | 205 | with open(file_name, 'r') as file_stream: | ||
1081 | 206 | data = yaml.load(file_stream) | ||
1082 | 207 | if not data: | ||
1083 | 208 | raise OSError("%s is empty" % file_name) | ||
1084 | 209 | return data | ||
1085 | 210 | |||
1086 | 211 | |||
1087 | 212 | class TemplateCallback(ManagerCallback): | ||
1088 | 213 | """ | ||
1089 | 214 | Callback class that will render a Jinja2 template, for use as a ready action. | ||
1090 | 215 | |||
1091 | 216 | :param str source: The template source file, relative to `$CHARM_DIR/templates` | ||
1092 | 217 | :param str target: The target to write the rendered template to | ||
1093 | 218 | :param str owner: The owner of the rendered file | ||
1094 | 219 | :param str group: The group of the rendered file | ||
1095 | 220 | :param int perms: The permissions of the rendered file | ||
1096 | 221 | """ | ||
1097 | 222 | def __init__(self, source, target, owner='root', group='root', perms=0444): | ||
1098 | 223 | self.source = source | ||
1099 | 224 | self.target = target | ||
1100 | 225 | self.owner = owner | ||
1101 | 226 | self.group = group | ||
1102 | 227 | self.perms = perms | ||
1103 | 228 | |||
1104 | 229 | def __call__(self, manager, service_name, event_name): | ||
1105 | 230 | service = manager.get_service(service_name) | ||
1106 | 231 | context = {} | ||
1107 | 232 | for ctx in service.get('required_data', []): | ||
1108 | 233 | context.update(ctx) | ||
1109 | 234 | templating.render(self.source, self.target, context, | ||
1110 | 235 | self.owner, self.group, self.perms) | ||
1111 | 236 | |||
1112 | 237 | |||
1113 | 238 | # Convenience aliases for templates | ||
1114 | 239 | render_template = template = TemplateCallback | ||
1115 | 0 | 240 | ||
1116 | === added file 'hooks/charmhelpers/core/templating.py' | |||
1117 | --- hooks/charmhelpers/core/templating.py 1970-01-01 00:00:00 +0000 | |||
1118 | +++ hooks/charmhelpers/core/templating.py 2014-09-26 07:21:45 +0000 | |||
1119 | @@ -0,0 +1,51 @@ | |||
1120 | 1 | import os | ||
1121 | 2 | |||
1122 | 3 | from charmhelpers.core import host | ||
1123 | 4 | from charmhelpers.core import hookenv | ||
1124 | 5 | |||
1125 | 6 | |||
1126 | 7 | def render(source, target, context, owner='root', group='root', perms=0444, templates_dir=None): | ||
1127 | 8 | """ | ||
1128 | 9 | Render a template. | ||
1129 | 10 | |||
1130 | 11 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
1131 | 12 | |||
1132 | 13 | The `target` path should be absolute. | ||
1133 | 14 | |||
1134 | 15 | The context should be a dict containing the values to be replaced in the | ||
1135 | 16 | template. | ||
1136 | 17 | |||
1137 | 18 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
1138 | 19 | |||
1139 | 20 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
1140 | 21 | |||
1141 | 22 | Note: Using this requires python-jinja2; if it is not installed, calling | ||
1142 | 23 | this will attempt to use charmhelpers.fetch.apt_install to install it. | ||
1143 | 24 | """ | ||
1144 | 25 | try: | ||
1145 | 26 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
1146 | 27 | except ImportError: | ||
1147 | 28 | try: | ||
1148 | 29 | from charmhelpers.fetch import apt_install | ||
1149 | 30 | except ImportError: | ||
1150 | 31 | hookenv.log('Could not import jinja2, and could not import ' | ||
1151 | 32 | 'charmhelpers.fetch to install it', | ||
1152 | 33 | level=hookenv.ERROR) | ||
1153 | 34 | raise | ||
1154 | 35 | apt_install('python-jinja2', fatal=True) | ||
1155 | 36 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
1156 | 37 | |||
1157 | 38 | if templates_dir is None: | ||
1158 | 39 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
1159 | 40 | loader = Environment(loader=FileSystemLoader(templates_dir)) | ||
1160 | 41 | try: | ||
1161 | 42 | source = source | ||
1162 | 43 | template = loader.get_template(source) | ||
1163 | 44 | except exceptions.TemplateNotFound as e: | ||
1164 | 45 | hookenv.log('Could not load template %s from %s.' % | ||
1165 | 46 | (source, templates_dir), | ||
1166 | 47 | level=hookenv.ERROR) | ||
1167 | 48 | raise e | ||
1168 | 49 | content = template.render(context) | ||
1169 | 50 | host.mkdir(os.path.dirname(target)) | ||
1170 | 51 | host.write_file(target, content, owner, group, perms) | ||
1171 | 0 | 52 | ||
1172 | === modified file 'hooks/charmhelpers/fetch/__init__.py' | |||
1173 | --- hooks/charmhelpers/fetch/__init__.py 2014-05-08 10:22:43 +0000 | |||
1174 | +++ hooks/charmhelpers/fetch/__init__.py 2014-09-26 07:21:45 +0000 | |||
1175 | @@ -1,4 +1,6 @@ | |||
1176 | 1 | import importlib | 1 | import importlib |
1177 | 2 | from tempfile import NamedTemporaryFile | ||
1178 | 3 | import time | ||
1179 | 2 | from yaml import safe_load | 4 | from yaml import safe_load |
1180 | 3 | from charmhelpers.core.host import ( | 5 | from charmhelpers.core.host import ( |
1181 | 4 | lsb_release | 6 | lsb_release |
1182 | @@ -12,9 +14,9 @@ | |||
1183 | 12 | config, | 14 | config, |
1184 | 13 | log, | 15 | log, |
1185 | 14 | ) | 16 | ) |
1186 | 15 | import apt_pkg | ||
1187 | 16 | import os | 17 | import os |
1188 | 17 | 18 | ||
1189 | 19 | |||
1190 | 18 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive | 20 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive |
1191 | 19 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main | 21 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main |
1192 | 20 | """ | 22 | """ |
1193 | @@ -54,13 +56,68 @@ | |||
1194 | 54 | 'icehouse/proposed': 'precise-proposed/icehouse', | 56 | 'icehouse/proposed': 'precise-proposed/icehouse', |
1195 | 55 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', | 57 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', |
1196 | 56 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', | 58 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', |
1197 | 59 | # Juno | ||
1198 | 60 | 'juno': 'trusty-updates/juno', | ||
1199 | 61 | 'trusty-juno': 'trusty-updates/juno', | ||
1200 | 62 | 'trusty-juno/updates': 'trusty-updates/juno', | ||
1201 | 63 | 'trusty-updates/juno': 'trusty-updates/juno', | ||
1202 | 64 | 'juno/proposed': 'trusty-proposed/juno', | ||
1203 | 65 | 'juno/proposed': 'trusty-proposed/juno', | ||
1204 | 66 | 'trusty-juno/proposed': 'trusty-proposed/juno', | ||
1205 | 67 | 'trusty-proposed/juno': 'trusty-proposed/juno', | ||
1206 | 57 | } | 68 | } |
1207 | 58 | 69 | ||
1208 | 70 | # The order of this list is very important. Handlers should be listed in from | ||
1209 | 71 | # least- to most-specific URL matching. | ||
1210 | 72 | FETCH_HANDLERS = ( | ||
1211 | 73 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
1212 | 74 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
1213 | 75 | ) | ||
1214 | 76 | |||
1215 | 77 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. | ||
1216 | 78 | APT_NO_LOCK_RETRY_DELAY = 10 # Wait 10 seconds between apt lock checks. | ||
1217 | 79 | APT_NO_LOCK_RETRY_COUNT = 30 # Retry to acquire the lock X times. | ||
1218 | 80 | |||
1219 | 81 | |||
1220 | 82 | class SourceConfigError(Exception): | ||
1221 | 83 | pass | ||
1222 | 84 | |||
1223 | 85 | |||
1224 | 86 | class UnhandledSource(Exception): | ||
1225 | 87 | pass | ||
1226 | 88 | |||
1227 | 89 | |||
1228 | 90 | class AptLockError(Exception): | ||
1229 | 91 | pass | ||
1230 | 92 | |||
1231 | 93 | |||
1232 | 94 | class BaseFetchHandler(object): | ||
1233 | 95 | |||
1234 | 96 | """Base class for FetchHandler implementations in fetch plugins""" | ||
1235 | 97 | |||
1236 | 98 | def can_handle(self, source): | ||
1237 | 99 | """Returns True if the source can be handled. Otherwise returns | ||
1238 | 100 | a string explaining why it cannot""" | ||
1239 | 101 | return "Wrong source type" | ||
1240 | 102 | |||
1241 | 103 | def install(self, source): | ||
1242 | 104 | """Try to download and unpack the source. Return the path to the | ||
1243 | 105 | unpacked files or raise UnhandledSource.""" | ||
1244 | 106 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
1245 | 107 | |||
1246 | 108 | def parse_url(self, url): | ||
1247 | 109 | return urlparse(url) | ||
1248 | 110 | |||
1249 | 111 | def base_url(self, url): | ||
1250 | 112 | """Return url without querystring or fragment""" | ||
1251 | 113 | parts = list(self.parse_url(url)) | ||
1252 | 114 | parts[4:] = ['' for i in parts[4:]] | ||
1253 | 115 | return urlunparse(parts) | ||
1254 | 116 | |||
1255 | 59 | 117 | ||
1256 | 60 | def filter_installed_packages(packages): | 118 | def filter_installed_packages(packages): |
1257 | 61 | """Returns a list of packages that require installation""" | 119 | """Returns a list of packages that require installation""" |
1260 | 62 | apt_pkg.init() | 120 | cache = apt_cache() |
1259 | 63 | cache = apt_pkg.Cache() | ||
1261 | 64 | _pkgs = [] | 121 | _pkgs = [] |
1262 | 65 | for package in packages: | 122 | for package in packages: |
1263 | 66 | try: | 123 | try: |
1264 | @@ -73,6 +130,16 @@ | |||
1265 | 73 | return _pkgs | 130 | return _pkgs |
1266 | 74 | 131 | ||
1267 | 75 | 132 | ||
1268 | 133 | def apt_cache(in_memory=True): | ||
1269 | 134 | """Build and return an apt cache""" | ||
1270 | 135 | import apt_pkg | ||
1271 | 136 | apt_pkg.init() | ||
1272 | 137 | if in_memory: | ||
1273 | 138 | apt_pkg.config.set("Dir::Cache::pkgcache", "") | ||
1274 | 139 | apt_pkg.config.set("Dir::Cache::srcpkgcache", "") | ||
1275 | 140 | return apt_pkg.Cache() | ||
1276 | 141 | |||
1277 | 142 | |||
1278 | 76 | def apt_install(packages, options=None, fatal=False): | 143 | def apt_install(packages, options=None, fatal=False): |
1279 | 77 | """Install one or more packages""" | 144 | """Install one or more packages""" |
1280 | 78 | if options is None: | 145 | if options is None: |
1281 | @@ -87,14 +154,7 @@ | |||
1282 | 87 | cmd.extend(packages) | 154 | cmd.extend(packages) |
1283 | 88 | log("Installing {} with options: {}".format(packages, | 155 | log("Installing {} with options: {}".format(packages, |
1284 | 89 | options)) | 156 | options)) |
1293 | 90 | env = os.environ.copy() | 157 | _run_apt_command(cmd, fatal) |
1286 | 91 | if 'DEBIAN_FRONTEND' not in env: | ||
1287 | 92 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
1288 | 93 | |||
1289 | 94 | if fatal: | ||
1290 | 95 | subprocess.check_call(cmd, env=env) | ||
1291 | 96 | else: | ||
1292 | 97 | subprocess.call(cmd, env=env) | ||
1294 | 98 | 158 | ||
1295 | 99 | 159 | ||
1296 | 100 | def apt_upgrade(options=None, fatal=False, dist=False): | 160 | def apt_upgrade(options=None, fatal=False, dist=False): |
1297 | @@ -109,24 +169,13 @@ | |||
1298 | 109 | else: | 169 | else: |
1299 | 110 | cmd.append('upgrade') | 170 | cmd.append('upgrade') |
1300 | 111 | log("Upgrading with options: {}".format(options)) | 171 | log("Upgrading with options: {}".format(options)) |
1310 | 112 | 172 | _run_apt_command(cmd, fatal) | |
1302 | 113 | env = os.environ.copy() | ||
1303 | 114 | if 'DEBIAN_FRONTEND' not in env: | ||
1304 | 115 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
1305 | 116 | |||
1306 | 117 | if fatal: | ||
1307 | 118 | subprocess.check_call(cmd, env=env) | ||
1308 | 119 | else: | ||
1309 | 120 | subprocess.call(cmd, env=env) | ||
1311 | 121 | 173 | ||
1312 | 122 | 174 | ||
1313 | 123 | def apt_update(fatal=False): | 175 | def apt_update(fatal=False): |
1314 | 124 | """Update local apt cache""" | 176 | """Update local apt cache""" |
1315 | 125 | cmd = ['apt-get', 'update'] | 177 | cmd = ['apt-get', 'update'] |
1320 | 126 | if fatal: | 178 | _run_apt_command(cmd, fatal) |
1317 | 127 | subprocess.check_call(cmd) | ||
1318 | 128 | else: | ||
1319 | 129 | subprocess.call(cmd) | ||
1321 | 130 | 179 | ||
1322 | 131 | 180 | ||
1323 | 132 | def apt_purge(packages, fatal=False): | 181 | def apt_purge(packages, fatal=False): |
1324 | @@ -137,10 +186,7 @@ | |||
1325 | 137 | else: | 186 | else: |
1326 | 138 | cmd.extend(packages) | 187 | cmd.extend(packages) |
1327 | 139 | log("Purging {}".format(packages)) | 188 | log("Purging {}".format(packages)) |
1332 | 140 | if fatal: | 189 | _run_apt_command(cmd, fatal) |
1329 | 141 | subprocess.check_call(cmd) | ||
1330 | 142 | else: | ||
1331 | 143 | subprocess.call(cmd) | ||
1333 | 144 | 190 | ||
1334 | 145 | 191 | ||
1335 | 146 | def apt_hold(packages, fatal=False): | 192 | def apt_hold(packages, fatal=False): |
1336 | @@ -151,6 +197,7 @@ | |||
1337 | 151 | else: | 197 | else: |
1338 | 152 | cmd.extend(packages) | 198 | cmd.extend(packages) |
1339 | 153 | log("Holding {}".format(packages)) | 199 | log("Holding {}".format(packages)) |
1340 | 200 | |||
1341 | 154 | if fatal: | 201 | if fatal: |
1342 | 155 | subprocess.check_call(cmd) | 202 | subprocess.check_call(cmd) |
1343 | 156 | else: | 203 | else: |
1344 | @@ -158,6 +205,28 @@ | |||
1345 | 158 | 205 | ||
1346 | 159 | 206 | ||
1347 | 160 | def add_source(source, key=None): | 207 | def add_source(source, key=None): |
1348 | 208 | """Add a package source to this system. | ||
1349 | 209 | |||
1350 | 210 | @param source: a URL or sources.list entry, as supported by | ||
1351 | 211 | add-apt-repository(1). Examples:: | ||
1352 | 212 | |||
1353 | 213 | ppa:charmers/example | ||
1354 | 214 | deb https://stub:key@private.example.com/ubuntu trusty main | ||
1355 | 215 | |||
1356 | 216 | In addition: | ||
1357 | 217 | 'proposed:' may be used to enable the standard 'proposed' | ||
1358 | 218 | pocket for the release. | ||
1359 | 219 | 'cloud:' may be used to activate official cloud archive pockets, | ||
1360 | 220 | such as 'cloud:icehouse' | ||
1361 | 221 | |||
1362 | 222 | @param key: A key to be added to the system's APT keyring and used | ||
1363 | 223 | to verify the signatures on packages. Ideally, this should be an | ||
1364 | 224 | ASCII format GPG public key including the block headers. A GPG key | ||
1365 | 225 | id may also be used, but be aware that only insecure protocols are | ||
1366 | 226 | available to retrieve the actual public key from a public keyserver | ||
1367 | 227 | placing your Juju environment at risk. ppa and cloud archive keys | ||
1368 | 228 | are securely added automtically, so sould not be provided. | ||
1369 | 229 | """ | ||
1370 | 161 | if source is None: | 230 | if source is None: |
1371 | 162 | log('Source is not present. Skipping') | 231 | log('Source is not present. Skipping') |
1372 | 163 | return | 232 | return |
1373 | @@ -182,76 +251,96 @@ | |||
1374 | 182 | release = lsb_release()['DISTRIB_CODENAME'] | 251 | release = lsb_release()['DISTRIB_CODENAME'] |
1375 | 183 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: | 252 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: |
1376 | 184 | apt.write(PROPOSED_POCKET.format(release)) | 253 | apt.write(PROPOSED_POCKET.format(release)) |
1377 | 254 | else: | ||
1378 | 255 | raise SourceConfigError("Unknown source: {!r}".format(source)) | ||
1379 | 256 | |||
1380 | 185 | if key: | 257 | if key: |
1388 | 186 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | 258 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: |
1389 | 187 | 'hkp://keyserver.ubuntu.com:80', '--recv', | 259 | with NamedTemporaryFile() as key_file: |
1390 | 188 | key]) | 260 | key_file.write(key) |
1391 | 189 | 261 | key_file.flush() | |
1392 | 190 | 262 | key_file.seek(0) | |
1393 | 191 | class SourceConfigError(Exception): | 263 | subprocess.check_call(['apt-key', 'add', '-'], stdin=key_file) |
1394 | 192 | pass | 264 | else: |
1395 | 265 | # Note that hkp: is in no way a secure protocol. Using a | ||
1396 | 266 | # GPG key id is pointless from a security POV unless you | ||
1397 | 267 | # absolutely trust your network and DNS. | ||
1398 | 268 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | ||
1399 | 269 | 'hkp://keyserver.ubuntu.com:80', '--recv', | ||
1400 | 270 | key]) | ||
1401 | 193 | 271 | ||
1402 | 194 | 272 | ||
1403 | 195 | def configure_sources(update=False, | 273 | def configure_sources(update=False, |
1404 | 196 | sources_var='install_sources', | 274 | sources_var='install_sources', |
1405 | 197 | keys_var='install_keys'): | 275 | keys_var='install_keys'): |
1406 | 198 | """ | 276 | """ |
1408 | 199 | Configure multiple sources from charm configuration | 277 | Configure multiple sources from charm configuration. |
1409 | 278 | |||
1410 | 279 | The lists are encoded as yaml fragments in the configuration. | ||
1411 | 280 | The frament needs to be included as a string. Sources and their | ||
1412 | 281 | corresponding keys are of the types supported by add_source(). | ||
1413 | 200 | 282 | ||
1414 | 201 | Example config: | 283 | Example config: |
1416 | 202 | install_sources: | 284 | install_sources: | |
1417 | 203 | - "ppa:foo" | 285 | - "ppa:foo" |
1418 | 204 | - "http://example.com/repo precise main" | 286 | - "http://example.com/repo precise main" |
1420 | 205 | install_keys: | 287 | install_keys: | |
1421 | 206 | - null | 288 | - null |
1422 | 207 | - "a1b2c3d4" | 289 | - "a1b2c3d4" |
1423 | 208 | 290 | ||
1424 | 209 | Note that 'null' (a.k.a. None) should not be quoted. | 291 | Note that 'null' (a.k.a. None) should not be quoted. |
1425 | 210 | """ | 292 | """ |
1433 | 211 | sources = safe_load(config(sources_var)) | 293 | sources = safe_load((config(sources_var) or '').strip()) or [] |
1434 | 212 | keys = config(keys_var) | 294 | keys = safe_load((config(keys_var) or '').strip()) or None |
1435 | 213 | if keys is not None: | 295 | |
1436 | 214 | keys = safe_load(keys) | 296 | if isinstance(sources, basestring): |
1437 | 215 | if isinstance(sources, basestring) and ( | 297 | sources = [sources] |
1438 | 216 | keys is None or isinstance(keys, basestring)): | 298 | |
1439 | 217 | add_source(sources, keys) | 299 | if keys is None: |
1440 | 300 | for source in sources: | ||
1441 | 301 | add_source(source, None) | ||
1442 | 218 | else: | 302 | else: |
1448 | 219 | if not len(sources) == len(keys): | 303 | if isinstance(keys, basestring): |
1449 | 220 | msg = 'Install sources and keys lists are different lengths' | 304 | keys = [keys] |
1450 | 221 | raise SourceConfigError(msg) | 305 | |
1451 | 222 | for src_num in range(len(sources)): | 306 | if len(sources) != len(keys): |
1452 | 223 | add_source(sources[src_num], keys[src_num]) | 307 | raise SourceConfigError( |
1453 | 308 | 'Install sources and keys lists are different lengths') | ||
1454 | 309 | for source, key in zip(sources, keys): | ||
1455 | 310 | add_source(source, key) | ||
1456 | 224 | if update: | 311 | if update: |
1457 | 225 | apt_update(fatal=True) | 312 | apt_update(fatal=True) |
1458 | 226 | 313 | ||
1472 | 227 | # The order of this list is very important. Handlers should be listed in from | 314 | |
1473 | 228 | # least- to most-specific URL matching. | 315 | def install_remote(source, *args, **kwargs): |
1461 | 229 | FETCH_HANDLERS = ( | ||
1462 | 230 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
1463 | 231 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
1464 | 232 | ) | ||
1465 | 233 | |||
1466 | 234 | |||
1467 | 235 | class UnhandledSource(Exception): | ||
1468 | 236 | pass | ||
1469 | 237 | |||
1470 | 238 | |||
1471 | 239 | def install_remote(source): | ||
1474 | 240 | """ | 316 | """ |
1475 | 241 | Install a file tree from a remote source | 317 | Install a file tree from a remote source |
1476 | 242 | 318 | ||
1477 | 243 | The specified source should be a url of the form: | 319 | The specified source should be a url of the form: |
1478 | 244 | scheme://[host]/path[#[option=value][&...]] | 320 | scheme://[host]/path[#[option=value][&...]] |
1479 | 245 | 321 | ||
1482 | 246 | Schemes supported are based on this modules submodules | 322 | Schemes supported are based on this modules submodules. |
1483 | 247 | Options supported are submodule-specific""" | 323 | Options supported are submodule-specific. |
1484 | 324 | Additional arguments are passed through to the submodule. | ||
1485 | 325 | |||
1486 | 326 | For example:: | ||
1487 | 327 | |||
1488 | 328 | dest = install_remote('http://example.com/archive.tgz', | ||
1489 | 329 | checksum='deadbeef', | ||
1490 | 330 | hash_type='sha1') | ||
1491 | 331 | |||
1492 | 332 | This will download `archive.tgz`, validate it using SHA1 and, if | ||
1493 | 333 | the file is ok, extract it and return the directory in which it | ||
1494 | 334 | was extracted. If the checksum fails, it will raise | ||
1495 | 335 | :class:`charmhelpers.core.host.ChecksumError`. | ||
1496 | 336 | """ | ||
1497 | 248 | # We ONLY check for True here because can_handle may return a string | 337 | # We ONLY check for True here because can_handle may return a string |
1498 | 249 | # explaining why it can't handle a given source. | 338 | # explaining why it can't handle a given source. |
1499 | 250 | handlers = [h for h in plugins() if h.can_handle(source) is True] | 339 | handlers = [h for h in plugins() if h.can_handle(source) is True] |
1500 | 251 | installed_to = None | 340 | installed_to = None |
1501 | 252 | for handler in handlers: | 341 | for handler in handlers: |
1502 | 253 | try: | 342 | try: |
1504 | 254 | installed_to = handler.install(source) | 343 | installed_to = handler.install(source, *args, **kwargs) |
1505 | 255 | except UnhandledSource: | 344 | except UnhandledSource: |
1506 | 256 | pass | 345 | pass |
1507 | 257 | if not installed_to: | 346 | if not installed_to: |
1508 | @@ -265,30 +354,6 @@ | |||
1509 | 265 | return install_remote(source) | 354 | return install_remote(source) |
1510 | 266 | 355 | ||
1511 | 267 | 356 | ||
1512 | 268 | class BaseFetchHandler(object): | ||
1513 | 269 | |||
1514 | 270 | """Base class for FetchHandler implementations in fetch plugins""" | ||
1515 | 271 | |||
1516 | 272 | def can_handle(self, source): | ||
1517 | 273 | """Returns True if the source can be handled. Otherwise returns | ||
1518 | 274 | a string explaining why it cannot""" | ||
1519 | 275 | return "Wrong source type" | ||
1520 | 276 | |||
1521 | 277 | def install(self, source): | ||
1522 | 278 | """Try to download and unpack the source. Return the path to the | ||
1523 | 279 | unpacked files or raise UnhandledSource.""" | ||
1524 | 280 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
1525 | 281 | |||
1526 | 282 | def parse_url(self, url): | ||
1527 | 283 | return urlparse(url) | ||
1528 | 284 | |||
1529 | 285 | def base_url(self, url): | ||
1530 | 286 | """Return url without querystring or fragment""" | ||
1531 | 287 | parts = list(self.parse_url(url)) | ||
1532 | 288 | parts[4:] = ['' for i in parts[4:]] | ||
1533 | 289 | return urlunparse(parts) | ||
1534 | 290 | |||
1535 | 291 | |||
1536 | 292 | def plugins(fetch_handlers=None): | 357 | def plugins(fetch_handlers=None): |
1537 | 293 | if not fetch_handlers: | 358 | if not fetch_handlers: |
1538 | 294 | fetch_handlers = FETCH_HANDLERS | 359 | fetch_handlers = FETCH_HANDLERS |
1539 | @@ -306,3 +371,40 @@ | |||
1540 | 306 | log("FetchHandler {} not found, skipping plugin".format( | 371 | log("FetchHandler {} not found, skipping plugin".format( |
1541 | 307 | handler_name)) | 372 | handler_name)) |
1542 | 308 | return plugin_list | 373 | return plugin_list |
1543 | 374 | |||
1544 | 375 | |||
1545 | 376 | def _run_apt_command(cmd, fatal=False): | ||
1546 | 377 | """ | ||
1547 | 378 | Run an APT command, checking output and retrying if the fatal flag is set | ||
1548 | 379 | to True. | ||
1549 | 380 | |||
1550 | 381 | :param: cmd: str: The apt command to run. | ||
1551 | 382 | :param: fatal: bool: Whether the command's output should be checked and | ||
1552 | 383 | retried. | ||
1553 | 384 | """ | ||
1554 | 385 | env = os.environ.copy() | ||
1555 | 386 | |||
1556 | 387 | if 'DEBIAN_FRONTEND' not in env: | ||
1557 | 388 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
1558 | 389 | |||
1559 | 390 | if fatal: | ||
1560 | 391 | retry_count = 0 | ||
1561 | 392 | result = None | ||
1562 | 393 | |||
1563 | 394 | # If the command is considered "fatal", we need to retry if the apt | ||
1564 | 395 | # lock was not acquired. | ||
1565 | 396 | |||
1566 | 397 | while result is None or result == APT_NO_LOCK: | ||
1567 | 398 | try: | ||
1568 | 399 | result = subprocess.check_call(cmd, env=env) | ||
1569 | 400 | except subprocess.CalledProcessError, e: | ||
1570 | 401 | retry_count = retry_count + 1 | ||
1571 | 402 | if retry_count > APT_NO_LOCK_RETRY_COUNT: | ||
1572 | 403 | raise | ||
1573 | 404 | result = e.returncode | ||
1574 | 405 | log("Couldn't acquire DPKG lock. Will retry in {} seconds." | ||
1575 | 406 | "".format(APT_NO_LOCK_RETRY_DELAY)) | ||
1576 | 407 | time.sleep(APT_NO_LOCK_RETRY_DELAY) | ||
1577 | 408 | |||
1578 | 409 | else: | ||
1579 | 410 | subprocess.call(cmd, env=env) | ||
1580 | 309 | 411 | ||
1581 | === modified file 'hooks/charmhelpers/fetch/archiveurl.py' | |||
1582 | --- hooks/charmhelpers/fetch/archiveurl.py 2014-04-17 10:53:00 +0000 | |||
1583 | +++ hooks/charmhelpers/fetch/archiveurl.py 2014-09-26 07:21:45 +0000 | |||
1584 | @@ -1,6 +1,8 @@ | |||
1585 | 1 | import os | 1 | import os |
1586 | 2 | import urllib2 | 2 | import urllib2 |
1587 | 3 | from urllib import urlretrieve | ||
1588 | 3 | import urlparse | 4 | import urlparse |
1589 | 5 | import hashlib | ||
1590 | 4 | 6 | ||
1591 | 5 | from charmhelpers.fetch import ( | 7 | from charmhelpers.fetch import ( |
1592 | 6 | BaseFetchHandler, | 8 | BaseFetchHandler, |
1593 | @@ -10,11 +12,19 @@ | |||
1594 | 10 | get_archive_handler, | 12 | get_archive_handler, |
1595 | 11 | extract, | 13 | extract, |
1596 | 12 | ) | 14 | ) |
1598 | 13 | from charmhelpers.core.host import mkdir | 15 | from charmhelpers.core.host import mkdir, check_hash |
1599 | 14 | 16 | ||
1600 | 15 | 17 | ||
1601 | 16 | class ArchiveUrlFetchHandler(BaseFetchHandler): | 18 | class ArchiveUrlFetchHandler(BaseFetchHandler): |
1603 | 17 | """Handler for archives via generic URLs""" | 19 | """ |
1604 | 20 | Handler to download archive files from arbitrary URLs. | ||
1605 | 21 | |||
1606 | 22 | Can fetch from http, https, ftp, and file URLs. | ||
1607 | 23 | |||
1608 | 24 | Can install either tarballs (.tar, .tgz, .tbz2, etc) or zip files. | ||
1609 | 25 | |||
1610 | 26 | Installs the contents of the archive in $CHARM_DIR/fetched/. | ||
1611 | 27 | """ | ||
1612 | 18 | def can_handle(self, source): | 28 | def can_handle(self, source): |
1613 | 19 | url_parts = self.parse_url(source) | 29 | url_parts = self.parse_url(source) |
1614 | 20 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): | 30 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): |
1615 | @@ -24,6 +34,12 @@ | |||
1616 | 24 | return False | 34 | return False |
1617 | 25 | 35 | ||
1618 | 26 | def download(self, source, dest): | 36 | def download(self, source, dest): |
1619 | 37 | """ | ||
1620 | 38 | Download an archive file. | ||
1621 | 39 | |||
1622 | 40 | :param str source: URL pointing to an archive file. | ||
1623 | 41 | :param str dest: Local path location to download archive file to. | ||
1624 | 42 | """ | ||
1625 | 27 | # propogate all exceptions | 43 | # propogate all exceptions |
1626 | 28 | # URLError, OSError, etc | 44 | # URLError, OSError, etc |
1627 | 29 | proto, netloc, path, params, query, fragment = urlparse.urlparse(source) | 45 | proto, netloc, path, params, query, fragment = urlparse.urlparse(source) |
1628 | @@ -48,7 +64,30 @@ | |||
1629 | 48 | os.unlink(dest) | 64 | os.unlink(dest) |
1630 | 49 | raise e | 65 | raise e |
1631 | 50 | 66 | ||
1633 | 51 | def install(self, source): | 67 | # Mandatory file validation via Sha1 or MD5 hashing. |
1634 | 68 | def download_and_validate(self, url, hashsum, validate="sha1"): | ||
1635 | 69 | tempfile, headers = urlretrieve(url) | ||
1636 | 70 | check_hash(tempfile, hashsum, validate) | ||
1637 | 71 | return tempfile | ||
1638 | 72 | |||
1639 | 73 | def install(self, source, dest=None, checksum=None, hash_type='sha1'): | ||
1640 | 74 | """ | ||
1641 | 75 | Download and install an archive file, with optional checksum validation. | ||
1642 | 76 | |||
1643 | 77 | The checksum can also be given on the `source` URL's fragment. | ||
1644 | 78 | For example:: | ||
1645 | 79 | |||
1646 | 80 | handler.install('http://example.com/file.tgz#sha1=deadbeef') | ||
1647 | 81 | |||
1648 | 82 | :param str source: URL pointing to an archive file. | ||
1649 | 83 | :param str dest: Local destination path to install to. If not given, | ||
1650 | 84 | installs to `$CHARM_DIR/archives/archive_file_name`. | ||
1651 | 85 | :param str checksum: If given, validate the archive file after download. | ||
1652 | 86 | :param str hash_type: Algorithm used to generate `checksum`. | ||
1653 | 87 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
1654 | 88 | such as md5, sha1, sha256, sha512, etc. | ||
1655 | 89 | |||
1656 | 90 | """ | ||
1657 | 52 | url_parts = self.parse_url(source) | 91 | url_parts = self.parse_url(source) |
1658 | 53 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') | 92 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') |
1659 | 54 | if not os.path.exists(dest_dir): | 93 | if not os.path.exists(dest_dir): |
1660 | @@ -60,4 +99,10 @@ | |||
1661 | 60 | raise UnhandledSource(e.reason) | 99 | raise UnhandledSource(e.reason) |
1662 | 61 | except OSError as e: | 100 | except OSError as e: |
1663 | 62 | raise UnhandledSource(e.strerror) | 101 | raise UnhandledSource(e.strerror) |
1665 | 63 | return extract(dld_file) | 102 | options = urlparse.parse_qs(url_parts.fragment) |
1666 | 103 | for key, value in options.items(): | ||
1667 | 104 | if key in hashlib.algorithms: | ||
1668 | 105 | check_hash(dld_file, value, key) | ||
1669 | 106 | if checksum: | ||
1670 | 107 | check_hash(dld_file, checksum, hash_type) | ||
1671 | 108 | return extract(dld_file, dest) | ||
1672 | 64 | 109 | ||
1673 | === modified file 'hooks/charmhelpers/fetch/bzrurl.py' | |||
1674 | --- hooks/charmhelpers/fetch/bzrurl.py 2014-02-19 14:49:31 +0000 | |||
1675 | +++ hooks/charmhelpers/fetch/bzrurl.py 2014-09-26 07:21:45 +0000 | |||
1676 | @@ -39,7 +39,8 @@ | |||
1677 | 39 | def install(self, source): | 39 | def install(self, source): |
1678 | 40 | url_parts = self.parse_url(source) | 40 | url_parts = self.parse_url(source) |
1679 | 41 | branch_name = url_parts.path.strip("/").split("/")[-1] | 41 | branch_name = url_parts.path.strip("/").split("/")[-1] |
1681 | 42 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", branch_name) | 42 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", |
1682 | 43 | branch_name) | ||
1683 | 43 | if not os.path.exists(dest_dir): | 44 | if not os.path.exists(dest_dir): |
1684 | 44 | mkdir(dest_dir, perms=0755) | 45 | mkdir(dest_dir, perms=0755) |
1685 | 45 | try: | 46 | try: |
This items has failed automated testing! Results available here http:// reports. vapour. ws/charm- tests/charm- bundle- test-1109- results