Merge lp:~michael.nelson/charms/trusty/elasticsearch/upgrade-charm-helpers into lp:charms/trusty/elasticsearch
- Trusty Tahr (14.04)
- upgrade-charm-helpers
- Merge into trunk
Proposed by
Michael Nelson
Status: | Merged |
---|---|
Merged at revision: | 36 |
Proposed branch: | lp:~michael.nelson/charms/trusty/elasticsearch/upgrade-charm-helpers |
Merge into: | lp:charms/trusty/elasticsearch |
Diff against target: |
2083 lines (+1393/-181) 19 files modified
README.md (+4/-0) hooks/charmhelpers/contrib/ansible/__init__.py (+63/-57) hooks/charmhelpers/contrib/templating/contexts.py (+19/-7) hooks/charmhelpers/core/fstab.py (+116/-0) hooks/charmhelpers/core/hookenv.py (+138/-7) hooks/charmhelpers/core/host.py (+107/-13) 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/sysctl.py (+34/-0) hooks/charmhelpers/core/templating.py (+51/-0) hooks/charmhelpers/fetch/__init__.py (+196/-90) hooks/charmhelpers/fetch/archiveurl.py (+49/-4) hooks/charmhelpers/fetch/bzrurl.py (+2/-1) hooks/charmhelpers/fetch/giturl.py (+44/-0) hooks/hooks.py (+1/-0) playbook.yaml (+4/-1) tasks/peer-relations.yml (+0/-1) tasks/setup-ufw.yml (+11/-0) |
To merge this branch: | bzr merge lp:~michael.nelson/charms/trusty/elasticsearch/upgrade-charm-helpers |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
charmers | Pending | ||
Review via email: mp+239933@code.launchpad.net |
Commit message
Description of the change
This branch is mechanical work that:
1) Resyncs the charmhelpers library to use the latest crack
2) Re-merges a branch which ensures uncomplicated firewall is used for the peer 9300 port also.
This branch doesn't work - the follow-on branch does the actual updates to the charm to ensure that it's working with the new charmhelpers:
To post a comment you must log in.
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === modified file 'README.md' | |||
2 | --- README.md 2014-08-19 16:47:21 +0000 | |||
3 | +++ README.md 2014-10-29 02:58:49 +0000 | |||
4 | @@ -37,6 +37,10 @@ | |||
5 | 37 | epoch timestamp cluster status node.total node.data shards ... | 37 | epoch timestamp cluster status node.total node.data shards ... |
6 | 38 | 1404728290 10:18:10 elasticsearch green 2 2 0 | 38 | 1404728290 10:18:10 elasticsearch green 2 2 0 |
7 | 39 | 39 | ||
8 | 40 | Note that the admin port (9200) is only accessible from the instance itself | ||
9 | 41 | and any clients that join. Similarly the node-to-node communication | ||
10 | 42 | port (9300) is only available to other units in the elasticsearch service. | ||
11 | 43 | |||
12 | 40 | See the separate HACKING.md for information about deploying this charm | 44 | See the separate HACKING.md for information about deploying this charm |
13 | 41 | from a local repository. | 45 | from a local repository. |
14 | 42 | 46 | ||
15 | 43 | 47 | ||
16 | === modified file 'hooks/charmhelpers/contrib/ansible/__init__.py' | |||
17 | --- hooks/charmhelpers/contrib/ansible/__init__.py 2014-02-06 12:54:59 +0000 | |||
18 | +++ hooks/charmhelpers/contrib/ansible/__init__.py 2014-10-29 02:58:49 +0000 | |||
19 | @@ -6,58 +6,59 @@ | |||
20 | 6 | 6 | ||
21 | 7 | This helper enables you to declare your machine state, rather than | 7 | This helper enables you to declare your machine state, rather than |
22 | 8 | program it procedurally (and have to test each change to your procedures). | 8 | program it procedurally (and have to test each change to your procedures). |
33 | 9 | Your install hook can be as simple as: | 9 | Your install hook can be as simple as:: |
34 | 10 | 10 | ||
35 | 11 | {{{ | 11 | {{{ |
36 | 12 | import charmhelpers.contrib.ansible | 12 | import charmhelpers.contrib.ansible |
37 | 13 | 13 | ||
38 | 14 | 14 | ||
39 | 15 | def install(): | 15 | def install(): |
40 | 16 | charmhelpers.contrib.ansible.install_ansible_support() | 16 | charmhelpers.contrib.ansible.install_ansible_support() |
41 | 17 | charmhelpers.contrib.ansible.apply_playbook('playbooks/install.yaml') | 17 | charmhelpers.contrib.ansible.apply_playbook('playbooks/install.yaml') |
42 | 18 | }}} | 18 | }}} |
43 | 19 | 19 | ||
44 | 20 | and won't need to change (nor will its tests) when you change the machine | 20 | and won't need to change (nor will its tests) when you change the machine |
45 | 21 | state. | 21 | state. |
46 | 22 | 22 | ||
47 | 23 | All of your juju config and relation-data are available as template | 23 | All of your juju config and relation-data are available as template |
48 | 24 | variables within your playbooks and templates. An install playbook looks | 24 | variables within your playbooks and templates. An install playbook looks |
85 | 25 | something like: | 25 | something like:: |
86 | 26 | 26 | ||
87 | 27 | {{{ | 27 | {{{ |
88 | 28 | --- | 28 | --- |
89 | 29 | - hosts: localhost | 29 | - hosts: localhost |
90 | 30 | user: root | 30 | user: root |
91 | 31 | 31 | ||
92 | 32 | tasks: | 32 | tasks: |
93 | 33 | - name: Add private repositories. | 33 | - name: Add private repositories. |
94 | 34 | template: | 34 | template: |
95 | 35 | src: ../templates/private-repositories.list.jinja2 | 35 | src: ../templates/private-repositories.list.jinja2 |
96 | 36 | dest: /etc/apt/sources.list.d/private.list | 36 | dest: /etc/apt/sources.list.d/private.list |
97 | 37 | 37 | ||
98 | 38 | - name: Update the cache. | 38 | - name: Update the cache. |
99 | 39 | apt: update_cache=yes | 39 | apt: update_cache=yes |
100 | 40 | 40 | ||
101 | 41 | - name: Install dependencies. | 41 | - name: Install dependencies. |
102 | 42 | apt: pkg={{ item }} | 42 | apt: pkg={{ item }} |
103 | 43 | with_items: | 43 | with_items: |
104 | 44 | - python-mimeparse | 44 | - python-mimeparse |
105 | 45 | - python-webob | 45 | - python-webob |
106 | 46 | - sunburnt | 46 | - sunburnt |
107 | 47 | 47 | ||
108 | 48 | - name: Setup groups. | 48 | - name: Setup groups. |
109 | 49 | group: name={{ item.name }} gid={{ item.gid }} | 49 | group: name={{ item.name }} gid={{ item.gid }} |
110 | 50 | with_items: | 50 | with_items: |
111 | 51 | - { name: 'deploy_user', gid: 1800 } | 51 | - { name: 'deploy_user', gid: 1800 } |
112 | 52 | - { name: 'service_user', gid: 1500 } | 52 | - { name: 'service_user', gid: 1500 } |
113 | 53 | 53 | ||
114 | 54 | ... | 54 | ... |
115 | 55 | }}} | 55 | }}} |
116 | 56 | 56 | ||
117 | 57 | Read more online about playbooks[1] and standard ansible modules[2]. | 57 | Read more online about `playbooks`_ and standard ansible `modules`_. |
118 | 58 | 58 | ||
119 | 59 | [1] http://www.ansibleworks.com/docs/playbooks.html | 59 | .. _playbooks: http://www.ansibleworks.com/docs/playbooks.html |
120 | 60 | [2] http://www.ansibleworks.com/docs/modules.html | 60 | .. _modules: http://www.ansibleworks.com/docs/modules.html |
121 | 61 | |||
122 | 61 | """ | 62 | """ |
123 | 62 | import os | 63 | import os |
124 | 63 | import subprocess | 64 | import subprocess |
125 | @@ -75,20 +76,20 @@ | |||
126 | 75 | ansible_vars_path = '/etc/ansible/host_vars/localhost' | 76 | ansible_vars_path = '/etc/ansible/host_vars/localhost' |
127 | 76 | 77 | ||
128 | 77 | 78 | ||
130 | 78 | def install_ansible_support(from_ppa=True): | 79 | def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'): |
131 | 79 | """Installs the ansible package. | 80 | """Installs the ansible package. |
132 | 80 | 81 | ||
140 | 81 | By default it is installed from the PPA [1] linked from | 82 | By default it is installed from the `PPA`_ linked from |
141 | 82 | the ansible website [2]. | 83 | the ansible `website`_ or from a ppa specified by a charm config.. |
142 | 83 | 84 | ||
143 | 84 | [1] https://launchpad.net/~rquillo/+archive/ansible | 85 | .. _PPA: https://launchpad.net/~rquillo/+archive/ansible |
144 | 85 | [2] http://www.ansibleworks.com/docs/gettingstarted.html#ubuntu-and-debian | 86 | .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu |
145 | 86 | 87 | ||
146 | 87 | If from_ppa is false, you must ensure that the package is available | 88 | If from_ppa is empty, you must ensure that the package is available |
147 | 88 | from a configured repository. | 89 | from a configured repository. |
148 | 89 | """ | 90 | """ |
149 | 90 | if from_ppa: | 91 | if from_ppa: |
151 | 91 | charmhelpers.fetch.add_source('ppa:rquillo/ansible') | 92 | charmhelpers.fetch.add_source(ppa_location) |
152 | 92 | charmhelpers.fetch.apt_update(fatal=True) | 93 | charmhelpers.fetch.apt_update(fatal=True) |
153 | 93 | charmhelpers.fetch.apt_install('ansible') | 94 | charmhelpers.fetch.apt_install('ansible') |
154 | 94 | with open(ansible_hosts_path, 'w+') as hosts_file: | 95 | with open(ansible_hosts_path, 'w+') as hosts_file: |
155 | @@ -101,6 +102,9 @@ | |||
156 | 101 | charmhelpers.contrib.templating.contexts.juju_state_to_yaml( | 102 | charmhelpers.contrib.templating.contexts.juju_state_to_yaml( |
157 | 102 | ansible_vars_path, namespace_separator='__', | 103 | ansible_vars_path, namespace_separator='__', |
158 | 103 | allow_hyphens_in_keys=False) | 104 | allow_hyphens_in_keys=False) |
159 | 105 | # we want ansible's log output to be unbuffered | ||
160 | 106 | env = os.environ.copy() | ||
161 | 107 | env['PYTHONUNBUFFERED'] = "1" | ||
162 | 104 | call = [ | 108 | call = [ |
163 | 105 | 'ansible-playbook', | 109 | 'ansible-playbook', |
164 | 106 | '-c', | 110 | '-c', |
165 | @@ -109,7 +113,7 @@ | |||
166 | 109 | ] | 113 | ] |
167 | 110 | if tags: | 114 | if tags: |
168 | 111 | call.extend(['--tags', '{}'.format(tags)]) | 115 | call.extend(['--tags', '{}'.format(tags)]) |
170 | 112 | subprocess.check_call(call) | 116 | subprocess.check_call(call, env=env) |
171 | 113 | 117 | ||
172 | 114 | 118 | ||
173 | 115 | class AnsibleHooks(charmhelpers.core.hookenv.Hooks): | 119 | class AnsibleHooks(charmhelpers.core.hookenv.Hooks): |
174 | @@ -119,7 +123,8 @@ | |||
175 | 119 | but additionally runs the playbook with the hook-name specified | 123 | but additionally runs the playbook with the hook-name specified |
176 | 120 | using --tags (ie. running all the tasks tagged with the hook-name). | 124 | using --tags (ie. running all the tasks tagged with the hook-name). |
177 | 121 | 125 | ||
179 | 122 | Example: | 126 | Example:: |
180 | 127 | |||
181 | 123 | hooks = AnsibleHooks(playbook_path='playbooks/my_machine_state.yaml') | 128 | hooks = AnsibleHooks(playbook_path='playbooks/my_machine_state.yaml') |
182 | 124 | 129 | ||
183 | 125 | # All the tasks within my_machine_state.yaml tagged with 'install' | 130 | # All the tasks within my_machine_state.yaml tagged with 'install' |
184 | @@ -144,6 +149,7 @@ | |||
185 | 144 | if __name__ == "__main__": | 149 | if __name__ == "__main__": |
186 | 145 | # execute a hook based on the name the program is called by | 150 | # execute a hook based on the name the program is called by |
187 | 146 | hooks.execute(sys.argv) | 151 | hooks.execute(sys.argv) |
188 | 152 | |||
189 | 147 | """ | 153 | """ |
190 | 148 | 154 | ||
191 | 149 | def __init__(self, playbook_path, default_hooks=None): | 155 | def __init__(self, playbook_path, default_hooks=None): |
192 | 150 | 156 | ||
193 | === modified file 'hooks/charmhelpers/contrib/templating/contexts.py' | |||
194 | --- hooks/charmhelpers/contrib/templating/contexts.py 2014-04-08 14:58:22 +0000 | |||
195 | +++ hooks/charmhelpers/contrib/templating/contexts.py 2014-10-29 02:58:49 +0000 | |||
196 | @@ -40,13 +40,25 @@ | |||
197 | 40 | relations = charmhelpers.core.hookenv.relations_of_type(relation_type) | 40 | relations = charmhelpers.core.hookenv.relations_of_type(relation_type) |
198 | 41 | relations = [dict_keys_without_hyphens(rel) for rel in relations] | 41 | relations = [dict_keys_without_hyphens(rel) for rel in relations] |
199 | 42 | 42 | ||
205 | 43 | if 'relations_deprecated' not in context: | 43 | context['relations_full'] = charmhelpers.core.hookenv.relations() |
201 | 44 | context['relations_deprecated'] = {} | ||
202 | 45 | if relation_type is not None: | ||
203 | 46 | relation_type = relation_type.replace('-', '_') | ||
204 | 47 | context['relations_deprecated'][relation_type] = relations | ||
206 | 48 | 44 | ||
208 | 49 | context['relations'] = charmhelpers.core.hookenv.relations() | 45 | # the hookenv.relations() data structure is effectively unusable in |
209 | 46 | # templates and other contexts when trying to access relation data other | ||
210 | 47 | # than the current relation. So provide a more useful structure that works | ||
211 | 48 | # with any hook. | ||
212 | 49 | local_unit = charmhelpers.core.hookenv.local_unit() | ||
213 | 50 | relations = {} | ||
214 | 51 | for rname, rids in context['relations_full'].items(): | ||
215 | 52 | relations[rname] = [] | ||
216 | 53 | for rid, rdata in rids.items(): | ||
217 | 54 | data = rdata.copy() | ||
218 | 55 | if local_unit in rdata: | ||
219 | 56 | data.pop(local_unit) | ||
220 | 57 | for unit_name, rel_data in data.items(): | ||
221 | 58 | new_data = {'__relid__': rid, '__unit__': unit_name} | ||
222 | 59 | new_data.update(rel_data) | ||
223 | 60 | relations[rname].append(new_data) | ||
224 | 61 | context['relations'] = relations | ||
225 | 50 | 62 | ||
226 | 51 | 63 | ||
227 | 52 | def juju_state_to_yaml(yaml_path, namespace_separator=':', | 64 | def juju_state_to_yaml(yaml_path, namespace_separator=':', |
228 | @@ -101,4 +113,4 @@ | |||
229 | 101 | update_relations(existing_vars, namespace_separator) | 113 | update_relations(existing_vars, namespace_separator) |
230 | 102 | 114 | ||
231 | 103 | with open(yaml_path, "w+") as fp: | 115 | with open(yaml_path, "w+") as fp: |
233 | 104 | fp.write(yaml.dump(existing_vars)) | 116 | fp.write(yaml.dump(existing_vars, default_flow_style=False)) |
234 | 105 | 117 | ||
235 | === added file 'hooks/charmhelpers/core/fstab.py' | |||
236 | --- hooks/charmhelpers/core/fstab.py 1970-01-01 00:00:00 +0000 | |||
237 | +++ hooks/charmhelpers/core/fstab.py 2014-10-29 02:58:49 +0000 | |||
238 | @@ -0,0 +1,116 @@ | |||
239 | 1 | #!/usr/bin/env python | ||
240 | 2 | # -*- coding: utf-8 -*- | ||
241 | 3 | |||
242 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
243 | 5 | |||
244 | 6 | import os | ||
245 | 7 | |||
246 | 8 | |||
247 | 9 | class Fstab(file): | ||
248 | 10 | """This class extends file in order to implement a file reader/writer | ||
249 | 11 | for file `/etc/fstab` | ||
250 | 12 | """ | ||
251 | 13 | |||
252 | 14 | class Entry(object): | ||
253 | 15 | """Entry class represents a non-comment line on the `/etc/fstab` file | ||
254 | 16 | """ | ||
255 | 17 | def __init__(self, device, mountpoint, filesystem, | ||
256 | 18 | options, d=0, p=0): | ||
257 | 19 | self.device = device | ||
258 | 20 | self.mountpoint = mountpoint | ||
259 | 21 | self.filesystem = filesystem | ||
260 | 22 | |||
261 | 23 | if not options: | ||
262 | 24 | options = "defaults" | ||
263 | 25 | |||
264 | 26 | self.options = options | ||
265 | 27 | self.d = d | ||
266 | 28 | self.p = p | ||
267 | 29 | |||
268 | 30 | def __eq__(self, o): | ||
269 | 31 | return str(self) == str(o) | ||
270 | 32 | |||
271 | 33 | def __str__(self): | ||
272 | 34 | return "{} {} {} {} {} {}".format(self.device, | ||
273 | 35 | self.mountpoint, | ||
274 | 36 | self.filesystem, | ||
275 | 37 | self.options, | ||
276 | 38 | self.d, | ||
277 | 39 | self.p) | ||
278 | 40 | |||
279 | 41 | DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab') | ||
280 | 42 | |||
281 | 43 | def __init__(self, path=None): | ||
282 | 44 | if path: | ||
283 | 45 | self._path = path | ||
284 | 46 | else: | ||
285 | 47 | self._path = self.DEFAULT_PATH | ||
286 | 48 | file.__init__(self, self._path, 'r+') | ||
287 | 49 | |||
288 | 50 | def _hydrate_entry(self, line): | ||
289 | 51 | # NOTE: use split with no arguments to split on any | ||
290 | 52 | # whitespace including tabs | ||
291 | 53 | return Fstab.Entry(*filter( | ||
292 | 54 | lambda x: x not in ('', None), | ||
293 | 55 | line.strip("\n").split())) | ||
294 | 56 | |||
295 | 57 | @property | ||
296 | 58 | def entries(self): | ||
297 | 59 | self.seek(0) | ||
298 | 60 | for line in self.readlines(): | ||
299 | 61 | try: | ||
300 | 62 | if not line.startswith("#"): | ||
301 | 63 | yield self._hydrate_entry(line) | ||
302 | 64 | except ValueError: | ||
303 | 65 | pass | ||
304 | 66 | |||
305 | 67 | def get_entry_by_attr(self, attr, value): | ||
306 | 68 | for entry in self.entries: | ||
307 | 69 | e_attr = getattr(entry, attr) | ||
308 | 70 | if e_attr == value: | ||
309 | 71 | return entry | ||
310 | 72 | return None | ||
311 | 73 | |||
312 | 74 | def add_entry(self, entry): | ||
313 | 75 | if self.get_entry_by_attr('device', entry.device): | ||
314 | 76 | return False | ||
315 | 77 | |||
316 | 78 | self.write(str(entry) + '\n') | ||
317 | 79 | self.truncate() | ||
318 | 80 | return entry | ||
319 | 81 | |||
320 | 82 | def remove_entry(self, entry): | ||
321 | 83 | self.seek(0) | ||
322 | 84 | |||
323 | 85 | lines = self.readlines() | ||
324 | 86 | |||
325 | 87 | found = False | ||
326 | 88 | for index, line in enumerate(lines): | ||
327 | 89 | if not line.startswith("#"): | ||
328 | 90 | if self._hydrate_entry(line) == entry: | ||
329 | 91 | found = True | ||
330 | 92 | break | ||
331 | 93 | |||
332 | 94 | if not found: | ||
333 | 95 | return False | ||
334 | 96 | |||
335 | 97 | lines.remove(line) | ||
336 | 98 | |||
337 | 99 | self.seek(0) | ||
338 | 100 | self.write(''.join(lines)) | ||
339 | 101 | self.truncate() | ||
340 | 102 | return True | ||
341 | 103 | |||
342 | 104 | @classmethod | ||
343 | 105 | def remove_by_mountpoint(cls, mountpoint, path=None): | ||
344 | 106 | fstab = cls(path=path) | ||
345 | 107 | entry = fstab.get_entry_by_attr('mountpoint', mountpoint) | ||
346 | 108 | if entry: | ||
347 | 109 | return fstab.remove_entry(entry) | ||
348 | 110 | return False | ||
349 | 111 | |||
350 | 112 | @classmethod | ||
351 | 113 | def add(cls, device, mountpoint, filesystem, options=None, path=None): | ||
352 | 114 | return cls(path=path).add_entry(Fstab.Entry(device, | ||
353 | 115 | mountpoint, filesystem, | ||
354 | 116 | options=options)) | ||
355 | 0 | 117 | ||
356 | === modified file 'hooks/charmhelpers/core/hookenv.py' | |||
357 | --- hooks/charmhelpers/core/hookenv.py 2014-02-06 12:54:59 +0000 | |||
358 | +++ hooks/charmhelpers/core/hookenv.py 2014-10-29 02:58:49 +0000 | |||
359 | @@ -25,7 +25,7 @@ | |||
360 | 25 | def cached(func): | 25 | def cached(func): |
361 | 26 | """Cache return values for multiple executions of func + args | 26 | """Cache return values for multiple executions of func + args |
362 | 27 | 27 | ||
364 | 28 | For example: | 28 | For example:: |
365 | 29 | 29 | ||
366 | 30 | @cached | 30 | @cached |
367 | 31 | def unit_get(attribute): | 31 | def unit_get(attribute): |
368 | @@ -155,6 +155,127 @@ | |||
369 | 155 | return os.path.basename(sys.argv[0]) | 155 | return os.path.basename(sys.argv[0]) |
370 | 156 | 156 | ||
371 | 157 | 157 | ||
372 | 158 | class Config(dict): | ||
373 | 159 | """A dictionary representation of the charm's config.yaml, with some | ||
374 | 160 | extra features: | ||
375 | 161 | |||
376 | 162 | - See which values in the dictionary have changed since the previous hook. | ||
377 | 163 | - For values that have changed, see what the previous value was. | ||
378 | 164 | - Store arbitrary data for use in a later hook. | ||
379 | 165 | |||
380 | 166 | NOTE: Do not instantiate this object directly - instead call | ||
381 | 167 | ``hookenv.config()``, which will return an instance of :class:`Config`. | ||
382 | 168 | |||
383 | 169 | Example usage:: | ||
384 | 170 | |||
385 | 171 | >>> # inside a hook | ||
386 | 172 | >>> from charmhelpers.core import hookenv | ||
387 | 173 | >>> config = hookenv.config() | ||
388 | 174 | >>> config['foo'] | ||
389 | 175 | 'bar' | ||
390 | 176 | >>> # store a new key/value for later use | ||
391 | 177 | >>> config['mykey'] = 'myval' | ||
392 | 178 | |||
393 | 179 | |||
394 | 180 | >>> # user runs `juju set mycharm foo=baz` | ||
395 | 181 | >>> # now we're inside subsequent config-changed hook | ||
396 | 182 | >>> config = hookenv.config() | ||
397 | 183 | >>> config['foo'] | ||
398 | 184 | 'baz' | ||
399 | 185 | >>> # test to see if this val has changed since last hook | ||
400 | 186 | >>> config.changed('foo') | ||
401 | 187 | True | ||
402 | 188 | >>> # what was the previous value? | ||
403 | 189 | >>> config.previous('foo') | ||
404 | 190 | 'bar' | ||
405 | 191 | >>> # keys/values that we add are preserved across hooks | ||
406 | 192 | >>> config['mykey'] | ||
407 | 193 | 'myval' | ||
408 | 194 | |||
409 | 195 | """ | ||
410 | 196 | CONFIG_FILE_NAME = '.juju-persistent-config' | ||
411 | 197 | |||
412 | 198 | def __init__(self, *args, **kw): | ||
413 | 199 | super(Config, self).__init__(*args, **kw) | ||
414 | 200 | self.implicit_save = True | ||
415 | 201 | self._prev_dict = None | ||
416 | 202 | self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME) | ||
417 | 203 | if os.path.exists(self.path): | ||
418 | 204 | self.load_previous() | ||
419 | 205 | |||
420 | 206 | def __getitem__(self, key): | ||
421 | 207 | """For regular dict lookups, check the current juju config first, | ||
422 | 208 | then the previous (saved) copy. This ensures that user-saved values | ||
423 | 209 | will be returned by a dict lookup. | ||
424 | 210 | |||
425 | 211 | """ | ||
426 | 212 | try: | ||
427 | 213 | return dict.__getitem__(self, key) | ||
428 | 214 | except KeyError: | ||
429 | 215 | return (self._prev_dict or {})[key] | ||
430 | 216 | |||
431 | 217 | def keys(self): | ||
432 | 218 | prev_keys = [] | ||
433 | 219 | if self._prev_dict is not None: | ||
434 | 220 | prev_keys = self._prev_dict.keys() | ||
435 | 221 | return list(set(prev_keys + dict.keys(self))) | ||
436 | 222 | |||
437 | 223 | def load_previous(self, path=None): | ||
438 | 224 | """Load previous copy of config from disk. | ||
439 | 225 | |||
440 | 226 | In normal usage you don't need to call this method directly - it | ||
441 | 227 | is called automatically at object initialization. | ||
442 | 228 | |||
443 | 229 | :param path: | ||
444 | 230 | |||
445 | 231 | File path from which to load the previous config. If `None`, | ||
446 | 232 | config is loaded from the default location. If `path` is | ||
447 | 233 | specified, subsequent `save()` calls will write to the same | ||
448 | 234 | path. | ||
449 | 235 | |||
450 | 236 | """ | ||
451 | 237 | self.path = path or self.path | ||
452 | 238 | with open(self.path) as f: | ||
453 | 239 | self._prev_dict = json.load(f) | ||
454 | 240 | |||
455 | 241 | def changed(self, key): | ||
456 | 242 | """Return True if the current value for this key is different from | ||
457 | 243 | the previous value. | ||
458 | 244 | |||
459 | 245 | """ | ||
460 | 246 | if self._prev_dict is None: | ||
461 | 247 | return True | ||
462 | 248 | return self.previous(key) != self.get(key) | ||
463 | 249 | |||
464 | 250 | def previous(self, key): | ||
465 | 251 | """Return previous value for this key, or None if there | ||
466 | 252 | is no previous value. | ||
467 | 253 | |||
468 | 254 | """ | ||
469 | 255 | if self._prev_dict: | ||
470 | 256 | return self._prev_dict.get(key) | ||
471 | 257 | return None | ||
472 | 258 | |||
473 | 259 | def save(self): | ||
474 | 260 | """Save this config to disk. | ||
475 | 261 | |||
476 | 262 | If the charm is using the :mod:`Services Framework <services.base>` | ||
477 | 263 | or :meth:'@hook <Hooks.hook>' decorator, this | ||
478 | 264 | is called automatically at the end of successful hook execution. | ||
479 | 265 | Otherwise, it should be called directly by user code. | ||
480 | 266 | |||
481 | 267 | To disable automatic saves, set ``implicit_save=False`` on this | ||
482 | 268 | instance. | ||
483 | 269 | |||
484 | 270 | """ | ||
485 | 271 | if self._prev_dict: | ||
486 | 272 | for k, v in self._prev_dict.iteritems(): | ||
487 | 273 | if k not in self: | ||
488 | 274 | self[k] = v | ||
489 | 275 | with open(self.path, 'w') as f: | ||
490 | 276 | json.dump(self, f) | ||
491 | 277 | |||
492 | 278 | |||
493 | 158 | @cached | 279 | @cached |
494 | 159 | def config(scope=None): | 280 | def config(scope=None): |
495 | 160 | """Juju charm configuration""" | 281 | """Juju charm configuration""" |
496 | @@ -163,7 +284,10 @@ | |||
497 | 163 | config_cmd_line.append(scope) | 284 | config_cmd_line.append(scope) |
498 | 164 | config_cmd_line.append('--format=json') | 285 | config_cmd_line.append('--format=json') |
499 | 165 | try: | 286 | try: |
501 | 166 | return json.loads(subprocess.check_output(config_cmd_line)) | 287 | config_data = json.loads(subprocess.check_output(config_cmd_line)) |
502 | 288 | if scope is not None: | ||
503 | 289 | return config_data | ||
504 | 290 | return Config(config_data) | ||
505 | 167 | except ValueError: | 291 | except ValueError: |
506 | 168 | return None | 292 | return None |
507 | 169 | 293 | ||
508 | @@ -188,8 +312,9 @@ | |||
509 | 188 | raise | 312 | raise |
510 | 189 | 313 | ||
511 | 190 | 314 | ||
513 | 191 | def relation_set(relation_id=None, relation_settings={}, **kwargs): | 315 | def relation_set(relation_id=None, relation_settings=None, **kwargs): |
514 | 192 | """Set relation information for the current unit""" | 316 | """Set relation information for the current unit""" |
515 | 317 | relation_settings = relation_settings if relation_settings else {} | ||
516 | 193 | relation_cmd_line = ['relation-set'] | 318 | relation_cmd_line = ['relation-set'] |
517 | 194 | if relation_id is not None: | 319 | if relation_id is not None: |
518 | 195 | relation_cmd_line.extend(('-r', relation_id)) | 320 | relation_cmd_line.extend(('-r', relation_id)) |
519 | @@ -348,27 +473,29 @@ | |||
520 | 348 | class Hooks(object): | 473 | class Hooks(object): |
521 | 349 | """A convenient handler for hook functions. | 474 | """A convenient handler for hook functions. |
522 | 350 | 475 | ||
524 | 351 | Example: | 476 | Example:: |
525 | 477 | |||
526 | 352 | hooks = Hooks() | 478 | hooks = Hooks() |
527 | 353 | 479 | ||
528 | 354 | # register a hook, taking its name from the function name | 480 | # register a hook, taking its name from the function name |
529 | 355 | @hooks.hook() | 481 | @hooks.hook() |
530 | 356 | def install(): | 482 | def install(): |
532 | 357 | ... | 483 | pass # your code here |
533 | 358 | 484 | ||
534 | 359 | # register a hook, providing a custom hook name | 485 | # register a hook, providing a custom hook name |
535 | 360 | @hooks.hook("config-changed") | 486 | @hooks.hook("config-changed") |
536 | 361 | def config_changed(): | 487 | def config_changed(): |
538 | 362 | ... | 488 | pass # your code here |
539 | 363 | 489 | ||
540 | 364 | if __name__ == "__main__": | 490 | if __name__ == "__main__": |
541 | 365 | # execute a hook based on the name the program is called by | 491 | # execute a hook based on the name the program is called by |
542 | 366 | hooks.execute(sys.argv) | 492 | hooks.execute(sys.argv) |
543 | 367 | """ | 493 | """ |
544 | 368 | 494 | ||
546 | 369 | def __init__(self): | 495 | def __init__(self, config_save=True): |
547 | 370 | super(Hooks, self).__init__() | 496 | super(Hooks, self).__init__() |
548 | 371 | self._hooks = {} | 497 | self._hooks = {} |
549 | 498 | self._config_save = config_save | ||
550 | 372 | 499 | ||
551 | 373 | def register(self, name, function): | 500 | def register(self, name, function): |
552 | 374 | """Register a hook""" | 501 | """Register a hook""" |
553 | @@ -379,6 +506,10 @@ | |||
554 | 379 | hook_name = os.path.basename(args[0]) | 506 | hook_name = os.path.basename(args[0]) |
555 | 380 | if hook_name in self._hooks: | 507 | if hook_name in self._hooks: |
556 | 381 | self._hooks[hook_name]() | 508 | self._hooks[hook_name]() |
557 | 509 | if self._config_save: | ||
558 | 510 | cfg = config() | ||
559 | 511 | if cfg.implicit_save: | ||
560 | 512 | cfg.save() | ||
561 | 382 | else: | 513 | else: |
562 | 383 | raise UnregisteredHookError(hook_name) | 514 | raise UnregisteredHookError(hook_name) |
563 | 384 | 515 | ||
564 | 385 | 516 | ||
565 | === modified file 'hooks/charmhelpers/core/host.py' | |||
566 | --- hooks/charmhelpers/core/host.py 2014-03-05 15:19:02 +0000 | |||
567 | +++ hooks/charmhelpers/core/host.py 2014-10-29 02:58:49 +0000 | |||
568 | @@ -6,16 +6,19 @@ | |||
569 | 6 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | 6 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> |
570 | 7 | 7 | ||
571 | 8 | import os | 8 | import os |
572 | 9 | import re | ||
573 | 9 | import pwd | 10 | import pwd |
574 | 10 | import grp | 11 | import grp |
575 | 11 | import random | 12 | import random |
576 | 12 | import string | 13 | import string |
577 | 13 | import subprocess | 14 | import subprocess |
578 | 14 | import hashlib | 15 | import hashlib |
579 | 16 | from contextlib import contextmanager | ||
580 | 15 | 17 | ||
581 | 16 | from collections import OrderedDict | 18 | from collections import OrderedDict |
582 | 17 | 19 | ||
583 | 18 | from hookenv import log | 20 | from hookenv import log |
584 | 21 | from fstab import Fstab | ||
585 | 19 | 22 | ||
586 | 20 | 23 | ||
587 | 21 | def service_start(service_name): | 24 | def service_start(service_name): |
588 | @@ -34,7 +37,8 @@ | |||
589 | 34 | 37 | ||
590 | 35 | 38 | ||
591 | 36 | def service_reload(service_name, restart_on_failure=False): | 39 | def service_reload(service_name, restart_on_failure=False): |
593 | 37 | """Reload a system service, optionally falling back to restart if reload fails""" | 40 | """Reload a system service, optionally falling back to restart if |
594 | 41 | reload fails""" | ||
595 | 38 | service_result = service('reload', service_name) | 42 | service_result = service('reload', service_name) |
596 | 39 | if not service_result and restart_on_failure: | 43 | if not service_result and restart_on_failure: |
597 | 40 | service_result = service('restart', service_name) | 44 | service_result = service('restart', service_name) |
598 | @@ -50,7 +54,7 @@ | |||
599 | 50 | def service_running(service): | 54 | def service_running(service): |
600 | 51 | """Determine whether a system service is running""" | 55 | """Determine whether a system service is running""" |
601 | 52 | try: | 56 | try: |
603 | 53 | output = subprocess.check_output(['service', service, 'status']) | 57 | output = subprocess.check_output(['service', service, 'status'], stderr=subprocess.STDOUT) |
604 | 54 | except subprocess.CalledProcessError: | 58 | except subprocess.CalledProcessError: |
605 | 55 | return False | 59 | return False |
606 | 56 | else: | 60 | else: |
607 | @@ -60,6 +64,16 @@ | |||
608 | 60 | return False | 64 | return False |
609 | 61 | 65 | ||
610 | 62 | 66 | ||
611 | 67 | def service_available(service_name): | ||
612 | 68 | """Determine whether a system service is available""" | ||
613 | 69 | try: | ||
614 | 70 | subprocess.check_output(['service', service_name, 'status'], stderr=subprocess.STDOUT) | ||
615 | 71 | except subprocess.CalledProcessError as e: | ||
616 | 72 | return 'unrecognized service' not in e.output | ||
617 | 73 | else: | ||
618 | 74 | return True | ||
619 | 75 | |||
620 | 76 | |||
621 | 63 | def adduser(username, password=None, shell='/bin/bash', system_user=False): | 77 | def adduser(username, password=None, shell='/bin/bash', system_user=False): |
622 | 64 | """Add a user to the system""" | 78 | """Add a user to the system""" |
623 | 65 | try: | 79 | try: |
624 | @@ -143,7 +157,19 @@ | |||
625 | 143 | target.write(content) | 157 | target.write(content) |
626 | 144 | 158 | ||
627 | 145 | 159 | ||
629 | 146 | def mount(device, mountpoint, options=None, persist=False): | 160 | def fstab_remove(mp): |
630 | 161 | """Remove the given mountpoint entry from /etc/fstab | ||
631 | 162 | """ | ||
632 | 163 | return Fstab.remove_by_mountpoint(mp) | ||
633 | 164 | |||
634 | 165 | |||
635 | 166 | def fstab_add(dev, mp, fs, options=None): | ||
636 | 167 | """Adds the given device entry to the /etc/fstab file | ||
637 | 168 | """ | ||
638 | 169 | return Fstab.add(dev, mp, fs, options=options) | ||
639 | 170 | |||
640 | 171 | |||
641 | 172 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): | ||
642 | 147 | """Mount a filesystem at a particular mountpoint""" | 173 | """Mount a filesystem at a particular mountpoint""" |
643 | 148 | cmd_args = ['mount'] | 174 | cmd_args = ['mount'] |
644 | 149 | if options is not None: | 175 | if options is not None: |
645 | @@ -154,9 +180,9 @@ | |||
646 | 154 | except subprocess.CalledProcessError, e: | 180 | except subprocess.CalledProcessError, e: |
647 | 155 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | 181 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) |
648 | 156 | return False | 182 | return False |
649 | 183 | |||
650 | 157 | if persist: | 184 | if persist: |
653 | 158 | # TODO: update fstab | 185 | return fstab_add(device, mountpoint, filesystem, options=options) |
652 | 159 | pass | ||
654 | 160 | return True | 186 | return True |
655 | 161 | 187 | ||
656 | 162 | 188 | ||
657 | @@ -168,9 +194,9 @@ | |||
658 | 168 | except subprocess.CalledProcessError, e: | 194 | except subprocess.CalledProcessError, e: |
659 | 169 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | 195 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) |
660 | 170 | return False | 196 | return False |
661 | 197 | |||
662 | 171 | if persist: | 198 | if persist: |
665 | 172 | # TODO: update fstab | 199 | return fstab_remove(mountpoint) |
664 | 173 | pass | ||
666 | 174 | return True | 200 | return True |
667 | 175 | 201 | ||
668 | 176 | 202 | ||
669 | @@ -183,10 +209,15 @@ | |||
670 | 183 | return system_mounts | 209 | return system_mounts |
671 | 184 | 210 | ||
672 | 185 | 211 | ||
675 | 186 | def file_hash(path): | 212 | def file_hash(path, hash_type='md5'): |
676 | 187 | """Generate a md5 hash of the contents of 'path' or None if not found """ | 213 | """ |
677 | 214 | Generate a hash checksum of the contents of 'path' or None if not found. | ||
678 | 215 | |||
679 | 216 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
680 | 217 | such as md5, sha1, sha256, sha512, etc. | ||
681 | 218 | """ | ||
682 | 188 | if os.path.exists(path): | 219 | if os.path.exists(path): |
684 | 189 | h = hashlib.md5() | 220 | h = getattr(hashlib, hash_type)() |
685 | 190 | with open(path, 'r') as source: | 221 | with open(path, 'r') as source: |
686 | 191 | h.update(source.read()) # IGNORE:E1101 - it does have update | 222 | h.update(source.read()) # IGNORE:E1101 - it does have update |
687 | 192 | return h.hexdigest() | 223 | return h.hexdigest() |
688 | @@ -194,16 +225,36 @@ | |||
689 | 194 | return None | 225 | return None |
690 | 195 | 226 | ||
691 | 196 | 227 | ||
692 | 228 | def check_hash(path, checksum, hash_type='md5'): | ||
693 | 229 | """ | ||
694 | 230 | Validate a file using a cryptographic checksum. | ||
695 | 231 | |||
696 | 232 | :param str checksum: Value of the checksum used to validate the file. | ||
697 | 233 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
698 | 234 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
699 | 235 | such as md5, sha1, sha256, sha512, etc. | ||
700 | 236 | :raises ChecksumError: If the file fails the checksum | ||
701 | 237 | |||
702 | 238 | """ | ||
703 | 239 | actual_checksum = file_hash(path, hash_type) | ||
704 | 240 | if checksum != actual_checksum: | ||
705 | 241 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
706 | 242 | |||
707 | 243 | |||
708 | 244 | class ChecksumError(ValueError): | ||
709 | 245 | pass | ||
710 | 246 | |||
711 | 247 | |||
712 | 197 | def restart_on_change(restart_map, stopstart=False): | 248 | def restart_on_change(restart_map, stopstart=False): |
713 | 198 | """Restart services based on configuration files changing | 249 | """Restart services based on configuration files changing |
714 | 199 | 250 | ||
716 | 200 | This function is used a decorator, for example | 251 | This function is used a decorator, for example:: |
717 | 201 | 252 | ||
718 | 202 | @restart_on_change({ | 253 | @restart_on_change({ |
719 | 203 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] | 254 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] |
720 | 204 | }) | 255 | }) |
721 | 205 | def ceph_client_changed(): | 256 | def ceph_client_changed(): |
723 | 206 | ... | 257 | pass # your code here |
724 | 207 | 258 | ||
725 | 208 | In this example, the cinder-api and cinder-volume services | 259 | In this example, the cinder-api and cinder-volume services |
726 | 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 |
727 | @@ -266,7 +317,13 @@ | |||
728 | 266 | ip_output = (line for line in ip_output if line) | 317 | ip_output = (line for line in ip_output if line) |
729 | 267 | for line in ip_output: | 318 | for line in ip_output: |
730 | 268 | if line.split()[1].startswith(int_type): | 319 | if line.split()[1].startswith(int_type): |
732 | 269 | interfaces.append(line.split()[1].replace(":", "")) | 320 | matched = re.search('.*: (bond[0-9]+\.[0-9]+)@.*', line) |
733 | 321 | if matched: | ||
734 | 322 | interface = matched.groups()[0] | ||
735 | 323 | else: | ||
736 | 324 | interface = line.split()[1].replace(":", "") | ||
737 | 325 | interfaces.append(interface) | ||
738 | 326 | |||
739 | 270 | return interfaces | 327 | return interfaces |
740 | 271 | 328 | ||
741 | 272 | 329 | ||
742 | @@ -295,3 +352,40 @@ | |||
743 | 295 | if 'link/ether' in words: | 352 | if 'link/ether' in words: |
744 | 296 | hwaddr = words[words.index('link/ether') + 1] | 353 | hwaddr = words[words.index('link/ether') + 1] |
745 | 297 | return hwaddr | 354 | return hwaddr |
746 | 355 | |||
747 | 356 | |||
748 | 357 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
749 | 358 | '''Compare supplied revno with the revno of the installed package | ||
750 | 359 | |||
751 | 360 | * 1 => Installed revno is greater than supplied arg | ||
752 | 361 | * 0 => Installed revno is the same as supplied arg | ||
753 | 362 | * -1 => Installed revno is less than supplied arg | ||
754 | 363 | |||
755 | 364 | ''' | ||
756 | 365 | import apt_pkg | ||
757 | 366 | from charmhelpers.fetch import apt_cache | ||
758 | 367 | if not pkgcache: | ||
759 | 368 | pkgcache = apt_cache() | ||
760 | 369 | pkg = pkgcache[package] | ||
761 | 370 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | ||
762 | 371 | |||
763 | 372 | |||
764 | 373 | @contextmanager | ||
765 | 374 | def chdir(d): | ||
766 | 375 | cur = os.getcwd() | ||
767 | 376 | try: | ||
768 | 377 | yield os.chdir(d) | ||
769 | 378 | finally: | ||
770 | 379 | os.chdir(cur) | ||
771 | 380 | |||
772 | 381 | |||
773 | 382 | def chownr(path, owner, group): | ||
774 | 383 | uid = pwd.getpwnam(owner).pw_uid | ||
775 | 384 | gid = grp.getgrnam(group).gr_gid | ||
776 | 385 | |||
777 | 386 | for root, dirs, files in os.walk(path): | ||
778 | 387 | for name in dirs + files: | ||
779 | 388 | full = os.path.join(root, name) | ||
780 | 389 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | ||
781 | 390 | if not broken_symlink: | ||
782 | 391 | os.chown(full, uid, gid) | ||
783 | 298 | 392 | ||
784 | === added directory 'hooks/charmhelpers/core/services' | |||
785 | === added file 'hooks/charmhelpers/core/services/__init__.py' | |||
786 | --- hooks/charmhelpers/core/services/__init__.py 1970-01-01 00:00:00 +0000 | |||
787 | +++ hooks/charmhelpers/core/services/__init__.py 2014-10-29 02:58:49 +0000 | |||
788 | @@ -0,0 +1,2 @@ | |||
789 | 1 | from .base import * # NOQA | ||
790 | 2 | from .helpers import * # NOQA | ||
791 | 0 | 3 | ||
792 | === added file 'hooks/charmhelpers/core/services/base.py' | |||
793 | --- hooks/charmhelpers/core/services/base.py 1970-01-01 00:00:00 +0000 | |||
794 | +++ hooks/charmhelpers/core/services/base.py 2014-10-29 02:58:49 +0000 | |||
795 | @@ -0,0 +1,313 @@ | |||
796 | 1 | import os | ||
797 | 2 | import re | ||
798 | 3 | import json | ||
799 | 4 | from collections import Iterable | ||
800 | 5 | |||
801 | 6 | from charmhelpers.core import host | ||
802 | 7 | from charmhelpers.core import hookenv | ||
803 | 8 | |||
804 | 9 | |||
805 | 10 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
806 | 11 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
807 | 12 | 'service_restart', 'service_stop'] | ||
808 | 13 | |||
809 | 14 | |||
810 | 15 | class ServiceManager(object): | ||
811 | 16 | def __init__(self, services=None): | ||
812 | 17 | """ | ||
813 | 18 | Register a list of services, given their definitions. | ||
814 | 19 | |||
815 | 20 | Service definitions are dicts in the following formats (all keys except | ||
816 | 21 | 'service' are optional):: | ||
817 | 22 | |||
818 | 23 | { | ||
819 | 24 | "service": <service name>, | ||
820 | 25 | "required_data": <list of required data contexts>, | ||
821 | 26 | "provided_data": <list of provided data contexts>, | ||
822 | 27 | "data_ready": <one or more callbacks>, | ||
823 | 28 | "data_lost": <one or more callbacks>, | ||
824 | 29 | "start": <one or more callbacks>, | ||
825 | 30 | "stop": <one or more callbacks>, | ||
826 | 31 | "ports": <list of ports to manage>, | ||
827 | 32 | } | ||
828 | 33 | |||
829 | 34 | The 'required_data' list should contain dicts of required data (or | ||
830 | 35 | dependency managers that act like dicts and know how to collect the data). | ||
831 | 36 | Only when all items in the 'required_data' list are populated are the list | ||
832 | 37 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
833 | 38 | information. | ||
834 | 39 | |||
835 | 40 | The 'provided_data' list should contain relation data providers, most likely | ||
836 | 41 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
837 | 42 | that will indicate a set of data to set on a given relation. | ||
838 | 43 | |||
839 | 44 | The 'data_ready' value should be either a single callback, or a list of | ||
840 | 45 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
841 | 46 | Each callback will be called with the service name as the only parameter. | ||
842 | 47 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
843 | 48 | are fired. | ||
844 | 49 | |||
845 | 50 | The 'data_lost' value should be either a single callback, or a list of | ||
846 | 51 | callbacks, to be called when a 'required_data' item no longer passes | ||
847 | 52 | `is_ready()`. Each callback will be called with the service name as the | ||
848 | 53 | only parameter. After all of the 'data_lost' callbacks are called, | ||
849 | 54 | the 'stop' callbacks are fired. | ||
850 | 55 | |||
851 | 56 | The 'start' value should be either a single callback, or a list of | ||
852 | 57 | callbacks, to be called when starting the service, after the 'data_ready' | ||
853 | 58 | callbacks are complete. Each callback will be called with the service | ||
854 | 59 | name as the only parameter. This defaults to | ||
855 | 60 | `[host.service_start, services.open_ports]`. | ||
856 | 61 | |||
857 | 62 | The 'stop' value should be either a single callback, or a list of | ||
858 | 63 | callbacks, to be called when stopping the service. If the service is | ||
859 | 64 | being stopped because it no longer has all of its 'required_data', this | ||
860 | 65 | will be called after all of the 'data_lost' callbacks are complete. | ||
861 | 66 | Each callback will be called with the service name as the only parameter. | ||
862 | 67 | This defaults to `[services.close_ports, host.service_stop]`. | ||
863 | 68 | |||
864 | 69 | The 'ports' value should be a list of ports to manage. The default | ||
865 | 70 | 'start' handler will open the ports after the service is started, | ||
866 | 71 | and the default 'stop' handler will close the ports prior to stopping | ||
867 | 72 | the service. | ||
868 | 73 | |||
869 | 74 | |||
870 | 75 | Examples: | ||
871 | 76 | |||
872 | 77 | The following registers an Upstart service called bingod that depends on | ||
873 | 78 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
874 | 79 | restarting the service, and a Runit service called spadesd:: | ||
875 | 80 | |||
876 | 81 | manager = services.ServiceManager([ | ||
877 | 82 | { | ||
878 | 83 | 'service': 'bingod', | ||
879 | 84 | 'ports': [80, 443], | ||
880 | 85 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
881 | 86 | 'data_ready': [ | ||
882 | 87 | services.template(source='bingod.conf'), | ||
883 | 88 | services.template(source='bingod.ini', | ||
884 | 89 | target='/etc/bingod.ini', | ||
885 | 90 | owner='bingo', perms=0400), | ||
886 | 91 | ], | ||
887 | 92 | }, | ||
888 | 93 | { | ||
889 | 94 | 'service': 'spadesd', | ||
890 | 95 | 'data_ready': services.template(source='spadesd_run.j2', | ||
891 | 96 | target='/etc/sv/spadesd/run', | ||
892 | 97 | perms=0555), | ||
893 | 98 | 'start': runit_start, | ||
894 | 99 | 'stop': runit_stop, | ||
895 | 100 | }, | ||
896 | 101 | ]) | ||
897 | 102 | manager.manage() | ||
898 | 103 | """ | ||
899 | 104 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
900 | 105 | self._ready = None | ||
901 | 106 | self.services = {} | ||
902 | 107 | for service in services or []: | ||
903 | 108 | service_name = service['service'] | ||
904 | 109 | self.services[service_name] = service | ||
905 | 110 | |||
906 | 111 | def manage(self): | ||
907 | 112 | """ | ||
908 | 113 | Handle the current hook by doing The Right Thing with the registered services. | ||
909 | 114 | """ | ||
910 | 115 | hook_name = hookenv.hook_name() | ||
911 | 116 | if hook_name == 'stop': | ||
912 | 117 | self.stop_services() | ||
913 | 118 | else: | ||
914 | 119 | self.provide_data() | ||
915 | 120 | self.reconfigure_services() | ||
916 | 121 | cfg = hookenv.config() | ||
917 | 122 | if cfg.implicit_save: | ||
918 | 123 | cfg.save() | ||
919 | 124 | |||
920 | 125 | def provide_data(self): | ||
921 | 126 | """ | ||
922 | 127 | Set the relation data for each provider in the ``provided_data`` list. | ||
923 | 128 | |||
924 | 129 | A provider must have a `name` attribute, which indicates which relation | ||
925 | 130 | to set data on, and a `provide_data()` method, which returns a dict of | ||
926 | 131 | data to set. | ||
927 | 132 | """ | ||
928 | 133 | hook_name = hookenv.hook_name() | ||
929 | 134 | for service in self.services.values(): | ||
930 | 135 | for provider in service.get('provided_data', []): | ||
931 | 136 | if re.match(r'{}-relation-(joined|changed)'.format(provider.name), hook_name): | ||
932 | 137 | data = provider.provide_data() | ||
933 | 138 | _ready = provider._is_ready(data) if hasattr(provider, '_is_ready') else data | ||
934 | 139 | if _ready: | ||
935 | 140 | hookenv.relation_set(None, data) | ||
936 | 141 | |||
937 | 142 | def reconfigure_services(self, *service_names): | ||
938 | 143 | """ | ||
939 | 144 | Update all files for one or more registered services, and, | ||
940 | 145 | if ready, optionally restart them. | ||
941 | 146 | |||
942 | 147 | If no service names are given, reconfigures all registered services. | ||
943 | 148 | """ | ||
944 | 149 | for service_name in service_names or self.services.keys(): | ||
945 | 150 | if self.is_ready(service_name): | ||
946 | 151 | self.fire_event('data_ready', service_name) | ||
947 | 152 | self.fire_event('start', service_name, default=[ | ||
948 | 153 | service_restart, | ||
949 | 154 | manage_ports]) | ||
950 | 155 | self.save_ready(service_name) | ||
951 | 156 | else: | ||
952 | 157 | if self.was_ready(service_name): | ||
953 | 158 | self.fire_event('data_lost', service_name) | ||
954 | 159 | self.fire_event('stop', service_name, default=[ | ||
955 | 160 | manage_ports, | ||
956 | 161 | service_stop]) | ||
957 | 162 | self.save_lost(service_name) | ||
958 | 163 | |||
959 | 164 | def stop_services(self, *service_names): | ||
960 | 165 | """ | ||
961 | 166 | Stop one or more registered services, by name. | ||
962 | 167 | |||
963 | 168 | If no service names are given, stops all registered services. | ||
964 | 169 | """ | ||
965 | 170 | for service_name in service_names or self.services.keys(): | ||
966 | 171 | self.fire_event('stop', service_name, default=[ | ||
967 | 172 | manage_ports, | ||
968 | 173 | service_stop]) | ||
969 | 174 | |||
970 | 175 | def get_service(self, service_name): | ||
971 | 176 | """ | ||
972 | 177 | Given the name of a registered service, return its service definition. | ||
973 | 178 | """ | ||
974 | 179 | service = self.services.get(service_name) | ||
975 | 180 | if not service: | ||
976 | 181 | raise KeyError('Service not registered: %s' % service_name) | ||
977 | 182 | return service | ||
978 | 183 | |||
979 | 184 | def fire_event(self, event_name, service_name, default=None): | ||
980 | 185 | """ | ||
981 | 186 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
982 | 187 | """ | ||
983 | 188 | service = self.get_service(service_name) | ||
984 | 189 | callbacks = service.get(event_name, default) | ||
985 | 190 | if not callbacks: | ||
986 | 191 | return | ||
987 | 192 | if not isinstance(callbacks, Iterable): | ||
988 | 193 | callbacks = [callbacks] | ||
989 | 194 | for callback in callbacks: | ||
990 | 195 | if isinstance(callback, ManagerCallback): | ||
991 | 196 | callback(self, service_name, event_name) | ||
992 | 197 | else: | ||
993 | 198 | callback(service_name) | ||
994 | 199 | |||
995 | 200 | def is_ready(self, service_name): | ||
996 | 201 | """ | ||
997 | 202 | Determine if a registered service is ready, by checking its 'required_data'. | ||
998 | 203 | |||
999 | 204 | A 'required_data' item can be any mapping type, and is considered ready | ||
1000 | 205 | if `bool(item)` evaluates as True. | ||
1001 | 206 | """ | ||
1002 | 207 | service = self.get_service(service_name) | ||
1003 | 208 | reqs = service.get('required_data', []) | ||
1004 | 209 | return all(bool(req) for req in reqs) | ||
1005 | 210 | |||
1006 | 211 | def _load_ready_file(self): | ||
1007 | 212 | if self._ready is not None: | ||
1008 | 213 | return | ||
1009 | 214 | if os.path.exists(self._ready_file): | ||
1010 | 215 | with open(self._ready_file) as fp: | ||
1011 | 216 | self._ready = set(json.load(fp)) | ||
1012 | 217 | else: | ||
1013 | 218 | self._ready = set() | ||
1014 | 219 | |||
1015 | 220 | def _save_ready_file(self): | ||
1016 | 221 | if self._ready is None: | ||
1017 | 222 | return | ||
1018 | 223 | with open(self._ready_file, 'w') as fp: | ||
1019 | 224 | json.dump(list(self._ready), fp) | ||
1020 | 225 | |||
1021 | 226 | def save_ready(self, service_name): | ||
1022 | 227 | """ | ||
1023 | 228 | Save an indicator that the given service is now data_ready. | ||
1024 | 229 | """ | ||
1025 | 230 | self._load_ready_file() | ||
1026 | 231 | self._ready.add(service_name) | ||
1027 | 232 | self._save_ready_file() | ||
1028 | 233 | |||
1029 | 234 | def save_lost(self, service_name): | ||
1030 | 235 | """ | ||
1031 | 236 | Save an indicator that the given service is no longer data_ready. | ||
1032 | 237 | """ | ||
1033 | 238 | self._load_ready_file() | ||
1034 | 239 | self._ready.discard(service_name) | ||
1035 | 240 | self._save_ready_file() | ||
1036 | 241 | |||
1037 | 242 | def was_ready(self, service_name): | ||
1038 | 243 | """ | ||
1039 | 244 | Determine if the given service was previously data_ready. | ||
1040 | 245 | """ | ||
1041 | 246 | self._load_ready_file() | ||
1042 | 247 | return service_name in self._ready | ||
1043 | 248 | |||
1044 | 249 | |||
1045 | 250 | class ManagerCallback(object): | ||
1046 | 251 | """ | ||
1047 | 252 | Special case of a callback that takes the `ServiceManager` instance | ||
1048 | 253 | in addition to the service name. | ||
1049 | 254 | |||
1050 | 255 | Subclasses should implement `__call__` which should accept three parameters: | ||
1051 | 256 | |||
1052 | 257 | * `manager` The `ServiceManager` instance | ||
1053 | 258 | * `service_name` The name of the service it's being triggered for | ||
1054 | 259 | * `event_name` The name of the event that this callback is handling | ||
1055 | 260 | """ | ||
1056 | 261 | def __call__(self, manager, service_name, event_name): | ||
1057 | 262 | raise NotImplementedError() | ||
1058 | 263 | |||
1059 | 264 | |||
1060 | 265 | class PortManagerCallback(ManagerCallback): | ||
1061 | 266 | """ | ||
1062 | 267 | Callback class that will open or close ports, for use as either | ||
1063 | 268 | a start or stop action. | ||
1064 | 269 | """ | ||
1065 | 270 | def __call__(self, manager, service_name, event_name): | ||
1066 | 271 | service = manager.get_service(service_name) | ||
1067 | 272 | new_ports = service.get('ports', []) | ||
1068 | 273 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
1069 | 274 | if os.path.exists(port_file): | ||
1070 | 275 | with open(port_file) as fp: | ||
1071 | 276 | old_ports = fp.read().split(',') | ||
1072 | 277 | for old_port in old_ports: | ||
1073 | 278 | if bool(old_port): | ||
1074 | 279 | old_port = int(old_port) | ||
1075 | 280 | if old_port not in new_ports: | ||
1076 | 281 | hookenv.close_port(old_port) | ||
1077 | 282 | with open(port_file, 'w') as fp: | ||
1078 | 283 | fp.write(','.join(str(port) for port in new_ports)) | ||
1079 | 284 | for port in new_ports: | ||
1080 | 285 | if event_name == 'start': | ||
1081 | 286 | hookenv.open_port(port) | ||
1082 | 287 | elif event_name == 'stop': | ||
1083 | 288 | hookenv.close_port(port) | ||
1084 | 289 | |||
1085 | 290 | |||
1086 | 291 | def service_stop(service_name): | ||
1087 | 292 | """ | ||
1088 | 293 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
1089 | 294 | messages in the logs. | ||
1090 | 295 | """ | ||
1091 | 296 | if host.service_running(service_name): | ||
1092 | 297 | host.service_stop(service_name) | ||
1093 | 298 | |||
1094 | 299 | |||
1095 | 300 | def service_restart(service_name): | ||
1096 | 301 | """ | ||
1097 | 302 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
1098 | 303 | messages in the logs. | ||
1099 | 304 | """ | ||
1100 | 305 | if host.service_available(service_name): | ||
1101 | 306 | if host.service_running(service_name): | ||
1102 | 307 | host.service_restart(service_name) | ||
1103 | 308 | else: | ||
1104 | 309 | host.service_start(service_name) | ||
1105 | 310 | |||
1106 | 311 | |||
1107 | 312 | # Convenience aliases | ||
1108 | 313 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
1109 | 0 | 314 | ||
1110 | === added file 'hooks/charmhelpers/core/services/helpers.py' | |||
1111 | --- hooks/charmhelpers/core/services/helpers.py 1970-01-01 00:00:00 +0000 | |||
1112 | +++ hooks/charmhelpers/core/services/helpers.py 2014-10-29 02:58:49 +0000 | |||
1113 | @@ -0,0 +1,239 @@ | |||
1114 | 1 | import os | ||
1115 | 2 | import yaml | ||
1116 | 3 | from charmhelpers.core import hookenv | ||
1117 | 4 | from charmhelpers.core import templating | ||
1118 | 5 | |||
1119 | 6 | from charmhelpers.core.services.base import ManagerCallback | ||
1120 | 7 | |||
1121 | 8 | |||
1122 | 9 | __all__ = ['RelationContext', 'TemplateCallback', | ||
1123 | 10 | 'render_template', 'template'] | ||
1124 | 11 | |||
1125 | 12 | |||
1126 | 13 | class RelationContext(dict): | ||
1127 | 14 | """ | ||
1128 | 15 | Base class for a context generator that gets relation data from juju. | ||
1129 | 16 | |||
1130 | 17 | Subclasses must provide the attributes `name`, which is the name of the | ||
1131 | 18 | interface of interest, `interface`, which is the type of the interface of | ||
1132 | 19 | interest, and `required_keys`, which is the set of keys required for the | ||
1133 | 20 | relation to be considered complete. The data for all interfaces matching | ||
1134 | 21 | the `name` attribute that are complete will used to populate the dictionary | ||
1135 | 22 | values (see `get_data`, below). | ||
1136 | 23 | |||
1137 | 24 | The generated context will be namespaced under the relation :attr:`name`, | ||
1138 | 25 | to prevent potential naming conflicts. | ||
1139 | 26 | |||
1140 | 27 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1141 | 28 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1142 | 29 | """ | ||
1143 | 30 | name = None | ||
1144 | 31 | interface = None | ||
1145 | 32 | required_keys = [] | ||
1146 | 33 | |||
1147 | 34 | def __init__(self, name=None, additional_required_keys=None): | ||
1148 | 35 | if name is not None: | ||
1149 | 36 | self.name = name | ||
1150 | 37 | if additional_required_keys is not None: | ||
1151 | 38 | self.required_keys.extend(additional_required_keys) | ||
1152 | 39 | self.get_data() | ||
1153 | 40 | |||
1154 | 41 | def __bool__(self): | ||
1155 | 42 | """ | ||
1156 | 43 | Returns True if all of the required_keys are available. | ||
1157 | 44 | """ | ||
1158 | 45 | return self.is_ready() | ||
1159 | 46 | |||
1160 | 47 | __nonzero__ = __bool__ | ||
1161 | 48 | |||
1162 | 49 | def __repr__(self): | ||
1163 | 50 | return super(RelationContext, self).__repr__() | ||
1164 | 51 | |||
1165 | 52 | def is_ready(self): | ||
1166 | 53 | """ | ||
1167 | 54 | Returns True if all of the `required_keys` are available from any units. | ||
1168 | 55 | """ | ||
1169 | 56 | ready = len(self.get(self.name, [])) > 0 | ||
1170 | 57 | if not ready: | ||
1171 | 58 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
1172 | 59 | return ready | ||
1173 | 60 | |||
1174 | 61 | def _is_ready(self, unit_data): | ||
1175 | 62 | """ | ||
1176 | 63 | Helper method that tests a set of relation data and returns True if | ||
1177 | 64 | all of the `required_keys` are present. | ||
1178 | 65 | """ | ||
1179 | 66 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
1180 | 67 | |||
1181 | 68 | def get_data(self): | ||
1182 | 69 | """ | ||
1183 | 70 | Retrieve the relation data for each unit involved in a relation and, | ||
1184 | 71 | if complete, store it in a list under `self[self.name]`. This | ||
1185 | 72 | is automatically called when the RelationContext is instantiated. | ||
1186 | 73 | |||
1187 | 74 | The units are sorted lexographically first by the service ID, then by | ||
1188 | 75 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
1189 | 76 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
1190 | 77 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
1191 | 78 | set of data, the relation data for the units will be stored in the | ||
1192 | 79 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
1193 | 80 | |||
1194 | 81 | If you only care about a single unit on the relation, you can just | ||
1195 | 82 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
1196 | 83 | support multiple units on a relation, you should iterate over the list, | ||
1197 | 84 | like:: | ||
1198 | 85 | |||
1199 | 86 | {% for unit in interface -%} | ||
1200 | 87 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
1201 | 88 | {%- endfor %} | ||
1202 | 89 | |||
1203 | 90 | Note that since all sets of relation data from all related services and | ||
1204 | 91 | units are in a single list, if you need to know which service or unit a | ||
1205 | 92 | set of data came from, you'll need to extend this class to preserve | ||
1206 | 93 | that information. | ||
1207 | 94 | """ | ||
1208 | 95 | if not hookenv.relation_ids(self.name): | ||
1209 | 96 | return | ||
1210 | 97 | |||
1211 | 98 | ns = self.setdefault(self.name, []) | ||
1212 | 99 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
1213 | 100 | for unit in sorted(hookenv.related_units(rid)): | ||
1214 | 101 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
1215 | 102 | if self._is_ready(reldata): | ||
1216 | 103 | ns.append(reldata) | ||
1217 | 104 | |||
1218 | 105 | def provide_data(self): | ||
1219 | 106 | """ | ||
1220 | 107 | Return data to be relation_set for this interface. | ||
1221 | 108 | """ | ||
1222 | 109 | return {} | ||
1223 | 110 | |||
1224 | 111 | |||
1225 | 112 | class MysqlRelation(RelationContext): | ||
1226 | 113 | """ | ||
1227 | 114 | Relation context for the `mysql` interface. | ||
1228 | 115 | |||
1229 | 116 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1230 | 117 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1231 | 118 | """ | ||
1232 | 119 | name = 'db' | ||
1233 | 120 | interface = 'mysql' | ||
1234 | 121 | required_keys = ['host', 'user', 'password', 'database'] | ||
1235 | 122 | |||
1236 | 123 | |||
1237 | 124 | class HttpRelation(RelationContext): | ||
1238 | 125 | """ | ||
1239 | 126 | Relation context for the `http` interface. | ||
1240 | 127 | |||
1241 | 128 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1242 | 129 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1243 | 130 | """ | ||
1244 | 131 | name = 'website' | ||
1245 | 132 | interface = 'http' | ||
1246 | 133 | required_keys = ['host', 'port'] | ||
1247 | 134 | |||
1248 | 135 | def provide_data(self): | ||
1249 | 136 | return { | ||
1250 | 137 | 'host': hookenv.unit_get('private-address'), | ||
1251 | 138 | 'port': 80, | ||
1252 | 139 | } | ||
1253 | 140 | |||
1254 | 141 | |||
1255 | 142 | class RequiredConfig(dict): | ||
1256 | 143 | """ | ||
1257 | 144 | Data context that loads config options with one or more mandatory options. | ||
1258 | 145 | |||
1259 | 146 | Once the required options have been changed from their default values, all | ||
1260 | 147 | config options will be available, namespaced under `config` to prevent | ||
1261 | 148 | potential naming conflicts (for example, between a config option and a | ||
1262 | 149 | relation property). | ||
1263 | 150 | |||
1264 | 151 | :param list *args: List of options that must be changed from their default values. | ||
1265 | 152 | """ | ||
1266 | 153 | |||
1267 | 154 | def __init__(self, *args): | ||
1268 | 155 | self.required_options = args | ||
1269 | 156 | self['config'] = hookenv.config() | ||
1270 | 157 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
1271 | 158 | self.config = yaml.load(fp).get('options', {}) | ||
1272 | 159 | |||
1273 | 160 | def __bool__(self): | ||
1274 | 161 | for option in self.required_options: | ||
1275 | 162 | if option not in self['config']: | ||
1276 | 163 | return False | ||
1277 | 164 | current_value = self['config'][option] | ||
1278 | 165 | default_value = self.config[option].get('default') | ||
1279 | 166 | if current_value == default_value: | ||
1280 | 167 | return False | ||
1281 | 168 | if current_value in (None, '') and default_value in (None, ''): | ||
1282 | 169 | return False | ||
1283 | 170 | return True | ||
1284 | 171 | |||
1285 | 172 | def __nonzero__(self): | ||
1286 | 173 | return self.__bool__() | ||
1287 | 174 | |||
1288 | 175 | |||
1289 | 176 | class StoredContext(dict): | ||
1290 | 177 | """ | ||
1291 | 178 | A data context that always returns the data that it was first created with. | ||
1292 | 179 | |||
1293 | 180 | This is useful to do a one-time generation of things like passwords, that | ||
1294 | 181 | will thereafter use the same value that was originally generated, instead | ||
1295 | 182 | of generating a new value each time it is run. | ||
1296 | 183 | """ | ||
1297 | 184 | def __init__(self, file_name, config_data): | ||
1298 | 185 | """ | ||
1299 | 186 | If the file exists, populate `self` with the data from the file. | ||
1300 | 187 | Otherwise, populate with the given data and persist it to the file. | ||
1301 | 188 | """ | ||
1302 | 189 | if os.path.exists(file_name): | ||
1303 | 190 | self.update(self.read_context(file_name)) | ||
1304 | 191 | else: | ||
1305 | 192 | self.store_context(file_name, config_data) | ||
1306 | 193 | self.update(config_data) | ||
1307 | 194 | |||
1308 | 195 | def store_context(self, file_name, config_data): | ||
1309 | 196 | if not os.path.isabs(file_name): | ||
1310 | 197 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
1311 | 198 | with open(file_name, 'w') as file_stream: | ||
1312 | 199 | os.fchmod(file_stream.fileno(), 0600) | ||
1313 | 200 | yaml.dump(config_data, file_stream) | ||
1314 | 201 | |||
1315 | 202 | def read_context(self, file_name): | ||
1316 | 203 | if not os.path.isabs(file_name): | ||
1317 | 204 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
1318 | 205 | with open(file_name, 'r') as file_stream: | ||
1319 | 206 | data = yaml.load(file_stream) | ||
1320 | 207 | if not data: | ||
1321 | 208 | raise OSError("%s is empty" % file_name) | ||
1322 | 209 | return data | ||
1323 | 210 | |||
1324 | 211 | |||
1325 | 212 | class TemplateCallback(ManagerCallback): | ||
1326 | 213 | """ | ||
1327 | 214 | Callback class that will render a Jinja2 template, for use as a ready action. | ||
1328 | 215 | |||
1329 | 216 | :param str source: The template source file, relative to `$CHARM_DIR/templates` | ||
1330 | 217 | :param str target: The target to write the rendered template to | ||
1331 | 218 | :param str owner: The owner of the rendered file | ||
1332 | 219 | :param str group: The group of the rendered file | ||
1333 | 220 | :param int perms: The permissions of the rendered file | ||
1334 | 221 | """ | ||
1335 | 222 | def __init__(self, source, target, owner='root', group='root', perms=0444): | ||
1336 | 223 | self.source = source | ||
1337 | 224 | self.target = target | ||
1338 | 225 | self.owner = owner | ||
1339 | 226 | self.group = group | ||
1340 | 227 | self.perms = perms | ||
1341 | 228 | |||
1342 | 229 | def __call__(self, manager, service_name, event_name): | ||
1343 | 230 | service = manager.get_service(service_name) | ||
1344 | 231 | context = {} | ||
1345 | 232 | for ctx in service.get('required_data', []): | ||
1346 | 233 | context.update(ctx) | ||
1347 | 234 | templating.render(self.source, self.target, context, | ||
1348 | 235 | self.owner, self.group, self.perms) | ||
1349 | 236 | |||
1350 | 237 | |||
1351 | 238 | # Convenience aliases for templates | ||
1352 | 239 | render_template = template = TemplateCallback | ||
1353 | 0 | 240 | ||
1354 | === added file 'hooks/charmhelpers/core/sysctl.py' | |||
1355 | --- hooks/charmhelpers/core/sysctl.py 1970-01-01 00:00:00 +0000 | |||
1356 | +++ hooks/charmhelpers/core/sysctl.py 2014-10-29 02:58:49 +0000 | |||
1357 | @@ -0,0 +1,34 @@ | |||
1358 | 1 | #!/usr/bin/env python | ||
1359 | 2 | # -*- coding: utf-8 -*- | ||
1360 | 3 | |||
1361 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
1362 | 5 | |||
1363 | 6 | import yaml | ||
1364 | 7 | |||
1365 | 8 | from subprocess import check_call | ||
1366 | 9 | |||
1367 | 10 | from charmhelpers.core.hookenv import ( | ||
1368 | 11 | log, | ||
1369 | 12 | DEBUG, | ||
1370 | 13 | ) | ||
1371 | 14 | |||
1372 | 15 | |||
1373 | 16 | def create(sysctl_dict, sysctl_file): | ||
1374 | 17 | """Creates a sysctl.conf file from a YAML associative array | ||
1375 | 18 | |||
1376 | 19 | :param sysctl_dict: a dict of sysctl options eg { 'kernel.max_pid': 1337 } | ||
1377 | 20 | :type sysctl_dict: dict | ||
1378 | 21 | :param sysctl_file: path to the sysctl file to be saved | ||
1379 | 22 | :type sysctl_file: str or unicode | ||
1380 | 23 | :returns: None | ||
1381 | 24 | """ | ||
1382 | 25 | sysctl_dict = yaml.load(sysctl_dict) | ||
1383 | 26 | |||
1384 | 27 | with open(sysctl_file, "w") as fd: | ||
1385 | 28 | for key, value in sysctl_dict.items(): | ||
1386 | 29 | fd.write("{}={}\n".format(key, value)) | ||
1387 | 30 | |||
1388 | 31 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict), | ||
1389 | 32 | level=DEBUG) | ||
1390 | 33 | |||
1391 | 34 | check_call(["sysctl", "-p", sysctl_file]) | ||
1392 | 0 | 35 | ||
1393 | === added file 'hooks/charmhelpers/core/templating.py' | |||
1394 | --- hooks/charmhelpers/core/templating.py 1970-01-01 00:00:00 +0000 | |||
1395 | +++ hooks/charmhelpers/core/templating.py 2014-10-29 02:58:49 +0000 | |||
1396 | @@ -0,0 +1,51 @@ | |||
1397 | 1 | import os | ||
1398 | 2 | |||
1399 | 3 | from charmhelpers.core import host | ||
1400 | 4 | from charmhelpers.core import hookenv | ||
1401 | 5 | |||
1402 | 6 | |||
1403 | 7 | def render(source, target, context, owner='root', group='root', perms=0444, templates_dir=None): | ||
1404 | 8 | """ | ||
1405 | 9 | Render a template. | ||
1406 | 10 | |||
1407 | 11 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
1408 | 12 | |||
1409 | 13 | The `target` path should be absolute. | ||
1410 | 14 | |||
1411 | 15 | The context should be a dict containing the values to be replaced in the | ||
1412 | 16 | template. | ||
1413 | 17 | |||
1414 | 18 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
1415 | 19 | |||
1416 | 20 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
1417 | 21 | |||
1418 | 22 | Note: Using this requires python-jinja2; if it is not installed, calling | ||
1419 | 23 | this will attempt to use charmhelpers.fetch.apt_install to install it. | ||
1420 | 24 | """ | ||
1421 | 25 | try: | ||
1422 | 26 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
1423 | 27 | except ImportError: | ||
1424 | 28 | try: | ||
1425 | 29 | from charmhelpers.fetch import apt_install | ||
1426 | 30 | except ImportError: | ||
1427 | 31 | hookenv.log('Could not import jinja2, and could not import ' | ||
1428 | 32 | 'charmhelpers.fetch to install it', | ||
1429 | 33 | level=hookenv.ERROR) | ||
1430 | 34 | raise | ||
1431 | 35 | apt_install('python-jinja2', fatal=True) | ||
1432 | 36 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
1433 | 37 | |||
1434 | 38 | if templates_dir is None: | ||
1435 | 39 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
1436 | 40 | loader = Environment(loader=FileSystemLoader(templates_dir)) | ||
1437 | 41 | try: | ||
1438 | 42 | source = source | ||
1439 | 43 | template = loader.get_template(source) | ||
1440 | 44 | except exceptions.TemplateNotFound as e: | ||
1441 | 45 | hookenv.log('Could not load template %s from %s.' % | ||
1442 | 46 | (source, templates_dir), | ||
1443 | 47 | level=hookenv.ERROR) | ||
1444 | 48 | raise e | ||
1445 | 49 | content = template.render(context) | ||
1446 | 50 | host.mkdir(os.path.dirname(target)) | ||
1447 | 51 | host.write_file(target, content, owner, group, perms) | ||
1448 | 0 | 52 | ||
1449 | === modified file 'hooks/charmhelpers/fetch/__init__.py' | |||
1450 | --- hooks/charmhelpers/fetch/__init__.py 2014-04-08 09:11:34 +0000 | |||
1451 | +++ hooks/charmhelpers/fetch/__init__.py 2014-10-29 02:58:49 +0000 | |||
1452 | @@ -1,4 +1,6 @@ | |||
1453 | 1 | import importlib | 1 | import importlib |
1454 | 2 | from tempfile import NamedTemporaryFile | ||
1455 | 3 | import time | ||
1456 | 2 | from yaml import safe_load | 4 | from yaml import safe_load |
1457 | 3 | from charmhelpers.core.host import ( | 5 | from charmhelpers.core.host import ( |
1458 | 4 | lsb_release | 6 | lsb_release |
1459 | @@ -12,9 +14,9 @@ | |||
1460 | 12 | config, | 14 | config, |
1461 | 13 | log, | 15 | log, |
1462 | 14 | ) | 16 | ) |
1463 | 15 | import apt_pkg | ||
1464 | 16 | import os | 17 | import os |
1465 | 17 | 18 | ||
1466 | 19 | |||
1467 | 18 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive | 20 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive |
1468 | 19 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main | 21 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main |
1469 | 20 | """ | 22 | """ |
1470 | @@ -54,13 +56,69 @@ | |||
1471 | 54 | 'icehouse/proposed': 'precise-proposed/icehouse', | 56 | 'icehouse/proposed': 'precise-proposed/icehouse', |
1472 | 55 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', | 57 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', |
1473 | 56 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', | 58 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', |
1474 | 59 | # Juno | ||
1475 | 60 | 'juno': 'trusty-updates/juno', | ||
1476 | 61 | 'trusty-juno': 'trusty-updates/juno', | ||
1477 | 62 | 'trusty-juno/updates': 'trusty-updates/juno', | ||
1478 | 63 | 'trusty-updates/juno': 'trusty-updates/juno', | ||
1479 | 64 | 'juno/proposed': 'trusty-proposed/juno', | ||
1480 | 65 | 'juno/proposed': 'trusty-proposed/juno', | ||
1481 | 66 | 'trusty-juno/proposed': 'trusty-proposed/juno', | ||
1482 | 67 | 'trusty-proposed/juno': 'trusty-proposed/juno', | ||
1483 | 57 | } | 68 | } |
1484 | 58 | 69 | ||
1485 | 70 | # The order of this list is very important. Handlers should be listed in from | ||
1486 | 71 | # least- to most-specific URL matching. | ||
1487 | 72 | FETCH_HANDLERS = ( | ||
1488 | 73 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
1489 | 74 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
1490 | 75 | 'charmhelpers.fetch.giturl.GitUrlFetchHandler', | ||
1491 | 76 | ) | ||
1492 | 77 | |||
1493 | 78 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. | ||
1494 | 79 | APT_NO_LOCK_RETRY_DELAY = 10 # Wait 10 seconds between apt lock checks. | ||
1495 | 80 | APT_NO_LOCK_RETRY_COUNT = 30 # Retry to acquire the lock X times. | ||
1496 | 81 | |||
1497 | 82 | |||
1498 | 83 | class SourceConfigError(Exception): | ||
1499 | 84 | pass | ||
1500 | 85 | |||
1501 | 86 | |||
1502 | 87 | class UnhandledSource(Exception): | ||
1503 | 88 | pass | ||
1504 | 89 | |||
1505 | 90 | |||
1506 | 91 | class AptLockError(Exception): | ||
1507 | 92 | pass | ||
1508 | 93 | |||
1509 | 94 | |||
1510 | 95 | class BaseFetchHandler(object): | ||
1511 | 96 | |||
1512 | 97 | """Base class for FetchHandler implementations in fetch plugins""" | ||
1513 | 98 | |||
1514 | 99 | def can_handle(self, source): | ||
1515 | 100 | """Returns True if the source can be handled. Otherwise returns | ||
1516 | 101 | a string explaining why it cannot""" | ||
1517 | 102 | return "Wrong source type" | ||
1518 | 103 | |||
1519 | 104 | def install(self, source): | ||
1520 | 105 | """Try to download and unpack the source. Return the path to the | ||
1521 | 106 | unpacked files or raise UnhandledSource.""" | ||
1522 | 107 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
1523 | 108 | |||
1524 | 109 | def parse_url(self, url): | ||
1525 | 110 | return urlparse(url) | ||
1526 | 111 | |||
1527 | 112 | def base_url(self, url): | ||
1528 | 113 | """Return url without querystring or fragment""" | ||
1529 | 114 | parts = list(self.parse_url(url)) | ||
1530 | 115 | parts[4:] = ['' for i in parts[4:]] | ||
1531 | 116 | return urlunparse(parts) | ||
1532 | 117 | |||
1533 | 59 | 118 | ||
1534 | 60 | def filter_installed_packages(packages): | 119 | def filter_installed_packages(packages): |
1535 | 61 | """Returns a list of packages that require installation""" | 120 | """Returns a list of packages that require installation""" |
1538 | 62 | apt_pkg.init() | 121 | cache = apt_cache() |
1537 | 63 | cache = apt_pkg.Cache() | ||
1539 | 64 | _pkgs = [] | 122 | _pkgs = [] |
1540 | 65 | for package in packages: | 123 | for package in packages: |
1541 | 66 | try: | 124 | try: |
1542 | @@ -73,6 +131,16 @@ | |||
1543 | 73 | return _pkgs | 131 | return _pkgs |
1544 | 74 | 132 | ||
1545 | 75 | 133 | ||
1546 | 134 | def apt_cache(in_memory=True): | ||
1547 | 135 | """Build and return an apt cache""" | ||
1548 | 136 | import apt_pkg | ||
1549 | 137 | apt_pkg.init() | ||
1550 | 138 | if in_memory: | ||
1551 | 139 | apt_pkg.config.set("Dir::Cache::pkgcache", "") | ||
1552 | 140 | apt_pkg.config.set("Dir::Cache::srcpkgcache", "") | ||
1553 | 141 | return apt_pkg.Cache() | ||
1554 | 142 | |||
1555 | 143 | |||
1556 | 76 | def apt_install(packages, options=None, fatal=False): | 144 | def apt_install(packages, options=None, fatal=False): |
1557 | 77 | """Install one or more packages""" | 145 | """Install one or more packages""" |
1558 | 78 | if options is None: | 146 | if options is None: |
1559 | @@ -87,14 +155,7 @@ | |||
1560 | 87 | cmd.extend(packages) | 155 | cmd.extend(packages) |
1561 | 88 | log("Installing {} with options: {}".format(packages, | 156 | log("Installing {} with options: {}".format(packages, |
1562 | 89 | options)) | 157 | options)) |
1571 | 90 | env = os.environ.copy() | 158 | _run_apt_command(cmd, fatal) |
1564 | 91 | if 'DEBIAN_FRONTEND' not in env: | ||
1565 | 92 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
1566 | 93 | |||
1567 | 94 | if fatal: | ||
1568 | 95 | subprocess.check_call(cmd, env=env) | ||
1569 | 96 | else: | ||
1570 | 97 | subprocess.call(cmd, env=env) | ||
1572 | 98 | 159 | ||
1573 | 99 | 160 | ||
1574 | 100 | def apt_upgrade(options=None, fatal=False, dist=False): | 161 | def apt_upgrade(options=None, fatal=False, dist=False): |
1575 | @@ -109,24 +170,13 @@ | |||
1576 | 109 | else: | 170 | else: |
1577 | 110 | cmd.append('upgrade') | 171 | cmd.append('upgrade') |
1578 | 111 | log("Upgrading with options: {}".format(options)) | 172 | log("Upgrading with options: {}".format(options)) |
1588 | 112 | 173 | _run_apt_command(cmd, fatal) | |
1580 | 113 | env = os.environ.copy() | ||
1581 | 114 | if 'DEBIAN_FRONTEND' not in env: | ||
1582 | 115 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
1583 | 116 | |||
1584 | 117 | if fatal: | ||
1585 | 118 | subprocess.check_call(cmd, env=env) | ||
1586 | 119 | else: | ||
1587 | 120 | subprocess.call(cmd, env=env) | ||
1589 | 121 | 174 | ||
1590 | 122 | 175 | ||
1591 | 123 | def apt_update(fatal=False): | 176 | def apt_update(fatal=False): |
1592 | 124 | """Update local apt cache""" | 177 | """Update local apt cache""" |
1593 | 125 | cmd = ['apt-get', 'update'] | 178 | cmd = ['apt-get', 'update'] |
1598 | 126 | if fatal: | 179 | _run_apt_command(cmd, fatal) |
1595 | 127 | subprocess.check_call(cmd) | ||
1596 | 128 | else: | ||
1597 | 129 | subprocess.call(cmd) | ||
1599 | 130 | 180 | ||
1600 | 131 | 181 | ||
1601 | 132 | def apt_purge(packages, fatal=False): | 182 | def apt_purge(packages, fatal=False): |
1602 | @@ -137,10 +187,7 @@ | |||
1603 | 137 | else: | 187 | else: |
1604 | 138 | cmd.extend(packages) | 188 | cmd.extend(packages) |
1605 | 139 | log("Purging {}".format(packages)) | 189 | log("Purging {}".format(packages)) |
1610 | 140 | if fatal: | 190 | _run_apt_command(cmd, fatal) |
1607 | 141 | subprocess.check_call(cmd) | ||
1608 | 142 | else: | ||
1609 | 143 | subprocess.call(cmd) | ||
1611 | 144 | 191 | ||
1612 | 145 | 192 | ||
1613 | 146 | def apt_hold(packages, fatal=False): | 193 | def apt_hold(packages, fatal=False): |
1614 | @@ -151,6 +198,7 @@ | |||
1615 | 151 | else: | 198 | else: |
1616 | 152 | cmd.extend(packages) | 199 | cmd.extend(packages) |
1617 | 153 | log("Holding {}".format(packages)) | 200 | log("Holding {}".format(packages)) |
1618 | 201 | |||
1619 | 154 | if fatal: | 202 | if fatal: |
1620 | 155 | subprocess.check_call(cmd) | 203 | subprocess.check_call(cmd) |
1621 | 156 | else: | 204 | else: |
1622 | @@ -158,6 +206,29 @@ | |||
1623 | 158 | 206 | ||
1624 | 159 | 207 | ||
1625 | 160 | def add_source(source, key=None): | 208 | def add_source(source, key=None): |
1626 | 209 | """Add a package source to this system. | ||
1627 | 210 | |||
1628 | 211 | @param source: a URL or sources.list entry, as supported by | ||
1629 | 212 | add-apt-repository(1). Examples:: | ||
1630 | 213 | |||
1631 | 214 | ppa:charmers/example | ||
1632 | 215 | deb https://stub:key@private.example.com/ubuntu trusty main | ||
1633 | 216 | |||
1634 | 217 | In addition: | ||
1635 | 218 | 'proposed:' may be used to enable the standard 'proposed' | ||
1636 | 219 | pocket for the release. | ||
1637 | 220 | 'cloud:' may be used to activate official cloud archive pockets, | ||
1638 | 221 | such as 'cloud:icehouse' | ||
1639 | 222 | 'distro' may be used as a noop | ||
1640 | 223 | |||
1641 | 224 | @param key: A key to be added to the system's APT keyring and used | ||
1642 | 225 | to verify the signatures on packages. Ideally, this should be an | ||
1643 | 226 | ASCII format GPG public key including the block headers. A GPG key | ||
1644 | 227 | id may also be used, but be aware that only insecure protocols are | ||
1645 | 228 | available to retrieve the actual public key from a public keyserver | ||
1646 | 229 | placing your Juju environment at risk. ppa and cloud archive keys | ||
1647 | 230 | are securely added automtically, so sould not be provided. | ||
1648 | 231 | """ | ||
1649 | 161 | if source is None: | 232 | if source is None: |
1650 | 162 | log('Source is not present. Skipping') | 233 | log('Source is not present. Skipping') |
1651 | 163 | return | 234 | return |
1652 | @@ -182,76 +253,98 @@ | |||
1653 | 182 | release = lsb_release()['DISTRIB_CODENAME'] | 253 | release = lsb_release()['DISTRIB_CODENAME'] |
1654 | 183 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: | 254 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: |
1655 | 184 | apt.write(PROPOSED_POCKET.format(release)) | 255 | apt.write(PROPOSED_POCKET.format(release)) |
1656 | 256 | elif source == 'distro': | ||
1657 | 257 | pass | ||
1658 | 258 | else: | ||
1659 | 259 | log("Unknown source: {!r}".format(source)) | ||
1660 | 260 | |||
1661 | 185 | if key: | 261 | if key: |
1669 | 186 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | 262 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: |
1670 | 187 | 'keyserver.ubuntu.com', '--recv', | 263 | with NamedTemporaryFile() as key_file: |
1671 | 188 | key]) | 264 | key_file.write(key) |
1672 | 189 | 265 | key_file.flush() | |
1673 | 190 | 266 | key_file.seek(0) | |
1674 | 191 | class SourceConfigError(Exception): | 267 | subprocess.check_call(['apt-key', 'add', '-'], stdin=key_file) |
1675 | 192 | pass | 268 | else: |
1676 | 269 | # Note that hkp: is in no way a secure protocol. Using a | ||
1677 | 270 | # GPG key id is pointless from a security POV unless you | ||
1678 | 271 | # absolutely trust your network and DNS. | ||
1679 | 272 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | ||
1680 | 273 | 'hkp://keyserver.ubuntu.com:80', '--recv', | ||
1681 | 274 | key]) | ||
1682 | 193 | 275 | ||
1683 | 194 | 276 | ||
1684 | 195 | def configure_sources(update=False, | 277 | def configure_sources(update=False, |
1685 | 196 | sources_var='install_sources', | 278 | sources_var='install_sources', |
1686 | 197 | keys_var='install_keys'): | 279 | keys_var='install_keys'): |
1687 | 198 | """ | 280 | """ |
1689 | 199 | Configure multiple sources from charm configuration | 281 | Configure multiple sources from charm configuration. |
1690 | 282 | |||
1691 | 283 | The lists are encoded as yaml fragments in the configuration. | ||
1692 | 284 | The frament needs to be included as a string. Sources and their | ||
1693 | 285 | corresponding keys are of the types supported by add_source(). | ||
1694 | 200 | 286 | ||
1695 | 201 | Example config: | 287 | Example config: |
1697 | 202 | install_sources: | 288 | install_sources: | |
1698 | 203 | - "ppa:foo" | 289 | - "ppa:foo" |
1699 | 204 | - "http://example.com/repo precise main" | 290 | - "http://example.com/repo precise main" |
1701 | 205 | install_keys: | 291 | install_keys: | |
1702 | 206 | - null | 292 | - null |
1703 | 207 | - "a1b2c3d4" | 293 | - "a1b2c3d4" |
1704 | 208 | 294 | ||
1705 | 209 | Note that 'null' (a.k.a. None) should not be quoted. | 295 | Note that 'null' (a.k.a. None) should not be quoted. |
1706 | 210 | """ | 296 | """ |
1714 | 211 | sources = safe_load(config(sources_var)) | 297 | sources = safe_load((config(sources_var) or '').strip()) or [] |
1715 | 212 | keys = config(keys_var) | 298 | keys = safe_load((config(keys_var) or '').strip()) or None |
1716 | 213 | if keys is not None: | 299 | |
1717 | 214 | keys = safe_load(keys) | 300 | if isinstance(sources, basestring): |
1718 | 215 | if isinstance(sources, basestring) and ( | 301 | sources = [sources] |
1719 | 216 | keys is None or isinstance(keys, basestring)): | 302 | |
1720 | 217 | add_source(sources, keys) | 303 | if keys is None: |
1721 | 304 | for source in sources: | ||
1722 | 305 | add_source(source, None) | ||
1723 | 218 | else: | 306 | else: |
1729 | 219 | if not len(sources) == len(keys): | 307 | if isinstance(keys, basestring): |
1730 | 220 | msg = 'Install sources and keys lists are different lengths' | 308 | keys = [keys] |
1731 | 221 | raise SourceConfigError(msg) | 309 | |
1732 | 222 | for src_num in range(len(sources)): | 310 | if len(sources) != len(keys): |
1733 | 223 | add_source(sources[src_num], keys[src_num]) | 311 | raise SourceConfigError( |
1734 | 312 | 'Install sources and keys lists are different lengths') | ||
1735 | 313 | for source, key in zip(sources, keys): | ||
1736 | 314 | add_source(source, key) | ||
1737 | 224 | if update: | 315 | if update: |
1738 | 225 | apt_update(fatal=True) | 316 | apt_update(fatal=True) |
1739 | 226 | 317 | ||
1753 | 227 | # The order of this list is very important. Handlers should be listed in from | 318 | |
1754 | 228 | # least- to most-specific URL matching. | 319 | def install_remote(source, *args, **kwargs): |
1742 | 229 | FETCH_HANDLERS = ( | ||
1743 | 230 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
1744 | 231 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
1745 | 232 | ) | ||
1746 | 233 | |||
1747 | 234 | |||
1748 | 235 | class UnhandledSource(Exception): | ||
1749 | 236 | pass | ||
1750 | 237 | |||
1751 | 238 | |||
1752 | 239 | def install_remote(source): | ||
1755 | 240 | """ | 320 | """ |
1756 | 241 | Install a file tree from a remote source | 321 | Install a file tree from a remote source |
1757 | 242 | 322 | ||
1758 | 243 | The specified source should be a url of the form: | 323 | The specified source should be a url of the form: |
1759 | 244 | scheme://[host]/path[#[option=value][&...]] | 324 | scheme://[host]/path[#[option=value][&...]] |
1760 | 245 | 325 | ||
1763 | 246 | Schemes supported are based on this modules submodules | 326 | Schemes supported are based on this modules submodules. |
1764 | 247 | Options supported are submodule-specific""" | 327 | Options supported are submodule-specific. |
1765 | 328 | Additional arguments are passed through to the submodule. | ||
1766 | 329 | |||
1767 | 330 | For example:: | ||
1768 | 331 | |||
1769 | 332 | dest = install_remote('http://example.com/archive.tgz', | ||
1770 | 333 | checksum='deadbeef', | ||
1771 | 334 | hash_type='sha1') | ||
1772 | 335 | |||
1773 | 336 | This will download `archive.tgz`, validate it using SHA1 and, if | ||
1774 | 337 | the file is ok, extract it and return the directory in which it | ||
1775 | 338 | was extracted. If the checksum fails, it will raise | ||
1776 | 339 | :class:`charmhelpers.core.host.ChecksumError`. | ||
1777 | 340 | """ | ||
1778 | 248 | # We ONLY check for True here because can_handle may return a string | 341 | # We ONLY check for True here because can_handle may return a string |
1779 | 249 | # explaining why it can't handle a given source. | 342 | # explaining why it can't handle a given source. |
1780 | 250 | handlers = [h for h in plugins() if h.can_handle(source) is True] | 343 | handlers = [h for h in plugins() if h.can_handle(source) is True] |
1781 | 251 | installed_to = None | 344 | installed_to = None |
1782 | 252 | for handler in handlers: | 345 | for handler in handlers: |
1783 | 253 | try: | 346 | try: |
1785 | 254 | installed_to = handler.install(source) | 347 | installed_to = handler.install(source, *args, **kwargs) |
1786 | 255 | except UnhandledSource: | 348 | except UnhandledSource: |
1787 | 256 | pass | 349 | pass |
1788 | 257 | if not installed_to: | 350 | if not installed_to: |
1789 | @@ -265,30 +358,6 @@ | |||
1790 | 265 | return install_remote(source) | 358 | return install_remote(source) |
1791 | 266 | 359 | ||
1792 | 267 | 360 | ||
1793 | 268 | class BaseFetchHandler(object): | ||
1794 | 269 | |||
1795 | 270 | """Base class for FetchHandler implementations in fetch plugins""" | ||
1796 | 271 | |||
1797 | 272 | def can_handle(self, source): | ||
1798 | 273 | """Returns True if the source can be handled. Otherwise returns | ||
1799 | 274 | a string explaining why it cannot""" | ||
1800 | 275 | return "Wrong source type" | ||
1801 | 276 | |||
1802 | 277 | def install(self, source): | ||
1803 | 278 | """Try to download and unpack the source. Return the path to the | ||
1804 | 279 | unpacked files or raise UnhandledSource.""" | ||
1805 | 280 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
1806 | 281 | |||
1807 | 282 | def parse_url(self, url): | ||
1808 | 283 | return urlparse(url) | ||
1809 | 284 | |||
1810 | 285 | def base_url(self, url): | ||
1811 | 286 | """Return url without querystring or fragment""" | ||
1812 | 287 | parts = list(self.parse_url(url)) | ||
1813 | 288 | parts[4:] = ['' for i in parts[4:]] | ||
1814 | 289 | return urlunparse(parts) | ||
1815 | 290 | |||
1816 | 291 | |||
1817 | 292 | def plugins(fetch_handlers=None): | 361 | def plugins(fetch_handlers=None): |
1818 | 293 | if not fetch_handlers: | 362 | if not fetch_handlers: |
1819 | 294 | fetch_handlers = FETCH_HANDLERS | 363 | fetch_handlers = FETCH_HANDLERS |
1820 | @@ -306,3 +375,40 @@ | |||
1821 | 306 | log("FetchHandler {} not found, skipping plugin".format( | 375 | log("FetchHandler {} not found, skipping plugin".format( |
1822 | 307 | handler_name)) | 376 | handler_name)) |
1823 | 308 | return plugin_list | 377 | return plugin_list |
1824 | 378 | |||
1825 | 379 | |||
1826 | 380 | def _run_apt_command(cmd, fatal=False): | ||
1827 | 381 | """ | ||
1828 | 382 | Run an APT command, checking output and retrying if the fatal flag is set | ||
1829 | 383 | to True. | ||
1830 | 384 | |||
1831 | 385 | :param: cmd: str: The apt command to run. | ||
1832 | 386 | :param: fatal: bool: Whether the command's output should be checked and | ||
1833 | 387 | retried. | ||
1834 | 388 | """ | ||
1835 | 389 | env = os.environ.copy() | ||
1836 | 390 | |||
1837 | 391 | if 'DEBIAN_FRONTEND' not in env: | ||
1838 | 392 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
1839 | 393 | |||
1840 | 394 | if fatal: | ||
1841 | 395 | retry_count = 0 | ||
1842 | 396 | result = None | ||
1843 | 397 | |||
1844 | 398 | # If the command is considered "fatal", we need to retry if the apt | ||
1845 | 399 | # lock was not acquired. | ||
1846 | 400 | |||
1847 | 401 | while result is None or result == APT_NO_LOCK: | ||
1848 | 402 | try: | ||
1849 | 403 | result = subprocess.check_call(cmd, env=env) | ||
1850 | 404 | except subprocess.CalledProcessError, e: | ||
1851 | 405 | retry_count = retry_count + 1 | ||
1852 | 406 | if retry_count > APT_NO_LOCK_RETRY_COUNT: | ||
1853 | 407 | raise | ||
1854 | 408 | result = e.returncode | ||
1855 | 409 | log("Couldn't acquire DPKG lock. Will retry in {} seconds." | ||
1856 | 410 | "".format(APT_NO_LOCK_RETRY_DELAY)) | ||
1857 | 411 | time.sleep(APT_NO_LOCK_RETRY_DELAY) | ||
1858 | 412 | |||
1859 | 413 | else: | ||
1860 | 414 | subprocess.call(cmd, env=env) | ||
1861 | 309 | 415 | ||
1862 | === modified file 'hooks/charmhelpers/fetch/archiveurl.py' | |||
1863 | --- hooks/charmhelpers/fetch/archiveurl.py 2014-04-08 09:11:34 +0000 | |||
1864 | +++ hooks/charmhelpers/fetch/archiveurl.py 2014-10-29 02:58:49 +0000 | |||
1865 | @@ -1,6 +1,8 @@ | |||
1866 | 1 | import os | 1 | import os |
1867 | 2 | import urllib2 | 2 | import urllib2 |
1868 | 3 | from urllib import urlretrieve | ||
1869 | 3 | import urlparse | 4 | import urlparse |
1870 | 5 | import hashlib | ||
1871 | 4 | 6 | ||
1872 | 5 | from charmhelpers.fetch import ( | 7 | from charmhelpers.fetch import ( |
1873 | 6 | BaseFetchHandler, | 8 | BaseFetchHandler, |
1874 | @@ -10,11 +12,19 @@ | |||
1875 | 10 | get_archive_handler, | 12 | get_archive_handler, |
1876 | 11 | extract, | 13 | extract, |
1877 | 12 | ) | 14 | ) |
1879 | 13 | from charmhelpers.core.host import mkdir | 15 | from charmhelpers.core.host import mkdir, check_hash |
1880 | 14 | 16 | ||
1881 | 15 | 17 | ||
1882 | 16 | class ArchiveUrlFetchHandler(BaseFetchHandler): | 18 | class ArchiveUrlFetchHandler(BaseFetchHandler): |
1884 | 17 | """Handler for archives via generic URLs""" | 19 | """ |
1885 | 20 | Handler to download archive files from arbitrary URLs. | ||
1886 | 21 | |||
1887 | 22 | Can fetch from http, https, ftp, and file URLs. | ||
1888 | 23 | |||
1889 | 24 | Can install either tarballs (.tar, .tgz, .tbz2, etc) or zip files. | ||
1890 | 25 | |||
1891 | 26 | Installs the contents of the archive in $CHARM_DIR/fetched/. | ||
1892 | 27 | """ | ||
1893 | 18 | def can_handle(self, source): | 28 | def can_handle(self, source): |
1894 | 19 | url_parts = self.parse_url(source) | 29 | url_parts = self.parse_url(source) |
1895 | 20 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): | 30 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): |
1896 | @@ -24,6 +34,12 @@ | |||
1897 | 24 | return False | 34 | return False |
1898 | 25 | 35 | ||
1899 | 26 | def download(self, source, dest): | 36 | def download(self, source, dest): |
1900 | 37 | """ | ||
1901 | 38 | Download an archive file. | ||
1902 | 39 | |||
1903 | 40 | :param str source: URL pointing to an archive file. | ||
1904 | 41 | :param str dest: Local path location to download archive file to. | ||
1905 | 42 | """ | ||
1906 | 27 | # propogate all exceptions | 43 | # propogate all exceptions |
1907 | 28 | # URLError, OSError, etc | 44 | # URLError, OSError, etc |
1908 | 29 | proto, netloc, path, params, query, fragment = urlparse.urlparse(source) | 45 | proto, netloc, path, params, query, fragment = urlparse.urlparse(source) |
1909 | @@ -48,7 +64,30 @@ | |||
1910 | 48 | os.unlink(dest) | 64 | os.unlink(dest) |
1911 | 49 | raise e | 65 | raise e |
1912 | 50 | 66 | ||
1914 | 51 | def install(self, source): | 67 | # Mandatory file validation via Sha1 or MD5 hashing. |
1915 | 68 | def download_and_validate(self, url, hashsum, validate="sha1"): | ||
1916 | 69 | tempfile, headers = urlretrieve(url) | ||
1917 | 70 | check_hash(tempfile, hashsum, validate) | ||
1918 | 71 | return tempfile | ||
1919 | 72 | |||
1920 | 73 | def install(self, source, dest=None, checksum=None, hash_type='sha1'): | ||
1921 | 74 | """ | ||
1922 | 75 | Download and install an archive file, with optional checksum validation. | ||
1923 | 76 | |||
1924 | 77 | The checksum can also be given on the `source` URL's fragment. | ||
1925 | 78 | For example:: | ||
1926 | 79 | |||
1927 | 80 | handler.install('http://example.com/file.tgz#sha1=deadbeef') | ||
1928 | 81 | |||
1929 | 82 | :param str source: URL pointing to an archive file. | ||
1930 | 83 | :param str dest: Local destination path to install to. If not given, | ||
1931 | 84 | installs to `$CHARM_DIR/archives/archive_file_name`. | ||
1932 | 85 | :param str checksum: If given, validate the archive file after download. | ||
1933 | 86 | :param str hash_type: Algorithm used to generate `checksum`. | ||
1934 | 87 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
1935 | 88 | such as md5, sha1, sha256, sha512, etc. | ||
1936 | 89 | |||
1937 | 90 | """ | ||
1938 | 52 | url_parts = self.parse_url(source) | 91 | url_parts = self.parse_url(source) |
1939 | 53 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') | 92 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') |
1940 | 54 | if not os.path.exists(dest_dir): | 93 | if not os.path.exists(dest_dir): |
1941 | @@ -60,4 +99,10 @@ | |||
1942 | 60 | raise UnhandledSource(e.reason) | 99 | raise UnhandledSource(e.reason) |
1943 | 61 | except OSError as e: | 100 | except OSError as e: |
1944 | 62 | raise UnhandledSource(e.strerror) | 101 | raise UnhandledSource(e.strerror) |
1946 | 63 | return extract(dld_file) | 102 | options = urlparse.parse_qs(url_parts.fragment) |
1947 | 103 | for key, value in options.items(): | ||
1948 | 104 | if key in hashlib.algorithms: | ||
1949 | 105 | check_hash(dld_file, value, key) | ||
1950 | 106 | if checksum: | ||
1951 | 107 | check_hash(dld_file, checksum, hash_type) | ||
1952 | 108 | return extract(dld_file, dest) | ||
1953 | 64 | 109 | ||
1954 | === modified file 'hooks/charmhelpers/fetch/bzrurl.py' | |||
1955 | --- hooks/charmhelpers/fetch/bzrurl.py 2014-02-06 12:54:59 +0000 | |||
1956 | +++ hooks/charmhelpers/fetch/bzrurl.py 2014-10-29 02:58:49 +0000 | |||
1957 | @@ -39,7 +39,8 @@ | |||
1958 | 39 | def install(self, source): | 39 | def install(self, source): |
1959 | 40 | url_parts = self.parse_url(source) | 40 | url_parts = self.parse_url(source) |
1960 | 41 | branch_name = url_parts.path.strip("/").split("/")[-1] | 41 | branch_name = url_parts.path.strip("/").split("/")[-1] |
1962 | 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", |
1963 | 43 | branch_name) | ||
1964 | 43 | if not os.path.exists(dest_dir): | 44 | if not os.path.exists(dest_dir): |
1965 | 44 | mkdir(dest_dir, perms=0755) | 45 | mkdir(dest_dir, perms=0755) |
1966 | 45 | try: | 46 | try: |
1967 | 46 | 47 | ||
1968 | === added file 'hooks/charmhelpers/fetch/giturl.py' | |||
1969 | --- hooks/charmhelpers/fetch/giturl.py 1970-01-01 00:00:00 +0000 | |||
1970 | +++ hooks/charmhelpers/fetch/giturl.py 2014-10-29 02:58:49 +0000 | |||
1971 | @@ -0,0 +1,44 @@ | |||
1972 | 1 | import os | ||
1973 | 2 | from charmhelpers.fetch import ( | ||
1974 | 3 | BaseFetchHandler, | ||
1975 | 4 | UnhandledSource | ||
1976 | 5 | ) | ||
1977 | 6 | from charmhelpers.core.host import mkdir | ||
1978 | 7 | |||
1979 | 8 | try: | ||
1980 | 9 | from git import Repo | ||
1981 | 10 | except ImportError: | ||
1982 | 11 | from charmhelpers.fetch import apt_install | ||
1983 | 12 | apt_install("python-git") | ||
1984 | 13 | from git import Repo | ||
1985 | 14 | |||
1986 | 15 | |||
1987 | 16 | class GitUrlFetchHandler(BaseFetchHandler): | ||
1988 | 17 | """Handler for git branches via generic and github URLs""" | ||
1989 | 18 | def can_handle(self, source): | ||
1990 | 19 | url_parts = self.parse_url(source) | ||
1991 | 20 | #TODO (mattyw) no support for ssh git@ yet | ||
1992 | 21 | if url_parts.scheme not in ('http', 'https', 'git'): | ||
1993 | 22 | return False | ||
1994 | 23 | else: | ||
1995 | 24 | return True | ||
1996 | 25 | |||
1997 | 26 | def clone(self, source, dest, branch): | ||
1998 | 27 | if not self.can_handle(source): | ||
1999 | 28 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
2000 | 29 | |||
2001 | 30 | repo = Repo.clone_from(source, dest) | ||
2002 | 31 | repo.git.checkout(branch) | ||
2003 | 32 | |||
2004 | 33 | def install(self, source, branch="master"): | ||
2005 | 34 | url_parts = self.parse_url(source) | ||
2006 | 35 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
2007 | 36 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
2008 | 37 | branch_name) | ||
2009 | 38 | if not os.path.exists(dest_dir): | ||
2010 | 39 | mkdir(dest_dir, perms=0755) | ||
2011 | 40 | try: | ||
2012 | 41 | self.clone(source, dest_dir, branch) | ||
2013 | 42 | except OSError as e: | ||
2014 | 43 | raise UnhandledSource(e.strerror) | ||
2015 | 44 | return dest_dir | ||
2016 | 0 | 45 | ||
2017 | === modified file 'hooks/hooks.py' | |||
2018 | --- hooks/hooks.py 2014-07-08 09:18:18 +0000 | |||
2019 | +++ hooks/hooks.py 2014-10-29 02:58:49 +0000 | |||
2020 | @@ -13,6 +13,7 @@ | |||
2021 | 13 | 'config-changed', | 13 | 'config-changed', |
2022 | 14 | 'cluster-relation-joined', | 14 | 'cluster-relation-joined', |
2023 | 15 | 'peer-relation-joined', | 15 | 'peer-relation-joined', |
2024 | 16 | 'peer-relation-departed', | ||
2025 | 16 | 'nrpe-external-master-relation-changed', | 17 | 'nrpe-external-master-relation-changed', |
2026 | 17 | 'rest-relation-joined', | 18 | 'rest-relation-joined', |
2027 | 18 | 'start', | 19 | 'start', |
2028 | 19 | 20 | ||
2029 | === added symlink 'hooks/peer-relation-departed' | |||
2030 | === target is u'hooks.py' | |||
2031 | === modified file 'playbook.yaml' | |||
2032 | --- playbook.yaml 2014-08-19 16:47:21 +0000 | |||
2033 | +++ playbook.yaml 2014-10-29 02:58:49 +0000 | |||
2034 | @@ -13,17 +13,20 @@ | |||
2035 | 13 | vars: | 13 | vars: |
2036 | 14 | - service_name: "{{ local_unit.split('/')[0] }}" | 14 | - service_name: "{{ local_unit.split('/')[0] }}" |
2037 | 15 | - client_relation_id: "{{ relations['client'].keys()[0] | default('') }}" | 15 | - client_relation_id: "{{ relations['client'].keys()[0] | default('') }}" |
2038 | 16 | - peer_relation_id: "{{ relations['peer'].keys()[0] | default('') }}" | ||
2039 | 16 | 17 | ||
2040 | 17 | tasks: | 18 | tasks: |
2041 | 18 | 19 | ||
2042 | 19 | - include: tasks/install-elasticsearch.yml | 20 | - include: tasks/install-elasticsearch.yml |
2043 | 21 | - include: tasks/peer-relations.yml | ||
2044 | 20 | - include: tasks/setup-ufw.yml | 22 | - include: tasks/setup-ufw.yml |
2045 | 21 | tags: | 23 | tags: |
2046 | 22 | - install | 24 | - install |
2047 | 23 | - upgrade-charm | 25 | - upgrade-charm |
2048 | 24 | - client-relation-joined | 26 | - client-relation-joined |
2049 | 25 | - client-relation-departed | 27 | - client-relation-departed |
2051 | 26 | - include: tasks/peer-relations.yml | 28 | - peer-relation-joined |
2052 | 29 | - peer-relation-departed | ||
2053 | 27 | 30 | ||
2054 | 28 | - name: Update configuration | 31 | - name: Update configuration |
2055 | 29 | tags: | 32 | tags: |
2056 | 30 | 33 | ||
2057 | === modified file 'tasks/peer-relations.yml' | |||
2058 | --- tasks/peer-relations.yml 2014-06-06 14:40:08 +0000 | |||
2059 | +++ tasks/peer-relations.yml 2014-10-29 02:58:49 +0000 | |||
2060 | @@ -54,4 +54,3 @@ | |||
2061 | 54 | - peer-relation-joined | 54 | - peer-relation-joined |
2062 | 55 | fail: msg="Unit failed to join cluster during peer-relation-joined" | 55 | fail: msg="Unit failed to join cluster during peer-relation-joined" |
2063 | 56 | when: cluster_health.json.number_of_nodes == 1 and cluster_health_after_restart.json.number_of_nodes == 1 | 56 | when: cluster_health.json.number_of_nodes == 1 and cluster_health_after_restart.json.number_of_nodes == 1 |
2064 | 57 | |||
2065 | 58 | 57 | ||
2066 | === modified file 'tasks/setup-ufw.yml' | |||
2067 | --- tasks/setup-ufw.yml 2014-07-30 06:35:59 +0000 | |||
2068 | +++ tasks/setup-ufw.yml 2014-10-29 02:58:49 +0000 | |||
2069 | @@ -27,3 +27,14 @@ | |||
2070 | 27 | 27 | ||
2071 | 28 | - name: Deny all other requests on 9200 | 28 | - name: Deny all other requests on 9200 |
2072 | 29 | ufw: rule=deny port=9200 | 29 | ufw: rule=deny port=9200 |
2073 | 30 | |||
2074 | 31 | - name: Open the firewall for all peers | ||
2075 | 32 | ufw: rule=allow src={{ item.value['private-address'] }} port=9300 proto=tcp | ||
2076 | 33 | with_dict: relations["peer"]["{{ peer_relation_id }}"] | default({}) | ||
2077 | 34 | when: not item.key == local_unit | ||
2078 | 35 | |||
2079 | 36 | # Only deny incoming on 9300 once the unit is part of a cluster. | ||
2080 | 37 | - name: Deny all incoming requests on 9300 once unit is part of cluster | ||
2081 | 38 | ufw: rule=deny port=9300 | ||
2082 | 39 | when: not peer_relation_id == "" | ||
2083 | 40 |