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