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