Merge lp:~facundo/charms/trusty/tanuki-spec-manager/first-draft into lp:~tanuki/charms/trusty/tanuki-spec-manager/trunk
- Trusty Tahr (14.04)
- first-draft
- Merge into trunk
Proposed by
Facundo Batista
Status: | Merged |
---|---|
Merged at revision: | 3 |
Proposed branch: | lp:~facundo/charms/trusty/tanuki-spec-manager/first-draft |
Merge into: | lp:~tanuki/charms/trusty/tanuki-spec-manager/trunk |
Diff against target: |
11661 lines (+11245/-0) 74 files modified
README (+15/-0) config.yaml (+10/-0) hooks/actions.py (+94/-0) hooks/charmhelpers/__init__.py (+38/-0) hooks/charmhelpers/contrib/__init__.py (+15/-0) hooks/charmhelpers/contrib/amulet/__init__.py (+15/-0) hooks/charmhelpers/contrib/amulet/deployment.py (+93/-0) hooks/charmhelpers/contrib/amulet/utils.py (+194/-0) hooks/charmhelpers/contrib/ansible/__init__.py (+190/-0) hooks/charmhelpers/contrib/charmhelpers/__init__.py (+208/-0) hooks/charmhelpers/contrib/charmsupport/__init__.py (+15/-0) hooks/charmhelpers/contrib/charmsupport/nrpe.py (+324/-0) hooks/charmhelpers/contrib/charmsupport/volumes.py (+175/-0) hooks/charmhelpers/contrib/database/mysql.py (+372/-0) hooks/charmhelpers/contrib/hahelpers/__init__.py (+15/-0) hooks/charmhelpers/contrib/hahelpers/apache.py (+82/-0) hooks/charmhelpers/contrib/hahelpers/cluster.py (+268/-0) hooks/charmhelpers/contrib/network/__init__.py (+15/-0) hooks/charmhelpers/contrib/network/ip.py (+367/-0) hooks/charmhelpers/contrib/network/ovs/__init__.py (+96/-0) hooks/charmhelpers/contrib/network/ufw.py (+276/-0) hooks/charmhelpers/contrib/openstack/__init__.py (+15/-0) hooks/charmhelpers/contrib/openstack/alternatives.py (+33/-0) hooks/charmhelpers/contrib/openstack/amulet/__init__.py (+15/-0) hooks/charmhelpers/contrib/openstack/amulet/deployment.py (+108/-0) hooks/charmhelpers/contrib/openstack/amulet/utils.py (+294/-0) hooks/charmhelpers/contrib/openstack/context.py (+1054/-0) hooks/charmhelpers/contrib/openstack/ip.py (+109/-0) hooks/charmhelpers/contrib/openstack/neutron.py (+239/-0) hooks/charmhelpers/contrib/openstack/templates/__init__.py (+18/-0) hooks/charmhelpers/contrib/openstack/templating.py (+295/-0) hooks/charmhelpers/contrib/openstack/utils.py (+641/-0) hooks/charmhelpers/contrib/peerstorage/__init__.py (+148/-0) hooks/charmhelpers/contrib/python/__init__.py (+15/-0) hooks/charmhelpers/contrib/python/debug.py (+56/-0) hooks/charmhelpers/contrib/python/packages.py (+96/-0) hooks/charmhelpers/contrib/python/rpdb.py (+58/-0) hooks/charmhelpers/contrib/python/version.py (+34/-0) hooks/charmhelpers/contrib/saltstack/__init__.py (+118/-0) hooks/charmhelpers/contrib/ssl/__init__.py (+94/-0) hooks/charmhelpers/contrib/ssl/service.py (+283/-0) hooks/charmhelpers/contrib/storage/__init__.py (+15/-0) hooks/charmhelpers/contrib/storage/linux/__init__.py (+15/-0) hooks/charmhelpers/contrib/storage/linux/ceph.py (+444/-0) hooks/charmhelpers/contrib/storage/linux/loopback.py (+78/-0) hooks/charmhelpers/contrib/storage/linux/lvm.py (+105/-0) hooks/charmhelpers/contrib/storage/linux/utils.py (+70/-0) hooks/charmhelpers/contrib/templating/__init__.py (+15/-0) hooks/charmhelpers/contrib/templating/contexts.py (+134/-0) hooks/charmhelpers/contrib/templating/jinja.py (+39/-0) hooks/charmhelpers/contrib/templating/pyformat.py (+29/-0) hooks/charmhelpers/contrib/unison/__init__.py (+297/-0) hooks/charmhelpers/core/__init__.py (+15/-0) hooks/charmhelpers/core/decorators.py (+57/-0) hooks/charmhelpers/core/fstab.py (+134/-0) hooks/charmhelpers/core/hookenv.py (+568/-0) hooks/charmhelpers/core/host.py (+446/-0) hooks/charmhelpers/core/services/__init__.py (+18/-0) hooks/charmhelpers/core/services/base.py (+329/-0) hooks/charmhelpers/core/services/helpers.py (+259/-0) hooks/charmhelpers/core/sysctl.py (+56/-0) hooks/charmhelpers/core/templating.py (+68/-0) hooks/charmhelpers/core/unitdata.py (+477/-0) hooks/charmhelpers/fetch/__init__.py (+439/-0) hooks/charmhelpers/fetch/archiveurl.py (+161/-0) hooks/charmhelpers/fetch/bzrurl.py (+78/-0) hooks/charmhelpers/fetch/giturl.py (+71/-0) hooks/charmhelpers/payload/__init__.py (+17/-0) hooks/charmhelpers/payload/archive.py (+73/-0) hooks/charmhelpers/payload/execd.py (+66/-0) hooks/hooks.py (+3/-0) hooks/services.py (+31/-0) metadata.yaml (+9/-0) templates/upstart.conf (+29/-0) |
To merge this branch: | bzr merge lp:~facundo/charms/trusty/tanuki-spec-manager/first-draft |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Celso Providelo (community) | Approve | ||
Facundo Batista (community) | Approve | ||
Review via email: mp+262345@code.launchpad.net |
Commit message
First draft of the charm for Spec Manager.
Description of the change
First draft of the charm for Spec Manager.
To post a comment you must log in.
- 2. By Facundo Batista
-
Better website relation management.
Revision history for this message
Facundo Batista (facundo) wrote : | # |
Done! will land
review:
Approve
- 3. By Facundo Batista
-
Proper cleaning and website relation handling.
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === added file 'README' | |||
2 | --- README 1970-01-01 00:00:00 +0000 | |||
3 | +++ README 2015-06-18 17:19:58 +0000 | |||
4 | @@ -0,0 +1,15 @@ | |||
5 | 1 | Overview | ||
6 | 2 | -------- | ||
7 | 3 | |||
8 | 4 | This charm provides the Spec Manager from lp:tanuki-spec-manager | ||
9 | 5 | |||
10 | 6 | Configuration | ||
11 | 7 | ------------- | ||
12 | 8 | |||
13 | 9 | There are only two config options for this charm: | ||
14 | 10 | * config-file: A base64 encoded string with the config file to use for | ||
15 | 11 | adt-cloud-service. | ||
16 | 12 | * environment: a string, one of "development" or "production" | ||
17 | 13 | |||
18 | 14 | NOTE: This expects the payload code in the form of spec-manager.tgz | ||
19 | 15 | to exist with the snapshot of lp:tanuki-spec-manager that needs deploying | ||
20 | 0 | 16 | ||
21 | === added file 'config.yaml' | |||
22 | --- config.yaml 1970-01-01 00:00:00 +0000 | |||
23 | +++ config.yaml 2015-06-18 17:19:58 +0000 | |||
24 | @@ -0,0 +1,10 @@ | |||
25 | 1 | options: | ||
26 | 2 | environment: | ||
27 | 3 | type: string | ||
28 | 4 | default: "production" | ||
29 | 5 | description: | | ||
30 | 6 | Environment (devel, staging, production, etc.) that we're running. | ||
31 | 7 | config-file: | ||
32 | 8 | type: string | ||
33 | 9 | description: | | ||
34 | 10 | base64 encoded string with the config file for adt-cloud-worker | ||
35 | 0 | 11 | ||
36 | === added directory 'files' | |||
37 | === added directory 'hooks' | |||
38 | === added file 'hooks/actions.py' | |||
39 | --- hooks/actions.py 1970-01-01 00:00:00 +0000 | |||
40 | +++ hooks/actions.py 2015-06-18 17:19:58 +0000 | |||
41 | @@ -0,0 +1,94 @@ | |||
42 | 1 | import base64 | ||
43 | 2 | import os | ||
44 | 3 | import subprocess | ||
45 | 4 | |||
46 | 5 | from charmhelpers import fetch | ||
47 | 6 | from charmhelpers.core import ( | ||
48 | 7 | hookenv, | ||
49 | 8 | host, | ||
50 | 9 | ) | ||
51 | 10 | from charmhelpers.core.services import helpers | ||
52 | 11 | from charmhelpers.payload import (archive, execd) | ||
53 | 12 | |||
54 | 13 | |||
55 | 14 | REQUIRED_PACKAGES = [ | ||
56 | 15 | 'python-virtualenv', 'python3-dev', | ||
57 | 16 | ] | ||
58 | 17 | |||
59 | 18 | WSGI_USER = 'www-data' | ||
60 | 19 | WSGI_GROUP = 'www-data' | ||
61 | 20 | |||
62 | 21 | config = hookenv.config() | ||
63 | 22 | |||
64 | 23 | SERVICE_DIR = '/srv/{}/spec-manager'.format(config['environment']) | ||
65 | 24 | LOG_DIR = os.path.join(SERVICE_DIR, 'logs') | ||
66 | 25 | |||
67 | 26 | |||
68 | 27 | def log_start(service_name): | ||
69 | 28 | hookenv.log('spec-manager starting') | ||
70 | 29 | |||
71 | 30 | |||
72 | 31 | def basenode(service_name): | ||
73 | 32 | hookenv.log("Executing basenode") | ||
74 | 33 | execd.execd_preinstall() | ||
75 | 34 | |||
76 | 35 | |||
77 | 36 | def install_packages(service_name): | ||
78 | 37 | hookenv.log('Installing dependencies...') | ||
79 | 38 | fetch.configure_sources(update=True) | ||
80 | 39 | fetch.apt_install(REQUIRED_PACKAGES, fatal=True) | ||
81 | 40 | |||
82 | 41 | |||
83 | 42 | def get_cloud_service_from_tarball(service_name): | ||
84 | 43 | files_dir = os.path.join(hookenv.charm_dir(), 'files') | ||
85 | 44 | tarball = os.path.join(files_dir, 'spec-manager.tgz') | ||
86 | 45 | if not os.path.exists(SERVICE_DIR): | ||
87 | 46 | hookenv.log('Installing the code for the first time from tarball') | ||
88 | 47 | archive.extract_tarfile(tarball, os.path.dirname(SERVICE_DIR)) | ||
89 | 48 | |||
90 | 49 | |||
91 | 50 | def get_config_file(service_name): | ||
92 | 51 | config_file = config.get('config-file') | ||
93 | 52 | if config_file is not None: | ||
94 | 53 | with open(os.path.join(SERVICE_DIR, 'spec-manager.conf'), 'w') as f: | ||
95 | 54 | f.write(base64.b64decode(config_file)) | ||
96 | 55 | |||
97 | 56 | |||
98 | 57 | def install_python_packages(service_name): | ||
99 | 58 | env_dir = os.path.join(SERVICE_DIR, 'env') | ||
100 | 59 | if os.path.exists(env_dir): | ||
101 | 60 | hookenv.log('Service venv already exists, nothing to do ...') | ||
102 | 61 | return | ||
103 | 62 | |||
104 | 63 | hookenv.log('Installing python packages into the venv ...') | ||
105 | 64 | subprocess.check_call(['virtualenv', '-p', 'python3', env_dir]) | ||
106 | 65 | |||
107 | 66 | pip_cache = os.path.join(hookenv.charm_dir(), 'files', 'pip-cache') | ||
108 | 67 | requirements = os.path.join(SERVICE_DIR, 'requirements_run.txt') | ||
109 | 68 | |||
110 | 69 | hookenv.log('Installing from download cache.') | ||
111 | 70 | subprocess.check_call(['%s/bin/pip' % env_dir, | ||
112 | 71 | 'install', | ||
113 | 72 | '--no-index', | ||
114 | 73 | '--find-links={}'.format(pip_cache), | ||
115 | 74 | '-r', requirements]) | ||
116 | 75 | |||
117 | 76 | subprocess.check_call(['%s/bin/pip' % env_dir, | ||
118 | 77 | 'install', '--no-deps', '-e', SERVICE_DIR]) | ||
119 | 78 | |||
120 | 79 | |||
121 | 80 | def prepare_for_wsgi(service_name): | ||
122 | 81 | host.adduser(WSGI_USER) | ||
123 | 82 | host.add_group(WSGI_GROUP) | ||
124 | 83 | host.add_user_to_group(WSGI_USER, WSGI_GROUP) | ||
125 | 84 | if not os.path.exists(LOG_DIR): | ||
126 | 85 | host.mkdir(LOG_DIR, WSGI_USER, WSGI_GROUP, perms=0o755) | ||
127 | 86 | |||
128 | 87 | |||
129 | 88 | class WebsiteRelation(helpers.HttpRelation): | ||
130 | 89 | |||
131 | 90 | def provide_data(self): | ||
132 | 91 | hookenv.log('Providing Website relation data.') | ||
133 | 92 | data = super(WebsiteRelation, self).provide_data() | ||
134 | 93 | data['port'] = 8000 | ||
135 | 94 | return data | ||
136 | 0 | 95 | ||
137 | === added directory 'hooks/charmhelpers' | |||
138 | === added file 'hooks/charmhelpers/__init__.py' | |||
139 | --- hooks/charmhelpers/__init__.py 1970-01-01 00:00:00 +0000 | |||
140 | +++ hooks/charmhelpers/__init__.py 2015-06-18 17:19:58 +0000 | |||
141 | @@ -0,0 +1,38 @@ | |||
142 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
143 | 2 | # | ||
144 | 3 | # This file is part of charm-helpers. | ||
145 | 4 | # | ||
146 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
147 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
148 | 7 | # published by the Free Software Foundation. | ||
149 | 8 | # | ||
150 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
151 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
152 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
153 | 12 | # GNU Lesser General Public License for more details. | ||
154 | 13 | # | ||
155 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
156 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
157 | 16 | |||
158 | 17 | # Bootstrap charm-helpers, installing its dependencies if necessary using | ||
159 | 18 | # only standard libraries. | ||
160 | 19 | import subprocess | ||
161 | 20 | import sys | ||
162 | 21 | |||
163 | 22 | try: | ||
164 | 23 | import six # flake8: noqa | ||
165 | 24 | except ImportError: | ||
166 | 25 | if sys.version_info.major == 2: | ||
167 | 26 | subprocess.check_call(['apt-get', 'install', '-y', 'python-six']) | ||
168 | 27 | else: | ||
169 | 28 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-six']) | ||
170 | 29 | import six # flake8: noqa | ||
171 | 30 | |||
172 | 31 | try: | ||
173 | 32 | import yaml # flake8: noqa | ||
174 | 33 | except ImportError: | ||
175 | 34 | if sys.version_info.major == 2: | ||
176 | 35 | subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml']) | ||
177 | 36 | else: | ||
178 | 37 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml']) | ||
179 | 38 | import yaml # flake8: noqa | ||
180 | 0 | 39 | ||
181 | === added directory 'hooks/charmhelpers/contrib' | |||
182 | === added file 'hooks/charmhelpers/contrib/__init__.py' | |||
183 | --- hooks/charmhelpers/contrib/__init__.py 1970-01-01 00:00:00 +0000 | |||
184 | +++ hooks/charmhelpers/contrib/__init__.py 2015-06-18 17:19:58 +0000 | |||
185 | @@ -0,0 +1,15 @@ | |||
186 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
187 | 2 | # | ||
188 | 3 | # This file is part of charm-helpers. | ||
189 | 4 | # | ||
190 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
191 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
192 | 7 | # published by the Free Software Foundation. | ||
193 | 8 | # | ||
194 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
195 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
196 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
197 | 12 | # GNU Lesser General Public License for more details. | ||
198 | 13 | # | ||
199 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
200 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
201 | 0 | 16 | ||
202 | === added directory 'hooks/charmhelpers/contrib/amulet' | |||
203 | === added file 'hooks/charmhelpers/contrib/amulet/__init__.py' | |||
204 | --- hooks/charmhelpers/contrib/amulet/__init__.py 1970-01-01 00:00:00 +0000 | |||
205 | +++ hooks/charmhelpers/contrib/amulet/__init__.py 2015-06-18 17:19:58 +0000 | |||
206 | @@ -0,0 +1,15 @@ | |||
207 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
208 | 2 | # | ||
209 | 3 | # This file is part of charm-helpers. | ||
210 | 4 | # | ||
211 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
212 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
213 | 7 | # published by the Free Software Foundation. | ||
214 | 8 | # | ||
215 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
216 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
217 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
218 | 12 | # GNU Lesser General Public License for more details. | ||
219 | 13 | # | ||
220 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
221 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
222 | 0 | 16 | ||
223 | === added file 'hooks/charmhelpers/contrib/amulet/deployment.py' | |||
224 | --- hooks/charmhelpers/contrib/amulet/deployment.py 1970-01-01 00:00:00 +0000 | |||
225 | +++ hooks/charmhelpers/contrib/amulet/deployment.py 2015-06-18 17:19:58 +0000 | |||
226 | @@ -0,0 +1,93 @@ | |||
227 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
228 | 2 | # | ||
229 | 3 | # This file is part of charm-helpers. | ||
230 | 4 | # | ||
231 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
232 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
233 | 7 | # published by the Free Software Foundation. | ||
234 | 8 | # | ||
235 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
236 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
237 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
238 | 12 | # GNU Lesser General Public License for more details. | ||
239 | 13 | # | ||
240 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
241 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
242 | 16 | |||
243 | 17 | import amulet | ||
244 | 18 | import os | ||
245 | 19 | import six | ||
246 | 20 | |||
247 | 21 | |||
248 | 22 | class AmuletDeployment(object): | ||
249 | 23 | """Amulet deployment. | ||
250 | 24 | |||
251 | 25 | This class provides generic Amulet deployment and test runner | ||
252 | 26 | methods. | ||
253 | 27 | """ | ||
254 | 28 | |||
255 | 29 | def __init__(self, series=None): | ||
256 | 30 | """Initialize the deployment environment.""" | ||
257 | 31 | self.series = None | ||
258 | 32 | |||
259 | 33 | if series: | ||
260 | 34 | self.series = series | ||
261 | 35 | self.d = amulet.Deployment(series=self.series) | ||
262 | 36 | else: | ||
263 | 37 | self.d = amulet.Deployment() | ||
264 | 38 | |||
265 | 39 | def _add_services(self, this_service, other_services): | ||
266 | 40 | """Add services. | ||
267 | 41 | |||
268 | 42 | Add services to the deployment where this_service is the local charm | ||
269 | 43 | that we're testing and other_services are the other services that | ||
270 | 44 | are being used in the local amulet tests. | ||
271 | 45 | """ | ||
272 | 46 | if this_service['name'] != os.path.basename(os.getcwd()): | ||
273 | 47 | s = this_service['name'] | ||
274 | 48 | msg = "The charm's root directory name needs to be {}".format(s) | ||
275 | 49 | amulet.raise_status(amulet.FAIL, msg=msg) | ||
276 | 50 | |||
277 | 51 | if 'units' not in this_service: | ||
278 | 52 | this_service['units'] = 1 | ||
279 | 53 | |||
280 | 54 | self.d.add(this_service['name'], units=this_service['units']) | ||
281 | 55 | |||
282 | 56 | for svc in other_services: | ||
283 | 57 | if 'location' in svc: | ||
284 | 58 | branch_location = svc['location'] | ||
285 | 59 | elif self.series: | ||
286 | 60 | branch_location = 'cs:{}/{}'.format(self.series, svc['name']), | ||
287 | 61 | else: | ||
288 | 62 | branch_location = None | ||
289 | 63 | |||
290 | 64 | if 'units' not in svc: | ||
291 | 65 | svc['units'] = 1 | ||
292 | 66 | |||
293 | 67 | self.d.add(svc['name'], charm=branch_location, units=svc['units']) | ||
294 | 68 | |||
295 | 69 | def _add_relations(self, relations): | ||
296 | 70 | """Add all of the relations for the services.""" | ||
297 | 71 | for k, v in six.iteritems(relations): | ||
298 | 72 | self.d.relate(k, v) | ||
299 | 73 | |||
300 | 74 | def _configure_services(self, configs): | ||
301 | 75 | """Configure all of the services.""" | ||
302 | 76 | for service, config in six.iteritems(configs): | ||
303 | 77 | self.d.configure(service, config) | ||
304 | 78 | |||
305 | 79 | def _deploy(self): | ||
306 | 80 | """Deploy environment and wait for all hooks to finish executing.""" | ||
307 | 81 | try: | ||
308 | 82 | self.d.setup(timeout=900) | ||
309 | 83 | self.d.sentry.wait(timeout=900) | ||
310 | 84 | except amulet.helpers.TimeoutError: | ||
311 | 85 | amulet.raise_status(amulet.FAIL, msg="Deployment timed out") | ||
312 | 86 | except Exception: | ||
313 | 87 | raise | ||
314 | 88 | |||
315 | 89 | def run_tests(self): | ||
316 | 90 | """Run all of the methods that are prefixed with 'test_'.""" | ||
317 | 91 | for test in dir(self): | ||
318 | 92 | if test.startswith('test_'): | ||
319 | 93 | getattr(self, test)() | ||
320 | 0 | 94 | ||
321 | === added file 'hooks/charmhelpers/contrib/amulet/utils.py' | |||
322 | --- hooks/charmhelpers/contrib/amulet/utils.py 1970-01-01 00:00:00 +0000 | |||
323 | +++ hooks/charmhelpers/contrib/amulet/utils.py 2015-06-18 17:19:58 +0000 | |||
324 | @@ -0,0 +1,194 @@ | |||
325 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
326 | 2 | # | ||
327 | 3 | # This file is part of charm-helpers. | ||
328 | 4 | # | ||
329 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
330 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
331 | 7 | # published by the Free Software Foundation. | ||
332 | 8 | # | ||
333 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
334 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
335 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
336 | 12 | # GNU Lesser General Public License for more details. | ||
337 | 13 | # | ||
338 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
339 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
340 | 16 | |||
341 | 17 | import ConfigParser | ||
342 | 18 | import io | ||
343 | 19 | import logging | ||
344 | 20 | import re | ||
345 | 21 | import sys | ||
346 | 22 | import time | ||
347 | 23 | |||
348 | 24 | import six | ||
349 | 25 | |||
350 | 26 | |||
351 | 27 | class AmuletUtils(object): | ||
352 | 28 | """Amulet utilities. | ||
353 | 29 | |||
354 | 30 | This class provides common utility functions that are used by Amulet | ||
355 | 31 | tests. | ||
356 | 32 | """ | ||
357 | 33 | |||
358 | 34 | def __init__(self, log_level=logging.ERROR): | ||
359 | 35 | self.log = self.get_logger(level=log_level) | ||
360 | 36 | |||
361 | 37 | def get_logger(self, name="amulet-logger", level=logging.DEBUG): | ||
362 | 38 | """Get a logger object that will log to stdout.""" | ||
363 | 39 | log = logging | ||
364 | 40 | logger = log.getLogger(name) | ||
365 | 41 | fmt = log.Formatter("%(asctime)s %(funcName)s " | ||
366 | 42 | "%(levelname)s: %(message)s") | ||
367 | 43 | |||
368 | 44 | handler = log.StreamHandler(stream=sys.stdout) | ||
369 | 45 | handler.setLevel(level) | ||
370 | 46 | handler.setFormatter(fmt) | ||
371 | 47 | |||
372 | 48 | logger.addHandler(handler) | ||
373 | 49 | logger.setLevel(level) | ||
374 | 50 | |||
375 | 51 | return logger | ||
376 | 52 | |||
377 | 53 | def valid_ip(self, ip): | ||
378 | 54 | if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip): | ||
379 | 55 | return True | ||
380 | 56 | else: | ||
381 | 57 | return False | ||
382 | 58 | |||
383 | 59 | def valid_url(self, url): | ||
384 | 60 | p = re.compile( | ||
385 | 61 | r'^(?:http|ftp)s?://' | ||
386 | 62 | r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # noqa | ||
387 | 63 | r'localhost|' | ||
388 | 64 | r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' | ||
389 | 65 | r'(?::\d+)?' | ||
390 | 66 | r'(?:/?|[/?]\S+)$', | ||
391 | 67 | re.IGNORECASE) | ||
392 | 68 | if p.match(url): | ||
393 | 69 | return True | ||
394 | 70 | else: | ||
395 | 71 | return False | ||
396 | 72 | |||
397 | 73 | def validate_services(self, commands): | ||
398 | 74 | """Validate services. | ||
399 | 75 | |||
400 | 76 | Verify the specified services are running on the corresponding | ||
401 | 77 | service units. | ||
402 | 78 | """ | ||
403 | 79 | for k, v in six.iteritems(commands): | ||
404 | 80 | for cmd in v: | ||
405 | 81 | output, code = k.run(cmd) | ||
406 | 82 | if code != 0: | ||
407 | 83 | return "command `{}` returned {}".format(cmd, str(code)) | ||
408 | 84 | return None | ||
409 | 85 | |||
410 | 86 | def _get_config(self, unit, filename): | ||
411 | 87 | """Get a ConfigParser object for parsing a unit's config file.""" | ||
412 | 88 | file_contents = unit.file_contents(filename) | ||
413 | 89 | config = ConfigParser.ConfigParser() | ||
414 | 90 | config.readfp(io.StringIO(file_contents)) | ||
415 | 91 | return config | ||
416 | 92 | |||
417 | 93 | def validate_config_data(self, sentry_unit, config_file, section, | ||
418 | 94 | expected): | ||
419 | 95 | """Validate config file data. | ||
420 | 96 | |||
421 | 97 | Verify that the specified section of the config file contains | ||
422 | 98 | the expected option key:value pairs. | ||
423 | 99 | """ | ||
424 | 100 | config = self._get_config(sentry_unit, config_file) | ||
425 | 101 | |||
426 | 102 | if section != 'DEFAULT' and not config.has_section(section): | ||
427 | 103 | return "section [{}] does not exist".format(section) | ||
428 | 104 | |||
429 | 105 | for k in expected.keys(): | ||
430 | 106 | if not config.has_option(section, k): | ||
431 | 107 | return "section [{}] is missing option {}".format(section, k) | ||
432 | 108 | if config.get(section, k) != expected[k]: | ||
433 | 109 | return "section [{}] {}:{} != expected {}:{}".format( | ||
434 | 110 | section, k, config.get(section, k), k, expected[k]) | ||
435 | 111 | return None | ||
436 | 112 | |||
437 | 113 | def _validate_dict_data(self, expected, actual): | ||
438 | 114 | """Validate dictionary data. | ||
439 | 115 | |||
440 | 116 | Compare expected dictionary data vs actual dictionary data. | ||
441 | 117 | The values in the 'expected' dictionary can be strings, bools, ints, | ||
442 | 118 | longs, or can be a function that evaluate a variable and returns a | ||
443 | 119 | bool. | ||
444 | 120 | """ | ||
445 | 121 | for k, v in six.iteritems(expected): | ||
446 | 122 | if k in actual: | ||
447 | 123 | if (isinstance(v, six.string_types) or | ||
448 | 124 | isinstance(v, bool) or | ||
449 | 125 | isinstance(v, six.integer_types)): | ||
450 | 126 | if v != actual[k]: | ||
451 | 127 | return "{}:{}".format(k, actual[k]) | ||
452 | 128 | elif not v(actual[k]): | ||
453 | 129 | return "{}:{}".format(k, actual[k]) | ||
454 | 130 | else: | ||
455 | 131 | return "key '{}' does not exist".format(k) | ||
456 | 132 | return None | ||
457 | 133 | |||
458 | 134 | def validate_relation_data(self, sentry_unit, relation, expected): | ||
459 | 135 | """Validate actual relation data based on expected relation data.""" | ||
460 | 136 | actual = sentry_unit.relation(relation[0], relation[1]) | ||
461 | 137 | self.log.debug('actual: {}'.format(repr(actual))) | ||
462 | 138 | return self._validate_dict_data(expected, actual) | ||
463 | 139 | |||
464 | 140 | def _validate_list_data(self, expected, actual): | ||
465 | 141 | """Compare expected list vs actual list data.""" | ||
466 | 142 | for e in expected: | ||
467 | 143 | if e not in actual: | ||
468 | 144 | return "expected item {} not found in actual list".format(e) | ||
469 | 145 | return None | ||
470 | 146 | |||
471 | 147 | def not_null(self, string): | ||
472 | 148 | if string is not None: | ||
473 | 149 | return True | ||
474 | 150 | else: | ||
475 | 151 | return False | ||
476 | 152 | |||
477 | 153 | def _get_file_mtime(self, sentry_unit, filename): | ||
478 | 154 | """Get last modification time of file.""" | ||
479 | 155 | return sentry_unit.file_stat(filename)['mtime'] | ||
480 | 156 | |||
481 | 157 | def _get_dir_mtime(self, sentry_unit, directory): | ||
482 | 158 | """Get last modification time of directory.""" | ||
483 | 159 | return sentry_unit.directory_stat(directory)['mtime'] | ||
484 | 160 | |||
485 | 161 | def _get_proc_start_time(self, sentry_unit, service, pgrep_full=False): | ||
486 | 162 | """Get process' start time. | ||
487 | 163 | |||
488 | 164 | Determine start time of the process based on the last modification | ||
489 | 165 | time of the /proc/pid directory. If pgrep_full is True, the process | ||
490 | 166 | name is matched against the full command line. | ||
491 | 167 | """ | ||
492 | 168 | if pgrep_full: | ||
493 | 169 | cmd = 'pgrep -o -f {}'.format(service) | ||
494 | 170 | else: | ||
495 | 171 | cmd = 'pgrep -o {}'.format(service) | ||
496 | 172 | proc_dir = '/proc/{}'.format(sentry_unit.run(cmd)[0].strip()) | ||
497 | 173 | return self._get_dir_mtime(sentry_unit, proc_dir) | ||
498 | 174 | |||
499 | 175 | def service_restarted(self, sentry_unit, service, filename, | ||
500 | 176 | pgrep_full=False, sleep_time=20): | ||
501 | 177 | """Check if service was restarted. | ||
502 | 178 | |||
503 | 179 | Compare a service's start time vs a file's last modification time | ||
504 | 180 | (such as a config file for that service) to determine if the service | ||
505 | 181 | has been restarted. | ||
506 | 182 | """ | ||
507 | 183 | time.sleep(sleep_time) | ||
508 | 184 | if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >= | ||
509 | 185 | self._get_file_mtime(sentry_unit, filename)): | ||
510 | 186 | return True | ||
511 | 187 | else: | ||
512 | 188 | return False | ||
513 | 189 | |||
514 | 190 | def relation_error(self, name, data): | ||
515 | 191 | return 'unexpected relation data in {} - {}'.format(name, data) | ||
516 | 192 | |||
517 | 193 | def endpoint_error(self, name, data): | ||
518 | 194 | return 'unexpected endpoint data in {} - {}'.format(name, data) | ||
519 | 0 | 195 | ||
520 | === added directory 'hooks/charmhelpers/contrib/ansible' | |||
521 | === added file 'hooks/charmhelpers/contrib/ansible/__init__.py' | |||
522 | --- hooks/charmhelpers/contrib/ansible/__init__.py 1970-01-01 00:00:00 +0000 | |||
523 | +++ hooks/charmhelpers/contrib/ansible/__init__.py 2015-06-18 17:19:58 +0000 | |||
524 | @@ -0,0 +1,190 @@ | |||
525 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
526 | 2 | # | ||
527 | 3 | # This file is part of charm-helpers. | ||
528 | 4 | # | ||
529 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
530 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
531 | 7 | # published by the Free Software Foundation. | ||
532 | 8 | # | ||
533 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
534 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
535 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
536 | 12 | # GNU Lesser General Public License for more details. | ||
537 | 13 | # | ||
538 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
539 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
540 | 16 | |||
541 | 17 | # Copyright 2013 Canonical Ltd. | ||
542 | 18 | # | ||
543 | 19 | # Authors: | ||
544 | 20 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
545 | 21 | """Charm Helpers ansible - declare the state of your machines. | ||
546 | 22 | |||
547 | 23 | This helper enables you to declare your machine state, rather than | ||
548 | 24 | program it procedurally (and have to test each change to your procedures). | ||
549 | 25 | Your install hook can be as simple as:: | ||
550 | 26 | |||
551 | 27 | {{{ | ||
552 | 28 | import charmhelpers.contrib.ansible | ||
553 | 29 | |||
554 | 30 | |||
555 | 31 | def install(): | ||
556 | 32 | charmhelpers.contrib.ansible.install_ansible_support() | ||
557 | 33 | charmhelpers.contrib.ansible.apply_playbook('playbooks/install.yaml') | ||
558 | 34 | }}} | ||
559 | 35 | |||
560 | 36 | and won't need to change (nor will its tests) when you change the machine | ||
561 | 37 | state. | ||
562 | 38 | |||
563 | 39 | All of your juju config and relation-data are available as template | ||
564 | 40 | variables within your playbooks and templates. An install playbook looks | ||
565 | 41 | something like:: | ||
566 | 42 | |||
567 | 43 | {{{ | ||
568 | 44 | --- | ||
569 | 45 | - hosts: localhost | ||
570 | 46 | user: root | ||
571 | 47 | |||
572 | 48 | tasks: | ||
573 | 49 | - name: Add private repositories. | ||
574 | 50 | template: | ||
575 | 51 | src: ../templates/private-repositories.list.jinja2 | ||
576 | 52 | dest: /etc/apt/sources.list.d/private.list | ||
577 | 53 | |||
578 | 54 | - name: Update the cache. | ||
579 | 55 | apt: update_cache=yes | ||
580 | 56 | |||
581 | 57 | - name: Install dependencies. | ||
582 | 58 | apt: pkg={{ item }} | ||
583 | 59 | with_items: | ||
584 | 60 | - python-mimeparse | ||
585 | 61 | - python-webob | ||
586 | 62 | - sunburnt | ||
587 | 63 | |||
588 | 64 | - name: Setup groups. | ||
589 | 65 | group: name={{ item.name }} gid={{ item.gid }} | ||
590 | 66 | with_items: | ||
591 | 67 | - { name: 'deploy_user', gid: 1800 } | ||
592 | 68 | - { name: 'service_user', gid: 1500 } | ||
593 | 69 | |||
594 | 70 | ... | ||
595 | 71 | }}} | ||
596 | 72 | |||
597 | 73 | Read more online about `playbooks`_ and standard ansible `modules`_. | ||
598 | 74 | |||
599 | 75 | .. _playbooks: http://www.ansibleworks.com/docs/playbooks.html | ||
600 | 76 | .. _modules: http://www.ansibleworks.com/docs/modules.html | ||
601 | 77 | |||
602 | 78 | """ | ||
603 | 79 | import os | ||
604 | 80 | import subprocess | ||
605 | 81 | |||
606 | 82 | import charmhelpers.contrib.templating.contexts | ||
607 | 83 | import charmhelpers.core.host | ||
608 | 84 | import charmhelpers.core.hookenv | ||
609 | 85 | import charmhelpers.fetch | ||
610 | 86 | |||
611 | 87 | |||
612 | 88 | charm_dir = os.environ.get('CHARM_DIR', '') | ||
613 | 89 | ansible_hosts_path = '/etc/ansible/hosts' | ||
614 | 90 | # Ansible will automatically include any vars in the following | ||
615 | 91 | # file in its inventory when run locally. | ||
616 | 92 | ansible_vars_path = '/etc/ansible/host_vars/localhost' | ||
617 | 93 | |||
618 | 94 | |||
619 | 95 | def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'): | ||
620 | 96 | """Installs the ansible package. | ||
621 | 97 | |||
622 | 98 | By default it is installed from the `PPA`_ linked from | ||
623 | 99 | the ansible `website`_ or from a ppa specified by a charm config.. | ||
624 | 100 | |||
625 | 101 | .. _PPA: https://launchpad.net/~rquillo/+archive/ansible | ||
626 | 102 | .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu | ||
627 | 103 | |||
628 | 104 | If from_ppa is empty, you must ensure that the package is available | ||
629 | 105 | from a configured repository. | ||
630 | 106 | """ | ||
631 | 107 | if from_ppa: | ||
632 | 108 | charmhelpers.fetch.add_source(ppa_location) | ||
633 | 109 | charmhelpers.fetch.apt_update(fatal=True) | ||
634 | 110 | charmhelpers.fetch.apt_install('ansible') | ||
635 | 111 | with open(ansible_hosts_path, 'w+') as hosts_file: | ||
636 | 112 | hosts_file.write('localhost ansible_connection=local') | ||
637 | 113 | |||
638 | 114 | |||
639 | 115 | def apply_playbook(playbook, tags=None): | ||
640 | 116 | tags = tags or [] | ||
641 | 117 | tags = ",".join(tags) | ||
642 | 118 | charmhelpers.contrib.templating.contexts.juju_state_to_yaml( | ||
643 | 119 | ansible_vars_path, namespace_separator='__', | ||
644 | 120 | allow_hyphens_in_keys=False) | ||
645 | 121 | # we want ansible's log output to be unbuffered | ||
646 | 122 | env = os.environ.copy() | ||
647 | 123 | env['PYTHONUNBUFFERED'] = "1" | ||
648 | 124 | call = [ | ||
649 | 125 | 'ansible-playbook', | ||
650 | 126 | '-c', | ||
651 | 127 | 'local', | ||
652 | 128 | playbook, | ||
653 | 129 | ] | ||
654 | 130 | if tags: | ||
655 | 131 | call.extend(['--tags', '{}'.format(tags)]) | ||
656 | 132 | subprocess.check_call(call, env=env) | ||
657 | 133 | |||
658 | 134 | |||
659 | 135 | class AnsibleHooks(charmhelpers.core.hookenv.Hooks): | ||
660 | 136 | """Run a playbook with the hook-name as the tag. | ||
661 | 137 | |||
662 | 138 | This helper builds on the standard hookenv.Hooks helper, | ||
663 | 139 | but additionally runs the playbook with the hook-name specified | ||
664 | 140 | using --tags (ie. running all the tasks tagged with the hook-name). | ||
665 | 141 | |||
666 | 142 | Example:: | ||
667 | 143 | |||
668 | 144 | hooks = AnsibleHooks(playbook_path='playbooks/my_machine_state.yaml') | ||
669 | 145 | |||
670 | 146 | # All the tasks within my_machine_state.yaml tagged with 'install' | ||
671 | 147 | # will be run automatically after do_custom_work() | ||
672 | 148 | @hooks.hook() | ||
673 | 149 | def install(): | ||
674 | 150 | do_custom_work() | ||
675 | 151 | |||
676 | 152 | # For most of your hooks, you won't need to do anything other | ||
677 | 153 | # than run the tagged tasks for the hook: | ||
678 | 154 | @hooks.hook('config-changed', 'start', 'stop') | ||
679 | 155 | def just_use_playbook(): | ||
680 | 156 | pass | ||
681 | 157 | |||
682 | 158 | # As a convenience, you can avoid the above noop function by specifying | ||
683 | 159 | # the hooks which are handled by ansible-only and they'll be registered | ||
684 | 160 | # for you: | ||
685 | 161 | # hooks = AnsibleHooks( | ||
686 | 162 | # 'playbooks/my_machine_state.yaml', | ||
687 | 163 | # default_hooks=['config-changed', 'start', 'stop']) | ||
688 | 164 | |||
689 | 165 | if __name__ == "__main__": | ||
690 | 166 | # execute a hook based on the name the program is called by | ||
691 | 167 | hooks.execute(sys.argv) | ||
692 | 168 | |||
693 | 169 | """ | ||
694 | 170 | |||
695 | 171 | def __init__(self, playbook_path, default_hooks=None): | ||
696 | 172 | """Register any hooks handled by ansible.""" | ||
697 | 173 | super(AnsibleHooks, self).__init__() | ||
698 | 174 | |||
699 | 175 | self.playbook_path = playbook_path | ||
700 | 176 | |||
701 | 177 | default_hooks = default_hooks or [] | ||
702 | 178 | |||
703 | 179 | def noop(*args, **kwargs): | ||
704 | 180 | pass | ||
705 | 181 | |||
706 | 182 | for hook in default_hooks: | ||
707 | 183 | self.register(hook, noop) | ||
708 | 184 | |||
709 | 185 | def execute(self, args): | ||
710 | 186 | """Execute the hook followed by the playbook using the hook as tag.""" | ||
711 | 187 | super(AnsibleHooks, self).execute(args) | ||
712 | 188 | hook_name = os.path.basename(args[0]) | ||
713 | 189 | charmhelpers.contrib.ansible.apply_playbook( | ||
714 | 190 | self.playbook_path, tags=[hook_name]) | ||
715 | 0 | 191 | ||
716 | === added directory 'hooks/charmhelpers/contrib/charmhelpers' | |||
717 | === added file 'hooks/charmhelpers/contrib/charmhelpers/__init__.py' | |||
718 | --- hooks/charmhelpers/contrib/charmhelpers/__init__.py 1970-01-01 00:00:00 +0000 | |||
719 | +++ hooks/charmhelpers/contrib/charmhelpers/__init__.py 2015-06-18 17:19:58 +0000 | |||
720 | @@ -0,0 +1,208 @@ | |||
721 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
722 | 2 | # | ||
723 | 3 | # This file is part of charm-helpers. | ||
724 | 4 | # | ||
725 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
726 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
727 | 7 | # published by the Free Software Foundation. | ||
728 | 8 | # | ||
729 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
730 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
731 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
732 | 12 | # GNU Lesser General Public License for more details. | ||
733 | 13 | # | ||
734 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
735 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
736 | 16 | |||
737 | 17 | # Copyright 2012 Canonical Ltd. This software is licensed under the | ||
738 | 18 | # GNU Affero General Public License version 3 (see the file LICENSE). | ||
739 | 19 | |||
740 | 20 | import warnings | ||
741 | 21 | warnings.warn("contrib.charmhelpers is deprecated", DeprecationWarning) # noqa | ||
742 | 22 | |||
743 | 23 | import operator | ||
744 | 24 | import tempfile | ||
745 | 25 | import time | ||
746 | 26 | import yaml | ||
747 | 27 | import subprocess | ||
748 | 28 | |||
749 | 29 | import six | ||
750 | 30 | if six.PY3: | ||
751 | 31 | from urllib.request import urlopen | ||
752 | 32 | from urllib.error import (HTTPError, URLError) | ||
753 | 33 | else: | ||
754 | 34 | from urllib2 import (urlopen, HTTPError, URLError) | ||
755 | 35 | |||
756 | 36 | """Helper functions for writing Juju charms in Python.""" | ||
757 | 37 | |||
758 | 38 | __metaclass__ = type | ||
759 | 39 | __all__ = [ | ||
760 | 40 | # 'get_config', # core.hookenv.config() | ||
761 | 41 | # 'log', # core.hookenv.log() | ||
762 | 42 | # 'log_entry', # core.hookenv.log() | ||
763 | 43 | # 'log_exit', # core.hookenv.log() | ||
764 | 44 | # 'relation_get', # core.hookenv.relation_get() | ||
765 | 45 | # 'relation_set', # core.hookenv.relation_set() | ||
766 | 46 | # 'relation_ids', # core.hookenv.relation_ids() | ||
767 | 47 | # 'relation_list', # core.hookenv.relation_units() | ||
768 | 48 | # 'config_get', # core.hookenv.config() | ||
769 | 49 | # 'unit_get', # core.hookenv.unit_get() | ||
770 | 50 | # 'open_port', # core.hookenv.open_port() | ||
771 | 51 | # 'close_port', # core.hookenv.close_port() | ||
772 | 52 | # 'service_control', # core.host.service() | ||
773 | 53 | 'unit_info', # client-side, NOT IMPLEMENTED | ||
774 | 54 | 'wait_for_machine', # client-side, NOT IMPLEMENTED | ||
775 | 55 | 'wait_for_page_contents', # client-side, NOT IMPLEMENTED | ||
776 | 56 | 'wait_for_relation', # client-side, NOT IMPLEMENTED | ||
777 | 57 | 'wait_for_unit', # client-side, NOT IMPLEMENTED | ||
778 | 58 | ] | ||
779 | 59 | |||
780 | 60 | |||
781 | 61 | SLEEP_AMOUNT = 0.1 | ||
782 | 62 | |||
783 | 63 | |||
784 | 64 | # We create a juju_status Command here because it makes testing much, | ||
785 | 65 | # much easier. | ||
786 | 66 | def juju_status(): | ||
787 | 67 | subprocess.check_call(['juju', 'status']) | ||
788 | 68 | |||
789 | 69 | # re-implemented as charmhelpers.fetch.configure_sources() | ||
790 | 70 | # def configure_source(update=False): | ||
791 | 71 | # source = config_get('source') | ||
792 | 72 | # if ((source.startswith('ppa:') or | ||
793 | 73 | # source.startswith('cloud:') or | ||
794 | 74 | # source.startswith('http:'))): | ||
795 | 75 | # run('add-apt-repository', source) | ||
796 | 76 | # if source.startswith("http:"): | ||
797 | 77 | # run('apt-key', 'import', config_get('key')) | ||
798 | 78 | # if update: | ||
799 | 79 | # run('apt-get', 'update') | ||
800 | 80 | |||
801 | 81 | |||
802 | 82 | # DEPRECATED: client-side only | ||
803 | 83 | def make_charm_config_file(charm_config): | ||
804 | 84 | charm_config_file = tempfile.NamedTemporaryFile(mode='w+') | ||
805 | 85 | charm_config_file.write(yaml.dump(charm_config)) | ||
806 | 86 | charm_config_file.flush() | ||
807 | 87 | # The NamedTemporaryFile instance is returned instead of just the name | ||
808 | 88 | # because we want to take advantage of garbage collection-triggered | ||
809 | 89 | # deletion of the temp file when it goes out of scope in the caller. | ||
810 | 90 | return charm_config_file | ||
811 | 91 | |||
812 | 92 | |||
813 | 93 | # DEPRECATED: client-side only | ||
814 | 94 | def unit_info(service_name, item_name, data=None, unit=None): | ||
815 | 95 | if data is None: | ||
816 | 96 | data = yaml.safe_load(juju_status()) | ||
817 | 97 | service = data['services'].get(service_name) | ||
818 | 98 | if service is None: | ||
819 | 99 | # XXX 2012-02-08 gmb: | ||
820 | 100 | # This allows us to cope with the race condition that we | ||
821 | 101 | # have between deploying a service and having it come up in | ||
822 | 102 | # `juju status`. We could probably do with cleaning it up so | ||
823 | 103 | # that it fails a bit more noisily after a while. | ||
824 | 104 | return '' | ||
825 | 105 | units = service['units'] | ||
826 | 106 | if unit is not None: | ||
827 | 107 | item = units[unit][item_name] | ||
828 | 108 | else: | ||
829 | 109 | # It might seem odd to sort the units here, but we do it to | ||
830 | 110 | # ensure that when no unit is specified, the first unit for the | ||
831 | 111 | # service (or at least the one with the lowest number) is the | ||
832 | 112 | # one whose data gets returned. | ||
833 | 113 | sorted_unit_names = sorted(units.keys()) | ||
834 | 114 | item = units[sorted_unit_names[0]][item_name] | ||
835 | 115 | return item | ||
836 | 116 | |||
837 | 117 | |||
838 | 118 | # DEPRECATED: client-side only | ||
839 | 119 | def get_machine_data(): | ||
840 | 120 | return yaml.safe_load(juju_status())['machines'] | ||
841 | 121 | |||
842 | 122 | |||
843 | 123 | # DEPRECATED: client-side only | ||
844 | 124 | def wait_for_machine(num_machines=1, timeout=300): | ||
845 | 125 | """Wait `timeout` seconds for `num_machines` machines to come up. | ||
846 | 126 | |||
847 | 127 | This wait_for... function can be called by other wait_for functions | ||
848 | 128 | whose timeouts might be too short in situations where only a bare | ||
849 | 129 | Juju setup has been bootstrapped. | ||
850 | 130 | |||
851 | 131 | :return: A tuple of (num_machines, time_taken). This is used for | ||
852 | 132 | testing. | ||
853 | 133 | """ | ||
854 | 134 | # You may think this is a hack, and you'd be right. The easiest way | ||
855 | 135 | # to tell what environment we're working in (LXC vs EC2) is to check | ||
856 | 136 | # the dns-name of the first machine. If it's localhost we're in LXC | ||
857 | 137 | # and we can just return here. | ||
858 | 138 | if get_machine_data()[0]['dns-name'] == 'localhost': | ||
859 | 139 | return 1, 0 | ||
860 | 140 | start_time = time.time() | ||
861 | 141 | while True: | ||
862 | 142 | # Drop the first machine, since it's the Zookeeper and that's | ||
863 | 143 | # not a machine that we need to wait for. This will only work | ||
864 | 144 | # for EC2 environments, which is why we return early above if | ||
865 | 145 | # we're in LXC. | ||
866 | 146 | machine_data = get_machine_data() | ||
867 | 147 | non_zookeeper_machines = [ | ||
868 | 148 | machine_data[key] for key in list(machine_data.keys())[1:]] | ||
869 | 149 | if len(non_zookeeper_machines) >= num_machines: | ||
870 | 150 | all_machines_running = True | ||
871 | 151 | for machine in non_zookeeper_machines: | ||
872 | 152 | if machine.get('instance-state') != 'running': | ||
873 | 153 | all_machines_running = False | ||
874 | 154 | break | ||
875 | 155 | if all_machines_running: | ||
876 | 156 | break | ||
877 | 157 | if time.time() - start_time >= timeout: | ||
878 | 158 | raise RuntimeError('timeout waiting for service to start') | ||
879 | 159 | time.sleep(SLEEP_AMOUNT) | ||
880 | 160 | return num_machines, time.time() - start_time | ||
881 | 161 | |||
882 | 162 | |||
883 | 163 | # DEPRECATED: client-side only | ||
884 | 164 | def wait_for_unit(service_name, timeout=480): | ||
885 | 165 | """Wait `timeout` seconds for a given service name to come up.""" | ||
886 | 166 | wait_for_machine(num_machines=1) | ||
887 | 167 | start_time = time.time() | ||
888 | 168 | while True: | ||
889 | 169 | state = unit_info(service_name, 'agent-state') | ||
890 | 170 | if 'error' in state or state == 'started': | ||
891 | 171 | break | ||
892 | 172 | if time.time() - start_time >= timeout: | ||
893 | 173 | raise RuntimeError('timeout waiting for service to start') | ||
894 | 174 | time.sleep(SLEEP_AMOUNT) | ||
895 | 175 | if state != 'started': | ||
896 | 176 | raise RuntimeError('unit did not start, agent-state: ' + state) | ||
897 | 177 | |||
898 | 178 | |||
899 | 179 | # DEPRECATED: client-side only | ||
900 | 180 | def wait_for_relation(service_name, relation_name, timeout=120): | ||
901 | 181 | """Wait `timeout` seconds for a given relation to come up.""" | ||
902 | 182 | start_time = time.time() | ||
903 | 183 | while True: | ||
904 | 184 | relation = unit_info(service_name, 'relations').get(relation_name) | ||
905 | 185 | if relation is not None and relation['state'] == 'up': | ||
906 | 186 | break | ||
907 | 187 | if time.time() - start_time >= timeout: | ||
908 | 188 | raise RuntimeError('timeout waiting for relation to be up') | ||
909 | 189 | time.sleep(SLEEP_AMOUNT) | ||
910 | 190 | |||
911 | 191 | |||
912 | 192 | # DEPRECATED: client-side only | ||
913 | 193 | def wait_for_page_contents(url, contents, timeout=120, validate=None): | ||
914 | 194 | if validate is None: | ||
915 | 195 | validate = operator.contains | ||
916 | 196 | start_time = time.time() | ||
917 | 197 | while True: | ||
918 | 198 | try: | ||
919 | 199 | stream = urlopen(url) | ||
920 | 200 | except (HTTPError, URLError): | ||
921 | 201 | pass | ||
922 | 202 | else: | ||
923 | 203 | page = stream.read() | ||
924 | 204 | if validate(page, contents): | ||
925 | 205 | return page | ||
926 | 206 | if time.time() - start_time >= timeout: | ||
927 | 207 | raise RuntimeError('timeout waiting for contents of ' + url) | ||
928 | 208 | time.sleep(SLEEP_AMOUNT) | ||
929 | 0 | 209 | ||
930 | === added directory 'hooks/charmhelpers/contrib/charmsupport' | |||
931 | === added file 'hooks/charmhelpers/contrib/charmsupport/__init__.py' | |||
932 | --- hooks/charmhelpers/contrib/charmsupport/__init__.py 1970-01-01 00:00:00 +0000 | |||
933 | +++ hooks/charmhelpers/contrib/charmsupport/__init__.py 2015-06-18 17:19:58 +0000 | |||
934 | @@ -0,0 +1,15 @@ | |||
935 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
936 | 2 | # | ||
937 | 3 | # This file is part of charm-helpers. | ||
938 | 4 | # | ||
939 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
940 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
941 | 7 | # published by the Free Software Foundation. | ||
942 | 8 | # | ||
943 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
944 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
945 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
946 | 12 | # GNU Lesser General Public License for more details. | ||
947 | 13 | # | ||
948 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
949 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
950 | 0 | 16 | ||
951 | === added file 'hooks/charmhelpers/contrib/charmsupport/nrpe.py' | |||
952 | --- hooks/charmhelpers/contrib/charmsupport/nrpe.py 1970-01-01 00:00:00 +0000 | |||
953 | +++ hooks/charmhelpers/contrib/charmsupport/nrpe.py 2015-06-18 17:19:58 +0000 | |||
954 | @@ -0,0 +1,324 @@ | |||
955 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
956 | 2 | # | ||
957 | 3 | # This file is part of charm-helpers. | ||
958 | 4 | # | ||
959 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
960 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
961 | 7 | # published by the Free Software Foundation. | ||
962 | 8 | # | ||
963 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
964 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
965 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
966 | 12 | # GNU Lesser General Public License for more details. | ||
967 | 13 | # | ||
968 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
969 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
970 | 16 | |||
971 | 17 | """Compatibility with the nrpe-external-master charm""" | ||
972 | 18 | # Copyright 2012 Canonical Ltd. | ||
973 | 19 | # | ||
974 | 20 | # Authors: | ||
975 | 21 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | ||
976 | 22 | |||
977 | 23 | import subprocess | ||
978 | 24 | import pwd | ||
979 | 25 | import grp | ||
980 | 26 | import os | ||
981 | 27 | import re | ||
982 | 28 | import shlex | ||
983 | 29 | import yaml | ||
984 | 30 | |||
985 | 31 | from charmhelpers.core.hookenv import ( | ||
986 | 32 | config, | ||
987 | 33 | local_unit, | ||
988 | 34 | log, | ||
989 | 35 | relation_ids, | ||
990 | 36 | relation_set, | ||
991 | 37 | relations_of_type, | ||
992 | 38 | ) | ||
993 | 39 | |||
994 | 40 | from charmhelpers.core.host import service | ||
995 | 41 | |||
996 | 42 | # This module adds compatibility with the nrpe-external-master and plain nrpe | ||
997 | 43 | # subordinate charms. To use it in your charm: | ||
998 | 44 | # | ||
999 | 45 | # 1. Update metadata.yaml | ||
1000 | 46 | # | ||
1001 | 47 | # provides: | ||
1002 | 48 | # (...) | ||
1003 | 49 | # nrpe-external-master: | ||
1004 | 50 | # interface: nrpe-external-master | ||
1005 | 51 | # scope: container | ||
1006 | 52 | # | ||
1007 | 53 | # and/or | ||
1008 | 54 | # | ||
1009 | 55 | # provides: | ||
1010 | 56 | # (...) | ||
1011 | 57 | # local-monitors: | ||
1012 | 58 | # interface: local-monitors | ||
1013 | 59 | # scope: container | ||
1014 | 60 | |||
1015 | 61 | # | ||
1016 | 62 | # 2. Add the following to config.yaml | ||
1017 | 63 | # | ||
1018 | 64 | # nagios_context: | ||
1019 | 65 | # default: "juju" | ||
1020 | 66 | # type: string | ||
1021 | 67 | # description: | | ||
1022 | 68 | # Used by the nrpe subordinate charms. | ||
1023 | 69 | # A string that will be prepended to instance name to set the host name | ||
1024 | 70 | # in nagios. So for instance the hostname would be something like: | ||
1025 | 71 | # juju-myservice-0 | ||
1026 | 72 | # If you're running multiple environments with the same services in them | ||
1027 | 73 | # this allows you to differentiate between them. | ||
1028 | 74 | # nagios_servicegroups: | ||
1029 | 75 | # default: "" | ||
1030 | 76 | # type: string | ||
1031 | 77 | # description: | | ||
1032 | 78 | # A comma-separated list of nagios servicegroups. | ||
1033 | 79 | # If left empty, the nagios_context will be used as the servicegroup | ||
1034 | 80 | # | ||
1035 | 81 | # 3. Add custom checks (Nagios plugins) to files/nrpe-external-master | ||
1036 | 82 | # | ||
1037 | 83 | # 4. Update your hooks.py with something like this: | ||
1038 | 84 | # | ||
1039 | 85 | # from charmsupport.nrpe import NRPE | ||
1040 | 86 | # (...) | ||
1041 | 87 | # def update_nrpe_config(): | ||
1042 | 88 | # nrpe_compat = NRPE() | ||
1043 | 89 | # nrpe_compat.add_check( | ||
1044 | 90 | # shortname = "myservice", | ||
1045 | 91 | # description = "Check MyService", | ||
1046 | 92 | # check_cmd = "check_http -w 2 -c 10 http://localhost" | ||
1047 | 93 | # ) | ||
1048 | 94 | # nrpe_compat.add_check( | ||
1049 | 95 | # "myservice_other", | ||
1050 | 96 | # "Check for widget failures", | ||
1051 | 97 | # check_cmd = "/srv/myapp/scripts/widget_check" | ||
1052 | 98 | # ) | ||
1053 | 99 | # nrpe_compat.write() | ||
1054 | 100 | # | ||
1055 | 101 | # def config_changed(): | ||
1056 | 102 | # (...) | ||
1057 | 103 | # update_nrpe_config() | ||
1058 | 104 | # | ||
1059 | 105 | # def nrpe_external_master_relation_changed(): | ||
1060 | 106 | # update_nrpe_config() | ||
1061 | 107 | # | ||
1062 | 108 | # def local_monitors_relation_changed(): | ||
1063 | 109 | # update_nrpe_config() | ||
1064 | 110 | # | ||
1065 | 111 | # 5. ln -s hooks.py nrpe-external-master-relation-changed | ||
1066 | 112 | # ln -s hooks.py local-monitors-relation-changed | ||
1067 | 113 | |||
1068 | 114 | |||
1069 | 115 | class CheckException(Exception): | ||
1070 | 116 | pass | ||
1071 | 117 | |||
1072 | 118 | |||
1073 | 119 | class Check(object): | ||
1074 | 120 | shortname_re = '[A-Za-z0-9-_]+$' | ||
1075 | 121 | service_template = (""" | ||
1076 | 122 | #--------------------------------------------------- | ||
1077 | 123 | # This file is Juju managed | ||
1078 | 124 | #--------------------------------------------------- | ||
1079 | 125 | define service {{ | ||
1080 | 126 | use active-service | ||
1081 | 127 | host_name {nagios_hostname} | ||
1082 | 128 | service_description {nagios_hostname}[{shortname}] """ | ||
1083 | 129 | """{description} | ||
1084 | 130 | check_command check_nrpe!{command} | ||
1085 | 131 | servicegroups {nagios_servicegroup} | ||
1086 | 132 | }} | ||
1087 | 133 | """) | ||
1088 | 134 | |||
1089 | 135 | def __init__(self, shortname, description, check_cmd): | ||
1090 | 136 | super(Check, self).__init__() | ||
1091 | 137 | # XXX: could be better to calculate this from the service name | ||
1092 | 138 | if not re.match(self.shortname_re, shortname): | ||
1093 | 139 | raise CheckException("shortname must match {}".format( | ||
1094 | 140 | Check.shortname_re)) | ||
1095 | 141 | self.shortname = shortname | ||
1096 | 142 | self.command = "check_{}".format(shortname) | ||
1097 | 143 | # Note: a set of invalid characters is defined by the | ||
1098 | 144 | # Nagios server config | ||
1099 | 145 | # The default is: illegal_object_name_chars=`~!$%^&*"|'<>?,()= | ||
1100 | 146 | self.description = description | ||
1101 | 147 | self.check_cmd = self._locate_cmd(check_cmd) | ||
1102 | 148 | |||
1103 | 149 | def _locate_cmd(self, check_cmd): | ||
1104 | 150 | search_path = ( | ||
1105 | 151 | '/usr/lib/nagios/plugins', | ||
1106 | 152 | '/usr/local/lib/nagios/plugins', | ||
1107 | 153 | ) | ||
1108 | 154 | parts = shlex.split(check_cmd) | ||
1109 | 155 | for path in search_path: | ||
1110 | 156 | if os.path.exists(os.path.join(path, parts[0])): | ||
1111 | 157 | command = os.path.join(path, parts[0]) | ||
1112 | 158 | if len(parts) > 1: | ||
1113 | 159 | command += " " + " ".join(parts[1:]) | ||
1114 | 160 | return command | ||
1115 | 161 | log('Check command not found: {}'.format(parts[0])) | ||
1116 | 162 | return '' | ||
1117 | 163 | |||
1118 | 164 | def write(self, nagios_context, hostname, nagios_servicegroups=None): | ||
1119 | 165 | nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format( | ||
1120 | 166 | self.command) | ||
1121 | 167 | with open(nrpe_check_file, 'w') as nrpe_check_config: | ||
1122 | 168 | nrpe_check_config.write("# check {}\n".format(self.shortname)) | ||
1123 | 169 | nrpe_check_config.write("command[{}]={}\n".format( | ||
1124 | 170 | self.command, self.check_cmd)) | ||
1125 | 171 | |||
1126 | 172 | if not os.path.exists(NRPE.nagios_exportdir): | ||
1127 | 173 | log('Not writing service config as {} is not accessible'.format( | ||
1128 | 174 | NRPE.nagios_exportdir)) | ||
1129 | 175 | else: | ||
1130 | 176 | self.write_service_config(nagios_context, hostname, | ||
1131 | 177 | nagios_servicegroups) | ||
1132 | 178 | |||
1133 | 179 | def write_service_config(self, nagios_context, hostname, | ||
1134 | 180 | nagios_servicegroups=None): | ||
1135 | 181 | for f in os.listdir(NRPE.nagios_exportdir): | ||
1136 | 182 | if re.search('.*{}.cfg'.format(self.command), f): | ||
1137 | 183 | os.remove(os.path.join(NRPE.nagios_exportdir, f)) | ||
1138 | 184 | |||
1139 | 185 | if not nagios_servicegroups: | ||
1140 | 186 | nagios_servicegroups = nagios_context | ||
1141 | 187 | |||
1142 | 188 | templ_vars = { | ||
1143 | 189 | 'nagios_hostname': hostname, | ||
1144 | 190 | 'nagios_servicegroup': nagios_servicegroups, | ||
1145 | 191 | 'description': self.description, | ||
1146 | 192 | 'shortname': self.shortname, | ||
1147 | 193 | 'command': self.command, | ||
1148 | 194 | } | ||
1149 | 195 | nrpe_service_text = Check.service_template.format(**templ_vars) | ||
1150 | 196 | nrpe_service_file = '{}/service__{}_{}.cfg'.format( | ||
1151 | 197 | NRPE.nagios_exportdir, hostname, self.command) | ||
1152 | 198 | with open(nrpe_service_file, 'w') as nrpe_service_config: | ||
1153 | 199 | nrpe_service_config.write(str(nrpe_service_text)) | ||
1154 | 200 | |||
1155 | 201 | def run(self): | ||
1156 | 202 | subprocess.call(self.check_cmd) | ||
1157 | 203 | |||
1158 | 204 | |||
1159 | 205 | class NRPE(object): | ||
1160 | 206 | nagios_logdir = '/var/log/nagios' | ||
1161 | 207 | nagios_exportdir = '/var/lib/nagios/export' | ||
1162 | 208 | nrpe_confdir = '/etc/nagios/nrpe.d' | ||
1163 | 209 | |||
1164 | 210 | def __init__(self, hostname=None): | ||
1165 | 211 | super(NRPE, self).__init__() | ||
1166 | 212 | self.config = config() | ||
1167 | 213 | self.nagios_context = self.config['nagios_context'] | ||
1168 | 214 | if 'nagios_servicegroups' in self.config: | ||
1169 | 215 | self.nagios_servicegroups = self.config['nagios_servicegroups'] | ||
1170 | 216 | else: | ||
1171 | 217 | self.nagios_servicegroups = 'juju' | ||
1172 | 218 | self.unit_name = local_unit().replace('/', '-') | ||
1173 | 219 | if hostname: | ||
1174 | 220 | self.hostname = hostname | ||
1175 | 221 | else: | ||
1176 | 222 | self.hostname = "{}-{}".format(self.nagios_context, self.unit_name) | ||
1177 | 223 | self.checks = [] | ||
1178 | 224 | |||
1179 | 225 | def add_check(self, *args, **kwargs): | ||
1180 | 226 | self.checks.append(Check(*args, **kwargs)) | ||
1181 | 227 | |||
1182 | 228 | def write(self): | ||
1183 | 229 | try: | ||
1184 | 230 | nagios_uid = pwd.getpwnam('nagios').pw_uid | ||
1185 | 231 | nagios_gid = grp.getgrnam('nagios').gr_gid | ||
1186 | 232 | except: | ||
1187 | 233 | log("Nagios user not set up, nrpe checks not updated") | ||
1188 | 234 | return | ||
1189 | 235 | |||
1190 | 236 | if not os.path.exists(NRPE.nagios_logdir): | ||
1191 | 237 | os.mkdir(NRPE.nagios_logdir) | ||
1192 | 238 | os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid) | ||
1193 | 239 | |||
1194 | 240 | nrpe_monitors = {} | ||
1195 | 241 | monitors = {"monitors": {"remote": {"nrpe": nrpe_monitors}}} | ||
1196 | 242 | for nrpecheck in self.checks: | ||
1197 | 243 | nrpecheck.write(self.nagios_context, self.hostname, | ||
1198 | 244 | self.nagios_servicegroups) | ||
1199 | 245 | nrpe_monitors[nrpecheck.shortname] = { | ||
1200 | 246 | "command": nrpecheck.command, | ||
1201 | 247 | } | ||
1202 | 248 | |||
1203 | 249 | service('restart', 'nagios-nrpe-server') | ||
1204 | 250 | |||
1205 | 251 | for rid in relation_ids("local-monitors"): | ||
1206 | 252 | relation_set(relation_id=rid, monitors=yaml.dump(monitors)) | ||
1207 | 253 | |||
1208 | 254 | |||
1209 | 255 | def get_nagios_hostcontext(relation_name='nrpe-external-master'): | ||
1210 | 256 | """ | ||
1211 | 257 | Query relation with nrpe subordinate, return the nagios_host_context | ||
1212 | 258 | |||
1213 | 259 | :param str relation_name: Name of relation nrpe sub joined to | ||
1214 | 260 | """ | ||
1215 | 261 | for rel in relations_of_type(relation_name): | ||
1216 | 262 | if 'nagios_hostname' in rel: | ||
1217 | 263 | return rel['nagios_host_context'] | ||
1218 | 264 | |||
1219 | 265 | |||
1220 | 266 | def get_nagios_hostname(relation_name='nrpe-external-master'): | ||
1221 | 267 | """ | ||
1222 | 268 | Query relation with nrpe subordinate, return the nagios_hostname | ||
1223 | 269 | |||
1224 | 270 | :param str relation_name: Name of relation nrpe sub joined to | ||
1225 | 271 | """ | ||
1226 | 272 | for rel in relations_of_type(relation_name): | ||
1227 | 273 | if 'nagios_hostname' in rel: | ||
1228 | 274 | return rel['nagios_hostname'] | ||
1229 | 275 | |||
1230 | 276 | |||
1231 | 277 | def get_nagios_unit_name(relation_name='nrpe-external-master'): | ||
1232 | 278 | """ | ||
1233 | 279 | Return the nagios unit name prepended with host_context if needed | ||
1234 | 280 | |||
1235 | 281 | :param str relation_name: Name of relation nrpe sub joined to | ||
1236 | 282 | """ | ||
1237 | 283 | host_context = get_nagios_hostcontext(relation_name) | ||
1238 | 284 | if host_context: | ||
1239 | 285 | unit = "%s:%s" % (host_context, local_unit()) | ||
1240 | 286 | else: | ||
1241 | 287 | unit = local_unit() | ||
1242 | 288 | return unit | ||
1243 | 289 | |||
1244 | 290 | |||
1245 | 291 | def add_init_service_checks(nrpe, services, unit_name): | ||
1246 | 292 | """ | ||
1247 | 293 | Add checks for each service in list | ||
1248 | 294 | |||
1249 | 295 | :param NRPE nrpe: NRPE object to add check to | ||
1250 | 296 | :param list services: List of services to check | ||
1251 | 297 | :param str unit_name: Unit name to use in check description | ||
1252 | 298 | """ | ||
1253 | 299 | for svc in services: | ||
1254 | 300 | upstart_init = '/etc/init/%s.conf' % svc | ||
1255 | 301 | sysv_init = '/etc/init.d/%s' % svc | ||
1256 | 302 | if os.path.exists(upstart_init): | ||
1257 | 303 | nrpe.add_check( | ||
1258 | 304 | shortname=svc, | ||
1259 | 305 | description='process check {%s}' % unit_name, | ||
1260 | 306 | check_cmd='check_upstart_job %s' % svc | ||
1261 | 307 | ) | ||
1262 | 308 | elif os.path.exists(sysv_init): | ||
1263 | 309 | cronpath = '/etc/cron.d/nagios-service-check-%s' % svc | ||
1264 | 310 | cron_file = ('*/5 * * * * root ' | ||
1265 | 311 | '/usr/local/lib/nagios/plugins/check_exit_status.pl ' | ||
1266 | 312 | '-s /etc/init.d/%s status > ' | ||
1267 | 313 | '/var/lib/nagios/service-check-%s.txt\n' % (svc, | ||
1268 | 314 | svc) | ||
1269 | 315 | ) | ||
1270 | 316 | f = open(cronpath, 'w') | ||
1271 | 317 | f.write(cron_file) | ||
1272 | 318 | f.close() | ||
1273 | 319 | nrpe.add_check( | ||
1274 | 320 | shortname=svc, | ||
1275 | 321 | description='process check {%s}' % unit_name, | ||
1276 | 322 | check_cmd='check_status_file.py -f ' | ||
1277 | 323 | '/var/lib/nagios/service-check-%s.txt' % svc, | ||
1278 | 324 | ) | ||
1279 | 0 | 325 | ||
1280 | === added file 'hooks/charmhelpers/contrib/charmsupport/volumes.py' | |||
1281 | --- hooks/charmhelpers/contrib/charmsupport/volumes.py 1970-01-01 00:00:00 +0000 | |||
1282 | +++ hooks/charmhelpers/contrib/charmsupport/volumes.py 2015-06-18 17:19:58 +0000 | |||
1283 | @@ -0,0 +1,175 @@ | |||
1284 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1285 | 2 | # | ||
1286 | 3 | # This file is part of charm-helpers. | ||
1287 | 4 | # | ||
1288 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1289 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1290 | 7 | # published by the Free Software Foundation. | ||
1291 | 8 | # | ||
1292 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1293 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1294 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1295 | 12 | # GNU Lesser General Public License for more details. | ||
1296 | 13 | # | ||
1297 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1298 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1299 | 16 | |||
1300 | 17 | ''' | ||
1301 | 18 | Functions for managing volumes in juju units. One volume is supported per unit. | ||
1302 | 19 | Subordinates may have their own storage, provided it is on its own partition. | ||
1303 | 20 | |||
1304 | 21 | Configuration stanzas:: | ||
1305 | 22 | |||
1306 | 23 | volume-ephemeral: | ||
1307 | 24 | type: boolean | ||
1308 | 25 | default: true | ||
1309 | 26 | description: > | ||
1310 | 27 | If false, a volume is mounted as sepecified in "volume-map" | ||
1311 | 28 | If true, ephemeral storage will be used, meaning that log data | ||
1312 | 29 | will only exist as long as the machine. YOU HAVE BEEN WARNED. | ||
1313 | 30 | volume-map: | ||
1314 | 31 | type: string | ||
1315 | 32 | default: {} | ||
1316 | 33 | description: > | ||
1317 | 34 | YAML map of units to device names, e.g: | ||
1318 | 35 | "{ rsyslog/0: /dev/vdb, rsyslog/1: /dev/vdb }" | ||
1319 | 36 | Service units will raise a configure-error if volume-ephemeral | ||
1320 | 37 | is 'true' and no volume-map value is set. Use 'juju set' to set a | ||
1321 | 38 | value and 'juju resolved' to complete configuration. | ||
1322 | 39 | |||
1323 | 40 | Usage:: | ||
1324 | 41 | |||
1325 | 42 | from charmsupport.volumes import configure_volume, VolumeConfigurationError | ||
1326 | 43 | from charmsupport.hookenv import log, ERROR | ||
1327 | 44 | def post_mount_hook(): | ||
1328 | 45 | stop_service('myservice') | ||
1329 | 46 | def post_mount_hook(): | ||
1330 | 47 | start_service('myservice') | ||
1331 | 48 | |||
1332 | 49 | if __name__ == '__main__': | ||
1333 | 50 | try: | ||
1334 | 51 | configure_volume(before_change=pre_mount_hook, | ||
1335 | 52 | after_change=post_mount_hook) | ||
1336 | 53 | except VolumeConfigurationError: | ||
1337 | 54 | log('Storage could not be configured', ERROR) | ||
1338 | 55 | |||
1339 | 56 | ''' | ||
1340 | 57 | |||
1341 | 58 | # XXX: Known limitations | ||
1342 | 59 | # - fstab is neither consulted nor updated | ||
1343 | 60 | |||
1344 | 61 | import os | ||
1345 | 62 | from charmhelpers.core import hookenv | ||
1346 | 63 | from charmhelpers.core import host | ||
1347 | 64 | import yaml | ||
1348 | 65 | |||
1349 | 66 | |||
1350 | 67 | MOUNT_BASE = '/srv/juju/volumes' | ||
1351 | 68 | |||
1352 | 69 | |||
1353 | 70 | class VolumeConfigurationError(Exception): | ||
1354 | 71 | '''Volume configuration data is missing or invalid''' | ||
1355 | 72 | pass | ||
1356 | 73 | |||
1357 | 74 | |||
1358 | 75 | def get_config(): | ||
1359 | 76 | '''Gather and sanity-check volume configuration data''' | ||
1360 | 77 | volume_config = {} | ||
1361 | 78 | config = hookenv.config() | ||
1362 | 79 | |||
1363 | 80 | errors = False | ||
1364 | 81 | |||
1365 | 82 | if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'): | ||
1366 | 83 | volume_config['ephemeral'] = True | ||
1367 | 84 | else: | ||
1368 | 85 | volume_config['ephemeral'] = False | ||
1369 | 86 | |||
1370 | 87 | try: | ||
1371 | 88 | volume_map = yaml.safe_load(config.get('volume-map', '{}')) | ||
1372 | 89 | except yaml.YAMLError as e: | ||
1373 | 90 | hookenv.log("Error parsing YAML volume-map: {}".format(e), | ||
1374 | 91 | hookenv.ERROR) | ||
1375 | 92 | errors = True | ||
1376 | 93 | if volume_map is None: | ||
1377 | 94 | # probably an empty string | ||
1378 | 95 | volume_map = {} | ||
1379 | 96 | elif not isinstance(volume_map, dict): | ||
1380 | 97 | hookenv.log("Volume-map should be a dictionary, not {}".format( | ||
1381 | 98 | type(volume_map))) | ||
1382 | 99 | errors = True | ||
1383 | 100 | |||
1384 | 101 | volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME']) | ||
1385 | 102 | if volume_config['device'] and volume_config['ephemeral']: | ||
1386 | 103 | # asked for ephemeral storage but also defined a volume ID | ||
1387 | 104 | hookenv.log('A volume is defined for this unit, but ephemeral ' | ||
1388 | 105 | 'storage was requested', hookenv.ERROR) | ||
1389 | 106 | errors = True | ||
1390 | 107 | elif not volume_config['device'] and not volume_config['ephemeral']: | ||
1391 | 108 | # asked for permanent storage but did not define volume ID | ||
1392 | 109 | hookenv.log('Ephemeral storage was requested, but there is no volume ' | ||
1393 | 110 | 'defined for this unit.', hookenv.ERROR) | ||
1394 | 111 | errors = True | ||
1395 | 112 | |||
1396 | 113 | unit_mount_name = hookenv.local_unit().replace('/', '-') | ||
1397 | 114 | volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name) | ||
1398 | 115 | |||
1399 | 116 | if errors: | ||
1400 | 117 | return None | ||
1401 | 118 | return volume_config | ||
1402 | 119 | |||
1403 | 120 | |||
1404 | 121 | def mount_volume(config): | ||
1405 | 122 | if os.path.exists(config['mountpoint']): | ||
1406 | 123 | if not os.path.isdir(config['mountpoint']): | ||
1407 | 124 | hookenv.log('Not a directory: {}'.format(config['mountpoint'])) | ||
1408 | 125 | raise VolumeConfigurationError() | ||
1409 | 126 | else: | ||
1410 | 127 | host.mkdir(config['mountpoint']) | ||
1411 | 128 | if os.path.ismount(config['mountpoint']): | ||
1412 | 129 | unmount_volume(config) | ||
1413 | 130 | if not host.mount(config['device'], config['mountpoint'], persist=True): | ||
1414 | 131 | raise VolumeConfigurationError() | ||
1415 | 132 | |||
1416 | 133 | |||
1417 | 134 | def unmount_volume(config): | ||
1418 | 135 | if os.path.ismount(config['mountpoint']): | ||
1419 | 136 | if not host.umount(config['mountpoint'], persist=True): | ||
1420 | 137 | raise VolumeConfigurationError() | ||
1421 | 138 | |||
1422 | 139 | |||
1423 | 140 | def managed_mounts(): | ||
1424 | 141 | '''List of all mounted managed volumes''' | ||
1425 | 142 | return filter(lambda mount: mount[0].startswith(MOUNT_BASE), host.mounts()) | ||
1426 | 143 | |||
1427 | 144 | |||
1428 | 145 | def configure_volume(before_change=lambda: None, after_change=lambda: None): | ||
1429 | 146 | '''Set up storage (or don't) according to the charm's volume configuration. | ||
1430 | 147 | Returns the mount point or "ephemeral". before_change and after_change | ||
1431 | 148 | are optional functions to be called if the volume configuration changes. | ||
1432 | 149 | ''' | ||
1433 | 150 | |||
1434 | 151 | config = get_config() | ||
1435 | 152 | if not config: | ||
1436 | 153 | hookenv.log('Failed to read volume configuration', hookenv.CRITICAL) | ||
1437 | 154 | raise VolumeConfigurationError() | ||
1438 | 155 | |||
1439 | 156 | if config['ephemeral']: | ||
1440 | 157 | if os.path.ismount(config['mountpoint']): | ||
1441 | 158 | before_change() | ||
1442 | 159 | unmount_volume(config) | ||
1443 | 160 | after_change() | ||
1444 | 161 | return 'ephemeral' | ||
1445 | 162 | else: | ||
1446 | 163 | # persistent storage | ||
1447 | 164 | if os.path.ismount(config['mountpoint']): | ||
1448 | 165 | mounts = dict(managed_mounts()) | ||
1449 | 166 | if mounts.get(config['mountpoint']) != config['device']: | ||
1450 | 167 | before_change() | ||
1451 | 168 | unmount_volume(config) | ||
1452 | 169 | mount_volume(config) | ||
1453 | 170 | after_change() | ||
1454 | 171 | else: | ||
1455 | 172 | before_change() | ||
1456 | 173 | mount_volume(config) | ||
1457 | 174 | after_change() | ||
1458 | 175 | return config['mountpoint'] | ||
1459 | 0 | 176 | ||
1460 | === added directory 'hooks/charmhelpers/contrib/database' | |||
1461 | === added file 'hooks/charmhelpers/contrib/database/__init__.py' | |||
1462 | === added file 'hooks/charmhelpers/contrib/database/mysql.py' | |||
1463 | --- hooks/charmhelpers/contrib/database/mysql.py 1970-01-01 00:00:00 +0000 | |||
1464 | +++ hooks/charmhelpers/contrib/database/mysql.py 2015-06-18 17:19:58 +0000 | |||
1465 | @@ -0,0 +1,372 @@ | |||
1466 | 1 | """Helper for working with a MySQL database""" | ||
1467 | 2 | import json | ||
1468 | 3 | import socket | ||
1469 | 4 | import re | ||
1470 | 5 | import sys | ||
1471 | 6 | import platform | ||
1472 | 7 | import os | ||
1473 | 8 | import glob | ||
1474 | 9 | |||
1475 | 10 | from string import upper | ||
1476 | 11 | |||
1477 | 12 | from charmhelpers.core.host import ( | ||
1478 | 13 | mkdir, | ||
1479 | 14 | pwgen, | ||
1480 | 15 | write_file | ||
1481 | 16 | ) | ||
1482 | 17 | from charmhelpers.core.hookenv import ( | ||
1483 | 18 | relation_get, | ||
1484 | 19 | related_units, | ||
1485 | 20 | unit_get, | ||
1486 | 21 | log, | ||
1487 | 22 | DEBUG, | ||
1488 | 23 | INFO, | ||
1489 | 24 | ) | ||
1490 | 25 | from charmhelpers.core.hookenv import config as config_get | ||
1491 | 26 | from charmhelpers.fetch import ( | ||
1492 | 27 | apt_install, | ||
1493 | 28 | apt_update, | ||
1494 | 29 | filter_installed_packages, | ||
1495 | 30 | ) | ||
1496 | 31 | from charmhelpers.contrib.peerstorage import ( | ||
1497 | 32 | peer_store, | ||
1498 | 33 | peer_retrieve, | ||
1499 | 34 | ) | ||
1500 | 35 | |||
1501 | 36 | try: | ||
1502 | 37 | import MySQLdb | ||
1503 | 38 | except ImportError: | ||
1504 | 39 | apt_update(fatal=True) | ||
1505 | 40 | apt_install(filter_installed_packages(['python-mysqldb']), fatal=True) | ||
1506 | 41 | import MySQLdb | ||
1507 | 42 | |||
1508 | 43 | |||
1509 | 44 | class MySQLHelper(object): | ||
1510 | 45 | |||
1511 | 46 | def __init__(self, rpasswdf_template, upasswdf_template, host='localhost'): | ||
1512 | 47 | self.host = host | ||
1513 | 48 | # Password file path templates | ||
1514 | 49 | self.root_passwd_file_template = rpasswdf_template | ||
1515 | 50 | self.user_passwd_file_template = upasswdf_template | ||
1516 | 51 | |||
1517 | 52 | def connect(self, user='root', password=None): | ||
1518 | 53 | self.connection = MySQLdb.connect(user=user, host=self.host, | ||
1519 | 54 | passwd=password) | ||
1520 | 55 | |||
1521 | 56 | def database_exists(self, db_name): | ||
1522 | 57 | cursor = self.connection.cursor() | ||
1523 | 58 | try: | ||
1524 | 59 | cursor.execute("SHOW DATABASES") | ||
1525 | 60 | databases = [i[0] for i in cursor.fetchall()] | ||
1526 | 61 | finally: | ||
1527 | 62 | cursor.close() | ||
1528 | 63 | |||
1529 | 64 | return db_name in databases | ||
1530 | 65 | |||
1531 | 66 | def create_database(self, db_name): | ||
1532 | 67 | cursor = self.connection.cursor() | ||
1533 | 68 | try: | ||
1534 | 69 | cursor.execute("CREATE DATABASE {} CHARACTER SET UTF8" | ||
1535 | 70 | .format(db_name)) | ||
1536 | 71 | finally: | ||
1537 | 72 | cursor.close() | ||
1538 | 73 | |||
1539 | 74 | def grant_exists(self, db_name, db_user, remote_ip): | ||
1540 | 75 | cursor = self.connection.cursor() | ||
1541 | 76 | priv_string = "GRANT ALL PRIVILEGES ON `{}`.* " \ | ||
1542 | 77 | "TO '{}'@'{}'".format(db_name, db_user, remote_ip) | ||
1543 | 78 | try: | ||
1544 | 79 | cursor.execute("SHOW GRANTS for '{}'@'{}'".format(db_user, | ||
1545 | 80 | remote_ip)) | ||
1546 | 81 | grants = [i[0] for i in cursor.fetchall()] | ||
1547 | 82 | except MySQLdb.OperationalError: | ||
1548 | 83 | return False | ||
1549 | 84 | finally: | ||
1550 | 85 | cursor.close() | ||
1551 | 86 | |||
1552 | 87 | # TODO: review for different grants | ||
1553 | 88 | return priv_string in grants | ||
1554 | 89 | |||
1555 | 90 | def create_grant(self, db_name, db_user, remote_ip, password): | ||
1556 | 91 | cursor = self.connection.cursor() | ||
1557 | 92 | try: | ||
1558 | 93 | # TODO: review for different grants | ||
1559 | 94 | cursor.execute("GRANT ALL PRIVILEGES ON {}.* TO '{}'@'{}' " | ||
1560 | 95 | "IDENTIFIED BY '{}'".format(db_name, | ||
1561 | 96 | db_user, | ||
1562 | 97 | remote_ip, | ||
1563 | 98 | password)) | ||
1564 | 99 | finally: | ||
1565 | 100 | cursor.close() | ||
1566 | 101 | |||
1567 | 102 | def create_admin_grant(self, db_user, remote_ip, password): | ||
1568 | 103 | cursor = self.connection.cursor() | ||
1569 | 104 | try: | ||
1570 | 105 | cursor.execute("GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}' " | ||
1571 | 106 | "IDENTIFIED BY '{}'".format(db_user, | ||
1572 | 107 | remote_ip, | ||
1573 | 108 | password)) | ||
1574 | 109 | finally: | ||
1575 | 110 | cursor.close() | ||
1576 | 111 | |||
1577 | 112 | def cleanup_grant(self, db_user, remote_ip): | ||
1578 | 113 | cursor = self.connection.cursor() | ||
1579 | 114 | try: | ||
1580 | 115 | cursor.execute("DROP FROM mysql.user WHERE user='{}' " | ||
1581 | 116 | "AND HOST='{}'".format(db_user, | ||
1582 | 117 | remote_ip)) | ||
1583 | 118 | finally: | ||
1584 | 119 | cursor.close() | ||
1585 | 120 | |||
1586 | 121 | def execute(self, sql): | ||
1587 | 122 | """Execute arbitary SQL against the database.""" | ||
1588 | 123 | cursor = self.connection.cursor() | ||
1589 | 124 | try: | ||
1590 | 125 | cursor.execute(sql) | ||
1591 | 126 | finally: | ||
1592 | 127 | cursor.close() | ||
1593 | 128 | |||
1594 | 129 | def migrate_passwords_to_peer_relation(self): | ||
1595 | 130 | """Migrate any passwords storage on disk to cluster peer relation.""" | ||
1596 | 131 | dirname = os.path.dirname(self.root_passwd_file_template) | ||
1597 | 132 | path = os.path.join(dirname, '*.passwd') | ||
1598 | 133 | for f in glob.glob(path): | ||
1599 | 134 | _key = os.path.basename(f) | ||
1600 | 135 | with open(f, 'r') as passwd: | ||
1601 | 136 | _value = passwd.read().strip() | ||
1602 | 137 | |||
1603 | 138 | try: | ||
1604 | 139 | peer_store(_key, _value) | ||
1605 | 140 | os.unlink(f) | ||
1606 | 141 | except ValueError: | ||
1607 | 142 | # NOTE cluster relation not yet ready - skip for now | ||
1608 | 143 | pass | ||
1609 | 144 | |||
1610 | 145 | def get_mysql_password_on_disk(self, username=None, password=None): | ||
1611 | 146 | """Retrieve, generate or store a mysql password for the provided | ||
1612 | 147 | username on disk.""" | ||
1613 | 148 | if username: | ||
1614 | 149 | template = self.user_passwd_file_template | ||
1615 | 150 | passwd_file = template.format(username) | ||
1616 | 151 | else: | ||
1617 | 152 | passwd_file = self.root_passwd_file_template | ||
1618 | 153 | |||
1619 | 154 | _password = None | ||
1620 | 155 | if os.path.exists(passwd_file): | ||
1621 | 156 | with open(passwd_file, 'r') as passwd: | ||
1622 | 157 | _password = passwd.read().strip() | ||
1623 | 158 | else: | ||
1624 | 159 | mkdir(os.path.dirname(passwd_file), owner='root', group='root', | ||
1625 | 160 | perms=0o770) | ||
1626 | 161 | # Force permissions - for some reason the chmod in makedirs fails | ||
1627 | 162 | os.chmod(os.path.dirname(passwd_file), 0o770) | ||
1628 | 163 | _password = password or pwgen(length=32) | ||
1629 | 164 | write_file(passwd_file, _password, owner='root', group='root', | ||
1630 | 165 | perms=0o660) | ||
1631 | 166 | |||
1632 | 167 | return _password | ||
1633 | 168 | |||
1634 | 169 | def get_mysql_password(self, username=None, password=None): | ||
1635 | 170 | """Retrieve, generate or store a mysql password for the provided | ||
1636 | 171 | username using peer relation cluster.""" | ||
1637 | 172 | self.migrate_passwords_to_peer_relation() | ||
1638 | 173 | if username: | ||
1639 | 174 | _key = 'mysql-{}.passwd'.format(username) | ||
1640 | 175 | else: | ||
1641 | 176 | _key = 'mysql.passwd' | ||
1642 | 177 | |||
1643 | 178 | try: | ||
1644 | 179 | _password = peer_retrieve(_key) | ||
1645 | 180 | if _password is None: | ||
1646 | 181 | _password = password or pwgen(length=32) | ||
1647 | 182 | peer_store(_key, _password) | ||
1648 | 183 | except ValueError: | ||
1649 | 184 | # cluster relation is not yet started; use on-disk | ||
1650 | 185 | _password = self.get_mysql_password_on_disk(username, password) | ||
1651 | 186 | |||
1652 | 187 | return _password | ||
1653 | 188 | |||
1654 | 189 | def get_mysql_root_password(self, password=None): | ||
1655 | 190 | """Retrieve or generate mysql root password for service units.""" | ||
1656 | 191 | return self.get_mysql_password(username=None, password=password) | ||
1657 | 192 | |||
1658 | 193 | def get_allowed_units(self, database, username, relation_id=None): | ||
1659 | 194 | """Get list of units with access grants for database with username. | ||
1660 | 195 | |||
1661 | 196 | This is typically used to provide shared-db relations with a list of | ||
1662 | 197 | which units have been granted access to the given database. | ||
1663 | 198 | """ | ||
1664 | 199 | self.connect(password=self.get_mysql_root_password()) | ||
1665 | 200 | allowed_units = set() | ||
1666 | 201 | for unit in related_units(relation_id): | ||
1667 | 202 | settings = relation_get(rid=relation_id, unit=unit) | ||
1668 | 203 | # First check for setting with prefix, then without | ||
1669 | 204 | for attr in ["%s_hostname" % (database), 'hostname']: | ||
1670 | 205 | hosts = settings.get(attr, None) | ||
1671 | 206 | if hosts: | ||
1672 | 207 | break | ||
1673 | 208 | |||
1674 | 209 | if hosts: | ||
1675 | 210 | # hostname can be json-encoded list of hostnames | ||
1676 | 211 | try: | ||
1677 | 212 | hosts = json.loads(hosts) | ||
1678 | 213 | except ValueError: | ||
1679 | 214 | hosts = [hosts] | ||
1680 | 215 | else: | ||
1681 | 216 | hosts = [settings['private-address']] | ||
1682 | 217 | |||
1683 | 218 | if hosts: | ||
1684 | 219 | for host in hosts: | ||
1685 | 220 | if self.grant_exists(database, username, host): | ||
1686 | 221 | log("Grant exists for host '%s' on db '%s'" % | ||
1687 | 222 | (host, database), level=DEBUG) | ||
1688 | 223 | if unit not in allowed_units: | ||
1689 | 224 | allowed_units.add(unit) | ||
1690 | 225 | else: | ||
1691 | 226 | log("Grant does NOT exist for host '%s' on db '%s'" % | ||
1692 | 227 | (host, database), level=DEBUG) | ||
1693 | 228 | else: | ||
1694 | 229 | log("No hosts found for grant check", level=INFO) | ||
1695 | 230 | |||
1696 | 231 | return allowed_units | ||
1697 | 232 | |||
1698 | 233 | def configure_db(self, hostname, database, username, admin=False): | ||
1699 | 234 | """Configure access to database for username from hostname.""" | ||
1700 | 235 | if config_get('prefer-ipv6'): | ||
1701 | 236 | remote_ip = hostname | ||
1702 | 237 | elif hostname != unit_get('private-address'): | ||
1703 | 238 | try: | ||
1704 | 239 | remote_ip = socket.gethostbyname(hostname) | ||
1705 | 240 | except Exception: | ||
1706 | 241 | # socket.gethostbyname doesn't support ipv6 | ||
1707 | 242 | remote_ip = hostname | ||
1708 | 243 | else: | ||
1709 | 244 | remote_ip = '127.0.0.1' | ||
1710 | 245 | |||
1711 | 246 | self.connect(password=self.get_mysql_root_password()) | ||
1712 | 247 | if not self.database_exists(database): | ||
1713 | 248 | self.create_database(database) | ||
1714 | 249 | |||
1715 | 250 | password = self.get_mysql_password(username) | ||
1716 | 251 | if not self.grant_exists(database, username, remote_ip): | ||
1717 | 252 | if not admin: | ||
1718 | 253 | self.create_grant(database, username, remote_ip, password) | ||
1719 | 254 | else: | ||
1720 | 255 | self.create_admin_grant(username, remote_ip, password) | ||
1721 | 256 | |||
1722 | 257 | return password | ||
1723 | 258 | |||
1724 | 259 | |||
1725 | 260 | class PerconaClusterHelper(object): | ||
1726 | 261 | |||
1727 | 262 | # Going for the biggest page size to avoid wasted bytes. InnoDB page size is | ||
1728 | 263 | # 16MB | ||
1729 | 264 | DEFAULT_PAGE_SIZE = 16 * 1024 * 1024 | ||
1730 | 265 | |||
1731 | 266 | def human_to_bytes(self, human): | ||
1732 | 267 | """Convert human readable configuration options to bytes.""" | ||
1733 | 268 | num_re = re.compile('^[0-9]+$') | ||
1734 | 269 | if num_re.match(human): | ||
1735 | 270 | return human | ||
1736 | 271 | |||
1737 | 272 | factors = { | ||
1738 | 273 | 'K': 1024, | ||
1739 | 274 | 'M': 1048576, | ||
1740 | 275 | 'G': 1073741824, | ||
1741 | 276 | 'T': 1099511627776 | ||
1742 | 277 | } | ||
1743 | 278 | modifier = human[-1] | ||
1744 | 279 | if modifier in factors: | ||
1745 | 280 | return int(human[:-1]) * factors[modifier] | ||
1746 | 281 | |||
1747 | 282 | if modifier == '%': | ||
1748 | 283 | total_ram = self.human_to_bytes(self.get_mem_total()) | ||
1749 | 284 | if self.is_32bit_system() and total_ram > self.sys_mem_limit(): | ||
1750 | 285 | total_ram = self.sys_mem_limit() | ||
1751 | 286 | factor = int(human[:-1]) * 0.01 | ||
1752 | 287 | pctram = total_ram * factor | ||
1753 | 288 | return int(pctram - (pctram % self.DEFAULT_PAGE_SIZE)) | ||
1754 | 289 | |||
1755 | 290 | raise ValueError("Can only convert K,M,G, or T") | ||
1756 | 291 | |||
1757 | 292 | def is_32bit_system(self): | ||
1758 | 293 | """Determine whether system is 32 or 64 bit.""" | ||
1759 | 294 | try: | ||
1760 | 295 | return sys.maxsize < 2 ** 32 | ||
1761 | 296 | except OverflowError: | ||
1762 | 297 | return False | ||
1763 | 298 | |||
1764 | 299 | def sys_mem_limit(self): | ||
1765 | 300 | """Determine the default memory limit for the current service unit.""" | ||
1766 | 301 | if platform.machine() in ['armv7l']: | ||
1767 | 302 | _mem_limit = self.human_to_bytes('2700M') # experimentally determined | ||
1768 | 303 | else: | ||
1769 | 304 | # Limit for x86 based 32bit systems | ||
1770 | 305 | _mem_limit = self.human_to_bytes('4G') | ||
1771 | 306 | |||
1772 | 307 | return _mem_limit | ||
1773 | 308 | |||
1774 | 309 | def get_mem_total(self): | ||
1775 | 310 | """Calculate the total memory in the current service unit.""" | ||
1776 | 311 | with open('/proc/meminfo') as meminfo_file: | ||
1777 | 312 | for line in meminfo_file: | ||
1778 | 313 | key, mem = line.split(':', 2) | ||
1779 | 314 | if key == 'MemTotal': | ||
1780 | 315 | mtot, modifier = mem.strip().split(' ') | ||
1781 | 316 | return '%s%s' % (mtot, upper(modifier[0])) | ||
1782 | 317 | |||
1783 | 318 | def parse_config(self): | ||
1784 | 319 | """Parse charm configuration and calculate values for config files.""" | ||
1785 | 320 | config = config_get() | ||
1786 | 321 | mysql_config = {} | ||
1787 | 322 | if 'max-connections' in config: | ||
1788 | 323 | mysql_config['max_connections'] = config['max-connections'] | ||
1789 | 324 | |||
1790 | 325 | # Total memory available for dataset | ||
1791 | 326 | dataset_bytes = self.human_to_bytes(config['dataset-size']) | ||
1792 | 327 | mysql_config['dataset_bytes'] = dataset_bytes | ||
1793 | 328 | |||
1794 | 329 | if 'query-cache-type' in config: | ||
1795 | 330 | # Query Cache Configuration | ||
1796 | 331 | mysql_config['query_cache_size'] = config['query-cache-size'] | ||
1797 | 332 | if (config['query-cache-size'] == -1 and | ||
1798 | 333 | config['query-cache-type'] in ['ON', 'DEMAND']): | ||
1799 | 334 | # Calculate the query cache size automatically | ||
1800 | 335 | qcache_bytes = (dataset_bytes * 0.20) | ||
1801 | 336 | qcache_bytes = int(qcache_bytes - | ||
1802 | 337 | (qcache_bytes % self.DEFAULT_PAGE_SIZE)) | ||
1803 | 338 | mysql_config['query_cache_size'] = qcache_bytes | ||
1804 | 339 | dataset_bytes -= qcache_bytes | ||
1805 | 340 | |||
1806 | 341 | # 5.5 allows the words, but not 5.1 | ||
1807 | 342 | if config['query-cache-type'] == 'ON': | ||
1808 | 343 | mysql_config['query_cache_type'] = 1 | ||
1809 | 344 | elif config['query-cache-type'] == 'DEMAND': | ||
1810 | 345 | mysql_config['query_cache_type'] = 2 | ||
1811 | 346 | else: | ||
1812 | 347 | mysql_config['query_cache_type'] = 0 | ||
1813 | 348 | |||
1814 | 349 | # Set a sane default key_buffer size | ||
1815 | 350 | mysql_config['key_buffer'] = self.human_to_bytes('32M') | ||
1816 | 351 | |||
1817 | 352 | if 'preferred-storage-engine' in config: | ||
1818 | 353 | # Storage engine configuration | ||
1819 | 354 | preferred_engines = config['preferred-storage-engine'].split(',') | ||
1820 | 355 | chunk_size = int(dataset_bytes / len(preferred_engines)) | ||
1821 | 356 | mysql_config['innodb_flush_log_at_trx_commit'] = 1 | ||
1822 | 357 | mysql_config['sync_binlog'] = 1 | ||
1823 | 358 | if 'InnoDB' in preferred_engines: | ||
1824 | 359 | mysql_config['innodb_buffer_pool_size'] = chunk_size | ||
1825 | 360 | if config['tuning-level'] == 'fast': | ||
1826 | 361 | mysql_config['innodb_flush_log_at_trx_commit'] = 2 | ||
1827 | 362 | else: | ||
1828 | 363 | mysql_config['innodb_buffer_pool_size'] = 0 | ||
1829 | 364 | |||
1830 | 365 | mysql_config['default_storage_engine'] = preferred_engines[0] | ||
1831 | 366 | if 'MyISAM' in preferred_engines: | ||
1832 | 367 | mysql_config['key_buffer'] = chunk_size | ||
1833 | 368 | |||
1834 | 369 | if config['tuning-level'] == 'fast': | ||
1835 | 370 | mysql_config['sync_binlog'] = 0 | ||
1836 | 371 | |||
1837 | 372 | return mysql_config | ||
1838 | 0 | 373 | ||
1839 | === added directory 'hooks/charmhelpers/contrib/hahelpers' | |||
1840 | === added file 'hooks/charmhelpers/contrib/hahelpers/__init__.py' | |||
1841 | --- hooks/charmhelpers/contrib/hahelpers/__init__.py 1970-01-01 00:00:00 +0000 | |||
1842 | +++ hooks/charmhelpers/contrib/hahelpers/__init__.py 2015-06-18 17:19:58 +0000 | |||
1843 | @@ -0,0 +1,15 @@ | |||
1844 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1845 | 2 | # | ||
1846 | 3 | # This file is part of charm-helpers. | ||
1847 | 4 | # | ||
1848 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1849 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1850 | 7 | # published by the Free Software Foundation. | ||
1851 | 8 | # | ||
1852 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1853 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1854 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1855 | 12 | # GNU Lesser General Public License for more details. | ||
1856 | 13 | # | ||
1857 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1858 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1859 | 0 | 16 | ||
1860 | === added file 'hooks/charmhelpers/contrib/hahelpers/apache.py' | |||
1861 | --- hooks/charmhelpers/contrib/hahelpers/apache.py 1970-01-01 00:00:00 +0000 | |||
1862 | +++ hooks/charmhelpers/contrib/hahelpers/apache.py 2015-06-18 17:19:58 +0000 | |||
1863 | @@ -0,0 +1,82 @@ | |||
1864 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1865 | 2 | # | ||
1866 | 3 | # This file is part of charm-helpers. | ||
1867 | 4 | # | ||
1868 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1869 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1870 | 7 | # published by the Free Software Foundation. | ||
1871 | 8 | # | ||
1872 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1873 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1874 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1875 | 12 | # GNU Lesser General Public License for more details. | ||
1876 | 13 | # | ||
1877 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1878 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1879 | 16 | |||
1880 | 17 | # | ||
1881 | 18 | # Copyright 2012 Canonical Ltd. | ||
1882 | 19 | # | ||
1883 | 20 | # This file is sourced from lp:openstack-charm-helpers | ||
1884 | 21 | # | ||
1885 | 22 | # Authors: | ||
1886 | 23 | # James Page <james.page@ubuntu.com> | ||
1887 | 24 | # Adam Gandelman <adamg@ubuntu.com> | ||
1888 | 25 | # | ||
1889 | 26 | |||
1890 | 27 | import subprocess | ||
1891 | 28 | |||
1892 | 29 | from charmhelpers.core.hookenv import ( | ||
1893 | 30 | config as config_get, | ||
1894 | 31 | relation_get, | ||
1895 | 32 | relation_ids, | ||
1896 | 33 | related_units as relation_list, | ||
1897 | 34 | log, | ||
1898 | 35 | INFO, | ||
1899 | 36 | ) | ||
1900 | 37 | |||
1901 | 38 | |||
1902 | 39 | def get_cert(cn=None): | ||
1903 | 40 | # TODO: deal with multiple https endpoints via charm config | ||
1904 | 41 | cert = config_get('ssl_cert') | ||
1905 | 42 | key = config_get('ssl_key') | ||
1906 | 43 | if not (cert and key): | ||
1907 | 44 | log("Inspecting identity-service relations for SSL certificate.", | ||
1908 | 45 | level=INFO) | ||
1909 | 46 | cert = key = None | ||
1910 | 47 | if cn: | ||
1911 | 48 | ssl_cert_attr = 'ssl_cert_{}'.format(cn) | ||
1912 | 49 | ssl_key_attr = 'ssl_key_{}'.format(cn) | ||
1913 | 50 | else: | ||
1914 | 51 | ssl_cert_attr = 'ssl_cert' | ||
1915 | 52 | ssl_key_attr = 'ssl_key' | ||
1916 | 53 | for r_id in relation_ids('identity-service'): | ||
1917 | 54 | for unit in relation_list(r_id): | ||
1918 | 55 | if not cert: | ||
1919 | 56 | cert = relation_get(ssl_cert_attr, | ||
1920 | 57 | rid=r_id, unit=unit) | ||
1921 | 58 | if not key: | ||
1922 | 59 | key = relation_get(ssl_key_attr, | ||
1923 | 60 | rid=r_id, unit=unit) | ||
1924 | 61 | return (cert, key) | ||
1925 | 62 | |||
1926 | 63 | |||
1927 | 64 | def get_ca_cert(): | ||
1928 | 65 | ca_cert = config_get('ssl_ca') | ||
1929 | 66 | if ca_cert is None: | ||
1930 | 67 | log("Inspecting identity-service relations for CA SSL certificate.", | ||
1931 | 68 | level=INFO) | ||
1932 | 69 | for r_id in relation_ids('identity-service'): | ||
1933 | 70 | for unit in relation_list(r_id): | ||
1934 | 71 | if ca_cert is None: | ||
1935 | 72 | ca_cert = relation_get('ca_cert', | ||
1936 | 73 | rid=r_id, unit=unit) | ||
1937 | 74 | return ca_cert | ||
1938 | 75 | |||
1939 | 76 | |||
1940 | 77 | def install_ca_cert(ca_cert): | ||
1941 | 78 | if ca_cert: | ||
1942 | 79 | with open('/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt', | ||
1943 | 80 | 'w') as crt: | ||
1944 | 81 | crt.write(ca_cert) | ||
1945 | 82 | subprocess.check_call(['update-ca-certificates', '--fresh']) | ||
1946 | 0 | 83 | ||
1947 | === added file 'hooks/charmhelpers/contrib/hahelpers/cluster.py' | |||
1948 | --- hooks/charmhelpers/contrib/hahelpers/cluster.py 1970-01-01 00:00:00 +0000 | |||
1949 | +++ hooks/charmhelpers/contrib/hahelpers/cluster.py 2015-06-18 17:19:58 +0000 | |||
1950 | @@ -0,0 +1,268 @@ | |||
1951 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1952 | 2 | # | ||
1953 | 3 | # This file is part of charm-helpers. | ||
1954 | 4 | # | ||
1955 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1956 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1957 | 7 | # published by the Free Software Foundation. | ||
1958 | 8 | # | ||
1959 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1960 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1961 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1962 | 12 | # GNU Lesser General Public License for more details. | ||
1963 | 13 | # | ||
1964 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1965 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1966 | 16 | |||
1967 | 17 | # | ||
1968 | 18 | # Copyright 2012 Canonical Ltd. | ||
1969 | 19 | # | ||
1970 | 20 | # Authors: | ||
1971 | 21 | # James Page <james.page@ubuntu.com> | ||
1972 | 22 | # Adam Gandelman <adamg@ubuntu.com> | ||
1973 | 23 | # | ||
1974 | 24 | |||
1975 | 25 | """ | ||
1976 | 26 | Helpers for clustering and determining "cluster leadership" and other | ||
1977 | 27 | clustering-related helpers. | ||
1978 | 28 | """ | ||
1979 | 29 | |||
1980 | 30 | import subprocess | ||
1981 | 31 | import os | ||
1982 | 32 | |||
1983 | 33 | from socket import gethostname as get_unit_hostname | ||
1984 | 34 | |||
1985 | 35 | import six | ||
1986 | 36 | |||
1987 | 37 | from charmhelpers.core.hookenv import ( | ||
1988 | 38 | log, | ||
1989 | 39 | relation_ids, | ||
1990 | 40 | related_units as relation_list, | ||
1991 | 41 | relation_get, | ||
1992 | 42 | config as config_get, | ||
1993 | 43 | INFO, | ||
1994 | 44 | ERROR, | ||
1995 | 45 | WARNING, | ||
1996 | 46 | unit_get, | ||
1997 | 47 | ) | ||
1998 | 48 | from charmhelpers.core.decorators import ( | ||
1999 | 49 | retry_on_exception, | ||
2000 | 50 | ) | ||
2001 | 51 | |||
2002 | 52 | |||
2003 | 53 | class HAIncompleteConfig(Exception): | ||
2004 | 54 | pass | ||
2005 | 55 | |||
2006 | 56 | |||
2007 | 57 | class CRMResourceNotFound(Exception): | ||
2008 | 58 | pass | ||
2009 | 59 | |||
2010 | 60 | |||
2011 | 61 | def is_elected_leader(resource): | ||
2012 | 62 | """ | ||
2013 | 63 | Returns True if the charm executing this is the elected cluster leader. | ||
2014 | 64 | |||
2015 | 65 | It relies on two mechanisms to determine leadership: | ||
2016 | 66 | 1. If the charm is part of a corosync cluster, call corosync to | ||
2017 | 67 | determine leadership. | ||
2018 | 68 | 2. If the charm is not part of a corosync cluster, the leader is | ||
2019 | 69 | determined as being "the alive unit with the lowest unit numer". In | ||
2020 | 70 | other words, the oldest surviving unit. | ||
2021 | 71 | """ | ||
2022 | 72 | if is_clustered(): | ||
2023 | 73 | if not is_crm_leader(resource): | ||
2024 | 74 | log('Deferring action to CRM leader.', level=INFO) | ||
2025 | 75 | return False | ||
2026 | 76 | else: | ||
2027 | 77 | peers = peer_units() | ||
2028 | 78 | if peers and not oldest_peer(peers): | ||
2029 | 79 | log('Deferring action to oldest service unit.', level=INFO) | ||
2030 | 80 | return False | ||
2031 | 81 | return True | ||
2032 | 82 | |||
2033 | 83 | |||
2034 | 84 | def is_clustered(): | ||
2035 | 85 | for r_id in (relation_ids('ha') or []): | ||
2036 | 86 | for unit in (relation_list(r_id) or []): | ||
2037 | 87 | clustered = relation_get('clustered', | ||
2038 | 88 | rid=r_id, | ||
2039 | 89 | unit=unit) | ||
2040 | 90 | if clustered: | ||
2041 | 91 | return True | ||
2042 | 92 | return False | ||
2043 | 93 | |||
2044 | 94 | |||
2045 | 95 | @retry_on_exception(5, base_delay=2, exc_type=CRMResourceNotFound) | ||
2046 | 96 | def is_crm_leader(resource, retry=False): | ||
2047 | 97 | """ | ||
2048 | 98 | Returns True if the charm calling this is the elected corosync leader, | ||
2049 | 99 | as returned by calling the external "crm" command. | ||
2050 | 100 | |||
2051 | 101 | We allow this operation to be retried to avoid the possibility of getting a | ||
2052 | 102 | false negative. See LP #1396246 for more info. | ||
2053 | 103 | """ | ||
2054 | 104 | cmd = ['crm', 'resource', 'show', resource] | ||
2055 | 105 | try: | ||
2056 | 106 | status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) | ||
2057 | 107 | if not isinstance(status, six.text_type): | ||
2058 | 108 | status = six.text_type(status, "utf-8") | ||
2059 | 109 | except subprocess.CalledProcessError: | ||
2060 | 110 | status = None | ||
2061 | 111 | |||
2062 | 112 | if status and get_unit_hostname() in status: | ||
2063 | 113 | return True | ||
2064 | 114 | |||
2065 | 115 | if status and "resource %s is NOT running" % (resource) in status: | ||
2066 | 116 | raise CRMResourceNotFound("CRM resource %s not found" % (resource)) | ||
2067 | 117 | |||
2068 | 118 | return False | ||
2069 | 119 | |||
2070 | 120 | |||
2071 | 121 | def is_leader(resource): | ||
2072 | 122 | log("is_leader is deprecated. Please consider using is_crm_leader " | ||
2073 | 123 | "instead.", level=WARNING) | ||
2074 | 124 | return is_crm_leader(resource) | ||
2075 | 125 | |||
2076 | 126 | |||
2077 | 127 | def peer_units(peer_relation="cluster"): | ||
2078 | 128 | peers = [] | ||
2079 | 129 | for r_id in (relation_ids(peer_relation) or []): | ||
2080 | 130 | for unit in (relation_list(r_id) or []): | ||
2081 | 131 | peers.append(unit) | ||
2082 | 132 | return peers | ||
2083 | 133 | |||
2084 | 134 | |||
2085 | 135 | def peer_ips(peer_relation='cluster', addr_key='private-address'): | ||
2086 | 136 | '''Return a dict of peers and their private-address''' | ||
2087 | 137 | peers = {} | ||
2088 | 138 | for r_id in relation_ids(peer_relation): | ||
2089 | 139 | for unit in relation_list(r_id): | ||
2090 | 140 | peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) | ||
2091 | 141 | return peers | ||
2092 | 142 | |||
2093 | 143 | |||
2094 | 144 | def oldest_peer(peers): | ||
2095 | 145 | """Determines who the oldest peer is by comparing unit numbers.""" | ||
2096 | 146 | local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) | ||
2097 | 147 | for peer in peers: | ||
2098 | 148 | remote_unit_no = int(peer.split('/')[1]) | ||
2099 | 149 | if remote_unit_no < local_unit_no: | ||
2100 | 150 | return False | ||
2101 | 151 | return True | ||
2102 | 152 | |||
2103 | 153 | |||
2104 | 154 | def eligible_leader(resource): | ||
2105 | 155 | log("eligible_leader is deprecated. Please consider using " | ||
2106 | 156 | "is_elected_leader instead.", level=WARNING) | ||
2107 | 157 | return is_elected_leader(resource) | ||
2108 | 158 | |||
2109 | 159 | |||
2110 | 160 | def https(): | ||
2111 | 161 | ''' | ||
2112 | 162 | Determines whether enough data has been provided in configuration | ||
2113 | 163 | or relation data to configure HTTPS | ||
2114 | 164 | . | ||
2115 | 165 | returns: boolean | ||
2116 | 166 | ''' | ||
2117 | 167 | if config_get('use-https') == "yes": | ||
2118 | 168 | return True | ||
2119 | 169 | if config_get('ssl_cert') and config_get('ssl_key'): | ||
2120 | 170 | return True | ||
2121 | 171 | for r_id in relation_ids('identity-service'): | ||
2122 | 172 | for unit in relation_list(r_id): | ||
2123 | 173 | # TODO - needs fixing for new helper as ssl_cert/key suffixes with CN | ||
2124 | 174 | rel_state = [ | ||
2125 | 175 | relation_get('https_keystone', rid=r_id, unit=unit), | ||
2126 | 176 | relation_get('ca_cert', rid=r_id, unit=unit), | ||
2127 | 177 | ] | ||
2128 | 178 | # NOTE: works around (LP: #1203241) | ||
2129 | 179 | if (None not in rel_state) and ('' not in rel_state): | ||
2130 | 180 | return True | ||
2131 | 181 | return False | ||
2132 | 182 | |||
2133 | 183 | |||
2134 | 184 | def determine_api_port(public_port, singlenode_mode=False): | ||
2135 | 185 | ''' | ||
2136 | 186 | Determine correct API server listening port based on | ||
2137 | 187 | existence of HTTPS reverse proxy and/or haproxy. | ||
2138 | 188 | |||
2139 | 189 | public_port: int: standard public port for given service | ||
2140 | 190 | |||
2141 | 191 | singlenode_mode: boolean: Shuffle ports when only a single unit is present | ||
2142 | 192 | |||
2143 | 193 | returns: int: the correct listening port for the API service | ||
2144 | 194 | ''' | ||
2145 | 195 | i = 0 | ||
2146 | 196 | if singlenode_mode: | ||
2147 | 197 | i += 1 | ||
2148 | 198 | elif len(peer_units()) > 0 or is_clustered(): | ||
2149 | 199 | i += 1 | ||
2150 | 200 | if https(): | ||
2151 | 201 | i += 1 | ||
2152 | 202 | return public_port - (i * 10) | ||
2153 | 203 | |||
2154 | 204 | |||
2155 | 205 | def determine_apache_port(public_port, singlenode_mode=False): | ||
2156 | 206 | ''' | ||
2157 | 207 | Description: Determine correct apache listening port based on public IP + | ||
2158 | 208 | state of the cluster. | ||
2159 | 209 | |||
2160 | 210 | public_port: int: standard public port for given service | ||
2161 | 211 | |||
2162 | 212 | singlenode_mode: boolean: Shuffle ports when only a single unit is present | ||
2163 | 213 | |||
2164 | 214 | returns: int: the correct listening port for the HAProxy service | ||
2165 | 215 | ''' | ||
2166 | 216 | i = 0 | ||
2167 | 217 | if singlenode_mode: | ||
2168 | 218 | i += 1 | ||
2169 | 219 | elif len(peer_units()) > 0 or is_clustered(): | ||
2170 | 220 | i += 1 | ||
2171 | 221 | return public_port - (i * 10) | ||
2172 | 222 | |||
2173 | 223 | |||
2174 | 224 | def get_hacluster_config(exclude_keys=None): | ||
2175 | 225 | ''' | ||
2176 | 226 | Obtains all relevant configuration from charm configuration required | ||
2177 | 227 | for initiating a relation to hacluster: | ||
2178 | 228 | |||
2179 | 229 | ha-bindiface, ha-mcastport, vip | ||
2180 | 230 | |||
2181 | 231 | param: exclude_keys: list of setting key(s) to be excluded. | ||
2182 | 232 | returns: dict: A dict containing settings keyed by setting name. | ||
2183 | 233 | raises: HAIncompleteConfig if settings are missing. | ||
2184 | 234 | ''' | ||
2185 | 235 | settings = ['ha-bindiface', 'ha-mcastport', 'vip'] | ||
2186 | 236 | conf = {} | ||
2187 | 237 | for setting in settings: | ||
2188 | 238 | if exclude_keys and setting in exclude_keys: | ||
2189 | 239 | continue | ||
2190 | 240 | |||
2191 | 241 | conf[setting] = config_get(setting) | ||
2192 | 242 | missing = [] | ||
2193 | 243 | [missing.append(s) for s, v in six.iteritems(conf) if v is None] | ||
2194 | 244 | if missing: | ||
2195 | 245 | log('Insufficient config data to configure hacluster.', level=ERROR) | ||
2196 | 246 | raise HAIncompleteConfig | ||
2197 | 247 | return conf | ||
2198 | 248 | |||
2199 | 249 | |||
2200 | 250 | def canonical_url(configs, vip_setting='vip'): | ||
2201 | 251 | ''' | ||
2202 | 252 | Returns the correct HTTP URL to this host given the state of HTTPS | ||
2203 | 253 | configuration and hacluster. | ||
2204 | 254 | |||
2205 | 255 | :configs : OSTemplateRenderer: A config tempating object to inspect for | ||
2206 | 256 | a complete https context. | ||
2207 | 257 | |||
2208 | 258 | :vip_setting: str: Setting in charm config that specifies | ||
2209 | 259 | VIP address. | ||
2210 | 260 | ''' | ||
2211 | 261 | scheme = 'http' | ||
2212 | 262 | if 'https' in configs.complete_contexts(): | ||
2213 | 263 | scheme = 'https' | ||
2214 | 264 | if is_clustered(): | ||
2215 | 265 | addr = config_get(vip_setting) | ||
2216 | 266 | else: | ||
2217 | 267 | addr = unit_get('private-address') | ||
2218 | 268 | return '%s://%s' % (scheme, addr) | ||
2219 | 0 | 269 | ||
2220 | === added directory 'hooks/charmhelpers/contrib/network' | |||
2221 | === added file 'hooks/charmhelpers/contrib/network/__init__.py' | |||
2222 | --- hooks/charmhelpers/contrib/network/__init__.py 1970-01-01 00:00:00 +0000 | |||
2223 | +++ hooks/charmhelpers/contrib/network/__init__.py 2015-06-18 17:19:58 +0000 | |||
2224 | @@ -0,0 +1,15 @@ | |||
2225 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2226 | 2 | # | ||
2227 | 3 | # This file is part of charm-helpers. | ||
2228 | 4 | # | ||
2229 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2230 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2231 | 7 | # published by the Free Software Foundation. | ||
2232 | 8 | # | ||
2233 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2234 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2235 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2236 | 12 | # GNU Lesser General Public License for more details. | ||
2237 | 13 | # | ||
2238 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2239 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2240 | 0 | 16 | ||
2241 | === added file 'hooks/charmhelpers/contrib/network/ip.py' | |||
2242 | --- hooks/charmhelpers/contrib/network/ip.py 1970-01-01 00:00:00 +0000 | |||
2243 | +++ hooks/charmhelpers/contrib/network/ip.py 2015-06-18 17:19:58 +0000 | |||
2244 | @@ -0,0 +1,367 @@ | |||
2245 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2246 | 2 | # | ||
2247 | 3 | # This file is part of charm-helpers. | ||
2248 | 4 | # | ||
2249 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2250 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2251 | 7 | # published by the Free Software Foundation. | ||
2252 | 8 | # | ||
2253 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2254 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2255 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2256 | 12 | # GNU Lesser General Public License for more details. | ||
2257 | 13 | # | ||
2258 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2259 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2260 | 16 | |||
2261 | 17 | import glob | ||
2262 | 18 | import re | ||
2263 | 19 | import subprocess | ||
2264 | 20 | |||
2265 | 21 | from functools import partial | ||
2266 | 22 | |||
2267 | 23 | from charmhelpers.core.hookenv import unit_get | ||
2268 | 24 | from charmhelpers.fetch import apt_install | ||
2269 | 25 | from charmhelpers.core.hookenv import ( | ||
2270 | 26 | log | ||
2271 | 27 | ) | ||
2272 | 28 | |||
2273 | 29 | try: | ||
2274 | 30 | import netifaces | ||
2275 | 31 | except ImportError: | ||
2276 | 32 | apt_install('python-netifaces') | ||
2277 | 33 | import netifaces | ||
2278 | 34 | |||
2279 | 35 | try: | ||
2280 | 36 | import netaddr | ||
2281 | 37 | except ImportError: | ||
2282 | 38 | apt_install('python-netaddr') | ||
2283 | 39 | import netaddr | ||
2284 | 40 | |||
2285 | 41 | |||
2286 | 42 | def _validate_cidr(network): | ||
2287 | 43 | try: | ||
2288 | 44 | netaddr.IPNetwork(network) | ||
2289 | 45 | except (netaddr.core.AddrFormatError, ValueError): | ||
2290 | 46 | raise ValueError("Network (%s) is not in CIDR presentation format" % | ||
2291 | 47 | network) | ||
2292 | 48 | |||
2293 | 49 | |||
2294 | 50 | def no_ip_found_error_out(network): | ||
2295 | 51 | errmsg = ("No IP address found in network: %s" % network) | ||
2296 | 52 | raise ValueError(errmsg) | ||
2297 | 53 | |||
2298 | 54 | |||
2299 | 55 | def get_address_in_network(network, fallback=None, fatal=False): | ||
2300 | 56 | """Get an IPv4 or IPv6 address within the network from the host. | ||
2301 | 57 | |||
2302 | 58 | :param network (str): CIDR presentation format. For example, | ||
2303 | 59 | '192.168.1.0/24'. | ||
2304 | 60 | :param fallback (str): If no address is found, return fallback. | ||
2305 | 61 | :param fatal (boolean): If no address is found, fallback is not | ||
2306 | 62 | set and fatal is True then exit(1). | ||
2307 | 63 | """ | ||
2308 | 64 | if network is None: | ||
2309 | 65 | if fallback is not None: | ||
2310 | 66 | return fallback | ||
2311 | 67 | |||
2312 | 68 | if fatal: | ||
2313 | 69 | no_ip_found_error_out(network) | ||
2314 | 70 | else: | ||
2315 | 71 | return None | ||
2316 | 72 | |||
2317 | 73 | _validate_cidr(network) | ||
2318 | 74 | network = netaddr.IPNetwork(network) | ||
2319 | 75 | for iface in netifaces.interfaces(): | ||
2320 | 76 | addresses = netifaces.ifaddresses(iface) | ||
2321 | 77 | if network.version == 4 and netifaces.AF_INET in addresses: | ||
2322 | 78 | addr = addresses[netifaces.AF_INET][0]['addr'] | ||
2323 | 79 | netmask = addresses[netifaces.AF_INET][0]['netmask'] | ||
2324 | 80 | cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask)) | ||
2325 | 81 | if cidr in network: | ||
2326 | 82 | return str(cidr.ip) | ||
2327 | 83 | |||
2328 | 84 | if network.version == 6 and netifaces.AF_INET6 in addresses: | ||
2329 | 85 | for addr in addresses[netifaces.AF_INET6]: | ||
2330 | 86 | if not addr['addr'].startswith('fe80'): | ||
2331 | 87 | cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'], | ||
2332 | 88 | addr['netmask'])) | ||
2333 | 89 | if cidr in network: | ||
2334 | 90 | return str(cidr.ip) | ||
2335 | 91 | |||
2336 | 92 | if fallback is not None: | ||
2337 | 93 | return fallback | ||
2338 | 94 | |||
2339 | 95 | if fatal: | ||
2340 | 96 | no_ip_found_error_out(network) | ||
2341 | 97 | |||
2342 | 98 | return None | ||
2343 | 99 | |||
2344 | 100 | |||
2345 | 101 | def is_ipv6(address): | ||
2346 | 102 | """Determine whether provided address is IPv6 or not.""" | ||
2347 | 103 | try: | ||
2348 | 104 | address = netaddr.IPAddress(address) | ||
2349 | 105 | except netaddr.AddrFormatError: | ||
2350 | 106 | # probably a hostname - so not an address at all! | ||
2351 | 107 | return False | ||
2352 | 108 | |||
2353 | 109 | return address.version == 6 | ||
2354 | 110 | |||
2355 | 111 | |||
2356 | 112 | def is_address_in_network(network, address): | ||
2357 | 113 | """ | ||
2358 | 114 | Determine whether the provided address is within a network range. | ||
2359 | 115 | |||
2360 | 116 | :param network (str): CIDR presentation format. For example, | ||
2361 | 117 | '192.168.1.0/24'. | ||
2362 | 118 | :param address: An individual IPv4 or IPv6 address without a net | ||
2363 | 119 | mask or subnet prefix. For example, '192.168.1.1'. | ||
2364 | 120 | :returns boolean: Flag indicating whether address is in network. | ||
2365 | 121 | """ | ||
2366 | 122 | try: | ||
2367 | 123 | network = netaddr.IPNetwork(network) | ||
2368 | 124 | except (netaddr.core.AddrFormatError, ValueError): | ||
2369 | 125 | raise ValueError("Network (%s) is not in CIDR presentation format" % | ||
2370 | 126 | network) | ||
2371 | 127 | |||
2372 | 128 | try: | ||
2373 | 129 | address = netaddr.IPAddress(address) | ||
2374 | 130 | except (netaddr.core.AddrFormatError, ValueError): | ||
2375 | 131 | raise ValueError("Address (%s) is not in correct presentation format" % | ||
2376 | 132 | address) | ||
2377 | 133 | |||
2378 | 134 | if address in network: | ||
2379 | 135 | return True | ||
2380 | 136 | else: | ||
2381 | 137 | return False | ||
2382 | 138 | |||
2383 | 139 | |||
2384 | 140 | def _get_for_address(address, key): | ||
2385 | 141 | """Retrieve an attribute of or the physical interface that | ||
2386 | 142 | the IP address provided could be bound to. | ||
2387 | 143 | |||
2388 | 144 | :param address (str): An individual IPv4 or IPv6 address without a net | ||
2389 | 145 | mask or subnet prefix. For example, '192.168.1.1'. | ||
2390 | 146 | :param key: 'iface' for the physical interface name or an attribute | ||
2391 | 147 | of the configured interface, for example 'netmask'. | ||
2392 | 148 | :returns str: Requested attribute or None if address is not bindable. | ||
2393 | 149 | """ | ||
2394 | 150 | address = netaddr.IPAddress(address) | ||
2395 | 151 | for iface in netifaces.interfaces(): | ||
2396 | 152 | addresses = netifaces.ifaddresses(iface) | ||
2397 | 153 | if address.version == 4 and netifaces.AF_INET in addresses: | ||
2398 | 154 | addr = addresses[netifaces.AF_INET][0]['addr'] | ||
2399 | 155 | netmask = addresses[netifaces.AF_INET][0]['netmask'] | ||
2400 | 156 | network = netaddr.IPNetwork("%s/%s" % (addr, netmask)) | ||
2401 | 157 | cidr = network.cidr | ||
2402 | 158 | if address in cidr: | ||
2403 | 159 | if key == 'iface': | ||
2404 | 160 | return iface | ||
2405 | 161 | else: | ||
2406 | 162 | return addresses[netifaces.AF_INET][0][key] | ||
2407 | 163 | |||
2408 | 164 | if address.version == 6 and netifaces.AF_INET6 in addresses: | ||
2409 | 165 | for addr in addresses[netifaces.AF_INET6]: | ||
2410 | 166 | if not addr['addr'].startswith('fe80'): | ||
2411 | 167 | network = netaddr.IPNetwork("%s/%s" % (addr['addr'], | ||
2412 | 168 | addr['netmask'])) | ||
2413 | 169 | cidr = network.cidr | ||
2414 | 170 | if address in cidr: | ||
2415 | 171 | if key == 'iface': | ||
2416 | 172 | return iface | ||
2417 | 173 | elif key == 'netmask' and cidr: | ||
2418 | 174 | return str(cidr).split('/')[1] | ||
2419 | 175 | else: | ||
2420 | 176 | return addr[key] | ||
2421 | 177 | |||
2422 | 178 | return None | ||
2423 | 179 | |||
2424 | 180 | |||
2425 | 181 | get_iface_for_address = partial(_get_for_address, key='iface') | ||
2426 | 182 | |||
2427 | 183 | |||
2428 | 184 | get_netmask_for_address = partial(_get_for_address, key='netmask') | ||
2429 | 185 | |||
2430 | 186 | |||
2431 | 187 | def format_ipv6_addr(address): | ||
2432 | 188 | """If address is IPv6, wrap it in '[]' otherwise return None. | ||
2433 | 189 | |||
2434 | 190 | This is required by most configuration files when specifying IPv6 | ||
2435 | 191 | addresses. | ||
2436 | 192 | """ | ||
2437 | 193 | if is_ipv6(address): | ||
2438 | 194 | return "[%s]" % address | ||
2439 | 195 | |||
2440 | 196 | return None | ||
2441 | 197 | |||
2442 | 198 | |||
2443 | 199 | def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False, | ||
2444 | 200 | fatal=True, exc_list=None): | ||
2445 | 201 | """Return the assigned IP address for a given interface, if any.""" | ||
2446 | 202 | # Extract nic if passed /dev/ethX | ||
2447 | 203 | if '/' in iface: | ||
2448 | 204 | iface = iface.split('/')[-1] | ||
2449 | 205 | |||
2450 | 206 | if not exc_list: | ||
2451 | 207 | exc_list = [] | ||
2452 | 208 | |||
2453 | 209 | try: | ||
2454 | 210 | inet_num = getattr(netifaces, inet_type) | ||
2455 | 211 | except AttributeError: | ||
2456 | 212 | raise Exception("Unknown inet type '%s'" % str(inet_type)) | ||
2457 | 213 | |||
2458 | 214 | interfaces = netifaces.interfaces() | ||
2459 | 215 | if inc_aliases: | ||
2460 | 216 | ifaces = [] | ||
2461 | 217 | for _iface in interfaces: | ||
2462 | 218 | if iface == _iface or _iface.split(':')[0] == iface: | ||
2463 | 219 | ifaces.append(_iface) | ||
2464 | 220 | |||
2465 | 221 | if fatal and not ifaces: | ||
2466 | 222 | raise Exception("Invalid interface '%s'" % iface) | ||
2467 | 223 | |||
2468 | 224 | ifaces.sort() | ||
2469 | 225 | else: | ||
2470 | 226 | if iface not in interfaces: | ||
2471 | 227 | if fatal: | ||
2472 | 228 | raise Exception("Interface '%s' not found " % (iface)) | ||
2473 | 229 | else: | ||
2474 | 230 | return [] | ||
2475 | 231 | |||
2476 | 232 | else: | ||
2477 | 233 | ifaces = [iface] | ||
2478 | 234 | |||
2479 | 235 | addresses = [] | ||
2480 | 236 | for netiface in ifaces: | ||
2481 | 237 | net_info = netifaces.ifaddresses(netiface) | ||
2482 | 238 | if inet_num in net_info: | ||
2483 | 239 | for entry in net_info[inet_num]: | ||
2484 | 240 | if 'addr' in entry and entry['addr'] not in exc_list: | ||
2485 | 241 | addresses.append(entry['addr']) | ||
2486 | 242 | |||
2487 | 243 | if fatal and not addresses: | ||
2488 | 244 | raise Exception("Interface '%s' doesn't have any %s addresses." % | ||
2489 | 245 | (iface, inet_type)) | ||
2490 | 246 | |||
2491 | 247 | return sorted(addresses) | ||
2492 | 248 | |||
2493 | 249 | |||
2494 | 250 | get_ipv4_addr = partial(get_iface_addr, inet_type='AF_INET') | ||
2495 | 251 | |||
2496 | 252 | |||
2497 | 253 | def get_iface_from_addr(addr): | ||
2498 | 254 | """Work out on which interface the provided address is configured.""" | ||
2499 | 255 | for iface in netifaces.interfaces(): | ||
2500 | 256 | addresses = netifaces.ifaddresses(iface) | ||
2501 | 257 | for inet_type in addresses: | ||
2502 | 258 | for _addr in addresses[inet_type]: | ||
2503 | 259 | _addr = _addr['addr'] | ||
2504 | 260 | # link local | ||
2505 | 261 | ll_key = re.compile("(.+)%.*") | ||
2506 | 262 | raw = re.match(ll_key, _addr) | ||
2507 | 263 | if raw: | ||
2508 | 264 | _addr = raw.group(1) | ||
2509 | 265 | |||
2510 | 266 | if _addr == addr: | ||
2511 | 267 | log("Address '%s' is configured on iface '%s'" % | ||
2512 | 268 | (addr, iface)) | ||
2513 | 269 | return iface | ||
2514 | 270 | |||
2515 | 271 | msg = "Unable to infer net iface on which '%s' is configured" % (addr) | ||
2516 | 272 | raise Exception(msg) | ||
2517 | 273 | |||
2518 | 274 | |||
2519 | 275 | def sniff_iface(f): | ||
2520 | 276 | """Ensure decorated function is called with a value for iface. | ||
2521 | 277 | |||
2522 | 278 | If no iface provided, inject net iface inferred from unit private address. | ||
2523 | 279 | """ | ||
2524 | 280 | def iface_sniffer(*args, **kwargs): | ||
2525 | 281 | if not kwargs.get('iface', None): | ||
2526 | 282 | kwargs['iface'] = get_iface_from_addr(unit_get('private-address')) | ||
2527 | 283 | |||
2528 | 284 | return f(*args, **kwargs) | ||
2529 | 285 | |||
2530 | 286 | return iface_sniffer | ||
2531 | 287 | |||
2532 | 288 | |||
2533 | 289 | @sniff_iface | ||
2534 | 290 | def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None, | ||
2535 | 291 | dynamic_only=True): | ||
2536 | 292 | """Get assigned IPv6 address for a given interface. | ||
2537 | 293 | |||
2538 | 294 | Returns list of addresses found. If no address found, returns empty list. | ||
2539 | 295 | |||
2540 | 296 | If iface is None, we infer the current primary interface by doing a reverse | ||
2541 | 297 | lookup on the unit private-address. | ||
2542 | 298 | |||
2543 | 299 | We currently only support scope global IPv6 addresses i.e. non-temporary | ||
2544 | 300 | addresses. If no global IPv6 address is found, return the first one found | ||
2545 | 301 | in the ipv6 address list. | ||
2546 | 302 | """ | ||
2547 | 303 | addresses = get_iface_addr(iface=iface, inet_type='AF_INET6', | ||
2548 | 304 | inc_aliases=inc_aliases, fatal=fatal, | ||
2549 | 305 | exc_list=exc_list) | ||
2550 | 306 | |||
2551 | 307 | if addresses: | ||
2552 | 308 | global_addrs = [] | ||
2553 | 309 | for addr in addresses: | ||
2554 | 310 | key_scope_link_local = re.compile("^fe80::..(.+)%(.+)") | ||
2555 | 311 | m = re.match(key_scope_link_local, addr) | ||
2556 | 312 | if m: | ||
2557 | 313 | eui_64_mac = m.group(1) | ||
2558 | 314 | iface = m.group(2) | ||
2559 | 315 | else: | ||
2560 | 316 | global_addrs.append(addr) | ||
2561 | 317 | |||
2562 | 318 | if global_addrs: | ||
2563 | 319 | # Make sure any found global addresses are not temporary | ||
2564 | 320 | cmd = ['ip', 'addr', 'show', iface] | ||
2565 | 321 | out = subprocess.check_output(cmd).decode('UTF-8') | ||
2566 | 322 | if dynamic_only: | ||
2567 | 323 | key = re.compile("inet6 (.+)/[0-9]+ scope global dynamic.*") | ||
2568 | 324 | else: | ||
2569 | 325 | key = re.compile("inet6 (.+)/[0-9]+ scope global.*") | ||
2570 | 326 | |||
2571 | 327 | addrs = [] | ||
2572 | 328 | for line in out.split('\n'): | ||
2573 | 329 | line = line.strip() | ||
2574 | 330 | m = re.match(key, line) | ||
2575 | 331 | if m and 'temporary' not in line: | ||
2576 | 332 | # Return the first valid address we find | ||
2577 | 333 | for addr in global_addrs: | ||
2578 | 334 | if m.group(1) == addr: | ||
2579 | 335 | if not dynamic_only or \ | ||
2580 | 336 | m.group(1).endswith(eui_64_mac): | ||
2581 | 337 | addrs.append(addr) | ||
2582 | 338 | |||
2583 | 339 | if addrs: | ||
2584 | 340 | return addrs | ||
2585 | 341 | |||
2586 | 342 | if fatal: | ||
2587 | 343 | raise Exception("Interface '%s' does not have a scope global " | ||
2588 | 344 | "non-temporary ipv6 address." % iface) | ||
2589 | 345 | |||
2590 | 346 | return [] | ||
2591 | 347 | |||
2592 | 348 | |||
2593 | 349 | def get_bridges(vnic_dir='/sys/devices/virtual/net'): | ||
2594 | 350 | """Return a list of bridges on the system.""" | ||
2595 | 351 | b_regex = "%s/*/bridge" % vnic_dir | ||
2596 | 352 | return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)] | ||
2597 | 353 | |||
2598 | 354 | |||
2599 | 355 | def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'): | ||
2600 | 356 | """Return a list of nics comprising a given bridge on the system.""" | ||
2601 | 357 | brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge) | ||
2602 | 358 | return [x.split('/')[-1] for x in glob.glob(brif_regex)] | ||
2603 | 359 | |||
2604 | 360 | |||
2605 | 361 | def is_bridge_member(nic): | ||
2606 | 362 | """Check if a given nic is a member of a bridge.""" | ||
2607 | 363 | for bridge in get_bridges(): | ||
2608 | 364 | if nic in get_bridge_nics(bridge): | ||
2609 | 365 | return True | ||
2610 | 366 | |||
2611 | 367 | return False | ||
2612 | 0 | 368 | ||
2613 | === added directory 'hooks/charmhelpers/contrib/network/ovs' | |||
2614 | === added file 'hooks/charmhelpers/contrib/network/ovs/__init__.py' | |||
2615 | --- hooks/charmhelpers/contrib/network/ovs/__init__.py 1970-01-01 00:00:00 +0000 | |||
2616 | +++ hooks/charmhelpers/contrib/network/ovs/__init__.py 2015-06-18 17:19:58 +0000 | |||
2617 | @@ -0,0 +1,96 @@ | |||
2618 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2619 | 2 | # | ||
2620 | 3 | # This file is part of charm-helpers. | ||
2621 | 4 | # | ||
2622 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2623 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2624 | 7 | # published by the Free Software Foundation. | ||
2625 | 8 | # | ||
2626 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2627 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2628 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2629 | 12 | # GNU Lesser General Public License for more details. | ||
2630 | 13 | # | ||
2631 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2632 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2633 | 16 | |||
2634 | 17 | ''' Helpers for interacting with OpenvSwitch ''' | ||
2635 | 18 | import subprocess | ||
2636 | 19 | import os | ||
2637 | 20 | from charmhelpers.core.hookenv import ( | ||
2638 | 21 | log, WARNING | ||
2639 | 22 | ) | ||
2640 | 23 | from charmhelpers.core.host import ( | ||
2641 | 24 | service | ||
2642 | 25 | ) | ||
2643 | 26 | |||
2644 | 27 | |||
2645 | 28 | def add_bridge(name): | ||
2646 | 29 | ''' Add the named bridge to openvswitch ''' | ||
2647 | 30 | log('Creating bridge {}'.format(name)) | ||
2648 | 31 | subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-br", name]) | ||
2649 | 32 | |||
2650 | 33 | |||
2651 | 34 | def del_bridge(name): | ||
2652 | 35 | ''' Delete the named bridge from openvswitch ''' | ||
2653 | 36 | log('Deleting bridge {}'.format(name)) | ||
2654 | 37 | subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-br", name]) | ||
2655 | 38 | |||
2656 | 39 | |||
2657 | 40 | def add_bridge_port(name, port, promisc=False): | ||
2658 | 41 | ''' Add a port to the named openvswitch bridge ''' | ||
2659 | 42 | log('Adding port {} to bridge {}'.format(port, name)) | ||
2660 | 43 | subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port", | ||
2661 | 44 | name, port]) | ||
2662 | 45 | subprocess.check_call(["ip", "link", "set", port, "up"]) | ||
2663 | 46 | if promisc: | ||
2664 | 47 | subprocess.check_call(["ip", "link", "set", port, "promisc", "on"]) | ||
2665 | 48 | else: | ||
2666 | 49 | subprocess.check_call(["ip", "link", "set", port, "promisc", "off"]) | ||
2667 | 50 | |||
2668 | 51 | |||
2669 | 52 | def del_bridge_port(name, port): | ||
2670 | 53 | ''' Delete a port from the named openvswitch bridge ''' | ||
2671 | 54 | log('Deleting port {} from bridge {}'.format(port, name)) | ||
2672 | 55 | subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port", | ||
2673 | 56 | name, port]) | ||
2674 | 57 | subprocess.check_call(["ip", "link", "set", port, "down"]) | ||
2675 | 58 | subprocess.check_call(["ip", "link", "set", port, "promisc", "off"]) | ||
2676 | 59 | |||
2677 | 60 | |||
2678 | 61 | def set_manager(manager): | ||
2679 | 62 | ''' Set the controller for the local openvswitch ''' | ||
2680 | 63 | log('Setting manager for local ovs to {}'.format(manager)) | ||
2681 | 64 | subprocess.check_call(['ovs-vsctl', 'set-manager', | ||
2682 | 65 | 'ssl:{}'.format(manager)]) | ||
2683 | 66 | |||
2684 | 67 | |||
2685 | 68 | CERT_PATH = '/etc/openvswitch/ovsclient-cert.pem' | ||
2686 | 69 | |||
2687 | 70 | |||
2688 | 71 | def get_certificate(): | ||
2689 | 72 | ''' Read openvswitch certificate from disk ''' | ||
2690 | 73 | if os.path.exists(CERT_PATH): | ||
2691 | 74 | log('Reading ovs certificate from {}'.format(CERT_PATH)) | ||
2692 | 75 | with open(CERT_PATH, 'r') as cert: | ||
2693 | 76 | full_cert = cert.read() | ||
2694 | 77 | begin_marker = "-----BEGIN CERTIFICATE-----" | ||
2695 | 78 | end_marker = "-----END CERTIFICATE-----" | ||
2696 | 79 | begin_index = full_cert.find(begin_marker) | ||
2697 | 80 | end_index = full_cert.rfind(end_marker) | ||
2698 | 81 | if end_index == -1 or begin_index == -1: | ||
2699 | 82 | raise RuntimeError("Certificate does not contain valid begin" | ||
2700 | 83 | " and end markers.") | ||
2701 | 84 | full_cert = full_cert[begin_index:(end_index + len(end_marker))] | ||
2702 | 85 | return full_cert | ||
2703 | 86 | else: | ||
2704 | 87 | log('Certificate not found', level=WARNING) | ||
2705 | 88 | return None | ||
2706 | 89 | |||
2707 | 90 | |||
2708 | 91 | def full_restart(): | ||
2709 | 92 | ''' Full restart and reload of openvswitch ''' | ||
2710 | 93 | if os.path.exists('/etc/init/openvswitch-force-reload-kmod.conf'): | ||
2711 | 94 | service('start', 'openvswitch-force-reload-kmod') | ||
2712 | 95 | else: | ||
2713 | 96 | service('force-reload-kmod', 'openvswitch-switch') | ||
2714 | 0 | 97 | ||
2715 | === added file 'hooks/charmhelpers/contrib/network/ufw.py' | |||
2716 | --- hooks/charmhelpers/contrib/network/ufw.py 1970-01-01 00:00:00 +0000 | |||
2717 | +++ hooks/charmhelpers/contrib/network/ufw.py 2015-06-18 17:19:58 +0000 | |||
2718 | @@ -0,0 +1,276 @@ | |||
2719 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2720 | 2 | # | ||
2721 | 3 | # This file is part of charm-helpers. | ||
2722 | 4 | # | ||
2723 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2724 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2725 | 7 | # published by the Free Software Foundation. | ||
2726 | 8 | # | ||
2727 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2728 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2729 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2730 | 12 | # GNU Lesser General Public License for more details. | ||
2731 | 13 | # | ||
2732 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2733 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2734 | 16 | |||
2735 | 17 | """ | ||
2736 | 18 | This module contains helpers to add and remove ufw rules. | ||
2737 | 19 | |||
2738 | 20 | Examples: | ||
2739 | 21 | |||
2740 | 22 | - open SSH port for subnet 10.0.3.0/24: | ||
2741 | 23 | |||
2742 | 24 | >>> from charmhelpers.contrib.network import ufw | ||
2743 | 25 | >>> ufw.enable() | ||
2744 | 26 | >>> ufw.grant_access(src='10.0.3.0/24', dst='any', port='22', proto='tcp') | ||
2745 | 27 | |||
2746 | 28 | - open service by name as defined in /etc/services: | ||
2747 | 29 | |||
2748 | 30 | >>> from charmhelpers.contrib.network import ufw | ||
2749 | 31 | >>> ufw.enable() | ||
2750 | 32 | >>> ufw.service('ssh', 'open') | ||
2751 | 33 | |||
2752 | 34 | - close service by port number: | ||
2753 | 35 | |||
2754 | 36 | >>> from charmhelpers.contrib.network import ufw | ||
2755 | 37 | >>> ufw.enable() | ||
2756 | 38 | >>> ufw.service('4949', 'close') # munin | ||
2757 | 39 | """ | ||
2758 | 40 | import re | ||
2759 | 41 | import os | ||
2760 | 42 | import subprocess | ||
2761 | 43 | from charmhelpers.core import hookenv | ||
2762 | 44 | |||
2763 | 45 | __author__ = "Felipe Reyes <felipe.reyes@canonical.com>" | ||
2764 | 46 | |||
2765 | 47 | |||
2766 | 48 | class UFWError(Exception): | ||
2767 | 49 | pass | ||
2768 | 50 | |||
2769 | 51 | |||
2770 | 52 | class UFWIPv6Error(UFWError): | ||
2771 | 53 | pass | ||
2772 | 54 | |||
2773 | 55 | |||
2774 | 56 | def is_enabled(): | ||
2775 | 57 | """ | ||
2776 | 58 | Check if `ufw` is enabled | ||
2777 | 59 | |||
2778 | 60 | :returns: True if ufw is enabled | ||
2779 | 61 | """ | ||
2780 | 62 | output = subprocess.check_output(['ufw', 'status'], | ||
2781 | 63 | universal_newlines=True, | ||
2782 | 64 | env={'LANG': 'en_US', | ||
2783 | 65 | 'PATH': os.environ['PATH']}) | ||
2784 | 66 | |||
2785 | 67 | m = re.findall(r'^Status: active\n', output, re.M) | ||
2786 | 68 | |||
2787 | 69 | return len(m) >= 1 | ||
2788 | 70 | |||
2789 | 71 | |||
2790 | 72 | def is_ipv6_ok(soft_fail=False): | ||
2791 | 73 | """ | ||
2792 | 74 | Check if IPv6 support is present and ip6tables functional | ||
2793 | 75 | |||
2794 | 76 | :param soft_fail: If set to True and IPv6 support is broken, then reports | ||
2795 | 77 | that the host doesn't have IPv6 support, otherwise a | ||
2796 | 78 | UFWIPv6Error exception is raised. | ||
2797 | 79 | :returns: True if IPv6 is working, False otherwise | ||
2798 | 80 | """ | ||
2799 | 81 | |||
2800 | 82 | # do we have IPv6 in the machine? | ||
2801 | 83 | if os.path.isdir('/proc/sys/net/ipv6'): | ||
2802 | 84 | # is ip6tables kernel module loaded? | ||
2803 | 85 | lsmod = subprocess.check_output(['lsmod'], universal_newlines=True) | ||
2804 | 86 | matches = re.findall('^ip6_tables[ ]+', lsmod, re.M) | ||
2805 | 87 | if len(matches) == 0: | ||
2806 | 88 | # ip6tables support isn't complete, let's try to load it | ||
2807 | 89 | try: | ||
2808 | 90 | subprocess.check_output(['modprobe', 'ip6_tables'], | ||
2809 | 91 | universal_newlines=True) | ||
2810 | 92 | # great, we could load the module | ||
2811 | 93 | return True | ||
2812 | 94 | except subprocess.CalledProcessError as ex: | ||
2813 | 95 | hookenv.log("Couldn't load ip6_tables module: %s" % ex.output, | ||
2814 | 96 | level="WARN") | ||
2815 | 97 | # we are in a world where ip6tables isn't working | ||
2816 | 98 | if soft_fail: | ||
2817 | 99 | # so we inform that the machine doesn't have IPv6 | ||
2818 | 100 | return False | ||
2819 | 101 | else: | ||
2820 | 102 | raise UFWIPv6Error("IPv6 firewall support broken") | ||
2821 | 103 | else: | ||
2822 | 104 | # the module is present :) | ||
2823 | 105 | return True | ||
2824 | 106 | |||
2825 | 107 | else: | ||
2826 | 108 | # the system doesn't have IPv6 | ||
2827 | 109 | return False | ||
2828 | 110 | |||
2829 | 111 | |||
2830 | 112 | def disable_ipv6(): | ||
2831 | 113 | """ | ||
2832 | 114 | Disable ufw IPv6 support in /etc/default/ufw | ||
2833 | 115 | """ | ||
2834 | 116 | exit_code = subprocess.call(['sed', '-i', 's/IPV6=.*/IPV6=no/g', | ||
2835 | 117 | '/etc/default/ufw']) | ||
2836 | 118 | if exit_code == 0: | ||
2837 | 119 | hookenv.log('IPv6 support in ufw disabled', level='INFO') | ||
2838 | 120 | else: | ||
2839 | 121 | hookenv.log("Couldn't disable IPv6 support in ufw", level="ERROR") | ||
2840 | 122 | raise UFWError("Couldn't disable IPv6 support in ufw") | ||
2841 | 123 | |||
2842 | 124 | |||
2843 | 125 | def enable(soft_fail=False): | ||
2844 | 126 | """ | ||
2845 | 127 | Enable ufw | ||
2846 | 128 | |||
2847 | 129 | :param soft_fail: If set to True silently disables IPv6 support in ufw, | ||
2848 | 130 | otherwise a UFWIPv6Error exception is raised when IP6 | ||
2849 | 131 | support is broken. | ||
2850 | 132 | :returns: True if ufw is successfully enabled | ||
2851 | 133 | """ | ||
2852 | 134 | if is_enabled(): | ||
2853 | 135 | return True | ||
2854 | 136 | |||
2855 | 137 | if not is_ipv6_ok(soft_fail): | ||
2856 | 138 | disable_ipv6() | ||
2857 | 139 | |||
2858 | 140 | output = subprocess.check_output(['ufw', 'enable'], | ||
2859 | 141 | universal_newlines=True, | ||
2860 | 142 | env={'LANG': 'en_US', | ||
2861 | 143 | 'PATH': os.environ['PATH']}) | ||
2862 | 144 | |||
2863 | 145 | m = re.findall('^Firewall is active and enabled on system startup\n', | ||
2864 | 146 | output, re.M) | ||
2865 | 147 | hookenv.log(output, level='DEBUG') | ||
2866 | 148 | |||
2867 | 149 | if len(m) == 0: | ||
2868 | 150 | hookenv.log("ufw couldn't be enabled", level='WARN') | ||
2869 | 151 | return False | ||
2870 | 152 | else: | ||
2871 | 153 | hookenv.log("ufw enabled", level='INFO') | ||
2872 | 154 | return True | ||
2873 | 155 | |||
2874 | 156 | |||
2875 | 157 | def disable(): | ||
2876 | 158 | """ | ||
2877 | 159 | Disable ufw | ||
2878 | 160 | |||
2879 | 161 | :returns: True if ufw is successfully disabled | ||
2880 | 162 | """ | ||
2881 | 163 | if not is_enabled(): | ||
2882 | 164 | return True | ||
2883 | 165 | |||
2884 | 166 | output = subprocess.check_output(['ufw', 'disable'], | ||
2885 | 167 | universal_newlines=True, | ||
2886 | 168 | env={'LANG': 'en_US', | ||
2887 | 169 | 'PATH': os.environ['PATH']}) | ||
2888 | 170 | |||
2889 | 171 | m = re.findall(r'^Firewall stopped and disabled on system startup\n', | ||
2890 | 172 | output, re.M) | ||
2891 | 173 | hookenv.log(output, level='DEBUG') | ||
2892 | 174 | |||
2893 | 175 | if len(m) == 0: | ||
2894 | 176 | hookenv.log("ufw couldn't be disabled", level='WARN') | ||
2895 | 177 | return False | ||
2896 | 178 | else: | ||
2897 | 179 | hookenv.log("ufw disabled", level='INFO') | ||
2898 | 180 | return True | ||
2899 | 181 | |||
2900 | 182 | |||
2901 | 183 | def modify_access(src, dst='any', port=None, proto=None, action='allow'): | ||
2902 | 184 | """ | ||
2903 | 185 | Grant access to an address or subnet | ||
2904 | 186 | |||
2905 | 187 | :param src: address (e.g. 192.168.1.234) or subnet | ||
2906 | 188 | (e.g. 192.168.1.0/24). | ||
2907 | 189 | :param dst: destiny of the connection, if the machine has multiple IPs and | ||
2908 | 190 | connections to only one of those have to accepted this is the | ||
2909 | 191 | field has to be set. | ||
2910 | 192 | :param port: destiny port | ||
2911 | 193 | :param proto: protocol (tcp or udp) | ||
2912 | 194 | :param action: `allow` or `delete` | ||
2913 | 195 | """ | ||
2914 | 196 | if not is_enabled(): | ||
2915 | 197 | hookenv.log('ufw is disabled, skipping modify_access()', level='WARN') | ||
2916 | 198 | return | ||
2917 | 199 | |||
2918 | 200 | if action == 'delete': | ||
2919 | 201 | cmd = ['ufw', 'delete', 'allow'] | ||
2920 | 202 | else: | ||
2921 | 203 | cmd = ['ufw', action] | ||
2922 | 204 | |||
2923 | 205 | if src is not None: | ||
2924 | 206 | cmd += ['from', src] | ||
2925 | 207 | |||
2926 | 208 | if dst is not None: | ||
2927 | 209 | cmd += ['to', dst] | ||
2928 | 210 | |||
2929 | 211 | if port is not None: | ||
2930 | 212 | cmd += ['port', str(port)] | ||
2931 | 213 | |||
2932 | 214 | if proto is not None: | ||
2933 | 215 | cmd += ['proto', proto] | ||
2934 | 216 | |||
2935 | 217 | hookenv.log('ufw {}: {}'.format(action, ' '.join(cmd)), level='DEBUG') | ||
2936 | 218 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE) | ||
2937 | 219 | (stdout, stderr) = p.communicate() | ||
2938 | 220 | |||
2939 | 221 | hookenv.log(stdout, level='INFO') | ||
2940 | 222 | |||
2941 | 223 | if p.returncode != 0: | ||
2942 | 224 | hookenv.log(stderr, level='ERROR') | ||
2943 | 225 | hookenv.log('Error running: {}, exit code: {}'.format(' '.join(cmd), | ||
2944 | 226 | p.returncode), | ||
2945 | 227 | level='ERROR') | ||
2946 | 228 | |||
2947 | 229 | |||
2948 | 230 | def grant_access(src, dst='any', port=None, proto=None): | ||
2949 | 231 | """ | ||
2950 | 232 | Grant access to an address or subnet | ||
2951 | 233 | |||
2952 | 234 | :param src: address (e.g. 192.168.1.234) or subnet | ||
2953 | 235 | (e.g. 192.168.1.0/24). | ||
2954 | 236 | :param dst: destiny of the connection, if the machine has multiple IPs and | ||
2955 | 237 | connections to only one of those have to accepted this is the | ||
2956 | 238 | field has to be set. | ||
2957 | 239 | :param port: destiny port | ||
2958 | 240 | :param proto: protocol (tcp or udp) | ||
2959 | 241 | """ | ||
2960 | 242 | return modify_access(src, dst=dst, port=port, proto=proto, action='allow') | ||
2961 | 243 | |||
2962 | 244 | |||
2963 | 245 | def revoke_access(src, dst='any', port=None, proto=None): | ||
2964 | 246 | """ | ||
2965 | 247 | Revoke access to an address or subnet | ||
2966 | 248 | |||
2967 | 249 | :param src: address (e.g. 192.168.1.234) or subnet | ||
2968 | 250 | (e.g. 192.168.1.0/24). | ||
2969 | 251 | :param dst: destiny of the connection, if the machine has multiple IPs and | ||
2970 | 252 | connections to only one of those have to accepted this is the | ||
2971 | 253 | field has to be set. | ||
2972 | 254 | :param port: destiny port | ||
2973 | 255 | :param proto: protocol (tcp or udp) | ||
2974 | 256 | """ | ||
2975 | 257 | return modify_access(src, dst=dst, port=port, proto=proto, action='delete') | ||
2976 | 258 | |||
2977 | 259 | |||
2978 | 260 | def service(name, action): | ||
2979 | 261 | """ | ||
2980 | 262 | Open/close access to a service | ||
2981 | 263 | |||
2982 | 264 | :param name: could be a service name defined in `/etc/services` or a port | ||
2983 | 265 | number. | ||
2984 | 266 | :param action: `open` or `close` | ||
2985 | 267 | """ | ||
2986 | 268 | if action == 'open': | ||
2987 | 269 | subprocess.check_output(['ufw', 'allow', str(name)], | ||
2988 | 270 | universal_newlines=True) | ||
2989 | 271 | elif action == 'close': | ||
2990 | 272 | subprocess.check_output(['ufw', 'delete', 'allow', str(name)], | ||
2991 | 273 | universal_newlines=True) | ||
2992 | 274 | else: | ||
2993 | 275 | raise UFWError(("'{}' not supported, use 'allow' " | ||
2994 | 276 | "or 'delete'").format(action)) | ||
2995 | 0 | 277 | ||
2996 | === added directory 'hooks/charmhelpers/contrib/openstack' | |||
2997 | === added file 'hooks/charmhelpers/contrib/openstack/__init__.py' | |||
2998 | --- hooks/charmhelpers/contrib/openstack/__init__.py 1970-01-01 00:00:00 +0000 | |||
2999 | +++ hooks/charmhelpers/contrib/openstack/__init__.py 2015-06-18 17:19:58 +0000 | |||
3000 | @@ -0,0 +1,15 @@ | |||
3001 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3002 | 2 | # | ||
3003 | 3 | # This file is part of charm-helpers. | ||
3004 | 4 | # | ||
3005 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3006 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3007 | 7 | # published by the Free Software Foundation. | ||
3008 | 8 | # | ||
3009 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3010 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3011 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3012 | 12 | # GNU Lesser General Public License for more details. | ||
3013 | 13 | # | ||
3014 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3015 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3016 | 0 | 16 | ||
3017 | === added file 'hooks/charmhelpers/contrib/openstack/alternatives.py' | |||
3018 | --- hooks/charmhelpers/contrib/openstack/alternatives.py 1970-01-01 00:00:00 +0000 | |||
3019 | +++ hooks/charmhelpers/contrib/openstack/alternatives.py 2015-06-18 17:19:58 +0000 | |||
3020 | @@ -0,0 +1,33 @@ | |||
3021 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3022 | 2 | # | ||
3023 | 3 | # This file is part of charm-helpers. | ||
3024 | 4 | # | ||
3025 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3026 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3027 | 7 | # published by the Free Software Foundation. | ||
3028 | 8 | # | ||
3029 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3030 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3031 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3032 | 12 | # GNU Lesser General Public License for more details. | ||
3033 | 13 | # | ||
3034 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3035 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3036 | 16 | |||
3037 | 17 | ''' Helper for managing alternatives for file conflict resolution ''' | ||
3038 | 18 | |||
3039 | 19 | import subprocess | ||
3040 | 20 | import shutil | ||
3041 | 21 | import os | ||
3042 | 22 | |||
3043 | 23 | |||
3044 | 24 | def install_alternative(name, target, source, priority=50): | ||
3045 | 25 | ''' Install alternative configuration ''' | ||
3046 | 26 | if (os.path.exists(target) and not os.path.islink(target)): | ||
3047 | 27 | # Move existing file/directory away before installing | ||
3048 | 28 | shutil.move(target, '{}.bak'.format(target)) | ||
3049 | 29 | cmd = [ | ||
3050 | 30 | 'update-alternatives', '--force', '--install', | ||
3051 | 31 | target, name, source, str(priority) | ||
3052 | 32 | ] | ||
3053 | 33 | subprocess.check_call(cmd) | ||
3054 | 0 | 34 | ||
3055 | === added directory 'hooks/charmhelpers/contrib/openstack/amulet' | |||
3056 | === added file 'hooks/charmhelpers/contrib/openstack/amulet/__init__.py' | |||
3057 | --- hooks/charmhelpers/contrib/openstack/amulet/__init__.py 1970-01-01 00:00:00 +0000 | |||
3058 | +++ hooks/charmhelpers/contrib/openstack/amulet/__init__.py 2015-06-18 17:19:58 +0000 | |||
3059 | @@ -0,0 +1,15 @@ | |||
3060 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3061 | 2 | # | ||
3062 | 3 | # This file is part of charm-helpers. | ||
3063 | 4 | # | ||
3064 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3065 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3066 | 7 | # published by the Free Software Foundation. | ||
3067 | 8 | # | ||
3068 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3069 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3070 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3071 | 12 | # GNU Lesser General Public License for more details. | ||
3072 | 13 | # | ||
3073 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3074 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3075 | 0 | 16 | ||
3076 | === added file 'hooks/charmhelpers/contrib/openstack/amulet/deployment.py' | |||
3077 | --- hooks/charmhelpers/contrib/openstack/amulet/deployment.py 1970-01-01 00:00:00 +0000 | |||
3078 | +++ hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-06-18 17:19:58 +0000 | |||
3079 | @@ -0,0 +1,108 @@ | |||
3080 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3081 | 2 | # | ||
3082 | 3 | # This file is part of charm-helpers. | ||
3083 | 4 | # | ||
3084 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3085 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3086 | 7 | # published by the Free Software Foundation. | ||
3087 | 8 | # | ||
3088 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3089 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3090 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3091 | 12 | # GNU Lesser General Public License for more details. | ||
3092 | 13 | # | ||
3093 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3094 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3095 | 16 | |||
3096 | 17 | import six | ||
3097 | 18 | from charmhelpers.contrib.amulet.deployment import ( | ||
3098 | 19 | AmuletDeployment | ||
3099 | 20 | ) | ||
3100 | 21 | |||
3101 | 22 | |||
3102 | 23 | class OpenStackAmuletDeployment(AmuletDeployment): | ||
3103 | 24 | """OpenStack amulet deployment. | ||
3104 | 25 | |||
3105 | 26 | This class inherits from AmuletDeployment and has additional support | ||
3106 | 27 | that is specifically for use by OpenStack charms. | ||
3107 | 28 | """ | ||
3108 | 29 | |||
3109 | 30 | def __init__(self, series=None, openstack=None, source=None, stable=True): | ||
3110 | 31 | """Initialize the deployment environment.""" | ||
3111 | 32 | super(OpenStackAmuletDeployment, self).__init__(series) | ||
3112 | 33 | self.openstack = openstack | ||
3113 | 34 | self.source = source | ||
3114 | 35 | self.stable = stable | ||
3115 | 36 | # Note(coreycb): this needs to be changed when new next branches come | ||
3116 | 37 | # out. | ||
3117 | 38 | self.current_next = "trusty" | ||
3118 | 39 | |||
3119 | 40 | def _determine_branch_locations(self, other_services): | ||
3120 | 41 | """Determine the branch locations for the other services. | ||
3121 | 42 | |||
3122 | 43 | Determine if the local branch being tested is derived from its | ||
3123 | 44 | stable or next (dev) branch, and based on this, use the corresonding | ||
3124 | 45 | stable or next branches for the other_services.""" | ||
3125 | 46 | base_charms = ['mysql', 'mongodb', 'rabbitmq-server'] | ||
3126 | 47 | |||
3127 | 48 | if self.stable: | ||
3128 | 49 | for svc in other_services: | ||
3129 | 50 | temp = 'lp:charms/{}' | ||
3130 | 51 | svc['location'] = temp.format(svc['name']) | ||
3131 | 52 | else: | ||
3132 | 53 | for svc in other_services: | ||
3133 | 54 | if svc['name'] in base_charms: | ||
3134 | 55 | temp = 'lp:charms/{}' | ||
3135 | 56 | svc['location'] = temp.format(svc['name']) | ||
3136 | 57 | else: | ||
3137 | 58 | temp = 'lp:~openstack-charmers/charms/{}/{}/next' | ||
3138 | 59 | svc['location'] = temp.format(self.current_next, | ||
3139 | 60 | svc['name']) | ||
3140 | 61 | return other_services | ||
3141 | 62 | |||
3142 | 63 | def _add_services(self, this_service, other_services): | ||
3143 | 64 | """Add services to the deployment and set openstack-origin/source.""" | ||
3144 | 65 | other_services = self._determine_branch_locations(other_services) | ||
3145 | 66 | |||
3146 | 67 | super(OpenStackAmuletDeployment, self)._add_services(this_service, | ||
3147 | 68 | other_services) | ||
3148 | 69 | |||
3149 | 70 | services = other_services | ||
3150 | 71 | services.append(this_service) | ||
3151 | 72 | use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph', | ||
3152 | 73 | 'ceph-osd', 'ceph-radosgw'] | ||
3153 | 74 | |||
3154 | 75 | if self.openstack: | ||
3155 | 76 | for svc in services: | ||
3156 | 77 | if svc['name'] not in use_source: | ||
3157 | 78 | config = {'openstack-origin': self.openstack} | ||
3158 | 79 | self.d.configure(svc['name'], config) | ||
3159 | 80 | |||
3160 | 81 | if self.source: | ||
3161 | 82 | for svc in services: | ||
3162 | 83 | if svc['name'] in use_source: | ||
3163 | 84 | config = {'source': self.source} | ||
3164 | 85 | self.d.configure(svc['name'], config) | ||
3165 | 86 | |||
3166 | 87 | def _configure_services(self, configs): | ||
3167 | 88 | """Configure all of the services.""" | ||
3168 | 89 | for service, config in six.iteritems(configs): | ||
3169 | 90 | self.d.configure(service, config) | ||
3170 | 91 | |||
3171 | 92 | def _get_openstack_release(self): | ||
3172 | 93 | """Get openstack release. | ||
3173 | 94 | |||
3174 | 95 | Return an integer representing the enum value of the openstack | ||
3175 | 96 | release. | ||
3176 | 97 | """ | ||
3177 | 98 | (self.precise_essex, self.precise_folsom, self.precise_grizzly, | ||
3178 | 99 | self.precise_havana, self.precise_icehouse, | ||
3179 | 100 | self.trusty_icehouse) = range(6) | ||
3180 | 101 | releases = { | ||
3181 | 102 | ('precise', None): self.precise_essex, | ||
3182 | 103 | ('precise', 'cloud:precise-folsom'): self.precise_folsom, | ||
3183 | 104 | ('precise', 'cloud:precise-grizzly'): self.precise_grizzly, | ||
3184 | 105 | ('precise', 'cloud:precise-havana'): self.precise_havana, | ||
3185 | 106 | ('precise', 'cloud:precise-icehouse'): self.precise_icehouse, | ||
3186 | 107 | ('trusty', None): self.trusty_icehouse} | ||
3187 | 108 | return releases[(self.series, self.openstack)] | ||
3188 | 0 | 109 | ||
3189 | === added file 'hooks/charmhelpers/contrib/openstack/amulet/utils.py' | |||
3190 | --- hooks/charmhelpers/contrib/openstack/amulet/utils.py 1970-01-01 00:00:00 +0000 | |||
3191 | +++ hooks/charmhelpers/contrib/openstack/amulet/utils.py 2015-06-18 17:19:58 +0000 | |||
3192 | @@ -0,0 +1,294 @@ | |||
3193 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3194 | 2 | # | ||
3195 | 3 | # This file is part of charm-helpers. | ||
3196 | 4 | # | ||
3197 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3198 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3199 | 7 | # published by the Free Software Foundation. | ||
3200 | 8 | # | ||
3201 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3202 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3203 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3204 | 12 | # GNU Lesser General Public License for more details. | ||
3205 | 13 | # | ||
3206 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3207 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3208 | 16 | |||
3209 | 17 | import logging | ||
3210 | 18 | import os | ||
3211 | 19 | import time | ||
3212 | 20 | import urllib | ||
3213 | 21 | |||
3214 | 22 | import glanceclient.v1.client as glance_client | ||
3215 | 23 | import keystoneclient.v2_0 as keystone_client | ||
3216 | 24 | import novaclient.v1_1.client as nova_client | ||
3217 | 25 | |||
3218 | 26 | import six | ||
3219 | 27 | |||
3220 | 28 | from charmhelpers.contrib.amulet.utils import ( | ||
3221 | 29 | AmuletUtils | ||
3222 | 30 | ) | ||
3223 | 31 | |||
3224 | 32 | DEBUG = logging.DEBUG | ||
3225 | 33 | ERROR = logging.ERROR | ||
3226 | 34 | |||
3227 | 35 | |||
3228 | 36 | class OpenStackAmuletUtils(AmuletUtils): | ||
3229 | 37 | """OpenStack amulet utilities. | ||
3230 | 38 | |||
3231 | 39 | This class inherits from AmuletUtils and has additional support | ||
3232 | 40 | that is specifically for use by OpenStack charms. | ||
3233 | 41 | """ | ||
3234 | 42 | |||
3235 | 43 | def __init__(self, log_level=ERROR): | ||
3236 | 44 | """Initialize the deployment environment.""" | ||
3237 | 45 | super(OpenStackAmuletUtils, self).__init__(log_level) | ||
3238 | 46 | |||
3239 | 47 | def validate_endpoint_data(self, endpoints, admin_port, internal_port, | ||
3240 | 48 | public_port, expected): | ||
3241 | 49 | """Validate endpoint data. | ||
3242 | 50 | |||
3243 | 51 | Validate actual endpoint data vs expected endpoint data. The ports | ||
3244 | 52 | are used to find the matching endpoint. | ||
3245 | 53 | """ | ||
3246 | 54 | found = False | ||
3247 | 55 | for ep in endpoints: | ||
3248 | 56 | self.log.debug('endpoint: {}'.format(repr(ep))) | ||
3249 | 57 | if (admin_port in ep.adminurl and | ||
3250 | 58 | internal_port in ep.internalurl and | ||
3251 | 59 | public_port in ep.publicurl): | ||
3252 | 60 | found = True | ||
3253 | 61 | actual = {'id': ep.id, | ||
3254 | 62 | 'region': ep.region, | ||
3255 | 63 | 'adminurl': ep.adminurl, | ||
3256 | 64 | 'internalurl': ep.internalurl, | ||
3257 | 65 | 'publicurl': ep.publicurl, | ||
3258 | 66 | 'service_id': ep.service_id} | ||
3259 | 67 | ret = self._validate_dict_data(expected, actual) | ||
3260 | 68 | if ret: | ||
3261 | 69 | return 'unexpected endpoint data - {}'.format(ret) | ||
3262 | 70 | |||
3263 | 71 | if not found: | ||
3264 | 72 | return 'endpoint not found' | ||
3265 | 73 | |||
3266 | 74 | def validate_svc_catalog_endpoint_data(self, expected, actual): | ||
3267 | 75 | """Validate service catalog endpoint data. | ||
3268 | 76 | |||
3269 | 77 | Validate a list of actual service catalog endpoints vs a list of | ||
3270 | 78 | expected service catalog endpoints. | ||
3271 | 79 | """ | ||
3272 | 80 | self.log.debug('actual: {}'.format(repr(actual))) | ||
3273 | 81 | for k, v in six.iteritems(expected): | ||
3274 | 82 | if k in actual: | ||
3275 | 83 | ret = self._validate_dict_data(expected[k][0], actual[k][0]) | ||
3276 | 84 | if ret: | ||
3277 | 85 | return self.endpoint_error(k, ret) | ||
3278 | 86 | else: | ||
3279 | 87 | return "endpoint {} does not exist".format(k) | ||
3280 | 88 | return ret | ||
3281 | 89 | |||
3282 | 90 | def validate_tenant_data(self, expected, actual): | ||
3283 | 91 | """Validate tenant data. | ||
3284 | 92 | |||
3285 | 93 | Validate a list of actual tenant data vs list of expected tenant | ||
3286 | 94 | data. | ||
3287 | 95 | """ | ||
3288 | 96 | self.log.debug('actual: {}'.format(repr(actual))) | ||
3289 | 97 | for e in expected: | ||
3290 | 98 | found = False | ||
3291 | 99 | for act in actual: | ||
3292 | 100 | a = {'enabled': act.enabled, 'description': act.description, | ||
3293 | 101 | 'name': act.name, 'id': act.id} | ||
3294 | 102 | if e['name'] == a['name']: | ||
3295 | 103 | found = True | ||
3296 | 104 | ret = self._validate_dict_data(e, a) | ||
3297 | 105 | if ret: | ||
3298 | 106 | return "unexpected tenant data - {}".format(ret) | ||
3299 | 107 | if not found: | ||
3300 | 108 | return "tenant {} does not exist".format(e['name']) | ||
3301 | 109 | return ret | ||
3302 | 110 | |||
3303 | 111 | def validate_role_data(self, expected, actual): | ||
3304 | 112 | """Validate role data. | ||
3305 | 113 | |||
3306 | 114 | Validate a list of actual role data vs a list of expected role | ||
3307 | 115 | data. | ||
3308 | 116 | """ | ||
3309 | 117 | self.log.debug('actual: {}'.format(repr(actual))) | ||
3310 | 118 | for e in expected: | ||
3311 | 119 | found = False | ||
3312 | 120 | for act in actual: | ||
3313 | 121 | a = {'name': act.name, 'id': act.id} | ||
3314 | 122 | if e['name'] == a['name']: | ||
3315 | 123 | found = True | ||
3316 | 124 | ret = self._validate_dict_data(e, a) | ||
3317 | 125 | if ret: | ||
3318 | 126 | return "unexpected role data - {}".format(ret) | ||
3319 | 127 | if not found: | ||
3320 | 128 | return "role {} does not exist".format(e['name']) | ||
3321 | 129 | return ret | ||
3322 | 130 | |||
3323 | 131 | def validate_user_data(self, expected, actual): | ||
3324 | 132 | """Validate user data. | ||
3325 | 133 | |||
3326 | 134 | Validate a list of actual user data vs a list of expected user | ||
3327 | 135 | data. | ||
3328 | 136 | """ | ||
3329 | 137 | self.log.debug('actual: {}'.format(repr(actual))) | ||
3330 | 138 | for e in expected: | ||
3331 | 139 | found = False | ||
3332 | 140 | for act in actual: | ||
3333 | 141 | a = {'enabled': act.enabled, 'name': act.name, | ||
3334 | 142 | 'email': act.email, 'tenantId': act.tenantId, | ||
3335 | 143 | 'id': act.id} | ||
3336 | 144 | if e['name'] == a['name']: | ||
3337 | 145 | found = True | ||
3338 | 146 | ret = self._validate_dict_data(e, a) | ||
3339 | 147 | if ret: | ||
3340 | 148 | return "unexpected user data - {}".format(ret) | ||
3341 | 149 | if not found: | ||
3342 | 150 | return "user {} does not exist".format(e['name']) | ||
3343 | 151 | return ret | ||
3344 | 152 | |||
3345 | 153 | def validate_flavor_data(self, expected, actual): | ||
3346 | 154 | """Validate flavor data. | ||
3347 | 155 | |||
3348 | 156 | Validate a list of actual flavors vs a list of expected flavors. | ||
3349 | 157 | """ | ||
3350 | 158 | self.log.debug('actual: {}'.format(repr(actual))) | ||
3351 | 159 | act = [a.name for a in actual] | ||
3352 | 160 | return self._validate_list_data(expected, act) | ||
3353 | 161 | |||
3354 | 162 | def tenant_exists(self, keystone, tenant): | ||
3355 | 163 | """Return True if tenant exists.""" | ||
3356 | 164 | return tenant in [t.name for t in keystone.tenants.list()] | ||
3357 | 165 | |||
3358 | 166 | def authenticate_keystone_admin(self, keystone_sentry, user, password, | ||
3359 | 167 | tenant): | ||
3360 | 168 | """Authenticates admin user with the keystone admin endpoint.""" | ||
3361 | 169 | unit = keystone_sentry | ||
3362 | 170 | service_ip = unit.relation('shared-db', | ||
3363 | 171 | 'mysql:shared-db')['private-address'] | ||
3364 | 172 | ep = "http://{}:35357/v2.0".format(service_ip.strip().decode('utf-8')) | ||
3365 | 173 | return keystone_client.Client(username=user, password=password, | ||
3366 | 174 | tenant_name=tenant, auth_url=ep) | ||
3367 | 175 | |||
3368 | 176 | def authenticate_keystone_user(self, keystone, user, password, tenant): | ||
3369 | 177 | """Authenticates a regular user with the keystone public endpoint.""" | ||
3370 | 178 | ep = keystone.service_catalog.url_for(service_type='identity', | ||
3371 | 179 | endpoint_type='publicURL') | ||
3372 | 180 | return keystone_client.Client(username=user, password=password, | ||
3373 | 181 | tenant_name=tenant, auth_url=ep) | ||
3374 | 182 | |||
3375 | 183 | def authenticate_glance_admin(self, keystone): | ||
3376 | 184 | """Authenticates admin user with glance.""" | ||
3377 | 185 | ep = keystone.service_catalog.url_for(service_type='image', | ||
3378 | 186 | endpoint_type='adminURL') | ||
3379 | 187 | return glance_client.Client(ep, token=keystone.auth_token) | ||
3380 | 188 | |||
3381 | 189 | def authenticate_nova_user(self, keystone, user, password, tenant): | ||
3382 | 190 | """Authenticates a regular user with nova-api.""" | ||
3383 | 191 | ep = keystone.service_catalog.url_for(service_type='identity', | ||
3384 | 192 | endpoint_type='publicURL') | ||
3385 | 193 | return nova_client.Client(username=user, api_key=password, | ||
3386 | 194 | project_id=tenant, auth_url=ep) | ||
3387 | 195 | |||
3388 | 196 | def create_cirros_image(self, glance, image_name): | ||
3389 | 197 | """Download the latest cirros image and upload it to glance.""" | ||
3390 | 198 | http_proxy = os.getenv('AMULET_HTTP_PROXY') | ||
3391 | 199 | self.log.debug('AMULET_HTTP_PROXY: {}'.format(http_proxy)) | ||
3392 | 200 | if http_proxy: | ||
3393 | 201 | proxies = {'http': http_proxy} | ||
3394 | 202 | opener = urllib.FancyURLopener(proxies) | ||
3395 | 203 | else: | ||
3396 | 204 | opener = urllib.FancyURLopener() | ||
3397 | 205 | |||
3398 | 206 | f = opener.open("http://download.cirros-cloud.net/version/released") | ||
3399 | 207 | version = f.read().strip() | ||
3400 | 208 | cirros_img = "cirros-{}-x86_64-disk.img".format(version) | ||
3401 | 209 | local_path = os.path.join('tests', cirros_img) | ||
3402 | 210 | |||
3403 | 211 | if not os.path.exists(local_path): | ||
3404 | 212 | cirros_url = "http://{}/{}/{}".format("download.cirros-cloud.net", | ||
3405 | 213 | version, cirros_img) | ||
3406 | 214 | opener.retrieve(cirros_url, local_path) | ||
3407 | 215 | f.close() | ||
3408 | 216 | |||
3409 | 217 | with open(local_path) as f: | ||
3410 | 218 | image = glance.images.create(name=image_name, is_public=True, | ||
3411 | 219 | disk_format='qcow2', | ||
3412 | 220 | container_format='bare', data=f) | ||
3413 | 221 | count = 1 | ||
3414 | 222 | status = image.status | ||
3415 | 223 | while status != 'active' and count < 10: | ||
3416 | 224 | time.sleep(3) | ||
3417 | 225 | image = glance.images.get(image.id) | ||
3418 | 226 | status = image.status | ||
3419 | 227 | self.log.debug('image status: {}'.format(status)) | ||
3420 | 228 | count += 1 | ||
3421 | 229 | |||
3422 | 230 | if status != 'active': | ||
3423 | 231 | self.log.error('image creation timed out') | ||
3424 | 232 | return None | ||
3425 | 233 | |||
3426 | 234 | return image | ||
3427 | 235 | |||
3428 | 236 | def delete_image(self, glance, image): | ||
3429 | 237 | """Delete the specified image.""" | ||
3430 | 238 | num_before = len(list(glance.images.list())) | ||
3431 | 239 | glance.images.delete(image) | ||
3432 | 240 | |||
3433 | 241 | count = 1 | ||
3434 | 242 | num_after = len(list(glance.images.list())) | ||
3435 | 243 | while num_after != (num_before - 1) and count < 10: | ||
3436 | 244 | time.sleep(3) | ||
3437 | 245 | num_after = len(list(glance.images.list())) | ||
3438 | 246 | self.log.debug('number of images: {}'.format(num_after)) | ||
3439 | 247 | count += 1 | ||
3440 | 248 | |||
3441 | 249 | if num_after != (num_before - 1): | ||
3442 | 250 | self.log.error('image deletion timed out') | ||
3443 | 251 | return False | ||
3444 | 252 | |||
3445 | 253 | return True | ||
3446 | 254 | |||
3447 | 255 | def create_instance(self, nova, image_name, instance_name, flavor): | ||
3448 | 256 | """Create the specified instance.""" | ||
3449 | 257 | image = nova.images.find(name=image_name) | ||
3450 | 258 | flavor = nova.flavors.find(name=flavor) | ||
3451 | 259 | instance = nova.servers.create(name=instance_name, image=image, | ||
3452 | 260 | flavor=flavor) | ||
3453 | 261 | |||
3454 | 262 | count = 1 | ||
3455 | 263 | status = instance.status | ||
3456 | 264 | while status != 'ACTIVE' and count < 60: | ||
3457 | 265 | time.sleep(3) | ||
3458 | 266 | instance = nova.servers.get(instance.id) | ||
3459 | 267 | status = instance.status | ||
3460 | 268 | self.log.debug('instance status: {}'.format(status)) | ||
3461 | 269 | count += 1 | ||
3462 | 270 | |||
3463 | 271 | if status != 'ACTIVE': | ||
3464 | 272 | self.log.error('instance creation timed out') | ||
3465 | 273 | return None | ||
3466 | 274 | |||
3467 | 275 | return instance | ||
3468 | 276 | |||
3469 | 277 | def delete_instance(self, nova, instance): | ||
3470 | 278 | """Delete the specified instance.""" | ||
3471 | 279 | num_before = len(list(nova.servers.list())) | ||
3472 | 280 | nova.servers.delete(instance) | ||
3473 | 281 | |||
3474 | 282 | count = 1 | ||
3475 | 283 | num_after = len(list(nova.servers.list())) | ||
3476 | 284 | while num_after != (num_before - 1) and count < 10: | ||
3477 | 285 | time.sleep(3) | ||
3478 | 286 | num_after = len(list(nova.servers.list())) | ||
3479 | 287 | self.log.debug('number of instances: {}'.format(num_after)) | ||
3480 | 288 | count += 1 | ||
3481 | 289 | |||
3482 | 290 | if num_after != (num_before - 1): | ||
3483 | 291 | self.log.error('instance deletion timed out') | ||
3484 | 292 | return False | ||
3485 | 293 | |||
3486 | 294 | return True | ||
3487 | 0 | 295 | ||
3488 | === added file 'hooks/charmhelpers/contrib/openstack/context.py' | |||
3489 | --- hooks/charmhelpers/contrib/openstack/context.py 1970-01-01 00:00:00 +0000 | |||
3490 | +++ hooks/charmhelpers/contrib/openstack/context.py 2015-06-18 17:19:58 +0000 | |||
3491 | @@ -0,0 +1,1054 @@ | |||
3492 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3493 | 2 | # | ||
3494 | 3 | # This file is part of charm-helpers. | ||
3495 | 4 | # | ||
3496 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3497 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3498 | 7 | # published by the Free Software Foundation. | ||
3499 | 8 | # | ||
3500 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3501 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3502 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3503 | 12 | # GNU Lesser General Public License for more details. | ||
3504 | 13 | # | ||
3505 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3506 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3507 | 16 | |||
3508 | 17 | import json | ||
3509 | 18 | import os | ||
3510 | 19 | import time | ||
3511 | 20 | from base64 import b64decode | ||
3512 | 21 | from subprocess import check_call | ||
3513 | 22 | |||
3514 | 23 | import six | ||
3515 | 24 | |||
3516 | 25 | from charmhelpers.fetch import ( | ||
3517 | 26 | apt_install, | ||
3518 | 27 | filter_installed_packages, | ||
3519 | 28 | ) | ||
3520 | 29 | from charmhelpers.core.hookenv import ( | ||
3521 | 30 | config, | ||
3522 | 31 | is_relation_made, | ||
3523 | 32 | local_unit, | ||
3524 | 33 | log, | ||
3525 | 34 | relation_get, | ||
3526 | 35 | relation_ids, | ||
3527 | 36 | related_units, | ||
3528 | 37 | relation_set, | ||
3529 | 38 | unit_get, | ||
3530 | 39 | unit_private_ip, | ||
3531 | 40 | charm_name, | ||
3532 | 41 | DEBUG, | ||
3533 | 42 | INFO, | ||
3534 | 43 | WARNING, | ||
3535 | 44 | ERROR, | ||
3536 | 45 | ) | ||
3537 | 46 | |||
3538 | 47 | from charmhelpers.core.sysctl import create as sysctl_create | ||
3539 | 48 | |||
3540 | 49 | from charmhelpers.core.host import ( | ||
3541 | 50 | mkdir, | ||
3542 | 51 | write_file, | ||
3543 | 52 | ) | ||
3544 | 53 | from charmhelpers.contrib.hahelpers.cluster import ( | ||
3545 | 54 | determine_apache_port, | ||
3546 | 55 | determine_api_port, | ||
3547 | 56 | https, | ||
3548 | 57 | is_clustered, | ||
3549 | 58 | ) | ||
3550 | 59 | from charmhelpers.contrib.hahelpers.apache import ( | ||
3551 | 60 | get_cert, | ||
3552 | 61 | get_ca_cert, | ||
3553 | 62 | install_ca_cert, | ||
3554 | 63 | ) | ||
3555 | 64 | from charmhelpers.contrib.openstack.neutron import ( | ||
3556 | 65 | neutron_plugin_attribute, | ||
3557 | 66 | ) | ||
3558 | 67 | from charmhelpers.contrib.network.ip import ( | ||
3559 | 68 | get_address_in_network, | ||
3560 | 69 | get_ipv6_addr, | ||
3561 | 70 | get_netmask_for_address, | ||
3562 | 71 | format_ipv6_addr, | ||
3563 | 72 | is_address_in_network, | ||
3564 | 73 | ) | ||
3565 | 74 | from charmhelpers.contrib.openstack.utils import get_host_ip | ||
3566 | 75 | |||
3567 | 76 | CA_CERT_PATH = '/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt' | ||
3568 | 77 | ADDRESS_TYPES = ['admin', 'internal', 'public'] | ||
3569 | 78 | |||
3570 | 79 | |||
3571 | 80 | class OSContextError(Exception): | ||
3572 | 81 | pass | ||
3573 | 82 | |||
3574 | 83 | |||
3575 | 84 | def ensure_packages(packages): | ||
3576 | 85 | """Install but do not upgrade required plugin packages.""" | ||
3577 | 86 | required = filter_installed_packages(packages) | ||
3578 | 87 | if required: | ||
3579 | 88 | apt_install(required, fatal=True) | ||
3580 | 89 | |||
3581 | 90 | |||
3582 | 91 | def context_complete(ctxt): | ||
3583 | 92 | _missing = [] | ||
3584 | 93 | for k, v in six.iteritems(ctxt): | ||
3585 | 94 | if v is None or v == '': | ||
3586 | 95 | _missing.append(k) | ||
3587 | 96 | |||
3588 | 97 | if _missing: | ||
3589 | 98 | log('Missing required data: %s' % ' '.join(_missing), level=INFO) | ||
3590 | 99 | return False | ||
3591 | 100 | |||
3592 | 101 | return True | ||
3593 | 102 | |||
3594 | 103 | |||
3595 | 104 | def config_flags_parser(config_flags): | ||
3596 | 105 | """Parses config flags string into dict. | ||
3597 | 106 | |||
3598 | 107 | The provided config_flags string may be a list of comma-separated values | ||
3599 | 108 | which themselves may be comma-separated list of values. | ||
3600 | 109 | """ | ||
3601 | 110 | if config_flags.find('==') >= 0: | ||
3602 | 111 | log("config_flags is not in expected format (key=value)", level=ERROR) | ||
3603 | 112 | raise OSContextError | ||
3604 | 113 | |||
3605 | 114 | # strip the following from each value. | ||
3606 | 115 | post_strippers = ' ,' | ||
3607 | 116 | # we strip any leading/trailing '=' or ' ' from the string then | ||
3608 | 117 | # split on '='. | ||
3609 | 118 | split = config_flags.strip(' =').split('=') | ||
3610 | 119 | limit = len(split) | ||
3611 | 120 | flags = {} | ||
3612 | 121 | for i in range(0, limit - 1): | ||
3613 | 122 | current = split[i] | ||
3614 | 123 | next = split[i + 1] | ||
3615 | 124 | vindex = next.rfind(',') | ||
3616 | 125 | if (i == limit - 2) or (vindex < 0): | ||
3617 | 126 | value = next | ||
3618 | 127 | else: | ||
3619 | 128 | value = next[:vindex] | ||
3620 | 129 | |||
3621 | 130 | if i == 0: | ||
3622 | 131 | key = current | ||
3623 | 132 | else: | ||
3624 | 133 | # if this not the first entry, expect an embedded key. | ||
3625 | 134 | index = current.rfind(',') | ||
3626 | 135 | if index < 0: | ||
3627 | 136 | log("Invalid config value(s) at index %s" % (i), level=ERROR) | ||
3628 | 137 | raise OSContextError | ||
3629 | 138 | key = current[index + 1:] | ||
3630 | 139 | |||
3631 | 140 | # Add to collection. | ||
3632 | 141 | flags[key.strip(post_strippers)] = value.rstrip(post_strippers) | ||
3633 | 142 | |||
3634 | 143 | return flags | ||
3635 | 144 | |||
3636 | 145 | |||
3637 | 146 | class OSContextGenerator(object): | ||
3638 | 147 | """Base class for all context generators.""" | ||
3639 | 148 | interfaces = [] | ||
3640 | 149 | |||
3641 | 150 | def __call__(self): | ||
3642 | 151 | raise NotImplementedError | ||
3643 | 152 | |||
3644 | 153 | |||
3645 | 154 | class SharedDBContext(OSContextGenerator): | ||
3646 | 155 | interfaces = ['shared-db'] | ||
3647 | 156 | |||
3648 | 157 | def __init__(self, | ||
3649 | 158 | database=None, user=None, relation_prefix=None, ssl_dir=None): | ||
3650 | 159 | """Allows inspecting relation for settings prefixed with | ||
3651 | 160 | relation_prefix. This is useful for parsing access for multiple | ||
3652 | 161 | databases returned via the shared-db interface (eg, nova_password, | ||
3653 | 162 | quantum_password) | ||
3654 | 163 | """ | ||
3655 | 164 | self.relation_prefix = relation_prefix | ||
3656 | 165 | self.database = database | ||
3657 | 166 | self.user = user | ||
3658 | 167 | self.ssl_dir = ssl_dir | ||
3659 | 168 | |||
3660 | 169 | def __call__(self): | ||
3661 | 170 | self.database = self.database or config('database') | ||
3662 | 171 | self.user = self.user or config('database-user') | ||
3663 | 172 | if None in [self.database, self.user]: | ||
3664 | 173 | log("Could not generate shared_db context. Missing required charm " | ||
3665 | 174 | "config options. (database name and user)", level=ERROR) | ||
3666 | 175 | raise OSContextError | ||
3667 | 176 | |||
3668 | 177 | ctxt = {} | ||
3669 | 178 | |||
3670 | 179 | # NOTE(jamespage) if mysql charm provides a network upon which | ||
3671 | 180 | # access to the database should be made, reconfigure relation | ||
3672 | 181 | # with the service units local address and defer execution | ||
3673 | 182 | access_network = relation_get('access-network') | ||
3674 | 183 | if access_network is not None: | ||
3675 | 184 | if self.relation_prefix is not None: | ||
3676 | 185 | hostname_key = "{}_hostname".format(self.relation_prefix) | ||
3677 | 186 | else: | ||
3678 | 187 | hostname_key = "hostname" | ||
3679 | 188 | access_hostname = get_address_in_network(access_network, | ||
3680 | 189 | unit_get('private-address')) | ||
3681 | 190 | set_hostname = relation_get(attribute=hostname_key, | ||
3682 | 191 | unit=local_unit()) | ||
3683 | 192 | if set_hostname != access_hostname: | ||
3684 | 193 | relation_set(relation_settings={hostname_key: access_hostname}) | ||
3685 | 194 | return ctxt # Defer any further hook execution for now.... | ||
3686 | 195 | |||
3687 | 196 | password_setting = 'password' | ||
3688 | 197 | if self.relation_prefix: | ||
3689 | 198 | password_setting = self.relation_prefix + '_password' | ||
3690 | 199 | |||
3691 | 200 | for rid in relation_ids('shared-db'): | ||
3692 | 201 | for unit in related_units(rid): | ||
3693 | 202 | rdata = relation_get(rid=rid, unit=unit) | ||
3694 | 203 | host = rdata.get('db_host') | ||
3695 | 204 | host = format_ipv6_addr(host) or host | ||
3696 | 205 | ctxt = { | ||
3697 | 206 | 'database_host': host, | ||
3698 | 207 | 'database': self.database, | ||
3699 | 208 | 'database_user': self.user, | ||
3700 | 209 | 'database_password': rdata.get(password_setting), | ||
3701 | 210 | 'database_type': 'mysql' | ||
3702 | 211 | } | ||
3703 | 212 | if context_complete(ctxt): | ||
3704 | 213 | db_ssl(rdata, ctxt, self.ssl_dir) | ||
3705 | 214 | return ctxt | ||
3706 | 215 | return {} | ||
3707 | 216 | |||
3708 | 217 | |||
3709 | 218 | class PostgresqlDBContext(OSContextGenerator): | ||
3710 | 219 | interfaces = ['pgsql-db'] | ||
3711 | 220 | |||
3712 | 221 | def __init__(self, database=None): | ||
3713 | 222 | self.database = database | ||
3714 | 223 | |||
3715 | 224 | def __call__(self): | ||
3716 | 225 | self.database = self.database or config('database') | ||
3717 | 226 | if self.database is None: | ||
3718 | 227 | log('Could not generate postgresql_db context. Missing required ' | ||
3719 | 228 | 'charm config options. (database name)', level=ERROR) | ||
3720 | 229 | raise OSContextError | ||
3721 | 230 | |||
3722 | 231 | ctxt = {} | ||
3723 | 232 | for rid in relation_ids(self.interfaces[0]): | ||
3724 | 233 | for unit in related_units(rid): | ||
3725 | 234 | rel_host = relation_get('host', rid=rid, unit=unit) | ||
3726 | 235 | rel_user = relation_get('user', rid=rid, unit=unit) | ||
3727 | 236 | rel_passwd = relation_get('password', rid=rid, unit=unit) | ||
3728 | 237 | ctxt = {'database_host': rel_host, | ||
3729 | 238 | 'database': self.database, | ||
3730 | 239 | 'database_user': rel_user, | ||
3731 | 240 | 'database_password': rel_passwd, | ||
3732 | 241 | 'database_type': 'postgresql'} | ||
3733 | 242 | if context_complete(ctxt): | ||
3734 | 243 | return ctxt | ||
3735 | 244 | |||
3736 | 245 | return {} | ||
3737 | 246 | |||
3738 | 247 | |||
3739 | 248 | def db_ssl(rdata, ctxt, ssl_dir): | ||
3740 | 249 | if 'ssl_ca' in rdata and ssl_dir: | ||
3741 | 250 | ca_path = os.path.join(ssl_dir, 'db-client.ca') | ||
3742 | 251 | with open(ca_path, 'w') as fh: | ||
3743 | 252 | fh.write(b64decode(rdata['ssl_ca'])) | ||
3744 | 253 | |||
3745 | 254 | ctxt['database_ssl_ca'] = ca_path | ||
3746 | 255 | elif 'ssl_ca' in rdata: | ||
3747 | 256 | log("Charm not setup for ssl support but ssl ca found", level=INFO) | ||
3748 | 257 | return ctxt | ||
3749 | 258 | |||
3750 | 259 | if 'ssl_cert' in rdata: | ||
3751 | 260 | cert_path = os.path.join( | ||
3752 | 261 | ssl_dir, 'db-client.cert') | ||
3753 | 262 | if not os.path.exists(cert_path): | ||
3754 | 263 | log("Waiting 1m for ssl client cert validity", level=INFO) | ||
3755 | 264 | time.sleep(60) | ||
3756 | 265 | |||
3757 | 266 | with open(cert_path, 'w') as fh: | ||
3758 | 267 | fh.write(b64decode(rdata['ssl_cert'])) | ||
3759 | 268 | |||
3760 | 269 | ctxt['database_ssl_cert'] = cert_path | ||
3761 | 270 | key_path = os.path.join(ssl_dir, 'db-client.key') | ||
3762 | 271 | with open(key_path, 'w') as fh: | ||
3763 | 272 | fh.write(b64decode(rdata['ssl_key'])) | ||
3764 | 273 | |||
3765 | 274 | ctxt['database_ssl_key'] = key_path | ||
3766 | 275 | |||
3767 | 276 | return ctxt | ||
3768 | 277 | |||
3769 | 278 | |||
3770 | 279 | class IdentityServiceContext(OSContextGenerator): | ||
3771 | 280 | interfaces = ['identity-service'] | ||
3772 | 281 | |||
3773 | 282 | def __call__(self): | ||
3774 | 283 | log('Generating template context for identity-service', level=DEBUG) | ||
3775 | 284 | ctxt = {} | ||
3776 | 285 | for rid in relation_ids('identity-service'): | ||
3777 | 286 | for unit in related_units(rid): | ||
3778 | 287 | rdata = relation_get(rid=rid, unit=unit) | ||
3779 | 288 | serv_host = rdata.get('service_host') | ||
3780 | 289 | serv_host = format_ipv6_addr(serv_host) or serv_host | ||
3781 | 290 | auth_host = rdata.get('auth_host') | ||
3782 | 291 | auth_host = format_ipv6_addr(auth_host) or auth_host | ||
3783 | 292 | svc_protocol = rdata.get('service_protocol') or 'http' | ||
3784 | 293 | auth_protocol = rdata.get('auth_protocol') or 'http' | ||
3785 | 294 | ctxt = {'service_port': rdata.get('service_port'), | ||
3786 | 295 | 'service_host': serv_host, | ||
3787 | 296 | 'auth_host': auth_host, | ||
3788 | 297 | 'auth_port': rdata.get('auth_port'), | ||
3789 | 298 | 'admin_tenant_name': rdata.get('service_tenant'), | ||
3790 | 299 | 'admin_user': rdata.get('service_username'), | ||
3791 | 300 | 'admin_password': rdata.get('service_password'), | ||
3792 | 301 | 'service_protocol': svc_protocol, | ||
3793 | 302 | 'auth_protocol': auth_protocol} | ||
3794 | 303 | if context_complete(ctxt): | ||
3795 | 304 | # NOTE(jamespage) this is required for >= icehouse | ||
3796 | 305 | # so a missing value just indicates keystone needs | ||
3797 | 306 | # upgrading | ||
3798 | 307 | ctxt['admin_tenant_id'] = rdata.get('service_tenant_id') | ||
3799 | 308 | return ctxt | ||
3800 | 309 | |||
3801 | 310 | return {} | ||
3802 | 311 | |||
3803 | 312 | |||
3804 | 313 | class AMQPContext(OSContextGenerator): | ||
3805 | 314 | |||
3806 | 315 | def __init__(self, ssl_dir=None, rel_name='amqp', relation_prefix=None): | ||
3807 | 316 | self.ssl_dir = ssl_dir | ||
3808 | 317 | self.rel_name = rel_name | ||
3809 | 318 | self.relation_prefix = relation_prefix | ||
3810 | 319 | self.interfaces = [rel_name] | ||
3811 | 320 | |||
3812 | 321 | def __call__(self): | ||
3813 | 322 | log('Generating template context for amqp', level=DEBUG) | ||
3814 | 323 | conf = config() | ||
3815 | 324 | if self.relation_prefix: | ||
3816 | 325 | user_setting = '%s-rabbit-user' % (self.relation_prefix) | ||
3817 | 326 | vhost_setting = '%s-rabbit-vhost' % (self.relation_prefix) | ||
3818 | 327 | else: | ||
3819 | 328 | user_setting = 'rabbit-user' | ||
3820 | 329 | vhost_setting = 'rabbit-vhost' | ||
3821 | 330 | |||
3822 | 331 | try: | ||
3823 | 332 | username = conf[user_setting] | ||
3824 | 333 | vhost = conf[vhost_setting] | ||
3825 | 334 | except KeyError as e: | ||
3826 | 335 | log('Could not generate shared_db context. Missing required charm ' | ||
3827 | 336 | 'config options: %s.' % e, level=ERROR) | ||
3828 | 337 | raise OSContextError | ||
3829 | 338 | |||
3830 | 339 | ctxt = {} | ||
3831 | 340 | for rid in relation_ids(self.rel_name): | ||
3832 | 341 | ha_vip_only = False | ||
3833 | 342 | for unit in related_units(rid): | ||
3834 | 343 | if relation_get('clustered', rid=rid, unit=unit): | ||
3835 | 344 | ctxt['clustered'] = True | ||
3836 | 345 | vip = relation_get('vip', rid=rid, unit=unit) | ||
3837 | 346 | vip = format_ipv6_addr(vip) or vip | ||
3838 | 347 | ctxt['rabbitmq_host'] = vip | ||
3839 | 348 | else: | ||
3840 | 349 | host = relation_get('private-address', rid=rid, unit=unit) | ||
3841 | 350 | host = format_ipv6_addr(host) or host | ||
3842 | 351 | ctxt['rabbitmq_host'] = host | ||
3843 | 352 | |||
3844 | 353 | ctxt.update({ | ||
3845 | 354 | 'rabbitmq_user': username, | ||
3846 | 355 | 'rabbitmq_password': relation_get('password', rid=rid, | ||
3847 | 356 | unit=unit), | ||
3848 | 357 | 'rabbitmq_virtual_host': vhost, | ||
3849 | 358 | }) | ||
3850 | 359 | |||
3851 | 360 | ssl_port = relation_get('ssl_port', rid=rid, unit=unit) | ||
3852 | 361 | if ssl_port: | ||
3853 | 362 | ctxt['rabbit_ssl_port'] = ssl_port | ||
3854 | 363 | |||
3855 | 364 | ssl_ca = relation_get('ssl_ca', rid=rid, unit=unit) | ||
3856 | 365 | if ssl_ca: | ||
3857 | 366 | ctxt['rabbit_ssl_ca'] = ssl_ca | ||
3858 | 367 | |||
3859 | 368 | if relation_get('ha_queues', rid=rid, unit=unit) is not None: | ||
3860 | 369 | ctxt['rabbitmq_ha_queues'] = True | ||
3861 | 370 | |||
3862 | 371 | ha_vip_only = relation_get('ha-vip-only', | ||
3863 | 372 | rid=rid, unit=unit) is not None | ||
3864 | 373 | |||
3865 | 374 | if context_complete(ctxt): | ||
3866 | 375 | if 'rabbit_ssl_ca' in ctxt: | ||
3867 | 376 | if not self.ssl_dir: | ||
3868 | 377 | log("Charm not setup for ssl support but ssl ca " | ||
3869 | 378 | "found", level=INFO) | ||
3870 | 379 | break | ||
3871 | 380 | |||
3872 | 381 | ca_path = os.path.join( | ||
3873 | 382 | self.ssl_dir, 'rabbit-client-ca.pem') | ||
3874 | 383 | with open(ca_path, 'w') as fh: | ||
3875 | 384 | fh.write(b64decode(ctxt['rabbit_ssl_ca'])) | ||
3876 | 385 | ctxt['rabbit_ssl_ca'] = ca_path | ||
3877 | 386 | |||
3878 | 387 | # Sufficient information found = break out! | ||
3879 | 388 | break | ||
3880 | 389 | |||
3881 | 390 | # Used for active/active rabbitmq >= grizzly | ||
3882 | 391 | if (('clustered' not in ctxt or ha_vip_only) and | ||
3883 | 392 | len(related_units(rid)) > 1): | ||
3884 | 393 | rabbitmq_hosts = [] | ||
3885 | 394 | for unit in related_units(rid): | ||
3886 | 395 | host = relation_get('private-address', rid=rid, unit=unit) | ||
3887 | 396 | host = format_ipv6_addr(host) or host | ||
3888 | 397 | rabbitmq_hosts.append(host) | ||
3889 | 398 | |||
3890 | 399 | ctxt['rabbitmq_hosts'] = ','.join(sorted(rabbitmq_hosts)) | ||
3891 | 400 | |||
3892 | 401 | if not context_complete(ctxt): | ||
3893 | 402 | return {} | ||
3894 | 403 | |||
3895 | 404 | return ctxt | ||
3896 | 405 | |||
3897 | 406 | |||
3898 | 407 | class CephContext(OSContextGenerator): | ||
3899 | 408 | """Generates context for /etc/ceph/ceph.conf templates.""" | ||
3900 | 409 | interfaces = ['ceph'] | ||
3901 | 410 | |||
3902 | 411 | def __call__(self): | ||
3903 | 412 | if not relation_ids('ceph'): | ||
3904 | 413 | return {} | ||
3905 | 414 | |||
3906 | 415 | log('Generating template context for ceph', level=DEBUG) | ||
3907 | 416 | mon_hosts = [] | ||
3908 | 417 | auth = None | ||
3909 | 418 | key = None | ||
3910 | 419 | use_syslog = str(config('use-syslog')).lower() | ||
3911 | 420 | for rid in relation_ids('ceph'): | ||
3912 | 421 | for unit in related_units(rid): | ||
3913 | 422 | auth = relation_get('auth', rid=rid, unit=unit) | ||
3914 | 423 | key = relation_get('key', rid=rid, unit=unit) | ||
3915 | 424 | ceph_pub_addr = relation_get('ceph-public-address', rid=rid, | ||
3916 | 425 | unit=unit) | ||
3917 | 426 | unit_priv_addr = relation_get('private-address', rid=rid, | ||
3918 | 427 | unit=unit) | ||
3919 | 428 | ceph_addr = ceph_pub_addr or unit_priv_addr | ||
3920 | 429 | ceph_addr = format_ipv6_addr(ceph_addr) or ceph_addr | ||
3921 | 430 | mon_hosts.append(ceph_addr) | ||
3922 | 431 | |||
3923 | 432 | ctxt = {'mon_hosts': ' '.join(sorted(mon_hosts)), | ||
3924 | 433 | 'auth': auth, | ||
3925 | 434 | 'key': key, | ||
3926 | 435 | 'use_syslog': use_syslog} | ||
3927 | 436 | |||
3928 | 437 | if not os.path.isdir('/etc/ceph'): | ||
3929 | 438 | os.mkdir('/etc/ceph') | ||
3930 | 439 | |||
3931 | 440 | if not context_complete(ctxt): | ||
3932 | 441 | return {} | ||
3933 | 442 | |||
3934 | 443 | ensure_packages(['ceph-common']) | ||
3935 | 444 | return ctxt | ||
3936 | 445 | |||
3937 | 446 | |||
3938 | 447 | class HAProxyContext(OSContextGenerator): | ||
3939 | 448 | """Provides half a context for the haproxy template, which describes | ||
3940 | 449 | all peers to be included in the cluster. Each charm needs to include | ||
3941 | 450 | its own context generator that describes the port mapping. | ||
3942 | 451 | """ | ||
3943 | 452 | interfaces = ['cluster'] | ||
3944 | 453 | |||
3945 | 454 | def __init__(self, singlenode_mode=False): | ||
3946 | 455 | self.singlenode_mode = singlenode_mode | ||
3947 | 456 | |||
3948 | 457 | def __call__(self): | ||
3949 | 458 | if not relation_ids('cluster') and not self.singlenode_mode: | ||
3950 | 459 | return {} | ||
3951 | 460 | |||
3952 | 461 | if config('prefer-ipv6'): | ||
3953 | 462 | addr = get_ipv6_addr(exc_list=[config('vip')])[0] | ||
3954 | 463 | else: | ||
3955 | 464 | addr = get_host_ip(unit_get('private-address')) | ||
3956 | 465 | |||
3957 | 466 | l_unit = local_unit().replace('/', '-') | ||
3958 | 467 | cluster_hosts = {} | ||
3959 | 468 | |||
3960 | 469 | # NOTE(jamespage): build out map of configured network endpoints | ||
3961 | 470 | # and associated backends | ||
3962 | 471 | for addr_type in ADDRESS_TYPES: | ||
3963 | 472 | cfg_opt = 'os-{}-network'.format(addr_type) | ||
3964 | 473 | laddr = get_address_in_network(config(cfg_opt)) | ||
3965 | 474 | if laddr: | ||
3966 | 475 | netmask = get_netmask_for_address(laddr) | ||
3967 | 476 | cluster_hosts[laddr] = {'network': "{}/{}".format(laddr, | ||
3968 | 477 | netmask), | ||
3969 | 478 | 'backends': {l_unit: laddr}} | ||
3970 | 479 | for rid in relation_ids('cluster'): | ||
3971 | 480 | for unit in related_units(rid): | ||
3972 | 481 | _laddr = relation_get('{}-address'.format(addr_type), | ||
3973 | 482 | rid=rid, unit=unit) | ||
3974 | 483 | if _laddr: | ||
3975 | 484 | _unit = unit.replace('/', '-') | ||
3976 | 485 | cluster_hosts[laddr]['backends'][_unit] = _laddr | ||
3977 | 486 | |||
3978 | 487 | # NOTE(jamespage) add backend based on private address - this | ||
3979 | 488 | # with either be the only backend or the fallback if no acls | ||
3980 | 489 | # match in the frontend | ||
3981 | 490 | cluster_hosts[addr] = {} | ||
3982 | 491 | netmask = get_netmask_for_address(addr) | ||
3983 | 492 | cluster_hosts[addr] = {'network': "{}/{}".format(addr, netmask), | ||
3984 | 493 | 'backends': {l_unit: addr}} | ||
3985 | 494 | for rid in relation_ids('cluster'): | ||
3986 | 495 | for unit in related_units(rid): | ||
3987 | 496 | _laddr = relation_get('private-address', | ||
3988 | 497 | rid=rid, unit=unit) | ||
3989 | 498 | if _laddr: | ||
3990 | 499 | _unit = unit.replace('/', '-') | ||
3991 | 500 | cluster_hosts[addr]['backends'][_unit] = _laddr | ||
3992 | 501 | |||
3993 | 502 | ctxt = { | ||
3994 | 503 | 'frontends': cluster_hosts, | ||
3995 | 504 | 'default_backend': addr | ||
3996 | 505 | } | ||
3997 | 506 | |||
3998 | 507 | if config('haproxy-server-timeout'): | ||
3999 | 508 | ctxt['haproxy_server_timeout'] = config('haproxy-server-timeout') | ||
4000 | 509 | |||
4001 | 510 | if config('haproxy-client-timeout'): | ||
4002 | 511 | ctxt['haproxy_client_timeout'] = config('haproxy-client-timeout') | ||
4003 | 512 | |||
4004 | 513 | if config('prefer-ipv6'): | ||
4005 | 514 | ctxt['ipv6'] = True | ||
4006 | 515 | ctxt['local_host'] = 'ip6-localhost' | ||
4007 | 516 | ctxt['haproxy_host'] = '::' | ||
4008 | 517 | ctxt['stat_port'] = ':::8888' | ||
4009 | 518 | else: | ||
4010 | 519 | ctxt['local_host'] = '127.0.0.1' | ||
4011 | 520 | ctxt['haproxy_host'] = '0.0.0.0' | ||
4012 | 521 | ctxt['stat_port'] = ':8888' | ||
4013 | 522 | |||
4014 | 523 | for frontend in cluster_hosts: | ||
4015 | 524 | if (len(cluster_hosts[frontend]['backends']) > 1 or | ||
4016 | 525 | self.singlenode_mode): | ||
4017 | 526 | # Enable haproxy when we have enough peers. | ||
4018 | 527 | log('Ensuring haproxy enabled in /etc/default/haproxy.', | ||
4019 | 528 | level=DEBUG) | ||
4020 | 529 | with open('/etc/default/haproxy', 'w') as out: | ||
4021 | 530 | out.write('ENABLED=1\n') | ||
4022 | 531 | |||
4023 | 532 | return ctxt | ||
4024 | 533 | |||
4025 | 534 | log('HAProxy context is incomplete, this unit has no peers.', | ||
4026 | 535 | level=INFO) | ||
4027 | 536 | return {} | ||
4028 | 537 | |||
4029 | 538 | |||
4030 | 539 | class ImageServiceContext(OSContextGenerator): | ||
4031 | 540 | interfaces = ['image-service'] | ||
4032 | 541 | |||
4033 | 542 | def __call__(self): | ||
4034 | 543 | """Obtains the glance API server from the image-service relation. | ||
4035 | 544 | Useful in nova and cinder (currently). | ||
4036 | 545 | """ | ||
4037 | 546 | log('Generating template context for image-service.', level=DEBUG) | ||
4038 | 547 | rids = relation_ids('image-service') | ||
4039 | 548 | if not rids: | ||
4040 | 549 | return {} | ||
4041 | 550 | |||
4042 | 551 | for rid in rids: | ||
4043 | 552 | for unit in related_units(rid): | ||
4044 | 553 | api_server = relation_get('glance-api-server', | ||
4045 | 554 | rid=rid, unit=unit) | ||
4046 | 555 | if api_server: | ||
4047 | 556 | return {'glance_api_servers': api_server} | ||
4048 | 557 | |||
4049 | 558 | log("ImageService context is incomplete. Missing required relation " | ||
4050 | 559 | "data.", level=INFO) | ||
4051 | 560 | return {} | ||
4052 | 561 | |||
4053 | 562 | |||
4054 | 563 | class ApacheSSLContext(OSContextGenerator): | ||
4055 | 564 | """Generates a context for an apache vhost configuration that configures | ||
4056 | 565 | HTTPS reverse proxying for one or many endpoints. Generated context | ||
4057 | 566 | looks something like:: | ||
4058 | 567 | |||
4059 | 568 | { | ||
4060 | 569 | 'namespace': 'cinder', | ||
4061 | 570 | 'private_address': 'iscsi.mycinderhost.com', | ||
4062 | 571 | 'endpoints': [(8776, 8766), (8777, 8767)] | ||
4063 | 572 | } | ||
4064 | 573 | |||
4065 | 574 | The endpoints list consists of a tuples mapping external ports | ||
4066 | 575 | to internal ports. | ||
4067 | 576 | """ | ||
4068 | 577 | interfaces = ['https'] | ||
4069 | 578 | |||
4070 | 579 | # charms should inherit this context and set external ports | ||
4071 | 580 | # and service namespace accordingly. | ||
4072 | 581 | external_ports = [] | ||
4073 | 582 | service_namespace = None | ||
4074 | 583 | |||
4075 | 584 | def enable_modules(self): | ||
4076 | 585 | cmd = ['a2enmod', 'ssl', 'proxy', 'proxy_http'] | ||
4077 | 586 | check_call(cmd) | ||
4078 | 587 | |||
4079 | 588 | def configure_cert(self, cn=None): | ||
4080 | 589 | ssl_dir = os.path.join('/etc/apache2/ssl/', self.service_namespace) | ||
4081 | 590 | mkdir(path=ssl_dir) | ||
4082 | 591 | cert, key = get_cert(cn) | ||
4083 | 592 | if cn: | ||
4084 | 593 | cert_filename = 'cert_{}'.format(cn) | ||
4085 | 594 | key_filename = 'key_{}'.format(cn) | ||
4086 | 595 | else: | ||
4087 | 596 | cert_filename = 'cert' | ||
4088 | 597 | key_filename = 'key' | ||
4089 | 598 | |||
4090 | 599 | write_file(path=os.path.join(ssl_dir, cert_filename), | ||
4091 | 600 | content=b64decode(cert)) | ||
4092 | 601 | write_file(path=os.path.join(ssl_dir, key_filename), | ||
4093 | 602 | content=b64decode(key)) | ||
4094 | 603 | |||
4095 | 604 | def configure_ca(self): | ||
4096 | 605 | ca_cert = get_ca_cert() | ||
4097 | 606 | if ca_cert: | ||
4098 | 607 | install_ca_cert(b64decode(ca_cert)) | ||
4099 | 608 | |||
4100 | 609 | def canonical_names(self): | ||
4101 | 610 | """Figure out which canonical names clients will access this service. | ||
4102 | 611 | """ | ||
4103 | 612 | cns = [] | ||
4104 | 613 | for r_id in relation_ids('identity-service'): | ||
4105 | 614 | for unit in related_units(r_id): | ||
4106 | 615 | rdata = relation_get(rid=r_id, unit=unit) | ||
4107 | 616 | for k in rdata: | ||
4108 | 617 | if k.startswith('ssl_key_'): | ||
4109 | 618 | cns.append(k.lstrip('ssl_key_')) | ||
4110 | 619 | |||
4111 | 620 | return sorted(list(set(cns))) | ||
4112 | 621 | |||
4113 | 622 | def get_network_addresses(self): | ||
4114 | 623 | """For each network configured, return corresponding address and vip | ||
4115 | 624 | (if available). | ||
4116 | 625 | |||
4117 | 626 | Returns a list of tuples of the form: | ||
4118 | 627 | |||
4119 | 628 | [(address_in_net_a, vip_in_net_a), | ||
4120 | 629 | (address_in_net_b, vip_in_net_b), | ||
4121 | 630 | ...] | ||
4122 | 631 | |||
4123 | 632 | or, if no vip(s) available: | ||
4124 | 633 | |||
4125 | 634 | [(address_in_net_a, address_in_net_a), | ||
4126 | 635 | (address_in_net_b, address_in_net_b), | ||
4127 | 636 | ...] | ||
4128 | 637 | """ | ||
4129 | 638 | addresses = [] | ||
4130 | 639 | if config('vip'): | ||
4131 | 640 | vips = config('vip').split() | ||
4132 | 641 | else: | ||
4133 | 642 | vips = [] | ||
4134 | 643 | |||
4135 | 644 | for net_type in ['os-internal-network', 'os-admin-network', | ||
4136 | 645 | 'os-public-network']: | ||
4137 | 646 | addr = get_address_in_network(config(net_type), | ||
4138 | 647 | unit_get('private-address')) | ||
4139 | 648 | if len(vips) > 1 and is_clustered(): | ||
4140 | 649 | if not config(net_type): | ||
4141 | 650 | log("Multiple networks configured but net_type " | ||
4142 | 651 | "is None (%s)." % net_type, level=WARNING) | ||
4143 | 652 | continue | ||
4144 | 653 | |||
4145 | 654 | for vip in vips: | ||
4146 | 655 | if is_address_in_network(config(net_type), vip): | ||
4147 | 656 | addresses.append((addr, vip)) | ||
4148 | 657 | break | ||
4149 | 658 | |||
4150 | 659 | elif is_clustered() and config('vip'): | ||
4151 | 660 | addresses.append((addr, config('vip'))) | ||
4152 | 661 | else: | ||
4153 | 662 | addresses.append((addr, addr)) | ||
4154 | 663 | |||
4155 | 664 | return sorted(addresses) | ||
4156 | 665 | |||
4157 | 666 | def __call__(self): | ||
4158 | 667 | if isinstance(self.external_ports, six.string_types): | ||
4159 | 668 | self.external_ports = [self.external_ports] | ||
4160 | 669 | |||
4161 | 670 | if not self.external_ports or not https(): | ||
4162 | 671 | return {} | ||
4163 | 672 | |||
4164 | 673 | self.configure_ca() | ||
4165 | 674 | self.enable_modules() | ||
4166 | 675 | |||
4167 | 676 | ctxt = {'namespace': self.service_namespace, | ||
4168 | 677 | 'endpoints': [], | ||
4169 | 678 | 'ext_ports': []} | ||
4170 | 679 | |||
4171 | 680 | for cn in self.canonical_names(): | ||
4172 | 681 | self.configure_cert(cn) | ||
4173 | 682 | |||
4174 | 683 | addresses = self.get_network_addresses() | ||
4175 | 684 | for address, endpoint in sorted(set(addresses)): | ||
4176 | 685 | for api_port in self.external_ports: | ||
4177 | 686 | ext_port = determine_apache_port(api_port, | ||
4178 | 687 | singlenode_mode=True) | ||
4179 | 688 | int_port = determine_api_port(api_port, singlenode_mode=True) | ||
4180 | 689 | portmap = (address, endpoint, int(ext_port), int(int_port)) | ||
4181 | 690 | ctxt['endpoints'].append(portmap) | ||
4182 | 691 | ctxt['ext_ports'].append(int(ext_port)) | ||
4183 | 692 | |||
4184 | 693 | ctxt['ext_ports'] = sorted(list(set(ctxt['ext_ports']))) | ||
4185 | 694 | return ctxt | ||
4186 | 695 | |||
4187 | 696 | |||
4188 | 697 | class NeutronContext(OSContextGenerator): | ||
4189 | 698 | interfaces = [] | ||
4190 | 699 | |||
4191 | 700 | @property | ||
4192 | 701 | def plugin(self): | ||
4193 | 702 | return None | ||
4194 | 703 | |||
4195 | 704 | @property | ||
4196 | 705 | def network_manager(self): | ||
4197 | 706 | return None | ||
4198 | 707 | |||
4199 | 708 | @property | ||
4200 | 709 | def packages(self): | ||
4201 | 710 | return neutron_plugin_attribute(self.plugin, 'packages', | ||
4202 | 711 | self.network_manager) | ||
4203 | 712 | |||
4204 | 713 | @property | ||
4205 | 714 | def neutron_security_groups(self): | ||
4206 | 715 | return None | ||
4207 | 716 | |||
4208 | 717 | def _ensure_packages(self): | ||
4209 | 718 | for pkgs in self.packages: | ||
4210 | 719 | ensure_packages(pkgs) | ||
4211 | 720 | |||
4212 | 721 | def _save_flag_file(self): | ||
4213 | 722 | if self.network_manager == 'quantum': | ||
4214 | 723 | _file = '/etc/nova/quantum_plugin.conf' | ||
4215 | 724 | else: | ||
4216 | 725 | _file = '/etc/nova/neutron_plugin.conf' | ||
4217 | 726 | |||
4218 | 727 | with open(_file, 'wb') as out: | ||
4219 | 728 | out.write(self.plugin + '\n') | ||
4220 | 729 | |||
4221 | 730 | def ovs_ctxt(self): | ||
4222 | 731 | driver = neutron_plugin_attribute(self.plugin, 'driver', | ||
4223 | 732 | self.network_manager) | ||
4224 | 733 | config = neutron_plugin_attribute(self.plugin, 'config', | ||
4225 | 734 | self.network_manager) | ||
4226 | 735 | ovs_ctxt = {'core_plugin': driver, | ||
4227 | 736 | 'neutron_plugin': 'ovs', | ||
4228 | 737 | 'neutron_security_groups': self.neutron_security_groups, | ||
4229 | 738 | 'local_ip': unit_private_ip(), | ||
4230 | 739 | 'config': config} | ||
4231 | 740 | |||
4232 | 741 | return ovs_ctxt | ||
4233 | 742 | |||
4234 | 743 | def nvp_ctxt(self): | ||
4235 | 744 | driver = neutron_plugin_attribute(self.plugin, 'driver', | ||
4236 | 745 | self.network_manager) | ||
4237 | 746 | config = neutron_plugin_attribute(self.plugin, 'config', | ||
4238 | 747 | self.network_manager) | ||
4239 | 748 | nvp_ctxt = {'core_plugin': driver, | ||
4240 | 749 | 'neutron_plugin': 'nvp', | ||
4241 | 750 | 'neutron_security_groups': self.neutron_security_groups, | ||
4242 | 751 | 'local_ip': unit_private_ip(), | ||
4243 | 752 | 'config': config} | ||
4244 | 753 | |||
4245 | 754 | return nvp_ctxt | ||
4246 | 755 | |||
4247 | 756 | def n1kv_ctxt(self): | ||
4248 | 757 | driver = neutron_plugin_attribute(self.plugin, 'driver', | ||
4249 | 758 | self.network_manager) | ||
4250 | 759 | n1kv_config = neutron_plugin_attribute(self.plugin, 'config', | ||
4251 | 760 | self.network_manager) | ||
4252 | 761 | n1kv_user_config_flags = config('n1kv-config-flags') | ||
4253 | 762 | restrict_policy_profiles = config('n1kv-restrict-policy-profiles') | ||
4254 | 763 | n1kv_ctxt = {'core_plugin': driver, | ||
4255 | 764 | 'neutron_plugin': 'n1kv', | ||
4256 | 765 | 'neutron_security_groups': self.neutron_security_groups, | ||
4257 | 766 | 'local_ip': unit_private_ip(), | ||
4258 | 767 | 'config': n1kv_config, | ||
4259 | 768 | 'vsm_ip': config('n1kv-vsm-ip'), | ||
4260 | 769 | 'vsm_username': config('n1kv-vsm-username'), | ||
4261 | 770 | 'vsm_password': config('n1kv-vsm-password'), | ||
4262 | 771 | 'restrict_policy_profiles': restrict_policy_profiles} | ||
4263 | 772 | |||
4264 | 773 | if n1kv_user_config_flags: | ||
4265 | 774 | flags = config_flags_parser(n1kv_user_config_flags) | ||
4266 | 775 | n1kv_ctxt['user_config_flags'] = flags | ||
4267 | 776 | |||
4268 | 777 | return n1kv_ctxt | ||
4269 | 778 | |||
4270 | 779 | def calico_ctxt(self): | ||
4271 | 780 | driver = neutron_plugin_attribute(self.plugin, 'driver', | ||
4272 | 781 | self.network_manager) | ||
4273 | 782 | config = neutron_plugin_attribute(self.plugin, 'config', | ||
4274 | 783 | self.network_manager) | ||
4275 | 784 | calico_ctxt = {'core_plugin': driver, | ||
4276 | 785 | 'neutron_plugin': 'Calico', | ||
4277 | 786 | 'neutron_security_groups': self.neutron_security_groups, | ||
4278 | 787 | 'local_ip': unit_private_ip(), | ||
4279 | 788 | 'config': config} | ||
4280 | 789 | |||
4281 | 790 | return calico_ctxt | ||
4282 | 791 | |||
4283 | 792 | def neutron_ctxt(self): | ||
4284 | 793 | if https(): | ||
4285 | 794 | proto = 'https' | ||
4286 | 795 | else: | ||
4287 | 796 | proto = 'http' | ||
4288 | 797 | |||
4289 | 798 | if is_clustered(): | ||
4290 | 799 | host = config('vip') | ||
4291 | 800 | else: | ||
4292 | 801 | host = unit_get('private-address') | ||
4293 | 802 | |||
4294 | 803 | ctxt = {'network_manager': self.network_manager, | ||
4295 | 804 | 'neutron_url': '%s://%s:%s' % (proto, host, '9696')} | ||
4296 | 805 | return ctxt | ||
4297 | 806 | |||
4298 | 807 | def __call__(self): | ||
4299 | 808 | self._ensure_packages() | ||
4300 | 809 | |||
4301 | 810 | if self.network_manager not in ['quantum', 'neutron']: | ||
4302 | 811 | return {} | ||
4303 | 812 | |||
4304 | 813 | if not self.plugin: | ||
4305 | 814 | return {} | ||
4306 | 815 | |||
4307 | 816 | ctxt = self.neutron_ctxt() | ||
4308 | 817 | |||
4309 | 818 | if self.plugin == 'ovs': | ||
4310 | 819 | ctxt.update(self.ovs_ctxt()) | ||
4311 | 820 | elif self.plugin in ['nvp', 'nsx']: | ||
4312 | 821 | ctxt.update(self.nvp_ctxt()) | ||
4313 | 822 | elif self.plugin == 'n1kv': | ||
4314 | 823 | ctxt.update(self.n1kv_ctxt()) | ||
4315 | 824 | elif self.plugin == 'Calico': | ||
4316 | 825 | ctxt.update(self.calico_ctxt()) | ||
4317 | 826 | |||
4318 | 827 | alchemy_flags = config('neutron-alchemy-flags') | ||
4319 | 828 | if alchemy_flags: | ||
4320 | 829 | flags = config_flags_parser(alchemy_flags) | ||
4321 | 830 | ctxt['neutron_alchemy_flags'] = flags | ||
4322 | 831 | |||
4323 | 832 | self._save_flag_file() | ||
4324 | 833 | return ctxt | ||
4325 | 834 | |||
4326 | 835 | |||
4327 | 836 | class OSConfigFlagContext(OSContextGenerator): | ||
4328 | 837 | """Provides support for user-defined config flags. | ||
4329 | 838 | |||
4330 | 839 | Users can define a comma-seperated list of key=value pairs | ||
4331 | 840 | in the charm configuration and apply them at any point in | ||
4332 | 841 | any file by using a template flag. | ||
4333 | 842 | |||
4334 | 843 | Sometimes users might want config flags inserted within a | ||
4335 | 844 | specific section so this class allows users to specify the | ||
4336 | 845 | template flag name, allowing for multiple template flags | ||
4337 | 846 | (sections) within the same context. | ||
4338 | 847 | |||
4339 | 848 | NOTE: the value of config-flags may be a comma-separated list of | ||
4340 | 849 | key=value pairs and some Openstack config files support | ||
4341 | 850 | comma-separated lists as values. | ||
4342 | 851 | """ | ||
4343 | 852 | |||
4344 | 853 | def __init__(self, charm_flag='config-flags', | ||
4345 | 854 | template_flag='user_config_flags'): | ||
4346 | 855 | """ | ||
4347 | 856 | :param charm_flag: config flags in charm configuration. | ||
4348 | 857 | :param template_flag: insert point for user-defined flags in template | ||
4349 | 858 | file. | ||
4350 | 859 | """ | ||
4351 | 860 | super(OSConfigFlagContext, self).__init__() | ||
4352 | 861 | self._charm_flag = charm_flag | ||
4353 | 862 | self._template_flag = template_flag | ||
4354 | 863 | |||
4355 | 864 | def __call__(self): | ||
4356 | 865 | config_flags = config(self._charm_flag) | ||
4357 | 866 | if not config_flags: | ||
4358 | 867 | return {} | ||
4359 | 868 | |||
4360 | 869 | return {self._template_flag: | ||
4361 | 870 | config_flags_parser(config_flags)} | ||
4362 | 871 | |||
4363 | 872 | |||
4364 | 873 | class SubordinateConfigContext(OSContextGenerator): | ||
4365 | 874 | |||
4366 | 875 | """ | ||
4367 | 876 | Responsible for inspecting relations to subordinates that | ||
4368 | 877 | may be exporting required config via a json blob. | ||
4369 | 878 | |||
4370 | 879 | The subordinate interface allows subordinates to export their | ||
4371 | 880 | configuration requirements to the principle for multiple config | ||
4372 | 881 | files and multiple serivces. Ie, a subordinate that has interfaces | ||
4373 | 882 | to both glance and nova may export to following yaml blob as json:: | ||
4374 | 883 | |||
4375 | 884 | glance: | ||
4376 | 885 | /etc/glance/glance-api.conf: | ||
4377 | 886 | sections: | ||
4378 | 887 | DEFAULT: | ||
4379 | 888 | - [key1, value1] | ||
4380 | 889 | /etc/glance/glance-registry.conf: | ||
4381 | 890 | MYSECTION: | ||
4382 | 891 | - [key2, value2] | ||
4383 | 892 | nova: | ||
4384 | 893 | /etc/nova/nova.conf: | ||
4385 | 894 | sections: | ||
4386 | 895 | DEFAULT: | ||
4387 | 896 | - [key3, value3] | ||
4388 | 897 | |||
4389 | 898 | |||
4390 | 899 | It is then up to the principle charms to subscribe this context to | ||
4391 | 900 | the service+config file it is interestd in. Configuration data will | ||
4392 | 901 | be available in the template context, in glance's case, as:: | ||
4393 | 902 | |||
4394 | 903 | ctxt = { | ||
4395 | 904 | ... other context ... | ||
4396 | 905 | 'subordinate_config': { | ||
4397 | 906 | 'DEFAULT': { | ||
4398 | 907 | 'key1': 'value1', | ||
4399 | 908 | }, | ||
4400 | 909 | 'MYSECTION': { | ||
4401 | 910 | 'key2': 'value2', | ||
4402 | 911 | }, | ||
4403 | 912 | } | ||
4404 | 913 | } | ||
4405 | 914 | """ | ||
4406 | 915 | |||
4407 | 916 | def __init__(self, service, config_file, interface): | ||
4408 | 917 | """ | ||
4409 | 918 | :param service : Service name key to query in any subordinate | ||
4410 | 919 | data found | ||
4411 | 920 | :param config_file : Service's config file to query sections | ||
4412 | 921 | :param interface : Subordinate interface to inspect | ||
4413 | 922 | """ | ||
4414 | 923 | self.service = service | ||
4415 | 924 | self.config_file = config_file | ||
4416 | 925 | self.interface = interface | ||
4417 | 926 | |||
4418 | 927 | def __call__(self): | ||
4419 | 928 | ctxt = {'sections': {}} | ||
4420 | 929 | for rid in relation_ids(self.interface): | ||
4421 | 930 | for unit in related_units(rid): | ||
4422 | 931 | sub_config = relation_get('subordinate_configuration', | ||
4423 | 932 | rid=rid, unit=unit) | ||
4424 | 933 | if sub_config and sub_config != '': | ||
4425 | 934 | try: | ||
4426 | 935 | sub_config = json.loads(sub_config) | ||
4427 | 936 | except: | ||
4428 | 937 | log('Could not parse JSON from subordinate_config ' | ||
4429 | 938 | 'setting from %s' % rid, level=ERROR) | ||
4430 | 939 | continue | ||
4431 | 940 | |||
4432 | 941 | if self.service not in sub_config: | ||
4433 | 942 | log('Found subordinate_config on %s but it contained' | ||
4434 | 943 | 'nothing for %s service' % (rid, self.service), | ||
4435 | 944 | level=INFO) | ||
4436 | 945 | continue | ||
4437 | 946 | |||
4438 | 947 | sub_config = sub_config[self.service] | ||
4439 | 948 | if self.config_file not in sub_config: | ||
4440 | 949 | log('Found subordinate_config on %s but it contained' | ||
4441 | 950 | 'nothing for %s' % (rid, self.config_file), | ||
4442 | 951 | level=INFO) | ||
4443 | 952 | continue | ||
4444 | 953 | |||
4445 | 954 | sub_config = sub_config[self.config_file] | ||
4446 | 955 | for k, v in six.iteritems(sub_config): | ||
4447 | 956 | if k == 'sections': | ||
4448 | 957 | for section, config_dict in six.iteritems(v): | ||
4449 | 958 | log("adding section '%s'" % (section), | ||
4450 | 959 | level=DEBUG) | ||
4451 | 960 | ctxt[k][section] = config_dict | ||
4452 | 961 | else: | ||
4453 | 962 | ctxt[k] = v | ||
4454 | 963 | |||
4455 | 964 | log("%d section(s) found" % (len(ctxt['sections'])), level=DEBUG) | ||
4456 | 965 | return ctxt | ||
4457 | 966 | |||
4458 | 967 | |||
4459 | 968 | class LogLevelContext(OSContextGenerator): | ||
4460 | 969 | |||
4461 | 970 | def __call__(self): | ||
4462 | 971 | ctxt = {} | ||
4463 | 972 | ctxt['debug'] = \ | ||
4464 | 973 | False if config('debug') is None else config('debug') | ||
4465 | 974 | ctxt['verbose'] = \ | ||
4466 | 975 | False if config('verbose') is None else config('verbose') | ||
4467 | 976 | |||
4468 | 977 | return ctxt | ||
4469 | 978 | |||
4470 | 979 | |||
4471 | 980 | class SyslogContext(OSContextGenerator): | ||
4472 | 981 | |||
4473 | 982 | def __call__(self): | ||
4474 | 983 | ctxt = {'use_syslog': config('use-syslog')} | ||
4475 | 984 | return ctxt | ||
4476 | 985 | |||
4477 | 986 | |||
4478 | 987 | class BindHostContext(OSContextGenerator): | ||
4479 | 988 | |||
4480 | 989 | def __call__(self): | ||
4481 | 990 | if config('prefer-ipv6'): | ||
4482 | 991 | return {'bind_host': '::'} | ||
4483 | 992 | else: | ||
4484 | 993 | return {'bind_host': '0.0.0.0'} | ||
4485 | 994 | |||
4486 | 995 | |||
4487 | 996 | class WorkerConfigContext(OSContextGenerator): | ||
4488 | 997 | |||
4489 | 998 | @property | ||
4490 | 999 | def num_cpus(self): | ||
4491 | 1000 | try: | ||
4492 | 1001 | from psutil import NUM_CPUS | ||
4493 | 1002 | except ImportError: | ||
4494 | 1003 | apt_install('python-psutil', fatal=True) | ||
4495 | 1004 | from psutil import NUM_CPUS | ||
4496 | 1005 | |||
4497 | 1006 | return NUM_CPUS | ||
4498 | 1007 | |||
4499 | 1008 | def __call__(self): | ||
4500 | 1009 | multiplier = config('worker-multiplier') or 0 | ||
4501 | 1010 | ctxt = {"workers": self.num_cpus * multiplier} | ||
4502 | 1011 | return ctxt | ||
4503 | 1012 | |||
4504 | 1013 | |||
4505 | 1014 | class ZeroMQContext(OSContextGenerator): | ||
4506 | 1015 | interfaces = ['zeromq-configuration'] | ||
4507 | 1016 | |||
4508 | 1017 | def __call__(self): | ||
4509 | 1018 | ctxt = {} | ||
4510 | 1019 | if is_relation_made('zeromq-configuration', 'host'): | ||
4511 | 1020 | for rid in relation_ids('zeromq-configuration'): | ||
4512 | 1021 | for unit in related_units(rid): | ||
4513 | 1022 | ctxt['zmq_nonce'] = relation_get('nonce', unit, rid) | ||
4514 | 1023 | ctxt['zmq_host'] = relation_get('host', unit, rid) | ||
4515 | 1024 | |||
4516 | 1025 | return ctxt | ||
4517 | 1026 | |||
4518 | 1027 | |||
4519 | 1028 | class NotificationDriverContext(OSContextGenerator): | ||
4520 | 1029 | |||
4521 | 1030 | def __init__(self, zmq_relation='zeromq-configuration', | ||
4522 | 1031 | amqp_relation='amqp'): | ||
4523 | 1032 | """ | ||
4524 | 1033 | :param zmq_relation: Name of Zeromq relation to check | ||
4525 | 1034 | """ | ||
4526 | 1035 | self.zmq_relation = zmq_relation | ||
4527 | 1036 | self.amqp_relation = amqp_relation | ||
4528 | 1037 | |||
4529 | 1038 | def __call__(self): | ||
4530 | 1039 | ctxt = {'notifications': 'False'} | ||
4531 | 1040 | if is_relation_made(self.amqp_relation): | ||
4532 | 1041 | ctxt['notifications'] = "True" | ||
4533 | 1042 | |||
4534 | 1043 | return ctxt | ||
4535 | 1044 | |||
4536 | 1045 | |||
4537 | 1046 | class SysctlContext(OSContextGenerator): | ||
4538 | 1047 | """This context check if the 'sysctl' option exists on configuration | ||
4539 | 1048 | then creates a file with the loaded contents""" | ||
4540 | 1049 | def __call__(self): | ||
4541 | 1050 | sysctl_dict = config('sysctl') | ||
4542 | 1051 | if sysctl_dict: | ||
4543 | 1052 | sysctl_create(sysctl_dict, | ||
4544 | 1053 | '/etc/sysctl.d/50-{0}.conf'.format(charm_name())) | ||
4545 | 1054 | return {'sysctl': sysctl_dict} | ||
4546 | 0 | 1055 | ||
4547 | === added file 'hooks/charmhelpers/contrib/openstack/ip.py' | |||
4548 | --- hooks/charmhelpers/contrib/openstack/ip.py 1970-01-01 00:00:00 +0000 | |||
4549 | +++ hooks/charmhelpers/contrib/openstack/ip.py 2015-06-18 17:19:58 +0000 | |||
4550 | @@ -0,0 +1,109 @@ | |||
4551 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4552 | 2 | # | ||
4553 | 3 | # This file is part of charm-helpers. | ||
4554 | 4 | # | ||
4555 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
4556 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
4557 | 7 | # published by the Free Software Foundation. | ||
4558 | 8 | # | ||
4559 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
4560 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
4561 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
4562 | 12 | # GNU Lesser General Public License for more details. | ||
4563 | 13 | # | ||
4564 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
4565 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
4566 | 16 | |||
4567 | 17 | from charmhelpers.core.hookenv import ( | ||
4568 | 18 | config, | ||
4569 | 19 | unit_get, | ||
4570 | 20 | ) | ||
4571 | 21 | from charmhelpers.contrib.network.ip import ( | ||
4572 | 22 | get_address_in_network, | ||
4573 | 23 | is_address_in_network, | ||
4574 | 24 | is_ipv6, | ||
4575 | 25 | get_ipv6_addr, | ||
4576 | 26 | ) | ||
4577 | 27 | from charmhelpers.contrib.hahelpers.cluster import is_clustered | ||
4578 | 28 | |||
4579 | 29 | PUBLIC = 'public' | ||
4580 | 30 | INTERNAL = 'int' | ||
4581 | 31 | ADMIN = 'admin' | ||
4582 | 32 | |||
4583 | 33 | ADDRESS_MAP = { | ||
4584 | 34 | PUBLIC: { | ||
4585 | 35 | 'config': 'os-public-network', | ||
4586 | 36 | 'fallback': 'public-address' | ||
4587 | 37 | }, | ||
4588 | 38 | INTERNAL: { | ||
4589 | 39 | 'config': 'os-internal-network', | ||
4590 | 40 | 'fallback': 'private-address' | ||
4591 | 41 | }, | ||
4592 | 42 | ADMIN: { | ||
4593 | 43 | 'config': 'os-admin-network', | ||
4594 | 44 | 'fallback': 'private-address' | ||
4595 | 45 | } | ||
4596 | 46 | } | ||
4597 | 47 | |||
4598 | 48 | |||
4599 | 49 | def canonical_url(configs, endpoint_type=PUBLIC): | ||
4600 | 50 | """Returns the correct HTTP URL to this host given the state of HTTPS | ||
4601 | 51 | configuration, hacluster and charm configuration. | ||
4602 | 52 | |||
4603 | 53 | :param configs: OSTemplateRenderer config templating object to inspect | ||
4604 | 54 | for a complete https context. | ||
4605 | 55 | :param endpoint_type: str endpoint type to resolve. | ||
4606 | 56 | :param returns: str base URL for services on the current service unit. | ||
4607 | 57 | """ | ||
4608 | 58 | scheme = 'http' | ||
4609 | 59 | if 'https' in configs.complete_contexts(): | ||
4610 | 60 | scheme = 'https' | ||
4611 | 61 | address = resolve_address(endpoint_type) | ||
4612 | 62 | if is_ipv6(address): | ||
4613 | 63 | address = "[{}]".format(address) | ||
4614 | 64 | return '%s://%s' % (scheme, address) | ||
4615 | 65 | |||
4616 | 66 | |||
4617 | 67 | def resolve_address(endpoint_type=PUBLIC): | ||
4618 | 68 | """Return unit address depending on net config. | ||
4619 | 69 | |||
4620 | 70 | If unit is clustered with vip(s) and has net splits defined, return vip on | ||
4621 | 71 | correct network. If clustered with no nets defined, return primary vip. | ||
4622 | 72 | |||
4623 | 73 | If not clustered, return unit address ensuring address is on configured net | ||
4624 | 74 | split if one is configured. | ||
4625 | 75 | |||
4626 | 76 | :param endpoint_type: Network endpoing type | ||
4627 | 77 | """ | ||
4628 | 78 | resolved_address = None | ||
4629 | 79 | vips = config('vip') | ||
4630 | 80 | if vips: | ||
4631 | 81 | vips = vips.split() | ||
4632 | 82 | |||
4633 | 83 | net_type = ADDRESS_MAP[endpoint_type]['config'] | ||
4634 | 84 | net_addr = config(net_type) | ||
4635 | 85 | net_fallback = ADDRESS_MAP[endpoint_type]['fallback'] | ||
4636 | 86 | clustered = is_clustered() | ||
4637 | 87 | if clustered: | ||
4638 | 88 | if not net_addr: | ||
4639 | 89 | # If no net-splits defined, we expect a single vip | ||
4640 | 90 | resolved_address = vips[0] | ||
4641 | 91 | else: | ||
4642 | 92 | for vip in vips: | ||
4643 | 93 | if is_address_in_network(net_addr, vip): | ||
4644 | 94 | resolved_address = vip | ||
4645 | 95 | break | ||
4646 | 96 | else: | ||
4647 | 97 | if config('prefer-ipv6'): | ||
4648 | 98 | fallback_addr = get_ipv6_addr(exc_list=vips)[0] | ||
4649 | 99 | else: | ||
4650 | 100 | fallback_addr = unit_get(net_fallback) | ||
4651 | 101 | |||
4652 | 102 | resolved_address = get_address_in_network(net_addr, fallback_addr) | ||
4653 | 103 | |||
4654 | 104 | if resolved_address is None: | ||
4655 | 105 | raise ValueError("Unable to resolve a suitable IP address based on " | ||
4656 | 106 | "charm state and configuration. (net_type=%s, " | ||
4657 | 107 | "clustered=%s)" % (net_type, clustered)) | ||
4658 | 108 | |||
4659 | 109 | return resolved_address | ||
4660 | 0 | 110 | ||
4661 | === added file 'hooks/charmhelpers/contrib/openstack/neutron.py' | |||
4662 | --- hooks/charmhelpers/contrib/openstack/neutron.py 1970-01-01 00:00:00 +0000 | |||
4663 | +++ hooks/charmhelpers/contrib/openstack/neutron.py 2015-06-18 17:19:58 +0000 | |||
4664 | @@ -0,0 +1,239 @@ | |||
4665 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4666 | 2 | # | ||
4667 | 3 | # This file is part of charm-helpers. | ||
4668 | 4 | # | ||
4669 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
4670 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
4671 | 7 | # published by the Free Software Foundation. | ||
4672 | 8 | # | ||
4673 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
4674 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
4675 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
4676 | 12 | # GNU Lesser General Public License for more details. | ||
4677 | 13 | # | ||
4678 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
4679 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
4680 | 16 | |||
4681 | 17 | # Various utilies for dealing with Neutron and the renaming from Quantum. | ||
4682 | 18 | |||
4683 | 19 | from subprocess import check_output | ||
4684 | 20 | |||
4685 | 21 | from charmhelpers.core.hookenv import ( | ||
4686 | 22 | config, | ||
4687 | 23 | log, | ||
4688 | 24 | ERROR, | ||
4689 | 25 | ) | ||
4690 | 26 | |||
4691 | 27 | from charmhelpers.contrib.openstack.utils import os_release | ||
4692 | 28 | |||
4693 | 29 | |||
4694 | 30 | def headers_package(): | ||
4695 | 31 | """Ensures correct linux-headers for running kernel are installed, | ||
4696 | 32 | for building DKMS package""" | ||
4697 | 33 | kver = check_output(['uname', '-r']).decode('UTF-8').strip() | ||
4698 | 34 | return 'linux-headers-%s' % kver | ||
4699 | 35 | |||
4700 | 36 | QUANTUM_CONF_DIR = '/etc/quantum' | ||
4701 | 37 | |||
4702 | 38 | |||
4703 | 39 | def kernel_version(): | ||
4704 | 40 | """ Retrieve the current major kernel version as a tuple e.g. (3, 13) """ | ||
4705 | 41 | kver = check_output(['uname', '-r']).decode('UTF-8').strip() | ||
4706 | 42 | kver = kver.split('.') | ||
4707 | 43 | return (int(kver[0]), int(kver[1])) | ||
4708 | 44 | |||
4709 | 45 | |||
4710 | 46 | def determine_dkms_package(): | ||
4711 | 47 | """ Determine which DKMS package should be used based on kernel version """ | ||
4712 | 48 | # NOTE: 3.13 kernels have support for GRE and VXLAN native | ||
4713 | 49 | if kernel_version() >= (3, 13): | ||
4714 | 50 | return [] | ||
4715 | 51 | else: | ||
4716 | 52 | return ['openvswitch-datapath-dkms'] | ||
4717 | 53 | |||
4718 | 54 | |||
4719 | 55 | # legacy | ||
4720 | 56 | |||
4721 | 57 | |||
4722 | 58 | def quantum_plugins(): | ||
4723 | 59 | from charmhelpers.contrib.openstack import context | ||
4724 | 60 | return { | ||
4725 | 61 | 'ovs': { | ||
4726 | 62 | 'config': '/etc/quantum/plugins/openvswitch/' | ||
4727 | 63 | 'ovs_quantum_plugin.ini', | ||
4728 | 64 | 'driver': 'quantum.plugins.openvswitch.ovs_quantum_plugin.' | ||
4729 | 65 | 'OVSQuantumPluginV2', | ||
4730 | 66 | 'contexts': [ | ||
4731 | 67 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4732 | 68 | database=config('neutron-database'), | ||
4733 | 69 | relation_prefix='neutron', | ||
4734 | 70 | ssl_dir=QUANTUM_CONF_DIR)], | ||
4735 | 71 | 'services': ['quantum-plugin-openvswitch-agent'], | ||
4736 | 72 | 'packages': [[headers_package()] + determine_dkms_package(), | ||
4737 | 73 | ['quantum-plugin-openvswitch-agent']], | ||
4738 | 74 | 'server_packages': ['quantum-server', | ||
4739 | 75 | 'quantum-plugin-openvswitch'], | ||
4740 | 76 | 'server_services': ['quantum-server'] | ||
4741 | 77 | }, | ||
4742 | 78 | 'nvp': { | ||
4743 | 79 | 'config': '/etc/quantum/plugins/nicira/nvp.ini', | ||
4744 | 80 | 'driver': 'quantum.plugins.nicira.nicira_nvp_plugin.' | ||
4745 | 81 | 'QuantumPlugin.NvpPluginV2', | ||
4746 | 82 | 'contexts': [ | ||
4747 | 83 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4748 | 84 | database=config('neutron-database'), | ||
4749 | 85 | relation_prefix='neutron', | ||
4750 | 86 | ssl_dir=QUANTUM_CONF_DIR)], | ||
4751 | 87 | 'services': [], | ||
4752 | 88 | 'packages': [], | ||
4753 | 89 | 'server_packages': ['quantum-server', | ||
4754 | 90 | 'quantum-plugin-nicira'], | ||
4755 | 91 | 'server_services': ['quantum-server'] | ||
4756 | 92 | } | ||
4757 | 93 | } | ||
4758 | 94 | |||
4759 | 95 | NEUTRON_CONF_DIR = '/etc/neutron' | ||
4760 | 96 | |||
4761 | 97 | |||
4762 | 98 | def neutron_plugins(): | ||
4763 | 99 | from charmhelpers.contrib.openstack import context | ||
4764 | 100 | release = os_release('nova-common') | ||
4765 | 101 | plugins = { | ||
4766 | 102 | 'ovs': { | ||
4767 | 103 | 'config': '/etc/neutron/plugins/openvswitch/' | ||
4768 | 104 | 'ovs_neutron_plugin.ini', | ||
4769 | 105 | 'driver': 'neutron.plugins.openvswitch.ovs_neutron_plugin.' | ||
4770 | 106 | 'OVSNeutronPluginV2', | ||
4771 | 107 | 'contexts': [ | ||
4772 | 108 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4773 | 109 | database=config('neutron-database'), | ||
4774 | 110 | relation_prefix='neutron', | ||
4775 | 111 | ssl_dir=NEUTRON_CONF_DIR)], | ||
4776 | 112 | 'services': ['neutron-plugin-openvswitch-agent'], | ||
4777 | 113 | 'packages': [[headers_package()] + determine_dkms_package(), | ||
4778 | 114 | ['neutron-plugin-openvswitch-agent']], | ||
4779 | 115 | 'server_packages': ['neutron-server', | ||
4780 | 116 | 'neutron-plugin-openvswitch'], | ||
4781 | 117 | 'server_services': ['neutron-server'] | ||
4782 | 118 | }, | ||
4783 | 119 | 'nvp': { | ||
4784 | 120 | 'config': '/etc/neutron/plugins/nicira/nvp.ini', | ||
4785 | 121 | 'driver': 'neutron.plugins.nicira.nicira_nvp_plugin.' | ||
4786 | 122 | 'NeutronPlugin.NvpPluginV2', | ||
4787 | 123 | 'contexts': [ | ||
4788 | 124 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4789 | 125 | database=config('neutron-database'), | ||
4790 | 126 | relation_prefix='neutron', | ||
4791 | 127 | ssl_dir=NEUTRON_CONF_DIR)], | ||
4792 | 128 | 'services': [], | ||
4793 | 129 | 'packages': [], | ||
4794 | 130 | 'server_packages': ['neutron-server', | ||
4795 | 131 | 'neutron-plugin-nicira'], | ||
4796 | 132 | 'server_services': ['neutron-server'] | ||
4797 | 133 | }, | ||
4798 | 134 | 'nsx': { | ||
4799 | 135 | 'config': '/etc/neutron/plugins/vmware/nsx.ini', | ||
4800 | 136 | 'driver': 'vmware', | ||
4801 | 137 | 'contexts': [ | ||
4802 | 138 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4803 | 139 | database=config('neutron-database'), | ||
4804 | 140 | relation_prefix='neutron', | ||
4805 | 141 | ssl_dir=NEUTRON_CONF_DIR)], | ||
4806 | 142 | 'services': [], | ||
4807 | 143 | 'packages': [], | ||
4808 | 144 | 'server_packages': ['neutron-server', | ||
4809 | 145 | 'neutron-plugin-vmware'], | ||
4810 | 146 | 'server_services': ['neutron-server'] | ||
4811 | 147 | }, | ||
4812 | 148 | 'n1kv': { | ||
4813 | 149 | 'config': '/etc/neutron/plugins/cisco/cisco_plugins.ini', | ||
4814 | 150 | 'driver': 'neutron.plugins.cisco.network_plugin.PluginV2', | ||
4815 | 151 | 'contexts': [ | ||
4816 | 152 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4817 | 153 | database=config('neutron-database'), | ||
4818 | 154 | relation_prefix='neutron', | ||
4819 | 155 | ssl_dir=NEUTRON_CONF_DIR)], | ||
4820 | 156 | 'services': [], | ||
4821 | 157 | 'packages': [[headers_package()] + determine_dkms_package(), | ||
4822 | 158 | ['neutron-plugin-cisco']], | ||
4823 | 159 | 'server_packages': ['neutron-server', | ||
4824 | 160 | 'neutron-plugin-cisco'], | ||
4825 | 161 | 'server_services': ['neutron-server'] | ||
4826 | 162 | }, | ||
4827 | 163 | 'Calico': { | ||
4828 | 164 | 'config': '/etc/neutron/plugins/ml2/ml2_conf.ini', | ||
4829 | 165 | 'driver': 'neutron.plugins.ml2.plugin.Ml2Plugin', | ||
4830 | 166 | 'contexts': [ | ||
4831 | 167 | context.SharedDBContext(user=config('neutron-database-user'), | ||
4832 | 168 | database=config('neutron-database'), | ||
4833 | 169 | relation_prefix='neutron', | ||
4834 | 170 | ssl_dir=NEUTRON_CONF_DIR)], | ||
4835 | 171 | 'services': ['calico-felix', | ||
4836 | 172 | 'bird', | ||
4837 | 173 | 'neutron-dhcp-agent', | ||
4838 | 174 | 'nova-api-metadata'], | ||
4839 | 175 | 'packages': [[headers_package()] + determine_dkms_package(), | ||
4840 | 176 | ['calico-compute', | ||
4841 | 177 | 'bird', | ||
4842 | 178 | 'neutron-dhcp-agent', | ||
4843 | 179 | 'nova-api-metadata']], | ||
4844 | 180 | 'server_packages': ['neutron-server', 'calico-control'], | ||
4845 | 181 | 'server_services': ['neutron-server'] | ||
4846 | 182 | } | ||
4847 | 183 | } | ||
4848 | 184 | if release >= 'icehouse': | ||
4849 | 185 | # NOTE: patch in ml2 plugin for icehouse onwards | ||
4850 | 186 | plugins['ovs']['config'] = '/etc/neutron/plugins/ml2/ml2_conf.ini' | ||
4851 | 187 | plugins['ovs']['driver'] = 'neutron.plugins.ml2.plugin.Ml2Plugin' | ||
4852 | 188 | plugins['ovs']['server_packages'] = ['neutron-server', | ||
4853 | 189 | 'neutron-plugin-ml2'] | ||
4854 | 190 | # NOTE: patch in vmware renames nvp->nsx for icehouse onwards | ||
4855 | 191 | plugins['nvp'] = plugins['nsx'] | ||
4856 | 192 | return plugins | ||
4857 | 193 | |||
4858 | 194 | |||
4859 | 195 | def neutron_plugin_attribute(plugin, attr, net_manager=None): | ||
4860 | 196 | manager = net_manager or network_manager() | ||
4861 | 197 | if manager == 'quantum': | ||
4862 | 198 | plugins = quantum_plugins() | ||
4863 | 199 | elif manager == 'neutron': | ||
4864 | 200 | plugins = neutron_plugins() | ||
4865 | 201 | else: | ||
4866 | 202 | log("Network manager '%s' does not support plugins." % (manager), | ||
4867 | 203 | level=ERROR) | ||
4868 | 204 | raise Exception | ||
4869 | 205 | |||
4870 | 206 | try: | ||
4871 | 207 | _plugin = plugins[plugin] | ||
4872 | 208 | except KeyError: | ||
4873 | 209 | log('Unrecognised plugin for %s: %s' % (manager, plugin), level=ERROR) | ||
4874 | 210 | raise Exception | ||
4875 | 211 | |||
4876 | 212 | try: | ||
4877 | 213 | return _plugin[attr] | ||
4878 | 214 | except KeyError: | ||
4879 | 215 | return None | ||
4880 | 216 | |||
4881 | 217 | |||
4882 | 218 | def network_manager(): | ||
4883 | 219 | ''' | ||
4884 | 220 | Deals with the renaming of Quantum to Neutron in H and any situations | ||
4885 | 221 | that require compatability (eg, deploying H with network-manager=quantum, | ||
4886 | 222 | upgrading from G). | ||
4887 | 223 | ''' | ||
4888 | 224 | release = os_release('nova-common') | ||
4889 | 225 | manager = config('network-manager').lower() | ||
4890 | 226 | |||
4891 | 227 | if manager not in ['quantum', 'neutron']: | ||
4892 | 228 | return manager | ||
4893 | 229 | |||
4894 | 230 | if release in ['essex']: | ||
4895 | 231 | # E does not support neutron | ||
4896 | 232 | log('Neutron networking not supported in Essex.', level=ERROR) | ||
4897 | 233 | raise Exception | ||
4898 | 234 | elif release in ['folsom', 'grizzly']: | ||
4899 | 235 | # neutron is named quantum in F and G | ||
4900 | 236 | return 'quantum' | ||
4901 | 237 | else: | ||
4902 | 238 | # ensure accurate naming for all releases post-H | ||
4903 | 239 | return 'neutron' | ||
4904 | 0 | 240 | ||
4905 | === added directory 'hooks/charmhelpers/contrib/openstack/templates' | |||
4906 | === added file 'hooks/charmhelpers/contrib/openstack/templates/__init__.py' | |||
4907 | --- hooks/charmhelpers/contrib/openstack/templates/__init__.py 1970-01-01 00:00:00 +0000 | |||
4908 | +++ hooks/charmhelpers/contrib/openstack/templates/__init__.py 2015-06-18 17:19:58 +0000 | |||
4909 | @@ -0,0 +1,18 @@ | |||
4910 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4911 | 2 | # | ||
4912 | 3 | # This file is part of charm-helpers. | ||
4913 | 4 | # | ||
4914 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
4915 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
4916 | 7 | # published by the Free Software Foundation. | ||
4917 | 8 | # | ||
4918 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
4919 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
4920 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
4921 | 12 | # GNU Lesser General Public License for more details. | ||
4922 | 13 | # | ||
4923 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
4924 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
4925 | 16 | |||
4926 | 17 | # dummy __init__.py to fool syncer into thinking this is a syncable python | ||
4927 | 18 | # module | ||
4928 | 0 | 19 | ||
4929 | === added file 'hooks/charmhelpers/contrib/openstack/templating.py' | |||
4930 | --- hooks/charmhelpers/contrib/openstack/templating.py 1970-01-01 00:00:00 +0000 | |||
4931 | +++ hooks/charmhelpers/contrib/openstack/templating.py 2015-06-18 17:19:58 +0000 | |||
4932 | @@ -0,0 +1,295 @@ | |||
4933 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4934 | 2 | # | ||
4935 | 3 | # This file is part of charm-helpers. | ||
4936 | 4 | # | ||
4937 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
4938 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
4939 | 7 | # published by the Free Software Foundation. | ||
4940 | 8 | # | ||
4941 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
4942 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
4943 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
4944 | 12 | # GNU Lesser General Public License for more details. | ||
4945 | 13 | # | ||
4946 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
4947 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
4948 | 16 | |||
4949 | 17 | import os | ||
4950 | 18 | |||
4951 | 19 | import six | ||
4952 | 20 | |||
4953 | 21 | from charmhelpers.fetch import apt_install | ||
4954 | 22 | from charmhelpers.core.hookenv import ( | ||
4955 | 23 | log, | ||
4956 | 24 | ERROR, | ||
4957 | 25 | INFO | ||
4958 | 26 | ) | ||
4959 | 27 | from charmhelpers.contrib.openstack.utils import OPENSTACK_CODENAMES | ||
4960 | 28 | |||
4961 | 29 | try: | ||
4962 | 30 | from jinja2 import FileSystemLoader, ChoiceLoader, Environment, exceptions | ||
4963 | 31 | except ImportError: | ||
4964 | 32 | # python-jinja2 may not be installed yet, or we're running unittests. | ||
4965 | 33 | FileSystemLoader = ChoiceLoader = Environment = exceptions = None | ||
4966 | 34 | |||
4967 | 35 | |||
4968 | 36 | class OSConfigException(Exception): | ||
4969 | 37 | pass | ||
4970 | 38 | |||
4971 | 39 | |||
4972 | 40 | def get_loader(templates_dir, os_release): | ||
4973 | 41 | """ | ||
4974 | 42 | Create a jinja2.ChoiceLoader containing template dirs up to | ||
4975 | 43 | and including os_release. If directory template directory | ||
4976 | 44 | is missing at templates_dir, it will be omitted from the loader. | ||
4977 | 45 | templates_dir is added to the bottom of the search list as a base | ||
4978 | 46 | loading dir. | ||
4979 | 47 | |||
4980 | 48 | A charm may also ship a templates dir with this module | ||
4981 | 49 | and it will be appended to the bottom of the search list, eg:: | ||
4982 | 50 | |||
4983 | 51 | hooks/charmhelpers/contrib/openstack/templates | ||
4984 | 52 | |||
4985 | 53 | :param templates_dir (str): Base template directory containing release | ||
4986 | 54 | sub-directories. | ||
4987 | 55 | :param os_release (str): OpenStack release codename to construct template | ||
4988 | 56 | loader. | ||
4989 | 57 | :returns: jinja2.ChoiceLoader constructed with a list of | ||
4990 | 58 | jinja2.FilesystemLoaders, ordered in descending | ||
4991 | 59 | order by OpenStack release. | ||
4992 | 60 | """ | ||
4993 | 61 | tmpl_dirs = [(rel, os.path.join(templates_dir, rel)) | ||
4994 | 62 | for rel in six.itervalues(OPENSTACK_CODENAMES)] | ||
4995 | 63 | |||
4996 | 64 | if not os.path.isdir(templates_dir): | ||
4997 | 65 | log('Templates directory not found @ %s.' % templates_dir, | ||
4998 | 66 | level=ERROR) | ||
4999 | 67 | raise OSConfigException | ||
5000 | 68 |
The diff has been truncated for viewing.
Facundo,
The diff is truncated, but you can land as long as you stop trying to install the spec_manager module (it will fail, because it's not installed atm) and remove the service action for filling website relation forcibly (remove the wsgi-relation- joined symlink and create the correct website-relation* ones).
[]