Merge lp:~hopem/charms/trusty/jenkins/python-redux into lp:charms/trusty/jenkins
- Trusty Tahr (14.04)
- python-redux
- Merge into trunk
Status: | Superseded |
---|---|
Proposed branch: | lp:~hopem/charms/trusty/jenkins/python-redux |
Merge into: | lp:charms/trusty/jenkins |
Diff against target: |
3754 lines (+3253/-274) 38 files modified
Makefile (+30/-0) bin/charm_helpers_sync.py (+225/-0) charm-helpers-hooks.yaml (+7/-0) config.yaml (+1/-1) hooks/addnode (+0/-21) hooks/charmhelpers/__init__.py (+22/-0) hooks/charmhelpers/core/decorators.py (+41/-0) hooks/charmhelpers/core/fstab.py (+118/-0) hooks/charmhelpers/core/hookenv.py (+552/-0) hooks/charmhelpers/core/host.py (+419/-0) hooks/charmhelpers/core/services/__init__.py (+2/-0) hooks/charmhelpers/core/services/base.py (+313/-0) hooks/charmhelpers/core/services/helpers.py (+243/-0) hooks/charmhelpers/core/sysctl.py (+34/-0) hooks/charmhelpers/core/templating.py (+52/-0) hooks/charmhelpers/fetch/__init__.py (+423/-0) hooks/charmhelpers/fetch/archiveurl.py (+145/-0) hooks/charmhelpers/fetch/bzrurl.py (+54/-0) hooks/charmhelpers/fetch/giturl.py (+51/-0) hooks/charmhelpers/payload/__init__.py (+1/-0) hooks/charmhelpers/payload/execd.py (+50/-0) hooks/config-changed (+0/-7) hooks/delnode (+0/-16) hooks/install (+0/-151) hooks/jenkins_hooks.py (+220/-0) hooks/jenkins_utils.py (+178/-0) hooks/master-relation-broken (+0/-17) hooks/master-relation-changed (+0/-24) hooks/master-relation-departed (+0/-12) hooks/master-relation-joined (+0/-5) hooks/start (+0/-3) hooks/stop (+0/-3) hooks/upgrade-charm (+0/-7) hooks/website-relation-joined (+0/-5) tests/100-deploy-trusty (+4/-2) tests/README (+56/-0) unit_tests/test_jenkins_hooks.py (+6/-0) unit_tests/test_jenkins_utils.py (+6/-0) |
To merge this branch: | bzr merge lp:~hopem/charms/trusty/jenkins/python-redux |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Whit Morriss (community) | Needs Fixing | ||
Review Queue (community) | automated testing | Needs Fixing | |
Ryan Beisner | Pending | ||
Felipe Reyes | Pending | ||
Paul Larson | Pending | ||
Jorge Niedbalski | Pending | ||
James Page | Pending | ||
Review via email: mp+245769@code.launchpad.net |
This proposal supersedes a proposal from 2014-12-12.
This proposal has been superseded by a proposal from 2015-01-20.
Commit message
Description of the change
Review Queue (review-queue) wrote : Posted in a previous version of this proposal | # |
Felipe Reyes (freyes) wrote : Posted in a previous version of this proposal | # |
Setting the password doesn't work, deploying as below doesn't allow you to login with admin/admin. Also when first deploying from the charm store and then upgrading to this branch breaks the password.
---
jenkins:
password: "admin"
---
$ juju deploy --config config.yaml local:trusty/
Edward Hope-Morley (hopem) wrote : Posted in a previous version of this proposal | # |
Thanks Felipe, taking a look.
Review Queue (review-queue) wrote : Posted in a previous version of this proposal | # |
This items has failed automated testing! Results available here http://
Review Queue (review-queue) wrote : Posted in a previous version of this proposal | # |
This items has failed automated testing! Results available here http://
Review Queue (review-queue) wrote : Posted in a previous version of this proposal | # |
This items has failed automated testing! Results available here http://
Review Queue (review-queue) wrote : Posted in a previous version of this proposal | # |
This items has failed automated testing! Results available here http://
Review Queue (review-queue) wrote : | # |
This items has failed automated testing! Results available here http://
Whit Morriss (whitmo) wrote : | # |
Thanks Edward, your python rewrite generally looks good at a glance.
I confirmed the test failures reported by automated testing: jenkins-slave is not being found because it is in the precise series only.
Changing test/100-
The tests also hit an error in "master-
I confirmed this as an issue in the merge targets bash implementation also. Adding some retry logic to add_node should fix this issues.
-1 for test fixes, but otherwise looks good. Thanks again!
Edward Hope-Morley (hopem) wrote : | # |
@whitmo awesome, thanks for reviewing. I'll see if I can improve the add_node issue and I'll get the amulet test fixed up. Thanks!
- 48. By Edward Hope-Morley
-
fix amulet test
- 49. By Edward Hope-Morley
-
synced charmhelpers
- 50. By Edward Hope-Morley
-
allow retries when adding node
- 51. By Edward Hope-Morley
-
* Fixed Makefile amulet test filename
* Synced charm-helpers python-six deps
* Synced charm-helpers test deps - 52. By Edward Hope-Morley
-
added precise and trusty amulet
- 53. By Edward Hope-Morley
-
switch makefile rules to names that juju ci (hopefully) understands
- 54. By Edward Hope-Morley
-
ensure apt update prior to install
- 55. By Edward Hope-Morley
-
added venv for tests and lint
Unmerged revisions
Preview Diff
1 | === added file 'Makefile' | |||
2 | --- Makefile 1970-01-01 00:00:00 +0000 | |||
3 | +++ Makefile 2015-01-20 18:33:44 +0000 | |||
4 | @@ -0,0 +1,30 @@ | |||
5 | 1 | #!/usr/bin/make | ||
6 | 2 | PYTHON := /usr/bin/env python | ||
7 | 3 | |||
8 | 4 | lint: | ||
9 | 5 | @flake8 --exclude hooks/charmhelpers hooks unit_tests tests | ||
10 | 6 | @charm proof | ||
11 | 7 | |||
12 | 8 | test: | ||
13 | 9 | @echo Starting Amulet tests... | ||
14 | 10 | # coreycb note: The -v should only be temporary until Amulet sends | ||
15 | 11 | # raise_status() messages to stderr: | ||
16 | 12 | # https://bugs.launchpad.net/amulet/+bug/1320357 | ||
17 | 13 | @juju test -v -p AMULET_HTTP_PROXY --timeout 900 \ | ||
18 | 14 | 00-setup 100-deploy | ||
19 | 15 | |||
20 | 16 | unit_test: | ||
21 | 17 | @echo Starting unit tests... | ||
22 | 18 | @$(PYTHON) /usr/bin/nosetests --nologcapture --with-coverage unit_tests | ||
23 | 19 | |||
24 | 20 | bin/charm_helpers_sync.py: | ||
25 | 21 | @mkdir -p bin | ||
26 | 22 | @bzr cat lp:charm-helpers/tools/charm_helpers_sync/charm_helpers_sync.py \ | ||
27 | 23 | > bin/charm_helpers_sync.py | ||
28 | 24 | |||
29 | 25 | sync: bin/charm_helpers_sync.py | ||
30 | 26 | @$(PYTHON) bin/charm_helpers_sync.py -c charm-helpers-hooks.yaml | ||
31 | 27 | |||
32 | 28 | publish: lint unit_test | ||
33 | 29 | bzr push lp:charms/jenkins | ||
34 | 30 | bzr push lp:charms/trusty/jenkins | ||
35 | 0 | 31 | ||
36 | === added directory 'bin' | |||
37 | === added file 'bin/charm_helpers_sync.py' | |||
38 | --- bin/charm_helpers_sync.py 1970-01-01 00:00:00 +0000 | |||
39 | +++ bin/charm_helpers_sync.py 2015-01-20 18:33:44 +0000 | |||
40 | @@ -0,0 +1,225 @@ | |||
41 | 1 | #!/usr/bin/python | ||
42 | 2 | # | ||
43 | 3 | # Copyright 2013 Canonical Ltd. | ||
44 | 4 | |||
45 | 5 | # Authors: | ||
46 | 6 | # Adam Gandelman <adamg@ubuntu.com> | ||
47 | 7 | # | ||
48 | 8 | |||
49 | 9 | import logging | ||
50 | 10 | import optparse | ||
51 | 11 | import os | ||
52 | 12 | import subprocess | ||
53 | 13 | import shutil | ||
54 | 14 | import sys | ||
55 | 15 | import tempfile | ||
56 | 16 | import yaml | ||
57 | 17 | |||
58 | 18 | from fnmatch import fnmatch | ||
59 | 19 | |||
60 | 20 | CHARM_HELPERS_BRANCH = 'lp:charm-helpers' | ||
61 | 21 | |||
62 | 22 | |||
63 | 23 | def parse_config(conf_file): | ||
64 | 24 | if not os.path.isfile(conf_file): | ||
65 | 25 | logging.error('Invalid config file: %s.' % conf_file) | ||
66 | 26 | return False | ||
67 | 27 | return yaml.load(open(conf_file).read()) | ||
68 | 28 | |||
69 | 29 | |||
70 | 30 | def clone_helpers(work_dir, branch): | ||
71 | 31 | dest = os.path.join(work_dir, 'charm-helpers') | ||
72 | 32 | logging.info('Checking out %s to %s.' % (branch, dest)) | ||
73 | 33 | cmd = ['bzr', 'checkout', '--lightweight', branch, dest] | ||
74 | 34 | subprocess.check_call(cmd) | ||
75 | 35 | return dest | ||
76 | 36 | |||
77 | 37 | |||
78 | 38 | def _module_path(module): | ||
79 | 39 | return os.path.join(*module.split('.')) | ||
80 | 40 | |||
81 | 41 | |||
82 | 42 | def _src_path(src, module): | ||
83 | 43 | return os.path.join(src, 'charmhelpers', _module_path(module)) | ||
84 | 44 | |||
85 | 45 | |||
86 | 46 | def _dest_path(dest, module): | ||
87 | 47 | return os.path.join(dest, _module_path(module)) | ||
88 | 48 | |||
89 | 49 | |||
90 | 50 | def _is_pyfile(path): | ||
91 | 51 | return os.path.isfile(path + '.py') | ||
92 | 52 | |||
93 | 53 | |||
94 | 54 | def ensure_init(path): | ||
95 | 55 | ''' | ||
96 | 56 | ensure directories leading up to path are importable, omitting | ||
97 | 57 | parent directory, eg path='/hooks/helpers/foo'/: | ||
98 | 58 | hooks/ | ||
99 | 59 | hooks/helpers/__init__.py | ||
100 | 60 | hooks/helpers/foo/__init__.py | ||
101 | 61 | ''' | ||
102 | 62 | for d, dirs, files in os.walk(os.path.join(*path.split('/')[:2])): | ||
103 | 63 | _i = os.path.join(d, '__init__.py') | ||
104 | 64 | if not os.path.exists(_i): | ||
105 | 65 | logging.info('Adding missing __init__.py: %s' % _i) | ||
106 | 66 | open(_i, 'wb').close() | ||
107 | 67 | |||
108 | 68 | |||
109 | 69 | def sync_pyfile(src, dest): | ||
110 | 70 | src = src + '.py' | ||
111 | 71 | src_dir = os.path.dirname(src) | ||
112 | 72 | logging.info('Syncing pyfile: %s -> %s.' % (src, dest)) | ||
113 | 73 | if not os.path.exists(dest): | ||
114 | 74 | os.makedirs(dest) | ||
115 | 75 | shutil.copy(src, dest) | ||
116 | 76 | if os.path.isfile(os.path.join(src_dir, '__init__.py')): | ||
117 | 77 | shutil.copy(os.path.join(src_dir, '__init__.py'), | ||
118 | 78 | dest) | ||
119 | 79 | ensure_init(dest) | ||
120 | 80 | |||
121 | 81 | |||
122 | 82 | def get_filter(opts=None): | ||
123 | 83 | opts = opts or [] | ||
124 | 84 | if 'inc=*' in opts: | ||
125 | 85 | # do not filter any files, include everything | ||
126 | 86 | return None | ||
127 | 87 | |||
128 | 88 | def _filter(dir, ls): | ||
129 | 89 | incs = [opt.split('=').pop() for opt in opts if 'inc=' in opt] | ||
130 | 90 | _filter = [] | ||
131 | 91 | for f in ls: | ||
132 | 92 | _f = os.path.join(dir, f) | ||
133 | 93 | |||
134 | 94 | if not os.path.isdir(_f) and not _f.endswith('.py') and incs: | ||
135 | 95 | if True not in [fnmatch(_f, inc) for inc in incs]: | ||
136 | 96 | logging.debug('Not syncing %s, does not match include ' | ||
137 | 97 | 'filters (%s)' % (_f, incs)) | ||
138 | 98 | _filter.append(f) | ||
139 | 99 | else: | ||
140 | 100 | logging.debug('Including file, which matches include ' | ||
141 | 101 | 'filters (%s): %s' % (incs, _f)) | ||
142 | 102 | elif (os.path.isfile(_f) and not _f.endswith('.py')): | ||
143 | 103 | logging.debug('Not syncing file: %s' % f) | ||
144 | 104 | _filter.append(f) | ||
145 | 105 | elif (os.path.isdir(_f) and not | ||
146 | 106 | os.path.isfile(os.path.join(_f, '__init__.py'))): | ||
147 | 107 | logging.debug('Not syncing directory: %s' % f) | ||
148 | 108 | _filter.append(f) | ||
149 | 109 | return _filter | ||
150 | 110 | return _filter | ||
151 | 111 | |||
152 | 112 | |||
153 | 113 | def sync_directory(src, dest, opts=None): | ||
154 | 114 | if os.path.exists(dest): | ||
155 | 115 | logging.debug('Removing existing directory: %s' % dest) | ||
156 | 116 | shutil.rmtree(dest) | ||
157 | 117 | logging.info('Syncing directory: %s -> %s.' % (src, dest)) | ||
158 | 118 | |||
159 | 119 | shutil.copytree(src, dest, ignore=get_filter(opts)) | ||
160 | 120 | ensure_init(dest) | ||
161 | 121 | |||
162 | 122 | |||
163 | 123 | def sync(src, dest, module, opts=None): | ||
164 | 124 | if os.path.isdir(_src_path(src, module)): | ||
165 | 125 | sync_directory(_src_path(src, module), _dest_path(dest, module), opts) | ||
166 | 126 | elif _is_pyfile(_src_path(src, module)): | ||
167 | 127 | sync_pyfile(_src_path(src, module), | ||
168 | 128 | os.path.dirname(_dest_path(dest, module))) | ||
169 | 129 | else: | ||
170 | 130 | logging.warn('Could not sync: %s. Neither a pyfile or directory, ' | ||
171 | 131 | 'does it even exist?' % module) | ||
172 | 132 | |||
173 | 133 | |||
174 | 134 | def parse_sync_options(options): | ||
175 | 135 | if not options: | ||
176 | 136 | return [] | ||
177 | 137 | return options.split(',') | ||
178 | 138 | |||
179 | 139 | |||
180 | 140 | def extract_options(inc, global_options=None): | ||
181 | 141 | global_options = global_options or [] | ||
182 | 142 | if global_options and isinstance(global_options, basestring): | ||
183 | 143 | global_options = [global_options] | ||
184 | 144 | if '|' not in inc: | ||
185 | 145 | return (inc, global_options) | ||
186 | 146 | inc, opts = inc.split('|') | ||
187 | 147 | return (inc, parse_sync_options(opts) + global_options) | ||
188 | 148 | |||
189 | 149 | |||
190 | 150 | def sync_helpers(include, src, dest, options=None): | ||
191 | 151 | if not os.path.isdir(dest): | ||
192 | 152 | os.makedirs(dest) | ||
193 | 153 | |||
194 | 154 | global_options = parse_sync_options(options) | ||
195 | 155 | |||
196 | 156 | for inc in include: | ||
197 | 157 | if isinstance(inc, str): | ||
198 | 158 | inc, opts = extract_options(inc, global_options) | ||
199 | 159 | sync(src, dest, inc, opts) | ||
200 | 160 | elif isinstance(inc, dict): | ||
201 | 161 | # could also do nested dicts here. | ||
202 | 162 | for k, v in inc.iteritems(): | ||
203 | 163 | if isinstance(v, list): | ||
204 | 164 | for m in v: | ||
205 | 165 | inc, opts = extract_options(m, global_options) | ||
206 | 166 | sync(src, dest, '%s.%s' % (k, inc), opts) | ||
207 | 167 | |||
208 | 168 | if __name__ == '__main__': | ||
209 | 169 | parser = optparse.OptionParser() | ||
210 | 170 | parser.add_option('-c', '--config', action='store', dest='config', | ||
211 | 171 | default=None, help='helper config file') | ||
212 | 172 | parser.add_option('-D', '--debug', action='store_true', dest='debug', | ||
213 | 173 | default=False, help='debug') | ||
214 | 174 | parser.add_option('-b', '--branch', action='store', dest='branch', | ||
215 | 175 | help='charm-helpers bzr branch (overrides config)') | ||
216 | 176 | parser.add_option('-d', '--destination', action='store', dest='dest_dir', | ||
217 | 177 | help='sync destination dir (overrides config)') | ||
218 | 178 | (opts, args) = parser.parse_args() | ||
219 | 179 | |||
220 | 180 | if opts.debug: | ||
221 | 181 | logging.basicConfig(level=logging.DEBUG) | ||
222 | 182 | else: | ||
223 | 183 | logging.basicConfig(level=logging.INFO) | ||
224 | 184 | |||
225 | 185 | if opts.config: | ||
226 | 186 | logging.info('Loading charm helper config from %s.' % opts.config) | ||
227 | 187 | config = parse_config(opts.config) | ||
228 | 188 | if not config: | ||
229 | 189 | logging.error('Could not parse config from %s.' % opts.config) | ||
230 | 190 | sys.exit(1) | ||
231 | 191 | else: | ||
232 | 192 | config = {} | ||
233 | 193 | |||
234 | 194 | if 'branch' not in config: | ||
235 | 195 | config['branch'] = CHARM_HELPERS_BRANCH | ||
236 | 196 | if opts.branch: | ||
237 | 197 | config['branch'] = opts.branch | ||
238 | 198 | if opts.dest_dir: | ||
239 | 199 | config['destination'] = opts.dest_dir | ||
240 | 200 | |||
241 | 201 | if 'destination' not in config: | ||
242 | 202 | logging.error('No destination dir. specified as option or config.') | ||
243 | 203 | sys.exit(1) | ||
244 | 204 | |||
245 | 205 | if 'include' not in config: | ||
246 | 206 | if not args: | ||
247 | 207 | logging.error('No modules to sync specified as option or config.') | ||
248 | 208 | sys.exit(1) | ||
249 | 209 | config['include'] = [] | ||
250 | 210 | [config['include'].append(a) for a in args] | ||
251 | 211 | |||
252 | 212 | sync_options = None | ||
253 | 213 | if 'options' in config: | ||
254 | 214 | sync_options = config['options'] | ||
255 | 215 | tmpd = tempfile.mkdtemp() | ||
256 | 216 | try: | ||
257 | 217 | checkout = clone_helpers(tmpd, config['branch']) | ||
258 | 218 | sync_helpers(config['include'], checkout, config['destination'], | ||
259 | 219 | options=sync_options) | ||
260 | 220 | except Exception, e: | ||
261 | 221 | logging.error("Could not sync: %s" % e) | ||
262 | 222 | raise e | ||
263 | 223 | finally: | ||
264 | 224 | logging.debug('Cleaning up %s' % tmpd) | ||
265 | 225 | shutil.rmtree(tmpd) | ||
266 | 0 | 226 | ||
267 | === added file 'charm-helpers-hooks.yaml' | |||
268 | --- charm-helpers-hooks.yaml 1970-01-01 00:00:00 +0000 | |||
269 | +++ charm-helpers-hooks.yaml 2015-01-20 18:33:44 +0000 | |||
270 | @@ -0,0 +1,7 @@ | |||
271 | 1 | branch: lp:charm-helpers | ||
272 | 2 | destination: hooks/charmhelpers | ||
273 | 3 | include: | ||
274 | 4 | - __init__ | ||
275 | 5 | - core | ||
276 | 6 | - fetch | ||
277 | 7 | - payload.execd | ||
278 | 0 | 8 | ||
279 | === modified file 'config.yaml' | |||
280 | --- config.yaml 2014-08-14 19:53:02 +0000 | |||
281 | +++ config.yaml 2015-01-20 18:33:44 +0000 | |||
282 | @@ -17,9 +17,9 @@ | |||
283 | 17 | slave nodes so please don't change in Jenkins. | 17 | slave nodes so please don't change in Jenkins. |
284 | 18 | password: | 18 | password: |
285 | 19 | type: string | 19 | type: string |
286 | 20 | default: "" | ||
287 | 20 | description: Admin user password - used to manage | 21 | description: Admin user password - used to manage |
288 | 21 | slave nodes so please don't change in Jenkins. | 22 | slave nodes so please don't change in Jenkins. |
289 | 22 | default: | ||
290 | 23 | plugins: | 23 | plugins: |
291 | 24 | type: string | 24 | type: string |
292 | 25 | default: "" | 25 | default: "" |
293 | 26 | 26 | ||
294 | === removed file 'hooks/addnode' | |||
295 | --- hooks/addnode 2012-04-27 13:04:33 +0000 | |||
296 | +++ hooks/addnode 1970-01-01 00:00:00 +0000 | |||
297 | @@ -1,21 +0,0 @@ | |||
298 | 1 | #!/usr/bin/python | ||
299 | 2 | |||
300 | 3 | import jenkins | ||
301 | 4 | import sys | ||
302 | 5 | |||
303 | 6 | host=sys.argv[1] | ||
304 | 7 | executors=sys.argv[2] | ||
305 | 8 | labels=sys.argv[3] | ||
306 | 9 | username=sys.argv[4] | ||
307 | 10 | password=sys.argv[5] | ||
308 | 11 | |||
309 | 12 | l_jenkins = jenkins.Jenkins("http://localhost:8080/",username,password) | ||
310 | 13 | |||
311 | 14 | if l_jenkins.node_exists(host): | ||
312 | 15 | print "Node exists - not adding" | ||
313 | 16 | else: | ||
314 | 17 | print "Adding node to Jenkins master" | ||
315 | 18 | l_jenkins.create_node(host, int(executors) * 2, host , labels=labels) | ||
316 | 19 | |||
317 | 20 | if not l_jenkins.node_exists(host): | ||
318 | 21 | print "Failed to create node" | ||
319 | 22 | 0 | ||
320 | === added directory 'hooks/charmhelpers' | |||
321 | === added file 'hooks/charmhelpers/__init__.py' | |||
322 | --- hooks/charmhelpers/__init__.py 1970-01-01 00:00:00 +0000 | |||
323 | +++ hooks/charmhelpers/__init__.py 2015-01-20 18:33:44 +0000 | |||
324 | @@ -0,0 +1,22 @@ | |||
325 | 1 | # Bootstrap charm-helpers, installing its dependencies if necessary using | ||
326 | 2 | # only standard libraries. | ||
327 | 3 | import subprocess | ||
328 | 4 | import sys | ||
329 | 5 | |||
330 | 6 | try: | ||
331 | 7 | import six # flake8: noqa | ||
332 | 8 | except ImportError: | ||
333 | 9 | if sys.version_info.major == 2: | ||
334 | 10 | subprocess.check_call(['apt-get', 'install', '-y', 'python-six']) | ||
335 | 11 | else: | ||
336 | 12 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-six']) | ||
337 | 13 | import six # flake8: noqa | ||
338 | 14 | |||
339 | 15 | try: | ||
340 | 16 | import yaml # flake8: noqa | ||
341 | 17 | except ImportError: | ||
342 | 18 | if sys.version_info.major == 2: | ||
343 | 19 | subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml']) | ||
344 | 20 | else: | ||
345 | 21 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml']) | ||
346 | 22 | import yaml # flake8: noqa | ||
347 | 0 | 23 | ||
348 | === added directory 'hooks/charmhelpers/contrib' | |||
349 | === added file 'hooks/charmhelpers/contrib/__init__.py' | |||
350 | === added directory 'hooks/charmhelpers/core' | |||
351 | === added file 'hooks/charmhelpers/core/__init__.py' | |||
352 | === added file 'hooks/charmhelpers/core/decorators.py' | |||
353 | --- hooks/charmhelpers/core/decorators.py 1970-01-01 00:00:00 +0000 | |||
354 | +++ hooks/charmhelpers/core/decorators.py 2015-01-20 18:33:44 +0000 | |||
355 | @@ -0,0 +1,41 @@ | |||
356 | 1 | # | ||
357 | 2 | # Copyright 2014 Canonical Ltd. | ||
358 | 3 | # | ||
359 | 4 | # Authors: | ||
360 | 5 | # Edward Hope-Morley <opentastic@gmail.com> | ||
361 | 6 | # | ||
362 | 7 | |||
363 | 8 | import time | ||
364 | 9 | |||
365 | 10 | from charmhelpers.core.hookenv import ( | ||
366 | 11 | log, | ||
367 | 12 | INFO, | ||
368 | 13 | ) | ||
369 | 14 | |||
370 | 15 | |||
371 | 16 | def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): | ||
372 | 17 | """If the decorated function raises exception exc_type, allow num_retries | ||
373 | 18 | retry attempts before raise the exception. | ||
374 | 19 | """ | ||
375 | 20 | def _retry_on_exception_inner_1(f): | ||
376 | 21 | def _retry_on_exception_inner_2(*args, **kwargs): | ||
377 | 22 | retries = num_retries | ||
378 | 23 | multiplier = 1 | ||
379 | 24 | while True: | ||
380 | 25 | try: | ||
381 | 26 | return f(*args, **kwargs) | ||
382 | 27 | except exc_type: | ||
383 | 28 | if not retries: | ||
384 | 29 | raise | ||
385 | 30 | |||
386 | 31 | delay = base_delay * multiplier | ||
387 | 32 | multiplier += 1 | ||
388 | 33 | log("Retrying '%s' %d more times (delay=%s)" % | ||
389 | 34 | (f.__name__, retries, delay), level=INFO) | ||
390 | 35 | retries -= 1 | ||
391 | 36 | if delay: | ||
392 | 37 | time.sleep(delay) | ||
393 | 38 | |||
394 | 39 | return _retry_on_exception_inner_2 | ||
395 | 40 | |||
396 | 41 | return _retry_on_exception_inner_1 | ||
397 | 0 | 42 | ||
398 | === added file 'hooks/charmhelpers/core/fstab.py' | |||
399 | --- hooks/charmhelpers/core/fstab.py 1970-01-01 00:00:00 +0000 | |||
400 | +++ hooks/charmhelpers/core/fstab.py 2015-01-20 18:33:44 +0000 | |||
401 | @@ -0,0 +1,118 @@ | |||
402 | 1 | #!/usr/bin/env python | ||
403 | 2 | # -*- coding: utf-8 -*- | ||
404 | 3 | |||
405 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
406 | 5 | |||
407 | 6 | import io | ||
408 | 7 | import os | ||
409 | 8 | |||
410 | 9 | |||
411 | 10 | class Fstab(io.FileIO): | ||
412 | 11 | """This class extends file in order to implement a file reader/writer | ||
413 | 12 | for file `/etc/fstab` | ||
414 | 13 | """ | ||
415 | 14 | |||
416 | 15 | class Entry(object): | ||
417 | 16 | """Entry class represents a non-comment line on the `/etc/fstab` file | ||
418 | 17 | """ | ||
419 | 18 | def __init__(self, device, mountpoint, filesystem, | ||
420 | 19 | options, d=0, p=0): | ||
421 | 20 | self.device = device | ||
422 | 21 | self.mountpoint = mountpoint | ||
423 | 22 | self.filesystem = filesystem | ||
424 | 23 | |||
425 | 24 | if not options: | ||
426 | 25 | options = "defaults" | ||
427 | 26 | |||
428 | 27 | self.options = options | ||
429 | 28 | self.d = int(d) | ||
430 | 29 | self.p = int(p) | ||
431 | 30 | |||
432 | 31 | def __eq__(self, o): | ||
433 | 32 | return str(self) == str(o) | ||
434 | 33 | |||
435 | 34 | def __str__(self): | ||
436 | 35 | return "{} {} {} {} {} {}".format(self.device, | ||
437 | 36 | self.mountpoint, | ||
438 | 37 | self.filesystem, | ||
439 | 38 | self.options, | ||
440 | 39 | self.d, | ||
441 | 40 | self.p) | ||
442 | 41 | |||
443 | 42 | DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab') | ||
444 | 43 | |||
445 | 44 | def __init__(self, path=None): | ||
446 | 45 | if path: | ||
447 | 46 | self._path = path | ||
448 | 47 | else: | ||
449 | 48 | self._path = self.DEFAULT_PATH | ||
450 | 49 | super(Fstab, self).__init__(self._path, 'rb+') | ||
451 | 50 | |||
452 | 51 | def _hydrate_entry(self, line): | ||
453 | 52 | # NOTE: use split with no arguments to split on any | ||
454 | 53 | # whitespace including tabs | ||
455 | 54 | return Fstab.Entry(*filter( | ||
456 | 55 | lambda x: x not in ('', None), | ||
457 | 56 | line.strip("\n").split())) | ||
458 | 57 | |||
459 | 58 | @property | ||
460 | 59 | def entries(self): | ||
461 | 60 | self.seek(0) | ||
462 | 61 | for line in self.readlines(): | ||
463 | 62 | line = line.decode('us-ascii') | ||
464 | 63 | try: | ||
465 | 64 | if line.strip() and not line.startswith("#"): | ||
466 | 65 | yield self._hydrate_entry(line) | ||
467 | 66 | except ValueError: | ||
468 | 67 | pass | ||
469 | 68 | |||
470 | 69 | def get_entry_by_attr(self, attr, value): | ||
471 | 70 | for entry in self.entries: | ||
472 | 71 | e_attr = getattr(entry, attr) | ||
473 | 72 | if e_attr == value: | ||
474 | 73 | return entry | ||
475 | 74 | return None | ||
476 | 75 | |||
477 | 76 | def add_entry(self, entry): | ||
478 | 77 | if self.get_entry_by_attr('device', entry.device): | ||
479 | 78 | return False | ||
480 | 79 | |||
481 | 80 | self.write((str(entry) + '\n').encode('us-ascii')) | ||
482 | 81 | self.truncate() | ||
483 | 82 | return entry | ||
484 | 83 | |||
485 | 84 | def remove_entry(self, entry): | ||
486 | 85 | self.seek(0) | ||
487 | 86 | |||
488 | 87 | lines = [l.decode('us-ascii') for l in self.readlines()] | ||
489 | 88 | |||
490 | 89 | found = False | ||
491 | 90 | for index, line in enumerate(lines): | ||
492 | 91 | if not line.startswith("#"): | ||
493 | 92 | if self._hydrate_entry(line) == entry: | ||
494 | 93 | found = True | ||
495 | 94 | break | ||
496 | 95 | |||
497 | 96 | if not found: | ||
498 | 97 | return False | ||
499 | 98 | |||
500 | 99 | lines.remove(line) | ||
501 | 100 | |||
502 | 101 | self.seek(0) | ||
503 | 102 | self.write(''.join(lines).encode('us-ascii')) | ||
504 | 103 | self.truncate() | ||
505 | 104 | return True | ||
506 | 105 | |||
507 | 106 | @classmethod | ||
508 | 107 | def remove_by_mountpoint(cls, mountpoint, path=None): | ||
509 | 108 | fstab = cls(path=path) | ||
510 | 109 | entry = fstab.get_entry_by_attr('mountpoint', mountpoint) | ||
511 | 110 | if entry: | ||
512 | 111 | return fstab.remove_entry(entry) | ||
513 | 112 | return False | ||
514 | 113 | |||
515 | 114 | @classmethod | ||
516 | 115 | def add(cls, device, mountpoint, filesystem, options=None, path=None): | ||
517 | 116 | return cls(path=path).add_entry(Fstab.Entry(device, | ||
518 | 117 | mountpoint, filesystem, | ||
519 | 118 | options=options)) | ||
520 | 0 | 119 | ||
521 | === added file 'hooks/charmhelpers/core/hookenv.py' | |||
522 | --- hooks/charmhelpers/core/hookenv.py 1970-01-01 00:00:00 +0000 | |||
523 | +++ hooks/charmhelpers/core/hookenv.py 2015-01-20 18:33:44 +0000 | |||
524 | @@ -0,0 +1,552 @@ | |||
525 | 1 | "Interactions with the Juju environment" | ||
526 | 2 | # Copyright 2013 Canonical Ltd. | ||
527 | 3 | # | ||
528 | 4 | # Authors: | ||
529 | 5 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
530 | 6 | |||
531 | 7 | import os | ||
532 | 8 | import json | ||
533 | 9 | import yaml | ||
534 | 10 | import subprocess | ||
535 | 11 | import sys | ||
536 | 12 | from subprocess import CalledProcessError | ||
537 | 13 | |||
538 | 14 | import six | ||
539 | 15 | if not six.PY3: | ||
540 | 16 | from UserDict import UserDict | ||
541 | 17 | else: | ||
542 | 18 | from collections import UserDict | ||
543 | 19 | |||
544 | 20 | CRITICAL = "CRITICAL" | ||
545 | 21 | ERROR = "ERROR" | ||
546 | 22 | WARNING = "WARNING" | ||
547 | 23 | INFO = "INFO" | ||
548 | 24 | DEBUG = "DEBUG" | ||
549 | 25 | MARKER = object() | ||
550 | 26 | |||
551 | 27 | cache = {} | ||
552 | 28 | |||
553 | 29 | |||
554 | 30 | def cached(func): | ||
555 | 31 | """Cache return values for multiple executions of func + args | ||
556 | 32 | |||
557 | 33 | For example:: | ||
558 | 34 | |||
559 | 35 | @cached | ||
560 | 36 | def unit_get(attribute): | ||
561 | 37 | pass | ||
562 | 38 | |||
563 | 39 | unit_get('test') | ||
564 | 40 | |||
565 | 41 | will cache the result of unit_get + 'test' for future calls. | ||
566 | 42 | """ | ||
567 | 43 | def wrapper(*args, **kwargs): | ||
568 | 44 | global cache | ||
569 | 45 | key = str((func, args, kwargs)) | ||
570 | 46 | try: | ||
571 | 47 | return cache[key] | ||
572 | 48 | except KeyError: | ||
573 | 49 | res = func(*args, **kwargs) | ||
574 | 50 | cache[key] = res | ||
575 | 51 | return res | ||
576 | 52 | return wrapper | ||
577 | 53 | |||
578 | 54 | |||
579 | 55 | def flush(key): | ||
580 | 56 | """Flushes any entries from function cache where the | ||
581 | 57 | key is found in the function+args """ | ||
582 | 58 | flush_list = [] | ||
583 | 59 | for item in cache: | ||
584 | 60 | if key in item: | ||
585 | 61 | flush_list.append(item) | ||
586 | 62 | for item in flush_list: | ||
587 | 63 | del cache[item] | ||
588 | 64 | |||
589 | 65 | |||
590 | 66 | def log(message, level=None): | ||
591 | 67 | """Write a message to the juju log""" | ||
592 | 68 | command = ['juju-log'] | ||
593 | 69 | if level: | ||
594 | 70 | command += ['-l', level] | ||
595 | 71 | if not isinstance(message, six.string_types): | ||
596 | 72 | message = repr(message) | ||
597 | 73 | command += [message] | ||
598 | 74 | subprocess.call(command) | ||
599 | 75 | |||
600 | 76 | |||
601 | 77 | class Serializable(UserDict): | ||
602 | 78 | """Wrapper, an object that can be serialized to yaml or json""" | ||
603 | 79 | |||
604 | 80 | def __init__(self, obj): | ||
605 | 81 | # wrap the object | ||
606 | 82 | UserDict.__init__(self) | ||
607 | 83 | self.data = obj | ||
608 | 84 | |||
609 | 85 | def __getattr__(self, attr): | ||
610 | 86 | # See if this object has attribute. | ||
611 | 87 | if attr in ("json", "yaml", "data"): | ||
612 | 88 | return self.__dict__[attr] | ||
613 | 89 | # Check for attribute in wrapped object. | ||
614 | 90 | got = getattr(self.data, attr, MARKER) | ||
615 | 91 | if got is not MARKER: | ||
616 | 92 | return got | ||
617 | 93 | # Proxy to the wrapped object via dict interface. | ||
618 | 94 | try: | ||
619 | 95 | return self.data[attr] | ||
620 | 96 | except KeyError: | ||
621 | 97 | raise AttributeError(attr) | ||
622 | 98 | |||
623 | 99 | def __getstate__(self): | ||
624 | 100 | # Pickle as a standard dictionary. | ||
625 | 101 | return self.data | ||
626 | 102 | |||
627 | 103 | def __setstate__(self, state): | ||
628 | 104 | # Unpickle into our wrapper. | ||
629 | 105 | self.data = state | ||
630 | 106 | |||
631 | 107 | def json(self): | ||
632 | 108 | """Serialize the object to json""" | ||
633 | 109 | return json.dumps(self.data) | ||
634 | 110 | |||
635 | 111 | def yaml(self): | ||
636 | 112 | """Serialize the object to yaml""" | ||
637 | 113 | return yaml.dump(self.data) | ||
638 | 114 | |||
639 | 115 | |||
640 | 116 | def execution_environment(): | ||
641 | 117 | """A convenient bundling of the current execution context""" | ||
642 | 118 | context = {} | ||
643 | 119 | context['conf'] = config() | ||
644 | 120 | if relation_id(): | ||
645 | 121 | context['reltype'] = relation_type() | ||
646 | 122 | context['relid'] = relation_id() | ||
647 | 123 | context['rel'] = relation_get() | ||
648 | 124 | context['unit'] = local_unit() | ||
649 | 125 | context['rels'] = relations() | ||
650 | 126 | context['env'] = os.environ | ||
651 | 127 | return context | ||
652 | 128 | |||
653 | 129 | |||
654 | 130 | def in_relation_hook(): | ||
655 | 131 | """Determine whether we're running in a relation hook""" | ||
656 | 132 | return 'JUJU_RELATION' in os.environ | ||
657 | 133 | |||
658 | 134 | |||
659 | 135 | def relation_type(): | ||
660 | 136 | """The scope for the current relation hook""" | ||
661 | 137 | return os.environ.get('JUJU_RELATION', None) | ||
662 | 138 | |||
663 | 139 | |||
664 | 140 | def relation_id(): | ||
665 | 141 | """The relation ID for the current relation hook""" | ||
666 | 142 | return os.environ.get('JUJU_RELATION_ID', None) | ||
667 | 143 | |||
668 | 144 | |||
669 | 145 | def local_unit(): | ||
670 | 146 | """Local unit ID""" | ||
671 | 147 | return os.environ['JUJU_UNIT_NAME'] | ||
672 | 148 | |||
673 | 149 | |||
674 | 150 | def remote_unit(): | ||
675 | 151 | """The remote unit for the current relation hook""" | ||
676 | 152 | return os.environ['JUJU_REMOTE_UNIT'] | ||
677 | 153 | |||
678 | 154 | |||
679 | 155 | def service_name(): | ||
680 | 156 | """The name service group this unit belongs to""" | ||
681 | 157 | return local_unit().split('/')[0] | ||
682 | 158 | |||
683 | 159 | |||
684 | 160 | def hook_name(): | ||
685 | 161 | """The name of the currently executing hook""" | ||
686 | 162 | return os.path.basename(sys.argv[0]) | ||
687 | 163 | |||
688 | 164 | |||
689 | 165 | class Config(dict): | ||
690 | 166 | """A dictionary representation of the charm's config.yaml, with some | ||
691 | 167 | extra features: | ||
692 | 168 | |||
693 | 169 | - See which values in the dictionary have changed since the previous hook. | ||
694 | 170 | - For values that have changed, see what the previous value was. | ||
695 | 171 | - Store arbitrary data for use in a later hook. | ||
696 | 172 | |||
697 | 173 | NOTE: Do not instantiate this object directly - instead call | ||
698 | 174 | ``hookenv.config()``, which will return an instance of :class:`Config`. | ||
699 | 175 | |||
700 | 176 | Example usage:: | ||
701 | 177 | |||
702 | 178 | >>> # inside a hook | ||
703 | 179 | >>> from charmhelpers.core import hookenv | ||
704 | 180 | >>> config = hookenv.config() | ||
705 | 181 | >>> config['foo'] | ||
706 | 182 | 'bar' | ||
707 | 183 | >>> # store a new key/value for later use | ||
708 | 184 | >>> config['mykey'] = 'myval' | ||
709 | 185 | |||
710 | 186 | |||
711 | 187 | >>> # user runs `juju set mycharm foo=baz` | ||
712 | 188 | >>> # now we're inside subsequent config-changed hook | ||
713 | 189 | >>> config = hookenv.config() | ||
714 | 190 | >>> config['foo'] | ||
715 | 191 | 'baz' | ||
716 | 192 | >>> # test to see if this val has changed since last hook | ||
717 | 193 | >>> config.changed('foo') | ||
718 | 194 | True | ||
719 | 195 | >>> # what was the previous value? | ||
720 | 196 | >>> config.previous('foo') | ||
721 | 197 | 'bar' | ||
722 | 198 | >>> # keys/values that we add are preserved across hooks | ||
723 | 199 | >>> config['mykey'] | ||
724 | 200 | 'myval' | ||
725 | 201 | |||
726 | 202 | """ | ||
727 | 203 | CONFIG_FILE_NAME = '.juju-persistent-config' | ||
728 | 204 | |||
729 | 205 | def __init__(self, *args, **kw): | ||
730 | 206 | super(Config, self).__init__(*args, **kw) | ||
731 | 207 | self.implicit_save = True | ||
732 | 208 | self._prev_dict = None | ||
733 | 209 | self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME) | ||
734 | 210 | if os.path.exists(self.path): | ||
735 | 211 | self.load_previous() | ||
736 | 212 | |||
737 | 213 | def __getitem__(self, key): | ||
738 | 214 | """For regular dict lookups, check the current juju config first, | ||
739 | 215 | then the previous (saved) copy. This ensures that user-saved values | ||
740 | 216 | will be returned by a dict lookup. | ||
741 | 217 | |||
742 | 218 | """ | ||
743 | 219 | try: | ||
744 | 220 | return dict.__getitem__(self, key) | ||
745 | 221 | except KeyError: | ||
746 | 222 | return (self._prev_dict or {})[key] | ||
747 | 223 | |||
748 | 224 | def keys(self): | ||
749 | 225 | prev_keys = [] | ||
750 | 226 | if self._prev_dict is not None: | ||
751 | 227 | prev_keys = self._prev_dict.keys() | ||
752 | 228 | return list(set(prev_keys + list(dict.keys(self)))) | ||
753 | 229 | |||
754 | 230 | def load_previous(self, path=None): | ||
755 | 231 | """Load previous copy of config from disk. | ||
756 | 232 | |||
757 | 233 | In normal usage you don't need to call this method directly - it | ||
758 | 234 | is called automatically at object initialization. | ||
759 | 235 | |||
760 | 236 | :param path: | ||
761 | 237 | |||
762 | 238 | File path from which to load the previous config. If `None`, | ||
763 | 239 | config is loaded from the default location. If `path` is | ||
764 | 240 | specified, subsequent `save()` calls will write to the same | ||
765 | 241 | path. | ||
766 | 242 | |||
767 | 243 | """ | ||
768 | 244 | self.path = path or self.path | ||
769 | 245 | with open(self.path) as f: | ||
770 | 246 | self._prev_dict = json.load(f) | ||
771 | 247 | |||
772 | 248 | def changed(self, key): | ||
773 | 249 | """Return True if the current value for this key is different from | ||
774 | 250 | the previous value. | ||
775 | 251 | |||
776 | 252 | """ | ||
777 | 253 | if self._prev_dict is None: | ||
778 | 254 | return True | ||
779 | 255 | return self.previous(key) != self.get(key) | ||
780 | 256 | |||
781 | 257 | def previous(self, key): | ||
782 | 258 | """Return previous value for this key, or None if there | ||
783 | 259 | is no previous value. | ||
784 | 260 | |||
785 | 261 | """ | ||
786 | 262 | if self._prev_dict: | ||
787 | 263 | return self._prev_dict.get(key) | ||
788 | 264 | return None | ||
789 | 265 | |||
790 | 266 | def save(self): | ||
791 | 267 | """Save this config to disk. | ||
792 | 268 | |||
793 | 269 | If the charm is using the :mod:`Services Framework <services.base>` | ||
794 | 270 | or :meth:'@hook <Hooks.hook>' decorator, this | ||
795 | 271 | is called automatically at the end of successful hook execution. | ||
796 | 272 | Otherwise, it should be called directly by user code. | ||
797 | 273 | |||
798 | 274 | To disable automatic saves, set ``implicit_save=False`` on this | ||
799 | 275 | instance. | ||
800 | 276 | |||
801 | 277 | """ | ||
802 | 278 | if self._prev_dict: | ||
803 | 279 | for k, v in six.iteritems(self._prev_dict): | ||
804 | 280 | if k not in self: | ||
805 | 281 | self[k] = v | ||
806 | 282 | with open(self.path, 'w') as f: | ||
807 | 283 | json.dump(self, f) | ||
808 | 284 | |||
809 | 285 | |||
810 | 286 | @cached | ||
811 | 287 | def config(scope=None): | ||
812 | 288 | """Juju charm configuration""" | ||
813 | 289 | config_cmd_line = ['config-get'] | ||
814 | 290 | if scope is not None: | ||
815 | 291 | config_cmd_line.append(scope) | ||
816 | 292 | config_cmd_line.append('--format=json') | ||
817 | 293 | try: | ||
818 | 294 | config_data = json.loads( | ||
819 | 295 | subprocess.check_output(config_cmd_line).decode('UTF-8')) | ||
820 | 296 | if scope is not None: | ||
821 | 297 | return config_data | ||
822 | 298 | return Config(config_data) | ||
823 | 299 | except ValueError: | ||
824 | 300 | return None | ||
825 | 301 | |||
826 | 302 | |||
827 | 303 | @cached | ||
828 | 304 | def relation_get(attribute=None, unit=None, rid=None): | ||
829 | 305 | """Get relation information""" | ||
830 | 306 | _args = ['relation-get', '--format=json'] | ||
831 | 307 | if rid: | ||
832 | 308 | _args.append('-r') | ||
833 | 309 | _args.append(rid) | ||
834 | 310 | _args.append(attribute or '-') | ||
835 | 311 | if unit: | ||
836 | 312 | _args.append(unit) | ||
837 | 313 | try: | ||
838 | 314 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
839 | 315 | except ValueError: | ||
840 | 316 | return None | ||
841 | 317 | except CalledProcessError as e: | ||
842 | 318 | if e.returncode == 2: | ||
843 | 319 | return None | ||
844 | 320 | raise | ||
845 | 321 | |||
846 | 322 | |||
847 | 323 | def relation_set(relation_id=None, relation_settings=None, **kwargs): | ||
848 | 324 | """Set relation information for the current unit""" | ||
849 | 325 | relation_settings = relation_settings if relation_settings else {} | ||
850 | 326 | relation_cmd_line = ['relation-set'] | ||
851 | 327 | if relation_id is not None: | ||
852 | 328 | relation_cmd_line.extend(('-r', relation_id)) | ||
853 | 329 | for k, v in (list(relation_settings.items()) + list(kwargs.items())): | ||
854 | 330 | if v is None: | ||
855 | 331 | relation_cmd_line.append('{}='.format(k)) | ||
856 | 332 | else: | ||
857 | 333 | relation_cmd_line.append('{}={}'.format(k, v)) | ||
858 | 334 | subprocess.check_call(relation_cmd_line) | ||
859 | 335 | # Flush cache of any relation-gets for local unit | ||
860 | 336 | flush(local_unit()) | ||
861 | 337 | |||
862 | 338 | |||
863 | 339 | @cached | ||
864 | 340 | def relation_ids(reltype=None): | ||
865 | 341 | """A list of relation_ids""" | ||
866 | 342 | reltype = reltype or relation_type() | ||
867 | 343 | relid_cmd_line = ['relation-ids', '--format=json'] | ||
868 | 344 | if reltype is not None: | ||
869 | 345 | relid_cmd_line.append(reltype) | ||
870 | 346 | return json.loads( | ||
871 | 347 | subprocess.check_output(relid_cmd_line).decode('UTF-8')) or [] | ||
872 | 348 | return [] | ||
873 | 349 | |||
874 | 350 | |||
875 | 351 | @cached | ||
876 | 352 | def related_units(relid=None): | ||
877 | 353 | """A list of related units""" | ||
878 | 354 | relid = relid or relation_id() | ||
879 | 355 | units_cmd_line = ['relation-list', '--format=json'] | ||
880 | 356 | if relid is not None: | ||
881 | 357 | units_cmd_line.extend(('-r', relid)) | ||
882 | 358 | return json.loads( | ||
883 | 359 | subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | ||
884 | 360 | |||
885 | 361 | |||
886 | 362 | @cached | ||
887 | 363 | def relation_for_unit(unit=None, rid=None): | ||
888 | 364 | """Get the json represenation of a unit's relation""" | ||
889 | 365 | unit = unit or remote_unit() | ||
890 | 366 | relation = relation_get(unit=unit, rid=rid) | ||
891 | 367 | for key in relation: | ||
892 | 368 | if key.endswith('-list'): | ||
893 | 369 | relation[key] = relation[key].split() | ||
894 | 370 | relation['__unit__'] = unit | ||
895 | 371 | return relation | ||
896 | 372 | |||
897 | 373 | |||
898 | 374 | @cached | ||
899 | 375 | def relations_for_id(relid=None): | ||
900 | 376 | """Get relations of a specific relation ID""" | ||
901 | 377 | relation_data = [] | ||
902 | 378 | relid = relid or relation_ids() | ||
903 | 379 | for unit in related_units(relid): | ||
904 | 380 | unit_data = relation_for_unit(unit, relid) | ||
905 | 381 | unit_data['__relid__'] = relid | ||
906 | 382 | relation_data.append(unit_data) | ||
907 | 383 | return relation_data | ||
908 | 384 | |||
909 | 385 | |||
910 | 386 | @cached | ||
911 | 387 | def relations_of_type(reltype=None): | ||
912 | 388 | """Get relations of a specific type""" | ||
913 | 389 | relation_data = [] | ||
914 | 390 | reltype = reltype or relation_type() | ||
915 | 391 | for relid in relation_ids(reltype): | ||
916 | 392 | for relation in relations_for_id(relid): | ||
917 | 393 | relation['__relid__'] = relid | ||
918 | 394 | relation_data.append(relation) | ||
919 | 395 | return relation_data | ||
920 | 396 | |||
921 | 397 | |||
922 | 398 | @cached | ||
923 | 399 | def metadata(): | ||
924 | 400 | """Get the current charm metadata.yaml contents as a python object""" | ||
925 | 401 | with open(os.path.join(charm_dir(), 'metadata.yaml')) as md: | ||
926 | 402 | return yaml.safe_load(md) | ||
927 | 403 | |||
928 | 404 | |||
929 | 405 | @cached | ||
930 | 406 | def relation_types(): | ||
931 | 407 | """Get a list of relation types supported by this charm""" | ||
932 | 408 | rel_types = [] | ||
933 | 409 | md = metadata() | ||
934 | 410 | for key in ('provides', 'requires', 'peers'): | ||
935 | 411 | section = md.get(key) | ||
936 | 412 | if section: | ||
937 | 413 | rel_types.extend(section.keys()) | ||
938 | 414 | return rel_types | ||
939 | 415 | |||
940 | 416 | |||
941 | 417 | @cached | ||
942 | 418 | def charm_name(): | ||
943 | 419 | """Get the name of the current charm as is specified on metadata.yaml""" | ||
944 | 420 | return metadata().get('name') | ||
945 | 421 | |||
946 | 422 | |||
947 | 423 | @cached | ||
948 | 424 | def relations(): | ||
949 | 425 | """Get a nested dictionary of relation data for all related units""" | ||
950 | 426 | rels = {} | ||
951 | 427 | for reltype in relation_types(): | ||
952 | 428 | relids = {} | ||
953 | 429 | for relid in relation_ids(reltype): | ||
954 | 430 | units = {local_unit(): relation_get(unit=local_unit(), rid=relid)} | ||
955 | 431 | for unit in related_units(relid): | ||
956 | 432 | reldata = relation_get(unit=unit, rid=relid) | ||
957 | 433 | units[unit] = reldata | ||
958 | 434 | relids[relid] = units | ||
959 | 435 | rels[reltype] = relids | ||
960 | 436 | return rels | ||
961 | 437 | |||
962 | 438 | |||
963 | 439 | @cached | ||
964 | 440 | def is_relation_made(relation, keys='private-address'): | ||
965 | 441 | ''' | ||
966 | 442 | Determine whether a relation is established by checking for | ||
967 | 443 | presence of key(s). If a list of keys is provided, they | ||
968 | 444 | must all be present for the relation to be identified as made | ||
969 | 445 | ''' | ||
970 | 446 | if isinstance(keys, str): | ||
971 | 447 | keys = [keys] | ||
972 | 448 | for r_id in relation_ids(relation): | ||
973 | 449 | for unit in related_units(r_id): | ||
974 | 450 | context = {} | ||
975 | 451 | for k in keys: | ||
976 | 452 | context[k] = relation_get(k, rid=r_id, | ||
977 | 453 | unit=unit) | ||
978 | 454 | if None not in context.values(): | ||
979 | 455 | return True | ||
980 | 456 | return False | ||
981 | 457 | |||
982 | 458 | |||
983 | 459 | def open_port(port, protocol="TCP"): | ||
984 | 460 | """Open a service network port""" | ||
985 | 461 | _args = ['open-port'] | ||
986 | 462 | _args.append('{}/{}'.format(port, protocol)) | ||
987 | 463 | subprocess.check_call(_args) | ||
988 | 464 | |||
989 | 465 | |||
990 | 466 | def close_port(port, protocol="TCP"): | ||
991 | 467 | """Close a service network port""" | ||
992 | 468 | _args = ['close-port'] | ||
993 | 469 | _args.append('{}/{}'.format(port, protocol)) | ||
994 | 470 | subprocess.check_call(_args) | ||
995 | 471 | |||
996 | 472 | |||
997 | 473 | @cached | ||
998 | 474 | def unit_get(attribute): | ||
999 | 475 | """Get the unit ID for the remote unit""" | ||
1000 | 476 | _args = ['unit-get', '--format=json', attribute] | ||
1001 | 477 | try: | ||
1002 | 478 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1003 | 479 | except ValueError: | ||
1004 | 480 | return None | ||
1005 | 481 | |||
1006 | 482 | |||
1007 | 483 | def unit_private_ip(): | ||
1008 | 484 | """Get this unit's private IP address""" | ||
1009 | 485 | return unit_get('private-address') | ||
1010 | 486 | |||
1011 | 487 | |||
1012 | 488 | class UnregisteredHookError(Exception): | ||
1013 | 489 | """Raised when an undefined hook is called""" | ||
1014 | 490 | pass | ||
1015 | 491 | |||
1016 | 492 | |||
1017 | 493 | class Hooks(object): | ||
1018 | 494 | """A convenient handler for hook functions. | ||
1019 | 495 | |||
1020 | 496 | Example:: | ||
1021 | 497 | |||
1022 | 498 | hooks = Hooks() | ||
1023 | 499 | |||
1024 | 500 | # register a hook, taking its name from the function name | ||
1025 | 501 | @hooks.hook() | ||
1026 | 502 | def install(): | ||
1027 | 503 | pass # your code here | ||
1028 | 504 | |||
1029 | 505 | # register a hook, providing a custom hook name | ||
1030 | 506 | @hooks.hook("config-changed") | ||
1031 | 507 | def config_changed(): | ||
1032 | 508 | pass # your code here | ||
1033 | 509 | |||
1034 | 510 | if __name__ == "__main__": | ||
1035 | 511 | # execute a hook based on the name the program is called by | ||
1036 | 512 | hooks.execute(sys.argv) | ||
1037 | 513 | """ | ||
1038 | 514 | |||
1039 | 515 | def __init__(self, config_save=True): | ||
1040 | 516 | super(Hooks, self).__init__() | ||
1041 | 517 | self._hooks = {} | ||
1042 | 518 | self._config_save = config_save | ||
1043 | 519 | |||
1044 | 520 | def register(self, name, function): | ||
1045 | 521 | """Register a hook""" | ||
1046 | 522 | self._hooks[name] = function | ||
1047 | 523 | |||
1048 | 524 | def execute(self, args): | ||
1049 | 525 | """Execute a registered hook based on args[0]""" | ||
1050 | 526 | hook_name = os.path.basename(args[0]) | ||
1051 | 527 | if hook_name in self._hooks: | ||
1052 | 528 | self._hooks[hook_name]() | ||
1053 | 529 | if self._config_save: | ||
1054 | 530 | cfg = config() | ||
1055 | 531 | if cfg.implicit_save: | ||
1056 | 532 | cfg.save() | ||
1057 | 533 | else: | ||
1058 | 534 | raise UnregisteredHookError(hook_name) | ||
1059 | 535 | |||
1060 | 536 | def hook(self, *hook_names): | ||
1061 | 537 | """Decorator, registering them as hooks""" | ||
1062 | 538 | def wrapper(decorated): | ||
1063 | 539 | for hook_name in hook_names: | ||
1064 | 540 | self.register(hook_name, decorated) | ||
1065 | 541 | else: | ||
1066 | 542 | self.register(decorated.__name__, decorated) | ||
1067 | 543 | if '_' in decorated.__name__: | ||
1068 | 544 | self.register( | ||
1069 | 545 | decorated.__name__.replace('_', '-'), decorated) | ||
1070 | 546 | return decorated | ||
1071 | 547 | return wrapper | ||
1072 | 548 | |||
1073 | 549 | |||
1074 | 550 | def charm_dir(): | ||
1075 | 551 | """Return the root directory of the current charm""" | ||
1076 | 552 | return os.environ.get('CHARM_DIR') | ||
1077 | 0 | 553 | ||
1078 | === added file 'hooks/charmhelpers/core/host.py' | |||
1079 | --- hooks/charmhelpers/core/host.py 1970-01-01 00:00:00 +0000 | |||
1080 | +++ hooks/charmhelpers/core/host.py 2015-01-20 18:33:44 +0000 | |||
1081 | @@ -0,0 +1,419 @@ | |||
1082 | 1 | """Tools for working with the host system""" | ||
1083 | 2 | # Copyright 2012 Canonical Ltd. | ||
1084 | 3 | # | ||
1085 | 4 | # Authors: | ||
1086 | 5 | # Nick Moffitt <nick.moffitt@canonical.com> | ||
1087 | 6 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | ||
1088 | 7 | |||
1089 | 8 | import os | ||
1090 | 9 | import re | ||
1091 | 10 | import pwd | ||
1092 | 11 | import grp | ||
1093 | 12 | import random | ||
1094 | 13 | import string | ||
1095 | 14 | import subprocess | ||
1096 | 15 | import hashlib | ||
1097 | 16 | from contextlib import contextmanager | ||
1098 | 17 | from collections import OrderedDict | ||
1099 | 18 | |||
1100 | 19 | import six | ||
1101 | 20 | |||
1102 | 21 | from .hookenv import log | ||
1103 | 22 | from .fstab import Fstab | ||
1104 | 23 | |||
1105 | 24 | |||
1106 | 25 | def service_start(service_name): | ||
1107 | 26 | """Start a system service""" | ||
1108 | 27 | return service('start', service_name) | ||
1109 | 28 | |||
1110 | 29 | |||
1111 | 30 | def service_stop(service_name): | ||
1112 | 31 | """Stop a system service""" | ||
1113 | 32 | return service('stop', service_name) | ||
1114 | 33 | |||
1115 | 34 | |||
1116 | 35 | def service_restart(service_name): | ||
1117 | 36 | """Restart a system service""" | ||
1118 | 37 | return service('restart', service_name) | ||
1119 | 38 | |||
1120 | 39 | |||
1121 | 40 | def service_reload(service_name, restart_on_failure=False): | ||
1122 | 41 | """Reload a system service, optionally falling back to restart if | ||
1123 | 42 | reload fails""" | ||
1124 | 43 | service_result = service('reload', service_name) | ||
1125 | 44 | if not service_result and restart_on_failure: | ||
1126 | 45 | service_result = service('restart', service_name) | ||
1127 | 46 | return service_result | ||
1128 | 47 | |||
1129 | 48 | |||
1130 | 49 | def service(action, service_name): | ||
1131 | 50 | """Control a system service""" | ||
1132 | 51 | cmd = ['service', service_name, action] | ||
1133 | 52 | return subprocess.call(cmd) == 0 | ||
1134 | 53 | |||
1135 | 54 | |||
1136 | 55 | def service_running(service): | ||
1137 | 56 | """Determine whether a system service is running""" | ||
1138 | 57 | try: | ||
1139 | 58 | output = subprocess.check_output( | ||
1140 | 59 | ['service', service, 'status'], | ||
1141 | 60 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1142 | 61 | except subprocess.CalledProcessError: | ||
1143 | 62 | return False | ||
1144 | 63 | else: | ||
1145 | 64 | if ("start/running" in output or "is running" in output): | ||
1146 | 65 | return True | ||
1147 | 66 | else: | ||
1148 | 67 | return False | ||
1149 | 68 | |||
1150 | 69 | |||
1151 | 70 | def service_available(service_name): | ||
1152 | 71 | """Determine whether a system service is available""" | ||
1153 | 72 | try: | ||
1154 | 73 | subprocess.check_output( | ||
1155 | 74 | ['service', service_name, 'status'], | ||
1156 | 75 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1157 | 76 | except subprocess.CalledProcessError as e: | ||
1158 | 77 | return 'unrecognized service' not in e.output | ||
1159 | 78 | else: | ||
1160 | 79 | return True | ||
1161 | 80 | |||
1162 | 81 | |||
1163 | 82 | def adduser(username, password=None, shell='/bin/bash', system_user=False): | ||
1164 | 83 | """Add a user to the system""" | ||
1165 | 84 | try: | ||
1166 | 85 | user_info = pwd.getpwnam(username) | ||
1167 | 86 | log('user {0} already exists!'.format(username)) | ||
1168 | 87 | except KeyError: | ||
1169 | 88 | log('creating user {0}'.format(username)) | ||
1170 | 89 | cmd = ['useradd'] | ||
1171 | 90 | if system_user or password is None: | ||
1172 | 91 | cmd.append('--system') | ||
1173 | 92 | else: | ||
1174 | 93 | cmd.extend([ | ||
1175 | 94 | '--create-home', | ||
1176 | 95 | '--shell', shell, | ||
1177 | 96 | '--password', password, | ||
1178 | 97 | ]) | ||
1179 | 98 | cmd.append(username) | ||
1180 | 99 | subprocess.check_call(cmd) | ||
1181 | 100 | user_info = pwd.getpwnam(username) | ||
1182 | 101 | return user_info | ||
1183 | 102 | |||
1184 | 103 | |||
1185 | 104 | def add_group(group_name, system_group=False): | ||
1186 | 105 | """Add a group to the system""" | ||
1187 | 106 | try: | ||
1188 | 107 | group_info = grp.getgrnam(group_name) | ||
1189 | 108 | log('group {0} already exists!'.format(group_name)) | ||
1190 | 109 | except KeyError: | ||
1191 | 110 | log('creating group {0}'.format(group_name)) | ||
1192 | 111 | cmd = ['addgroup'] | ||
1193 | 112 | if system_group: | ||
1194 | 113 | cmd.append('--system') | ||
1195 | 114 | else: | ||
1196 | 115 | cmd.extend([ | ||
1197 | 116 | '--group', | ||
1198 | 117 | ]) | ||
1199 | 118 | cmd.append(group_name) | ||
1200 | 119 | subprocess.check_call(cmd) | ||
1201 | 120 | group_info = grp.getgrnam(group_name) | ||
1202 | 121 | return group_info | ||
1203 | 122 | |||
1204 | 123 | |||
1205 | 124 | def add_user_to_group(username, group): | ||
1206 | 125 | """Add a user to a group""" | ||
1207 | 126 | cmd = [ | ||
1208 | 127 | 'gpasswd', '-a', | ||
1209 | 128 | username, | ||
1210 | 129 | group | ||
1211 | 130 | ] | ||
1212 | 131 | log("Adding user {} to group {}".format(username, group)) | ||
1213 | 132 | subprocess.check_call(cmd) | ||
1214 | 133 | |||
1215 | 134 | |||
1216 | 135 | def rsync(from_path, to_path, flags='-r', options=None): | ||
1217 | 136 | """Replicate the contents of a path""" | ||
1218 | 137 | options = options or ['--delete', '--executability'] | ||
1219 | 138 | cmd = ['/usr/bin/rsync', flags] | ||
1220 | 139 | cmd.extend(options) | ||
1221 | 140 | cmd.append(from_path) | ||
1222 | 141 | cmd.append(to_path) | ||
1223 | 142 | log(" ".join(cmd)) | ||
1224 | 143 | return subprocess.check_output(cmd).decode('UTF-8').strip() | ||
1225 | 144 | |||
1226 | 145 | |||
1227 | 146 | def symlink(source, destination): | ||
1228 | 147 | """Create a symbolic link""" | ||
1229 | 148 | log("Symlinking {} as {}".format(source, destination)) | ||
1230 | 149 | cmd = [ | ||
1231 | 150 | 'ln', | ||
1232 | 151 | '-sf', | ||
1233 | 152 | source, | ||
1234 | 153 | destination, | ||
1235 | 154 | ] | ||
1236 | 155 | subprocess.check_call(cmd) | ||
1237 | 156 | |||
1238 | 157 | |||
1239 | 158 | def mkdir(path, owner='root', group='root', perms=0o555, force=False): | ||
1240 | 159 | """Create a directory""" | ||
1241 | 160 | log("Making dir {} {}:{} {:o}".format(path, owner, group, | ||
1242 | 161 | perms)) | ||
1243 | 162 | uid = pwd.getpwnam(owner).pw_uid | ||
1244 | 163 | gid = grp.getgrnam(group).gr_gid | ||
1245 | 164 | realpath = os.path.abspath(path) | ||
1246 | 165 | path_exists = os.path.exists(realpath) | ||
1247 | 166 | if path_exists and force: | ||
1248 | 167 | if not os.path.isdir(realpath): | ||
1249 | 168 | log("Removing non-directory file {} prior to mkdir()".format(path)) | ||
1250 | 169 | os.unlink(realpath) | ||
1251 | 170 | os.makedirs(realpath, perms) | ||
1252 | 171 | os.chown(realpath, uid, gid) | ||
1253 | 172 | elif not path_exists: | ||
1254 | 173 | os.makedirs(realpath, perms) | ||
1255 | 174 | os.chown(realpath, uid, gid) | ||
1256 | 175 | |||
1257 | 176 | |||
1258 | 177 | def write_file(path, content, owner='root', group='root', perms=0o444): | ||
1259 | 178 | """Create or overwrite a file with the contents of a string""" | ||
1260 | 179 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) | ||
1261 | 180 | uid = pwd.getpwnam(owner).pw_uid | ||
1262 | 181 | gid = grp.getgrnam(group).gr_gid | ||
1263 | 182 | with open(path, 'w') as target: | ||
1264 | 183 | os.fchown(target.fileno(), uid, gid) | ||
1265 | 184 | os.fchmod(target.fileno(), perms) | ||
1266 | 185 | target.write(content) | ||
1267 | 186 | |||
1268 | 187 | |||
1269 | 188 | def fstab_remove(mp): | ||
1270 | 189 | """Remove the given mountpoint entry from /etc/fstab | ||
1271 | 190 | """ | ||
1272 | 191 | return Fstab.remove_by_mountpoint(mp) | ||
1273 | 192 | |||
1274 | 193 | |||
1275 | 194 | def fstab_add(dev, mp, fs, options=None): | ||
1276 | 195 | """Adds the given device entry to the /etc/fstab file | ||
1277 | 196 | """ | ||
1278 | 197 | return Fstab.add(dev, mp, fs, options=options) | ||
1279 | 198 | |||
1280 | 199 | |||
1281 | 200 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): | ||
1282 | 201 | """Mount a filesystem at a particular mountpoint""" | ||
1283 | 202 | cmd_args = ['mount'] | ||
1284 | 203 | if options is not None: | ||
1285 | 204 | cmd_args.extend(['-o', options]) | ||
1286 | 205 | cmd_args.extend([device, mountpoint]) | ||
1287 | 206 | try: | ||
1288 | 207 | subprocess.check_output(cmd_args) | ||
1289 | 208 | except subprocess.CalledProcessError as e: | ||
1290 | 209 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | ||
1291 | 210 | return False | ||
1292 | 211 | |||
1293 | 212 | if persist: | ||
1294 | 213 | return fstab_add(device, mountpoint, filesystem, options=options) | ||
1295 | 214 | return True | ||
1296 | 215 | |||
1297 | 216 | |||
1298 | 217 | def umount(mountpoint, persist=False): | ||
1299 | 218 | """Unmount a filesystem""" | ||
1300 | 219 | cmd_args = ['umount', mountpoint] | ||
1301 | 220 | try: | ||
1302 | 221 | subprocess.check_output(cmd_args) | ||
1303 | 222 | except subprocess.CalledProcessError as e: | ||
1304 | 223 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | ||
1305 | 224 | return False | ||
1306 | 225 | |||
1307 | 226 | if persist: | ||
1308 | 227 | return fstab_remove(mountpoint) | ||
1309 | 228 | return True | ||
1310 | 229 | |||
1311 | 230 | |||
1312 | 231 | def mounts(): | ||
1313 | 232 | """Get a list of all mounted volumes as [[mountpoint,device],[...]]""" | ||
1314 | 233 | with open('/proc/mounts') as f: | ||
1315 | 234 | # [['/mount/point','/dev/path'],[...]] | ||
1316 | 235 | system_mounts = [m[1::-1] for m in [l.strip().split() | ||
1317 | 236 | for l in f.readlines()]] | ||
1318 | 237 | return system_mounts | ||
1319 | 238 | |||
1320 | 239 | |||
1321 | 240 | def file_hash(path, hash_type='md5'): | ||
1322 | 241 | """ | ||
1323 | 242 | Generate a hash checksum of the contents of 'path' or None if not found. | ||
1324 | 243 | |||
1325 | 244 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
1326 | 245 | such as md5, sha1, sha256, sha512, etc. | ||
1327 | 246 | """ | ||
1328 | 247 | if os.path.exists(path): | ||
1329 | 248 | h = getattr(hashlib, hash_type)() | ||
1330 | 249 | with open(path, 'rb') as source: | ||
1331 | 250 | h.update(source.read()) | ||
1332 | 251 | return h.hexdigest() | ||
1333 | 252 | else: | ||
1334 | 253 | return None | ||
1335 | 254 | |||
1336 | 255 | |||
1337 | 256 | def check_hash(path, checksum, hash_type='md5'): | ||
1338 | 257 | """ | ||
1339 | 258 | Validate a file using a cryptographic checksum. | ||
1340 | 259 | |||
1341 | 260 | :param str checksum: Value of the checksum used to validate the file. | ||
1342 | 261 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
1343 | 262 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
1344 | 263 | such as md5, sha1, sha256, sha512, etc. | ||
1345 | 264 | :raises ChecksumError: If the file fails the checksum | ||
1346 | 265 | |||
1347 | 266 | """ | ||
1348 | 267 | actual_checksum = file_hash(path, hash_type) | ||
1349 | 268 | if checksum != actual_checksum: | ||
1350 | 269 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
1351 | 270 | |||
1352 | 271 | |||
1353 | 272 | class ChecksumError(ValueError): | ||
1354 | 273 | pass | ||
1355 | 274 | |||
1356 | 275 | |||
1357 | 276 | def restart_on_change(restart_map, stopstart=False): | ||
1358 | 277 | """Restart services based on configuration files changing | ||
1359 | 278 | |||
1360 | 279 | This function is used a decorator, for example:: | ||
1361 | 280 | |||
1362 | 281 | @restart_on_change({ | ||
1363 | 282 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] | ||
1364 | 283 | }) | ||
1365 | 284 | def ceph_client_changed(): | ||
1366 | 285 | pass # your code here | ||
1367 | 286 | |||
1368 | 287 | In this example, the cinder-api and cinder-volume services | ||
1369 | 288 | would be restarted if /etc/ceph/ceph.conf is changed by the | ||
1370 | 289 | ceph_client_changed function. | ||
1371 | 290 | """ | ||
1372 | 291 | def wrap(f): | ||
1373 | 292 | def wrapped_f(*args): | ||
1374 | 293 | checksums = {} | ||
1375 | 294 | for path in restart_map: | ||
1376 | 295 | checksums[path] = file_hash(path) | ||
1377 | 296 | f(*args) | ||
1378 | 297 | restarts = [] | ||
1379 | 298 | for path in restart_map: | ||
1380 | 299 | if checksums[path] != file_hash(path): | ||
1381 | 300 | restarts += restart_map[path] | ||
1382 | 301 | services_list = list(OrderedDict.fromkeys(restarts)) | ||
1383 | 302 | if not stopstart: | ||
1384 | 303 | for service_name in services_list: | ||
1385 | 304 | service('restart', service_name) | ||
1386 | 305 | else: | ||
1387 | 306 | for action in ['stop', 'start']: | ||
1388 | 307 | for service_name in services_list: | ||
1389 | 308 | service(action, service_name) | ||
1390 | 309 | return wrapped_f | ||
1391 | 310 | return wrap | ||
1392 | 311 | |||
1393 | 312 | |||
1394 | 313 | def lsb_release(): | ||
1395 | 314 | """Return /etc/lsb-release in a dict""" | ||
1396 | 315 | d = {} | ||
1397 | 316 | with open('/etc/lsb-release', 'r') as lsb: | ||
1398 | 317 | for l in lsb: | ||
1399 | 318 | k, v = l.split('=') | ||
1400 | 319 | d[k.strip()] = v.strip() | ||
1401 | 320 | return d | ||
1402 | 321 | |||
1403 | 322 | |||
1404 | 323 | def pwgen(length=None): | ||
1405 | 324 | """Generate a random pasword.""" | ||
1406 | 325 | if length is None: | ||
1407 | 326 | length = random.choice(range(35, 45)) | ||
1408 | 327 | alphanumeric_chars = [ | ||
1409 | 328 | l for l in (string.ascii_letters + string.digits) | ||
1410 | 329 | if l not in 'l0QD1vAEIOUaeiou'] | ||
1411 | 330 | random_chars = [ | ||
1412 | 331 | random.choice(alphanumeric_chars) for _ in range(length)] | ||
1413 | 332 | return(''.join(random_chars)) | ||
1414 | 333 | |||
1415 | 334 | |||
1416 | 335 | def list_nics(nic_type): | ||
1417 | 336 | '''Return a list of nics of given type(s)''' | ||
1418 | 337 | if isinstance(nic_type, six.string_types): | ||
1419 | 338 | int_types = [nic_type] | ||
1420 | 339 | else: | ||
1421 | 340 | int_types = nic_type | ||
1422 | 341 | interfaces = [] | ||
1423 | 342 | for int_type in int_types: | ||
1424 | 343 | cmd = ['ip', 'addr', 'show', 'label', int_type + '*'] | ||
1425 | 344 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
1426 | 345 | ip_output = (line for line in ip_output if line) | ||
1427 | 346 | for line in ip_output: | ||
1428 | 347 | if line.split()[1].startswith(int_type): | ||
1429 | 348 | matched = re.search('.*: (bond[0-9]+\.[0-9]+)@.*', line) | ||
1430 | 349 | if matched: | ||
1431 | 350 | interface = matched.groups()[0] | ||
1432 | 351 | else: | ||
1433 | 352 | interface = line.split()[1].replace(":", "") | ||
1434 | 353 | interfaces.append(interface) | ||
1435 | 354 | |||
1436 | 355 | return interfaces | ||
1437 | 356 | |||
1438 | 357 | |||
1439 | 358 | def set_nic_mtu(nic, mtu): | ||
1440 | 359 | '''Set MTU on a network interface''' | ||
1441 | 360 | cmd = ['ip', 'link', 'set', nic, 'mtu', mtu] | ||
1442 | 361 | subprocess.check_call(cmd) | ||
1443 | 362 | |||
1444 | 363 | |||
1445 | 364 | def get_nic_mtu(nic): | ||
1446 | 365 | cmd = ['ip', 'addr', 'show', nic] | ||
1447 | 366 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
1448 | 367 | mtu = "" | ||
1449 | 368 | for line in ip_output: | ||
1450 | 369 | words = line.split() | ||
1451 | 370 | if 'mtu' in words: | ||
1452 | 371 | mtu = words[words.index("mtu") + 1] | ||
1453 | 372 | return mtu | ||
1454 | 373 | |||
1455 | 374 | |||
1456 | 375 | def get_nic_hwaddr(nic): | ||
1457 | 376 | cmd = ['ip', '-o', '-0', 'addr', 'show', nic] | ||
1458 | 377 | ip_output = subprocess.check_output(cmd).decode('UTF-8') | ||
1459 | 378 | hwaddr = "" | ||
1460 | 379 | words = ip_output.split() | ||
1461 | 380 | if 'link/ether' in words: | ||
1462 | 381 | hwaddr = words[words.index('link/ether') + 1] | ||
1463 | 382 | return hwaddr | ||
1464 | 383 | |||
1465 | 384 | |||
1466 | 385 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
1467 | 386 | '''Compare supplied revno with the revno of the installed package | ||
1468 | 387 | |||
1469 | 388 | * 1 => Installed revno is greater than supplied arg | ||
1470 | 389 | * 0 => Installed revno is the same as supplied arg | ||
1471 | 390 | * -1 => Installed revno is less than supplied arg | ||
1472 | 391 | |||
1473 | 392 | ''' | ||
1474 | 393 | import apt_pkg | ||
1475 | 394 | if not pkgcache: | ||
1476 | 395 | from charmhelpers.fetch import apt_cache | ||
1477 | 396 | pkgcache = apt_cache() | ||
1478 | 397 | pkg = pkgcache[package] | ||
1479 | 398 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | ||
1480 | 399 | |||
1481 | 400 | |||
1482 | 401 | @contextmanager | ||
1483 | 402 | def chdir(d): | ||
1484 | 403 | cur = os.getcwd() | ||
1485 | 404 | try: | ||
1486 | 405 | yield os.chdir(d) | ||
1487 | 406 | finally: | ||
1488 | 407 | os.chdir(cur) | ||
1489 | 408 | |||
1490 | 409 | |||
1491 | 410 | def chownr(path, owner, group): | ||
1492 | 411 | uid = pwd.getpwnam(owner).pw_uid | ||
1493 | 412 | gid = grp.getgrnam(group).gr_gid | ||
1494 | 413 | |||
1495 | 414 | for root, dirs, files in os.walk(path): | ||
1496 | 415 | for name in dirs + files: | ||
1497 | 416 | full = os.path.join(root, name) | ||
1498 | 417 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | ||
1499 | 418 | if not broken_symlink: | ||
1500 | 419 | os.chown(full, uid, gid) | ||
1501 | 0 | 420 | ||
1502 | === added directory 'hooks/charmhelpers/core/services' | |||
1503 | === added file 'hooks/charmhelpers/core/services/__init__.py' | |||
1504 | --- hooks/charmhelpers/core/services/__init__.py 1970-01-01 00:00:00 +0000 | |||
1505 | +++ hooks/charmhelpers/core/services/__init__.py 2015-01-20 18:33:44 +0000 | |||
1506 | @@ -0,0 +1,2 @@ | |||
1507 | 1 | from .base import * # NOQA | ||
1508 | 2 | from .helpers import * # NOQA | ||
1509 | 0 | 3 | ||
1510 | === added file 'hooks/charmhelpers/core/services/base.py' | |||
1511 | --- hooks/charmhelpers/core/services/base.py 1970-01-01 00:00:00 +0000 | |||
1512 | +++ hooks/charmhelpers/core/services/base.py 2015-01-20 18:33:44 +0000 | |||
1513 | @@ -0,0 +1,313 @@ | |||
1514 | 1 | import os | ||
1515 | 2 | import re | ||
1516 | 3 | import json | ||
1517 | 4 | from collections import Iterable | ||
1518 | 5 | |||
1519 | 6 | from charmhelpers.core import host | ||
1520 | 7 | from charmhelpers.core import hookenv | ||
1521 | 8 | |||
1522 | 9 | |||
1523 | 10 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
1524 | 11 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
1525 | 12 | 'service_restart', 'service_stop'] | ||
1526 | 13 | |||
1527 | 14 | |||
1528 | 15 | class ServiceManager(object): | ||
1529 | 16 | def __init__(self, services=None): | ||
1530 | 17 | """ | ||
1531 | 18 | Register a list of services, given their definitions. | ||
1532 | 19 | |||
1533 | 20 | Service definitions are dicts in the following formats (all keys except | ||
1534 | 21 | 'service' are optional):: | ||
1535 | 22 | |||
1536 | 23 | { | ||
1537 | 24 | "service": <service name>, | ||
1538 | 25 | "required_data": <list of required data contexts>, | ||
1539 | 26 | "provided_data": <list of provided data contexts>, | ||
1540 | 27 | "data_ready": <one or more callbacks>, | ||
1541 | 28 | "data_lost": <one or more callbacks>, | ||
1542 | 29 | "start": <one or more callbacks>, | ||
1543 | 30 | "stop": <one or more callbacks>, | ||
1544 | 31 | "ports": <list of ports to manage>, | ||
1545 | 32 | } | ||
1546 | 33 | |||
1547 | 34 | The 'required_data' list should contain dicts of required data (or | ||
1548 | 35 | dependency managers that act like dicts and know how to collect the data). | ||
1549 | 36 | Only when all items in the 'required_data' list are populated are the list | ||
1550 | 37 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
1551 | 38 | information. | ||
1552 | 39 | |||
1553 | 40 | The 'provided_data' list should contain relation data providers, most likely | ||
1554 | 41 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
1555 | 42 | that will indicate a set of data to set on a given relation. | ||
1556 | 43 | |||
1557 | 44 | The 'data_ready' value should be either a single callback, or a list of | ||
1558 | 45 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
1559 | 46 | Each callback will be called with the service name as the only parameter. | ||
1560 | 47 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
1561 | 48 | are fired. | ||
1562 | 49 | |||
1563 | 50 | The 'data_lost' value should be either a single callback, or a list of | ||
1564 | 51 | callbacks, to be called when a 'required_data' item no longer passes | ||
1565 | 52 | `is_ready()`. Each callback will be called with the service name as the | ||
1566 | 53 | only parameter. After all of the 'data_lost' callbacks are called, | ||
1567 | 54 | the 'stop' callbacks are fired. | ||
1568 | 55 | |||
1569 | 56 | The 'start' value should be either a single callback, or a list of | ||
1570 | 57 | callbacks, to be called when starting the service, after the 'data_ready' | ||
1571 | 58 | callbacks are complete. Each callback will be called with the service | ||
1572 | 59 | name as the only parameter. This defaults to | ||
1573 | 60 | `[host.service_start, services.open_ports]`. | ||
1574 | 61 | |||
1575 | 62 | The 'stop' value should be either a single callback, or a list of | ||
1576 | 63 | callbacks, to be called when stopping the service. If the service is | ||
1577 | 64 | being stopped because it no longer has all of its 'required_data', this | ||
1578 | 65 | will be called after all of the 'data_lost' callbacks are complete. | ||
1579 | 66 | Each callback will be called with the service name as the only parameter. | ||
1580 | 67 | This defaults to `[services.close_ports, host.service_stop]`. | ||
1581 | 68 | |||
1582 | 69 | The 'ports' value should be a list of ports to manage. The default | ||
1583 | 70 | 'start' handler will open the ports after the service is started, | ||
1584 | 71 | and the default 'stop' handler will close the ports prior to stopping | ||
1585 | 72 | the service. | ||
1586 | 73 | |||
1587 | 74 | |||
1588 | 75 | Examples: | ||
1589 | 76 | |||
1590 | 77 | The following registers an Upstart service called bingod that depends on | ||
1591 | 78 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
1592 | 79 | restarting the service, and a Runit service called spadesd:: | ||
1593 | 80 | |||
1594 | 81 | manager = services.ServiceManager([ | ||
1595 | 82 | { | ||
1596 | 83 | 'service': 'bingod', | ||
1597 | 84 | 'ports': [80, 443], | ||
1598 | 85 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
1599 | 86 | 'data_ready': [ | ||
1600 | 87 | services.template(source='bingod.conf'), | ||
1601 | 88 | services.template(source='bingod.ini', | ||
1602 | 89 | target='/etc/bingod.ini', | ||
1603 | 90 | owner='bingo', perms=0400), | ||
1604 | 91 | ], | ||
1605 | 92 | }, | ||
1606 | 93 | { | ||
1607 | 94 | 'service': 'spadesd', | ||
1608 | 95 | 'data_ready': services.template(source='spadesd_run.j2', | ||
1609 | 96 | target='/etc/sv/spadesd/run', | ||
1610 | 97 | perms=0555), | ||
1611 | 98 | 'start': runit_start, | ||
1612 | 99 | 'stop': runit_stop, | ||
1613 | 100 | }, | ||
1614 | 101 | ]) | ||
1615 | 102 | manager.manage() | ||
1616 | 103 | """ | ||
1617 | 104 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
1618 | 105 | self._ready = None | ||
1619 | 106 | self.services = {} | ||
1620 | 107 | for service in services or []: | ||
1621 | 108 | service_name = service['service'] | ||
1622 | 109 | self.services[service_name] = service | ||
1623 | 110 | |||
1624 | 111 | def manage(self): | ||
1625 | 112 | """ | ||
1626 | 113 | Handle the current hook by doing The Right Thing with the registered services. | ||
1627 | 114 | """ | ||
1628 | 115 | hook_name = hookenv.hook_name() | ||
1629 | 116 | if hook_name == 'stop': | ||
1630 | 117 | self.stop_services() | ||
1631 | 118 | else: | ||
1632 | 119 | self.provide_data() | ||
1633 | 120 | self.reconfigure_services() | ||
1634 | 121 | cfg = hookenv.config() | ||
1635 | 122 | if cfg.implicit_save: | ||
1636 | 123 | cfg.save() | ||
1637 | 124 | |||
1638 | 125 | def provide_data(self): | ||
1639 | 126 | """ | ||
1640 | 127 | Set the relation data for each provider in the ``provided_data`` list. | ||
1641 | 128 | |||
1642 | 129 | A provider must have a `name` attribute, which indicates which relation | ||
1643 | 130 | to set data on, and a `provide_data()` method, which returns a dict of | ||
1644 | 131 | data to set. | ||
1645 | 132 | """ | ||
1646 | 133 | hook_name = hookenv.hook_name() | ||
1647 | 134 | for service in self.services.values(): | ||
1648 | 135 | for provider in service.get('provided_data', []): | ||
1649 | 136 | if re.match(r'{}-relation-(joined|changed)'.format(provider.name), hook_name): | ||
1650 | 137 | data = provider.provide_data() | ||
1651 | 138 | _ready = provider._is_ready(data) if hasattr(provider, '_is_ready') else data | ||
1652 | 139 | if _ready: | ||
1653 | 140 | hookenv.relation_set(None, data) | ||
1654 | 141 | |||
1655 | 142 | def reconfigure_services(self, *service_names): | ||
1656 | 143 | """ | ||
1657 | 144 | Update all files for one or more registered services, and, | ||
1658 | 145 | if ready, optionally restart them. | ||
1659 | 146 | |||
1660 | 147 | If no service names are given, reconfigures all registered services. | ||
1661 | 148 | """ | ||
1662 | 149 | for service_name in service_names or self.services.keys(): | ||
1663 | 150 | if self.is_ready(service_name): | ||
1664 | 151 | self.fire_event('data_ready', service_name) | ||
1665 | 152 | self.fire_event('start', service_name, default=[ | ||
1666 | 153 | service_restart, | ||
1667 | 154 | manage_ports]) | ||
1668 | 155 | self.save_ready(service_name) | ||
1669 | 156 | else: | ||
1670 | 157 | if self.was_ready(service_name): | ||
1671 | 158 | self.fire_event('data_lost', service_name) | ||
1672 | 159 | self.fire_event('stop', service_name, default=[ | ||
1673 | 160 | manage_ports, | ||
1674 | 161 | service_stop]) | ||
1675 | 162 | self.save_lost(service_name) | ||
1676 | 163 | |||
1677 | 164 | def stop_services(self, *service_names): | ||
1678 | 165 | """ | ||
1679 | 166 | Stop one or more registered services, by name. | ||
1680 | 167 | |||
1681 | 168 | If no service names are given, stops all registered services. | ||
1682 | 169 | """ | ||
1683 | 170 | for service_name in service_names or self.services.keys(): | ||
1684 | 171 | self.fire_event('stop', service_name, default=[ | ||
1685 | 172 | manage_ports, | ||
1686 | 173 | service_stop]) | ||
1687 | 174 | |||
1688 | 175 | def get_service(self, service_name): | ||
1689 | 176 | """ | ||
1690 | 177 | Given the name of a registered service, return its service definition. | ||
1691 | 178 | """ | ||
1692 | 179 | service = self.services.get(service_name) | ||
1693 | 180 | if not service: | ||
1694 | 181 | raise KeyError('Service not registered: %s' % service_name) | ||
1695 | 182 | return service | ||
1696 | 183 | |||
1697 | 184 | def fire_event(self, event_name, service_name, default=None): | ||
1698 | 185 | """ | ||
1699 | 186 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
1700 | 187 | """ | ||
1701 | 188 | service = self.get_service(service_name) | ||
1702 | 189 | callbacks = service.get(event_name, default) | ||
1703 | 190 | if not callbacks: | ||
1704 | 191 | return | ||
1705 | 192 | if not isinstance(callbacks, Iterable): | ||
1706 | 193 | callbacks = [callbacks] | ||
1707 | 194 | for callback in callbacks: | ||
1708 | 195 | if isinstance(callback, ManagerCallback): | ||
1709 | 196 | callback(self, service_name, event_name) | ||
1710 | 197 | else: | ||
1711 | 198 | callback(service_name) | ||
1712 | 199 | |||
1713 | 200 | def is_ready(self, service_name): | ||
1714 | 201 | """ | ||
1715 | 202 | Determine if a registered service is ready, by checking its 'required_data'. | ||
1716 | 203 | |||
1717 | 204 | A 'required_data' item can be any mapping type, and is considered ready | ||
1718 | 205 | if `bool(item)` evaluates as True. | ||
1719 | 206 | """ | ||
1720 | 207 | service = self.get_service(service_name) | ||
1721 | 208 | reqs = service.get('required_data', []) | ||
1722 | 209 | return all(bool(req) for req in reqs) | ||
1723 | 210 | |||
1724 | 211 | def _load_ready_file(self): | ||
1725 | 212 | if self._ready is not None: | ||
1726 | 213 | return | ||
1727 | 214 | if os.path.exists(self._ready_file): | ||
1728 | 215 | with open(self._ready_file) as fp: | ||
1729 | 216 | self._ready = set(json.load(fp)) | ||
1730 | 217 | else: | ||
1731 | 218 | self._ready = set() | ||
1732 | 219 | |||
1733 | 220 | def _save_ready_file(self): | ||
1734 | 221 | if self._ready is None: | ||
1735 | 222 | return | ||
1736 | 223 | with open(self._ready_file, 'w') as fp: | ||
1737 | 224 | json.dump(list(self._ready), fp) | ||
1738 | 225 | |||
1739 | 226 | def save_ready(self, service_name): | ||
1740 | 227 | """ | ||
1741 | 228 | Save an indicator that the given service is now data_ready. | ||
1742 | 229 | """ | ||
1743 | 230 | self._load_ready_file() | ||
1744 | 231 | self._ready.add(service_name) | ||
1745 | 232 | self._save_ready_file() | ||
1746 | 233 | |||
1747 | 234 | def save_lost(self, service_name): | ||
1748 | 235 | """ | ||
1749 | 236 | Save an indicator that the given service is no longer data_ready. | ||
1750 | 237 | """ | ||
1751 | 238 | self._load_ready_file() | ||
1752 | 239 | self._ready.discard(service_name) | ||
1753 | 240 | self._save_ready_file() | ||
1754 | 241 | |||
1755 | 242 | def was_ready(self, service_name): | ||
1756 | 243 | """ | ||
1757 | 244 | Determine if the given service was previously data_ready. | ||
1758 | 245 | """ | ||
1759 | 246 | self._load_ready_file() | ||
1760 | 247 | return service_name in self._ready | ||
1761 | 248 | |||
1762 | 249 | |||
1763 | 250 | class ManagerCallback(object): | ||
1764 | 251 | """ | ||
1765 | 252 | Special case of a callback that takes the `ServiceManager` instance | ||
1766 | 253 | in addition to the service name. | ||
1767 | 254 | |||
1768 | 255 | Subclasses should implement `__call__` which should accept three parameters: | ||
1769 | 256 | |||
1770 | 257 | * `manager` The `ServiceManager` instance | ||
1771 | 258 | * `service_name` The name of the service it's being triggered for | ||
1772 | 259 | * `event_name` The name of the event that this callback is handling | ||
1773 | 260 | """ | ||
1774 | 261 | def __call__(self, manager, service_name, event_name): | ||
1775 | 262 | raise NotImplementedError() | ||
1776 | 263 | |||
1777 | 264 | |||
1778 | 265 | class PortManagerCallback(ManagerCallback): | ||
1779 | 266 | """ | ||
1780 | 267 | Callback class that will open or close ports, for use as either | ||
1781 | 268 | a start or stop action. | ||
1782 | 269 | """ | ||
1783 | 270 | def __call__(self, manager, service_name, event_name): | ||
1784 | 271 | service = manager.get_service(service_name) | ||
1785 | 272 | new_ports = service.get('ports', []) | ||
1786 | 273 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
1787 | 274 | if os.path.exists(port_file): | ||
1788 | 275 | with open(port_file) as fp: | ||
1789 | 276 | old_ports = fp.read().split(',') | ||
1790 | 277 | for old_port in old_ports: | ||
1791 | 278 | if bool(old_port): | ||
1792 | 279 | old_port = int(old_port) | ||
1793 | 280 | if old_port not in new_ports: | ||
1794 | 281 | hookenv.close_port(old_port) | ||
1795 | 282 | with open(port_file, 'w') as fp: | ||
1796 | 283 | fp.write(','.join(str(port) for port in new_ports)) | ||
1797 | 284 | for port in new_ports: | ||
1798 | 285 | if event_name == 'start': | ||
1799 | 286 | hookenv.open_port(port) | ||
1800 | 287 | elif event_name == 'stop': | ||
1801 | 288 | hookenv.close_port(port) | ||
1802 | 289 | |||
1803 | 290 | |||
1804 | 291 | def service_stop(service_name): | ||
1805 | 292 | """ | ||
1806 | 293 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
1807 | 294 | messages in the logs. | ||
1808 | 295 | """ | ||
1809 | 296 | if host.service_running(service_name): | ||
1810 | 297 | host.service_stop(service_name) | ||
1811 | 298 | |||
1812 | 299 | |||
1813 | 300 | def service_restart(service_name): | ||
1814 | 301 | """ | ||
1815 | 302 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
1816 | 303 | messages in the logs. | ||
1817 | 304 | """ | ||
1818 | 305 | if host.service_available(service_name): | ||
1819 | 306 | if host.service_running(service_name): | ||
1820 | 307 | host.service_restart(service_name) | ||
1821 | 308 | else: | ||
1822 | 309 | host.service_start(service_name) | ||
1823 | 310 | |||
1824 | 311 | |||
1825 | 312 | # Convenience aliases | ||
1826 | 313 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
1827 | 0 | 314 | ||
1828 | === added file 'hooks/charmhelpers/core/services/helpers.py' | |||
1829 | --- hooks/charmhelpers/core/services/helpers.py 1970-01-01 00:00:00 +0000 | |||
1830 | +++ hooks/charmhelpers/core/services/helpers.py 2015-01-20 18:33:44 +0000 | |||
1831 | @@ -0,0 +1,243 @@ | |||
1832 | 1 | import os | ||
1833 | 2 | import yaml | ||
1834 | 3 | from charmhelpers.core import hookenv | ||
1835 | 4 | from charmhelpers.core import templating | ||
1836 | 5 | |||
1837 | 6 | from charmhelpers.core.services.base import ManagerCallback | ||
1838 | 7 | |||
1839 | 8 | |||
1840 | 9 | __all__ = ['RelationContext', 'TemplateCallback', | ||
1841 | 10 | 'render_template', 'template'] | ||
1842 | 11 | |||
1843 | 12 | |||
1844 | 13 | class RelationContext(dict): | ||
1845 | 14 | """ | ||
1846 | 15 | Base class for a context generator that gets relation data from juju. | ||
1847 | 16 | |||
1848 | 17 | Subclasses must provide the attributes `name`, which is the name of the | ||
1849 | 18 | interface of interest, `interface`, which is the type of the interface of | ||
1850 | 19 | interest, and `required_keys`, which is the set of keys required for the | ||
1851 | 20 | relation to be considered complete. The data for all interfaces matching | ||
1852 | 21 | the `name` attribute that are complete will used to populate the dictionary | ||
1853 | 22 | values (see `get_data`, below). | ||
1854 | 23 | |||
1855 | 24 | The generated context will be namespaced under the relation :attr:`name`, | ||
1856 | 25 | to prevent potential naming conflicts. | ||
1857 | 26 | |||
1858 | 27 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1859 | 28 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1860 | 29 | """ | ||
1861 | 30 | name = None | ||
1862 | 31 | interface = None | ||
1863 | 32 | required_keys = [] | ||
1864 | 33 | |||
1865 | 34 | def __init__(self, name=None, additional_required_keys=None): | ||
1866 | 35 | if name is not None: | ||
1867 | 36 | self.name = name | ||
1868 | 37 | if additional_required_keys is not None: | ||
1869 | 38 | self.required_keys.extend(additional_required_keys) | ||
1870 | 39 | self.get_data() | ||
1871 | 40 | |||
1872 | 41 | def __bool__(self): | ||
1873 | 42 | """ | ||
1874 | 43 | Returns True if all of the required_keys are available. | ||
1875 | 44 | """ | ||
1876 | 45 | return self.is_ready() | ||
1877 | 46 | |||
1878 | 47 | __nonzero__ = __bool__ | ||
1879 | 48 | |||
1880 | 49 | def __repr__(self): | ||
1881 | 50 | return super(RelationContext, self).__repr__() | ||
1882 | 51 | |||
1883 | 52 | def is_ready(self): | ||
1884 | 53 | """ | ||
1885 | 54 | Returns True if all of the `required_keys` are available from any units. | ||
1886 | 55 | """ | ||
1887 | 56 | ready = len(self.get(self.name, [])) > 0 | ||
1888 | 57 | if not ready: | ||
1889 | 58 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
1890 | 59 | return ready | ||
1891 | 60 | |||
1892 | 61 | def _is_ready(self, unit_data): | ||
1893 | 62 | """ | ||
1894 | 63 | Helper method that tests a set of relation data and returns True if | ||
1895 | 64 | all of the `required_keys` are present. | ||
1896 | 65 | """ | ||
1897 | 66 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
1898 | 67 | |||
1899 | 68 | def get_data(self): | ||
1900 | 69 | """ | ||
1901 | 70 | Retrieve the relation data for each unit involved in a relation and, | ||
1902 | 71 | if complete, store it in a list under `self[self.name]`. This | ||
1903 | 72 | is automatically called when the RelationContext is instantiated. | ||
1904 | 73 | |||
1905 | 74 | The units are sorted lexographically first by the service ID, then by | ||
1906 | 75 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
1907 | 76 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
1908 | 77 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
1909 | 78 | set of data, the relation data for the units will be stored in the | ||
1910 | 79 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
1911 | 80 | |||
1912 | 81 | If you only care about a single unit on the relation, you can just | ||
1913 | 82 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
1914 | 83 | support multiple units on a relation, you should iterate over the list, | ||
1915 | 84 | like:: | ||
1916 | 85 | |||
1917 | 86 | {% for unit in interface -%} | ||
1918 | 87 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
1919 | 88 | {%- endfor %} | ||
1920 | 89 | |||
1921 | 90 | Note that since all sets of relation data from all related services and | ||
1922 | 91 | units are in a single list, if you need to know which service or unit a | ||
1923 | 92 | set of data came from, you'll need to extend this class to preserve | ||
1924 | 93 | that information. | ||
1925 | 94 | """ | ||
1926 | 95 | if not hookenv.relation_ids(self.name): | ||
1927 | 96 | return | ||
1928 | 97 | |||
1929 | 98 | ns = self.setdefault(self.name, []) | ||
1930 | 99 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
1931 | 100 | for unit in sorted(hookenv.related_units(rid)): | ||
1932 | 101 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
1933 | 102 | if self._is_ready(reldata): | ||
1934 | 103 | ns.append(reldata) | ||
1935 | 104 | |||
1936 | 105 | def provide_data(self): | ||
1937 | 106 | """ | ||
1938 | 107 | Return data to be relation_set for this interface. | ||
1939 | 108 | """ | ||
1940 | 109 | return {} | ||
1941 | 110 | |||
1942 | 111 | |||
1943 | 112 | class MysqlRelation(RelationContext): | ||
1944 | 113 | """ | ||
1945 | 114 | Relation context for the `mysql` interface. | ||
1946 | 115 | |||
1947 | 116 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1948 | 117 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1949 | 118 | """ | ||
1950 | 119 | name = 'db' | ||
1951 | 120 | interface = 'mysql' | ||
1952 | 121 | required_keys = ['host', 'user', 'password', 'database'] | ||
1953 | 122 | |||
1954 | 123 | |||
1955 | 124 | class HttpRelation(RelationContext): | ||
1956 | 125 | """ | ||
1957 | 126 | Relation context for the `http` interface. | ||
1958 | 127 | |||
1959 | 128 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
1960 | 129 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
1961 | 130 | """ | ||
1962 | 131 | name = 'website' | ||
1963 | 132 | interface = 'http' | ||
1964 | 133 | required_keys = ['host', 'port'] | ||
1965 | 134 | |||
1966 | 135 | def provide_data(self): | ||
1967 | 136 | return { | ||
1968 | 137 | 'host': hookenv.unit_get('private-address'), | ||
1969 | 138 | 'port': 80, | ||
1970 | 139 | } | ||
1971 | 140 | |||
1972 | 141 | |||
1973 | 142 | class RequiredConfig(dict): | ||
1974 | 143 | """ | ||
1975 | 144 | Data context that loads config options with one or more mandatory options. | ||
1976 | 145 | |||
1977 | 146 | Once the required options have been changed from their default values, all | ||
1978 | 147 | config options will be available, namespaced under `config` to prevent | ||
1979 | 148 | potential naming conflicts (for example, between a config option and a | ||
1980 | 149 | relation property). | ||
1981 | 150 | |||
1982 | 151 | :param list *args: List of options that must be changed from their default values. | ||
1983 | 152 | """ | ||
1984 | 153 | |||
1985 | 154 | def __init__(self, *args): | ||
1986 | 155 | self.required_options = args | ||
1987 | 156 | self['config'] = hookenv.config() | ||
1988 | 157 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
1989 | 158 | self.config = yaml.load(fp).get('options', {}) | ||
1990 | 159 | |||
1991 | 160 | def __bool__(self): | ||
1992 | 161 | for option in self.required_options: | ||
1993 | 162 | if option not in self['config']: | ||
1994 | 163 | return False | ||
1995 | 164 | current_value = self['config'][option] | ||
1996 | 165 | default_value = self.config[option].get('default') | ||
1997 | 166 | if current_value == default_value: | ||
1998 | 167 | return False | ||
1999 | 168 | if current_value in (None, '') and default_value in (None, ''): | ||
2000 | 169 | return False | ||
2001 | 170 | return True | ||
2002 | 171 | |||
2003 | 172 | def __nonzero__(self): | ||
2004 | 173 | return self.__bool__() | ||
2005 | 174 | |||
2006 | 175 | |||
2007 | 176 | class StoredContext(dict): | ||
2008 | 177 | """ | ||
2009 | 178 | A data context that always returns the data that it was first created with. | ||
2010 | 179 | |||
2011 | 180 | This is useful to do a one-time generation of things like passwords, that | ||
2012 | 181 | will thereafter use the same value that was originally generated, instead | ||
2013 | 182 | of generating a new value each time it is run. | ||
2014 | 183 | """ | ||
2015 | 184 | def __init__(self, file_name, config_data): | ||
2016 | 185 | """ | ||
2017 | 186 | If the file exists, populate `self` with the data from the file. | ||
2018 | 187 | Otherwise, populate with the given data and persist it to the file. | ||
2019 | 188 | """ | ||
2020 | 189 | if os.path.exists(file_name): | ||
2021 | 190 | self.update(self.read_context(file_name)) | ||
2022 | 191 | else: | ||
2023 | 192 | self.store_context(file_name, config_data) | ||
2024 | 193 | self.update(config_data) | ||
2025 | 194 | |||
2026 | 195 | def store_context(self, file_name, config_data): | ||
2027 | 196 | if not os.path.isabs(file_name): | ||
2028 | 197 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
2029 | 198 | with open(file_name, 'w') as file_stream: | ||
2030 | 199 | os.fchmod(file_stream.fileno(), 0o600) | ||
2031 | 200 | yaml.dump(config_data, file_stream) | ||
2032 | 201 | |||
2033 | 202 | def read_context(self, file_name): | ||
2034 | 203 | if not os.path.isabs(file_name): | ||
2035 | 204 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
2036 | 205 | with open(file_name, 'r') as file_stream: | ||
2037 | 206 | data = yaml.load(file_stream) | ||
2038 | 207 | if not data: | ||
2039 | 208 | raise OSError("%s is empty" % file_name) | ||
2040 | 209 | return data | ||
2041 | 210 | |||
2042 | 211 | |||
2043 | 212 | class TemplateCallback(ManagerCallback): | ||
2044 | 213 | """ | ||
2045 | 214 | Callback class that will render a Jinja2 template, for use as a ready | ||
2046 | 215 | action. | ||
2047 | 216 | |||
2048 | 217 | :param str source: The template source file, relative to | ||
2049 | 218 | `$CHARM_DIR/templates` | ||
2050 | 219 | |||
2051 | 220 | :param str target: The target to write the rendered template to | ||
2052 | 221 | :param str owner: The owner of the rendered file | ||
2053 | 222 | :param str group: The group of the rendered file | ||
2054 | 223 | :param int perms: The permissions of the rendered file | ||
2055 | 224 | """ | ||
2056 | 225 | def __init__(self, source, target, | ||
2057 | 226 | owner='root', group='root', perms=0o444): | ||
2058 | 227 | self.source = source | ||
2059 | 228 | self.target = target | ||
2060 | 229 | self.owner = owner | ||
2061 | 230 | self.group = group | ||
2062 | 231 | self.perms = perms | ||
2063 | 232 | |||
2064 | 233 | def __call__(self, manager, service_name, event_name): | ||
2065 | 234 | service = manager.get_service(service_name) | ||
2066 | 235 | context = {} | ||
2067 | 236 | for ctx in service.get('required_data', []): | ||
2068 | 237 | context.update(ctx) | ||
2069 | 238 | templating.render(self.source, self.target, context, | ||
2070 | 239 | self.owner, self.group, self.perms) | ||
2071 | 240 | |||
2072 | 241 | |||
2073 | 242 | # Convenience aliases for templates | ||
2074 | 243 | render_template = template = TemplateCallback | ||
2075 | 0 | 244 | ||
2076 | === added file 'hooks/charmhelpers/core/sysctl.py' | |||
2077 | --- hooks/charmhelpers/core/sysctl.py 1970-01-01 00:00:00 +0000 | |||
2078 | +++ hooks/charmhelpers/core/sysctl.py 2015-01-20 18:33:44 +0000 | |||
2079 | @@ -0,0 +1,34 @@ | |||
2080 | 1 | #!/usr/bin/env python | ||
2081 | 2 | # -*- coding: utf-8 -*- | ||
2082 | 3 | |||
2083 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
2084 | 5 | |||
2085 | 6 | import yaml | ||
2086 | 7 | |||
2087 | 8 | from subprocess import check_call | ||
2088 | 9 | |||
2089 | 10 | from charmhelpers.core.hookenv import ( | ||
2090 | 11 | log, | ||
2091 | 12 | DEBUG, | ||
2092 | 13 | ) | ||
2093 | 14 | |||
2094 | 15 | |||
2095 | 16 | def create(sysctl_dict, sysctl_file): | ||
2096 | 17 | """Creates a sysctl.conf file from a YAML associative array | ||
2097 | 18 | |||
2098 | 19 | :param sysctl_dict: a dict of sysctl options eg { 'kernel.max_pid': 1337 } | ||
2099 | 20 | :type sysctl_dict: dict | ||
2100 | 21 | :param sysctl_file: path to the sysctl file to be saved | ||
2101 | 22 | :type sysctl_file: str or unicode | ||
2102 | 23 | :returns: None | ||
2103 | 24 | """ | ||
2104 | 25 | sysctl_dict = yaml.load(sysctl_dict) | ||
2105 | 26 | |||
2106 | 27 | with open(sysctl_file, "w") as fd: | ||
2107 | 28 | for key, value in sysctl_dict.items(): | ||
2108 | 29 | fd.write("{}={}\n".format(key, value)) | ||
2109 | 30 | |||
2110 | 31 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict), | ||
2111 | 32 | level=DEBUG) | ||
2112 | 33 | |||
2113 | 34 | check_call(["sysctl", "-p", sysctl_file]) | ||
2114 | 0 | 35 | ||
2115 | === added file 'hooks/charmhelpers/core/templating.py' | |||
2116 | --- hooks/charmhelpers/core/templating.py 1970-01-01 00:00:00 +0000 | |||
2117 | +++ hooks/charmhelpers/core/templating.py 2015-01-20 18:33:44 +0000 | |||
2118 | @@ -0,0 +1,52 @@ | |||
2119 | 1 | import os | ||
2120 | 2 | |||
2121 | 3 | from charmhelpers.core import host | ||
2122 | 4 | from charmhelpers.core import hookenv | ||
2123 | 5 | |||
2124 | 6 | |||
2125 | 7 | def render(source, target, context, owner='root', group='root', | ||
2126 | 8 | perms=0o444, templates_dir=None): | ||
2127 | 9 | """ | ||
2128 | 10 | Render a template. | ||
2129 | 11 | |||
2130 | 12 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
2131 | 13 | |||
2132 | 14 | The `target` path should be absolute. | ||
2133 | 15 | |||
2134 | 16 | The context should be a dict containing the values to be replaced in the | ||
2135 | 17 | template. | ||
2136 | 18 | |||
2137 | 19 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
2138 | 20 | |||
2139 | 21 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
2140 | 22 | |||
2141 | 23 | Note: Using this requires python-jinja2; if it is not installed, calling | ||
2142 | 24 | this will attempt to use charmhelpers.fetch.apt_install to install it. | ||
2143 | 25 | """ | ||
2144 | 26 | try: | ||
2145 | 27 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2146 | 28 | except ImportError: | ||
2147 | 29 | try: | ||
2148 | 30 | from charmhelpers.fetch import apt_install | ||
2149 | 31 | except ImportError: | ||
2150 | 32 | hookenv.log('Could not import jinja2, and could not import ' | ||
2151 | 33 | 'charmhelpers.fetch to install it', | ||
2152 | 34 | level=hookenv.ERROR) | ||
2153 | 35 | raise | ||
2154 | 36 | apt_install('python-jinja2', fatal=True) | ||
2155 | 37 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2156 | 38 | |||
2157 | 39 | if templates_dir is None: | ||
2158 | 40 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
2159 | 41 | loader = Environment(loader=FileSystemLoader(templates_dir)) | ||
2160 | 42 | try: | ||
2161 | 43 | source = source | ||
2162 | 44 | template = loader.get_template(source) | ||
2163 | 45 | except exceptions.TemplateNotFound as e: | ||
2164 | 46 | hookenv.log('Could not load template %s from %s.' % | ||
2165 | 47 | (source, templates_dir), | ||
2166 | 48 | level=hookenv.ERROR) | ||
2167 | 49 | raise e | ||
2168 | 50 | content = template.render(context) | ||
2169 | 51 | host.mkdir(os.path.dirname(target), owner, group) | ||
2170 | 52 | host.write_file(target, content, owner, group, perms) | ||
2171 | 0 | 53 | ||
2172 | === added directory 'hooks/charmhelpers/fetch' | |||
2173 | === added file 'hooks/charmhelpers/fetch/__init__.py' | |||
2174 | --- hooks/charmhelpers/fetch/__init__.py 1970-01-01 00:00:00 +0000 | |||
2175 | +++ hooks/charmhelpers/fetch/__init__.py 2015-01-20 18:33:44 +0000 | |||
2176 | @@ -0,0 +1,423 @@ | |||
2177 | 1 | import importlib | ||
2178 | 2 | from tempfile import NamedTemporaryFile | ||
2179 | 3 | import time | ||
2180 | 4 | from yaml import safe_load | ||
2181 | 5 | from charmhelpers.core.host import ( | ||
2182 | 6 | lsb_release | ||
2183 | 7 | ) | ||
2184 | 8 | import subprocess | ||
2185 | 9 | from charmhelpers.core.hookenv import ( | ||
2186 | 10 | config, | ||
2187 | 11 | log, | ||
2188 | 12 | ) | ||
2189 | 13 | import os | ||
2190 | 14 | |||
2191 | 15 | import six | ||
2192 | 16 | if six.PY3: | ||
2193 | 17 | from urllib.parse import urlparse, urlunparse | ||
2194 | 18 | else: | ||
2195 | 19 | from urlparse import urlparse, urlunparse | ||
2196 | 20 | |||
2197 | 21 | |||
2198 | 22 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive | ||
2199 | 23 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main | ||
2200 | 24 | """ | ||
2201 | 25 | PROPOSED_POCKET = """# Proposed | ||
2202 | 26 | deb http://archive.ubuntu.com/ubuntu {}-proposed main universe multiverse restricted | ||
2203 | 27 | """ | ||
2204 | 28 | CLOUD_ARCHIVE_POCKETS = { | ||
2205 | 29 | # Folsom | ||
2206 | 30 | 'folsom': 'precise-updates/folsom', | ||
2207 | 31 | 'precise-folsom': 'precise-updates/folsom', | ||
2208 | 32 | 'precise-folsom/updates': 'precise-updates/folsom', | ||
2209 | 33 | 'precise-updates/folsom': 'precise-updates/folsom', | ||
2210 | 34 | 'folsom/proposed': 'precise-proposed/folsom', | ||
2211 | 35 | 'precise-folsom/proposed': 'precise-proposed/folsom', | ||
2212 | 36 | 'precise-proposed/folsom': 'precise-proposed/folsom', | ||
2213 | 37 | # Grizzly | ||
2214 | 38 | 'grizzly': 'precise-updates/grizzly', | ||
2215 | 39 | 'precise-grizzly': 'precise-updates/grizzly', | ||
2216 | 40 | 'precise-grizzly/updates': 'precise-updates/grizzly', | ||
2217 | 41 | 'precise-updates/grizzly': 'precise-updates/grizzly', | ||
2218 | 42 | 'grizzly/proposed': 'precise-proposed/grizzly', | ||
2219 | 43 | 'precise-grizzly/proposed': 'precise-proposed/grizzly', | ||
2220 | 44 | 'precise-proposed/grizzly': 'precise-proposed/grizzly', | ||
2221 | 45 | # Havana | ||
2222 | 46 | 'havana': 'precise-updates/havana', | ||
2223 | 47 | 'precise-havana': 'precise-updates/havana', | ||
2224 | 48 | 'precise-havana/updates': 'precise-updates/havana', | ||
2225 | 49 | 'precise-updates/havana': 'precise-updates/havana', | ||
2226 | 50 | 'havana/proposed': 'precise-proposed/havana', | ||
2227 | 51 | 'precise-havana/proposed': 'precise-proposed/havana', | ||
2228 | 52 | 'precise-proposed/havana': 'precise-proposed/havana', | ||
2229 | 53 | # Icehouse | ||
2230 | 54 | 'icehouse': 'precise-updates/icehouse', | ||
2231 | 55 | 'precise-icehouse': 'precise-updates/icehouse', | ||
2232 | 56 | 'precise-icehouse/updates': 'precise-updates/icehouse', | ||
2233 | 57 | 'precise-updates/icehouse': 'precise-updates/icehouse', | ||
2234 | 58 | 'icehouse/proposed': 'precise-proposed/icehouse', | ||
2235 | 59 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', | ||
2236 | 60 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', | ||
2237 | 61 | # Juno | ||
2238 | 62 | 'juno': 'trusty-updates/juno', | ||
2239 | 63 | 'trusty-juno': 'trusty-updates/juno', | ||
2240 | 64 | 'trusty-juno/updates': 'trusty-updates/juno', | ||
2241 | 65 | 'trusty-updates/juno': 'trusty-updates/juno', | ||
2242 | 66 | 'juno/proposed': 'trusty-proposed/juno', | ||
2243 | 67 | 'trusty-juno/proposed': 'trusty-proposed/juno', | ||
2244 | 68 | 'trusty-proposed/juno': 'trusty-proposed/juno', | ||
2245 | 69 | # Kilo | ||
2246 | 70 | 'kilo': 'trusty-updates/kilo', | ||
2247 | 71 | 'trusty-kilo': 'trusty-updates/kilo', | ||
2248 | 72 | 'trusty-kilo/updates': 'trusty-updates/kilo', | ||
2249 | 73 | 'trusty-updates/kilo': 'trusty-updates/kilo', | ||
2250 | 74 | 'kilo/proposed': 'trusty-proposed/kilo', | ||
2251 | 75 | 'trusty-kilo/proposed': 'trusty-proposed/kilo', | ||
2252 | 76 | 'trusty-proposed/kilo': 'trusty-proposed/kilo', | ||
2253 | 77 | } | ||
2254 | 78 | |||
2255 | 79 | # The order of this list is very important. Handlers should be listed in from | ||
2256 | 80 | # least- to most-specific URL matching. | ||
2257 | 81 | FETCH_HANDLERS = ( | ||
2258 | 82 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
2259 | 83 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
2260 | 84 | 'charmhelpers.fetch.giturl.GitUrlFetchHandler', | ||
2261 | 85 | ) | ||
2262 | 86 | |||
2263 | 87 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. | ||
2264 | 88 | APT_NO_LOCK_RETRY_DELAY = 10 # Wait 10 seconds between apt lock checks. | ||
2265 | 89 | APT_NO_LOCK_RETRY_COUNT = 30 # Retry to acquire the lock X times. | ||
2266 | 90 | |||
2267 | 91 | |||
2268 | 92 | class SourceConfigError(Exception): | ||
2269 | 93 | pass | ||
2270 | 94 | |||
2271 | 95 | |||
2272 | 96 | class UnhandledSource(Exception): | ||
2273 | 97 | pass | ||
2274 | 98 | |||
2275 | 99 | |||
2276 | 100 | class AptLockError(Exception): | ||
2277 | 101 | pass | ||
2278 | 102 | |||
2279 | 103 | |||
2280 | 104 | class BaseFetchHandler(object): | ||
2281 | 105 | |||
2282 | 106 | """Base class for FetchHandler implementations in fetch plugins""" | ||
2283 | 107 | |||
2284 | 108 | def can_handle(self, source): | ||
2285 | 109 | """Returns True if the source can be handled. Otherwise returns | ||
2286 | 110 | a string explaining why it cannot""" | ||
2287 | 111 | return "Wrong source type" | ||
2288 | 112 | |||
2289 | 113 | def install(self, source): | ||
2290 | 114 | """Try to download and unpack the source. Return the path to the | ||
2291 | 115 | unpacked files or raise UnhandledSource.""" | ||
2292 | 116 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
2293 | 117 | |||
2294 | 118 | def parse_url(self, url): | ||
2295 | 119 | return urlparse(url) | ||
2296 | 120 | |||
2297 | 121 | def base_url(self, url): | ||
2298 | 122 | """Return url without querystring or fragment""" | ||
2299 | 123 | parts = list(self.parse_url(url)) | ||
2300 | 124 | parts[4:] = ['' for i in parts[4:]] | ||
2301 | 125 | return urlunparse(parts) | ||
2302 | 126 | |||
2303 | 127 | |||
2304 | 128 | def filter_installed_packages(packages): | ||
2305 | 129 | """Returns a list of packages that require installation""" | ||
2306 | 130 | cache = apt_cache() | ||
2307 | 131 | _pkgs = [] | ||
2308 | 132 | for package in packages: | ||
2309 | 133 | try: | ||
2310 | 134 | p = cache[package] | ||
2311 | 135 | p.current_ver or _pkgs.append(package) | ||
2312 | 136 | except KeyError: | ||
2313 | 137 | log('Package {} has no installation candidate.'.format(package), | ||
2314 | 138 | level='WARNING') | ||
2315 | 139 | _pkgs.append(package) | ||
2316 | 140 | return _pkgs | ||
2317 | 141 | |||
2318 | 142 | |||
2319 | 143 | def apt_cache(in_memory=True): | ||
2320 | 144 | """Build and return an apt cache""" | ||
2321 | 145 | import apt_pkg | ||
2322 | 146 | apt_pkg.init() | ||
2323 | 147 | if in_memory: | ||
2324 | 148 | apt_pkg.config.set("Dir::Cache::pkgcache", "") | ||
2325 | 149 | apt_pkg.config.set("Dir::Cache::srcpkgcache", "") | ||
2326 | 150 | return apt_pkg.Cache() | ||
2327 | 151 | |||
2328 | 152 | |||
2329 | 153 | def apt_install(packages, options=None, fatal=False): | ||
2330 | 154 | """Install one or more packages""" | ||
2331 | 155 | if options is None: | ||
2332 | 156 | options = ['--option=Dpkg::Options::=--force-confold'] | ||
2333 | 157 | |||
2334 | 158 | cmd = ['apt-get', '--assume-yes'] | ||
2335 | 159 | cmd.extend(options) | ||
2336 | 160 | cmd.append('install') | ||
2337 | 161 | if isinstance(packages, six.string_types): | ||
2338 | 162 | cmd.append(packages) | ||
2339 | 163 | else: | ||
2340 | 164 | cmd.extend(packages) | ||
2341 | 165 | log("Installing {} with options: {}".format(packages, | ||
2342 | 166 | options)) | ||
2343 | 167 | _run_apt_command(cmd, fatal) | ||
2344 | 168 | |||
2345 | 169 | |||
2346 | 170 | def apt_upgrade(options=None, fatal=False, dist=False): | ||
2347 | 171 | """Upgrade all packages""" | ||
2348 | 172 | if options is None: | ||
2349 | 173 | options = ['--option=Dpkg::Options::=--force-confold'] | ||
2350 | 174 | |||
2351 | 175 | cmd = ['apt-get', '--assume-yes'] | ||
2352 | 176 | cmd.extend(options) | ||
2353 | 177 | if dist: | ||
2354 | 178 | cmd.append('dist-upgrade') | ||
2355 | 179 | else: | ||
2356 | 180 | cmd.append('upgrade') | ||
2357 | 181 | log("Upgrading with options: {}".format(options)) | ||
2358 | 182 | _run_apt_command(cmd, fatal) | ||
2359 | 183 | |||
2360 | 184 | |||
2361 | 185 | def apt_update(fatal=False): | ||
2362 | 186 | """Update local apt cache""" | ||
2363 | 187 | cmd = ['apt-get', 'update'] | ||
2364 | 188 | _run_apt_command(cmd, fatal) | ||
2365 | 189 | |||
2366 | 190 | |||
2367 | 191 | def apt_purge(packages, fatal=False): | ||
2368 | 192 | """Purge one or more packages""" | ||
2369 | 193 | cmd = ['apt-get', '--assume-yes', 'purge'] | ||
2370 | 194 | if isinstance(packages, six.string_types): | ||
2371 | 195 | cmd.append(packages) | ||
2372 | 196 | else: | ||
2373 | 197 | cmd.extend(packages) | ||
2374 | 198 | log("Purging {}".format(packages)) | ||
2375 | 199 | _run_apt_command(cmd, fatal) | ||
2376 | 200 | |||
2377 | 201 | |||
2378 | 202 | def apt_hold(packages, fatal=False): | ||
2379 | 203 | """Hold one or more packages""" | ||
2380 | 204 | cmd = ['apt-mark', 'hold'] | ||
2381 | 205 | if isinstance(packages, six.string_types): | ||
2382 | 206 | cmd.append(packages) | ||
2383 | 207 | else: | ||
2384 | 208 | cmd.extend(packages) | ||
2385 | 209 | log("Holding {}".format(packages)) | ||
2386 | 210 | |||
2387 | 211 | if fatal: | ||
2388 | 212 | subprocess.check_call(cmd) | ||
2389 | 213 | else: | ||
2390 | 214 | subprocess.call(cmd) | ||
2391 | 215 | |||
2392 | 216 | |||
2393 | 217 | def add_source(source, key=None): | ||
2394 | 218 | """Add a package source to this system. | ||
2395 | 219 | |||
2396 | 220 | @param source: a URL or sources.list entry, as supported by | ||
2397 | 221 | add-apt-repository(1). Examples:: | ||
2398 | 222 | |||
2399 | 223 | ppa:charmers/example | ||
2400 | 224 | deb https://stub:key@private.example.com/ubuntu trusty main | ||
2401 | 225 | |||
2402 | 226 | In addition: | ||
2403 | 227 | 'proposed:' may be used to enable the standard 'proposed' | ||
2404 | 228 | pocket for the release. | ||
2405 | 229 | 'cloud:' may be used to activate official cloud archive pockets, | ||
2406 | 230 | such as 'cloud:icehouse' | ||
2407 | 231 | 'distro' may be used as a noop | ||
2408 | 232 | |||
2409 | 233 | @param key: A key to be added to the system's APT keyring and used | ||
2410 | 234 | to verify the signatures on packages. Ideally, this should be an | ||
2411 | 235 | ASCII format GPG public key including the block headers. A GPG key | ||
2412 | 236 | id may also be used, but be aware that only insecure protocols are | ||
2413 | 237 | available to retrieve the actual public key from a public keyserver | ||
2414 | 238 | placing your Juju environment at risk. ppa and cloud archive keys | ||
2415 | 239 | are securely added automtically, so sould not be provided. | ||
2416 | 240 | """ | ||
2417 | 241 | if source is None: | ||
2418 | 242 | log('Source is not present. Skipping') | ||
2419 | 243 | return | ||
2420 | 244 | |||
2421 | 245 | if (source.startswith('ppa:') or | ||
2422 | 246 | source.startswith('http') or | ||
2423 | 247 | source.startswith('deb ') or | ||
2424 | 248 | source.startswith('cloud-archive:')): | ||
2425 | 249 | subprocess.check_call(['add-apt-repository', '--yes', source]) | ||
2426 | 250 | elif source.startswith('cloud:'): | ||
2427 | 251 | apt_install(filter_installed_packages(['ubuntu-cloud-keyring']), | ||
2428 | 252 | fatal=True) | ||
2429 | 253 | pocket = source.split(':')[-1] | ||
2430 | 254 | if pocket not in CLOUD_ARCHIVE_POCKETS: | ||
2431 | 255 | raise SourceConfigError( | ||
2432 | 256 | 'Unsupported cloud: source option %s' % | ||
2433 | 257 | pocket) | ||
2434 | 258 | actual_pocket = CLOUD_ARCHIVE_POCKETS[pocket] | ||
2435 | 259 | with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as apt: | ||
2436 | 260 | apt.write(CLOUD_ARCHIVE.format(actual_pocket)) | ||
2437 | 261 | elif source == 'proposed': | ||
2438 | 262 | release = lsb_release()['DISTRIB_CODENAME'] | ||
2439 | 263 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: | ||
2440 | 264 | apt.write(PROPOSED_POCKET.format(release)) | ||
2441 | 265 | elif source == 'distro': | ||
2442 | 266 | pass | ||
2443 | 267 | else: | ||
2444 | 268 | log("Unknown source: {!r}".format(source)) | ||
2445 | 269 | |||
2446 | 270 | if key: | ||
2447 | 271 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: | ||
2448 | 272 | with NamedTemporaryFile('w+') as key_file: | ||
2449 | 273 | key_file.write(key) | ||
2450 | 274 | key_file.flush() | ||
2451 | 275 | key_file.seek(0) | ||
2452 | 276 | subprocess.check_call(['apt-key', 'add', '-'], stdin=key_file) | ||
2453 | 277 | else: | ||
2454 | 278 | # Note that hkp: is in no way a secure protocol. Using a | ||
2455 | 279 | # GPG key id is pointless from a security POV unless you | ||
2456 | 280 | # absolutely trust your network and DNS. | ||
2457 | 281 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | ||
2458 | 282 | 'hkp://keyserver.ubuntu.com:80', '--recv', | ||
2459 | 283 | key]) | ||
2460 | 284 | |||
2461 | 285 | |||
2462 | 286 | def configure_sources(update=False, | ||
2463 | 287 | sources_var='install_sources', | ||
2464 | 288 | keys_var='install_keys'): | ||
2465 | 289 | """ | ||
2466 | 290 | Configure multiple sources from charm configuration. | ||
2467 | 291 | |||
2468 | 292 | The lists are encoded as yaml fragments in the configuration. | ||
2469 | 293 | The frament needs to be included as a string. Sources and their | ||
2470 | 294 | corresponding keys are of the types supported by add_source(). | ||
2471 | 295 | |||
2472 | 296 | Example config: | ||
2473 | 297 | install_sources: | | ||
2474 | 298 | - "ppa:foo" | ||
2475 | 299 | - "http://example.com/repo precise main" | ||
2476 | 300 | install_keys: | | ||
2477 | 301 | - null | ||
2478 | 302 | - "a1b2c3d4" | ||
2479 | 303 | |||
2480 | 304 | Note that 'null' (a.k.a. None) should not be quoted. | ||
2481 | 305 | """ | ||
2482 | 306 | sources = safe_load((config(sources_var) or '').strip()) or [] | ||
2483 | 307 | keys = safe_load((config(keys_var) or '').strip()) or None | ||
2484 | 308 | |||
2485 | 309 | if isinstance(sources, six.string_types): | ||
2486 | 310 | sources = [sources] | ||
2487 | 311 | |||
2488 | 312 | if keys is None: | ||
2489 | 313 | for source in sources: | ||
2490 | 314 | add_source(source, None) | ||
2491 | 315 | else: | ||
2492 | 316 | if isinstance(keys, six.string_types): | ||
2493 | 317 | keys = [keys] | ||
2494 | 318 | |||
2495 | 319 | if len(sources) != len(keys): | ||
2496 | 320 | raise SourceConfigError( | ||
2497 | 321 | 'Install sources and keys lists are different lengths') | ||
2498 | 322 | for source, key in zip(sources, keys): | ||
2499 | 323 | add_source(source, key) | ||
2500 | 324 | if update: | ||
2501 | 325 | apt_update(fatal=True) | ||
2502 | 326 | |||
2503 | 327 | |||
2504 | 328 | def install_remote(source, *args, **kwargs): | ||
2505 | 329 | """ | ||
2506 | 330 | Install a file tree from a remote source | ||
2507 | 331 | |||
2508 | 332 | The specified source should be a url of the form: | ||
2509 | 333 | scheme://[host]/path[#[option=value][&...]] | ||
2510 | 334 | |||
2511 | 335 | Schemes supported are based on this modules submodules. | ||
2512 | 336 | Options supported are submodule-specific. | ||
2513 | 337 | Additional arguments are passed through to the submodule. | ||
2514 | 338 | |||
2515 | 339 | For example:: | ||
2516 | 340 | |||
2517 | 341 | dest = install_remote('http://example.com/archive.tgz', | ||
2518 | 342 | checksum='deadbeef', | ||
2519 | 343 | hash_type='sha1') | ||
2520 | 344 | |||
2521 | 345 | This will download `archive.tgz`, validate it using SHA1 and, if | ||
2522 | 346 | the file is ok, extract it and return the directory in which it | ||
2523 | 347 | was extracted. If the checksum fails, it will raise | ||
2524 | 348 | :class:`charmhelpers.core.host.ChecksumError`. | ||
2525 | 349 | """ | ||
2526 | 350 | # We ONLY check for True here because can_handle may return a string | ||
2527 | 351 | # explaining why it can't handle a given source. | ||
2528 | 352 | handlers = [h for h in plugins() if h.can_handle(source) is True] | ||
2529 | 353 | installed_to = None | ||
2530 | 354 | for handler in handlers: | ||
2531 | 355 | try: | ||
2532 | 356 | installed_to = handler.install(source, *args, **kwargs) | ||
2533 | 357 | except UnhandledSource: | ||
2534 | 358 | pass | ||
2535 | 359 | if not installed_to: | ||
2536 | 360 | raise UnhandledSource("No handler found for source {}".format(source)) | ||
2537 | 361 | return installed_to | ||
2538 | 362 | |||
2539 | 363 | |||
2540 | 364 | def install_from_config(config_var_name): | ||
2541 | 365 | charm_config = config() | ||
2542 | 366 | source = charm_config[config_var_name] | ||
2543 | 367 | return install_remote(source) | ||
2544 | 368 | |||
2545 | 369 | |||
2546 | 370 | def plugins(fetch_handlers=None): | ||
2547 | 371 | if not fetch_handlers: | ||
2548 | 372 | fetch_handlers = FETCH_HANDLERS | ||
2549 | 373 | plugin_list = [] | ||
2550 | 374 | for handler_name in fetch_handlers: | ||
2551 | 375 | package, classname = handler_name.rsplit('.', 1) | ||
2552 | 376 | try: | ||
2553 | 377 | handler_class = getattr( | ||
2554 | 378 | importlib.import_module(package), | ||
2555 | 379 | classname) | ||
2556 | 380 | plugin_list.append(handler_class()) | ||
2557 | 381 | except (ImportError, AttributeError): | ||
2558 | 382 | # Skip missing plugins so that they can be ommitted from | ||
2559 | 383 | # installation if desired | ||
2560 | 384 | log("FetchHandler {} not found, skipping plugin".format( | ||
2561 | 385 | handler_name)) | ||
2562 | 386 | return plugin_list | ||
2563 | 387 | |||
2564 | 388 | |||
2565 | 389 | def _run_apt_command(cmd, fatal=False): | ||
2566 | 390 | """ | ||
2567 | 391 | Run an APT command, checking output and retrying if the fatal flag is set | ||
2568 | 392 | to True. | ||
2569 | 393 | |||
2570 | 394 | :param: cmd: str: The apt command to run. | ||
2571 | 395 | :param: fatal: bool: Whether the command's output should be checked and | ||
2572 | 396 | retried. | ||
2573 | 397 | """ | ||
2574 | 398 | env = os.environ.copy() | ||
2575 | 399 | |||
2576 | 400 | if 'DEBIAN_FRONTEND' not in env: | ||
2577 | 401 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
2578 | 402 | |||
2579 | 403 | if fatal: | ||
2580 | 404 | retry_count = 0 | ||
2581 | 405 | result = None | ||
2582 | 406 | |||
2583 | 407 | # If the command is considered "fatal", we need to retry if the apt | ||
2584 | 408 | # lock was not acquired. | ||
2585 | 409 | |||
2586 | 410 | while result is None or result == APT_NO_LOCK: | ||
2587 | 411 | try: | ||
2588 | 412 | result = subprocess.check_call(cmd, env=env) | ||
2589 | 413 | except subprocess.CalledProcessError as e: | ||
2590 | 414 | retry_count = retry_count + 1 | ||
2591 | 415 | if retry_count > APT_NO_LOCK_RETRY_COUNT: | ||
2592 | 416 | raise | ||
2593 | 417 | result = e.returncode | ||
2594 | 418 | log("Couldn't acquire DPKG lock. Will retry in {} seconds." | ||
2595 | 419 | "".format(APT_NO_LOCK_RETRY_DELAY)) | ||
2596 | 420 | time.sleep(APT_NO_LOCK_RETRY_DELAY) | ||
2597 | 421 | |||
2598 | 422 | else: | ||
2599 | 423 | subprocess.call(cmd, env=env) | ||
2600 | 0 | 424 | ||
2601 | === added file 'hooks/charmhelpers/fetch/archiveurl.py' | |||
2602 | --- hooks/charmhelpers/fetch/archiveurl.py 1970-01-01 00:00:00 +0000 | |||
2603 | +++ hooks/charmhelpers/fetch/archiveurl.py 2015-01-20 18:33:44 +0000 | |||
2604 | @@ -0,0 +1,145 @@ | |||
2605 | 1 | import os | ||
2606 | 2 | import hashlib | ||
2607 | 3 | import re | ||
2608 | 4 | |||
2609 | 5 | import six | ||
2610 | 6 | if six.PY3: | ||
2611 | 7 | from urllib.request import ( | ||
2612 | 8 | build_opener, install_opener, urlopen, urlretrieve, | ||
2613 | 9 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
2614 | 10 | ) | ||
2615 | 11 | from urllib.parse import urlparse, urlunparse, parse_qs | ||
2616 | 12 | from urllib.error import URLError | ||
2617 | 13 | else: | ||
2618 | 14 | from urllib import urlretrieve | ||
2619 | 15 | from urllib2 import ( | ||
2620 | 16 | build_opener, install_opener, urlopen, | ||
2621 | 17 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
2622 | 18 | URLError | ||
2623 | 19 | ) | ||
2624 | 20 | from urlparse import urlparse, urlunparse, parse_qs | ||
2625 | 21 | |||
2626 | 22 | from charmhelpers.fetch import ( | ||
2627 | 23 | BaseFetchHandler, | ||
2628 | 24 | UnhandledSource | ||
2629 | 25 | ) | ||
2630 | 26 | from charmhelpers.payload.archive import ( | ||
2631 | 27 | get_archive_handler, | ||
2632 | 28 | extract, | ||
2633 | 29 | ) | ||
2634 | 30 | from charmhelpers.core.host import mkdir, check_hash | ||
2635 | 31 | |||
2636 | 32 | |||
2637 | 33 | def splituser(host): | ||
2638 | 34 | '''urllib.splituser(), but six's support of this seems broken''' | ||
2639 | 35 | _userprog = re.compile('^(.*)@(.*)$') | ||
2640 | 36 | match = _userprog.match(host) | ||
2641 | 37 | if match: | ||
2642 | 38 | return match.group(1, 2) | ||
2643 | 39 | return None, host | ||
2644 | 40 | |||
2645 | 41 | |||
2646 | 42 | def splitpasswd(user): | ||
2647 | 43 | '''urllib.splitpasswd(), but six's support of this is missing''' | ||
2648 | 44 | _passwdprog = re.compile('^([^:]*):(.*)$', re.S) | ||
2649 | 45 | match = _passwdprog.match(user) | ||
2650 | 46 | if match: | ||
2651 | 47 | return match.group(1, 2) | ||
2652 | 48 | return user, None | ||
2653 | 49 | |||
2654 | 50 | |||
2655 | 51 | class ArchiveUrlFetchHandler(BaseFetchHandler): | ||
2656 | 52 | """ | ||
2657 | 53 | Handler to download archive files from arbitrary URLs. | ||
2658 | 54 | |||
2659 | 55 | Can fetch from http, https, ftp, and file URLs. | ||
2660 | 56 | |||
2661 | 57 | Can install either tarballs (.tar, .tgz, .tbz2, etc) or zip files. | ||
2662 | 58 | |||
2663 | 59 | Installs the contents of the archive in $CHARM_DIR/fetched/. | ||
2664 | 60 | """ | ||
2665 | 61 | def can_handle(self, source): | ||
2666 | 62 | url_parts = self.parse_url(source) | ||
2667 | 63 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): | ||
2668 | 64 | return "Wrong source type" | ||
2669 | 65 | if get_archive_handler(self.base_url(source)): | ||
2670 | 66 | return True | ||
2671 | 67 | return False | ||
2672 | 68 | |||
2673 | 69 | def download(self, source, dest): | ||
2674 | 70 | """ | ||
2675 | 71 | Download an archive file. | ||
2676 | 72 | |||
2677 | 73 | :param str source: URL pointing to an archive file. | ||
2678 | 74 | :param str dest: Local path location to download archive file to. | ||
2679 | 75 | """ | ||
2680 | 76 | # propogate all exceptions | ||
2681 | 77 | # URLError, OSError, etc | ||
2682 | 78 | proto, netloc, path, params, query, fragment = urlparse(source) | ||
2683 | 79 | if proto in ('http', 'https'): | ||
2684 | 80 | auth, barehost = splituser(netloc) | ||
2685 | 81 | if auth is not None: | ||
2686 | 82 | source = urlunparse((proto, barehost, path, params, query, fragment)) | ||
2687 | 83 | username, password = splitpasswd(auth) | ||
2688 | 84 | passman = HTTPPasswordMgrWithDefaultRealm() | ||
2689 | 85 | # Realm is set to None in add_password to force the username and password | ||
2690 | 86 | # to be used whatever the realm | ||
2691 | 87 | passman.add_password(None, source, username, password) | ||
2692 | 88 | authhandler = HTTPBasicAuthHandler(passman) | ||
2693 | 89 | opener = build_opener(authhandler) | ||
2694 | 90 | install_opener(opener) | ||
2695 | 91 | response = urlopen(source) | ||
2696 | 92 | try: | ||
2697 | 93 | with open(dest, 'w') as dest_file: | ||
2698 | 94 | dest_file.write(response.read()) | ||
2699 | 95 | except Exception as e: | ||
2700 | 96 | if os.path.isfile(dest): | ||
2701 | 97 | os.unlink(dest) | ||
2702 | 98 | raise e | ||
2703 | 99 | |||
2704 | 100 | # Mandatory file validation via Sha1 or MD5 hashing. | ||
2705 | 101 | def download_and_validate(self, url, hashsum, validate="sha1"): | ||
2706 | 102 | tempfile, headers = urlretrieve(url) | ||
2707 | 103 | check_hash(tempfile, hashsum, validate) | ||
2708 | 104 | return tempfile | ||
2709 | 105 | |||
2710 | 106 | def install(self, source, dest=None, checksum=None, hash_type='sha1'): | ||
2711 | 107 | """ | ||
2712 | 108 | Download and install an archive file, with optional checksum validation. | ||
2713 | 109 | |||
2714 | 110 | The checksum can also be given on the `source` URL's fragment. | ||
2715 | 111 | For example:: | ||
2716 | 112 | |||
2717 | 113 | handler.install('http://example.com/file.tgz#sha1=deadbeef') | ||
2718 | 114 | |||
2719 | 115 | :param str source: URL pointing to an archive file. | ||
2720 | 116 | :param str dest: Local destination path to install to. If not given, | ||
2721 | 117 | installs to `$CHARM_DIR/archives/archive_file_name`. | ||
2722 | 118 | :param str checksum: If given, validate the archive file after download. | ||
2723 | 119 | :param str hash_type: Algorithm used to generate `checksum`. | ||
2724 | 120 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
2725 | 121 | such as md5, sha1, sha256, sha512, etc. | ||
2726 | 122 | |||
2727 | 123 | """ | ||
2728 | 124 | url_parts = self.parse_url(source) | ||
2729 | 125 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') | ||
2730 | 126 | if not os.path.exists(dest_dir): | ||
2731 | 127 | mkdir(dest_dir, perms=0o755) | ||
2732 | 128 | dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path)) | ||
2733 | 129 | try: | ||
2734 | 130 | self.download(source, dld_file) | ||
2735 | 131 | except URLError as e: | ||
2736 | 132 | raise UnhandledSource(e.reason) | ||
2737 | 133 | except OSError as e: | ||
2738 | 134 | raise UnhandledSource(e.strerror) | ||
2739 | 135 | options = parse_qs(url_parts.fragment) | ||
2740 | 136 | for key, value in options.items(): | ||
2741 | 137 | if not six.PY3: | ||
2742 | 138 | algorithms = hashlib.algorithms | ||
2743 | 139 | else: | ||
2744 | 140 | algorithms = hashlib.algorithms_available | ||
2745 | 141 | if key in algorithms: | ||
2746 | 142 | check_hash(dld_file, value, key) | ||
2747 | 143 | if checksum: | ||
2748 | 144 | check_hash(dld_file, checksum, hash_type) | ||
2749 | 145 | return extract(dld_file, dest) | ||
2750 | 0 | 146 | ||
2751 | === added file 'hooks/charmhelpers/fetch/bzrurl.py' | |||
2752 | --- hooks/charmhelpers/fetch/bzrurl.py 1970-01-01 00:00:00 +0000 | |||
2753 | +++ hooks/charmhelpers/fetch/bzrurl.py 2015-01-20 18:33:44 +0000 | |||
2754 | @@ -0,0 +1,54 @@ | |||
2755 | 1 | import os | ||
2756 | 2 | from charmhelpers.fetch import ( | ||
2757 | 3 | BaseFetchHandler, | ||
2758 | 4 | UnhandledSource | ||
2759 | 5 | ) | ||
2760 | 6 | from charmhelpers.core.host import mkdir | ||
2761 | 7 | |||
2762 | 8 | import six | ||
2763 | 9 | if six.PY3: | ||
2764 | 10 | raise ImportError('bzrlib does not support Python3') | ||
2765 | 11 | |||
2766 | 12 | try: | ||
2767 | 13 | from bzrlib.branch import Branch | ||
2768 | 14 | except ImportError: | ||
2769 | 15 | from charmhelpers.fetch import apt_install | ||
2770 | 16 | apt_install("python-bzrlib") | ||
2771 | 17 | from bzrlib.branch import Branch | ||
2772 | 18 | |||
2773 | 19 | |||
2774 | 20 | class BzrUrlFetchHandler(BaseFetchHandler): | ||
2775 | 21 | """Handler for bazaar branches via generic and lp URLs""" | ||
2776 | 22 | def can_handle(self, source): | ||
2777 | 23 | url_parts = self.parse_url(source) | ||
2778 | 24 | if url_parts.scheme not in ('bzr+ssh', 'lp'): | ||
2779 | 25 | return False | ||
2780 | 26 | else: | ||
2781 | 27 | return True | ||
2782 | 28 | |||
2783 | 29 | def branch(self, source, dest): | ||
2784 | 30 | url_parts = self.parse_url(source) | ||
2785 | 31 | # If we use lp:branchname scheme we need to load plugins | ||
2786 | 32 | if not self.can_handle(source): | ||
2787 | 33 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
2788 | 34 | if url_parts.scheme == "lp": | ||
2789 | 35 | from bzrlib.plugin import load_plugins | ||
2790 | 36 | load_plugins() | ||
2791 | 37 | try: | ||
2792 | 38 | remote_branch = Branch.open(source) | ||
2793 | 39 | remote_branch.bzrdir.sprout(dest).open_branch() | ||
2794 | 40 | except Exception as e: | ||
2795 | 41 | raise e | ||
2796 | 42 | |||
2797 | 43 | def install(self, source): | ||
2798 | 44 | url_parts = self.parse_url(source) | ||
2799 | 45 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
2800 | 46 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
2801 | 47 | branch_name) | ||
2802 | 48 | if not os.path.exists(dest_dir): | ||
2803 | 49 | mkdir(dest_dir, perms=0o755) | ||
2804 | 50 | try: | ||
2805 | 51 | self.branch(source, dest_dir) | ||
2806 | 52 | except OSError as e: | ||
2807 | 53 | raise UnhandledSource(e.strerror) | ||
2808 | 54 | return dest_dir | ||
2809 | 0 | 55 | ||
2810 | === added file 'hooks/charmhelpers/fetch/giturl.py' | |||
2811 | --- hooks/charmhelpers/fetch/giturl.py 1970-01-01 00:00:00 +0000 | |||
2812 | +++ hooks/charmhelpers/fetch/giturl.py 2015-01-20 18:33:44 +0000 | |||
2813 | @@ -0,0 +1,51 @@ | |||
2814 | 1 | import os | ||
2815 | 2 | from charmhelpers.fetch import ( | ||
2816 | 3 | BaseFetchHandler, | ||
2817 | 4 | UnhandledSource | ||
2818 | 5 | ) | ||
2819 | 6 | from charmhelpers.core.host import mkdir | ||
2820 | 7 | |||
2821 | 8 | import six | ||
2822 | 9 | if six.PY3: | ||
2823 | 10 | raise ImportError('GitPython does not support Python 3') | ||
2824 | 11 | |||
2825 | 12 | try: | ||
2826 | 13 | from git import Repo | ||
2827 | 14 | except ImportError: | ||
2828 | 15 | from charmhelpers.fetch import apt_install | ||
2829 | 16 | apt_install("python-git") | ||
2830 | 17 | from git import Repo | ||
2831 | 18 | |||
2832 | 19 | |||
2833 | 20 | class GitUrlFetchHandler(BaseFetchHandler): | ||
2834 | 21 | """Handler for git branches via generic and github URLs""" | ||
2835 | 22 | def can_handle(self, source): | ||
2836 | 23 | url_parts = self.parse_url(source) | ||
2837 | 24 | # TODO (mattyw) no support for ssh git@ yet | ||
2838 | 25 | if url_parts.scheme not in ('http', 'https', 'git'): | ||
2839 | 26 | return False | ||
2840 | 27 | else: | ||
2841 | 28 | return True | ||
2842 | 29 | |||
2843 | 30 | def clone(self, source, dest, branch): | ||
2844 | 31 | if not self.can_handle(source): | ||
2845 | 32 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
2846 | 33 | |||
2847 | 34 | repo = Repo.clone_from(source, dest) | ||
2848 | 35 | repo.git.checkout(branch) | ||
2849 | 36 | |||
2850 | 37 | def install(self, source, branch="master", dest=None): | ||
2851 | 38 | url_parts = self.parse_url(source) | ||
2852 | 39 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
2853 | 40 | if dest: | ||
2854 | 41 | dest_dir = os.path.join(dest, branch_name) | ||
2855 | 42 | else: | ||
2856 | 43 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
2857 | 44 | branch_name) | ||
2858 | 45 | if not os.path.exists(dest_dir): | ||
2859 | 46 | mkdir(dest_dir, perms=0o755) | ||
2860 | 47 | try: | ||
2861 | 48 | self.clone(source, dest_dir, branch) | ||
2862 | 49 | except OSError as e: | ||
2863 | 50 | raise UnhandledSource(e.strerror) | ||
2864 | 51 | return dest_dir | ||
2865 | 0 | 52 | ||
2866 | === added directory 'hooks/charmhelpers/payload' | |||
2867 | === added file 'hooks/charmhelpers/payload/__init__.py' | |||
2868 | --- hooks/charmhelpers/payload/__init__.py 1970-01-01 00:00:00 +0000 | |||
2869 | +++ hooks/charmhelpers/payload/__init__.py 2015-01-20 18:33:44 +0000 | |||
2870 | @@ -0,0 +1,1 @@ | |||
2871 | 1 | "Tools for working with files injected into a charm just before deployment." | ||
2872 | 0 | 2 | ||
2873 | === added file 'hooks/charmhelpers/payload/execd.py' | |||
2874 | --- hooks/charmhelpers/payload/execd.py 1970-01-01 00:00:00 +0000 | |||
2875 | +++ hooks/charmhelpers/payload/execd.py 2015-01-20 18:33:44 +0000 | |||
2876 | @@ -0,0 +1,50 @@ | |||
2877 | 1 | #!/usr/bin/env python | ||
2878 | 2 | |||
2879 | 3 | import os | ||
2880 | 4 | import sys | ||
2881 | 5 | import subprocess | ||
2882 | 6 | from charmhelpers.core import hookenv | ||
2883 | 7 | |||
2884 | 8 | |||
2885 | 9 | def default_execd_dir(): | ||
2886 | 10 | return os.path.join(os.environ['CHARM_DIR'], 'exec.d') | ||
2887 | 11 | |||
2888 | 12 | |||
2889 | 13 | def execd_module_paths(execd_dir=None): | ||
2890 | 14 | """Generate a list of full paths to modules within execd_dir.""" | ||
2891 | 15 | if not execd_dir: | ||
2892 | 16 | execd_dir = default_execd_dir() | ||
2893 | 17 | |||
2894 | 18 | if not os.path.exists(execd_dir): | ||
2895 | 19 | return | ||
2896 | 20 | |||
2897 | 21 | for subpath in os.listdir(execd_dir): | ||
2898 | 22 | module = os.path.join(execd_dir, subpath) | ||
2899 | 23 | if os.path.isdir(module): | ||
2900 | 24 | yield module | ||
2901 | 25 | |||
2902 | 26 | |||
2903 | 27 | def execd_submodule_paths(command, execd_dir=None): | ||
2904 | 28 | """Generate a list of full paths to the specified command within exec_dir. | ||
2905 | 29 | """ | ||
2906 | 30 | for module_path in execd_module_paths(execd_dir): | ||
2907 | 31 | path = os.path.join(module_path, command) | ||
2908 | 32 | if os.access(path, os.X_OK) and os.path.isfile(path): | ||
2909 | 33 | yield path | ||
2910 | 34 | |||
2911 | 35 | |||
2912 | 36 | def execd_run(command, execd_dir=None, die_on_error=False, stderr=None): | ||
2913 | 37 | """Run command for each module within execd_dir which defines it.""" | ||
2914 | 38 | for submodule_path in execd_submodule_paths(command, execd_dir): | ||
2915 | 39 | try: | ||
2916 | 40 | subprocess.check_call(submodule_path, shell=True, stderr=stderr) | ||
2917 | 41 | except subprocess.CalledProcessError as e: | ||
2918 | 42 | hookenv.log("Error ({}) running {}. Output: {}".format( | ||
2919 | 43 | e.returncode, e.cmd, e.output)) | ||
2920 | 44 | if die_on_error: | ||
2921 | 45 | sys.exit(e.returncode) | ||
2922 | 46 | |||
2923 | 47 | |||
2924 | 48 | def execd_preinstall(execd_dir=None): | ||
2925 | 49 | """Run charm-pre-install for each module within execd_dir.""" | ||
2926 | 50 | execd_run('charm-pre-install', execd_dir=execd_dir) | ||
2927 | 0 | 51 | ||
2928 | === modified file 'hooks/config-changed' | |||
2929 | --- hooks/config-changed 2011-09-22 14:46:56 +0000 | |||
2930 | +++ hooks/config-changed 1970-01-01 00:00:00 +0000 | |||
2931 | @@ -1,7 +0,0 @@ | |||
2932 | 1 | #!/bin/sh | ||
2933 | 2 | set -e | ||
2934 | 3 | |||
2935 | 4 | home=`dirname $0` | ||
2936 | 5 | |||
2937 | 6 | juju-log "Reconfiguring charm by installing hook again." | ||
2938 | 7 | exec $home/install | ||
2939 | 8 | 0 | ||
2940 | === target is u'jenkins_hooks.py' | |||
2941 | === removed file 'hooks/delnode' | |||
2942 | --- hooks/delnode 2011-09-22 14:46:56 +0000 | |||
2943 | +++ hooks/delnode 1970-01-01 00:00:00 +0000 | |||
2944 | @@ -1,16 +0,0 @@ | |||
2945 | 1 | #!/usr/bin/python | ||
2946 | 2 | |||
2947 | 3 | import jenkins | ||
2948 | 4 | import sys | ||
2949 | 5 | |||
2950 | 6 | host=sys.argv[1] | ||
2951 | 7 | username=sys.argv[2] | ||
2952 | 8 | password=sys.argv[3] | ||
2953 | 9 | |||
2954 | 10 | l_jenkins = jenkins.Jenkins("http://localhost:8080/",username,password) | ||
2955 | 11 | |||
2956 | 12 | if l_jenkins.node_exists(host): | ||
2957 | 13 | print "Node exists" | ||
2958 | 14 | l_jenkins.delete_node(host) | ||
2959 | 15 | else: | ||
2960 | 16 | print "Node does not exist - not deleting" | ||
2961 | 17 | 0 | ||
2962 | === modified file 'hooks/install' | |||
2963 | --- hooks/install 2014-04-17 12:35:18 +0000 | |||
2964 | +++ hooks/install 1970-01-01 00:00:00 +0000 | |||
2965 | @@ -1,151 +0,0 @@ | |||
2966 | 1 | #!/bin/bash | ||
2967 | 2 | |||
2968 | 3 | set -eu | ||
2969 | 4 | |||
2970 | 5 | RELEASE=$(config-get release) | ||
2971 | 6 | ADMIN_USERNAME=$(config-get username) | ||
2972 | 7 | ADMIN_PASSWORD=$(config-get password) | ||
2973 | 8 | PLUGINS=$(config-get plugins) | ||
2974 | 9 | PLUGINS_SITE=$(config-get plugins-site) | ||
2975 | 10 | PLUGINS_CHECK_CERT=$(config-get plugins-check-certificate) | ||
2976 | 11 | REMOVE_UNLISTED_PLUGINS=$(config-get remove-unlisted-plugins) | ||
2977 | 12 | CWD=$(dirname $0) | ||
2978 | 13 | JENKINS_HOME=/var/lib/jenkins | ||
2979 | 14 | |||
2980 | 15 | setup_source () { | ||
2981 | 16 | # Do something with < Oneiric releases - maybe PPA | ||
2982 | 17 | # apt-get -y install python-software-properties | ||
2983 | 18 | # add-apt-repository ppa:hudson-ubuntu/testing | ||
2984 | 19 | juju-log "Configuring source of jenkins as $RELEASE" | ||
2985 | 20 | # Configure to use upstream archives | ||
2986 | 21 | # lts - debian-stable | ||
2987 | 22 | # trunk - debian | ||
2988 | 23 | case $RELEASE in | ||
2989 | 24 | lts) | ||
2990 | 25 | SOURCE="debian-stable";; | ||
2991 | 26 | trunk) | ||
2992 | 27 | SOURCE="debian";; | ||
2993 | 28 | *) | ||
2994 | 29 | juju-log "release configuration not recognised" && exit 1;; | ||
2995 | 30 | esac | ||
2996 | 31 | # Setup archive to use appropriate jenkins upstream | ||
2997 | 32 | wget -q -O - http://pkg.jenkins-ci.org/$SOURCE/jenkins-ci.org.key | apt-key add - | ||
2998 | 33 | echo "deb http://pkg.jenkins-ci.org/$SOURCE binary/" \ | ||
2999 | 34 | > /etc/apt/sources.list.d/jenkins.list | ||
3000 | 35 | apt-get update || true | ||
3001 | 36 | } | ||
3002 | 37 | # Only setup the source if jenkins is not already installed | ||
3003 | 38 | # this makes the config 'release' immutable - i.e. you | ||
3004 | 39 | # can change source once deployed | ||
3005 | 40 | [[ -d /var/lib/jenkins ]] || setup_source | ||
3006 | 41 | |||
3007 | 42 | # Install jenkins | ||
3008 | 43 | install_jenkins () { | ||
3009 | 44 | juju-log "Installing/upgrading jenkins..." | ||
3010 | 45 | apt-get -y install -qq jenkins default-jre-headless | ||
3011 | 46 | } | ||
3012 | 47 | # Re-run whenever called to pickup any updates | ||
3013 | 48 | install_jenkins | ||
3014 | 49 | |||
3015 | 50 | configure_jenkins_user () { | ||
3016 | 51 | juju-log "Configuring user for jenkins..." | ||
3017 | 52 | # Check to see if password provided | ||
3018 | 53 | if [ -z "$ADMIN_PASSWORD" ] | ||
3019 | 54 | then | ||
3020 | 55 | # Generate a random one for security | ||
3021 | 56 | # User can then override using juju set | ||
3022 | 57 | ADMIN_PASSWORD=$(< /dev/urandom tr -dc A-Za-z | head -c16) | ||
3023 | 58 | echo $ADMIN_PASSWORD > $JENKINS_HOME/.admin_password | ||
3024 | 59 | chmod 0600 $JENKINS_HOME/.admin_password | ||
3025 | 60 | fi | ||
3026 | 61 | # Generate Salt and Hash Password for Jenkins | ||
3027 | 62 | SALT="$(< /dev/urandom tr -dc A-Za-z | head -c6)" | ||
3028 | 63 | PASSWORD="$SALT:$(echo -n "$ADMIN_PASSWORD{$SALT}" | shasum -a 256 | awk '{ print $1 }')" | ||
3029 | 64 | mkdir -p $JENKINS_HOME/users/$ADMIN_USERNAME | ||
3030 | 65 | sed -e s#__USERNAME__#$ADMIN_USERNAME# -e s#__PASSWORD__#$PASSWORD# \ | ||
3031 | 66 | $CWD/../templates/user-config.xml > $JENKINS_HOME/users/$ADMIN_USERNAME/config.xml | ||
3032 | 67 | chown -R jenkins:nogroup $JENKINS_HOME/users | ||
3033 | 68 | } | ||
3034 | 69 | # Always run - even if config has not changed, its safe | ||
3035 | 70 | configure_jenkins_user | ||
3036 | 71 | |||
3037 | 72 | boostrap_jenkins_configuration (){ | ||
3038 | 73 | juju-log "Bootstrapping secure initial configuration in Jenkins..." | ||
3039 | 74 | cp $CWD/../templates/jenkins-config.xml $JENKINS_HOME/config.xml | ||
3040 | 75 | chown jenkins:nogroup $JENKINS_HOME/config.xml | ||
3041 | 76 | touch /var/lib/jenkins/config.bootstrapped | ||
3042 | 77 | } | ||
3043 | 78 | # Only run on first invocation otherwise we blast | ||
3044 | 79 | # any configuration changes made | ||
3045 | 80 | [[ -f /var/lib/jenkins/config.bootstrapped ]] || boostrap_jenkins_configuration | ||
3046 | 81 | |||
3047 | 82 | install_plugins(){ | ||
3048 | 83 | juju-log "Installing plugins ($PLUGINS)" | ||
3049 | 84 | mkdir -p $JENKINS_HOME/plugins | ||
3050 | 85 | chmod a+rx $JENKINS_HOME/plugins | ||
3051 | 86 | chown jenkins:nogroup $JENKINS_HOME/plugins | ||
3052 | 87 | track_dir=`mktemp -d /tmp/plugins.installed.XXXXXXXX` | ||
3053 | 88 | installed_plugins=`find $JENKINS_HOME/plugins -name '*.hpi'` | ||
3054 | 89 | [ -z "$installed_plugins" ] || ln -s $installed_plugins $track_dir | ||
3055 | 90 | local plugin="" | ||
3056 | 91 | local plugin_file="" | ||
3057 | 92 | local opts="" | ||
3058 | 93 | pushd $JENKINS_HOME/plugins | ||
3059 | 94 | for plugin in $PLUGINS ; do | ||
3060 | 95 | plugin_file=$JENKINS_HOME/plugins/$plugin.hpi | ||
3061 | 96 | # Note that by default wget verifies certificates as of 1.10. | ||
3062 | 97 | if [ "$PLUGINS_CHECK_CERT" = "no" ] ; then | ||
3063 | 98 | opts="--no-check-certificate" | ||
3064 | 99 | fi | ||
3065 | 100 | wget $opts --timestamping $PLUGINS_SITE/latest/$plugin.hpi | ||
3066 | 101 | chmod a+r $plugin_file | ||
3067 | 102 | rm -f $track_dir/$plugin.hpi | ||
3068 | 103 | done | ||
3069 | 104 | popd | ||
3070 | 105 | # Warn about undesirable plugins, or remove them. | ||
3071 | 106 | unlisted_plugins=`ls $track_dir` | ||
3072 | 107 | [[ -n "$unlisted_plugins" ]] || return 0 | ||
3073 | 108 | if [[ $REMOVE_UNLISTED_PLUGINS = "yes" ]] ; then | ||
3074 | 109 | for plugin_file in `ls $track_dir` ; do | ||
3075 | 110 | rm -vf $JENKINS_HOME/plugins/$plugin_file | ||
3076 | 111 | done | ||
3077 | 112 | else | ||
3078 | 113 | juju-log -l WARNING "Unlisted plugins: (`ls $track_dir`) Not removed. Set remove-unlisted-plugins to yes to clear them away." | ||
3079 | 114 | fi | ||
3080 | 115 | } | ||
3081 | 116 | |||
3082 | 117 | install_plugins | ||
3083 | 118 | |||
3084 | 119 | juju-log "Restarting jenkins to pickup configuration changes" | ||
3085 | 120 | service jenkins restart | ||
3086 | 121 | |||
3087 | 122 | # Install helpers - python jenkins ++ | ||
3088 | 123 | install_python_jenkins () { | ||
3089 | 124 | juju-log "Installing python-jenkins..." | ||
3090 | 125 | apt-get -y install -qq python-jenkins | ||
3091 | 126 | } | ||
3092 | 127 | # Only install once | ||
3093 | 128 | [[ -d /usr/share/pyshared/jenkins ]] || install_python_jenkins | ||
3094 | 129 | |||
3095 | 130 | # Install some tools - can get set up deployment time | ||
3096 | 131 | install_tools () { | ||
3097 | 132 | juju-log "Installing tools..." | ||
3098 | 133 | apt-get -y install -qq `config-get tools` | ||
3099 | 134 | } | ||
3100 | 135 | # Always run - tools might get re-configured | ||
3101 | 136 | install_tools | ||
3102 | 137 | |||
3103 | 138 | juju-log "Opening ports" | ||
3104 | 139 | open-port 8080 | ||
3105 | 140 | |||
3106 | 141 | # Execute any hook overlay which may be provided | ||
3107 | 142 | # by forks of this charm | ||
3108 | 143 | if [ -d hooks/install.d ] | ||
3109 | 144 | then | ||
3110 | 145 | for i in `ls -1 hooks/install.d/*` | ||
3111 | 146 | do | ||
3112 | 147 | [[ -x $i ]] && . ./$i | ||
3113 | 148 | done | ||
3114 | 149 | fi | ||
3115 | 150 | |||
3116 | 151 | exit 0 | ||
3117 | 152 | 0 | ||
3118 | === target is u'jenkins_hooks.py' | |||
3119 | === added file 'hooks/jenkins_hooks.py' | |||
3120 | --- hooks/jenkins_hooks.py 1970-01-01 00:00:00 +0000 | |||
3121 | +++ hooks/jenkins_hooks.py 2015-01-20 18:33:44 +0000 | |||
3122 | @@ -0,0 +1,220 @@ | |||
3123 | 1 | #!/usr/bin/python | ||
3124 | 2 | import grp | ||
3125 | 3 | import hashlib | ||
3126 | 4 | import os | ||
3127 | 5 | import pwd | ||
3128 | 6 | import shutil | ||
3129 | 7 | import subprocess | ||
3130 | 8 | import sys | ||
3131 | 9 | |||
3132 | 10 | from charmhelpers.core.hookenv import ( | ||
3133 | 11 | Hooks, | ||
3134 | 12 | UnregisteredHookError, | ||
3135 | 13 | config, | ||
3136 | 14 | remote_unit, | ||
3137 | 15 | relation_get, | ||
3138 | 16 | relation_set, | ||
3139 | 17 | relation_ids, | ||
3140 | 18 | unit_get, | ||
3141 | 19 | open_port, | ||
3142 | 20 | log, | ||
3143 | 21 | DEBUG, | ||
3144 | 22 | INFO, | ||
3145 | 23 | ) | ||
3146 | 24 | from charmhelpers.fetch import apt_install | ||
3147 | 25 | from charmhelpers.core.host import ( | ||
3148 | 26 | service_start, | ||
3149 | 27 | service_stop, | ||
3150 | 28 | ) | ||
3151 | 29 | from charmhelpers.payload.execd import execd_preinstall | ||
3152 | 30 | from jenkins_utils import ( | ||
3153 | 31 | JENKINS_HOME, | ||
3154 | 32 | JENKINS_USERS, | ||
3155 | 33 | TEMPLATES_DIR, | ||
3156 | 34 | add_node, | ||
3157 | 35 | del_node, | ||
3158 | 36 | setup_source, | ||
3159 | 37 | install_jenkins_plugins, | ||
3160 | 38 | ) | ||
3161 | 39 | |||
3162 | 40 | hooks = Hooks() | ||
3163 | 41 | |||
3164 | 42 | |||
3165 | 43 | @hooks.hook('install') | ||
3166 | 44 | def install(): | ||
3167 | 45 | execd_preinstall('hooks/install.d') | ||
3168 | 46 | # Only setup the source if jenkins is not already installed i.e. makes the | ||
3169 | 47 | # config 'release' immutable so you can't change source once deployed | ||
3170 | 48 | setup_source(config('release')) | ||
3171 | 49 | config_changed() | ||
3172 | 50 | open_port(8080) | ||
3173 | 51 | |||
3174 | 52 | |||
3175 | 53 | @hooks.hook('config-changed') | ||
3176 | 54 | def config_changed(): | ||
3177 | 55 | # Re-run whenever called to pickup any updates | ||
3178 | 56 | log("Installing/upgrading jenkins.", level=DEBUG) | ||
3179 | 57 | apt_install(['jenkins', 'default-jre-headless', 'pwgen'], fatal=True) | ||
3180 | 58 | |||
3181 | 59 | # Always run - even if config has not changed, its safe | ||
3182 | 60 | log("Configuring user for jenkins.", level=DEBUG) | ||
3183 | 61 | # Check to see if password provided | ||
3184 | 62 | admin_passwd = config('password') | ||
3185 | 63 | if not admin_passwd: | ||
3186 | 64 | # Generate a random one for security. User can then override using juju | ||
3187 | 65 | # set. | ||
3188 | 66 | admin_passwd = subprocess.check_output(['pwgen', '-N1', '15']) | ||
3189 | 67 | admin_passwd = admin_passwd.strip() | ||
3190 | 68 | |||
3191 | 69 | passwd_file = os.path.join(JENKINS_HOME, '.admin_password') | ||
3192 | 70 | with open(passwd_file, 'w+') as fd: | ||
3193 | 71 | fd.write(admin_passwd) | ||
3194 | 72 | |||
3195 | 73 | os.chmod(passwd_file, 0600) | ||
3196 | 74 | |||
3197 | 75 | jenkins_uid = pwd.getpwnam('jenkins').pw_uid | ||
3198 | 76 | jenkins_gid = grp.getgrnam('jenkins').gr_gid | ||
3199 | 77 | nogroup_gid = grp.getgrnam('nogroup').gr_gid | ||
3200 | 78 | |||
3201 | 79 | # Generate Salt and Hash Password for Jenkins | ||
3202 | 80 | salt = subprocess.check_output(['pwgen', '-N1', '6']).strip() | ||
3203 | 81 | csum = hashlib.sha256("%s{%s}" % (admin_passwd, salt)).hexdigest() | ||
3204 | 82 | salty_password = "%s:%s" % (salt, csum) | ||
3205 | 83 | |||
3206 | 84 | admin_username = config('username') | ||
3207 | 85 | admin_user_home = os.path.join(JENKINS_USERS, admin_username) | ||
3208 | 86 | if not os.path.isdir(admin_user_home): | ||
3209 | 87 | os.makedirs(admin_user_home, 0o0700) | ||
3210 | 88 | os.chown(JENKINS_USERS, jenkins_uid, nogroup_gid) | ||
3211 | 89 | os.chown(admin_user_home, jenkins_uid, nogroup_gid) | ||
3212 | 90 | |||
3213 | 91 | # NOTE: overwriting will destroy any data added by jenkins or via the ui | ||
3214 | 92 | admin_user_config = os.path.join(admin_user_home, 'config.xml') | ||
3215 | 93 | with open(os.path.join(TEMPLATES_DIR, 'user-config.xml')) as src_fd: | ||
3216 | 94 | with open(admin_user_config, 'w') as dst_fd: | ||
3217 | 95 | lines = src_fd.readlines() | ||
3218 | 96 | for line in lines: | ||
3219 | 97 | kvs = {'__USERNAME__': admin_username, | ||
3220 | 98 | '__PASSWORD__': salty_password} | ||
3221 | 99 | |||
3222 | 100 | for key, val in kvs.iteritems(): | ||
3223 | 101 | if key in line: | ||
3224 | 102 | line = line.replace(key, val) | ||
3225 | 103 | |||
3226 | 104 | dst_fd.write(line) | ||
3227 | 105 | os.chown(admin_user_config, jenkins_uid, nogroup_gid) | ||
3228 | 106 | |||
3229 | 107 | # Only run on first invocation otherwise we blast | ||
3230 | 108 | # any configuration changes made | ||
3231 | 109 | jenkins_bootstrap_flag = '/var/lib/jenkins/config.bootstrapped' | ||
3232 | 110 | if not os.path.exists(jenkins_bootstrap_flag): | ||
3233 | 111 | log("Bootstrapping secure initial configuration in Jenkins.", | ||
3234 | 112 | level=DEBUG) | ||
3235 | 113 | src = os.path.join(TEMPLATES_DIR, 'jenkins-config.xml') | ||
3236 | 114 | dst = os.path.join(JENKINS_HOME, 'config.xml') | ||
3237 | 115 | shutil.copy(src, dst) | ||
3238 | 116 | os.chown(dst, jenkins_uid, nogroup_gid) | ||
3239 | 117 | # Touch | ||
3240 | 118 | with open(jenkins_bootstrap_flag, 'w'): | ||
3241 | 119 | pass | ||
3242 | 120 | |||
3243 | 121 | log("Stopping jenkins for plugin update(s)", level=DEBUG) | ||
3244 | 122 | service_stop('jenkins') | ||
3245 | 123 | install_jenkins_plugins(jenkins_uid, jenkins_gid) | ||
3246 | 124 | log("Starting jenkins to pickup configuration changes", level=DEBUG) | ||
3247 | 125 | service_start('jenkins') | ||
3248 | 126 | |||
3249 | 127 | apt_install(['python-jenkins'], fatal=True) | ||
3250 | 128 | tools = config('tools') | ||
3251 | 129 | if tools: | ||
3252 | 130 | log("Installing tools.", level=DEBUG) | ||
3253 | 131 | apt_install(tools.split(), fatal=True) | ||
3254 | 132 | |||
3255 | 133 | |||
3256 | 134 | @hooks.hook('start') | ||
3257 | 135 | def start(): | ||
3258 | 136 | service_start('jenkins') | ||
3259 | 137 | |||
3260 | 138 | |||
3261 | 139 | @hooks.hook('stop') | ||
3262 | 140 | def stop(): | ||
3263 | 141 | service_stop('jenkins') | ||
3264 | 142 | |||
3265 | 143 | |||
3266 | 144 | @hooks.hook('upgrade-charm') | ||
3267 | 145 | def upgrade_charm(): | ||
3268 | 146 | log("Upgrading charm.", level=DEBUG) | ||
3269 | 147 | config_changed() | ||
3270 | 148 | |||
3271 | 149 | |||
3272 | 150 | @hooks.hook('master-relation-joined') | ||
3273 | 151 | def master_relation_joined(): | ||
3274 | 152 | HOSTNAME = unit_get('private-address') | ||
3275 | 153 | log("Setting url relation to http://%s:8080" % (HOSTNAME), level=DEBUG) | ||
3276 | 154 | relation_set(url="http://%s:8080" % (HOSTNAME)) | ||
3277 | 155 | |||
3278 | 156 | |||
3279 | 157 | @hooks.hook('master-relation-changed') | ||
3280 | 158 | def master_relation_changed(): | ||
3281 | 159 | PASSWORD = config('password') | ||
3282 | 160 | if PASSWORD: | ||
3283 | 161 | with open('/var/lib/jenkins/.admin_password', 'r') as fd: | ||
3284 | 162 | PASSWORD = fd.read() | ||
3285 | 163 | |||
3286 | 164 | required_settings = ['executors', 'labels', 'slavehost'] | ||
3287 | 165 | settings = relation_get() | ||
3288 | 166 | missing = [s for s in required_settings if s not in settings] | ||
3289 | 167 | if missing: | ||
3290 | 168 | log("Not all required relation settings received yet (missing=%s) - " | ||
3291 | 169 | "skipping" % (', '.join(missing)), level=INFO) | ||
3292 | 170 | return | ||
3293 | 171 | |||
3294 | 172 | slavehost = settings['slavehost'] | ||
3295 | 173 | executors = settings['executors'] | ||
3296 | 174 | labels = settings['labels'] | ||
3297 | 175 | |||
3298 | 176 | # Double check to see if this has happened yet | ||
3299 | 177 | if "x%s" % (slavehost) == "x": | ||
3300 | 178 | log("Slave host not yet defined - skipping", level=INFO) | ||
3301 | 179 | return | ||
3302 | 180 | |||
3303 | 181 | log("Adding slave with hostname %s." % (slavehost), level=DEBUG) | ||
3304 | 182 | add_node(slavehost, executors, labels, config('username'), PASSWORD) | ||
3305 | 183 | log("Node slave %s added." % (slavehost), level=DEBUG) | ||
3306 | 184 | |||
3307 | 185 | |||
3308 | 186 | @hooks.hook('master-relation-departed') | ||
3309 | 187 | def master_relation_departed(): | ||
3310 | 188 | # Slave hostname is derived from unit name so | ||
3311 | 189 | # this is pretty safe | ||
3312 | 190 | slavehost = remote_unit() | ||
3313 | 191 | log("Deleting slave with hostname %s." % (slavehost), level=DEBUG) | ||
3314 | 192 | del_node(slavehost, config('username'), config('password')) | ||
3315 | 193 | |||
3316 | 194 | |||
3317 | 195 | @hooks.hook('master-relation-broken') | ||
3318 | 196 | def master_relation_broken(): | ||
3319 | 197 | password = config('password') | ||
3320 | 198 | if not password: | ||
3321 | 199 | passwd_file = os.path.join(JENKINS_HOME, '.admin_password') | ||
3322 | 200 | with open(passwd_file, 'w+') as fd: | ||
3323 | 201 | PASSWORD = fd.read() | ||
3324 | 202 | |||
3325 | 203 | for member in relation_ids(): | ||
3326 | 204 | member = member.replace('/', '-') | ||
3327 | 205 | log("Removing node %s from Jenkins master." % (member), level=DEBUG) | ||
3328 | 206 | del_node(member, config('username'), PASSWORD) | ||
3329 | 207 | |||
3330 | 208 | |||
3331 | 209 | @hooks.hook('website-relation-joined') | ||
3332 | 210 | def website_relation_joined(): | ||
3333 | 211 | hostname = unit_get('private-address') | ||
3334 | 212 | log("Setting website URL to %s:8080" % (hostname), level=DEBUG) | ||
3335 | 213 | relation_set(port=8080, hostname=hostname) | ||
3336 | 214 | |||
3337 | 215 | |||
3338 | 216 | if __name__ == '__main__': | ||
3339 | 217 | try: | ||
3340 | 218 | hooks.execute(sys.argv) | ||
3341 | 219 | except UnregisteredHookError as e: | ||
3342 | 220 | log('Unknown hook {} - skipping.'.format(e), level=INFO) | ||
3343 | 0 | 221 | ||
3344 | === added file 'hooks/jenkins_utils.py' | |||
3345 | --- hooks/jenkins_utils.py 1970-01-01 00:00:00 +0000 | |||
3346 | +++ hooks/jenkins_utils.py 2015-01-20 18:33:44 +0000 | |||
3347 | @@ -0,0 +1,178 @@ | |||
3348 | 1 | #!/usr/bin/python | ||
3349 | 2 | import glob | ||
3350 | 3 | import os | ||
3351 | 4 | import shutil | ||
3352 | 5 | import subprocess | ||
3353 | 6 | import tempfile | ||
3354 | 7 | |||
3355 | 8 | from charmhelpers.core.hookenv import ( | ||
3356 | 9 | config, | ||
3357 | 10 | log, | ||
3358 | 11 | DEBUG, | ||
3359 | 12 | INFO, | ||
3360 | 13 | WARNING, | ||
3361 | 14 | ) | ||
3362 | 15 | from charmhelpers.fetch import ( | ||
3363 | 16 | apt_update, | ||
3364 | 17 | add_source, | ||
3365 | 18 | ) | ||
3366 | 19 | |||
3367 | 20 | from charmhelpers.core.decorators import ( | ||
3368 | 21 | retry_on_exception, | ||
3369 | 22 | ) | ||
3370 | 23 | |||
3371 | 24 | JENKINS_HOME = '/var/lib/jenkins' | ||
3372 | 25 | JENKINS_USERS = os.path.join(JENKINS_HOME, 'users') | ||
3373 | 26 | JENKINS_PLUGINS = os.path.join(JENKINS_HOME, 'plugins') | ||
3374 | 27 | TEMPLATES_DIR = 'templates' | ||
3375 | 28 | |||
3376 | 29 | |||
3377 | 30 | def add_node(host, executors, labels, username, password): | ||
3378 | 31 | import jenkins | ||
3379 | 32 | |||
3380 | 33 | @retry_on_exception(2, 2, exc_type=jenkins.JenkinsException) | ||
3381 | 34 | def _add_node(*args, **kwargs): | ||
3382 | 35 | l_jenkins = jenkins.Jenkins("http://localhost:8080/", username, | ||
3383 | 36 | password) | ||
3384 | 37 | |||
3385 | 38 | if l_jenkins.node_exists(host): | ||
3386 | 39 | log("Node exists - not adding", level=DEBUG) | ||
3387 | 40 | return | ||
3388 | 41 | |||
3389 | 42 | log("Adding node '%s' to Jenkins master" % (host), level=INFO) | ||
3390 | 43 | l_jenkins.create_node(host, int(executors) * 2, host, labels=labels) | ||
3391 | 44 | |||
3392 | 45 | if not l_jenkins.node_exists(host): | ||
3393 | 46 | log("Failed to create node '%s'" % (host), level=WARNING) | ||
3394 | 47 | |||
3395 | 48 | return _add_node() | ||
3396 | 49 | |||
3397 | 50 | |||
3398 | 51 | def del_node(host, username, password): | ||
3399 | 52 | import jenkins | ||
3400 | 53 | |||
3401 | 54 | l_jenkins = jenkins.Jenkins("http://localhost:8080/", username, password) | ||
3402 | 55 | |||
3403 | 56 | if l_jenkins.node_exists(host): | ||
3404 | 57 | log("Node '%s' exists" % (host), level=DEBUG) | ||
3405 | 58 | l_jenkins.delete_node(host) | ||
3406 | 59 | else: | ||
3407 | 60 | log("Node '%s' does not exist - not deleting" % (host), level=INFO) | ||
3408 | 61 | |||
3409 | 62 | |||
3410 | 63 | def setup_source(release): | ||
3411 | 64 | """Install Jenkins archive.""" | ||
3412 | 65 | log("Configuring source of jenkins as %s" % release, level=INFO) | ||
3413 | 66 | |||
3414 | 67 | # Configure to use upstream archives | ||
3415 | 68 | # lts - debian-stable | ||
3416 | 69 | # trunk - debian | ||
3417 | 70 | if release == 'lts': | ||
3418 | 71 | source = "debian-stable" | ||
3419 | 72 | elif release == 'trunk': | ||
3420 | 73 | source = "debian" | ||
3421 | 74 | else: | ||
3422 | 75 | errmsg = "Release '%s' configuration not recognised" % (release) | ||
3423 | 76 | raise Exception(errmsg) | ||
3424 | 77 | |||
3425 | 78 | # Setup archive to use appropriate jenkins upstream | ||
3426 | 79 | key = 'http://pkg.jenkins-ci.org/%s/jenkins-ci.org.key' % source | ||
3427 | 80 | target = "%s-%s" % (source, 'jenkins-ci.org.key') | ||
3428 | 81 | subprocess.check_call(['wget', '-q', '-O', target, key]) | ||
3429 | 82 | with open(target, 'r') as fd: | ||
3430 | 83 | key = fd.read() | ||
3431 | 84 | |||
3432 | 85 | deb = "deb http://pkg.jenkins-ci.org/%s binary/" % (source) | ||
3433 | 86 | sources_file = "/etc/apt/sources.list.d/jenkins.list" | ||
3434 | 87 | |||
3435 | 88 | found = False | ||
3436 | 89 | if os.path.exists(sources_file): | ||
3437 | 90 | with open(sources_file, 'r') as fd: | ||
3438 | 91 | for line in fd: | ||
3439 | 92 | if deb in line: | ||
3440 | 93 | found = True | ||
3441 | 94 | break | ||
3442 | 95 | |||
3443 | 96 | if not found: | ||
3444 | 97 | with open(sources_file, 'a') as fd: | ||
3445 | 98 | fd.write("%s\n" % deb) | ||
3446 | 99 | else: | ||
3447 | 100 | with open(sources_file, 'w') as fd: | ||
3448 | 101 | fd.write("%s\n" % deb) | ||
3449 | 102 | |||
3450 | 103 | if not found: | ||
3451 | 104 | # NOTE: don't use add_source for adding source since it adds deb and | ||
3452 | 105 | # deb-src entries but pkg.jenkins-ci.org has no deb-src. | ||
3453 | 106 | add_source("#dummy-source", key=key) | ||
3454 | 107 | |||
3455 | 108 | apt_update(fatal=True) | ||
3456 | 109 | |||
3457 | 110 | |||
3458 | 111 | def install_jenkins_plugins(jenkins_uid, jenkins_gid): | ||
3459 | 112 | plugins = config('plugins') | ||
3460 | 113 | if plugins: | ||
3461 | 114 | plugins = plugins.split() | ||
3462 | 115 | else: | ||
3463 | 116 | plugins = [] | ||
3464 | 117 | |||
3465 | 118 | log("Installing plugins (%s)" % (' '.join(plugins)), level=DEBUG) | ||
3466 | 119 | if not os.path.isdir(JENKINS_PLUGINS): | ||
3467 | 120 | os.makedirs(JENKINS_PLUGINS) | ||
3468 | 121 | |||
3469 | 122 | os.chmod(JENKINS_PLUGINS, 0o0755) | ||
3470 | 123 | os.chown(JENKINS_PLUGINS, jenkins_uid, jenkins_gid) | ||
3471 | 124 | |||
3472 | 125 | track_dir = tempfile.mkdtemp(prefix='/tmp/plugins.installed') | ||
3473 | 126 | try: | ||
3474 | 127 | installed_plugins = glob.glob("%s/*.hpi" % (JENKINS_PLUGINS)) | ||
3475 | 128 | for plugin in installed_plugins: | ||
3476 | 129 | # Create a ref of installed plugin | ||
3477 | 130 | with open(os.path.join(track_dir, os.path.basename(plugin)), | ||
3478 | 131 | 'w'): | ||
3479 | 132 | pass | ||
3480 | 133 | |||
3481 | 134 | plugins_site = config('plugins-site') | ||
3482 | 135 | log("Fetching plugins from %s" % (plugins_site), level=DEBUG) | ||
3483 | 136 | # NOTE: by default wget verifies certificates as of 1.10. | ||
3484 | 137 | if config('plugins-check-certificate') == "no": | ||
3485 | 138 | opts = ["--no-check-certificate"] | ||
3486 | 139 | else: | ||
3487 | 140 | opts = [] | ||
3488 | 141 | |||
3489 | 142 | for plugin in plugins: | ||
3490 | 143 | plugin_filename = "%s.hpi" % (plugin) | ||
3491 | 144 | url = os.path.join(plugins_site, 'latest', plugin_filename) | ||
3492 | 145 | plugin_path = os.path.join(JENKINS_PLUGINS, plugin_filename) | ||
3493 | 146 | if not os.path.isfile(plugin_path): | ||
3494 | 147 | log("Installing plugin %s" % (plugin_filename), level=DEBUG) | ||
3495 | 148 | cmd = ['wget'] + opts + ['--timestamping', url, '-O', | ||
3496 | 149 | plugin_path] | ||
3497 | 150 | subprocess.check_call(cmd) | ||
3498 | 151 | os.chmod(plugin_path, 0744) | ||
3499 | 152 | os.chown(plugin_path, jenkins_uid, jenkins_gid) | ||
3500 | 153 | |||
3501 | 154 | else: | ||
3502 | 155 | log("Plugin %s already installed" % (plugin_filename), | ||
3503 | 156 | level=DEBUG) | ||
3504 | 157 | |||
3505 | 158 | ref = os.path.join(track_dir, plugin_filename) | ||
3506 | 159 | if os.path.exists(ref): | ||
3507 | 160 | # Delete ref since plugin is installed. | ||
3508 | 161 | os.remove(ref) | ||
3509 | 162 | |||
3510 | 163 | installed_plugins = os.listdir(track_dir) | ||
3511 | 164 | if installed_plugins: | ||
3512 | 165 | if config('remove-unlisted-plugins') == "yes": | ||
3513 | 166 | for plugin in installed_plugins: | ||
3514 | 167 | path = os.path.join(JENKINS_HOME, 'plugins', plugin) | ||
3515 | 168 | if os.path.isfile(path): | ||
3516 | 169 | log("Deleting unlisted plugin '%s'" % (path), | ||
3517 | 170 | level=INFO) | ||
3518 | 171 | os.remove(path) | ||
3519 | 172 | else: | ||
3520 | 173 | log("Unlisted plugins: (%s) Not removed. Set " | ||
3521 | 174 | "remove-unlisted-plugins to 'yes' to clear them away." % | ||
3522 | 175 | ', '.join(installed_plugins), level=INFO) | ||
3523 | 176 | finally: | ||
3524 | 177 | # Delete install refs | ||
3525 | 178 | shutil.rmtree(track_dir) | ||
3526 | 0 | 179 | ||
3527 | === modified file 'hooks/master-relation-broken' | |||
3528 | --- hooks/master-relation-broken 2012-07-31 10:32:36 +0000 | |||
3529 | +++ hooks/master-relation-broken 1970-01-01 00:00:00 +0000 | |||
3530 | @@ -1,17 +0,0 @@ | |||
3531 | 1 | #!/bin/sh | ||
3532 | 2 | |||
3533 | 3 | PASSWORD=`config-get password` | ||
3534 | 4 | if [ -z "$PASSWORD" ] | ||
3535 | 5 | then | ||
3536 | 6 | PASSWORD=`cat /var/lib/jenkins/.admin_password` | ||
3537 | 7 | fi | ||
3538 | 8 | |||
3539 | 9 | MEMBERS=`relation-list` | ||
3540 | 10 | |||
3541 | 11 | for MEMBER in $MEMBERS | ||
3542 | 12 | do | ||
3543 | 13 | juju-log "Removing node $MEMBER from Jenkins master..." | ||
3544 | 14 | $(dirname $0)/delnode `echo $MEMBER | sed s,/,-,` `config-get username` $PASSWORD | ||
3545 | 15 | done | ||
3546 | 16 | |||
3547 | 17 | exit 0 | ||
3548 | 18 | 0 | ||
3549 | === target is u'jenkins_hooks.py' | |||
3550 | === modified file 'hooks/master-relation-changed' | |||
3551 | --- hooks/master-relation-changed 2012-07-31 10:32:36 +0000 | |||
3552 | +++ hooks/master-relation-changed 1970-01-01 00:00:00 +0000 | |||
3553 | @@ -1,24 +0,0 @@ | |||
3554 | 1 | #!/bin/bash | ||
3555 | 2 | |||
3556 | 3 | set -ue | ||
3557 | 4 | |||
3558 | 5 | PASSWORD=`config-get password` | ||
3559 | 6 | if [ -z "$PASSWORD" ] | ||
3560 | 7 | then | ||
3561 | 8 | PASSWORD=`cat /var/lib/jenkins/.admin_password` | ||
3562 | 9 | fi | ||
3563 | 10 | |||
3564 | 11 | # Grab information that remote unit has posted to relation | ||
3565 | 12 | slavehost=$(relation-get slavehost) | ||
3566 | 13 | executors=$(relation-get executors) | ||
3567 | 14 | labels=$(relation-get labels) | ||
3568 | 15 | |||
3569 | 16 | # Double check to see if this has happened yet | ||
3570 | 17 | if [ "x$slavehost" = "x" ]; then | ||
3571 | 18 | juju-log "Slave host not yet defined, exiting..." | ||
3572 | 19 | exit 0 | ||
3573 | 20 | fi | ||
3574 | 21 | |||
3575 | 22 | juju-log "Adding slave with hostname $slavehost..." | ||
3576 | 23 | $(dirname $0)/addnode $slavehost $executors "$labels" `config-get username` $PASSWORD | ||
3577 | 24 | juju-log "Node slave $slavehost added..." | ||
3578 | 25 | 0 | ||
3579 | === target is u'jenkins_hooks.py' | |||
3580 | === modified file 'hooks/master-relation-departed' | |||
3581 | --- hooks/master-relation-departed 2011-09-22 14:46:56 +0000 | |||
3582 | +++ hooks/master-relation-departed 1970-01-01 00:00:00 +0000 | |||
3583 | @@ -1,12 +0,0 @@ | |||
3584 | 1 | #!/bin/bash | ||
3585 | 2 | |||
3586 | 3 | set -ue | ||
3587 | 4 | |||
3588 | 5 | # Slave hostname is derived from unit name so | ||
3589 | 6 | # this is pretty safe | ||
3590 | 7 | slavehost=`echo $JUJU_REMOTE_UNIT | sed s,/,-,` | ||
3591 | 8 | |||
3592 | 9 | juju-log "Deleting slave with hostname $slavehost..." | ||
3593 | 10 | $(dirname $0)/delnode $slavehost `config-get username` `config-get password` | ||
3594 | 11 | |||
3595 | 12 | exit 0 | ||
3596 | 13 | 0 | ||
3597 | === target is u'jenkins_hooks.py' | |||
3598 | === modified file 'hooks/master-relation-joined' | |||
3599 | --- hooks/master-relation-joined 2011-10-07 13:43:19 +0000 | |||
3600 | +++ hooks/master-relation-joined 1970-01-01 00:00:00 +0000 | |||
3601 | @@ -1,5 +0,0 @@ | |||
3602 | 1 | #!/bin/sh | ||
3603 | 2 | |||
3604 | 3 | HOSTNAME=`unit-get private-address` | ||
3605 | 4 | juju-log "Setting url relation to http://$HOSTNAME:8080" | ||
3606 | 5 | relation-set url="http://$HOSTNAME:8080" | ||
3607 | 6 | 0 | ||
3608 | === target is u'jenkins_hooks.py' | |||
3609 | === modified file 'hooks/start' | |||
3610 | --- hooks/start 2011-09-22 14:46:56 +0000 | |||
3611 | +++ hooks/start 1970-01-01 00:00:00 +0000 | |||
3612 | @@ -1,3 +0,0 @@ | |||
3613 | 1 | #!/bin/bash | ||
3614 | 2 | |||
3615 | 3 | service jenkins start || true | ||
3616 | 4 | 0 | ||
3617 | === target is u'jenkins_hooks.py' | |||
3618 | === modified file 'hooks/stop' | |||
3619 | --- hooks/stop 2011-09-22 14:46:56 +0000 | |||
3620 | +++ hooks/stop 1970-01-01 00:00:00 +0000 | |||
3621 | @@ -1,3 +0,0 @@ | |||
3622 | 1 | #!/bin/bash | ||
3623 | 2 | |||
3624 | 3 | service jenkins stop | ||
3625 | 4 | 0 | ||
3626 | === target is u'jenkins_hooks.py' | |||
3627 | === modified file 'hooks/upgrade-charm' | |||
3628 | --- hooks/upgrade-charm 2011-09-22 14:46:56 +0000 | |||
3629 | +++ hooks/upgrade-charm 1970-01-01 00:00:00 +0000 | |||
3630 | @@ -1,7 +0,0 @@ | |||
3631 | 1 | #!/bin/sh | ||
3632 | 2 | set -e | ||
3633 | 3 | |||
3634 | 4 | home=`dirname $0` | ||
3635 | 5 | |||
3636 | 6 | juju-log "Upgrading charm by running install hook again." | ||
3637 | 7 | exec $home/install | ||
3638 | 8 | 0 | ||
3639 | === target is u'jenkins_hooks.py' | |||
3640 | === modified file 'hooks/website-relation-joined' | |||
3641 | --- hooks/website-relation-joined 2011-10-07 13:43:19 +0000 | |||
3642 | +++ hooks/website-relation-joined 1970-01-01 00:00:00 +0000 | |||
3643 | @@ -1,5 +0,0 @@ | |||
3644 | 1 | #!/bin/sh | ||
3645 | 2 | |||
3646 | 3 | HOSTNAME=`unit-get private-address` | ||
3647 | 4 | juju-log "Setting website URL to $HOSTNAME:8080" | ||
3648 | 5 | relation-set port=8080 hostname=$HOSTNAME | ||
3649 | 6 | 0 | ||
3650 | === target is u'jenkins_hooks.py' | |||
3651 | === renamed file 'tests/100-deploy' => 'tests/100-deploy-trusty' | |||
3652 | --- tests/100-deploy 2014-03-05 19:18:19 +0000 | |||
3653 | +++ tests/100-deploy-trusty 2015-01-20 18:33:44 +0000 | |||
3654 | @@ -12,11 +12,13 @@ | |||
3655 | 12 | ### | 12 | ### |
3656 | 13 | # Deployment Setup | 13 | # Deployment Setup |
3657 | 14 | ### | 14 | ### |
3659 | 15 | d = amulet.Deployment() | 15 | d = amulet.Deployment(series='trusty') |
3660 | 16 | 16 | ||
3661 | 17 | d.add('haproxy') # website-relation | 17 | d.add('haproxy') # website-relation |
3662 | 18 | d.add('jenkins') # Subject matter | 18 | d.add('jenkins') # Subject matter |
3664 | 19 | d.add('jenkins-slave') # Job Runner | 19 | # TODO(hopem): we don't yet have a precise version of jenkins-slave |
3665 | 20 | # so use the precise version for now. | ||
3666 | 21 | d.add('jenkins-slave', 'cs:precise/jenkins-slave') # Job Runner | ||
3667 | 20 | 22 | ||
3668 | 21 | 23 | ||
3669 | 22 | d.relate('jenkins:website', 'haproxy:reverseproxy') | 24 | d.relate('jenkins:website', 'haproxy:reverseproxy') |
3670 | 23 | 25 | ||
3671 | === added file 'tests/README' | |||
3672 | --- tests/README 1970-01-01 00:00:00 +0000 | |||
3673 | +++ tests/README 2015-01-20 18:33:44 +0000 | |||
3674 | @@ -0,0 +1,56 @@ | |||
3675 | 1 | This directory provides Amulet tests that focus on verification of Jenkins | ||
3676 | 2 | deployments. | ||
3677 | 3 | |||
3678 | 4 | In order to run tests, you'll need charm-tools installed (in addition to | ||
3679 | 5 | juju, of course): | ||
3680 | 6 | |||
3681 | 7 | sudo add-apt-repository ppa:juju/stable | ||
3682 | 8 | sudo apt-get update | ||
3683 | 9 | sudo apt-get install charm-tools | ||
3684 | 10 | |||
3685 | 11 | If you use a web proxy server to access the web, you'll need to set the | ||
3686 | 12 | AMULET_HTTP_PROXY environment variable to the http URL of the proxy server. | ||
3687 | 13 | |||
3688 | 14 | The following examples demonstrate different ways that tests can be executed. | ||
3689 | 15 | All examples are run from the charm's root directory. | ||
3690 | 16 | |||
3691 | 17 | * To run all tests (starting with 00-setup): | ||
3692 | 18 | |||
3693 | 19 | make test | ||
3694 | 20 | |||
3695 | 21 | * To run a specific test module (or modules): | ||
3696 | 22 | |||
3697 | 23 | juju test -v -p AMULET_HTTP_PROXY 100-deploy | ||
3698 | 24 | |||
3699 | 25 | * To run a specific test module (or modules), and keep the environment | ||
3700 | 26 | deployed after a failure: | ||
3701 | 27 | |||
3702 | 28 | juju test --set-e -v -p AMULET_HTTP_PROXY 100-deploy | ||
3703 | 29 | |||
3704 | 30 | * To re-run a test module against an already deployed environment (one | ||
3705 | 31 | that was deployed by a previous call to 'juju test --set-e'): | ||
3706 | 32 | |||
3707 | 33 | ./tests/100-deploy | ||
3708 | 34 | |||
3709 | 35 | |||
3710 | 36 | For debugging and test development purposes, all code should be idempotent. | ||
3711 | 37 | In other words, the code should have the ability to be re-run without changing | ||
3712 | 38 | the results beyond the initial run. This enables editing and re-running of a | ||
3713 | 39 | test module against an already deployed environment, as described above. | ||
3714 | 40 | |||
3715 | 41 | |||
3716 | 42 | Notes for additional test writing: | ||
3717 | 43 | |||
3718 | 44 | * Use DEBUG to turn on debug logging, use ERROR otherwise. | ||
3719 | 45 | u = OpenStackAmuletUtils(ERROR) | ||
3720 | 46 | u = OpenStackAmuletUtils(DEBUG) | ||
3721 | 47 | |||
3722 | 48 | * Preserving the deployed environment: | ||
3723 | 49 | Even with juju --set-e, amulet will tear down the juju environment | ||
3724 | 50 | when all tests pass. This force_fail 'test' can be used in basic_deployment.py | ||
3725 | 51 | to simulate a failed test and keep the environment. | ||
3726 | 52 | |||
3727 | 53 | def test_zzzz_fake_fail(self): | ||
3728 | 54 | '''Force a fake fail to keep juju environment after a successful test run''' | ||
3729 | 55 | # Useful in test writing, when used with: juju test --set-e | ||
3730 | 56 | amulet.raise_status(amulet.FAIL, msg='using fake fail to keep juju environment') | ||
3731 | 0 | 57 | ||
3732 | === added directory 'unit_tests' | |||
3733 | === added file 'unit_tests/__init__.py' | |||
3734 | === added file 'unit_tests/test_jenkins_hooks.py' | |||
3735 | --- unit_tests/test_jenkins_hooks.py 1970-01-01 00:00:00 +0000 | |||
3736 | +++ unit_tests/test_jenkins_hooks.py 2015-01-20 18:33:44 +0000 | |||
3737 | @@ -0,0 +1,6 @@ | |||
3738 | 1 | import unittest | ||
3739 | 2 | |||
3740 | 3 | |||
3741 | 4 | class JenkinsHooksTests(unittest.TestCase): | ||
3742 | 5 | def setUp(self): | ||
3743 | 6 | super(JenkinsHooksTests, self).setUp() | ||
3744 | 0 | 7 | ||
3745 | === added file 'unit_tests/test_jenkins_utils.py' | |||
3746 | --- unit_tests/test_jenkins_utils.py 1970-01-01 00:00:00 +0000 | |||
3747 | +++ unit_tests/test_jenkins_utils.py 2015-01-20 18:33:44 +0000 | |||
3748 | @@ -0,0 +1,6 @@ | |||
3749 | 1 | import unittest | ||
3750 | 2 | |||
3751 | 3 | |||
3752 | 4 | class JenkinsUtilsTests(unittest.TestCase): | ||
3753 | 5 | def setUp(self): | ||
3754 | 6 | super(JenkinsUtilsTests, self).setUp() |
This items has failed automated testing! Results available here http:// reports. vapour. ws/charm- tests/charm- bundle- test-10336- results