Merge ~pwlars/revcache/+git/revcache-charm:juju1-support into revcache:master
- Git
- lp:~pwlars/revcache/+git/revcache-charm
- juju1-support
- Merge into master
Status: | Superseded |
---|---|
Proposed branch: | ~pwlars/revcache/+git/revcache-charm:juju1-support |
Merge into: | revcache:master |
Diff against target: |
6772 lines (+6450/-0) 54 files modified
.gitignore (+3/-0) README.md (+221/-0) config.yaml (+21/-0) copyright (+9/-0) hooks/charmhelpers/__init__.py (+36/-0) hooks/charmhelpers/contrib/__init__.py (+13/-0) hooks/charmhelpers/contrib/ansible/__init__.py (+252/-0) hooks/charmhelpers/contrib/templating/__init__.py (+13/-0) hooks/charmhelpers/contrib/templating/contexts.py (+137/-0) hooks/charmhelpers/core/__init__.py (+13/-0) hooks/charmhelpers/core/decorators.py (+55/-0) hooks/charmhelpers/core/files.py (+43/-0) hooks/charmhelpers/core/fstab.py (+132/-0) hooks/charmhelpers/core/hookenv.py (+1068/-0) hooks/charmhelpers/core/host.py (+922/-0) hooks/charmhelpers/core/host_factory/__init__.py (+0/-0) hooks/charmhelpers/core/host_factory/centos.py (+72/-0) hooks/charmhelpers/core/host_factory/ubuntu.py (+88/-0) hooks/charmhelpers/core/hugepage.py (+69/-0) hooks/charmhelpers/core/kernel.py (+72/-0) hooks/charmhelpers/core/kernel_factory/__init__.py (+0/-0) hooks/charmhelpers/core/kernel_factory/centos.py (+17/-0) hooks/charmhelpers/core/kernel_factory/ubuntu.py (+13/-0) hooks/charmhelpers/core/services/__init__.py (+16/-0) hooks/charmhelpers/core/services/base.py (+351/-0) hooks/charmhelpers/core/services/helpers.py (+290/-0) hooks/charmhelpers/core/strutils.py (+123/-0) hooks/charmhelpers/core/sysctl.py (+54/-0) hooks/charmhelpers/core/templating.py (+84/-0) hooks/charmhelpers/core/unitdata.py (+518/-0) hooks/charmhelpers/fetch/__init__.py (+197/-0) hooks/charmhelpers/fetch/archiveurl.py (+165/-0) hooks/charmhelpers/fetch/bzrurl.py (+76/-0) hooks/charmhelpers/fetch/centos.py (+171/-0) hooks/charmhelpers/fetch/giturl.py (+69/-0) hooks/charmhelpers/fetch/snap.py (+122/-0) hooks/charmhelpers/fetch/ubuntu.py (+364/-0) hooks/charmhelpers/osplatform.py (+25/-0) hooks/charmhelpers/payload/__init__.py (+15/-0) hooks/charmhelpers/payload/archive.py (+71/-0) hooks/charmhelpers/payload/execd.py (+65/-0) hooks/config-changed (+21/-0) hooks/db-relation-changed (+21/-0) hooks/db-relation-joined (+21/-0) hooks/hooks.py (+21/-0) hooks/install (+21/-0) hooks/start (+21/-0) hooks/stop (+21/-0) metadata.yaml (+23/-0) playbooks/revcache.yaml (+194/-0) templates/revcache-vhost-https.conf (+14/-0) templates/revcache-vhost.conf (+12/-0) templates/revcache.conf (+2/-0) templates/revcache.service (+13/-0) |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Canonical Hardware Certification | Pending | ||
Review via email:
|
This proposal has been superseded by a proposal from 2018-06-20.
Commit message
Description of the change
I think this finally does what I want. I've tested it locally with some fake keys, and confirmed that it puts the files in the right location and uses the correct vhost template with ssl support for nginx *only* when specifying the certificates and ssl key in either the config or in an artifact. This allows us to support both juju1 and juju2 in the same charm!
Unmerged commits
- fff4d98... by Paul Larson
-
Also support ssl on juju v1 via config settings and include-base64
- 5d56cf8... by PMR <pmr@pmr-lander>
-
Merge #346656 from ~pwlars/
revcache/ +git/revcache- charm:ssl- support - a5135d1... by Paul Larson
-
Add https support
- daf9c5e... by Paul Larson
-
Add python3-gevent dependency and minor fixes to systemd service file
- 76d9edd... by Paul Larson
-
Remove setup step and ensure logfile is created
- d0098af... by Paul Larson
-
Initial checking of revcache charm
Preview Diff
1 | diff --git a/.gitignore b/.gitignore | |||
2 | 0 | new file mode 100644 | 0 | new file mode 100644 |
3 | index 0000000..021454b | |||
4 | --- /dev/null | |||
5 | +++ b/.gitignore | |||
6 | @@ -0,0 +1,3 @@ | |||
7 | 1 | *.pyc | ||
8 | 2 | *~ | ||
9 | 3 | *.swp | ||
10 | diff --git a/README.md b/README.md | |||
11 | 0 | new file mode 100644 | 4 | new file mode 100644 |
12 | index 0000000..0337c83 | |||
13 | --- /dev/null | |||
14 | +++ b/README.md | |||
15 | @@ -0,0 +1,221 @@ | |||
16 | 1 | # Overview | ||
17 | 2 | |||
18 | 3 | This is the base layer for all charms [built using layers][building]. It | ||
19 | 4 | provides all of the standard Juju hooks and runs the | ||
20 | 5 | [charms.reactive.main][charms.reactive] loop for them. It also bootstraps the | ||
21 | 6 | [charm-helpers][] and [charms.reactive][] libraries and all of their | ||
22 | 7 | dependencies for use by the charm. | ||
23 | 8 | |||
24 | 9 | # Usage | ||
25 | 10 | |||
26 | 11 | To create a charm layer using this base layer, you need only include it in | ||
27 | 12 | a `layer.yaml` file: | ||
28 | 13 | |||
29 | 14 | ```yaml | ||
30 | 15 | includes: ['layer:basic'] | ||
31 | 16 | ``` | ||
32 | 17 | |||
33 | 18 | This will fetch this layer from [interfaces.juju.solutions][] and incorporate | ||
34 | 19 | it into your charm layer. You can then add handlers under the `reactive/` | ||
35 | 20 | directory. Note that **any** file under `reactive/` will be expected to | ||
36 | 21 | contain handlers, whether as Python decorated functions or [executables][non-python] | ||
37 | 22 | using the [external handler protocol][]. | ||
38 | 23 | |||
39 | 24 | ### Charm Dependencies | ||
40 | 25 | |||
41 | 26 | Each layer can include a `wheelhouse.txt` file with Python requirement lines. | ||
42 | 27 | For example, this layer's `wheelhouse.txt` includes: | ||
43 | 28 | |||
44 | 29 | ``` | ||
45 | 30 | pip>=7.0.0,<8.0.0 | ||
46 | 31 | charmhelpers>=0.4.0,<1.0.0 | ||
47 | 32 | charms.reactive>=0.1.0,<2.0.0 | ||
48 | 33 | ``` | ||
49 | 34 | |||
50 | 35 | All of these dependencies from each layer will be fetched (and updated) at build | ||
51 | 36 | time and will be automatically installed by this base layer before any reactive | ||
52 | 37 | handlers are run. | ||
53 | 38 | |||
54 | 39 | Note that the `wheelhouse.txt` file is intended for **charm** dependencies only. | ||
55 | 40 | That is, for libraries that the charm code itself needs to do its job of deploying | ||
56 | 41 | and configuring the payload. If the payload itself has Python dependencies, those | ||
57 | 42 | should be handled separately, by the charm. | ||
58 | 43 | |||
59 | 44 | See [PyPI][pypi charms.X] for packages under the `charms.` namespace which might | ||
60 | 45 | be useful for your charm. | ||
61 | 46 | |||
62 | 47 | ### Layer Namespace | ||
63 | 48 | |||
64 | 49 | Each layer has a reserved section in the `charms.layer.` Python package namespace, | ||
65 | 50 | which it can populate by including a `lib/charms/layer/<layer-name>.py` file or | ||
66 | 51 | by placing files under `lib/charms/layer/<layer-name>/`. (If the layer name | ||
67 | 52 | includes hyphens, replace them with underscores.) These can be helpers that the | ||
68 | 53 | layer uses internally, or it can expose classes or functions to be used by other | ||
69 | 54 | layers to interact with that layer. | ||
70 | 55 | |||
71 | 56 | For example, a layer named `foo` could include a `lib/charms/layer/foo.py` file | ||
72 | 57 | with some helper functions that other layers could access using: | ||
73 | 58 | |||
74 | 59 | ```python | ||
75 | 60 | from charms.layer.foo import my_helper | ||
76 | 61 | ``` | ||
77 | 62 | |||
78 | 63 | ### Layer Options | ||
79 | 64 | |||
80 | 65 | Any layer can define options in its `layer.yaml`. Those options can then be set | ||
81 | 66 | by other layers to change the behavior of your layer. The options are defined | ||
82 | 67 | using [jsonschema][], which is the same way that [action paramters][] are defined. | ||
83 | 68 | |||
84 | 69 | For example, the `foo` layer could include the following option definitons: | ||
85 | 70 | |||
86 | 71 | ```yaml | ||
87 | 72 | includes: ['layer:basic'] | ||
88 | 73 | defines: # define some options for this layer (the layer "foo") | ||
89 | 74 | enable-bar: # define an "enable-bar" option for this layer | ||
90 | 75 | description: If true, enable support for "bar". | ||
91 | 76 | type: boolean | ||
92 | 77 | default: false | ||
93 | 78 | ``` | ||
94 | 79 | |||
95 | 80 | A layer using `foo` could then set it: | ||
96 | 81 | |||
97 | 82 | ```yaml | ||
98 | 83 | includes: ['layer:foo'] | ||
99 | 84 | options: | ||
100 | 85 | foo: # setting options for the "foo" layer | ||
101 | 86 | enable-bar: true # set the "enable-bar" option to true | ||
102 | 87 | ``` | ||
103 | 88 | |||
104 | 89 | The `foo` layer can then use the `charms.layer.options` helper to load the values | ||
105 | 90 | for the options that it defined. For example: | ||
106 | 91 | |||
107 | 92 | ```python | ||
108 | 93 | from charms import layer | ||
109 | 94 | |||
110 | 95 | @when('state') | ||
111 | 96 | def do_thing(): | ||
112 | 97 | layer_opts = layer.options('foo') # load all of the options for the "foo" layer | ||
113 | 98 | if layer_opts['enable-bar']: # check the value of the "enable-bar" option | ||
114 | 99 | hookenv.log("Bar is enabled") | ||
115 | 100 | ``` | ||
116 | 101 | |||
117 | 102 | You can also access layer options in other handlers, such as Bash, using | ||
118 | 103 | the command-line interface: | ||
119 | 104 | |||
120 | 105 | ```bash | ||
121 | 106 | . charms.reactive.sh | ||
122 | 107 | |||
123 | 108 | @when 'state' | ||
124 | 109 | function do_thing() { | ||
125 | 110 | if layer_option foo enable-bar; then | ||
126 | 111 | juju-log "Bar is enabled" | ||
127 | 112 | juju-log "bar-value is: $(layer_option foo bar-value)" | ||
128 | 113 | fi | ||
129 | 114 | } | ||
130 | 115 | |||
131 | 116 | reactive_handler_main | ||
132 | 117 | ``` | ||
133 | 118 | |||
134 | 119 | Note that options of type `boolean` will set the exit code, while other types | ||
135 | 120 | will be printed out. | ||
136 | 121 | |||
137 | 122 | # Hooks | ||
138 | 123 | |||
139 | 124 | This layer provides hooks that other layers can react to using the decorators | ||
140 | 125 | of the [charms.reactive][] library: | ||
141 | 126 | |||
142 | 127 | * `config-changed` | ||
143 | 128 | * `install` | ||
144 | 129 | * `leader-elected` | ||
145 | 130 | * `leader-settings-changed` | ||
146 | 131 | * `start` | ||
147 | 132 | * `stop` | ||
148 | 133 | * `upgrade-charm` | ||
149 | 134 | * `update-status` | ||
150 | 135 | |||
151 | 136 | Other hooks are not implemented at this time. A new layer can implement storage | ||
152 | 137 | or relation hooks in their own layer by putting them in the `hooks` directory. | ||
153 | 138 | |||
154 | 139 | **Note:** Because `update-status` is invoked every 5 minutes, you should take | ||
155 | 140 | care to ensure that your reactive handlers only invoke expensive operations | ||
156 | 141 | when absolutely necessary. It is recommended that you use helpers like | ||
157 | 142 | [`@only_once`][], [`@when_file_changed`][], and [`data_changed`][] to ensure | ||
158 | 143 | that handlers run only when necessary. | ||
159 | 144 | |||
160 | 145 | # Layer Configuration | ||
161 | 146 | |||
162 | 147 | This layer supports the following options, which can be set in `layer.yaml`: | ||
163 | 148 | |||
164 | 149 | * **packages** A list of system packages to be installed before the reactive | ||
165 | 150 | handlers are invoked. | ||
166 | 151 | |||
167 | 152 | * **use_venv** If set to true, the charm dependencies from the various | ||
168 | 153 | layers' `wheelhouse.txt` files will be installed in a Python virtualenv | ||
169 | 154 | located at `$CHARM_DIR/../.venv`. This keeps charm dependencies from | ||
170 | 155 | conflicting with payload dependencies, but you must take care to preserve | ||
171 | 156 | the environment and interpreter if using `execl` or `subprocess`. | ||
172 | 157 | |||
173 | 158 | * **include_system_packages** If set to true and using a venv, include | ||
174 | 159 | the `--system-site-packages` options to make system Python libraries | ||
175 | 160 | visible within the venv. | ||
176 | 161 | |||
177 | 162 | An example `layer.yaml` using these options might be: | ||
178 | 163 | |||
179 | 164 | ```yaml | ||
180 | 165 | includes: ['layer:basic'] | ||
181 | 166 | options: | ||
182 | 167 | basic: | ||
183 | 168 | packages: ['git'] | ||
184 | 169 | use_venv: true | ||
185 | 170 | include_system_packages: true | ||
186 | 171 | ``` | ||
187 | 172 | |||
188 | 173 | |||
189 | 174 | # Reactive States | ||
190 | 175 | |||
191 | 176 | This layer will set the following states: | ||
192 | 177 | |||
193 | 178 | * **`config.changed`** Any config option has changed from its previous value. | ||
194 | 179 | This state is cleared automatically at the end of each hook invocation. | ||
195 | 180 | |||
196 | 181 | * **`config.changed.<option>`** A specific config option has changed. | ||
197 | 182 | **`<option>`** will be replaced by the config option name from `config.yaml`. | ||
198 | 183 | This state is cleared automatically at the end of each hook invocation. | ||
199 | 184 | |||
200 | 185 | * **`config.set.<option>`** A specific config option has a True or non-empty | ||
201 | 186 | value set. **`<option>`** will be replaced by the config option name from | ||
202 | 187 | `config.yaml`. This state is cleared automatically at the end of each hook | ||
203 | 188 | invocation. | ||
204 | 189 | |||
205 | 190 | * **`config.default.<option>`** A specific config option is set to its | ||
206 | 191 | default value. **`<option>`** will be replaced by the config option name | ||
207 | 192 | from `config.yaml`. This state is cleared automatically at the end of | ||
208 | 193 | each hook invocation. | ||
209 | 194 | |||
210 | 195 | An example using the config states would be: | ||
211 | 196 | |||
212 | 197 | ```python | ||
213 | 198 | @when('config.changed.my-opt') | ||
214 | 199 | def my_opt_changed(): | ||
215 | 200 | update_config() | ||
216 | 201 | restart_service() | ||
217 | 202 | ``` | ||
218 | 203 | |||
219 | 204 | |||
220 | 205 | # Actions | ||
221 | 206 | |||
222 | 207 | This layer currently does not define any actions. | ||
223 | 208 | |||
224 | 209 | |||
225 | 210 | [building]: https://jujucharms.com/docs/devel/authors-charm-building | ||
226 | 211 | [charm-helpers]: https://pythonhosted.org/charmhelpers/ | ||
227 | 212 | [charms.reactive]: https://pythonhosted.org/charms.reactive/ | ||
228 | 213 | [interfaces.juju.solutions]: http://interfaces.juju.solutions/ | ||
229 | 214 | [non-python]: https://pythonhosted.org/charms.reactive/#non-python-reactive-handlers | ||
230 | 215 | [external handler protocol]: https://pythonhosted.org/charms.reactive/charms.reactive.bus.html#charms.reactive.bus.ExternalHandler | ||
231 | 216 | [jsonschema]: http://json-schema.org/ | ||
232 | 217 | [action paramters]: https://jujucharms.com/docs/stable/authors-charm-actions | ||
233 | 218 | [pypi charms.X]: https://pypi.python.org/pypi?%3Aaction=search&term=charms.&submit=search | ||
234 | 219 | [`@only_once`]: https://pythonhosted.org/charms.reactive/charms.reactive.decorators.html#charms.reactive.decorators.only_once | ||
235 | 220 | [`@when_file_changed`]: https://pythonhosted.org/charms.reactive/charms.reactive.decorators.html#charms.reactive.decorators.when_file_changed | ||
236 | 221 | [`data_changed`]: https://pythonhosted.org/charms.reactive/charms.reactive.helpers.html#charms.reactive.helpers.data_changed | ||
237 | diff --git a/config.yaml b/config.yaml | |||
238 | 0 | new file mode 100644 | 222 | new file mode 100644 |
239 | index 0000000..1e4601f | |||
240 | --- /dev/null | |||
241 | +++ b/config.yaml | |||
242 | @@ -0,0 +1,21 @@ | |||
243 | 1 | options: | ||
244 | 2 | revcache-repo: | ||
245 | 3 | type: string | ||
246 | 4 | description: git repo for revcache | ||
247 | 5 | default: "https://git.launchpad.net/~pwlars/revcache" | ||
248 | 6 | revcache-branch: | ||
249 | 7 | type: string | ||
250 | 8 | description: git branch for revcache | ||
251 | 9 | default: "start" | ||
252 | 10 | config-ssl-certificate: | ||
253 | 11 | type: string | ||
254 | 12 | description: base64 encoded ssl certificate file | ||
255 | 13 | default: "" | ||
256 | 14 | config-ssl-chain: | ||
257 | 15 | type: string | ||
258 | 16 | description: base64 encoded ssl chain file | ||
259 | 17 | default: "" | ||
260 | 18 | config-ssl-key: | ||
261 | 19 | type: string | ||
262 | 20 | description: base64 encoded ssl key file | ||
263 | 21 | default: "" | ||
264 | diff --git a/copyright b/copyright | |||
265 | 0 | new file mode 100644 | 22 | new file mode 100644 |
266 | index 0000000..4aca5f0 | |||
267 | --- /dev/null | |||
268 | +++ b/copyright | |||
269 | @@ -0,0 +1,9 @@ | |||
270 | 1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0 | ||
271 | 2 | |||
272 | 3 | Files: * | ||
273 | 4 | Copyright: 2018, Canonical Ltd. | ||
274 | 5 | License: GPL-3 | ||
275 | 6 | |||
276 | 7 | License: GPL-3 | ||
277 | 8 | On Debian GNU/Linux system you can find the complete text of the | ||
278 | 9 | GPL-3 license in '/usr/share/common-licenses/GPL-3' | ||
279 | diff --git a/hooks/charmhelpers/__init__.py b/hooks/charmhelpers/__init__.py | |||
280 | 0 | new file mode 100644 | 10 | new file mode 100644 |
281 | index 0000000..4886788 | |||
282 | --- /dev/null | |||
283 | +++ b/hooks/charmhelpers/__init__.py | |||
284 | @@ -0,0 +1,36 @@ | |||
285 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
286 | 2 | # | ||
287 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
288 | 4 | # you may not use this file except in compliance with the License. | ||
289 | 5 | # You may obtain a copy of the License at | ||
290 | 6 | # | ||
291 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
292 | 8 | # | ||
293 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
294 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
295 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
296 | 12 | # See the License for the specific language governing permissions and | ||
297 | 13 | # limitations under the License. | ||
298 | 14 | |||
299 | 15 | # Bootstrap charm-helpers, installing its dependencies if necessary using | ||
300 | 16 | # only standard libraries. | ||
301 | 17 | import subprocess | ||
302 | 18 | import sys | ||
303 | 19 | |||
304 | 20 | try: | ||
305 | 21 | import six # flake8: noqa | ||
306 | 22 | except ImportError: | ||
307 | 23 | if sys.version_info.major == 2: | ||
308 | 24 | subprocess.check_call(['apt-get', 'install', '-y', 'python-six']) | ||
309 | 25 | else: | ||
310 | 26 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-six']) | ||
311 | 27 | import six # flake8: noqa | ||
312 | 28 | |||
313 | 29 | try: | ||
314 | 30 | import yaml # flake8: noqa | ||
315 | 31 | except ImportError: | ||
316 | 32 | if sys.version_info.major == 2: | ||
317 | 33 | subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml']) | ||
318 | 34 | else: | ||
319 | 35 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml']) | ||
320 | 36 | import yaml # flake8: noqa | ||
321 | diff --git a/hooks/charmhelpers/contrib/__init__.py b/hooks/charmhelpers/contrib/__init__.py | |||
322 | 0 | new file mode 100644 | 37 | new file mode 100644 |
323 | index 0000000..d7567b8 | |||
324 | --- /dev/null | |||
325 | +++ b/hooks/charmhelpers/contrib/__init__.py | |||
326 | @@ -0,0 +1,13 @@ | |||
327 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
328 | 2 | # | ||
329 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
330 | 4 | # you may not use this file except in compliance with the License. | ||
331 | 5 | # You may obtain a copy of the License at | ||
332 | 6 | # | ||
333 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
334 | 8 | # | ||
335 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
336 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
337 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
338 | 12 | # See the License for the specific language governing permissions and | ||
339 | 13 | # limitations under the License. | ||
340 | diff --git a/hooks/charmhelpers/contrib/ansible/__init__.py b/hooks/charmhelpers/contrib/ansible/__init__.py | |||
341 | 0 | new file mode 100644 | 14 | new file mode 100644 |
342 | index 0000000..f3617db | |||
343 | --- /dev/null | |||
344 | +++ b/hooks/charmhelpers/contrib/ansible/__init__.py | |||
345 | @@ -0,0 +1,252 @@ | |||
346 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
347 | 2 | # | ||
348 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
349 | 4 | # you may not use this file except in compliance with the License. | ||
350 | 5 | # You may obtain a copy of the License at | ||
351 | 6 | # | ||
352 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
353 | 8 | # | ||
354 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
355 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
356 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
357 | 12 | # See the License for the specific language governing permissions and | ||
358 | 13 | # limitations under the License. | ||
359 | 14 | |||
360 | 15 | # Copyright 2013 Canonical Ltd. | ||
361 | 16 | # | ||
362 | 17 | # Authors: | ||
363 | 18 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
364 | 19 | """Charm Helpers ansible - declare the state of your machines. | ||
365 | 20 | |||
366 | 21 | This helper enables you to declare your machine state, rather than | ||
367 | 22 | program it procedurally (and have to test each change to your procedures). | ||
368 | 23 | Your install hook can be as simple as:: | ||
369 | 24 | |||
370 | 25 | {{{ | ||
371 | 26 | import charmhelpers.contrib.ansible | ||
372 | 27 | |||
373 | 28 | |||
374 | 29 | def install(): | ||
375 | 30 | charmhelpers.contrib.ansible.install_ansible_support() | ||
376 | 31 | charmhelpers.contrib.ansible.apply_playbook('playbooks/install.yaml') | ||
377 | 32 | }}} | ||
378 | 33 | |||
379 | 34 | and won't need to change (nor will its tests) when you change the machine | ||
380 | 35 | state. | ||
381 | 36 | |||
382 | 37 | All of your juju config and relation-data are available as template | ||
383 | 38 | variables within your playbooks and templates. An install playbook looks | ||
384 | 39 | something like:: | ||
385 | 40 | |||
386 | 41 | {{{ | ||
387 | 42 | --- | ||
388 | 43 | - hosts: localhost | ||
389 | 44 | user: root | ||
390 | 45 | |||
391 | 46 | tasks: | ||
392 | 47 | - name: Add private repositories. | ||
393 | 48 | template: | ||
394 | 49 | src: ../templates/private-repositories.list.jinja2 | ||
395 | 50 | dest: /etc/apt/sources.list.d/private.list | ||
396 | 51 | |||
397 | 52 | - name: Update the cache. | ||
398 | 53 | apt: update_cache=yes | ||
399 | 54 | |||
400 | 55 | - name: Install dependencies. | ||
401 | 56 | apt: pkg={{ item }} | ||
402 | 57 | with_items: | ||
403 | 58 | - python-mimeparse | ||
404 | 59 | - python-webob | ||
405 | 60 | - sunburnt | ||
406 | 61 | |||
407 | 62 | - name: Setup groups. | ||
408 | 63 | group: name={{ item.name }} gid={{ item.gid }} | ||
409 | 64 | with_items: | ||
410 | 65 | - { name: 'deploy_user', gid: 1800 } | ||
411 | 66 | - { name: 'service_user', gid: 1500 } | ||
412 | 67 | |||
413 | 68 | ... | ||
414 | 69 | }}} | ||
415 | 70 | |||
416 | 71 | Read more online about `playbooks`_ and standard ansible `modules`_. | ||
417 | 72 | |||
418 | 73 | .. _playbooks: http://www.ansibleworks.com/docs/playbooks.html | ||
419 | 74 | .. _modules: http://www.ansibleworks.com/docs/modules.html | ||
420 | 75 | |||
421 | 76 | A further feature os the ansible hooks is to provide a light weight "action" | ||
422 | 77 | scripting tool. This is a decorator that you apply to a function, and that | ||
423 | 78 | function can now receive cli args, and can pass extra args to the playbook. | ||
424 | 79 | |||
425 | 80 | e.g. | ||
426 | 81 | |||
427 | 82 | |||
428 | 83 | @hooks.action() | ||
429 | 84 | def some_action(amount, force="False"): | ||
430 | 85 | "Usage: some-action AMOUNT [force=True]" # <-- shown on error | ||
431 | 86 | # process the arguments | ||
432 | 87 | # do some calls | ||
433 | 88 | # return extra-vars to be passed to ansible-playbook | ||
434 | 89 | return { | ||
435 | 90 | 'amount': int(amount), | ||
436 | 91 | 'type': force, | ||
437 | 92 | } | ||
438 | 93 | |||
439 | 94 | You can now create a symlink to hooks.py that can be invoked like a hook, but | ||
440 | 95 | with cli params: | ||
441 | 96 | |||
442 | 97 | # link actions/some-action to hooks/hooks.py | ||
443 | 98 | |||
444 | 99 | actions/some-action amount=10 force=true | ||
445 | 100 | |||
446 | 101 | """ | ||
447 | 102 | import os | ||
448 | 103 | import stat | ||
449 | 104 | import subprocess | ||
450 | 105 | import functools | ||
451 | 106 | |||
452 | 107 | import charmhelpers.contrib.templating.contexts | ||
453 | 108 | import charmhelpers.core.host | ||
454 | 109 | import charmhelpers.core.hookenv | ||
455 | 110 | import charmhelpers.fetch | ||
456 | 111 | |||
457 | 112 | |||
458 | 113 | charm_dir = os.environ.get('CHARM_DIR', '') | ||
459 | 114 | ansible_hosts_path = '/etc/ansible/hosts' | ||
460 | 115 | # Ansible will automatically include any vars in the following | ||
461 | 116 | # file in its inventory when run locally. | ||
462 | 117 | ansible_vars_path = '/etc/ansible/host_vars/localhost' | ||
463 | 118 | |||
464 | 119 | |||
465 | 120 | def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'): | ||
466 | 121 | """Installs the ansible package. | ||
467 | 122 | |||
468 | 123 | By default it is installed from the `PPA`_ linked from | ||
469 | 124 | the ansible `website`_ or from a ppa specified by a charm config.. | ||
470 | 125 | |||
471 | 126 | .. _PPA: https://launchpad.net/~rquillo/+archive/ansible | ||
472 | 127 | .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu | ||
473 | 128 | |||
474 | 129 | If from_ppa is empty, you must ensure that the package is available | ||
475 | 130 | from a configured repository. | ||
476 | 131 | """ | ||
477 | 132 | if from_ppa: | ||
478 | 133 | charmhelpers.fetch.add_source(ppa_location) | ||
479 | 134 | charmhelpers.fetch.apt_update(fatal=True) | ||
480 | 135 | charmhelpers.fetch.apt_install('ansible') | ||
481 | 136 | with open(ansible_hosts_path, 'w+') as hosts_file: | ||
482 | 137 | hosts_file.write('localhost ansible_connection=local') | ||
483 | 138 | |||
484 | 139 | |||
485 | 140 | def apply_playbook(playbook, tags=None, extra_vars=None): | ||
486 | 141 | tags = tags or [] | ||
487 | 142 | tags = ",".join(tags) | ||
488 | 143 | charmhelpers.contrib.templating.contexts.juju_state_to_yaml( | ||
489 | 144 | ansible_vars_path, namespace_separator='__', | ||
490 | 145 | allow_hyphens_in_keys=False, mode=(stat.S_IRUSR | stat.S_IWUSR)) | ||
491 | 146 | |||
492 | 147 | # we want ansible's log output to be unbuffered | ||
493 | 148 | env = os.environ.copy() | ||
494 | 149 | env['PYTHONUNBUFFERED'] = "1" | ||
495 | 150 | call = [ | ||
496 | 151 | 'ansible-playbook', | ||
497 | 152 | '-c', | ||
498 | 153 | 'local', | ||
499 | 154 | playbook, | ||
500 | 155 | ] | ||
501 | 156 | if tags: | ||
502 | 157 | call.extend(['--tags', '{}'.format(tags)]) | ||
503 | 158 | if extra_vars: | ||
504 | 159 | extra = ["%s=%s" % (k, v) for k, v in extra_vars.items()] | ||
505 | 160 | call.extend(['--extra-vars', " ".join(extra)]) | ||
506 | 161 | subprocess.check_call(call, env=env) | ||
507 | 162 | |||
508 | 163 | |||
509 | 164 | class AnsibleHooks(charmhelpers.core.hookenv.Hooks): | ||
510 | 165 | """Run a playbook with the hook-name as the tag. | ||
511 | 166 | |||
512 | 167 | This helper builds on the standard hookenv.Hooks helper, | ||
513 | 168 | but additionally runs the playbook with the hook-name specified | ||
514 | 169 | using --tags (ie. running all the tasks tagged with the hook-name). | ||
515 | 170 | |||
516 | 171 | Example:: | ||
517 | 172 | |||
518 | 173 | hooks = AnsibleHooks(playbook_path='playbooks/my_machine_state.yaml') | ||
519 | 174 | |||
520 | 175 | # All the tasks within my_machine_state.yaml tagged with 'install' | ||
521 | 176 | # will be run automatically after do_custom_work() | ||
522 | 177 | @hooks.hook() | ||
523 | 178 | def install(): | ||
524 | 179 | do_custom_work() | ||
525 | 180 | |||
526 | 181 | # For most of your hooks, you won't need to do anything other | ||
527 | 182 | # than run the tagged tasks for the hook: | ||
528 | 183 | @hooks.hook('config-changed', 'start', 'stop') | ||
529 | 184 | def just_use_playbook(): | ||
530 | 185 | pass | ||
531 | 186 | |||
532 | 187 | # As a convenience, you can avoid the above noop function by specifying | ||
533 | 188 | # the hooks which are handled by ansible-only and they'll be registered | ||
534 | 189 | # for you: | ||
535 | 190 | # hooks = AnsibleHooks( | ||
536 | 191 | # 'playbooks/my_machine_state.yaml', | ||
537 | 192 | # default_hooks=['config-changed', 'start', 'stop']) | ||
538 | 193 | |||
539 | 194 | if __name__ == "__main__": | ||
540 | 195 | # execute a hook based on the name the program is called by | ||
541 | 196 | hooks.execute(sys.argv) | ||
542 | 197 | |||
543 | 198 | """ | ||
544 | 199 | |||
545 | 200 | def __init__(self, playbook_path, default_hooks=None): | ||
546 | 201 | """Register any hooks handled by ansible.""" | ||
547 | 202 | super(AnsibleHooks, self).__init__() | ||
548 | 203 | |||
549 | 204 | self._actions = {} | ||
550 | 205 | self.playbook_path = playbook_path | ||
551 | 206 | |||
552 | 207 | default_hooks = default_hooks or [] | ||
553 | 208 | |||
554 | 209 | def noop(*args, **kwargs): | ||
555 | 210 | pass | ||
556 | 211 | |||
557 | 212 | for hook in default_hooks: | ||
558 | 213 | self.register(hook, noop) | ||
559 | 214 | |||
560 | 215 | def register_action(self, name, function): | ||
561 | 216 | """Register a hook""" | ||
562 | 217 | self._actions[name] = function | ||
563 | 218 | |||
564 | 219 | def execute(self, args): | ||
565 | 220 | """Execute the hook followed by the playbook using the hook as tag.""" | ||
566 | 221 | hook_name = os.path.basename(args[0]) | ||
567 | 222 | extra_vars = None | ||
568 | 223 | if hook_name in self._actions: | ||
569 | 224 | extra_vars = self._actions[hook_name](args[1:]) | ||
570 | 225 | else: | ||
571 | 226 | super(AnsibleHooks, self).execute(args) | ||
572 | 227 | |||
573 | 228 | charmhelpers.contrib.ansible.apply_playbook( | ||
574 | 229 | self.playbook_path, tags=[hook_name], extra_vars=extra_vars) | ||
575 | 230 | |||
576 | 231 | def action(self, *action_names): | ||
577 | 232 | """Decorator, registering them as actions""" | ||
578 | 233 | def action_wrapper(decorated): | ||
579 | 234 | |||
580 | 235 | @functools.wraps(decorated) | ||
581 | 236 | def wrapper(argv): | ||
582 | 237 | kwargs = dict(arg.split('=') for arg in argv) | ||
583 | 238 | try: | ||
584 | 239 | return decorated(**kwargs) | ||
585 | 240 | except TypeError as e: | ||
586 | 241 | if decorated.__doc__: | ||
587 | 242 | e.args += (decorated.__doc__,) | ||
588 | 243 | raise | ||
589 | 244 | |||
590 | 245 | self.register_action(decorated.__name__, wrapper) | ||
591 | 246 | if '_' in decorated.__name__: | ||
592 | 247 | self.register_action( | ||
593 | 248 | decorated.__name__.replace('_', '-'), wrapper) | ||
594 | 249 | |||
595 | 250 | return wrapper | ||
596 | 251 | |||
597 | 252 | return action_wrapper | ||
598 | diff --git a/hooks/charmhelpers/contrib/templating/__init__.py b/hooks/charmhelpers/contrib/templating/__init__.py | |||
599 | 0 | new file mode 100644 | 253 | new file mode 100644 |
600 | index 0000000..d7567b8 | |||
601 | --- /dev/null | |||
602 | +++ b/hooks/charmhelpers/contrib/templating/__init__.py | |||
603 | @@ -0,0 +1,13 @@ | |||
604 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
605 | 2 | # | ||
606 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
607 | 4 | # you may not use this file except in compliance with the License. | ||
608 | 5 | # You may obtain a copy of the License at | ||
609 | 6 | # | ||
610 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
611 | 8 | # | ||
612 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
613 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
614 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
615 | 12 | # See the License for the specific language governing permissions and | ||
616 | 13 | # limitations under the License. | ||
617 | diff --git a/hooks/charmhelpers/contrib/templating/contexts.py b/hooks/charmhelpers/contrib/templating/contexts.py | |||
618 | 0 | new file mode 100644 | 14 | new file mode 100644 |
619 | index 0000000..c1adf94 | |||
620 | --- /dev/null | |||
621 | +++ b/hooks/charmhelpers/contrib/templating/contexts.py | |||
622 | @@ -0,0 +1,137 @@ | |||
623 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
624 | 2 | # | ||
625 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
626 | 4 | # you may not use this file except in compliance with the License. | ||
627 | 5 | # You may obtain a copy of the License at | ||
628 | 6 | # | ||
629 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
630 | 8 | # | ||
631 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
632 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
633 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
634 | 12 | # See the License for the specific language governing permissions and | ||
635 | 13 | # limitations under the License. | ||
636 | 14 | |||
637 | 15 | # Copyright 2013 Canonical Ltd. | ||
638 | 16 | # | ||
639 | 17 | # Authors: | ||
640 | 18 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
641 | 19 | """A helper to create a yaml cache of config with namespaced relation data.""" | ||
642 | 20 | import os | ||
643 | 21 | import yaml | ||
644 | 22 | |||
645 | 23 | import six | ||
646 | 24 | |||
647 | 25 | import charmhelpers.core.hookenv | ||
648 | 26 | |||
649 | 27 | |||
650 | 28 | charm_dir = os.environ.get('CHARM_DIR', '') | ||
651 | 29 | |||
652 | 30 | |||
653 | 31 | def dict_keys_without_hyphens(a_dict): | ||
654 | 32 | """Return the a new dict with underscores instead of hyphens in keys.""" | ||
655 | 33 | return dict( | ||
656 | 34 | (key.replace('-', '_'), val) for key, val in a_dict.items()) | ||
657 | 35 | |||
658 | 36 | |||
659 | 37 | def update_relations(context, namespace_separator=':'): | ||
660 | 38 | """Update the context with the relation data.""" | ||
661 | 39 | # Add any relation data prefixed with the relation type. | ||
662 | 40 | relation_type = charmhelpers.core.hookenv.relation_type() | ||
663 | 41 | relations = [] | ||
664 | 42 | context['current_relation'] = {} | ||
665 | 43 | if relation_type is not None: | ||
666 | 44 | relation_data = charmhelpers.core.hookenv.relation_get() | ||
667 | 45 | context['current_relation'] = relation_data | ||
668 | 46 | # Deprecated: the following use of relation data as keys | ||
669 | 47 | # directly in the context will be removed. | ||
670 | 48 | relation_data = dict( | ||
671 | 49 | ("{relation_type}{namespace_separator}{key}".format( | ||
672 | 50 | relation_type=relation_type, | ||
673 | 51 | key=key, | ||
674 | 52 | namespace_separator=namespace_separator), val) | ||
675 | 53 | for key, val in relation_data.items()) | ||
676 | 54 | relation_data = dict_keys_without_hyphens(relation_data) | ||
677 | 55 | context.update(relation_data) | ||
678 | 56 | relations = charmhelpers.core.hookenv.relations_of_type(relation_type) | ||
679 | 57 | relations = [dict_keys_without_hyphens(rel) for rel in relations] | ||
680 | 58 | |||
681 | 59 | context['relations_full'] = charmhelpers.core.hookenv.relations() | ||
682 | 60 | |||
683 | 61 | # the hookenv.relations() data structure is effectively unusable in | ||
684 | 62 | # templates and other contexts when trying to access relation data other | ||
685 | 63 | # than the current relation. So provide a more useful structure that works | ||
686 | 64 | # with any hook. | ||
687 | 65 | local_unit = charmhelpers.core.hookenv.local_unit() | ||
688 | 66 | relations = {} | ||
689 | 67 | for rname, rids in context['relations_full'].items(): | ||
690 | 68 | relations[rname] = [] | ||
691 | 69 | for rid, rdata in rids.items(): | ||
692 | 70 | data = rdata.copy() | ||
693 | 71 | if local_unit in rdata: | ||
694 | 72 | data.pop(local_unit) | ||
695 | 73 | for unit_name, rel_data in data.items(): | ||
696 | 74 | new_data = {'__relid__': rid, '__unit__': unit_name} | ||
697 | 75 | new_data.update(rel_data) | ||
698 | 76 | relations[rname].append(new_data) | ||
699 | 77 | context['relations'] = relations | ||
700 | 78 | |||
701 | 79 | |||
702 | 80 | def juju_state_to_yaml(yaml_path, namespace_separator=':', | ||
703 | 81 | allow_hyphens_in_keys=True, mode=None): | ||
704 | 82 | """Update the juju config and state in a yaml file. | ||
705 | 83 | |||
706 | 84 | This includes any current relation-get data, and the charm | ||
707 | 85 | directory. | ||
708 | 86 | |||
709 | 87 | This function was created for the ansible and saltstack | ||
710 | 88 | support, as those libraries can use a yaml file to supply | ||
711 | 89 | context to templates, but it may be useful generally to | ||
712 | 90 | create and update an on-disk cache of all the config, including | ||
713 | 91 | previous relation data. | ||
714 | 92 | |||
715 | 93 | By default, hyphens are allowed in keys as this is supported | ||
716 | 94 | by yaml, but for tools like ansible, hyphens are not valid [1]. | ||
717 | 95 | |||
718 | 96 | [1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name | ||
719 | 97 | """ | ||
720 | 98 | config = charmhelpers.core.hookenv.config() | ||
721 | 99 | |||
722 | 100 | # Add the charm_dir which we will need to refer to charm | ||
723 | 101 | # file resources etc. | ||
724 | 102 | config['charm_dir'] = charm_dir | ||
725 | 103 | config['local_unit'] = charmhelpers.core.hookenv.local_unit() | ||
726 | 104 | config['unit_private_address'] = charmhelpers.core.hookenv.unit_private_ip() | ||
727 | 105 | config['unit_public_address'] = charmhelpers.core.hookenv.unit_get( | ||
728 | 106 | 'public-address' | ||
729 | 107 | ) | ||
730 | 108 | |||
731 | 109 | # Don't use non-standard tags for unicode which will not | ||
732 | 110 | # work when salt uses yaml.load_safe. | ||
733 | 111 | yaml.add_representer(six.text_type, | ||
734 | 112 | lambda dumper, value: dumper.represent_scalar( | ||
735 | 113 | six.u('tag:yaml.org,2002:str'), value)) | ||
736 | 114 | |||
737 | 115 | yaml_dir = os.path.dirname(yaml_path) | ||
738 | 116 | if not os.path.exists(yaml_dir): | ||
739 | 117 | os.makedirs(yaml_dir) | ||
740 | 118 | |||
741 | 119 | if os.path.exists(yaml_path): | ||
742 | 120 | with open(yaml_path, "r") as existing_vars_file: | ||
743 | 121 | existing_vars = yaml.load(existing_vars_file.read()) | ||
744 | 122 | else: | ||
745 | 123 | with open(yaml_path, "w+"): | ||
746 | 124 | pass | ||
747 | 125 | existing_vars = {} | ||
748 | 126 | |||
749 | 127 | if mode is not None: | ||
750 | 128 | os.chmod(yaml_path, mode) | ||
751 | 129 | |||
752 | 130 | if not allow_hyphens_in_keys: | ||
753 | 131 | config = dict_keys_without_hyphens(config) | ||
754 | 132 | existing_vars.update(config) | ||
755 | 133 | |||
756 | 134 | update_relations(existing_vars, namespace_separator) | ||
757 | 135 | |||
758 | 136 | with open(yaml_path, "w+") as fp: | ||
759 | 137 | fp.write(yaml.dump(existing_vars, default_flow_style=False)) | ||
760 | diff --git a/hooks/charmhelpers/core/__init__.py b/hooks/charmhelpers/core/__init__.py | |||
761 | 0 | new file mode 100644 | 138 | new file mode 100644 |
762 | index 0000000..d7567b8 | |||
763 | --- /dev/null | |||
764 | +++ b/hooks/charmhelpers/core/__init__.py | |||
765 | @@ -0,0 +1,13 @@ | |||
766 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
767 | 2 | # | ||
768 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
769 | 4 | # you may not use this file except in compliance with the License. | ||
770 | 5 | # You may obtain a copy of the License at | ||
771 | 6 | # | ||
772 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
773 | 8 | # | ||
774 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
775 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
776 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
777 | 12 | # See the License for the specific language governing permissions and | ||
778 | 13 | # limitations under the License. | ||
779 | diff --git a/hooks/charmhelpers/core/decorators.py b/hooks/charmhelpers/core/decorators.py | |||
780 | 0 | new file mode 100644 | 14 | new file mode 100644 |
781 | index 0000000..6ad41ee | |||
782 | --- /dev/null | |||
783 | +++ b/hooks/charmhelpers/core/decorators.py | |||
784 | @@ -0,0 +1,55 @@ | |||
785 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
786 | 2 | # | ||
787 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
788 | 4 | # you may not use this file except in compliance with the License. | ||
789 | 5 | # You may obtain a copy of the License at | ||
790 | 6 | # | ||
791 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
792 | 8 | # | ||
793 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
794 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
795 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
796 | 12 | # See the License for the specific language governing permissions and | ||
797 | 13 | # limitations under the License. | ||
798 | 14 | |||
799 | 15 | # | ||
800 | 16 | # Copyright 2014 Canonical Ltd. | ||
801 | 17 | # | ||
802 | 18 | # Authors: | ||
803 | 19 | # Edward Hope-Morley <opentastic@gmail.com> | ||
804 | 20 | # | ||
805 | 21 | |||
806 | 22 | import time | ||
807 | 23 | |||
808 | 24 | from charmhelpers.core.hookenv import ( | ||
809 | 25 | log, | ||
810 | 26 | INFO, | ||
811 | 27 | ) | ||
812 | 28 | |||
813 | 29 | |||
814 | 30 | def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): | ||
815 | 31 | """If the decorated function raises exception exc_type, allow num_retries | ||
816 | 32 | retry attempts before raise the exception. | ||
817 | 33 | """ | ||
818 | 34 | def _retry_on_exception_inner_1(f): | ||
819 | 35 | def _retry_on_exception_inner_2(*args, **kwargs): | ||
820 | 36 | retries = num_retries | ||
821 | 37 | multiplier = 1 | ||
822 | 38 | while True: | ||
823 | 39 | try: | ||
824 | 40 | return f(*args, **kwargs) | ||
825 | 41 | except exc_type: | ||
826 | 42 | if not retries: | ||
827 | 43 | raise | ||
828 | 44 | |||
829 | 45 | delay = base_delay * multiplier | ||
830 | 46 | multiplier += 1 | ||
831 | 47 | log("Retrying '%s' %d more times (delay=%s)" % | ||
832 | 48 | (f.__name__, retries, delay), level=INFO) | ||
833 | 49 | retries -= 1 | ||
834 | 50 | if delay: | ||
835 | 51 | time.sleep(delay) | ||
836 | 52 | |||
837 | 53 | return _retry_on_exception_inner_2 | ||
838 | 54 | |||
839 | 55 | return _retry_on_exception_inner_1 | ||
840 | diff --git a/hooks/charmhelpers/core/files.py b/hooks/charmhelpers/core/files.py | |||
841 | 0 | new file mode 100644 | 56 | new file mode 100644 |
842 | index 0000000..fdd82b7 | |||
843 | --- /dev/null | |||
844 | +++ b/hooks/charmhelpers/core/files.py | |||
845 | @@ -0,0 +1,43 @@ | |||
846 | 1 | #!/usr/bin/env python | ||
847 | 2 | # -*- coding: utf-8 -*- | ||
848 | 3 | |||
849 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
850 | 5 | # | ||
851 | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
852 | 7 | # you may not use this file except in compliance with the License. | ||
853 | 8 | # You may obtain a copy of the License at | ||
854 | 9 | # | ||
855 | 10 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
856 | 11 | # | ||
857 | 12 | # Unless required by applicable law or agreed to in writing, software | ||
858 | 13 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
859 | 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
860 | 15 | # See the License for the specific language governing permissions and | ||
861 | 16 | # limitations under the License. | ||
862 | 17 | |||
863 | 18 | __author__ = 'Jorge Niedbalski <niedbalski@ubuntu.com>' | ||
864 | 19 | |||
865 | 20 | import os | ||
866 | 21 | import subprocess | ||
867 | 22 | |||
868 | 23 | |||
869 | 24 | def sed(filename, before, after, flags='g'): | ||
870 | 25 | """ | ||
871 | 26 | Search and replaces the given pattern on filename. | ||
872 | 27 | |||
873 | 28 | :param filename: relative or absolute file path. | ||
874 | 29 | :param before: expression to be replaced (see 'man sed') | ||
875 | 30 | :param after: expression to replace with (see 'man sed') | ||
876 | 31 | :param flags: sed-compatible regex flags in example, to make | ||
877 | 32 | the search and replace case insensitive, specify ``flags="i"``. | ||
878 | 33 | The ``g`` flag is always specified regardless, so you do not | ||
879 | 34 | need to remember to include it when overriding this parameter. | ||
880 | 35 | :returns: If the sed command exit code was zero then return, | ||
881 | 36 | otherwise raise CalledProcessError. | ||
882 | 37 | """ | ||
883 | 38 | expression = r's/{0}/{1}/{2}'.format(before, | ||
884 | 39 | after, flags) | ||
885 | 40 | |||
886 | 41 | return subprocess.check_call(["sed", "-i", "-r", "-e", | ||
887 | 42 | expression, | ||
888 | 43 | os.path.expanduser(filename)]) | ||
889 | diff --git a/hooks/charmhelpers/core/fstab.py b/hooks/charmhelpers/core/fstab.py | |||
890 | 0 | new file mode 100644 | 44 | new file mode 100644 |
891 | index 0000000..d9fa915 | |||
892 | --- /dev/null | |||
893 | +++ b/hooks/charmhelpers/core/fstab.py | |||
894 | @@ -0,0 +1,132 @@ | |||
895 | 1 | #!/usr/bin/env python | ||
896 | 2 | # -*- coding: utf-8 -*- | ||
897 | 3 | |||
898 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
899 | 5 | # | ||
900 | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
901 | 7 | # you may not use this file except in compliance with the License. | ||
902 | 8 | # You may obtain a copy of the License at | ||
903 | 9 | # | ||
904 | 10 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
905 | 11 | # | ||
906 | 12 | # Unless required by applicable law or agreed to in writing, software | ||
907 | 13 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
908 | 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
909 | 15 | # See the License for the specific language governing permissions and | ||
910 | 16 | # limitations under the License. | ||
911 | 17 | |||
912 | 18 | import io | ||
913 | 19 | import os | ||
914 | 20 | |||
915 | 21 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
916 | 22 | |||
917 | 23 | |||
918 | 24 | class Fstab(io.FileIO): | ||
919 | 25 | """This class extends file in order to implement a file reader/writer | ||
920 | 26 | for file `/etc/fstab` | ||
921 | 27 | """ | ||
922 | 28 | |||
923 | 29 | class Entry(object): | ||
924 | 30 | """Entry class represents a non-comment line on the `/etc/fstab` file | ||
925 | 31 | """ | ||
926 | 32 | def __init__(self, device, mountpoint, filesystem, | ||
927 | 33 | options, d=0, p=0): | ||
928 | 34 | self.device = device | ||
929 | 35 | self.mountpoint = mountpoint | ||
930 | 36 | self.filesystem = filesystem | ||
931 | 37 | |||
932 | 38 | if not options: | ||
933 | 39 | options = "defaults" | ||
934 | 40 | |||
935 | 41 | self.options = options | ||
936 | 42 | self.d = int(d) | ||
937 | 43 | self.p = int(p) | ||
938 | 44 | |||
939 | 45 | def __eq__(self, o): | ||
940 | 46 | return str(self) == str(o) | ||
941 | 47 | |||
942 | 48 | def __str__(self): | ||
943 | 49 | return "{} {} {} {} {} {}".format(self.device, | ||
944 | 50 | self.mountpoint, | ||
945 | 51 | self.filesystem, | ||
946 | 52 | self.options, | ||
947 | 53 | self.d, | ||
948 | 54 | self.p) | ||
949 | 55 | |||
950 | 56 | DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab') | ||
951 | 57 | |||
952 | 58 | def __init__(self, path=None): | ||
953 | 59 | if path: | ||
954 | 60 | self._path = path | ||
955 | 61 | else: | ||
956 | 62 | self._path = self.DEFAULT_PATH | ||
957 | 63 | super(Fstab, self).__init__(self._path, 'rb+') | ||
958 | 64 | |||
959 | 65 | def _hydrate_entry(self, line): | ||
960 | 66 | # NOTE: use split with no arguments to split on any | ||
961 | 67 | # whitespace including tabs | ||
962 | 68 | return Fstab.Entry(*filter( | ||
963 | 69 | lambda x: x not in ('', None), | ||
964 | 70 | line.strip("\n").split())) | ||
965 | 71 | |||
966 | 72 | @property | ||
967 | 73 | def entries(self): | ||
968 | 74 | self.seek(0) | ||
969 | 75 | for line in self.readlines(): | ||
970 | 76 | line = line.decode('us-ascii') | ||
971 | 77 | try: | ||
972 | 78 | if line.strip() and not line.strip().startswith("#"): | ||
973 | 79 | yield self._hydrate_entry(line) | ||
974 | 80 | except ValueError: | ||
975 | 81 | pass | ||
976 | 82 | |||
977 | 83 | def get_entry_by_attr(self, attr, value): | ||
978 | 84 | for entry in self.entries: | ||
979 | 85 | e_attr = getattr(entry, attr) | ||
980 | 86 | if e_attr == value: | ||
981 | 87 | return entry | ||
982 | 88 | return None | ||
983 | 89 | |||
984 | 90 | def add_entry(self, entry): | ||
985 | 91 | if self.get_entry_by_attr('device', entry.device): | ||
986 | 92 | return False | ||
987 | 93 | |||
988 | 94 | self.write((str(entry) + '\n').encode('us-ascii')) | ||
989 | 95 | self.truncate() | ||
990 | 96 | return entry | ||
991 | 97 | |||
992 | 98 | def remove_entry(self, entry): | ||
993 | 99 | self.seek(0) | ||
994 | 100 | |||
995 | 101 | lines = [l.decode('us-ascii') for l in self.readlines()] | ||
996 | 102 | |||
997 | 103 | found = False | ||
998 | 104 | for index, line in enumerate(lines): | ||
999 | 105 | if line.strip() and not line.strip().startswith("#"): | ||
1000 | 106 | if self._hydrate_entry(line) == entry: | ||
1001 | 107 | found = True | ||
1002 | 108 | break | ||
1003 | 109 | |||
1004 | 110 | if not found: | ||
1005 | 111 | return False | ||
1006 | 112 | |||
1007 | 113 | lines.remove(line) | ||
1008 | 114 | |||
1009 | 115 | self.seek(0) | ||
1010 | 116 | self.write(''.join(lines).encode('us-ascii')) | ||
1011 | 117 | self.truncate() | ||
1012 | 118 | return True | ||
1013 | 119 | |||
1014 | 120 | @classmethod | ||
1015 | 121 | def remove_by_mountpoint(cls, mountpoint, path=None): | ||
1016 | 122 | fstab = cls(path=path) | ||
1017 | 123 | entry = fstab.get_entry_by_attr('mountpoint', mountpoint) | ||
1018 | 124 | if entry: | ||
1019 | 125 | return fstab.remove_entry(entry) | ||
1020 | 126 | return False | ||
1021 | 127 | |||
1022 | 128 | @classmethod | ||
1023 | 129 | def add(cls, device, mountpoint, filesystem, options=None, path=None): | ||
1024 | 130 | return cls(path=path).add_entry(Fstab.Entry(device, | ||
1025 | 131 | mountpoint, filesystem, | ||
1026 | 132 | options=options)) | ||
1027 | diff --git a/hooks/charmhelpers/core/hookenv.py b/hooks/charmhelpers/core/hookenv.py | |||
1028 | 0 | new file mode 100644 | 133 | new file mode 100644 |
1029 | index 0000000..e44e22b | |||
1030 | --- /dev/null | |||
1031 | +++ b/hooks/charmhelpers/core/hookenv.py | |||
1032 | @@ -0,0 +1,1068 @@ | |||
1033 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1034 | 2 | # | ||
1035 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
1036 | 4 | # you may not use this file except in compliance with the License. | ||
1037 | 5 | # You may obtain a copy of the License at | ||
1038 | 6 | # | ||
1039 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
1040 | 8 | # | ||
1041 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
1042 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
1043 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
1044 | 12 | # See the License for the specific language governing permissions and | ||
1045 | 13 | # limitations under the License. | ||
1046 | 14 | |||
1047 | 15 | "Interactions with the Juju environment" | ||
1048 | 16 | # Copyright 2013 Canonical Ltd. | ||
1049 | 17 | # | ||
1050 | 18 | # Authors: | ||
1051 | 19 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
1052 | 20 | |||
1053 | 21 | from __future__ import print_function | ||
1054 | 22 | import copy | ||
1055 | 23 | from distutils.version import LooseVersion | ||
1056 | 24 | from functools import wraps | ||
1057 | 25 | import glob | ||
1058 | 26 | import os | ||
1059 | 27 | import json | ||
1060 | 28 | import yaml | ||
1061 | 29 | import subprocess | ||
1062 | 30 | import sys | ||
1063 | 31 | import errno | ||
1064 | 32 | import tempfile | ||
1065 | 33 | from subprocess import CalledProcessError | ||
1066 | 34 | |||
1067 | 35 | import six | ||
1068 | 36 | if not six.PY3: | ||
1069 | 37 | from UserDict import UserDict | ||
1070 | 38 | else: | ||
1071 | 39 | from collections import UserDict | ||
1072 | 40 | |||
1073 | 41 | CRITICAL = "CRITICAL" | ||
1074 | 42 | ERROR = "ERROR" | ||
1075 | 43 | WARNING = "WARNING" | ||
1076 | 44 | INFO = "INFO" | ||
1077 | 45 | DEBUG = "DEBUG" | ||
1078 | 46 | MARKER = object() | ||
1079 | 47 | |||
1080 | 48 | cache = {} | ||
1081 | 49 | |||
1082 | 50 | |||
1083 | 51 | def cached(func): | ||
1084 | 52 | """Cache return values for multiple executions of func + args | ||
1085 | 53 | |||
1086 | 54 | For example:: | ||
1087 | 55 | |||
1088 | 56 | @cached | ||
1089 | 57 | def unit_get(attribute): | ||
1090 | 58 | pass | ||
1091 | 59 | |||
1092 | 60 | unit_get('test') | ||
1093 | 61 | |||
1094 | 62 | will cache the result of unit_get + 'test' for future calls. | ||
1095 | 63 | """ | ||
1096 | 64 | @wraps(func) | ||
1097 | 65 | def wrapper(*args, **kwargs): | ||
1098 | 66 | global cache | ||
1099 | 67 | key = str((func, args, kwargs)) | ||
1100 | 68 | try: | ||
1101 | 69 | return cache[key] | ||
1102 | 70 | except KeyError: | ||
1103 | 71 | pass # Drop out of the exception handler scope. | ||
1104 | 72 | res = func(*args, **kwargs) | ||
1105 | 73 | cache[key] = res | ||
1106 | 74 | return res | ||
1107 | 75 | wrapper._wrapped = func | ||
1108 | 76 | return wrapper | ||
1109 | 77 | |||
1110 | 78 | |||
1111 | 79 | def flush(key): | ||
1112 | 80 | """Flushes any entries from function cache where the | ||
1113 | 81 | key is found in the function+args """ | ||
1114 | 82 | flush_list = [] | ||
1115 | 83 | for item in cache: | ||
1116 | 84 | if key in item: | ||
1117 | 85 | flush_list.append(item) | ||
1118 | 86 | for item in flush_list: | ||
1119 | 87 | del cache[item] | ||
1120 | 88 | |||
1121 | 89 | |||
1122 | 90 | def log(message, level=None): | ||
1123 | 91 | """Write a message to the juju log""" | ||
1124 | 92 | command = ['juju-log'] | ||
1125 | 93 | if level: | ||
1126 | 94 | command += ['-l', level] | ||
1127 | 95 | if not isinstance(message, six.string_types): | ||
1128 | 96 | message = repr(message) | ||
1129 | 97 | command += [message] | ||
1130 | 98 | # Missing juju-log should not cause failures in unit tests | ||
1131 | 99 | # Send log output to stderr | ||
1132 | 100 | try: | ||
1133 | 101 | subprocess.call(command) | ||
1134 | 102 | except OSError as e: | ||
1135 | 103 | if e.errno == errno.ENOENT: | ||
1136 | 104 | if level: | ||
1137 | 105 | message = "{}: {}".format(level, message) | ||
1138 | 106 | message = "juju-log: {}".format(message) | ||
1139 | 107 | print(message, file=sys.stderr) | ||
1140 | 108 | else: | ||
1141 | 109 | raise | ||
1142 | 110 | |||
1143 | 111 | |||
1144 | 112 | class Serializable(UserDict): | ||
1145 | 113 | """Wrapper, an object that can be serialized to yaml or json""" | ||
1146 | 114 | |||
1147 | 115 | def __init__(self, obj): | ||
1148 | 116 | # wrap the object | ||
1149 | 117 | UserDict.__init__(self) | ||
1150 | 118 | self.data = obj | ||
1151 | 119 | |||
1152 | 120 | def __getattr__(self, attr): | ||
1153 | 121 | # See if this object has attribute. | ||
1154 | 122 | if attr in ("json", "yaml", "data"): | ||
1155 | 123 | return self.__dict__[attr] | ||
1156 | 124 | # Check for attribute in wrapped object. | ||
1157 | 125 | got = getattr(self.data, attr, MARKER) | ||
1158 | 126 | if got is not MARKER: | ||
1159 | 127 | return got | ||
1160 | 128 | # Proxy to the wrapped object via dict interface. | ||
1161 | 129 | try: | ||
1162 | 130 | return self.data[attr] | ||
1163 | 131 | except KeyError: | ||
1164 | 132 | raise AttributeError(attr) | ||
1165 | 133 | |||
1166 | 134 | def __getstate__(self): | ||
1167 | 135 | # Pickle as a standard dictionary. | ||
1168 | 136 | return self.data | ||
1169 | 137 | |||
1170 | 138 | def __setstate__(self, state): | ||
1171 | 139 | # Unpickle into our wrapper. | ||
1172 | 140 | self.data = state | ||
1173 | 141 | |||
1174 | 142 | def json(self): | ||
1175 | 143 | """Serialize the object to json""" | ||
1176 | 144 | return json.dumps(self.data) | ||
1177 | 145 | |||
1178 | 146 | def yaml(self): | ||
1179 | 147 | """Serialize the object to yaml""" | ||
1180 | 148 | return yaml.dump(self.data) | ||
1181 | 149 | |||
1182 | 150 | |||
1183 | 151 | def execution_environment(): | ||
1184 | 152 | """A convenient bundling of the current execution context""" | ||
1185 | 153 | context = {} | ||
1186 | 154 | context['conf'] = config() | ||
1187 | 155 | if relation_id(): | ||
1188 | 156 | context['reltype'] = relation_type() | ||
1189 | 157 | context['relid'] = relation_id() | ||
1190 | 158 | context['rel'] = relation_get() | ||
1191 | 159 | context['unit'] = local_unit() | ||
1192 | 160 | context['rels'] = relations() | ||
1193 | 161 | context['env'] = os.environ | ||
1194 | 162 | return context | ||
1195 | 163 | |||
1196 | 164 | |||
1197 | 165 | def in_relation_hook(): | ||
1198 | 166 | """Determine whether we're running in a relation hook""" | ||
1199 | 167 | return 'JUJU_RELATION' in os.environ | ||
1200 | 168 | |||
1201 | 169 | |||
1202 | 170 | def relation_type(): | ||
1203 | 171 | """The scope for the current relation hook""" | ||
1204 | 172 | return os.environ.get('JUJU_RELATION', None) | ||
1205 | 173 | |||
1206 | 174 | |||
1207 | 175 | @cached | ||
1208 | 176 | def relation_id(relation_name=None, service_or_unit=None): | ||
1209 | 177 | """The relation ID for the current or a specified relation""" | ||
1210 | 178 | if not relation_name and not service_or_unit: | ||
1211 | 179 | return os.environ.get('JUJU_RELATION_ID', None) | ||
1212 | 180 | elif relation_name and service_or_unit: | ||
1213 | 181 | service_name = service_or_unit.split('/')[0] | ||
1214 | 182 | for relid in relation_ids(relation_name): | ||
1215 | 183 | remote_service = remote_service_name(relid) | ||
1216 | 184 | if remote_service == service_name: | ||
1217 | 185 | return relid | ||
1218 | 186 | else: | ||
1219 | 187 | raise ValueError('Must specify neither or both of relation_name and service_or_unit') | ||
1220 | 188 | |||
1221 | 189 | |||
1222 | 190 | def local_unit(): | ||
1223 | 191 | """Local unit ID""" | ||
1224 | 192 | return os.environ['JUJU_UNIT_NAME'] | ||
1225 | 193 | |||
1226 | 194 | |||
1227 | 195 | def remote_unit(): | ||
1228 | 196 | """The remote unit for the current relation hook""" | ||
1229 | 197 | return os.environ.get('JUJU_REMOTE_UNIT', None) | ||
1230 | 198 | |||
1231 | 199 | |||
1232 | 200 | def service_name(): | ||
1233 | 201 | """The name service group this unit belongs to""" | ||
1234 | 202 | return local_unit().split('/')[0] | ||
1235 | 203 | |||
1236 | 204 | |||
1237 | 205 | @cached | ||
1238 | 206 | def remote_service_name(relid=None): | ||
1239 | 207 | """The remote service name for a given relation-id (or the current relation)""" | ||
1240 | 208 | if relid is None: | ||
1241 | 209 | unit = remote_unit() | ||
1242 | 210 | else: | ||
1243 | 211 | units = related_units(relid) | ||
1244 | 212 | unit = units[0] if units else None | ||
1245 | 213 | return unit.split('/')[0] if unit else None | ||
1246 | 214 | |||
1247 | 215 | |||
1248 | 216 | def hook_name(): | ||
1249 | 217 | """The name of the currently executing hook""" | ||
1250 | 218 | return os.environ.get('JUJU_HOOK_NAME', os.path.basename(sys.argv[0])) | ||
1251 | 219 | |||
1252 | 220 | |||
1253 | 221 | class Config(dict): | ||
1254 | 222 | """A dictionary representation of the charm's config.yaml, with some | ||
1255 | 223 | extra features: | ||
1256 | 224 | |||
1257 | 225 | - See which values in the dictionary have changed since the previous hook. | ||
1258 | 226 | - For values that have changed, see what the previous value was. | ||
1259 | 227 | - Store arbitrary data for use in a later hook. | ||
1260 | 228 | |||
1261 | 229 | NOTE: Do not instantiate this object directly - instead call | ||
1262 | 230 | ``hookenv.config()``, which will return an instance of :class:`Config`. | ||
1263 | 231 | |||
1264 | 232 | Example usage:: | ||
1265 | 233 | |||
1266 | 234 | >>> # inside a hook | ||
1267 | 235 | >>> from charmhelpers.core import hookenv | ||
1268 | 236 | >>> config = hookenv.config() | ||
1269 | 237 | >>> config['foo'] | ||
1270 | 238 | 'bar' | ||
1271 | 239 | >>> # store a new key/value for later use | ||
1272 | 240 | >>> config['mykey'] = 'myval' | ||
1273 | 241 | |||
1274 | 242 | |||
1275 | 243 | >>> # user runs `juju set mycharm foo=baz` | ||
1276 | 244 | >>> # now we're inside subsequent config-changed hook | ||
1277 | 245 | >>> config = hookenv.config() | ||
1278 | 246 | >>> config['foo'] | ||
1279 | 247 | 'baz' | ||
1280 | 248 | >>> # test to see if this val has changed since last hook | ||
1281 | 249 | >>> config.changed('foo') | ||
1282 | 250 | True | ||
1283 | 251 | >>> # what was the previous value? | ||
1284 | 252 | >>> config.previous('foo') | ||
1285 | 253 | 'bar' | ||
1286 | 254 | >>> # keys/values that we add are preserved across hooks | ||
1287 | 255 | >>> config['mykey'] | ||
1288 | 256 | 'myval' | ||
1289 | 257 | |||
1290 | 258 | """ | ||
1291 | 259 | CONFIG_FILE_NAME = '.juju-persistent-config' | ||
1292 | 260 | |||
1293 | 261 | def __init__(self, *args, **kw): | ||
1294 | 262 | super(Config, self).__init__(*args, **kw) | ||
1295 | 263 | self.implicit_save = True | ||
1296 | 264 | self._prev_dict = None | ||
1297 | 265 | self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME) | ||
1298 | 266 | if os.path.exists(self.path): | ||
1299 | 267 | self.load_previous() | ||
1300 | 268 | atexit(self._implicit_save) | ||
1301 | 269 | |||
1302 | 270 | def load_previous(self, path=None): | ||
1303 | 271 | """Load previous copy of config from disk. | ||
1304 | 272 | |||
1305 | 273 | In normal usage you don't need to call this method directly - it | ||
1306 | 274 | is called automatically at object initialization. | ||
1307 | 275 | |||
1308 | 276 | :param path: | ||
1309 | 277 | |||
1310 | 278 | File path from which to load the previous config. If `None`, | ||
1311 | 279 | config is loaded from the default location. If `path` is | ||
1312 | 280 | specified, subsequent `save()` calls will write to the same | ||
1313 | 281 | path. | ||
1314 | 282 | |||
1315 | 283 | """ | ||
1316 | 284 | self.path = path or self.path | ||
1317 | 285 | with open(self.path) as f: | ||
1318 | 286 | self._prev_dict = json.load(f) | ||
1319 | 287 | for k, v in copy.deepcopy(self._prev_dict).items(): | ||
1320 | 288 | if k not in self: | ||
1321 | 289 | self[k] = v | ||
1322 | 290 | |||
1323 | 291 | def changed(self, key): | ||
1324 | 292 | """Return True if the current value for this key is different from | ||
1325 | 293 | the previous value. | ||
1326 | 294 | |||
1327 | 295 | """ | ||
1328 | 296 | if self._prev_dict is None: | ||
1329 | 297 | return True | ||
1330 | 298 | return self.previous(key) != self.get(key) | ||
1331 | 299 | |||
1332 | 300 | def previous(self, key): | ||
1333 | 301 | """Return previous value for this key, or None if there | ||
1334 | 302 | is no previous value. | ||
1335 | 303 | |||
1336 | 304 | """ | ||
1337 | 305 | if self._prev_dict: | ||
1338 | 306 | return self._prev_dict.get(key) | ||
1339 | 307 | return None | ||
1340 | 308 | |||
1341 | 309 | def save(self): | ||
1342 | 310 | """Save this config to disk. | ||
1343 | 311 | |||
1344 | 312 | If the charm is using the :mod:`Services Framework <services.base>` | ||
1345 | 313 | or :meth:'@hook <Hooks.hook>' decorator, this | ||
1346 | 314 | is called automatically at the end of successful hook execution. | ||
1347 | 315 | Otherwise, it should be called directly by user code. | ||
1348 | 316 | |||
1349 | 317 | To disable automatic saves, set ``implicit_save=False`` on this | ||
1350 | 318 | instance. | ||
1351 | 319 | |||
1352 | 320 | """ | ||
1353 | 321 | with open(self.path, 'w') as f: | ||
1354 | 322 | json.dump(self, f) | ||
1355 | 323 | |||
1356 | 324 | def _implicit_save(self): | ||
1357 | 325 | if self.implicit_save: | ||
1358 | 326 | self.save() | ||
1359 | 327 | |||
1360 | 328 | |||
1361 | 329 | @cached | ||
1362 | 330 | def config(scope=None): | ||
1363 | 331 | """Juju charm configuration""" | ||
1364 | 332 | config_cmd_line = ['config-get'] | ||
1365 | 333 | if scope is not None: | ||
1366 | 334 | config_cmd_line.append(scope) | ||
1367 | 335 | else: | ||
1368 | 336 | config_cmd_line.append('--all') | ||
1369 | 337 | config_cmd_line.append('--format=json') | ||
1370 | 338 | try: | ||
1371 | 339 | config_data = json.loads( | ||
1372 | 340 | subprocess.check_output(config_cmd_line).decode('UTF-8')) | ||
1373 | 341 | if scope is not None: | ||
1374 | 342 | return config_data | ||
1375 | 343 | return Config(config_data) | ||
1376 | 344 | except ValueError: | ||
1377 | 345 | return None | ||
1378 | 346 | |||
1379 | 347 | |||
1380 | 348 | @cached | ||
1381 | 349 | def relation_get(attribute=None, unit=None, rid=None): | ||
1382 | 350 | """Get relation information""" | ||
1383 | 351 | _args = ['relation-get', '--format=json'] | ||
1384 | 352 | if rid: | ||
1385 | 353 | _args.append('-r') | ||
1386 | 354 | _args.append(rid) | ||
1387 | 355 | _args.append(attribute or '-') | ||
1388 | 356 | if unit: | ||
1389 | 357 | _args.append(unit) | ||
1390 | 358 | try: | ||
1391 | 359 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1392 | 360 | except ValueError: | ||
1393 | 361 | return None | ||
1394 | 362 | except CalledProcessError as e: | ||
1395 | 363 | if e.returncode == 2: | ||
1396 | 364 | return None | ||
1397 | 365 | raise | ||
1398 | 366 | |||
1399 | 367 | |||
1400 | 368 | def relation_set(relation_id=None, relation_settings=None, **kwargs): | ||
1401 | 369 | """Set relation information for the current unit""" | ||
1402 | 370 | relation_settings = relation_settings if relation_settings else {} | ||
1403 | 371 | relation_cmd_line = ['relation-set'] | ||
1404 | 372 | accepts_file = "--file" in subprocess.check_output( | ||
1405 | 373 | relation_cmd_line + ["--help"], universal_newlines=True) | ||
1406 | 374 | if relation_id is not None: | ||
1407 | 375 | relation_cmd_line.extend(('-r', relation_id)) | ||
1408 | 376 | settings = relation_settings.copy() | ||
1409 | 377 | settings.update(kwargs) | ||
1410 | 378 | for key, value in settings.items(): | ||
1411 | 379 | # Force value to be a string: it always should, but some call | ||
1412 | 380 | # sites pass in things like dicts or numbers. | ||
1413 | 381 | if value is not None: | ||
1414 | 382 | settings[key] = "{}".format(value) | ||
1415 | 383 | if accepts_file: | ||
1416 | 384 | # --file was introduced in Juju 1.23.2. Use it by default if | ||
1417 | 385 | # available, since otherwise we'll break if the relation data is | ||
1418 | 386 | # too big. Ideally we should tell relation-set to read the data from | ||
1419 | 387 | # stdin, but that feature is broken in 1.23.2: Bug #1454678. | ||
1420 | 388 | with tempfile.NamedTemporaryFile(delete=False) as settings_file: | ||
1421 | 389 | settings_file.write(yaml.safe_dump(settings).encode("utf-8")) | ||
1422 | 390 | subprocess.check_call( | ||
1423 | 391 | relation_cmd_line + ["--file", settings_file.name]) | ||
1424 | 392 | os.remove(settings_file.name) | ||
1425 | 393 | else: | ||
1426 | 394 | for key, value in settings.items(): | ||
1427 | 395 | if value is None: | ||
1428 | 396 | relation_cmd_line.append('{}='.format(key)) | ||
1429 | 397 | else: | ||
1430 | 398 | relation_cmd_line.append('{}={}'.format(key, value)) | ||
1431 | 399 | subprocess.check_call(relation_cmd_line) | ||
1432 | 400 | # Flush cache of any relation-gets for local unit | ||
1433 | 401 | flush(local_unit()) | ||
1434 | 402 | |||
1435 | 403 | |||
1436 | 404 | def relation_clear(r_id=None): | ||
1437 | 405 | ''' Clears any relation data already set on relation r_id ''' | ||
1438 | 406 | settings = relation_get(rid=r_id, | ||
1439 | 407 | unit=local_unit()) | ||
1440 | 408 | for setting in settings: | ||
1441 | 409 | if setting not in ['public-address', 'private-address']: | ||
1442 | 410 | settings[setting] = None | ||
1443 | 411 | relation_set(relation_id=r_id, | ||
1444 | 412 | **settings) | ||
1445 | 413 | |||
1446 | 414 | |||
1447 | 415 | @cached | ||
1448 | 416 | def relation_ids(reltype=None): | ||
1449 | 417 | """A list of relation_ids""" | ||
1450 | 418 | reltype = reltype or relation_type() | ||
1451 | 419 | relid_cmd_line = ['relation-ids', '--format=json'] | ||
1452 | 420 | if reltype is not None: | ||
1453 | 421 | relid_cmd_line.append(reltype) | ||
1454 | 422 | return json.loads( | ||
1455 | 423 | subprocess.check_output(relid_cmd_line).decode('UTF-8')) or [] | ||
1456 | 424 | return [] | ||
1457 | 425 | |||
1458 | 426 | |||
1459 | 427 | @cached | ||
1460 | 428 | def related_units(relid=None): | ||
1461 | 429 | """A list of related units""" | ||
1462 | 430 | relid = relid or relation_id() | ||
1463 | 431 | units_cmd_line = ['relation-list', '--format=json'] | ||
1464 | 432 | if relid is not None: | ||
1465 | 433 | units_cmd_line.extend(('-r', relid)) | ||
1466 | 434 | return json.loads( | ||
1467 | 435 | subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | ||
1468 | 436 | |||
1469 | 437 | |||
1470 | 438 | @cached | ||
1471 | 439 | def relation_for_unit(unit=None, rid=None): | ||
1472 | 440 | """Get the json represenation of a unit's relation""" | ||
1473 | 441 | unit = unit or remote_unit() | ||
1474 | 442 | relation = relation_get(unit=unit, rid=rid) | ||
1475 | 443 | for key in relation: | ||
1476 | 444 | if key.endswith('-list'): | ||
1477 | 445 | relation[key] = relation[key].split() | ||
1478 | 446 | relation['__unit__'] = unit | ||
1479 | 447 | return relation | ||
1480 | 448 | |||
1481 | 449 | |||
1482 | 450 | @cached | ||
1483 | 451 | def relations_for_id(relid=None): | ||
1484 | 452 | """Get relations of a specific relation ID""" | ||
1485 | 453 | relation_data = [] | ||
1486 | 454 | relid = relid or relation_ids() | ||
1487 | 455 | for unit in related_units(relid): | ||
1488 | 456 | unit_data = relation_for_unit(unit, relid) | ||
1489 | 457 | unit_data['__relid__'] = relid | ||
1490 | 458 | relation_data.append(unit_data) | ||
1491 | 459 | return relation_data | ||
1492 | 460 | |||
1493 | 461 | |||
1494 | 462 | @cached | ||
1495 | 463 | def relations_of_type(reltype=None): | ||
1496 | 464 | """Get relations of a specific type""" | ||
1497 | 465 | relation_data = [] | ||
1498 | 466 | reltype = reltype or relation_type() | ||
1499 | 467 | for relid in relation_ids(reltype): | ||
1500 | 468 | for relation in relations_for_id(relid): | ||
1501 | 469 | relation['__relid__'] = relid | ||
1502 | 470 | relation_data.append(relation) | ||
1503 | 471 | return relation_data | ||
1504 | 472 | |||
1505 | 473 | |||
1506 | 474 | @cached | ||
1507 | 475 | def metadata(): | ||
1508 | 476 | """Get the current charm metadata.yaml contents as a python object""" | ||
1509 | 477 | with open(os.path.join(charm_dir(), 'metadata.yaml')) as md: | ||
1510 | 478 | return yaml.safe_load(md) | ||
1511 | 479 | |||
1512 | 480 | |||
1513 | 481 | @cached | ||
1514 | 482 | def relation_types(): | ||
1515 | 483 | """Get a list of relation types supported by this charm""" | ||
1516 | 484 | rel_types = [] | ||
1517 | 485 | md = metadata() | ||
1518 | 486 | for key in ('provides', 'requires', 'peers'): | ||
1519 | 487 | section = md.get(key) | ||
1520 | 488 | if section: | ||
1521 | 489 | rel_types.extend(section.keys()) | ||
1522 | 490 | return rel_types | ||
1523 | 491 | |||
1524 | 492 | |||
1525 | 493 | @cached | ||
1526 | 494 | def peer_relation_id(): | ||
1527 | 495 | '''Get the peers relation id if a peers relation has been joined, else None.''' | ||
1528 | 496 | md = metadata() | ||
1529 | 497 | section = md.get('peers') | ||
1530 | 498 | if section: | ||
1531 | 499 | for key in section: | ||
1532 | 500 | relids = relation_ids(key) | ||
1533 | 501 | if relids: | ||
1534 | 502 | return relids[0] | ||
1535 | 503 | return None | ||
1536 | 504 | |||
1537 | 505 | |||
1538 | 506 | @cached | ||
1539 | 507 | def relation_to_interface(relation_name): | ||
1540 | 508 | """ | ||
1541 | 509 | Given the name of a relation, return the interface that relation uses. | ||
1542 | 510 | |||
1543 | 511 | :returns: The interface name, or ``None``. | ||
1544 | 512 | """ | ||
1545 | 513 | return relation_to_role_and_interface(relation_name)[1] | ||
1546 | 514 | |||
1547 | 515 | |||
1548 | 516 | @cached | ||
1549 | 517 | def relation_to_role_and_interface(relation_name): | ||
1550 | 518 | """ | ||
1551 | 519 | Given the name of a relation, return the role and the name of the interface | ||
1552 | 520 | that relation uses (where role is one of ``provides``, ``requires``, or ``peers``). | ||
1553 | 521 | |||
1554 | 522 | :returns: A tuple containing ``(role, interface)``, or ``(None, None)``. | ||
1555 | 523 | """ | ||
1556 | 524 | _metadata = metadata() | ||
1557 | 525 | for role in ('provides', 'requires', 'peers'): | ||
1558 | 526 | interface = _metadata.get(role, {}).get(relation_name, {}).get('interface') | ||
1559 | 527 | if interface: | ||
1560 | 528 | return role, interface | ||
1561 | 529 | return None, None | ||
1562 | 530 | |||
1563 | 531 | |||
1564 | 532 | @cached | ||
1565 | 533 | def role_and_interface_to_relations(role, interface_name): | ||
1566 | 534 | """ | ||
1567 | 535 | Given a role and interface name, return a list of relation names for the | ||
1568 | 536 | current charm that use that interface under that role (where role is one | ||
1569 | 537 | of ``provides``, ``requires``, or ``peers``). | ||
1570 | 538 | |||
1571 | 539 | :returns: A list of relation names. | ||
1572 | 540 | """ | ||
1573 | 541 | _metadata = metadata() | ||
1574 | 542 | results = [] | ||
1575 | 543 | for relation_name, relation in _metadata.get(role, {}).items(): | ||
1576 | 544 | if relation['interface'] == interface_name: | ||
1577 | 545 | results.append(relation_name) | ||
1578 | 546 | return results | ||
1579 | 547 | |||
1580 | 548 | |||
1581 | 549 | @cached | ||
1582 | 550 | def interface_to_relations(interface_name): | ||
1583 | 551 | """ | ||
1584 | 552 | Given an interface, return a list of relation names for the current | ||
1585 | 553 | charm that use that interface. | ||
1586 | 554 | |||
1587 | 555 | :returns: A list of relation names. | ||
1588 | 556 | """ | ||
1589 | 557 | results = [] | ||
1590 | 558 | for role in ('provides', 'requires', 'peers'): | ||
1591 | 559 | results.extend(role_and_interface_to_relations(role, interface_name)) | ||
1592 | 560 | return results | ||
1593 | 561 | |||
1594 | 562 | |||
1595 | 563 | @cached | ||
1596 | 564 | def charm_name(): | ||
1597 | 565 | """Get the name of the current charm as is specified on metadata.yaml""" | ||
1598 | 566 | return metadata().get('name') | ||
1599 | 567 | |||
1600 | 568 | |||
1601 | 569 | @cached | ||
1602 | 570 | def relations(): | ||
1603 | 571 | """Get a nested dictionary of relation data for all related units""" | ||
1604 | 572 | rels = {} | ||
1605 | 573 | for reltype in relation_types(): | ||
1606 | 574 | relids = {} | ||
1607 | 575 | for relid in relation_ids(reltype): | ||
1608 | 576 | units = {local_unit(): relation_get(unit=local_unit(), rid=relid)} | ||
1609 | 577 | for unit in related_units(relid): | ||
1610 | 578 | reldata = relation_get(unit=unit, rid=relid) | ||
1611 | 579 | units[unit] = reldata | ||
1612 | 580 | relids[relid] = units | ||
1613 | 581 | rels[reltype] = relids | ||
1614 | 582 | return rels | ||
1615 | 583 | |||
1616 | 584 | |||
1617 | 585 | @cached | ||
1618 | 586 | def is_relation_made(relation, keys='private-address'): | ||
1619 | 587 | ''' | ||
1620 | 588 | Determine whether a relation is established by checking for | ||
1621 | 589 | presence of key(s). If a list of keys is provided, they | ||
1622 | 590 | must all be present for the relation to be identified as made | ||
1623 | 591 | ''' | ||
1624 | 592 | if isinstance(keys, str): | ||
1625 | 593 | keys = [keys] | ||
1626 | 594 | for r_id in relation_ids(relation): | ||
1627 | 595 | for unit in related_units(r_id): | ||
1628 | 596 | context = {} | ||
1629 | 597 | for k in keys: | ||
1630 | 598 | context[k] = relation_get(k, rid=r_id, | ||
1631 | 599 | unit=unit) | ||
1632 | 600 | if None not in context.values(): | ||
1633 | 601 | return True | ||
1634 | 602 | return False | ||
1635 | 603 | |||
1636 | 604 | |||
1637 | 605 | def open_port(port, protocol="TCP"): | ||
1638 | 606 | """Open a service network port""" | ||
1639 | 607 | _args = ['open-port'] | ||
1640 | 608 | _args.append('{}/{}'.format(port, protocol)) | ||
1641 | 609 | subprocess.check_call(_args) | ||
1642 | 610 | |||
1643 | 611 | |||
1644 | 612 | def close_port(port, protocol="TCP"): | ||
1645 | 613 | """Close a service network port""" | ||
1646 | 614 | _args = ['close-port'] | ||
1647 | 615 | _args.append('{}/{}'.format(port, protocol)) | ||
1648 | 616 | subprocess.check_call(_args) | ||
1649 | 617 | |||
1650 | 618 | |||
1651 | 619 | def open_ports(start, end, protocol="TCP"): | ||
1652 | 620 | """Opens a range of service network ports""" | ||
1653 | 621 | _args = ['open-port'] | ||
1654 | 622 | _args.append('{}-{}/{}'.format(start, end, protocol)) | ||
1655 | 623 | subprocess.check_call(_args) | ||
1656 | 624 | |||
1657 | 625 | |||
1658 | 626 | def close_ports(start, end, protocol="TCP"): | ||
1659 | 627 | """Close a range of service network ports""" | ||
1660 | 628 | _args = ['close-port'] | ||
1661 | 629 | _args.append('{}-{}/{}'.format(start, end, protocol)) | ||
1662 | 630 | subprocess.check_call(_args) | ||
1663 | 631 | |||
1664 | 632 | |||
1665 | 633 | @cached | ||
1666 | 634 | def unit_get(attribute): | ||
1667 | 635 | """Get the unit ID for the remote unit""" | ||
1668 | 636 | _args = ['unit-get', '--format=json', attribute] | ||
1669 | 637 | try: | ||
1670 | 638 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1671 | 639 | except ValueError: | ||
1672 | 640 | return None | ||
1673 | 641 | |||
1674 | 642 | |||
1675 | 643 | def unit_public_ip(): | ||
1676 | 644 | """Get this unit's public IP address""" | ||
1677 | 645 | return unit_get('public-address') | ||
1678 | 646 | |||
1679 | 647 | |||
1680 | 648 | def unit_private_ip(): | ||
1681 | 649 | """Get this unit's private IP address""" | ||
1682 | 650 | return unit_get('private-address') | ||
1683 | 651 | |||
1684 | 652 | |||
1685 | 653 | @cached | ||
1686 | 654 | def storage_get(attribute=None, storage_id=None): | ||
1687 | 655 | """Get storage attributes""" | ||
1688 | 656 | _args = ['storage-get', '--format=json'] | ||
1689 | 657 | if storage_id: | ||
1690 | 658 | _args.extend(('-s', storage_id)) | ||
1691 | 659 | if attribute: | ||
1692 | 660 | _args.append(attribute) | ||
1693 | 661 | try: | ||
1694 | 662 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1695 | 663 | except ValueError: | ||
1696 | 664 | return None | ||
1697 | 665 | |||
1698 | 666 | |||
1699 | 667 | @cached | ||
1700 | 668 | def storage_list(storage_name=None): | ||
1701 | 669 | """List the storage IDs for the unit""" | ||
1702 | 670 | _args = ['storage-list', '--format=json'] | ||
1703 | 671 | if storage_name: | ||
1704 | 672 | _args.append(storage_name) | ||
1705 | 673 | try: | ||
1706 | 674 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1707 | 675 | except ValueError: | ||
1708 | 676 | return None | ||
1709 | 677 | except OSError as e: | ||
1710 | 678 | import errno | ||
1711 | 679 | if e.errno == errno.ENOENT: | ||
1712 | 680 | # storage-list does not exist | ||
1713 | 681 | return [] | ||
1714 | 682 | raise | ||
1715 | 683 | |||
1716 | 684 | |||
1717 | 685 | class UnregisteredHookError(Exception): | ||
1718 | 686 | """Raised when an undefined hook is called""" | ||
1719 | 687 | pass | ||
1720 | 688 | |||
1721 | 689 | |||
1722 | 690 | class Hooks(object): | ||
1723 | 691 | """A convenient handler for hook functions. | ||
1724 | 692 | |||
1725 | 693 | Example:: | ||
1726 | 694 | |||
1727 | 695 | hooks = Hooks() | ||
1728 | 696 | |||
1729 | 697 | # register a hook, taking its name from the function name | ||
1730 | 698 | @hooks.hook() | ||
1731 | 699 | def install(): | ||
1732 | 700 | pass # your code here | ||
1733 | 701 | |||
1734 | 702 | # register a hook, providing a custom hook name | ||
1735 | 703 | @hooks.hook("config-changed") | ||
1736 | 704 | def config_changed(): | ||
1737 | 705 | pass # your code here | ||
1738 | 706 | |||
1739 | 707 | if __name__ == "__main__": | ||
1740 | 708 | # execute a hook based on the name the program is called by | ||
1741 | 709 | hooks.execute(sys.argv) | ||
1742 | 710 | """ | ||
1743 | 711 | |||
1744 | 712 | def __init__(self, config_save=None): | ||
1745 | 713 | super(Hooks, self).__init__() | ||
1746 | 714 | self._hooks = {} | ||
1747 | 715 | |||
1748 | 716 | # For unknown reasons, we allow the Hooks constructor to override | ||
1749 | 717 | # config().implicit_save. | ||
1750 | 718 | if config_save is not None: | ||
1751 | 719 | config().implicit_save = config_save | ||
1752 | 720 | |||
1753 | 721 | def register(self, name, function): | ||
1754 | 722 | """Register a hook""" | ||
1755 | 723 | self._hooks[name] = function | ||
1756 | 724 | |||
1757 | 725 | def execute(self, args): | ||
1758 | 726 | """Execute a registered hook based on args[0]""" | ||
1759 | 727 | _run_atstart() | ||
1760 | 728 | hook_name = os.path.basename(args[0]) | ||
1761 | 729 | if hook_name in self._hooks: | ||
1762 | 730 | try: | ||
1763 | 731 | self._hooks[hook_name]() | ||
1764 | 732 | except SystemExit as x: | ||
1765 | 733 | if x.code is None or x.code == 0: | ||
1766 | 734 | _run_atexit() | ||
1767 | 735 | raise | ||
1768 | 736 | _run_atexit() | ||
1769 | 737 | else: | ||
1770 | 738 | raise UnregisteredHookError(hook_name) | ||
1771 | 739 | |||
1772 | 740 | def hook(self, *hook_names): | ||
1773 | 741 | """Decorator, registering them as hooks""" | ||
1774 | 742 | def wrapper(decorated): | ||
1775 | 743 | for hook_name in hook_names: | ||
1776 | 744 | self.register(hook_name, decorated) | ||
1777 | 745 | else: | ||
1778 | 746 | self.register(decorated.__name__, decorated) | ||
1779 | 747 | if '_' in decorated.__name__: | ||
1780 | 748 | self.register( | ||
1781 | 749 | decorated.__name__.replace('_', '-'), decorated) | ||
1782 | 750 | return decorated | ||
1783 | 751 | return wrapper | ||
1784 | 752 | |||
1785 | 753 | |||
1786 | 754 | def charm_dir(): | ||
1787 | 755 | """Return the root directory of the current charm""" | ||
1788 | 756 | return os.environ.get('CHARM_DIR') | ||
1789 | 757 | |||
1790 | 758 | |||
1791 | 759 | @cached | ||
1792 | 760 | def action_get(key=None): | ||
1793 | 761 | """Gets the value of an action parameter, or all key/value param pairs""" | ||
1794 | 762 | cmd = ['action-get'] | ||
1795 | 763 | if key is not None: | ||
1796 | 764 | cmd.append(key) | ||
1797 | 765 | cmd.append('--format=json') | ||
1798 | 766 | action_data = json.loads(subprocess.check_output(cmd).decode('UTF-8')) | ||
1799 | 767 | return action_data | ||
1800 | 768 | |||
1801 | 769 | |||
1802 | 770 | def action_set(values): | ||
1803 | 771 | """Sets the values to be returned after the action finishes""" | ||
1804 | 772 | cmd = ['action-set'] | ||
1805 | 773 | for k, v in list(values.items()): | ||
1806 | 774 | cmd.append('{}={}'.format(k, v)) | ||
1807 | 775 | subprocess.check_call(cmd) | ||
1808 | 776 | |||
1809 | 777 | |||
1810 | 778 | def action_fail(message): | ||
1811 | 779 | """Sets the action status to failed and sets the error message. | ||
1812 | 780 | |||
1813 | 781 | The results set by action_set are preserved.""" | ||
1814 | 782 | subprocess.check_call(['action-fail', message]) | ||
1815 | 783 | |||
1816 | 784 | |||
1817 | 785 | def action_name(): | ||
1818 | 786 | """Get the name of the currently executing action.""" | ||
1819 | 787 | return os.environ.get('JUJU_ACTION_NAME') | ||
1820 | 788 | |||
1821 | 789 | |||
1822 | 790 | def action_uuid(): | ||
1823 | 791 | """Get the UUID of the currently executing action.""" | ||
1824 | 792 | return os.environ.get('JUJU_ACTION_UUID') | ||
1825 | 793 | |||
1826 | 794 | |||
1827 | 795 | def action_tag(): | ||
1828 | 796 | """Get the tag for the currently executing action.""" | ||
1829 | 797 | return os.environ.get('JUJU_ACTION_TAG') | ||
1830 | 798 | |||
1831 | 799 | |||
1832 | 800 | def status_set(workload_state, message): | ||
1833 | 801 | """Set the workload state with a message | ||
1834 | 802 | |||
1835 | 803 | Use status-set to set the workload state with a message which is visible | ||
1836 | 804 | to the user via juju status. If the status-set command is not found then | ||
1837 | 805 | assume this is juju < 1.23 and juju-log the message unstead. | ||
1838 | 806 | |||
1839 | 807 | workload_state -- valid juju workload state. | ||
1840 | 808 | message -- status update message | ||
1841 | 809 | """ | ||
1842 | 810 | valid_states = ['maintenance', 'blocked', 'waiting', 'active'] | ||
1843 | 811 | if workload_state not in valid_states: | ||
1844 | 812 | raise ValueError( | ||
1845 | 813 | '{!r} is not a valid workload state'.format(workload_state) | ||
1846 | 814 | ) | ||
1847 | 815 | cmd = ['status-set', workload_state, message] | ||
1848 | 816 | try: | ||
1849 | 817 | ret = subprocess.call(cmd) | ||
1850 | 818 | if ret == 0: | ||
1851 | 819 | return | ||
1852 | 820 | except OSError as e: | ||
1853 | 821 | if e.errno != errno.ENOENT: | ||
1854 | 822 | raise | ||
1855 | 823 | log_message = 'status-set failed: {} {}'.format(workload_state, | ||
1856 | 824 | message) | ||
1857 | 825 | log(log_message, level='INFO') | ||
1858 | 826 | |||
1859 | 827 | |||
1860 | 828 | def status_get(): | ||
1861 | 829 | """Retrieve the previously set juju workload state and message | ||
1862 | 830 | |||
1863 | 831 | If the status-get command is not found then assume this is juju < 1.23 and | ||
1864 | 832 | return 'unknown', "" | ||
1865 | 833 | |||
1866 | 834 | """ | ||
1867 | 835 | cmd = ['status-get', "--format=json", "--include-data"] | ||
1868 | 836 | try: | ||
1869 | 837 | raw_status = subprocess.check_output(cmd) | ||
1870 | 838 | except OSError as e: | ||
1871 | 839 | if e.errno == errno.ENOENT: | ||
1872 | 840 | return ('unknown', "") | ||
1873 | 841 | else: | ||
1874 | 842 | raise | ||
1875 | 843 | else: | ||
1876 | 844 | status = json.loads(raw_status.decode("UTF-8")) | ||
1877 | 845 | return (status["status"], status["message"]) | ||
1878 | 846 | |||
1879 | 847 | |||
1880 | 848 | def translate_exc(from_exc, to_exc): | ||
1881 | 849 | def inner_translate_exc1(f): | ||
1882 | 850 | @wraps(f) | ||
1883 | 851 | def inner_translate_exc2(*args, **kwargs): | ||
1884 | 852 | try: | ||
1885 | 853 | return f(*args, **kwargs) | ||
1886 | 854 | except from_exc: | ||
1887 | 855 | raise to_exc | ||
1888 | 856 | |||
1889 | 857 | return inner_translate_exc2 | ||
1890 | 858 | |||
1891 | 859 | return inner_translate_exc1 | ||
1892 | 860 | |||
1893 | 861 | |||
1894 | 862 | def application_version_set(version): | ||
1895 | 863 | """Charm authors may trigger this command from any hook to output what | ||
1896 | 864 | version of the application is running. This could be a package version, | ||
1897 | 865 | for instance postgres version 9.5. It could also be a build number or | ||
1898 | 866 | version control revision identifier, for instance git sha 6fb7ba68. """ | ||
1899 | 867 | |||
1900 | 868 | cmd = ['application-version-set'] | ||
1901 | 869 | cmd.append(version) | ||
1902 | 870 | try: | ||
1903 | 871 | subprocess.check_call(cmd) | ||
1904 | 872 | except OSError: | ||
1905 | 873 | log("Application Version: {}".format(version)) | ||
1906 | 874 | |||
1907 | 875 | |||
1908 | 876 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1909 | 877 | def is_leader(): | ||
1910 | 878 | """Does the current unit hold the juju leadership | ||
1911 | 879 | |||
1912 | 880 | Uses juju to determine whether the current unit is the leader of its peers | ||
1913 | 881 | """ | ||
1914 | 882 | cmd = ['is-leader', '--format=json'] | ||
1915 | 883 | return json.loads(subprocess.check_output(cmd).decode('UTF-8')) | ||
1916 | 884 | |||
1917 | 885 | |||
1918 | 886 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1919 | 887 | def leader_get(attribute=None): | ||
1920 | 888 | """Juju leader get value(s)""" | ||
1921 | 889 | cmd = ['leader-get', '--format=json'] + [attribute or '-'] | ||
1922 | 890 | return json.loads(subprocess.check_output(cmd).decode('UTF-8')) | ||
1923 | 891 | |||
1924 | 892 | |||
1925 | 893 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1926 | 894 | def leader_set(settings=None, **kwargs): | ||
1927 | 895 | """Juju leader set value(s)""" | ||
1928 | 896 | # Don't log secrets. | ||
1929 | 897 | # log("Juju leader-set '%s'" % (settings), level=DEBUG) | ||
1930 | 898 | cmd = ['leader-set'] | ||
1931 | 899 | settings = settings or {} | ||
1932 | 900 | settings.update(kwargs) | ||
1933 | 901 | for k, v in settings.items(): | ||
1934 | 902 | if v is None: | ||
1935 | 903 | cmd.append('{}='.format(k)) | ||
1936 | 904 | else: | ||
1937 | 905 | cmd.append('{}={}'.format(k, v)) | ||
1938 | 906 | subprocess.check_call(cmd) | ||
1939 | 907 | |||
1940 | 908 | |||
1941 | 909 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1942 | 910 | def payload_register(ptype, klass, pid): | ||
1943 | 911 | """ is used while a hook is running to let Juju know that a | ||
1944 | 912 | payload has been started.""" | ||
1945 | 913 | cmd = ['payload-register'] | ||
1946 | 914 | for x in [ptype, klass, pid]: | ||
1947 | 915 | cmd.append(x) | ||
1948 | 916 | subprocess.check_call(cmd) | ||
1949 | 917 | |||
1950 | 918 | |||
1951 | 919 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1952 | 920 | def payload_unregister(klass, pid): | ||
1953 | 921 | """ is used while a hook is running to let Juju know | ||
1954 | 922 | that a payload has been manually stopped. The <class> and <id> provided | ||
1955 | 923 | must match a payload that has been previously registered with juju using | ||
1956 | 924 | payload-register.""" | ||
1957 | 925 | cmd = ['payload-unregister'] | ||
1958 | 926 | for x in [klass, pid]: | ||
1959 | 927 | cmd.append(x) | ||
1960 | 928 | subprocess.check_call(cmd) | ||
1961 | 929 | |||
1962 | 930 | |||
1963 | 931 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1964 | 932 | def payload_status_set(klass, pid, status): | ||
1965 | 933 | """is used to update the current status of a registered payload. | ||
1966 | 934 | The <class> and <id> provided must match a payload that has been previously | ||
1967 | 935 | registered with juju using payload-register. The <status> must be one of the | ||
1968 | 936 | follow: starting, started, stopping, stopped""" | ||
1969 | 937 | cmd = ['payload-status-set'] | ||
1970 | 938 | for x in [klass, pid, status]: | ||
1971 | 939 | cmd.append(x) | ||
1972 | 940 | subprocess.check_call(cmd) | ||
1973 | 941 | |||
1974 | 942 | |||
1975 | 943 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
1976 | 944 | def resource_get(name): | ||
1977 | 945 | """used to fetch the resource path of the given name. | ||
1978 | 946 | |||
1979 | 947 | <name> must match a name of defined resource in metadata.yaml | ||
1980 | 948 | |||
1981 | 949 | returns either a path or False if resource not available | ||
1982 | 950 | """ | ||
1983 | 951 | if not name: | ||
1984 | 952 | return False | ||
1985 | 953 | |||
1986 | 954 | cmd = ['resource-get', name] | ||
1987 | 955 | try: | ||
1988 | 956 | return subprocess.check_output(cmd).decode('UTF-8') | ||
1989 | 957 | except subprocess.CalledProcessError: | ||
1990 | 958 | return False | ||
1991 | 959 | |||
1992 | 960 | |||
1993 | 961 | @cached | ||
1994 | 962 | def juju_version(): | ||
1995 | 963 | """Full version string (eg. '1.23.3.1-trusty-amd64')""" | ||
1996 | 964 | # Per https://bugs.launchpad.net/juju-core/+bug/1455368/comments/1 | ||
1997 | 965 | jujud = glob.glob('/var/lib/juju/tools/machine-*/jujud')[0] | ||
1998 | 966 | return subprocess.check_output([jujud, 'version'], | ||
1999 | 967 | universal_newlines=True).strip() | ||
2000 | 968 | |||
2001 | 969 | |||
2002 | 970 | @cached | ||
2003 | 971 | def has_juju_version(minimum_version): | ||
2004 | 972 | """Return True if the Juju version is at least the provided version""" | ||
2005 | 973 | return LooseVersion(juju_version()) >= LooseVersion(minimum_version) | ||
2006 | 974 | |||
2007 | 975 | |||
2008 | 976 | _atexit = [] | ||
2009 | 977 | _atstart = [] | ||
2010 | 978 | |||
2011 | 979 | |||
2012 | 980 | def atstart(callback, *args, **kwargs): | ||
2013 | 981 | '''Schedule a callback to run before the main hook. | ||
2014 | 982 | |||
2015 | 983 | Callbacks are run in the order they were added. | ||
2016 | 984 | |||
2017 | 985 | This is useful for modules and classes to perform initialization | ||
2018 | 986 | and inject behavior. In particular: | ||
2019 | 987 | |||
2020 | 988 | - Run common code before all of your hooks, such as logging | ||
2021 | 989 | the hook name or interesting relation data. | ||
2022 | 990 | - Defer object or module initialization that requires a hook | ||
2023 | 991 | context until we know there actually is a hook context, | ||
2024 | 992 | making testing easier. | ||
2025 | 993 | - Rather than requiring charm authors to include boilerplate to | ||
2026 | 994 | invoke your helper's behavior, have it run automatically if | ||
2027 | 995 | your object is instantiated or module imported. | ||
2028 | 996 | |||
2029 | 997 | This is not at all useful after your hook framework as been launched. | ||
2030 | 998 | ''' | ||
2031 | 999 | global _atstart | ||
2032 | 1000 | _atstart.append((callback, args, kwargs)) | ||
2033 | 1001 | |||
2034 | 1002 | |||
2035 | 1003 | def atexit(callback, *args, **kwargs): | ||
2036 | 1004 | '''Schedule a callback to run on successful hook completion. | ||
2037 | 1005 | |||
2038 | 1006 | Callbacks are run in the reverse order that they were added.''' | ||
2039 | 1007 | _atexit.append((callback, args, kwargs)) | ||
2040 | 1008 | |||
2041 | 1009 | |||
2042 | 1010 | def _run_atstart(): | ||
2043 | 1011 | '''Hook frameworks must invoke this before running the main hook body.''' | ||
2044 | 1012 | global _atstart | ||
2045 | 1013 | for callback, args, kwargs in _atstart: | ||
2046 | 1014 | callback(*args, **kwargs) | ||
2047 | 1015 | del _atstart[:] | ||
2048 | 1016 | |||
2049 | 1017 | |||
2050 | 1018 | def _run_atexit(): | ||
2051 | 1019 | '''Hook frameworks must invoke this after the main hook body has | ||
2052 | 1020 | successfully completed. Do not invoke it if the hook fails.''' | ||
2053 | 1021 | global _atexit | ||
2054 | 1022 | for callback, args, kwargs in reversed(_atexit): | ||
2055 | 1023 | callback(*args, **kwargs) | ||
2056 | 1024 | del _atexit[:] | ||
2057 | 1025 | |||
2058 | 1026 | |||
2059 | 1027 | @translate_exc(from_exc=OSError, to_exc=NotImplementedError) | ||
2060 | 1028 | def network_get_primary_address(binding): | ||
2061 | 1029 | ''' | ||
2062 | 1030 | Retrieve the primary network address for a named binding | ||
2063 | 1031 | |||
2064 | 1032 | :param binding: string. The name of a relation of extra-binding | ||
2065 | 1033 | :return: string. The primary IP address for the named binding | ||
2066 | 1034 | :raise: NotImplementedError if run on Juju < 2.0 | ||
2067 | 1035 | ''' | ||
2068 | 1036 | cmd = ['network-get', '--primary-address', binding] | ||
2069 | 1037 | return subprocess.check_output(cmd).decode('UTF-8').strip() | ||
2070 | 1038 | |||
2071 | 1039 | |||
2072 | 1040 | def add_metric(*args, **kwargs): | ||
2073 | 1041 | """Add metric values. Values may be expressed with keyword arguments. For | ||
2074 | 1042 | metric names containing dashes, these may be expressed as one or more | ||
2075 | 1043 | 'key=value' positional arguments. May only be called from the collect-metrics | ||
2076 | 1044 | hook.""" | ||
2077 | 1045 | _args = ['add-metric'] | ||
2078 | 1046 | _kvpairs = [] | ||
2079 | 1047 | _kvpairs.extend(args) | ||
2080 | 1048 | _kvpairs.extend(['{}={}'.format(k, v) for k, v in kwargs.items()]) | ||
2081 | 1049 | _args.extend(sorted(_kvpairs)) | ||
2082 | 1050 | try: | ||
2083 | 1051 | subprocess.check_call(_args) | ||
2084 | 1052 | return | ||
2085 | 1053 | except EnvironmentError as e: | ||
2086 | 1054 | if e.errno != errno.ENOENT: | ||
2087 | 1055 | raise | ||
2088 | 1056 | log_message = 'add-metric failed: {}'.format(' '.join(_kvpairs)) | ||
2089 | 1057 | log(log_message, level='INFO') | ||
2090 | 1058 | |||
2091 | 1059 | |||
2092 | 1060 | def meter_status(): | ||
2093 | 1061 | """Get the meter status, if running in the meter-status-changed hook.""" | ||
2094 | 1062 | return os.environ.get('JUJU_METER_STATUS') | ||
2095 | 1063 | |||
2096 | 1064 | |||
2097 | 1065 | def meter_info(): | ||
2098 | 1066 | """Get the meter status information, if running in the meter-status-changed | ||
2099 | 1067 | hook.""" | ||
2100 | 1068 | return os.environ.get('JUJU_METER_INFO') | ||
2101 | diff --git a/hooks/charmhelpers/core/host.py b/hooks/charmhelpers/core/host.py | |||
2102 | 0 | new file mode 100644 | 1069 | new file mode 100644 |
2103 | index 0000000..88e80a4 | |||
2104 | --- /dev/null | |||
2105 | +++ b/hooks/charmhelpers/core/host.py | |||
2106 | @@ -0,0 +1,922 @@ | |||
2107 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2108 | 2 | # | ||
2109 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
2110 | 4 | # you may not use this file except in compliance with the License. | ||
2111 | 5 | # You may obtain a copy of the License at | ||
2112 | 6 | # | ||
2113 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
2114 | 8 | # | ||
2115 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
2116 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
2117 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
2118 | 12 | # See the License for the specific language governing permissions and | ||
2119 | 13 | # limitations under the License. | ||
2120 | 14 | |||
2121 | 15 | """Tools for working with the host system""" | ||
2122 | 16 | # Copyright 2012 Canonical Ltd. | ||
2123 | 17 | # | ||
2124 | 18 | # Authors: | ||
2125 | 19 | # Nick Moffitt <nick.moffitt@canonical.com> | ||
2126 | 20 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | ||
2127 | 21 | |||
2128 | 22 | import os | ||
2129 | 23 | import re | ||
2130 | 24 | import pwd | ||
2131 | 25 | import glob | ||
2132 | 26 | import grp | ||
2133 | 27 | import random | ||
2134 | 28 | import string | ||
2135 | 29 | import subprocess | ||
2136 | 30 | import hashlib | ||
2137 | 31 | import functools | ||
2138 | 32 | import itertools | ||
2139 | 33 | import six | ||
2140 | 34 | |||
2141 | 35 | from contextlib import contextmanager | ||
2142 | 36 | from collections import OrderedDict | ||
2143 | 37 | from .hookenv import log | ||
2144 | 38 | from .fstab import Fstab | ||
2145 | 39 | from charmhelpers.osplatform import get_platform | ||
2146 | 40 | |||
2147 | 41 | __platform__ = get_platform() | ||
2148 | 42 | if __platform__ == "ubuntu": | ||
2149 | 43 | from charmhelpers.core.host_factory.ubuntu import ( | ||
2150 | 44 | service_available, | ||
2151 | 45 | add_new_group, | ||
2152 | 46 | lsb_release, | ||
2153 | 47 | cmp_pkgrevno, | ||
2154 | 48 | CompareHostReleases, | ||
2155 | 49 | ) # flake8: noqa -- ignore F401 for this import | ||
2156 | 50 | elif __platform__ == "centos": | ||
2157 | 51 | from charmhelpers.core.host_factory.centos import ( | ||
2158 | 52 | service_available, | ||
2159 | 53 | add_new_group, | ||
2160 | 54 | lsb_release, | ||
2161 | 55 | cmp_pkgrevno, | ||
2162 | 56 | CompareHostReleases, | ||
2163 | 57 | ) # flake8: noqa -- ignore F401 for this import | ||
2164 | 58 | |||
2165 | 59 | UPDATEDB_PATH = '/etc/updatedb.conf' | ||
2166 | 60 | |||
2167 | 61 | def service_start(service_name, **kwargs): | ||
2168 | 62 | """Start a system service. | ||
2169 | 63 | |||
2170 | 64 | The specified service name is managed via the system level init system. | ||
2171 | 65 | Some init systems (e.g. upstart) require that additional arguments be | ||
2172 | 66 | provided in order to directly control service instances whereas other init | ||
2173 | 67 | systems allow for addressing instances of a service directly by name (e.g. | ||
2174 | 68 | systemd). | ||
2175 | 69 | |||
2176 | 70 | The kwargs allow for the additional parameters to be passed to underlying | ||
2177 | 71 | init systems for those systems which require/allow for them. For example, | ||
2178 | 72 | the ceph-osd upstart script requires the id parameter to be passed along | ||
2179 | 73 | in order to identify which running daemon should be reloaded. The follow- | ||
2180 | 74 | ing example stops the ceph-osd service for instance id=4: | ||
2181 | 75 | |||
2182 | 76 | service_stop('ceph-osd', id=4) | ||
2183 | 77 | |||
2184 | 78 | :param service_name: the name of the service to stop | ||
2185 | 79 | :param **kwargs: additional parameters to pass to the init system when | ||
2186 | 80 | managing services. These will be passed as key=value | ||
2187 | 81 | parameters to the init system's commandline. kwargs | ||
2188 | 82 | are ignored for systemd enabled systems. | ||
2189 | 83 | """ | ||
2190 | 84 | return service('start', service_name, **kwargs) | ||
2191 | 85 | |||
2192 | 86 | |||
2193 | 87 | def service_stop(service_name, **kwargs): | ||
2194 | 88 | """Stop a system service. | ||
2195 | 89 | |||
2196 | 90 | The specified service name is managed via the system level init system. | ||
2197 | 91 | Some init systems (e.g. upstart) require that additional arguments be | ||
2198 | 92 | provided in order to directly control service instances whereas other init | ||
2199 | 93 | systems allow for addressing instances of a service directly by name (e.g. | ||
2200 | 94 | systemd). | ||
2201 | 95 | |||
2202 | 96 | The kwargs allow for the additional parameters to be passed to underlying | ||
2203 | 97 | init systems for those systems which require/allow for them. For example, | ||
2204 | 98 | the ceph-osd upstart script requires the id parameter to be passed along | ||
2205 | 99 | in order to identify which running daemon should be reloaded. The follow- | ||
2206 | 100 | ing example stops the ceph-osd service for instance id=4: | ||
2207 | 101 | |||
2208 | 102 | service_stop('ceph-osd', id=4) | ||
2209 | 103 | |||
2210 | 104 | :param service_name: the name of the service to stop | ||
2211 | 105 | :param **kwargs: additional parameters to pass to the init system when | ||
2212 | 106 | managing services. These will be passed as key=value | ||
2213 | 107 | parameters to the init system's commandline. kwargs | ||
2214 | 108 | are ignored for systemd enabled systems. | ||
2215 | 109 | """ | ||
2216 | 110 | return service('stop', service_name, **kwargs) | ||
2217 | 111 | |||
2218 | 112 | |||
2219 | 113 | def service_restart(service_name, **kwargs): | ||
2220 | 114 | """Restart a system service. | ||
2221 | 115 | |||
2222 | 116 | The specified service name is managed via the system level init system. | ||
2223 | 117 | Some init systems (e.g. upstart) require that additional arguments be | ||
2224 | 118 | provided in order to directly control service instances whereas other init | ||
2225 | 119 | systems allow for addressing instances of a service directly by name (e.g. | ||
2226 | 120 | systemd). | ||
2227 | 121 | |||
2228 | 122 | The kwargs allow for the additional parameters to be passed to underlying | ||
2229 | 123 | init systems for those systems which require/allow for them. For example, | ||
2230 | 124 | the ceph-osd upstart script requires the id parameter to be passed along | ||
2231 | 125 | in order to identify which running daemon should be restarted. The follow- | ||
2232 | 126 | ing example restarts the ceph-osd service for instance id=4: | ||
2233 | 127 | |||
2234 | 128 | service_restart('ceph-osd', id=4) | ||
2235 | 129 | |||
2236 | 130 | :param service_name: the name of the service to restart | ||
2237 | 131 | :param **kwargs: additional parameters to pass to the init system when | ||
2238 | 132 | managing services. These will be passed as key=value | ||
2239 | 133 | parameters to the init system's commandline. kwargs | ||
2240 | 134 | are ignored for init systems not allowing additional | ||
2241 | 135 | parameters via the commandline (systemd). | ||
2242 | 136 | """ | ||
2243 | 137 | return service('restart', service_name) | ||
2244 | 138 | |||
2245 | 139 | |||
2246 | 140 | def service_reload(service_name, restart_on_failure=False, **kwargs): | ||
2247 | 141 | """Reload a system service, optionally falling back to restart if | ||
2248 | 142 | reload fails. | ||
2249 | 143 | |||
2250 | 144 | The specified service name is managed via the system level init system. | ||
2251 | 145 | Some init systems (e.g. upstart) require that additional arguments be | ||
2252 | 146 | provided in order to directly control service instances whereas other init | ||
2253 | 147 | systems allow for addressing instances of a service directly by name (e.g. | ||
2254 | 148 | systemd). | ||
2255 | 149 | |||
2256 | 150 | The kwargs allow for the additional parameters to be passed to underlying | ||
2257 | 151 | init systems for those systems which require/allow for them. For example, | ||
2258 | 152 | the ceph-osd upstart script requires the id parameter to be passed along | ||
2259 | 153 | in order to identify which running daemon should be reloaded. The follow- | ||
2260 | 154 | ing example restarts the ceph-osd service for instance id=4: | ||
2261 | 155 | |||
2262 | 156 | service_reload('ceph-osd', id=4) | ||
2263 | 157 | |||
2264 | 158 | :param service_name: the name of the service to reload | ||
2265 | 159 | :param restart_on_failure: boolean indicating whether to fallback to a | ||
2266 | 160 | restart if the reload fails. | ||
2267 | 161 | :param **kwargs: additional parameters to pass to the init system when | ||
2268 | 162 | managing services. These will be passed as key=value | ||
2269 | 163 | parameters to the init system's commandline. kwargs | ||
2270 | 164 | are ignored for init systems not allowing additional | ||
2271 | 165 | parameters via the commandline (systemd). | ||
2272 | 166 | """ | ||
2273 | 167 | service_result = service('reload', service_name, **kwargs) | ||
2274 | 168 | if not service_result and restart_on_failure: | ||
2275 | 169 | service_result = service('restart', service_name, **kwargs) | ||
2276 | 170 | return service_result | ||
2277 | 171 | |||
2278 | 172 | |||
2279 | 173 | def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", | ||
2280 | 174 | **kwargs): | ||
2281 | 175 | """Pause a system service. | ||
2282 | 176 | |||
2283 | 177 | Stop it, and prevent it from starting again at boot. | ||
2284 | 178 | |||
2285 | 179 | :param service_name: the name of the service to pause | ||
2286 | 180 | :param init_dir: path to the upstart init directory | ||
2287 | 181 | :param initd_dir: path to the sysv init directory | ||
2288 | 182 | :param **kwargs: additional parameters to pass to the init system when | ||
2289 | 183 | managing services. These will be passed as key=value | ||
2290 | 184 | parameters to the init system's commandline. kwargs | ||
2291 | 185 | are ignored for init systems which do not support | ||
2292 | 186 | key=value arguments via the commandline. | ||
2293 | 187 | """ | ||
2294 | 188 | stopped = True | ||
2295 | 189 | if service_running(service_name, **kwargs): | ||
2296 | 190 | stopped = service_stop(service_name, **kwargs) | ||
2297 | 191 | upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) | ||
2298 | 192 | sysv_file = os.path.join(initd_dir, service_name) | ||
2299 | 193 | if init_is_systemd(): | ||
2300 | 194 | service('mask', service_name) | ||
2301 | 195 | elif os.path.exists(upstart_file): | ||
2302 | 196 | override_path = os.path.join( | ||
2303 | 197 | init_dir, '{}.override'.format(service_name)) | ||
2304 | 198 | with open(override_path, 'w') as fh: | ||
2305 | 199 | fh.write("manual\n") | ||
2306 | 200 | elif os.path.exists(sysv_file): | ||
2307 | 201 | subprocess.check_call(["update-rc.d", service_name, "disable"]) | ||
2308 | 202 | else: | ||
2309 | 203 | raise ValueError( | ||
2310 | 204 | "Unable to detect {0} as SystemD, Upstart {1} or" | ||
2311 | 205 | " SysV {2}".format( | ||
2312 | 206 | service_name, upstart_file, sysv_file)) | ||
2313 | 207 | return stopped | ||
2314 | 208 | |||
2315 | 209 | |||
2316 | 210 | def service_resume(service_name, init_dir="/etc/init", | ||
2317 | 211 | initd_dir="/etc/init.d", **kwargs): | ||
2318 | 212 | """Resume a system service. | ||
2319 | 213 | |||
2320 | 214 | Reenable starting again at boot. Start the service. | ||
2321 | 215 | |||
2322 | 216 | :param service_name: the name of the service to resume | ||
2323 | 217 | :param init_dir: the path to the init dir | ||
2324 | 218 | :param initd dir: the path to the initd dir | ||
2325 | 219 | :param **kwargs: additional parameters to pass to the init system when | ||
2326 | 220 | managing services. These will be passed as key=value | ||
2327 | 221 | parameters to the init system's commandline. kwargs | ||
2328 | 222 | are ignored for systemd enabled systems. | ||
2329 | 223 | """ | ||
2330 | 224 | upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) | ||
2331 | 225 | sysv_file = os.path.join(initd_dir, service_name) | ||
2332 | 226 | if init_is_systemd(): | ||
2333 | 227 | service('unmask', service_name) | ||
2334 | 228 | elif os.path.exists(upstart_file): | ||
2335 | 229 | override_path = os.path.join( | ||
2336 | 230 | init_dir, '{}.override'.format(service_name)) | ||
2337 | 231 | if os.path.exists(override_path): | ||
2338 | 232 | os.unlink(override_path) | ||
2339 | 233 | elif os.path.exists(sysv_file): | ||
2340 | 234 | subprocess.check_call(["update-rc.d", service_name, "enable"]) | ||
2341 | 235 | else: | ||
2342 | 236 | raise ValueError( | ||
2343 | 237 | "Unable to detect {0} as SystemD, Upstart {1} or" | ||
2344 | 238 | " SysV {2}".format( | ||
2345 | 239 | service_name, upstart_file, sysv_file)) | ||
2346 | 240 | started = service_running(service_name, **kwargs) | ||
2347 | 241 | |||
2348 | 242 | if not started: | ||
2349 | 243 | started = service_start(service_name, **kwargs) | ||
2350 | 244 | return started | ||
2351 | 245 | |||
2352 | 246 | |||
2353 | 247 | def service(action, service_name, **kwargs): | ||
2354 | 248 | """Control a system service. | ||
2355 | 249 | |||
2356 | 250 | :param action: the action to take on the service | ||
2357 | 251 | :param service_name: the name of the service to perform th action on | ||
2358 | 252 | :param **kwargs: additional params to be passed to the service command in | ||
2359 | 253 | the form of key=value. | ||
2360 | 254 | """ | ||
2361 | 255 | if init_is_systemd(): | ||
2362 | 256 | cmd = ['systemctl', action, service_name] | ||
2363 | 257 | else: | ||
2364 | 258 | cmd = ['service', service_name, action] | ||
2365 | 259 | for key, value in six.iteritems(kwargs): | ||
2366 | 260 | parameter = '%s=%s' % (key, value) | ||
2367 | 261 | cmd.append(parameter) | ||
2368 | 262 | return subprocess.call(cmd) == 0 | ||
2369 | 263 | |||
2370 | 264 | |||
2371 | 265 | _UPSTART_CONF = "/etc/init/{}.conf" | ||
2372 | 266 | _INIT_D_CONF = "/etc/init.d/{}" | ||
2373 | 267 | |||
2374 | 268 | |||
2375 | 269 | def service_running(service_name, **kwargs): | ||
2376 | 270 | """Determine whether a system service is running. | ||
2377 | 271 | |||
2378 | 272 | :param service_name: the name of the service | ||
2379 | 273 | :param **kwargs: additional args to pass to the service command. This is | ||
2380 | 274 | used to pass additional key=value arguments to the | ||
2381 | 275 | service command line for managing specific instance | ||
2382 | 276 | units (e.g. service ceph-osd status id=2). The kwargs | ||
2383 | 277 | are ignored in systemd services. | ||
2384 | 278 | """ | ||
2385 | 279 | if init_is_systemd(): | ||
2386 | 280 | return service('is-active', service_name) | ||
2387 | 281 | else: | ||
2388 | 282 | if os.path.exists(_UPSTART_CONF.format(service_name)): | ||
2389 | 283 | try: | ||
2390 | 284 | cmd = ['status', service_name] | ||
2391 | 285 | for key, value in six.iteritems(kwargs): | ||
2392 | 286 | parameter = '%s=%s' % (key, value) | ||
2393 | 287 | cmd.append(parameter) | ||
2394 | 288 | output = subprocess.check_output(cmd, | ||
2395 | 289 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
2396 | 290 | except subprocess.CalledProcessError: | ||
2397 | 291 | return False | ||
2398 | 292 | else: | ||
2399 | 293 | # This works for upstart scripts where the 'service' command | ||
2400 | 294 | # returns a consistent string to represent running | ||
2401 | 295 | # 'start/running' | ||
2402 | 296 | if ("start/running" in output or | ||
2403 | 297 | "is running" in output or | ||
2404 | 298 | "up and running" in output): | ||
2405 | 299 | return True | ||
2406 | 300 | elif os.path.exists(_INIT_D_CONF.format(service_name)): | ||
2407 | 301 | # Check System V scripts init script return codes | ||
2408 | 302 | return service('status', service_name) | ||
2409 | 303 | return False | ||
2410 | 304 | |||
2411 | 305 | |||
2412 | 306 | SYSTEMD_SYSTEM = '/run/systemd/system' | ||
2413 | 307 | |||
2414 | 308 | |||
2415 | 309 | def init_is_systemd(): | ||
2416 | 310 | """Return True if the host system uses systemd, False otherwise.""" | ||
2417 | 311 | if lsb_release()['DISTRIB_CODENAME'] == 'trusty': | ||
2418 | 312 | return False | ||
2419 | 313 | return os.path.isdir(SYSTEMD_SYSTEM) | ||
2420 | 314 | |||
2421 | 315 | |||
2422 | 316 | def adduser(username, password=None, shell='/bin/bash', | ||
2423 | 317 | system_user=False, primary_group=None, | ||
2424 | 318 | secondary_groups=None, uid=None, home_dir=None): | ||
2425 | 319 | """Add a user to the system. | ||
2426 | 320 | |||
2427 | 321 | Will log but otherwise succeed if the user already exists. | ||
2428 | 322 | |||
2429 | 323 | :param str username: Username to create | ||
2430 | 324 | :param str password: Password for user; if ``None``, create a system user | ||
2431 | 325 | :param str shell: The default shell for the user | ||
2432 | 326 | :param bool system_user: Whether to create a login or system user | ||
2433 | 327 | :param str primary_group: Primary group for user; defaults to username | ||
2434 | 328 | :param list secondary_groups: Optional list of additional groups | ||
2435 | 329 | :param int uid: UID for user being created | ||
2436 | 330 | :param str home_dir: Home directory for user | ||
2437 | 331 | |||
2438 | 332 | :returns: The password database entry struct, as returned by `pwd.getpwnam` | ||
2439 | 333 | """ | ||
2440 | 334 | try: | ||
2441 | 335 | user_info = pwd.getpwnam(username) | ||
2442 | 336 | log('user {0} already exists!'.format(username)) | ||
2443 | 337 | if uid: | ||
2444 | 338 | user_info = pwd.getpwuid(int(uid)) | ||
2445 | 339 | log('user with uid {0} already exists!'.format(uid)) | ||
2446 | 340 | except KeyError: | ||
2447 | 341 | log('creating user {0}'.format(username)) | ||
2448 | 342 | cmd = ['useradd'] | ||
2449 | 343 | if uid: | ||
2450 | 344 | cmd.extend(['--uid', str(uid)]) | ||
2451 | 345 | if home_dir: | ||
2452 | 346 | cmd.extend(['--home', str(home_dir)]) | ||
2453 | 347 | if system_user or password is None: | ||
2454 | 348 | cmd.append('--system') | ||
2455 | 349 | else: | ||
2456 | 350 | cmd.extend([ | ||
2457 | 351 | '--create-home', | ||
2458 | 352 | '--shell', shell, | ||
2459 | 353 | '--password', password, | ||
2460 | 354 | ]) | ||
2461 | 355 | if not primary_group: | ||
2462 | 356 | try: | ||
2463 | 357 | grp.getgrnam(username) | ||
2464 | 358 | primary_group = username # avoid "group exists" error | ||
2465 | 359 | except KeyError: | ||
2466 | 360 | pass | ||
2467 | 361 | if primary_group: | ||
2468 | 362 | cmd.extend(['-g', primary_group]) | ||
2469 | 363 | if secondary_groups: | ||
2470 | 364 | cmd.extend(['-G', ','.join(secondary_groups)]) | ||
2471 | 365 | cmd.append(username) | ||
2472 | 366 | subprocess.check_call(cmd) | ||
2473 | 367 | user_info = pwd.getpwnam(username) | ||
2474 | 368 | return user_info | ||
2475 | 369 | |||
2476 | 370 | |||
2477 | 371 | def user_exists(username): | ||
2478 | 372 | """Check if a user exists""" | ||
2479 | 373 | try: | ||
2480 | 374 | pwd.getpwnam(username) | ||
2481 | 375 | user_exists = True | ||
2482 | 376 | except KeyError: | ||
2483 | 377 | user_exists = False | ||
2484 | 378 | return user_exists | ||
2485 | 379 | |||
2486 | 380 | |||
2487 | 381 | def uid_exists(uid): | ||
2488 | 382 | """Check if a uid exists""" | ||
2489 | 383 | try: | ||
2490 | 384 | pwd.getpwuid(uid) | ||
2491 | 385 | uid_exists = True | ||
2492 | 386 | except KeyError: | ||
2493 | 387 | uid_exists = False | ||
2494 | 388 | return uid_exists | ||
2495 | 389 | |||
2496 | 390 | |||
2497 | 391 | def group_exists(groupname): | ||
2498 | 392 | """Check if a group exists""" | ||
2499 | 393 | try: | ||
2500 | 394 | grp.getgrnam(groupname) | ||
2501 | 395 | group_exists = True | ||
2502 | 396 | except KeyError: | ||
2503 | 397 | group_exists = False | ||
2504 | 398 | return group_exists | ||
2505 | 399 | |||
2506 | 400 | |||
2507 | 401 | def gid_exists(gid): | ||
2508 | 402 | """Check if a gid exists""" | ||
2509 | 403 | try: | ||
2510 | 404 | grp.getgrgid(gid) | ||
2511 | 405 | gid_exists = True | ||
2512 | 406 | except KeyError: | ||
2513 | 407 | gid_exists = False | ||
2514 | 408 | return gid_exists | ||
2515 | 409 | |||
2516 | 410 | |||
2517 | 411 | def add_group(group_name, system_group=False, gid=None): | ||
2518 | 412 | """Add a group to the system | ||
2519 | 413 | |||
2520 | 414 | Will log but otherwise succeed if the group already exists. | ||
2521 | 415 | |||
2522 | 416 | :param str group_name: group to create | ||
2523 | 417 | :param bool system_group: Create system group | ||
2524 | 418 | :param int gid: GID for user being created | ||
2525 | 419 | |||
2526 | 420 | :returns: The password database entry struct, as returned by `grp.getgrnam` | ||
2527 | 421 | """ | ||
2528 | 422 | try: | ||
2529 | 423 | group_info = grp.getgrnam(group_name) | ||
2530 | 424 | log('group {0} already exists!'.format(group_name)) | ||
2531 | 425 | if gid: | ||
2532 | 426 | group_info = grp.getgrgid(gid) | ||
2533 | 427 | log('group with gid {0} already exists!'.format(gid)) | ||
2534 | 428 | except KeyError: | ||
2535 | 429 | log('creating group {0}'.format(group_name)) | ||
2536 | 430 | add_new_group(group_name, system_group, gid) | ||
2537 | 431 | group_info = grp.getgrnam(group_name) | ||
2538 | 432 | return group_info | ||
2539 | 433 | |||
2540 | 434 | |||
2541 | 435 | def add_user_to_group(username, group): | ||
2542 | 436 | """Add a user to a group""" | ||
2543 | 437 | cmd = ['gpasswd', '-a', username, group] | ||
2544 | 438 | log("Adding user {} to group {}".format(username, group)) | ||
2545 | 439 | subprocess.check_call(cmd) | ||
2546 | 440 | |||
2547 | 441 | |||
2548 | 442 | def rsync(from_path, to_path, flags='-r', options=None, timeout=None): | ||
2549 | 443 | """Replicate the contents of a path""" | ||
2550 | 444 | options = options or ['--delete', '--executability'] | ||
2551 | 445 | cmd = ['/usr/bin/rsync', flags] | ||
2552 | 446 | if timeout: | ||
2553 | 447 | cmd = ['timeout', str(timeout)] + cmd | ||
2554 | 448 | cmd.extend(options) | ||
2555 | 449 | cmd.append(from_path) | ||
2556 | 450 | cmd.append(to_path) | ||
2557 | 451 | log(" ".join(cmd)) | ||
2558 | 452 | return subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('UTF-8').strip() | ||
2559 | 453 | |||
2560 | 454 | |||
2561 | 455 | def symlink(source, destination): | ||
2562 | 456 | """Create a symbolic link""" | ||
2563 | 457 | log("Symlinking {} as {}".format(source, destination)) | ||
2564 | 458 | cmd = [ | ||
2565 | 459 | 'ln', | ||
2566 | 460 | '-sf', | ||
2567 | 461 | source, | ||
2568 | 462 | destination, | ||
2569 | 463 | ] | ||
2570 | 464 | subprocess.check_call(cmd) | ||
2571 | 465 | |||
2572 | 466 | |||
2573 | 467 | def mkdir(path, owner='root', group='root', perms=0o555, force=False): | ||
2574 | 468 | """Create a directory""" | ||
2575 | 469 | log("Making dir {} {}:{} {:o}".format(path, owner, group, | ||
2576 | 470 | perms)) | ||
2577 | 471 | uid = pwd.getpwnam(owner).pw_uid | ||
2578 | 472 | gid = grp.getgrnam(group).gr_gid | ||
2579 | 473 | realpath = os.path.abspath(path) | ||
2580 | 474 | path_exists = os.path.exists(realpath) | ||
2581 | 475 | if path_exists and force: | ||
2582 | 476 | if not os.path.isdir(realpath): | ||
2583 | 477 | log("Removing non-directory file {} prior to mkdir()".format(path)) | ||
2584 | 478 | os.unlink(realpath) | ||
2585 | 479 | os.makedirs(realpath, perms) | ||
2586 | 480 | elif not path_exists: | ||
2587 | 481 | os.makedirs(realpath, perms) | ||
2588 | 482 | os.chown(realpath, uid, gid) | ||
2589 | 483 | os.chmod(realpath, perms) | ||
2590 | 484 | |||
2591 | 485 | |||
2592 | 486 | def write_file(path, content, owner='root', group='root', perms=0o444): | ||
2593 | 487 | """Create or overwrite a file with the contents of a byte string.""" | ||
2594 | 488 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) | ||
2595 | 489 | uid = pwd.getpwnam(owner).pw_uid | ||
2596 | 490 | gid = grp.getgrnam(group).gr_gid | ||
2597 | 491 | with open(path, 'wb') as target: | ||
2598 | 492 | os.fchown(target.fileno(), uid, gid) | ||
2599 | 493 | os.fchmod(target.fileno(), perms) | ||
2600 | 494 | target.write(content) | ||
2601 | 495 | |||
2602 | 496 | |||
2603 | 497 | def fstab_remove(mp): | ||
2604 | 498 | """Remove the given mountpoint entry from /etc/fstab""" | ||
2605 | 499 | return Fstab.remove_by_mountpoint(mp) | ||
2606 | 500 | |||
2607 | 501 | |||
2608 | 502 | def fstab_add(dev, mp, fs, options=None): | ||
2609 | 503 | """Adds the given device entry to the /etc/fstab file""" | ||
2610 | 504 | return Fstab.add(dev, mp, fs, options=options) | ||
2611 | 505 | |||
2612 | 506 | |||
2613 | 507 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): | ||
2614 | 508 | """Mount a filesystem at a particular mountpoint""" | ||
2615 | 509 | cmd_args = ['mount'] | ||
2616 | 510 | if options is not None: | ||
2617 | 511 | cmd_args.extend(['-o', options]) | ||
2618 | 512 | cmd_args.extend([device, mountpoint]) | ||
2619 | 513 | try: | ||
2620 | 514 | subprocess.check_output(cmd_args) | ||
2621 | 515 | except subprocess.CalledProcessError as e: | ||
2622 | 516 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | ||
2623 | 517 | return False | ||
2624 | 518 | |||
2625 | 519 | if persist: | ||
2626 | 520 | return fstab_add(device, mountpoint, filesystem, options=options) | ||
2627 | 521 | return True | ||
2628 | 522 | |||
2629 | 523 | |||
2630 | 524 | def umount(mountpoint, persist=False): | ||
2631 | 525 | """Unmount a filesystem""" | ||
2632 | 526 | cmd_args = ['umount', mountpoint] | ||
2633 | 527 | try: | ||
2634 | 528 | subprocess.check_output(cmd_args) | ||
2635 | 529 | except subprocess.CalledProcessError as e: | ||
2636 | 530 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | ||
2637 | 531 | return False | ||
2638 | 532 | |||
2639 | 533 | if persist: | ||
2640 | 534 | return fstab_remove(mountpoint) | ||
2641 | 535 | return True | ||
2642 | 536 | |||
2643 | 537 | |||
2644 | 538 | def mounts(): | ||
2645 | 539 | """Get a list of all mounted volumes as [[mountpoint,device],[...]]""" | ||
2646 | 540 | with open('/proc/mounts') as f: | ||
2647 | 541 | # [['/mount/point','/dev/path'],[...]] | ||
2648 | 542 | system_mounts = [m[1::-1] for m in [l.strip().split() | ||
2649 | 543 | for l in f.readlines()]] | ||
2650 | 544 | return system_mounts | ||
2651 | 545 | |||
2652 | 546 | |||
2653 | 547 | def fstab_mount(mountpoint): | ||
2654 | 548 | """Mount filesystem using fstab""" | ||
2655 | 549 | cmd_args = ['mount', mountpoint] | ||
2656 | 550 | try: | ||
2657 | 551 | subprocess.check_output(cmd_args) | ||
2658 | 552 | except subprocess.CalledProcessError as e: | ||
2659 | 553 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | ||
2660 | 554 | return False | ||
2661 | 555 | return True | ||
2662 | 556 | |||
2663 | 557 | |||
2664 | 558 | def file_hash(path, hash_type='md5'): | ||
2665 | 559 | """Generate a hash checksum of the contents of 'path' or None if not found. | ||
2666 | 560 | |||
2667 | 561 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
2668 | 562 | such as md5, sha1, sha256, sha512, etc. | ||
2669 | 563 | """ | ||
2670 | 564 | if os.path.exists(path): | ||
2671 | 565 | h = getattr(hashlib, hash_type)() | ||
2672 | 566 | with open(path, 'rb') as source: | ||
2673 | 567 | h.update(source.read()) | ||
2674 | 568 | return h.hexdigest() | ||
2675 | 569 | else: | ||
2676 | 570 | return None | ||
2677 | 571 | |||
2678 | 572 | |||
2679 | 573 | def path_hash(path): | ||
2680 | 574 | """Generate a hash checksum of all files matching 'path'. Standard | ||
2681 | 575 | wildcards like '*' and '?' are supported, see documentation for the 'glob' | ||
2682 | 576 | module for more information. | ||
2683 | 577 | |||
2684 | 578 | :return: dict: A { filename: hash } dictionary for all matched files. | ||
2685 | 579 | Empty if none found. | ||
2686 | 580 | """ | ||
2687 | 581 | return { | ||
2688 | 582 | filename: file_hash(filename) | ||
2689 | 583 | for filename in glob.iglob(path) | ||
2690 | 584 | } | ||
2691 | 585 | |||
2692 | 586 | |||
2693 | 587 | def check_hash(path, checksum, hash_type='md5'): | ||
2694 | 588 | """Validate a file using a cryptographic checksum. | ||
2695 | 589 | |||
2696 | 590 | :param str checksum: Value of the checksum used to validate the file. | ||
2697 | 591 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
2698 | 592 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
2699 | 593 | such as md5, sha1, sha256, sha512, etc. | ||
2700 | 594 | :raises ChecksumError: If the file fails the checksum | ||
2701 | 595 | |||
2702 | 596 | """ | ||
2703 | 597 | actual_checksum = file_hash(path, hash_type) | ||
2704 | 598 | if checksum != actual_checksum: | ||
2705 | 599 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
2706 | 600 | |||
2707 | 601 | |||
2708 | 602 | class ChecksumError(ValueError): | ||
2709 | 603 | """A class derived from Value error to indicate the checksum failed.""" | ||
2710 | 604 | pass | ||
2711 | 605 | |||
2712 | 606 | |||
2713 | 607 | def restart_on_change(restart_map, stopstart=False, restart_functions=None): | ||
2714 | 608 | """Restart services based on configuration files changing | ||
2715 | 609 | |||
2716 | 610 | This function is used a decorator, for example:: | ||
2717 | 611 | |||
2718 | 612 | @restart_on_change({ | ||
2719 | 613 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] | ||
2720 | 614 | '/etc/apache/sites-enabled/*': [ 'apache2' ] | ||
2721 | 615 | }) | ||
2722 | 616 | def config_changed(): | ||
2723 | 617 | pass # your code here | ||
2724 | 618 | |||
2725 | 619 | In this example, the cinder-api and cinder-volume services | ||
2726 | 620 | would be restarted if /etc/ceph/ceph.conf is changed by the | ||
2727 | 621 | ceph_client_changed function. The apache2 service would be | ||
2728 | 622 | restarted if any file matching the pattern got changed, created | ||
2729 | 623 | or removed. Standard wildcards are supported, see documentation | ||
2730 | 624 | for the 'glob' module for more information. | ||
2731 | 625 | |||
2732 | 626 | @param restart_map: {path_file_name: [service_name, ...] | ||
2733 | 627 | @param stopstart: DEFAULT false; whether to stop, start OR restart | ||
2734 | 628 | @param restart_functions: nonstandard functions to use to restart services | ||
2735 | 629 | {svc: func, ...} | ||
2736 | 630 | @returns result from decorated function | ||
2737 | 631 | """ | ||
2738 | 632 | def wrap(f): | ||
2739 | 633 | @functools.wraps(f) | ||
2740 | 634 | def wrapped_f(*args, **kwargs): | ||
2741 | 635 | return restart_on_change_helper( | ||
2742 | 636 | (lambda: f(*args, **kwargs)), restart_map, stopstart, | ||
2743 | 637 | restart_functions) | ||
2744 | 638 | return wrapped_f | ||
2745 | 639 | return wrap | ||
2746 | 640 | |||
2747 | 641 | |||
2748 | 642 | def restart_on_change_helper(lambda_f, restart_map, stopstart=False, | ||
2749 | 643 | restart_functions=None): | ||
2750 | 644 | """Helper function to perform the restart_on_change function. | ||
2751 | 645 | |||
2752 | 646 | This is provided for decorators to restart services if files described | ||
2753 | 647 | in the restart_map have changed after an invocation of lambda_f(). | ||
2754 | 648 | |||
2755 | 649 | @param lambda_f: function to call. | ||
2756 | 650 | @param restart_map: {file: [service, ...]} | ||
2757 | 651 | @param stopstart: whether to stop, start or restart a service | ||
2758 | 652 | @param restart_functions: nonstandard functions to use to restart services | ||
2759 | 653 | {svc: func, ...} | ||
2760 | 654 | @returns result of lambda_f() | ||
2761 | 655 | """ | ||
2762 | 656 | if restart_functions is None: | ||
2763 | 657 | restart_functions = {} | ||
2764 | 658 | checksums = {path: path_hash(path) for path in restart_map} | ||
2765 | 659 | r = lambda_f() | ||
2766 | 660 | # create a list of lists of the services to restart | ||
2767 | 661 | restarts = [restart_map[path] | ||
2768 | 662 | for path in restart_map | ||
2769 | 663 | if path_hash(path) != checksums[path]] | ||
2770 | 664 | # create a flat list of ordered services without duplicates from lists | ||
2771 | 665 | services_list = list(OrderedDict.fromkeys(itertools.chain(*restarts))) | ||
2772 | 666 | if services_list: | ||
2773 | 667 | actions = ('stop', 'start') if stopstart else ('restart',) | ||
2774 | 668 | for service_name in services_list: | ||
2775 | 669 | if service_name in restart_functions: | ||
2776 | 670 | restart_functions[service_name](service_name) | ||
2777 | 671 | else: | ||
2778 | 672 | for action in actions: | ||
2779 | 673 | service(action, service_name) | ||
2780 | 674 | return r | ||
2781 | 675 | |||
2782 | 676 | |||
2783 | 677 | def pwgen(length=None): | ||
2784 | 678 | """Generate a random pasword.""" | ||
2785 | 679 | if length is None: | ||
2786 | 680 | # A random length is ok to use a weak PRNG | ||
2787 | 681 | length = random.choice(range(35, 45)) | ||
2788 | 682 | alphanumeric_chars = [ | ||
2789 | 683 | l for l in (string.ascii_letters + string.digits) | ||
2790 | 684 | if l not in 'l0QD1vAEIOUaeiou'] | ||
2791 | 685 | # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the | ||
2792 | 686 | # actual password | ||
2793 | 687 | random_generator = random.SystemRandom() | ||
2794 | 688 | random_chars = [ | ||
2795 | 689 | random_generator.choice(alphanumeric_chars) for _ in range(length)] | ||
2796 | 690 | return(''.join(random_chars)) | ||
2797 | 691 | |||
2798 | 692 | |||
2799 | 693 | def is_phy_iface(interface): | ||
2800 | 694 | """Returns True if interface is not virtual, otherwise False.""" | ||
2801 | 695 | if interface: | ||
2802 | 696 | sys_net = '/sys/class/net' | ||
2803 | 697 | if os.path.isdir(sys_net): | ||
2804 | 698 | for iface in glob.glob(os.path.join(sys_net, '*')): | ||
2805 | 699 | if '/virtual/' in os.path.realpath(iface): | ||
2806 | 700 | continue | ||
2807 | 701 | |||
2808 | 702 | if interface == os.path.basename(iface): | ||
2809 | 703 | return True | ||
2810 | 704 | |||
2811 | 705 | return False | ||
2812 | 706 | |||
2813 | 707 | |||
2814 | 708 | def get_bond_master(interface): | ||
2815 | 709 | """Returns bond master if interface is bond slave otherwise None. | ||
2816 | 710 | |||
2817 | 711 | NOTE: the provided interface is expected to be physical | ||
2818 | 712 | """ | ||
2819 | 713 | if interface: | ||
2820 | 714 | iface_path = '/sys/class/net/%s' % (interface) | ||
2821 | 715 | if os.path.exists(iface_path): | ||
2822 | 716 | if '/virtual/' in os.path.realpath(iface_path): | ||
2823 | 717 | return None | ||
2824 | 718 | |||
2825 | 719 | master = os.path.join(iface_path, 'master') | ||
2826 | 720 | if os.path.exists(master): | ||
2827 | 721 | master = os.path.realpath(master) | ||
2828 | 722 | # make sure it is a bond master | ||
2829 | 723 | if os.path.exists(os.path.join(master, 'bonding')): | ||
2830 | 724 | return os.path.basename(master) | ||
2831 | 725 | |||
2832 | 726 | return None | ||
2833 | 727 | |||
2834 | 728 | |||
2835 | 729 | def list_nics(nic_type=None): | ||
2836 | 730 | """Return a list of nics of given type(s)""" | ||
2837 | 731 | if isinstance(nic_type, six.string_types): | ||
2838 | 732 | int_types = [nic_type] | ||
2839 | 733 | else: | ||
2840 | 734 | int_types = nic_type | ||
2841 | 735 | |||
2842 | 736 | interfaces = [] | ||
2843 | 737 | if nic_type: | ||
2844 | 738 | for int_type in int_types: | ||
2845 | 739 | cmd = ['ip', 'addr', 'show', 'label', int_type + '*'] | ||
2846 | 740 | ip_output = subprocess.check_output(cmd).decode('UTF-8') | ||
2847 | 741 | ip_output = ip_output.split('\n') | ||
2848 | 742 | ip_output = (line for line in ip_output if line) | ||
2849 | 743 | for line in ip_output: | ||
2850 | 744 | if line.split()[1].startswith(int_type): | ||
2851 | 745 | matched = re.search('.*: (' + int_type + | ||
2852 | 746 | r'[0-9]+\.[0-9]+)@.*', line) | ||
2853 | 747 | if matched: | ||
2854 | 748 | iface = matched.groups()[0] | ||
2855 | 749 | else: | ||
2856 | 750 | iface = line.split()[1].replace(":", "") | ||
2857 | 751 | |||
2858 | 752 | if iface not in interfaces: | ||
2859 | 753 | interfaces.append(iface) | ||
2860 | 754 | else: | ||
2861 | 755 | cmd = ['ip', 'a'] | ||
2862 | 756 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
2863 | 757 | ip_output = (line.strip() for line in ip_output if line) | ||
2864 | 758 | |||
2865 | 759 | key = re.compile('^[0-9]+:\s+(.+):') | ||
2866 | 760 | for line in ip_output: | ||
2867 | 761 | matched = re.search(key, line) | ||
2868 | 762 | if matched: | ||
2869 | 763 | iface = matched.group(1) | ||
2870 | 764 | iface = iface.partition("@")[0] | ||
2871 | 765 | if iface not in interfaces: | ||
2872 | 766 | interfaces.append(iface) | ||
2873 | 767 | |||
2874 | 768 | return interfaces | ||
2875 | 769 | |||
2876 | 770 | |||
2877 | 771 | def set_nic_mtu(nic, mtu): | ||
2878 | 772 | """Set the Maximum Transmission Unit (MTU) on a network interface.""" | ||
2879 | 773 | cmd = ['ip', 'link', 'set', nic, 'mtu', mtu] | ||
2880 | 774 | subprocess.check_call(cmd) | ||
2881 | 775 | |||
2882 | 776 | |||
2883 | 777 | def get_nic_mtu(nic): | ||
2884 | 778 | """Return the Maximum Transmission Unit (MTU) for a network interface.""" | ||
2885 | 779 | cmd = ['ip', 'addr', 'show', nic] | ||
2886 | 780 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
2887 | 781 | mtu = "" | ||
2888 | 782 | for line in ip_output: | ||
2889 | 783 | words = line.split() | ||
2890 | 784 | if 'mtu' in words: | ||
2891 | 785 | mtu = words[words.index("mtu") + 1] | ||
2892 | 786 | return mtu | ||
2893 | 787 | |||
2894 | 788 | |||
2895 | 789 | def get_nic_hwaddr(nic): | ||
2896 | 790 | """Return the Media Access Control (MAC) for a network interface.""" | ||
2897 | 791 | cmd = ['ip', '-o', '-0', 'addr', 'show', nic] | ||
2898 | 792 | ip_output = subprocess.check_output(cmd).decode('UTF-8') | ||
2899 | 793 | hwaddr = "" | ||
2900 | 794 | words = ip_output.split() | ||
2901 | 795 | if 'link/ether' in words: | ||
2902 | 796 | hwaddr = words[words.index('link/ether') + 1] | ||
2903 | 797 | return hwaddr | ||
2904 | 798 | |||
2905 | 799 | |||
2906 | 800 | @contextmanager | ||
2907 | 801 | def chdir(directory): | ||
2908 | 802 | """Change the current working directory to a different directory for a code | ||
2909 | 803 | block and return the previous directory after the block exits. Useful to | ||
2910 | 804 | run commands from a specificed directory. | ||
2911 | 805 | |||
2912 | 806 | :param str directory: The directory path to change to for this context. | ||
2913 | 807 | """ | ||
2914 | 808 | cur = os.getcwd() | ||
2915 | 809 | try: | ||
2916 | 810 | yield os.chdir(directory) | ||
2917 | 811 | finally: | ||
2918 | 812 | os.chdir(cur) | ||
2919 | 813 | |||
2920 | 814 | |||
2921 | 815 | def chownr(path, owner, group, follow_links=True, chowntopdir=False): | ||
2922 | 816 | """Recursively change user and group ownership of files and directories | ||
2923 | 817 | in given path. Doesn't chown path itself by default, only its children. | ||
2924 | 818 | |||
2925 | 819 | :param str path: The string path to start changing ownership. | ||
2926 | 820 | :param str owner: The owner string to use when looking up the uid. | ||
2927 | 821 | :param str group: The group string to use when looking up the gid. | ||
2928 | 822 | :param bool follow_links: Also follow and chown links if True | ||
2929 | 823 | :param bool chowntopdir: Also chown path itself if True | ||
2930 | 824 | """ | ||
2931 | 825 | uid = pwd.getpwnam(owner).pw_uid | ||
2932 | 826 | gid = grp.getgrnam(group).gr_gid | ||
2933 | 827 | if follow_links: | ||
2934 | 828 | chown = os.chown | ||
2935 | 829 | else: | ||
2936 | 830 | chown = os.lchown | ||
2937 | 831 | |||
2938 | 832 | if chowntopdir: | ||
2939 | 833 | broken_symlink = os.path.lexists(path) and not os.path.exists(path) | ||
2940 | 834 | if not broken_symlink: | ||
2941 | 835 | chown(path, uid, gid) | ||
2942 | 836 | for root, dirs, files in os.walk(path, followlinks=follow_links): | ||
2943 | 837 | for name in dirs + files: | ||
2944 | 838 | full = os.path.join(root, name) | ||
2945 | 839 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | ||
2946 | 840 | if not broken_symlink: | ||
2947 | 841 | chown(full, uid, gid) | ||
2948 | 842 | |||
2949 | 843 | |||
2950 | 844 | def lchownr(path, owner, group): | ||
2951 | 845 | """Recursively change user and group ownership of files and directories | ||
2952 | 846 | in a given path, not following symbolic links. See the documentation for | ||
2953 | 847 | 'os.lchown' for more information. | ||
2954 | 848 | |||
2955 | 849 | :param str path: The string path to start changing ownership. | ||
2956 | 850 | :param str owner: The owner string to use when looking up the uid. | ||
2957 | 851 | :param str group: The group string to use when looking up the gid. | ||
2958 | 852 | """ | ||
2959 | 853 | chownr(path, owner, group, follow_links=False) | ||
2960 | 854 | |||
2961 | 855 | |||
2962 | 856 | def owner(path): | ||
2963 | 857 | """Returns a tuple containing the username & groupname owning the path. | ||
2964 | 858 | |||
2965 | 859 | :param str path: the string path to retrieve the ownership | ||
2966 | 860 | :return tuple(str, str): A (username, groupname) tuple containing the | ||
2967 | 861 | name of the user and group owning the path. | ||
2968 | 862 | :raises OSError: if the specified path does not exist | ||
2969 | 863 | """ | ||
2970 | 864 | stat = os.stat(path) | ||
2971 | 865 | username = pwd.getpwuid(stat.st_uid)[0] | ||
2972 | 866 | groupname = grp.getgrgid(stat.st_gid)[0] | ||
2973 | 867 | return username, groupname | ||
2974 | 868 | |||
2975 | 869 | |||
2976 | 870 | def get_total_ram(): | ||
2977 | 871 | """The total amount of system RAM in bytes. | ||
2978 | 872 | |||
2979 | 873 | This is what is reported by the OS, and may be overcommitted when | ||
2980 | 874 | there are multiple containers hosted on the same machine. | ||
2981 | 875 | """ | ||
2982 | 876 | with open('/proc/meminfo', 'r') as f: | ||
2983 | 877 | for line in f.readlines(): | ||
2984 | 878 | if line: | ||
2985 | 879 | key, value, unit = line.split() | ||
2986 | 880 | if key == 'MemTotal:': | ||
2987 | 881 | assert unit == 'kB', 'Unknown unit' | ||
2988 | 882 | return int(value) * 1024 # Classic, not KiB. | ||
2989 | 883 | raise NotImplementedError() | ||
2990 | 884 | |||
2991 | 885 | |||
2992 | 886 | UPSTART_CONTAINER_TYPE = '/run/container_type' | ||
2993 | 887 | |||
2994 | 888 | |||
2995 | 889 | def is_container(): | ||
2996 | 890 | """Determine whether unit is running in a container | ||
2997 | 891 | |||
2998 | 892 | @return: boolean indicating if unit is in a container | ||
2999 | 893 | """ | ||
3000 | 894 | if init_is_systemd(): | ||
3001 | 895 | # Detect using systemd-detect-virt | ||
3002 | 896 | return subprocess.call(['systemd-detect-virt', | ||
3003 | 897 | '--container']) == 0 | ||
3004 | 898 | else: | ||
3005 | 899 | # Detect using upstart container file marker | ||
3006 | 900 | return os.path.exists(UPSTART_CONTAINER_TYPE) | ||
3007 | 901 | |||
3008 | 902 | |||
3009 | 903 | def add_to_updatedb_prunepath(path, updatedb_path=UPDATEDB_PATH): | ||
3010 | 904 | with open(updatedb_path, 'r+') as f_id: | ||
3011 | 905 | updatedb_text = f_id.read() | ||
3012 | 906 | output = updatedb(updatedb_text, path) | ||
3013 | 907 | f_id.seek(0) | ||
3014 | 908 | f_id.write(output) | ||
3015 | 909 | f_id.truncate() | ||
3016 | 910 | |||
3017 | 911 | |||
3018 | 912 | def updatedb(updatedb_text, new_path): | ||
3019 | 913 | lines = [line for line in updatedb_text.split("\n")] | ||
3020 | 914 | for i, line in enumerate(lines): | ||
3021 | 915 | if line.startswith("PRUNEPATHS="): | ||
3022 | 916 | paths_line = line.split("=")[1].replace('"', '') | ||
3023 | 917 | paths = paths_line.split(" ") | ||
3024 | 918 | if new_path not in paths: | ||
3025 | 919 | paths.append(new_path) | ||
3026 | 920 | lines[i] = 'PRUNEPATHS="{}"'.format(' '.join(paths)) | ||
3027 | 921 | output = "\n".join(lines) | ||
3028 | 922 | return output | ||
3029 | diff --git a/hooks/charmhelpers/core/host_factory/__init__.py b/hooks/charmhelpers/core/host_factory/__init__.py | |||
3030 | 0 | new file mode 100644 | 923 | new file mode 100644 |
3031 | index 0000000..e69de29 | |||
3032 | --- /dev/null | |||
3033 | +++ b/hooks/charmhelpers/core/host_factory/__init__.py | |||
3034 | diff --git a/hooks/charmhelpers/core/host_factory/centos.py b/hooks/charmhelpers/core/host_factory/centos.py | |||
3035 | 1 | new file mode 100644 | 924 | new file mode 100644 |
3036 | index 0000000..7781a39 | |||
3037 | --- /dev/null | |||
3038 | +++ b/hooks/charmhelpers/core/host_factory/centos.py | |||
3039 | @@ -0,0 +1,72 @@ | |||
3040 | 1 | import subprocess | ||
3041 | 2 | import yum | ||
3042 | 3 | import os | ||
3043 | 4 | |||
3044 | 5 | from charmhelpers.core.strutils import BasicStringComparator | ||
3045 | 6 | |||
3046 | 7 | |||
3047 | 8 | class CompareHostReleases(BasicStringComparator): | ||
3048 | 9 | """Provide comparisons of Host releases. | ||
3049 | 10 | |||
3050 | 11 | Use in the form of | ||
3051 | 12 | |||
3052 | 13 | if CompareHostReleases(release) > 'trusty': | ||
3053 | 14 | # do something with mitaka | ||
3054 | 15 | """ | ||
3055 | 16 | |||
3056 | 17 | def __init__(self, item): | ||
3057 | 18 | raise NotImplementedError( | ||
3058 | 19 | "CompareHostReleases() is not implemented for CentOS") | ||
3059 | 20 | |||
3060 | 21 | |||
3061 | 22 | def service_available(service_name): | ||
3062 | 23 | # """Determine whether a system service is available.""" | ||
3063 | 24 | if os.path.isdir('/run/systemd/system'): | ||
3064 | 25 | cmd = ['systemctl', 'is-enabled', service_name] | ||
3065 | 26 | else: | ||
3066 | 27 | cmd = ['service', service_name, 'is-enabled'] | ||
3067 | 28 | return subprocess.call(cmd) == 0 | ||
3068 | 29 | |||
3069 | 30 | |||
3070 | 31 | def add_new_group(group_name, system_group=False, gid=None): | ||
3071 | 32 | cmd = ['groupadd'] | ||
3072 | 33 | if gid: | ||
3073 | 34 | cmd.extend(['--gid', str(gid)]) | ||
3074 | 35 | if system_group: | ||
3075 | 36 | cmd.append('-r') | ||
3076 | 37 | cmd.append(group_name) | ||
3077 | 38 | subprocess.check_call(cmd) | ||
3078 | 39 | |||
3079 | 40 | |||
3080 | 41 | def lsb_release(): | ||
3081 | 42 | """Return /etc/os-release in a dict.""" | ||
3082 | 43 | d = {} | ||
3083 | 44 | with open('/etc/os-release', 'r') as lsb: | ||
3084 | 45 | for l in lsb: | ||
3085 | 46 | s = l.split('=') | ||
3086 | 47 | if len(s) != 2: | ||
3087 | 48 | continue | ||
3088 | 49 | d[s[0].strip()] = s[1].strip() | ||
3089 | 50 | return d | ||
3090 | 51 | |||
3091 | 52 | |||
3092 | 53 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
3093 | 54 | """Compare supplied revno with the revno of the installed package. | ||
3094 | 55 | |||
3095 | 56 | * 1 => Installed revno is greater than supplied arg | ||
3096 | 57 | * 0 => Installed revno is the same as supplied arg | ||
3097 | 58 | * -1 => Installed revno is less than supplied arg | ||
3098 | 59 | |||
3099 | 60 | This function imports YumBase function if the pkgcache argument | ||
3100 | 61 | is None. | ||
3101 | 62 | """ | ||
3102 | 63 | if not pkgcache: | ||
3103 | 64 | y = yum.YumBase() | ||
3104 | 65 | packages = y.doPackageLists() | ||
3105 | 66 | pkgcache = {i.Name: i.version for i in packages['installed']} | ||
3106 | 67 | pkg = pkgcache[package] | ||
3107 | 68 | if pkg > revno: | ||
3108 | 69 | return 1 | ||
3109 | 70 | if pkg < revno: | ||
3110 | 71 | return -1 | ||
3111 | 72 | return 0 | ||
3112 | diff --git a/hooks/charmhelpers/core/host_factory/ubuntu.py b/hooks/charmhelpers/core/host_factory/ubuntu.py | |||
3113 | 0 | new file mode 100644 | 73 | new file mode 100644 |
3114 | index 0000000..0448288 | |||
3115 | --- /dev/null | |||
3116 | +++ b/hooks/charmhelpers/core/host_factory/ubuntu.py | |||
3117 | @@ -0,0 +1,88 @@ | |||
3118 | 1 | import subprocess | ||
3119 | 2 | |||
3120 | 3 | from charmhelpers.core.strutils import BasicStringComparator | ||
3121 | 4 | |||
3122 | 5 | |||
3123 | 6 | UBUNTU_RELEASES = ( | ||
3124 | 7 | 'lucid', | ||
3125 | 8 | 'maverick', | ||
3126 | 9 | 'natty', | ||
3127 | 10 | 'oneiric', | ||
3128 | 11 | 'precise', | ||
3129 | 12 | 'quantal', | ||
3130 | 13 | 'raring', | ||
3131 | 14 | 'saucy', | ||
3132 | 15 | 'trusty', | ||
3133 | 16 | 'utopic', | ||
3134 | 17 | 'vivid', | ||
3135 | 18 | 'wily', | ||
3136 | 19 | 'xenial', | ||
3137 | 20 | 'yakkety', | ||
3138 | 21 | 'zesty', | ||
3139 | 22 | ) | ||
3140 | 23 | |||
3141 | 24 | |||
3142 | 25 | class CompareHostReleases(BasicStringComparator): | ||
3143 | 26 | """Provide comparisons of Ubuntu releases. | ||
3144 | 27 | |||
3145 | 28 | Use in the form of | ||
3146 | 29 | |||
3147 | 30 | if CompareHostReleases(release) > 'trusty': | ||
3148 | 31 | # do something with mitaka | ||
3149 | 32 | """ | ||
3150 | 33 | _list = UBUNTU_RELEASES | ||
3151 | 34 | |||
3152 | 35 | |||
3153 | 36 | def service_available(service_name): | ||
3154 | 37 | """Determine whether a system service is available""" | ||
3155 | 38 | try: | ||
3156 | 39 | subprocess.check_output( | ||
3157 | 40 | ['service', service_name, 'status'], | ||
3158 | 41 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
3159 | 42 | except subprocess.CalledProcessError as e: | ||
3160 | 43 | return b'unrecognized service' not in e.output | ||
3161 | 44 | else: | ||
3162 | 45 | return True | ||
3163 | 46 | |||
3164 | 47 | |||
3165 | 48 | def add_new_group(group_name, system_group=False, gid=None): | ||
3166 | 49 | cmd = ['addgroup'] | ||
3167 | 50 | if gid: | ||
3168 | 51 | cmd.extend(['--gid', str(gid)]) | ||
3169 | 52 | if system_group: | ||
3170 | 53 | cmd.append('--system') | ||
3171 | 54 | else: | ||
3172 | 55 | cmd.extend([ | ||
3173 | 56 | '--group', | ||
3174 | 57 | ]) | ||
3175 | 58 | cmd.append(group_name) | ||
3176 | 59 | subprocess.check_call(cmd) | ||
3177 | 60 | |||
3178 | 61 | |||
3179 | 62 | def lsb_release(): | ||
3180 | 63 | """Return /etc/lsb-release in a dict""" | ||
3181 | 64 | d = {} | ||
3182 | 65 | with open('/etc/lsb-release', 'r') as lsb: | ||
3183 | 66 | for l in lsb: | ||
3184 | 67 | k, v = l.split('=') | ||
3185 | 68 | d[k.strip()] = v.strip() | ||
3186 | 69 | return d | ||
3187 | 70 | |||
3188 | 71 | |||
3189 | 72 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
3190 | 73 | """Compare supplied revno with the revno of the installed package. | ||
3191 | 74 | |||
3192 | 75 | * 1 => Installed revno is greater than supplied arg | ||
3193 | 76 | * 0 => Installed revno is the same as supplied arg | ||
3194 | 77 | * -1 => Installed revno is less than supplied arg | ||
3195 | 78 | |||
3196 | 79 | This function imports apt_cache function from charmhelpers.fetch if | ||
3197 | 80 | the pkgcache argument is None. Be sure to add charmhelpers.fetch if | ||
3198 | 81 | you call this function, or pass an apt_pkg.Cache() instance. | ||
3199 | 82 | """ | ||
3200 | 83 | import apt_pkg | ||
3201 | 84 | if not pkgcache: | ||
3202 | 85 | from charmhelpers.fetch import apt_cache | ||
3203 | 86 | pkgcache = apt_cache() | ||
3204 | 87 | pkg = pkgcache[package] | ||
3205 | 88 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | ||
3206 | diff --git a/hooks/charmhelpers/core/hugepage.py b/hooks/charmhelpers/core/hugepage.py | |||
3207 | 0 | new file mode 100644 | 89 | new file mode 100644 |
3208 | index 0000000..54b5b5e | |||
3209 | --- /dev/null | |||
3210 | +++ b/hooks/charmhelpers/core/hugepage.py | |||
3211 | @@ -0,0 +1,69 @@ | |||
3212 | 1 | # -*- coding: utf-8 -*- | ||
3213 | 2 | |||
3214 | 3 | # Copyright 2014-2015 Canonical Limited. | ||
3215 | 4 | # | ||
3216 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
3217 | 6 | # you may not use this file except in compliance with the License. | ||
3218 | 7 | # You may obtain a copy of the License at | ||
3219 | 8 | # | ||
3220 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
3221 | 10 | # | ||
3222 | 11 | # Unless required by applicable law or agreed to in writing, software | ||
3223 | 12 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
3224 | 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
3225 | 14 | # See the License for the specific language governing permissions and | ||
3226 | 15 | # limitations under the License. | ||
3227 | 16 | |||
3228 | 17 | import yaml | ||
3229 | 18 | from charmhelpers.core import fstab | ||
3230 | 19 | from charmhelpers.core import sysctl | ||
3231 | 20 | from charmhelpers.core.host import ( | ||
3232 | 21 | add_group, | ||
3233 | 22 | add_user_to_group, | ||
3234 | 23 | fstab_mount, | ||
3235 | 24 | mkdir, | ||
3236 | 25 | ) | ||
3237 | 26 | from charmhelpers.core.strutils import bytes_from_string | ||
3238 | 27 | from subprocess import check_output | ||
3239 | 28 | |||
3240 | 29 | |||
3241 | 30 | def hugepage_support(user, group='hugetlb', nr_hugepages=256, | ||
3242 | 31 | max_map_count=65536, mnt_point='/run/hugepages/kvm', | ||
3243 | 32 | pagesize='2MB', mount=True, set_shmmax=False): | ||
3244 | 33 | """Enable hugepages on system. | ||
3245 | 34 | |||
3246 | 35 | Args: | ||
3247 | 36 | user (str) -- Username to allow access to hugepages to | ||
3248 | 37 | group (str) -- Group name to own hugepages | ||
3249 | 38 | nr_hugepages (int) -- Number of pages to reserve | ||
3250 | 39 | max_map_count (int) -- Number of Virtual Memory Areas a process can own | ||
3251 | 40 | mnt_point (str) -- Directory to mount hugepages on | ||
3252 | 41 | pagesize (str) -- Size of hugepages | ||
3253 | 42 | mount (bool) -- Whether to Mount hugepages | ||
3254 | 43 | """ | ||
3255 | 44 | group_info = add_group(group) | ||
3256 | 45 | gid = group_info.gr_gid | ||
3257 | 46 | add_user_to_group(user, group) | ||
3258 | 47 | if max_map_count < 2 * nr_hugepages: | ||
3259 | 48 | max_map_count = 2 * nr_hugepages | ||
3260 | 49 | sysctl_settings = { | ||
3261 | 50 | 'vm.nr_hugepages': nr_hugepages, | ||
3262 | 51 | 'vm.max_map_count': max_map_count, | ||
3263 | 52 | 'vm.hugetlb_shm_group': gid, | ||
3264 | 53 | } | ||
3265 | 54 | if set_shmmax: | ||
3266 | 55 | shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax'])) | ||
3267 | 56 | shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages | ||
3268 | 57 | if shmmax_minsize > shmmax_current: | ||
3269 | 58 | sysctl_settings['kernel.shmmax'] = shmmax_minsize | ||
3270 | 59 | sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf') | ||
3271 | 60 | mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False) | ||
3272 | 61 | lfstab = fstab.Fstab() | ||
3273 | 62 | fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point) | ||
3274 | 63 | if fstab_entry: | ||
3275 | 64 | lfstab.remove_entry(fstab_entry) | ||
3276 | 65 | entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs', | ||
3277 | 66 | 'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0) | ||
3278 | 67 | lfstab.add_entry(entry) | ||
3279 | 68 | if mount: | ||
3280 | 69 | fstab_mount(mnt_point) | ||
3281 | diff --git a/hooks/charmhelpers/core/kernel.py b/hooks/charmhelpers/core/kernel.py | |||
3282 | 0 | new file mode 100644 | 70 | new file mode 100644 |
3283 | index 0000000..2d40452 | |||
3284 | --- /dev/null | |||
3285 | +++ b/hooks/charmhelpers/core/kernel.py | |||
3286 | @@ -0,0 +1,72 @@ | |||
3287 | 1 | #!/usr/bin/env python | ||
3288 | 2 | # -*- coding: utf-8 -*- | ||
3289 | 3 | |||
3290 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
3291 | 5 | # | ||
3292 | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
3293 | 7 | # you may not use this file except in compliance with the License. | ||
3294 | 8 | # You may obtain a copy of the License at | ||
3295 | 9 | # | ||
3296 | 10 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
3297 | 11 | # | ||
3298 | 12 | # Unless required by applicable law or agreed to in writing, software | ||
3299 | 13 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
3300 | 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
3301 | 15 | # See the License for the specific language governing permissions and | ||
3302 | 16 | # limitations under the License. | ||
3303 | 17 | |||
3304 | 18 | import re | ||
3305 | 19 | import subprocess | ||
3306 | 20 | |||
3307 | 21 | from charmhelpers.osplatform import get_platform | ||
3308 | 22 | from charmhelpers.core.hookenv import ( | ||
3309 | 23 | log, | ||
3310 | 24 | INFO | ||
3311 | 25 | ) | ||
3312 | 26 | |||
3313 | 27 | __platform__ = get_platform() | ||
3314 | 28 | if __platform__ == "ubuntu": | ||
3315 | 29 | from charmhelpers.core.kernel_factory.ubuntu import ( | ||
3316 | 30 | persistent_modprobe, | ||
3317 | 31 | update_initramfs, | ||
3318 | 32 | ) # flake8: noqa -- ignore F401 for this import | ||
3319 | 33 | elif __platform__ == "centos": | ||
3320 | 34 | from charmhelpers.core.kernel_factory.centos import ( | ||
3321 | 35 | persistent_modprobe, | ||
3322 | 36 | update_initramfs, | ||
3323 | 37 | ) # flake8: noqa -- ignore F401 for this import | ||
3324 | 38 | |||
3325 | 39 | __author__ = "Jorge Niedbalski <jorge.niedbalski@canonical.com>" | ||
3326 | 40 | |||
3327 | 41 | |||
3328 | 42 | def modprobe(module, persist=True): | ||
3329 | 43 | """Load a kernel module and configure for auto-load on reboot.""" | ||
3330 | 44 | cmd = ['modprobe', module] | ||
3331 | 45 | |||
3332 | 46 | log('Loading kernel module %s' % module, level=INFO) | ||
3333 | 47 | |||
3334 | 48 | subprocess.check_call(cmd) | ||
3335 | 49 | if persist: | ||
3336 | 50 | persistent_modprobe(module) | ||
3337 | 51 | |||
3338 | 52 | |||
3339 | 53 | def rmmod(module, force=False): | ||
3340 | 54 | """Remove a module from the linux kernel""" | ||
3341 | 55 | cmd = ['rmmod'] | ||
3342 | 56 | if force: | ||
3343 | 57 | cmd.append('-f') | ||
3344 | 58 | cmd.append(module) | ||
3345 | 59 | log('Removing kernel module %s' % module, level=INFO) | ||
3346 | 60 | return subprocess.check_call(cmd) | ||
3347 | 61 | |||
3348 | 62 | |||
3349 | 63 | def lsmod(): | ||
3350 | 64 | """Shows what kernel modules are currently loaded""" | ||
3351 | 65 | return subprocess.check_output(['lsmod'], | ||
3352 | 66 | universal_newlines=True) | ||
3353 | 67 | |||
3354 | 68 | |||
3355 | 69 | def is_module_loaded(module): | ||
3356 | 70 | """Checks if a kernel module is already loaded""" | ||
3357 | 71 | matches = re.findall('^%s[ ]+' % module, lsmod(), re.M) | ||
3358 | 72 | return len(matches) > 0 | ||
3359 | diff --git a/hooks/charmhelpers/core/kernel_factory/__init__.py b/hooks/charmhelpers/core/kernel_factory/__init__.py | |||
3360 | 0 | new file mode 100644 | 73 | new file mode 100644 |
3361 | index 0000000..e69de29 | |||
3362 | --- /dev/null | |||
3363 | +++ b/hooks/charmhelpers/core/kernel_factory/__init__.py | |||
3364 | diff --git a/hooks/charmhelpers/core/kernel_factory/centos.py b/hooks/charmhelpers/core/kernel_factory/centos.py | |||
3365 | 1 | new file mode 100644 | 74 | new file mode 100644 |
3366 | index 0000000..1c402c1 | |||
3367 | --- /dev/null | |||
3368 | +++ b/hooks/charmhelpers/core/kernel_factory/centos.py | |||
3369 | @@ -0,0 +1,17 @@ | |||
3370 | 1 | import subprocess | ||
3371 | 2 | import os | ||
3372 | 3 | |||
3373 | 4 | |||
3374 | 5 | def persistent_modprobe(module): | ||
3375 | 6 | """Load a kernel module and configure for auto-load on reboot.""" | ||
3376 | 7 | if not os.path.exists('/etc/rc.modules'): | ||
3377 | 8 | open('/etc/rc.modules', 'a') | ||
3378 | 9 | os.chmod('/etc/rc.modules', 111) | ||
3379 | 10 | with open('/etc/rc.modules', 'r+') as modules: | ||
3380 | 11 | if module not in modules.read(): | ||
3381 | 12 | modules.write('modprobe %s\n' % module) | ||
3382 | 13 | |||
3383 | 14 | |||
3384 | 15 | def update_initramfs(version='all'): | ||
3385 | 16 | """Updates an initramfs image.""" | ||
3386 | 17 | return subprocess.check_call(["dracut", "-f", version]) | ||
3387 | diff --git a/hooks/charmhelpers/core/kernel_factory/ubuntu.py b/hooks/charmhelpers/core/kernel_factory/ubuntu.py | |||
3388 | 0 | new file mode 100644 | 18 | new file mode 100644 |
3389 | index 0000000..3de372f | |||
3390 | --- /dev/null | |||
3391 | +++ b/hooks/charmhelpers/core/kernel_factory/ubuntu.py | |||
3392 | @@ -0,0 +1,13 @@ | |||
3393 | 1 | import subprocess | ||
3394 | 2 | |||
3395 | 3 | |||
3396 | 4 | def persistent_modprobe(module): | ||
3397 | 5 | """Load a kernel module and configure for auto-load on reboot.""" | ||
3398 | 6 | with open('/etc/modules', 'r+') as modules: | ||
3399 | 7 | if module not in modules.read(): | ||
3400 | 8 | modules.write(module + "\n") | ||
3401 | 9 | |||
3402 | 10 | |||
3403 | 11 | def update_initramfs(version='all'): | ||
3404 | 12 | """Updates an initramfs image.""" | ||
3405 | 13 | return subprocess.check_call(["update-initramfs", "-k", version, "-u"]) | ||
3406 | diff --git a/hooks/charmhelpers/core/services/__init__.py b/hooks/charmhelpers/core/services/__init__.py | |||
3407 | 0 | new file mode 100644 | 14 | new file mode 100644 |
3408 | index 0000000..61fd074 | |||
3409 | --- /dev/null | |||
3410 | +++ b/hooks/charmhelpers/core/services/__init__.py | |||
3411 | @@ -0,0 +1,16 @@ | |||
3412 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3413 | 2 | # | ||
3414 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
3415 | 4 | # you may not use this file except in compliance with the License. | ||
3416 | 5 | # You may obtain a copy of the License at | ||
3417 | 6 | # | ||
3418 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
3419 | 8 | # | ||
3420 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
3421 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
3422 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
3423 | 12 | # See the License for the specific language governing permissions and | ||
3424 | 13 | # limitations under the License. | ||
3425 | 14 | |||
3426 | 15 | from .base import * # NOQA | ||
3427 | 16 | from .helpers import * # NOQA | ||
3428 | diff --git a/hooks/charmhelpers/core/services/base.py b/hooks/charmhelpers/core/services/base.py | |||
3429 | 0 | new file mode 100644 | 17 | new file mode 100644 |
3430 | index 0000000..ca9dc99 | |||
3431 | --- /dev/null | |||
3432 | +++ b/hooks/charmhelpers/core/services/base.py | |||
3433 | @@ -0,0 +1,351 @@ | |||
3434 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3435 | 2 | # | ||
3436 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
3437 | 4 | # you may not use this file except in compliance with the License. | ||
3438 | 5 | # You may obtain a copy of the License at | ||
3439 | 6 | # | ||
3440 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
3441 | 8 | # | ||
3442 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
3443 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
3444 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
3445 | 12 | # See the License for the specific language governing permissions and | ||
3446 | 13 | # limitations under the License. | ||
3447 | 14 | |||
3448 | 15 | import os | ||
3449 | 16 | import json | ||
3450 | 17 | from inspect import getargspec | ||
3451 | 18 | from collections import Iterable, OrderedDict | ||
3452 | 19 | |||
3453 | 20 | from charmhelpers.core import host | ||
3454 | 21 | from charmhelpers.core import hookenv | ||
3455 | 22 | |||
3456 | 23 | |||
3457 | 24 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
3458 | 25 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
3459 | 26 | 'service_restart', 'service_stop'] | ||
3460 | 27 | |||
3461 | 28 | |||
3462 | 29 | class ServiceManager(object): | ||
3463 | 30 | def __init__(self, services=None): | ||
3464 | 31 | """ | ||
3465 | 32 | Register a list of services, given their definitions. | ||
3466 | 33 | |||
3467 | 34 | Service definitions are dicts in the following formats (all keys except | ||
3468 | 35 | 'service' are optional):: | ||
3469 | 36 | |||
3470 | 37 | { | ||
3471 | 38 | "service": <service name>, | ||
3472 | 39 | "required_data": <list of required data contexts>, | ||
3473 | 40 | "provided_data": <list of provided data contexts>, | ||
3474 | 41 | "data_ready": <one or more callbacks>, | ||
3475 | 42 | "data_lost": <one or more callbacks>, | ||
3476 | 43 | "start": <one or more callbacks>, | ||
3477 | 44 | "stop": <one or more callbacks>, | ||
3478 | 45 | "ports": <list of ports to manage>, | ||
3479 | 46 | } | ||
3480 | 47 | |||
3481 | 48 | The 'required_data' list should contain dicts of required data (or | ||
3482 | 49 | dependency managers that act like dicts and know how to collect the data). | ||
3483 | 50 | Only when all items in the 'required_data' list are populated are the list | ||
3484 | 51 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
3485 | 52 | information. | ||
3486 | 53 | |||
3487 | 54 | The 'provided_data' list should contain relation data providers, most likely | ||
3488 | 55 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
3489 | 56 | that will indicate a set of data to set on a given relation. | ||
3490 | 57 | |||
3491 | 58 | The 'data_ready' value should be either a single callback, or a list of | ||
3492 | 59 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
3493 | 60 | Each callback will be called with the service name as the only parameter. | ||
3494 | 61 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
3495 | 62 | are fired. | ||
3496 | 63 | |||
3497 | 64 | The 'data_lost' value should be either a single callback, or a list of | ||
3498 | 65 | callbacks, to be called when a 'required_data' item no longer passes | ||
3499 | 66 | `is_ready()`. Each callback will be called with the service name as the | ||
3500 | 67 | only parameter. After all of the 'data_lost' callbacks are called, | ||
3501 | 68 | the 'stop' callbacks are fired. | ||
3502 | 69 | |||
3503 | 70 | The 'start' value should be either a single callback, or a list of | ||
3504 | 71 | callbacks, to be called when starting the service, after the 'data_ready' | ||
3505 | 72 | callbacks are complete. Each callback will be called with the service | ||
3506 | 73 | name as the only parameter. This defaults to | ||
3507 | 74 | `[host.service_start, services.open_ports]`. | ||
3508 | 75 | |||
3509 | 76 | The 'stop' value should be either a single callback, or a list of | ||
3510 | 77 | callbacks, to be called when stopping the service. If the service is | ||
3511 | 78 | being stopped because it no longer has all of its 'required_data', this | ||
3512 | 79 | will be called after all of the 'data_lost' callbacks are complete. | ||
3513 | 80 | Each callback will be called with the service name as the only parameter. | ||
3514 | 81 | This defaults to `[services.close_ports, host.service_stop]`. | ||
3515 | 82 | |||
3516 | 83 | The 'ports' value should be a list of ports to manage. The default | ||
3517 | 84 | 'start' handler will open the ports after the service is started, | ||
3518 | 85 | and the default 'stop' handler will close the ports prior to stopping | ||
3519 | 86 | the service. | ||
3520 | 87 | |||
3521 | 88 | |||
3522 | 89 | Examples: | ||
3523 | 90 | |||
3524 | 91 | The following registers an Upstart service called bingod that depends on | ||
3525 | 92 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
3526 | 93 | restarting the service, and a Runit service called spadesd:: | ||
3527 | 94 | |||
3528 | 95 | manager = services.ServiceManager([ | ||
3529 | 96 | { | ||
3530 | 97 | 'service': 'bingod', | ||
3531 | 98 | 'ports': [80, 443], | ||
3532 | 99 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
3533 | 100 | 'data_ready': [ | ||
3534 | 101 | services.template(source='bingod.conf'), | ||
3535 | 102 | services.template(source='bingod.ini', | ||
3536 | 103 | target='/etc/bingod.ini', | ||
3537 | 104 | owner='bingo', perms=0400), | ||
3538 | 105 | ], | ||
3539 | 106 | }, | ||
3540 | 107 | { | ||
3541 | 108 | 'service': 'spadesd', | ||
3542 | 109 | 'data_ready': services.template(source='spadesd_run.j2', | ||
3543 | 110 | target='/etc/sv/spadesd/run', | ||
3544 | 111 | perms=0555), | ||
3545 | 112 | 'start': runit_start, | ||
3546 | 113 | 'stop': runit_stop, | ||
3547 | 114 | }, | ||
3548 | 115 | ]) | ||
3549 | 116 | manager.manage() | ||
3550 | 117 | """ | ||
3551 | 118 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
3552 | 119 | self._ready = None | ||
3553 | 120 | self.services = OrderedDict() | ||
3554 | 121 | for service in services or []: | ||
3555 | 122 | service_name = service['service'] | ||
3556 | 123 | self.services[service_name] = service | ||
3557 | 124 | |||
3558 | 125 | def manage(self): | ||
3559 | 126 | """ | ||
3560 | 127 | Handle the current hook by doing The Right Thing with the registered services. | ||
3561 | 128 | """ | ||
3562 | 129 | hookenv._run_atstart() | ||
3563 | 130 | try: | ||
3564 | 131 | hook_name = hookenv.hook_name() | ||
3565 | 132 | if hook_name == 'stop': | ||
3566 | 133 | self.stop_services() | ||
3567 | 134 | else: | ||
3568 | 135 | self.reconfigure_services() | ||
3569 | 136 | self.provide_data() | ||
3570 | 137 | except SystemExit as x: | ||
3571 | 138 | if x.code is None or x.code == 0: | ||
3572 | 139 | hookenv._run_atexit() | ||
3573 | 140 | hookenv._run_atexit() | ||
3574 | 141 | |||
3575 | 142 | def provide_data(self): | ||
3576 | 143 | """ | ||
3577 | 144 | Set the relation data for each provider in the ``provided_data`` list. | ||
3578 | 145 | |||
3579 | 146 | A provider must have a `name` attribute, which indicates which relation | ||
3580 | 147 | to set data on, and a `provide_data()` method, which returns a dict of | ||
3581 | 148 | data to set. | ||
3582 | 149 | |||
3583 | 150 | The `provide_data()` method can optionally accept two parameters: | ||
3584 | 151 | |||
3585 | 152 | * ``remote_service`` The name of the remote service that the data will | ||
3586 | 153 | be provided to. The `provide_data()` method will be called once | ||
3587 | 154 | for each connected service (not unit). This allows the method to | ||
3588 | 155 | tailor its data to the given service. | ||
3589 | 156 | * ``service_ready`` Whether or not the service definition had all of | ||
3590 | 157 | its requirements met, and thus the ``data_ready`` callbacks run. | ||
3591 | 158 | |||
3592 | 159 | Note that the ``provided_data`` methods are now called **after** the | ||
3593 | 160 | ``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks | ||
3594 | 161 | a chance to generate any data necessary for the providing to the remote | ||
3595 | 162 | services. | ||
3596 | 163 | """ | ||
3597 | 164 | for service_name, service in self.services.items(): | ||
3598 | 165 | service_ready = self.is_ready(service_name) | ||
3599 | 166 | for provider in service.get('provided_data', []): | ||
3600 | 167 | for relid in hookenv.relation_ids(provider.name): | ||
3601 | 168 | units = hookenv.related_units(relid) | ||
3602 | 169 | if not units: | ||
3603 | 170 | continue | ||
3604 | 171 | remote_service = units[0].split('/')[0] | ||
3605 | 172 | argspec = getargspec(provider.provide_data) | ||
3606 | 173 | if len(argspec.args) > 1: | ||
3607 | 174 | data = provider.provide_data(remote_service, service_ready) | ||
3608 | 175 | else: | ||
3609 | 176 | data = provider.provide_data() | ||
3610 | 177 | if data: | ||
3611 | 178 | hookenv.relation_set(relid, data) | ||
3612 | 179 | |||
3613 | 180 | def reconfigure_services(self, *service_names): | ||
3614 | 181 | """ | ||
3615 | 182 | Update all files for one or more registered services, and, | ||
3616 | 183 | if ready, optionally restart them. | ||
3617 | 184 | |||
3618 | 185 | If no service names are given, reconfigures all registered services. | ||
3619 | 186 | """ | ||
3620 | 187 | for service_name in service_names or self.services.keys(): | ||
3621 | 188 | if self.is_ready(service_name): | ||
3622 | 189 | self.fire_event('data_ready', service_name) | ||
3623 | 190 | self.fire_event('start', service_name, default=[ | ||
3624 | 191 | service_restart, | ||
3625 | 192 | manage_ports]) | ||
3626 | 193 | self.save_ready(service_name) | ||
3627 | 194 | else: | ||
3628 | 195 | if self.was_ready(service_name): | ||
3629 | 196 | self.fire_event('data_lost', service_name) | ||
3630 | 197 | self.fire_event('stop', service_name, default=[ | ||
3631 | 198 | manage_ports, | ||
3632 | 199 | service_stop]) | ||
3633 | 200 | self.save_lost(service_name) | ||
3634 | 201 | |||
3635 | 202 | def stop_services(self, *service_names): | ||
3636 | 203 | """ | ||
3637 | 204 | Stop one or more registered services, by name. | ||
3638 | 205 | |||
3639 | 206 | If no service names are given, stops all registered services. | ||
3640 | 207 | """ | ||
3641 | 208 | for service_name in service_names or self.services.keys(): | ||
3642 | 209 | self.fire_event('stop', service_name, default=[ | ||
3643 | 210 | manage_ports, | ||
3644 | 211 | service_stop]) | ||
3645 | 212 | |||
3646 | 213 | def get_service(self, service_name): | ||
3647 | 214 | """ | ||
3648 | 215 | Given the name of a registered service, return its service definition. | ||
3649 | 216 | """ | ||
3650 | 217 | service = self.services.get(service_name) | ||
3651 | 218 | if not service: | ||
3652 | 219 | raise KeyError('Service not registered: %s' % service_name) | ||
3653 | 220 | return service | ||
3654 | 221 | |||
3655 | 222 | def fire_event(self, event_name, service_name, default=None): | ||
3656 | 223 | """ | ||
3657 | 224 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
3658 | 225 | """ | ||
3659 | 226 | service = self.get_service(service_name) | ||
3660 | 227 | callbacks = service.get(event_name, default) | ||
3661 | 228 | if not callbacks: | ||
3662 | 229 | return | ||
3663 | 230 | if not isinstance(callbacks, Iterable): | ||
3664 | 231 | callbacks = [callbacks] | ||
3665 | 232 | for callback in callbacks: | ||
3666 | 233 | if isinstance(callback, ManagerCallback): | ||
3667 | 234 | callback(self, service_name, event_name) | ||
3668 | 235 | else: | ||
3669 | 236 | callback(service_name) | ||
3670 | 237 | |||
3671 | 238 | def is_ready(self, service_name): | ||
3672 | 239 | """ | ||
3673 | 240 | Determine if a registered service is ready, by checking its 'required_data'. | ||
3674 | 241 | |||
3675 | 242 | A 'required_data' item can be any mapping type, and is considered ready | ||
3676 | 243 | if `bool(item)` evaluates as True. | ||
3677 | 244 | """ | ||
3678 | 245 | service = self.get_service(service_name) | ||
3679 | 246 | reqs = service.get('required_data', []) | ||
3680 | 247 | return all(bool(req) for req in reqs) | ||
3681 | 248 | |||
3682 | 249 | def _load_ready_file(self): | ||
3683 | 250 | if self._ready is not None: | ||
3684 | 251 | return | ||
3685 | 252 | if os.path.exists(self._ready_file): | ||
3686 | 253 | with open(self._ready_file) as fp: | ||
3687 | 254 | self._ready = set(json.load(fp)) | ||
3688 | 255 | else: | ||
3689 | 256 | self._ready = set() | ||
3690 | 257 | |||
3691 | 258 | def _save_ready_file(self): | ||
3692 | 259 | if self._ready is None: | ||
3693 | 260 | return | ||
3694 | 261 | with open(self._ready_file, 'w') as fp: | ||
3695 | 262 | json.dump(list(self._ready), fp) | ||
3696 | 263 | |||
3697 | 264 | def save_ready(self, service_name): | ||
3698 | 265 | """ | ||
3699 | 266 | Save an indicator that the given service is now data_ready. | ||
3700 | 267 | """ | ||
3701 | 268 | self._load_ready_file() | ||
3702 | 269 | self._ready.add(service_name) | ||
3703 | 270 | self._save_ready_file() | ||
3704 | 271 | |||
3705 | 272 | def save_lost(self, service_name): | ||
3706 | 273 | """ | ||
3707 | 274 | Save an indicator that the given service is no longer data_ready. | ||
3708 | 275 | """ | ||
3709 | 276 | self._load_ready_file() | ||
3710 | 277 | self._ready.discard(service_name) | ||
3711 | 278 | self._save_ready_file() | ||
3712 | 279 | |||
3713 | 280 | def was_ready(self, service_name): | ||
3714 | 281 | """ | ||
3715 | 282 | Determine if the given service was previously data_ready. | ||
3716 | 283 | """ | ||
3717 | 284 | self._load_ready_file() | ||
3718 | 285 | return service_name in self._ready | ||
3719 | 286 | |||
3720 | 287 | |||
3721 | 288 | class ManagerCallback(object): | ||
3722 | 289 | """ | ||
3723 | 290 | Special case of a callback that takes the `ServiceManager` instance | ||
3724 | 291 | in addition to the service name. | ||
3725 | 292 | |||
3726 | 293 | Subclasses should implement `__call__` which should accept three parameters: | ||
3727 | 294 | |||
3728 | 295 | * `manager` The `ServiceManager` instance | ||
3729 | 296 | * `service_name` The name of the service it's being triggered for | ||
3730 | 297 | * `event_name` The name of the event that this callback is handling | ||
3731 | 298 | """ | ||
3732 | 299 | def __call__(self, manager, service_name, event_name): | ||
3733 | 300 | raise NotImplementedError() | ||
3734 | 301 | |||
3735 | 302 | |||
3736 | 303 | class PortManagerCallback(ManagerCallback): | ||
3737 | 304 | """ | ||
3738 | 305 | Callback class that will open or close ports, for use as either | ||
3739 | 306 | a start or stop action. | ||
3740 | 307 | """ | ||
3741 | 308 | def __call__(self, manager, service_name, event_name): | ||
3742 | 309 | service = manager.get_service(service_name) | ||
3743 | 310 | new_ports = service.get('ports', []) | ||
3744 | 311 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
3745 | 312 | if os.path.exists(port_file): | ||
3746 | 313 | with open(port_file) as fp: | ||
3747 | 314 | old_ports = fp.read().split(',') | ||
3748 | 315 | for old_port in old_ports: | ||
3749 | 316 | if bool(old_port): | ||
3750 | 317 | old_port = int(old_port) | ||
3751 | 318 | if old_port not in new_ports: | ||
3752 | 319 | hookenv.close_port(old_port) | ||
3753 | 320 | with open(port_file, 'w') as fp: | ||
3754 | 321 | fp.write(','.join(str(port) for port in new_ports)) | ||
3755 | 322 | for port in new_ports: | ||
3756 | 323 | if event_name == 'start': | ||
3757 | 324 | hookenv.open_port(port) | ||
3758 | 325 | elif event_name == 'stop': | ||
3759 | 326 | hookenv.close_port(port) | ||
3760 | 327 | |||
3761 | 328 | |||
3762 | 329 | def service_stop(service_name): | ||
3763 | 330 | """ | ||
3764 | 331 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
3765 | 332 | messages in the logs. | ||
3766 | 333 | """ | ||
3767 | 334 | if host.service_running(service_name): | ||
3768 | 335 | host.service_stop(service_name) | ||
3769 | 336 | |||
3770 | 337 | |||
3771 | 338 | def service_restart(service_name): | ||
3772 | 339 | """ | ||
3773 | 340 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
3774 | 341 | messages in the logs. | ||
3775 | 342 | """ | ||
3776 | 343 | if host.service_available(service_name): | ||
3777 | 344 | if host.service_running(service_name): | ||
3778 | 345 | host.service_restart(service_name) | ||
3779 | 346 | else: | ||
3780 | 347 | host.service_start(service_name) | ||
3781 | 348 | |||
3782 | 349 | |||
3783 | 350 | # Convenience aliases | ||
3784 | 351 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
3785 | diff --git a/hooks/charmhelpers/core/services/helpers.py b/hooks/charmhelpers/core/services/helpers.py | |||
3786 | 0 | new file mode 100644 | 352 | new file mode 100644 |
3787 | index 0000000..3e6e30d | |||
3788 | --- /dev/null | |||
3789 | +++ b/hooks/charmhelpers/core/services/helpers.py | |||
3790 | @@ -0,0 +1,290 @@ | |||
3791 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3792 | 2 | # | ||
3793 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
3794 | 4 | # you may not use this file except in compliance with the License. | ||
3795 | 5 | # You may obtain a copy of the License at | ||
3796 | 6 | # | ||
3797 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
3798 | 8 | # | ||
3799 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
3800 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
3801 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
3802 | 12 | # See the License for the specific language governing permissions and | ||
3803 | 13 | # limitations under the License. | ||
3804 | 14 | |||
3805 | 15 | import os | ||
3806 | 16 | import yaml | ||
3807 | 17 | |||
3808 | 18 | from charmhelpers.core import hookenv | ||
3809 | 19 | from charmhelpers.core import host | ||
3810 | 20 | from charmhelpers.core import templating | ||
3811 | 21 | |||
3812 | 22 | from charmhelpers.core.services.base import ManagerCallback | ||
3813 | 23 | |||
3814 | 24 | |||
3815 | 25 | __all__ = ['RelationContext', 'TemplateCallback', | ||
3816 | 26 | 'render_template', 'template'] | ||
3817 | 27 | |||
3818 | 28 | |||
3819 | 29 | class RelationContext(dict): | ||
3820 | 30 | """ | ||
3821 | 31 | Base class for a context generator that gets relation data from juju. | ||
3822 | 32 | |||
3823 | 33 | Subclasses must provide the attributes `name`, which is the name of the | ||
3824 | 34 | interface of interest, `interface`, which is the type of the interface of | ||
3825 | 35 | interest, and `required_keys`, which is the set of keys required for the | ||
3826 | 36 | relation to be considered complete. The data for all interfaces matching | ||
3827 | 37 | the `name` attribute that are complete will used to populate the dictionary | ||
3828 | 38 | values (see `get_data`, below). | ||
3829 | 39 | |||
3830 | 40 | The generated context will be namespaced under the relation :attr:`name`, | ||
3831 | 41 | to prevent potential naming conflicts. | ||
3832 | 42 | |||
3833 | 43 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
3834 | 44 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
3835 | 45 | """ | ||
3836 | 46 | name = None | ||
3837 | 47 | interface = None | ||
3838 | 48 | |||
3839 | 49 | def __init__(self, name=None, additional_required_keys=None): | ||
3840 | 50 | if not hasattr(self, 'required_keys'): | ||
3841 | 51 | self.required_keys = [] | ||
3842 | 52 | |||
3843 | 53 | if name is not None: | ||
3844 | 54 | self.name = name | ||
3845 | 55 | if additional_required_keys: | ||
3846 | 56 | self.required_keys.extend(additional_required_keys) | ||
3847 | 57 | self.get_data() | ||
3848 | 58 | |||
3849 | 59 | def __bool__(self): | ||
3850 | 60 | """ | ||
3851 | 61 | Returns True if all of the required_keys are available. | ||
3852 | 62 | """ | ||
3853 | 63 | return self.is_ready() | ||
3854 | 64 | |||
3855 | 65 | __nonzero__ = __bool__ | ||
3856 | 66 | |||
3857 | 67 | def __repr__(self): | ||
3858 | 68 | return super(RelationContext, self).__repr__() | ||
3859 | 69 | |||
3860 | 70 | def is_ready(self): | ||
3861 | 71 | """ | ||
3862 | 72 | Returns True if all of the `required_keys` are available from any units. | ||
3863 | 73 | """ | ||
3864 | 74 | ready = len(self.get(self.name, [])) > 0 | ||
3865 | 75 | if not ready: | ||
3866 | 76 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
3867 | 77 | return ready | ||
3868 | 78 | |||
3869 | 79 | def _is_ready(self, unit_data): | ||
3870 | 80 | """ | ||
3871 | 81 | Helper method that tests a set of relation data and returns True if | ||
3872 | 82 | all of the `required_keys` are present. | ||
3873 | 83 | """ | ||
3874 | 84 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
3875 | 85 | |||
3876 | 86 | def get_data(self): | ||
3877 | 87 | """ | ||
3878 | 88 | Retrieve the relation data for each unit involved in a relation and, | ||
3879 | 89 | if complete, store it in a list under `self[self.name]`. This | ||
3880 | 90 | is automatically called when the RelationContext is instantiated. | ||
3881 | 91 | |||
3882 | 92 | The units are sorted lexographically first by the service ID, then by | ||
3883 | 93 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
3884 | 94 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
3885 | 95 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
3886 | 96 | set of data, the relation data for the units will be stored in the | ||
3887 | 97 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
3888 | 98 | |||
3889 | 99 | If you only care about a single unit on the relation, you can just | ||
3890 | 100 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
3891 | 101 | support multiple units on a relation, you should iterate over the list, | ||
3892 | 102 | like:: | ||
3893 | 103 | |||
3894 | 104 | {% for unit in interface -%} | ||
3895 | 105 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
3896 | 106 | {%- endfor %} | ||
3897 | 107 | |||
3898 | 108 | Note that since all sets of relation data from all related services and | ||
3899 | 109 | units are in a single list, if you need to know which service or unit a | ||
3900 | 110 | set of data came from, you'll need to extend this class to preserve | ||
3901 | 111 | that information. | ||
3902 | 112 | """ | ||
3903 | 113 | if not hookenv.relation_ids(self.name): | ||
3904 | 114 | return | ||
3905 | 115 | |||
3906 | 116 | ns = self.setdefault(self.name, []) | ||
3907 | 117 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
3908 | 118 | for unit in sorted(hookenv.related_units(rid)): | ||
3909 | 119 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
3910 | 120 | if self._is_ready(reldata): | ||
3911 | 121 | ns.append(reldata) | ||
3912 | 122 | |||
3913 | 123 | def provide_data(self): | ||
3914 | 124 | """ | ||
3915 | 125 | Return data to be relation_set for this interface. | ||
3916 | 126 | """ | ||
3917 | 127 | return {} | ||
3918 | 128 | |||
3919 | 129 | |||
3920 | 130 | class MysqlRelation(RelationContext): | ||
3921 | 131 | """ | ||
3922 | 132 | Relation context for the `mysql` interface. | ||
3923 | 133 | |||
3924 | 134 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
3925 | 135 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
3926 | 136 | """ | ||
3927 | 137 | name = 'db' | ||
3928 | 138 | interface = 'mysql' | ||
3929 | 139 | |||
3930 | 140 | def __init__(self, *args, **kwargs): | ||
3931 | 141 | self.required_keys = ['host', 'user', 'password', 'database'] | ||
3932 | 142 | RelationContext.__init__(self, *args, **kwargs) | ||
3933 | 143 | |||
3934 | 144 | |||
3935 | 145 | class HttpRelation(RelationContext): | ||
3936 | 146 | """ | ||
3937 | 147 | Relation context for the `http` interface. | ||
3938 | 148 | |||
3939 | 149 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
3940 | 150 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
3941 | 151 | """ | ||
3942 | 152 | name = 'website' | ||
3943 | 153 | interface = 'http' | ||
3944 | 154 | |||
3945 | 155 | def __init__(self, *args, **kwargs): | ||
3946 | 156 | self.required_keys = ['host', 'port'] | ||
3947 | 157 | RelationContext.__init__(self, *args, **kwargs) | ||
3948 | 158 | |||
3949 | 159 | def provide_data(self): | ||
3950 | 160 | return { | ||
3951 | 161 | 'host': hookenv.unit_get('private-address'), | ||
3952 | 162 | 'port': 80, | ||
3953 | 163 | } | ||
3954 | 164 | |||
3955 | 165 | |||
3956 | 166 | class RequiredConfig(dict): | ||
3957 | 167 | """ | ||
3958 | 168 | Data context that loads config options with one or more mandatory options. | ||
3959 | 169 | |||
3960 | 170 | Once the required options have been changed from their default values, all | ||
3961 | 171 | config options will be available, namespaced under `config` to prevent | ||
3962 | 172 | potential naming conflicts (for example, between a config option and a | ||
3963 | 173 | relation property). | ||
3964 | 174 | |||
3965 | 175 | :param list *args: List of options that must be changed from their default values. | ||
3966 | 176 | """ | ||
3967 | 177 | |||
3968 | 178 | def __init__(self, *args): | ||
3969 | 179 | self.required_options = args | ||
3970 | 180 | self['config'] = hookenv.config() | ||
3971 | 181 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
3972 | 182 | self.config = yaml.load(fp).get('options', {}) | ||
3973 | 183 | |||
3974 | 184 | def __bool__(self): | ||
3975 | 185 | for option in self.required_options: | ||
3976 | 186 | if option not in self['config']: | ||
3977 | 187 | return False | ||
3978 | 188 | current_value = self['config'][option] | ||
3979 | 189 | default_value = self.config[option].get('default') | ||
3980 | 190 | if current_value == default_value: | ||
3981 | 191 | return False | ||
3982 | 192 | if current_value in (None, '') and default_value in (None, ''): | ||
3983 | 193 | return False | ||
3984 | 194 | return True | ||
3985 | 195 | |||
3986 | 196 | def __nonzero__(self): | ||
3987 | 197 | return self.__bool__() | ||
3988 | 198 | |||
3989 | 199 | |||
3990 | 200 | class StoredContext(dict): | ||
3991 | 201 | """ | ||
3992 | 202 | A data context that always returns the data that it was first created with. | ||
3993 | 203 | |||
3994 | 204 | This is useful to do a one-time generation of things like passwords, that | ||
3995 | 205 | will thereafter use the same value that was originally generated, instead | ||
3996 | 206 | of generating a new value each time it is run. | ||
3997 | 207 | """ | ||
3998 | 208 | def __init__(self, file_name, config_data): | ||
3999 | 209 | """ | ||
4000 | 210 | If the file exists, populate `self` with the data from the file. | ||
4001 | 211 | Otherwise, populate with the given data and persist it to the file. | ||
4002 | 212 | """ | ||
4003 | 213 | if os.path.exists(file_name): | ||
4004 | 214 | self.update(self.read_context(file_name)) | ||
4005 | 215 | else: | ||
4006 | 216 | self.store_context(file_name, config_data) | ||
4007 | 217 | self.update(config_data) | ||
4008 | 218 | |||
4009 | 219 | def store_context(self, file_name, config_data): | ||
4010 | 220 | if not os.path.isabs(file_name): | ||
4011 | 221 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
4012 | 222 | with open(file_name, 'w') as file_stream: | ||
4013 | 223 | os.fchmod(file_stream.fileno(), 0o600) | ||
4014 | 224 | yaml.dump(config_data, file_stream) | ||
4015 | 225 | |||
4016 | 226 | def read_context(self, file_name): | ||
4017 | 227 | if not os.path.isabs(file_name): | ||
4018 | 228 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
4019 | 229 | with open(file_name, 'r') as file_stream: | ||
4020 | 230 | data = yaml.load(file_stream) | ||
4021 | 231 | if not data: | ||
4022 | 232 | raise OSError("%s is empty" % file_name) | ||
4023 | 233 | return data | ||
4024 | 234 | |||
4025 | 235 | |||
4026 | 236 | class TemplateCallback(ManagerCallback): | ||
4027 | 237 | """ | ||
4028 | 238 | Callback class that will render a Jinja2 template, for use as a ready | ||
4029 | 239 | action. | ||
4030 | 240 | |||
4031 | 241 | :param str source: The template source file, relative to | ||
4032 | 242 | `$CHARM_DIR/templates` | ||
4033 | 243 | |||
4034 | 244 | :param str target: The target to write the rendered template to (or None) | ||
4035 | 245 | :param str owner: The owner of the rendered file | ||
4036 | 246 | :param str group: The group of the rendered file | ||
4037 | 247 | :param int perms: The permissions of the rendered file | ||
4038 | 248 | :param partial on_change_action: functools partial to be executed when | ||
4039 | 249 | rendered file changes | ||
4040 | 250 | :param jinja2 loader template_loader: A jinja2 template loader | ||
4041 | 251 | |||
4042 | 252 | :return str: The rendered template | ||
4043 | 253 | """ | ||
4044 | 254 | def __init__(self, source, target, | ||
4045 | 255 | owner='root', group='root', perms=0o444, | ||
4046 | 256 | on_change_action=None, template_loader=None): | ||
4047 | 257 | self.source = source | ||
4048 | 258 | self.target = target | ||
4049 | 259 | self.owner = owner | ||
4050 | 260 | self.group = group | ||
4051 | 261 | self.perms = perms | ||
4052 | 262 | self.on_change_action = on_change_action | ||
4053 | 263 | self.template_loader = template_loader | ||
4054 | 264 | |||
4055 | 265 | def __call__(self, manager, service_name, event_name): | ||
4056 | 266 | pre_checksum = '' | ||
4057 | 267 | if self.on_change_action and os.path.isfile(self.target): | ||
4058 | 268 | pre_checksum = host.file_hash(self.target) | ||
4059 | 269 | service = manager.get_service(service_name) | ||
4060 | 270 | context = {'ctx': {}} | ||
4061 | 271 | for ctx in service.get('required_data', []): | ||
4062 | 272 | context.update(ctx) | ||
4063 | 273 | context['ctx'].update(ctx) | ||
4064 | 274 | |||
4065 | 275 | result = templating.render(self.source, self.target, context, | ||
4066 | 276 | self.owner, self.group, self.perms, | ||
4067 | 277 | template_loader=self.template_loader) | ||
4068 | 278 | if self.on_change_action: | ||
4069 | 279 | if pre_checksum == host.file_hash(self.target): | ||
4070 | 280 | hookenv.log( | ||
4071 | 281 | 'No change detected: {}'.format(self.target), | ||
4072 | 282 | hookenv.DEBUG) | ||
4073 | 283 | else: | ||
4074 | 284 | self.on_change_action() | ||
4075 | 285 | |||
4076 | 286 | return result | ||
4077 | 287 | |||
4078 | 288 | |||
4079 | 289 | # Convenience aliases for templates | ||
4080 | 290 | render_template = template = TemplateCallback | ||
4081 | diff --git a/hooks/charmhelpers/core/strutils.py b/hooks/charmhelpers/core/strutils.py | |||
4082 | 0 | new file mode 100644 | 291 | new file mode 100644 |
4083 | index 0000000..685dabd | |||
4084 | --- /dev/null | |||
4085 | +++ b/hooks/charmhelpers/core/strutils.py | |||
4086 | @@ -0,0 +1,123 @@ | |||
4087 | 1 | #!/usr/bin/env python | ||
4088 | 2 | # -*- coding: utf-8 -*- | ||
4089 | 3 | |||
4090 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
4091 | 5 | # | ||
4092 | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
4093 | 7 | # you may not use this file except in compliance with the License. | ||
4094 | 8 | # You may obtain a copy of the License at | ||
4095 | 9 | # | ||
4096 | 10 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
4097 | 11 | # | ||
4098 | 12 | # Unless required by applicable law or agreed to in writing, software | ||
4099 | 13 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
4100 | 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
4101 | 15 | # See the License for the specific language governing permissions and | ||
4102 | 16 | # limitations under the License. | ||
4103 | 17 | |||
4104 | 18 | import six | ||
4105 | 19 | import re | ||
4106 | 20 | |||
4107 | 21 | |||
4108 | 22 | def bool_from_string(value): | ||
4109 | 23 | """Interpret string value as boolean. | ||
4110 | 24 | |||
4111 | 25 | Returns True if value translates to True otherwise False. | ||
4112 | 26 | """ | ||
4113 | 27 | if isinstance(value, six.string_types): | ||
4114 | 28 | value = six.text_type(value) | ||
4115 | 29 | else: | ||
4116 | 30 | msg = "Unable to interpret non-string value '%s' as boolean" % (value) | ||
4117 | 31 | raise ValueError(msg) | ||
4118 | 32 | |||
4119 | 33 | value = value.strip().lower() | ||
4120 | 34 | |||
4121 | 35 | if value in ['y', 'yes', 'true', 't', 'on']: | ||
4122 | 36 | return True | ||
4123 | 37 | elif value in ['n', 'no', 'false', 'f', 'off']: | ||
4124 | 38 | return False | ||
4125 | 39 | |||
4126 | 40 | msg = "Unable to interpret string value '%s' as boolean" % (value) | ||
4127 | 41 | raise ValueError(msg) | ||
4128 | 42 | |||
4129 | 43 | |||
4130 | 44 | def bytes_from_string(value): | ||
4131 | 45 | """Interpret human readable string value as bytes. | ||
4132 | 46 | |||
4133 | 47 | Returns int | ||
4134 | 48 | """ | ||
4135 | 49 | BYTE_POWER = { | ||
4136 | 50 | 'K': 1, | ||
4137 | 51 | 'KB': 1, | ||
4138 | 52 | 'M': 2, | ||
4139 | 53 | 'MB': 2, | ||
4140 | 54 | 'G': 3, | ||
4141 | 55 | 'GB': 3, | ||
4142 | 56 | 'T': 4, | ||
4143 | 57 | 'TB': 4, | ||
4144 | 58 | 'P': 5, | ||
4145 | 59 | 'PB': 5, | ||
4146 | 60 | } | ||
4147 | 61 | if isinstance(value, six.string_types): | ||
4148 | 62 | value = six.text_type(value) | ||
4149 | 63 | else: | ||
4150 | 64 | msg = "Unable to interpret non-string value '%s' as boolean" % (value) | ||
4151 | 65 | raise ValueError(msg) | ||
4152 | 66 | matches = re.match("([0-9]+)([a-zA-Z]+)", value) | ||
4153 | 67 | if not matches: | ||
4154 | 68 | msg = "Unable to interpret string value '%s' as bytes" % (value) | ||
4155 | 69 | raise ValueError(msg) | ||
4156 | 70 | return int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)]) | ||
4157 | 71 | |||
4158 | 72 | |||
4159 | 73 | class BasicStringComparator(object): | ||
4160 | 74 | """Provides a class that will compare strings from an iterator type object. | ||
4161 | 75 | Used to provide > and < comparisons on strings that may not necessarily be | ||
4162 | 76 | alphanumerically ordered. e.g. OpenStack or Ubuntu releases AFTER the | ||
4163 | 77 | z-wrap. | ||
4164 | 78 | """ | ||
4165 | 79 | |||
4166 | 80 | _list = None | ||
4167 | 81 | |||
4168 | 82 | def __init__(self, item): | ||
4169 | 83 | if self._list is None: | ||
4170 | 84 | raise Exception("Must define the _list in the class definition!") | ||
4171 | 85 | try: | ||
4172 | 86 | self.index = self._list.index(item) | ||
4173 | 87 | except Exception: | ||
4174 | 88 | raise KeyError("Item '{}' is not in list '{}'" | ||
4175 | 89 | .format(item, self._list)) | ||
4176 | 90 | |||
4177 | 91 | def __eq__(self, other): | ||
4178 | 92 | assert isinstance(other, str) or isinstance(other, self.__class__) | ||
4179 | 93 | return self.index == self._list.index(other) | ||
4180 | 94 | |||
4181 | 95 | def __ne__(self, other): | ||
4182 | 96 | return not self.__eq__(other) | ||
4183 | 97 | |||
4184 | 98 | def __lt__(self, other): | ||
4185 | 99 | assert isinstance(other, str) or isinstance(other, self.__class__) | ||
4186 | 100 | return self.index < self._list.index(other) | ||
4187 | 101 | |||
4188 | 102 | def __ge__(self, other): | ||
4189 | 103 | return not self.__lt__(other) | ||
4190 | 104 | |||
4191 | 105 | def __gt__(self, other): | ||
4192 | 106 | assert isinstance(other, str) or isinstance(other, self.__class__) | ||
4193 | 107 | return self.index > self._list.index(other) | ||
4194 | 108 | |||
4195 | 109 | def __le__(self, other): | ||
4196 | 110 | return not self.__gt__(other) | ||
4197 | 111 | |||
4198 | 112 | def __str__(self): | ||
4199 | 113 | """Always give back the item at the index so it can be used in | ||
4200 | 114 | comparisons like: | ||
4201 | 115 | |||
4202 | 116 | s_mitaka = CompareOpenStack('mitaka') | ||
4203 | 117 | s_newton = CompareOpenstack('newton') | ||
4204 | 118 | |||
4205 | 119 | assert s_newton > s_mitaka | ||
4206 | 120 | |||
4207 | 121 | @returns: <string> | ||
4208 | 122 | """ | ||
4209 | 123 | return self._list[self.index] | ||
4210 | diff --git a/hooks/charmhelpers/core/sysctl.py b/hooks/charmhelpers/core/sysctl.py | |||
4211 | 0 | new file mode 100644 | 124 | new file mode 100644 |
4212 | index 0000000..6e413e3 | |||
4213 | --- /dev/null | |||
4214 | +++ b/hooks/charmhelpers/core/sysctl.py | |||
4215 | @@ -0,0 +1,54 @@ | |||
4216 | 1 | #!/usr/bin/env python | ||
4217 | 2 | # -*- coding: utf-8 -*- | ||
4218 | 3 | |||
4219 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
4220 | 5 | # | ||
4221 | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
4222 | 7 | # you may not use this file except in compliance with the License. | ||
4223 | 8 | # You may obtain a copy of the License at | ||
4224 | 9 | # | ||
4225 | 10 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
4226 | 11 | # | ||
4227 | 12 | # Unless required by applicable law or agreed to in writing, software | ||
4228 | 13 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
4229 | 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
4230 | 15 | # See the License for the specific language governing permissions and | ||
4231 | 16 | # limitations under the License. | ||
4232 | 17 | |||
4233 | 18 | import yaml | ||
4234 | 19 | |||
4235 | 20 | from subprocess import check_call | ||
4236 | 21 | |||
4237 | 22 | from charmhelpers.core.hookenv import ( | ||
4238 | 23 | log, | ||
4239 | 24 | DEBUG, | ||
4240 | 25 | ERROR, | ||
4241 | 26 | ) | ||
4242 | 27 | |||
4243 | 28 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
4244 | 29 | |||
4245 | 30 | |||
4246 | 31 | def create(sysctl_dict, sysctl_file): | ||
4247 | 32 | """Creates a sysctl.conf file from a YAML associative array | ||
4248 | 33 | |||
4249 | 34 | :param sysctl_dict: a YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" | ||
4250 | 35 | :type sysctl_dict: str | ||
4251 | 36 | :param sysctl_file: path to the sysctl file to be saved | ||
4252 | 37 | :type sysctl_file: str or unicode | ||
4253 | 38 | :returns: None | ||
4254 | 39 | """ | ||
4255 | 40 | try: | ||
4256 | 41 | sysctl_dict_parsed = yaml.safe_load(sysctl_dict) | ||
4257 | 42 | except yaml.YAMLError: | ||
4258 | 43 | log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict), | ||
4259 | 44 | level=ERROR) | ||
4260 | 45 | return | ||
4261 | 46 | |||
4262 | 47 | with open(sysctl_file, "w") as fd: | ||
4263 | 48 | for key, value in sysctl_dict_parsed.items(): | ||
4264 | 49 | fd.write("{}={}\n".format(key, value)) | ||
4265 | 50 | |||
4266 | 51 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict_parsed), | ||
4267 | 52 | level=DEBUG) | ||
4268 | 53 | |||
4269 | 54 | check_call(["sysctl", "-p", sysctl_file]) | ||
4270 | diff --git a/hooks/charmhelpers/core/templating.py b/hooks/charmhelpers/core/templating.py | |||
4271 | 0 | new file mode 100644 | 55 | new file mode 100644 |
4272 | index 0000000..7b801a3 | |||
4273 | --- /dev/null | |||
4274 | +++ b/hooks/charmhelpers/core/templating.py | |||
4275 | @@ -0,0 +1,84 @@ | |||
4276 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4277 | 2 | # | ||
4278 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
4279 | 4 | # you may not use this file except in compliance with the License. | ||
4280 | 5 | # You may obtain a copy of the License at | ||
4281 | 6 | # | ||
4282 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
4283 | 8 | # | ||
4284 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
4285 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
4286 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
4287 | 12 | # See the License for the specific language governing permissions and | ||
4288 | 13 | # limitations under the License. | ||
4289 | 14 | |||
4290 | 15 | import os | ||
4291 | 16 | import sys | ||
4292 | 17 | |||
4293 | 18 | from charmhelpers.core import host | ||
4294 | 19 | from charmhelpers.core import hookenv | ||
4295 | 20 | |||
4296 | 21 | |||
4297 | 22 | def render(source, target, context, owner='root', group='root', | ||
4298 | 23 | perms=0o444, templates_dir=None, encoding='UTF-8', template_loader=None): | ||
4299 | 24 | """ | ||
4300 | 25 | Render a template. | ||
4301 | 26 | |||
4302 | 27 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
4303 | 28 | |||
4304 | 29 | The `target` path should be absolute. It can also be `None`, in which | ||
4305 | 30 | case no file will be written. | ||
4306 | 31 | |||
4307 | 32 | The context should be a dict containing the values to be replaced in the | ||
4308 | 33 | template. | ||
4309 | 34 | |||
4310 | 35 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
4311 | 36 | |||
4312 | 37 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
4313 | 38 | |||
4314 | 39 | The rendered template will be written to the file as well as being returned | ||
4315 | 40 | as a string. | ||
4316 | 41 | |||
4317 | 42 | Note: Using this requires python-jinja2 or python3-jinja2; if it is not | ||
4318 | 43 | installed, calling this will attempt to use charmhelpers.fetch.apt_install | ||
4319 | 44 | to install it. | ||
4320 | 45 | """ | ||
4321 | 46 | try: | ||
4322 | 47 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
4323 | 48 | except ImportError: | ||
4324 | 49 | try: | ||
4325 | 50 | from charmhelpers.fetch import apt_install | ||
4326 | 51 | except ImportError: | ||
4327 | 52 | hookenv.log('Could not import jinja2, and could not import ' | ||
4328 | 53 | 'charmhelpers.fetch to install it', | ||
4329 | 54 | level=hookenv.ERROR) | ||
4330 | 55 | raise | ||
4331 | 56 | if sys.version_info.major == 2: | ||
4332 | 57 | apt_install('python-jinja2', fatal=True) | ||
4333 | 58 | else: | ||
4334 | 59 | apt_install('python3-jinja2', fatal=True) | ||
4335 | 60 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
4336 | 61 | |||
4337 | 62 | if template_loader: | ||
4338 | 63 | template_env = Environment(loader=template_loader) | ||
4339 | 64 | else: | ||
4340 | 65 | if templates_dir is None: | ||
4341 | 66 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
4342 | 67 | template_env = Environment(loader=FileSystemLoader(templates_dir)) | ||
4343 | 68 | try: | ||
4344 | 69 | source = source | ||
4345 | 70 | template = template_env.get_template(source) | ||
4346 | 71 | except exceptions.TemplateNotFound as e: | ||
4347 | 72 | hookenv.log('Could not load template %s from %s.' % | ||
4348 | 73 | (source, templates_dir), | ||
4349 | 74 | level=hookenv.ERROR) | ||
4350 | 75 | raise e | ||
4351 | 76 | content = template.render(context) | ||
4352 | 77 | if target is not None: | ||
4353 | 78 | target_dir = os.path.dirname(target) | ||
4354 | 79 | if not os.path.exists(target_dir): | ||
4355 | 80 | # This is a terrible default directory permission, as the file | ||
4356 | 81 | # or its siblings will often contain secrets. | ||
4357 | 82 | host.mkdir(os.path.dirname(target), owner, group, perms=0o755) | ||
4358 | 83 | host.write_file(target, content.encode(encoding), owner, group, perms) | ||
4359 | 84 | return content | ||
4360 | diff --git a/hooks/charmhelpers/core/unitdata.py b/hooks/charmhelpers/core/unitdata.py | |||
4361 | 0 | new file mode 100644 | 85 | new file mode 100644 |
4362 | index 0000000..54ec969 | |||
4363 | --- /dev/null | |||
4364 | +++ b/hooks/charmhelpers/core/unitdata.py | |||
4365 | @@ -0,0 +1,518 @@ | |||
4366 | 1 | #!/usr/bin/env python | ||
4367 | 2 | # -*- coding: utf-8 -*- | ||
4368 | 3 | # | ||
4369 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
4370 | 5 | # | ||
4371 | 6 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
4372 | 7 | # you may not use this file except in compliance with the License. | ||
4373 | 8 | # You may obtain a copy of the License at | ||
4374 | 9 | # | ||
4375 | 10 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
4376 | 11 | # | ||
4377 | 12 | # Unless required by applicable law or agreed to in writing, software | ||
4378 | 13 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
4379 | 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
4380 | 15 | # See the License for the specific language governing permissions and | ||
4381 | 16 | # limitations under the License. | ||
4382 | 17 | # | ||
4383 | 18 | # Authors: | ||
4384 | 19 | # Kapil Thangavelu <kapil.foss@gmail.com> | ||
4385 | 20 | # | ||
4386 | 21 | """ | ||
4387 | 22 | Intro | ||
4388 | 23 | ----- | ||
4389 | 24 | |||
4390 | 25 | A simple way to store state in units. This provides a key value | ||
4391 | 26 | storage with support for versioned, transactional operation, | ||
4392 | 27 | and can calculate deltas from previous values to simplify unit logic | ||
4393 | 28 | when processing changes. | ||
4394 | 29 | |||
4395 | 30 | |||
4396 | 31 | Hook Integration | ||
4397 | 32 | ---------------- | ||
4398 | 33 | |||
4399 | 34 | There are several extant frameworks for hook execution, including | ||
4400 | 35 | |||
4401 | 36 | - charmhelpers.core.hookenv.Hooks | ||
4402 | 37 | - charmhelpers.core.services.ServiceManager | ||
4403 | 38 | |||
4404 | 39 | The storage classes are framework agnostic, one simple integration is | ||
4405 | 40 | via the HookData contextmanager. It will record the current hook | ||
4406 | 41 | execution environment (including relation data, config data, etc.), | ||
4407 | 42 | setup a transaction and allow easy access to the changes from | ||
4408 | 43 | previously seen values. One consequence of the integration is the | ||
4409 | 44 | reservation of particular keys ('rels', 'unit', 'env', 'config', | ||
4410 | 45 | 'charm_revisions') for their respective values. | ||
4411 | 46 | |||
4412 | 47 | Here's a fully worked integration example using hookenv.Hooks:: | ||
4413 | 48 | |||
4414 | 49 | from charmhelper.core import hookenv, unitdata | ||
4415 | 50 | |||
4416 | 51 | hook_data = unitdata.HookData() | ||
4417 | 52 | db = unitdata.kv() | ||
4418 | 53 | hooks = hookenv.Hooks() | ||
4419 | 54 | |||
4420 | 55 | @hooks.hook | ||
4421 | 56 | def config_changed(): | ||
4422 | 57 | # Print all changes to configuration from previously seen | ||
4423 | 58 | # values. | ||
4424 | 59 | for changed, (prev, cur) in hook_data.conf.items(): | ||
4425 | 60 | print('config changed', changed, | ||
4426 | 61 | 'previous value', prev, | ||
4427 | 62 | 'current value', cur) | ||
4428 | 63 | |||
4429 | 64 | # Get some unit specific bookeeping | ||
4430 | 65 | if not db.get('pkg_key'): | ||
4431 | 66 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
4432 | 67 | db.set('pkg_key', key) | ||
4433 | 68 | |||
4434 | 69 | # Directly access all charm config as a mapping. | ||
4435 | 70 | conf = db.getrange('config', True) | ||
4436 | 71 | |||
4437 | 72 | # Directly access all relation data as a mapping | ||
4438 | 73 | rels = db.getrange('rels', True) | ||
4439 | 74 | |||
4440 | 75 | if __name__ == '__main__': | ||
4441 | 76 | with hook_data(): | ||
4442 | 77 | hook.execute() | ||
4443 | 78 | |||
4444 | 79 | |||
4445 | 80 | A more basic integration is via the hook_scope context manager which simply | ||
4446 | 81 | manages transaction scope (and records hook name, and timestamp):: | ||
4447 | 82 | |||
4448 | 83 | >>> from unitdata import kv | ||
4449 | 84 | >>> db = kv() | ||
4450 | 85 | >>> with db.hook_scope('install'): | ||
4451 | 86 | ... # do work, in transactional scope. | ||
4452 | 87 | ... db.set('x', 1) | ||
4453 | 88 | >>> db.get('x') | ||
4454 | 89 | 1 | ||
4455 | 90 | |||
4456 | 91 | |||
4457 | 92 | Usage | ||
4458 | 93 | ----- | ||
4459 | 94 | |||
4460 | 95 | Values are automatically json de/serialized to preserve basic typing | ||
4461 | 96 | and complex data struct capabilities (dicts, lists, ints, booleans, etc). | ||
4462 | 97 | |||
4463 | 98 | Individual values can be manipulated via get/set:: | ||
4464 | 99 | |||
4465 | 100 | >>> kv.set('y', True) | ||
4466 | 101 | >>> kv.get('y') | ||
4467 | 102 | True | ||
4468 | 103 | |||
4469 | 104 | # We can set complex values (dicts, lists) as a single key. | ||
4470 | 105 | >>> kv.set('config', {'a': 1, 'b': True'}) | ||
4471 | 106 | |||
4472 | 107 | # Also supports returning dictionaries as a record which | ||
4473 | 108 | # provides attribute access. | ||
4474 | 109 | >>> config = kv.get('config', record=True) | ||
4475 | 110 | >>> config.b | ||
4476 | 111 | True | ||
4477 | 112 | |||
4478 | 113 | |||
4479 | 114 | Groups of keys can be manipulated with update/getrange:: | ||
4480 | 115 | |||
4481 | 116 | >>> kv.update({'z': 1, 'y': 2}, prefix="gui.") | ||
4482 | 117 | >>> kv.getrange('gui.', strip=True) | ||
4483 | 118 | {'z': 1, 'y': 2} | ||
4484 | 119 | |||
4485 | 120 | When updating values, its very helpful to understand which values | ||
4486 | 121 | have actually changed and how have they changed. The storage | ||
4487 | 122 | provides a delta method to provide for this:: | ||
4488 | 123 | |||
4489 | 124 | >>> data = {'debug': True, 'option': 2} | ||
4490 | 125 | >>> delta = kv.delta(data, 'config.') | ||
4491 | 126 | >>> delta.debug.previous | ||
4492 | 127 | None | ||
4493 | 128 | >>> delta.debug.current | ||
4494 | 129 | True | ||
4495 | 130 | >>> delta | ||
4496 | 131 | {'debug': (None, True), 'option': (None, 2)} | ||
4497 | 132 | |||
4498 | 133 | Note the delta method does not persist the actual change, it needs to | ||
4499 | 134 | be explicitly saved via 'update' method:: | ||
4500 | 135 | |||
4501 | 136 | >>> kv.update(data, 'config.') | ||
4502 | 137 | |||
4503 | 138 | Values modified in the context of a hook scope retain historical values | ||
4504 | 139 | associated to the hookname. | ||
4505 | 140 | |||
4506 | 141 | >>> with db.hook_scope('config-changed'): | ||
4507 | 142 | ... db.set('x', 42) | ||
4508 | 143 | >>> db.gethistory('x') | ||
4509 | 144 | [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'), | ||
4510 | 145 | (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')] | ||
4511 | 146 | |||
4512 | 147 | """ | ||
4513 | 148 | |||
4514 | 149 | import collections | ||
4515 | 150 | import contextlib | ||
4516 | 151 | import datetime | ||
4517 | 152 | import itertools | ||
4518 | 153 | import json | ||
4519 | 154 | import os | ||
4520 | 155 | import pprint | ||
4521 | 156 | import sqlite3 | ||
4522 | 157 | import sys | ||
4523 | 158 | |||
4524 | 159 | __author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>' | ||
4525 | 160 | |||
4526 | 161 | |||
4527 | 162 | class Storage(object): | ||
4528 | 163 | """Simple key value database for local unit state within charms. | ||
4529 | 164 | |||
4530 | 165 | Modifications are not persisted unless :meth:`flush` is called. | ||
4531 | 166 | |||
4532 | 167 | To support dicts, lists, integer, floats, and booleans values | ||
4533 | 168 | are automatically json encoded/decoded. | ||
4534 | 169 | """ | ||
4535 | 170 | def __init__(self, path=None): | ||
4536 | 171 | self.db_path = path | ||
4537 | 172 | if path is None: | ||
4538 | 173 | if 'UNIT_STATE_DB' in os.environ: | ||
4539 | 174 | self.db_path = os.environ['UNIT_STATE_DB'] | ||
4540 | 175 | else: | ||
4541 | 176 | self.db_path = os.path.join( | ||
4542 | 177 | os.environ.get('CHARM_DIR', ''), '.unit-state.db') | ||
4543 | 178 | self.conn = sqlite3.connect('%s' % self.db_path) | ||
4544 | 179 | self.cursor = self.conn.cursor() | ||
4545 | 180 | self.revision = None | ||
4546 | 181 | self._closed = False | ||
4547 | 182 | self._init() | ||
4548 | 183 | |||
4549 | 184 | def close(self): | ||
4550 | 185 | if self._closed: | ||
4551 | 186 | return | ||
4552 | 187 | self.flush(False) | ||
4553 | 188 | self.cursor.close() | ||
4554 | 189 | self.conn.close() | ||
4555 | 190 | self._closed = True | ||
4556 | 191 | |||
4557 | 192 | def get(self, key, default=None, record=False): | ||
4558 | 193 | self.cursor.execute('select data from kv where key=?', [key]) | ||
4559 | 194 | result = self.cursor.fetchone() | ||
4560 | 195 | if not result: | ||
4561 | 196 | return default | ||
4562 | 197 | if record: | ||
4563 | 198 | return Record(json.loads(result[0])) | ||
4564 | 199 | return json.loads(result[0]) | ||
4565 | 200 | |||
4566 | 201 | def getrange(self, key_prefix, strip=False): | ||
4567 | 202 | """ | ||
4568 | 203 | Get a range of keys starting with a common prefix as a mapping of | ||
4569 | 204 | keys to values. | ||
4570 | 205 | |||
4571 | 206 | :param str key_prefix: Common prefix among all keys | ||
4572 | 207 | :param bool strip: Optionally strip the common prefix from the key | ||
4573 | 208 | names in the returned dict | ||
4574 | 209 | :return dict: A (possibly empty) dict of key-value mappings | ||
4575 | 210 | """ | ||
4576 | 211 | self.cursor.execute("select key, data from kv where key like ?", | ||
4577 | 212 | ['%s%%' % key_prefix]) | ||
4578 | 213 | result = self.cursor.fetchall() | ||
4579 | 214 | |||
4580 | 215 | if not result: | ||
4581 | 216 | return {} | ||
4582 | 217 | if not strip: | ||
4583 | 218 | key_prefix = '' | ||
4584 | 219 | return dict([ | ||
4585 | 220 | (k[len(key_prefix):], json.loads(v)) for k, v in result]) | ||
4586 | 221 | |||
4587 | 222 | def update(self, mapping, prefix=""): | ||
4588 | 223 | """ | ||
4589 | 224 | Set the values of multiple keys at once. | ||
4590 | 225 | |||
4591 | 226 | :param dict mapping: Mapping of keys to values | ||
4592 | 227 | :param str prefix: Optional prefix to apply to all keys in `mapping` | ||
4593 | 228 | before setting | ||
4594 | 229 | """ | ||
4595 | 230 | for k, v in mapping.items(): | ||
4596 | 231 | self.set("%s%s" % (prefix, k), v) | ||
4597 | 232 | |||
4598 | 233 | def unset(self, key): | ||
4599 | 234 | """ | ||
4600 | 235 | Remove a key from the database entirely. | ||
4601 | 236 | """ | ||
4602 | 237 | self.cursor.execute('delete from kv where key=?', [key]) | ||
4603 | 238 | if self.revision and self.cursor.rowcount: | ||
4604 | 239 | self.cursor.execute( | ||
4605 | 240 | 'insert into kv_revisions values (?, ?, ?)', | ||
4606 | 241 | [key, self.revision, json.dumps('DELETED')]) | ||
4607 | 242 | |||
4608 | 243 | def unsetrange(self, keys=None, prefix=""): | ||
4609 | 244 | """ | ||
4610 | 245 | Remove a range of keys starting with a common prefix, from the database | ||
4611 | 246 | entirely. | ||
4612 | 247 | |||
4613 | 248 | :param list keys: List of keys to remove. | ||
4614 | 249 | :param str prefix: Optional prefix to apply to all keys in ``keys`` | ||
4615 | 250 | before removing. | ||
4616 | 251 | """ | ||
4617 | 252 | if keys is not None: | ||
4618 | 253 | keys = ['%s%s' % (prefix, key) for key in keys] | ||
4619 | 254 | self.cursor.execute('delete from kv where key in (%s)' % ','.join(['?'] * len(keys)), keys) | ||
4620 | 255 | if self.revision and self.cursor.rowcount: | ||
4621 | 256 | self.cursor.execute( | ||
4622 | 257 | 'insert into kv_revisions values %s' % ','.join(['(?, ?, ?)'] * len(keys)), | ||
4623 | 258 | list(itertools.chain.from_iterable((key, self.revision, json.dumps('DELETED')) for key in keys))) | ||
4624 | 259 | else: | ||
4625 | 260 | self.cursor.execute('delete from kv where key like ?', | ||
4626 | 261 | ['%s%%' % prefix]) | ||
4627 | 262 | if self.revision and self.cursor.rowcount: | ||
4628 | 263 | self.cursor.execute( | ||
4629 | 264 | 'insert into kv_revisions values (?, ?, ?)', | ||
4630 | 265 | ['%s%%' % prefix, self.revision, json.dumps('DELETED')]) | ||
4631 | 266 | |||
4632 | 267 | def set(self, key, value): | ||
4633 | 268 | """ | ||
4634 | 269 | Set a value in the database. | ||
4635 | 270 | |||
4636 | 271 | :param str key: Key to set the value for | ||
4637 | 272 | :param value: Any JSON-serializable value to be set | ||
4638 | 273 | """ | ||
4639 | 274 | serialized = json.dumps(value) | ||
4640 | 275 | |||
4641 | 276 | self.cursor.execute('select data from kv where key=?', [key]) | ||
4642 | 277 | exists = self.cursor.fetchone() | ||
4643 | 278 | |||
4644 | 279 | # Skip mutations to the same value | ||
4645 | 280 | if exists: | ||
4646 | 281 | if exists[0] == serialized: | ||
4647 | 282 | return value | ||
4648 | 283 | |||
4649 | 284 | if not exists: | ||
4650 | 285 | self.cursor.execute( | ||
4651 | 286 | 'insert into kv (key, data) values (?, ?)', | ||
4652 | 287 | (key, serialized)) | ||
4653 | 288 | else: | ||
4654 | 289 | self.cursor.execute(''' | ||
4655 | 290 | update kv | ||
4656 | 291 | set data = ? | ||
4657 | 292 | where key = ?''', [serialized, key]) | ||
4658 | 293 | |||
4659 | 294 | # Save | ||
4660 | 295 | if not self.revision: | ||
4661 | 296 | return value | ||
4662 | 297 | |||
4663 | 298 | self.cursor.execute( | ||
4664 | 299 | 'select 1 from kv_revisions where key=? and revision=?', | ||
4665 | 300 | [key, self.revision]) | ||
4666 | 301 | exists = self.cursor.fetchone() | ||
4667 | 302 | |||
4668 | 303 | if not exists: | ||
4669 | 304 | self.cursor.execute( | ||
4670 | 305 | '''insert into kv_revisions ( | ||
4671 | 306 | revision, key, data) values (?, ?, ?)''', | ||
4672 | 307 | (self.revision, key, serialized)) | ||
4673 | 308 | else: | ||
4674 | 309 | self.cursor.execute( | ||
4675 | 310 | ''' | ||
4676 | 311 | update kv_revisions | ||
4677 | 312 | set data = ? | ||
4678 | 313 | where key = ? | ||
4679 | 314 | and revision = ?''', | ||
4680 | 315 | [serialized, key, self.revision]) | ||
4681 | 316 | |||
4682 | 317 | return value | ||
4683 | 318 | |||
4684 | 319 | def delta(self, mapping, prefix): | ||
4685 | 320 | """ | ||
4686 | 321 | return a delta containing values that have changed. | ||
4687 | 322 | """ | ||
4688 | 323 | previous = self.getrange(prefix, strip=True) | ||
4689 | 324 | if not previous: | ||
4690 | 325 | pk = set() | ||
4691 | 326 | else: | ||
4692 | 327 | pk = set(previous.keys()) | ||
4693 | 328 | ck = set(mapping.keys()) | ||
4694 | 329 | delta = DeltaSet() | ||
4695 | 330 | |||
4696 | 331 | # added | ||
4697 | 332 | for k in ck.difference(pk): | ||
4698 | 333 | delta[k] = Delta(None, mapping[k]) | ||
4699 | 334 | |||
4700 | 335 | # removed | ||
4701 | 336 | for k in pk.difference(ck): | ||
4702 | 337 | delta[k] = Delta(previous[k], None) | ||
4703 | 338 | |||
4704 | 339 | # changed | ||
4705 | 340 | for k in pk.intersection(ck): | ||
4706 | 341 | c = mapping[k] | ||
4707 | 342 | p = previous[k] | ||
4708 | 343 | if c != p: | ||
4709 | 344 | delta[k] = Delta(p, c) | ||
4710 | 345 | |||
4711 | 346 | return delta | ||
4712 | 347 | |||
4713 | 348 | @contextlib.contextmanager | ||
4714 | 349 | def hook_scope(self, name=""): | ||
4715 | 350 | """Scope all future interactions to the current hook execution | ||
4716 | 351 | revision.""" | ||
4717 | 352 | assert not self.revision | ||
4718 | 353 | self.cursor.execute( | ||
4719 | 354 | 'insert into hooks (hook, date) values (?, ?)', | ||
4720 | 355 | (name or sys.argv[0], | ||
4721 | 356 | datetime.datetime.utcnow().isoformat())) | ||
4722 | 357 | self.revision = self.cursor.lastrowid | ||
4723 | 358 | try: | ||
4724 | 359 | yield self.revision | ||
4725 | 360 | self.revision = None | ||
4726 | 361 | except: | ||
4727 | 362 | self.flush(False) | ||
4728 | 363 | self.revision = None | ||
4729 | 364 | raise | ||
4730 | 365 | else: | ||
4731 | 366 | self.flush() | ||
4732 | 367 | |||
4733 | 368 | def flush(self, save=True): | ||
4734 | 369 | if save: | ||
4735 | 370 | self.conn.commit() | ||
4736 | 371 | elif self._closed: | ||
4737 | 372 | return | ||
4738 | 373 | else: | ||
4739 | 374 | self.conn.rollback() | ||
4740 | 375 | |||
4741 | 376 | def _init(self): | ||
4742 | 377 | self.cursor.execute(''' | ||
4743 | 378 | create table if not exists kv ( | ||
4744 | 379 | key text, | ||
4745 | 380 | data text, | ||
4746 | 381 | primary key (key) | ||
4747 | 382 | )''') | ||
4748 | 383 | self.cursor.execute(''' | ||
4749 | 384 | create table if not exists kv_revisions ( | ||
4750 | 385 | key text, | ||
4751 | 386 | revision integer, | ||
4752 | 387 | data text, | ||
4753 | 388 | primary key (key, revision) | ||
4754 | 389 | )''') | ||
4755 | 390 | self.cursor.execute(''' | ||
4756 | 391 | create table if not exists hooks ( | ||
4757 | 392 | version integer primary key autoincrement, | ||
4758 | 393 | hook text, | ||
4759 | 394 | date text | ||
4760 | 395 | )''') | ||
4761 | 396 | self.conn.commit() | ||
4762 | 397 | |||
4763 | 398 | def gethistory(self, key, deserialize=False): | ||
4764 | 399 | self.cursor.execute( | ||
4765 | 400 | ''' | ||
4766 | 401 | select kv.revision, kv.key, kv.data, h.hook, h.date | ||
4767 | 402 | from kv_revisions kv, | ||
4768 | 403 | hooks h | ||
4769 | 404 | where kv.key=? | ||
4770 | 405 | and kv.revision = h.version | ||
4771 | 406 | ''', [key]) | ||
4772 | 407 | if deserialize is False: | ||
4773 | 408 | return self.cursor.fetchall() | ||
4774 | 409 | return map(_parse_history, self.cursor.fetchall()) | ||
4775 | 410 | |||
4776 | 411 | def debug(self, fh=sys.stderr): | ||
4777 | 412 | self.cursor.execute('select * from kv') | ||
4778 | 413 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
4779 | 414 | self.cursor.execute('select * from kv_revisions') | ||
4780 | 415 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
4781 | 416 | |||
4782 | 417 | |||
4783 | 418 | def _parse_history(d): | ||
4784 | 419 | return (d[0], d[1], json.loads(d[2]), d[3], | ||
4785 | 420 | datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f")) | ||
4786 | 421 | |||
4787 | 422 | |||
4788 | 423 | class HookData(object): | ||
4789 | 424 | """Simple integration for existing hook exec frameworks. | ||
4790 | 425 | |||
4791 | 426 | Records all unit information, and stores deltas for processing | ||
4792 | 427 | by the hook. | ||
4793 | 428 | |||
4794 | 429 | Sample:: | ||
4795 | 430 | |||
4796 | 431 | from charmhelper.core import hookenv, unitdata | ||
4797 | 432 | |||
4798 | 433 | changes = unitdata.HookData() | ||
4799 | 434 | db = unitdata.kv() | ||
4800 | 435 | hooks = hookenv.Hooks() | ||
4801 | 436 | |||
4802 | 437 | @hooks.hook | ||
4803 | 438 | def config_changed(): | ||
4804 | 439 | # View all changes to configuration | ||
4805 | 440 | for changed, (prev, cur) in changes.conf.items(): | ||
4806 | 441 | print('config changed', changed, | ||
4807 | 442 | 'previous value', prev, | ||
4808 | 443 | 'current value', cur) | ||
4809 | 444 | |||
4810 | 445 | # Get some unit specific bookeeping | ||
4811 | 446 | if not db.get('pkg_key'): | ||
4812 | 447 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
4813 | 448 | db.set('pkg_key', key) | ||
4814 | 449 | |||
4815 | 450 | if __name__ == '__main__': | ||
4816 | 451 | with changes(): | ||
4817 | 452 | hook.execute() | ||
4818 | 453 | |||
4819 | 454 | """ | ||
4820 | 455 | def __init__(self): | ||
4821 | 456 | self.kv = kv() | ||
4822 | 457 | self.conf = None | ||
4823 | 458 | self.rels = None | ||
4824 | 459 | |||
4825 | 460 | @contextlib.contextmanager | ||
4826 | 461 | def __call__(self): | ||
4827 | 462 | from charmhelpers.core import hookenv | ||
4828 | 463 | hook_name = hookenv.hook_name() | ||
4829 | 464 | |||
4830 | 465 | with self.kv.hook_scope(hook_name): | ||
4831 | 466 | self._record_charm_version(hookenv.charm_dir()) | ||
4832 | 467 | delta_config, delta_relation = self._record_hook(hookenv) | ||
4833 | 468 | yield self.kv, delta_config, delta_relation | ||
4834 | 469 | |||
4835 | 470 | def _record_charm_version(self, charm_dir): | ||
4836 | 471 | # Record revisions.. charm revisions are meaningless | ||
4837 | 472 | # to charm authors as they don't control the revision. | ||
4838 | 473 | # so logic dependnent on revision is not particularly | ||
4839 | 474 | # useful, however it is useful for debugging analysis. | ||
4840 | 475 | charm_rev = open( | ||
4841 | 476 | os.path.join(charm_dir, 'revision')).read().strip() | ||
4842 | 477 | charm_rev = charm_rev or '0' | ||
4843 | 478 | revs = self.kv.get('charm_revisions', []) | ||
4844 | 479 | if charm_rev not in revs: | ||
4845 | 480 | revs.append(charm_rev.strip() or '0') | ||
4846 | 481 | self.kv.set('charm_revisions', revs) | ||
4847 | 482 | |||
4848 | 483 | def _record_hook(self, hookenv): | ||
4849 | 484 | data = hookenv.execution_environment() | ||
4850 | 485 | self.conf = conf_delta = self.kv.delta(data['conf'], 'config') | ||
4851 | 486 | self.rels = rels_delta = self.kv.delta(data['rels'], 'rels') | ||
4852 | 487 | self.kv.set('env', dict(data['env'])) | ||
4853 | 488 | self.kv.set('unit', data['unit']) | ||
4854 | 489 | self.kv.set('relid', data.get('relid')) | ||
4855 | 490 | return conf_delta, rels_delta | ||
4856 | 491 | |||
4857 | 492 | |||
4858 | 493 | class Record(dict): | ||
4859 | 494 | |||
4860 | 495 | __slots__ = () | ||
4861 | 496 | |||
4862 | 497 | def __getattr__(self, k): | ||
4863 | 498 | if k in self: | ||
4864 | 499 | return self[k] | ||
4865 | 500 | raise AttributeError(k) | ||
4866 | 501 | |||
4867 | 502 | |||
4868 | 503 | class DeltaSet(Record): | ||
4869 | 504 | |||
4870 | 505 | __slots__ = () | ||
4871 | 506 | |||
4872 | 507 | |||
4873 | 508 | Delta = collections.namedtuple('Delta', ['previous', 'current']) | ||
4874 | 509 | |||
4875 | 510 | |||
4876 | 511 | _KV = None | ||
4877 | 512 | |||
4878 | 513 | |||
4879 | 514 | def kv(): | ||
4880 | 515 | global _KV | ||
4881 | 516 | if _KV is None: | ||
4882 | 517 | _KV = Storage() | ||
4883 | 518 | return _KV | ||
4884 | diff --git a/hooks/charmhelpers/fetch/__init__.py b/hooks/charmhelpers/fetch/__init__.py | |||
4885 | 0 | new file mode 100644 | 519 | new file mode 100644 |
4886 | index 0000000..ec5e0fe | |||
4887 | --- /dev/null | |||
4888 | +++ b/hooks/charmhelpers/fetch/__init__.py | |||
4889 | @@ -0,0 +1,197 @@ | |||
4890 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
4891 | 2 | # | ||
4892 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
4893 | 4 | # you may not use this file except in compliance with the License. | ||
4894 | 5 | # You may obtain a copy of the License at | ||
4895 | 6 | # | ||
4896 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
4897 | 8 | # | ||
4898 | 9 | # Unless required by applicable law or agreed to in writing, software | ||
4899 | 10 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
4900 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
4901 | 12 | # See the License for the specific language governing permissions and | ||
4902 | 13 | # limitations under the License. | ||
4903 | 14 | |||
4904 | 15 | import importlib | ||
4905 | 16 | from charmhelpers.osplatform import get_platform | ||
4906 | 17 | from yaml import safe_load | ||
4907 | 18 | from charmhelpers.core.hookenv import ( | ||
4908 | 19 | config, | ||
4909 | 20 | log, | ||
4910 | 21 | ) | ||
4911 | 22 | |||
4912 | 23 | import six | ||
4913 | 24 | if six.PY3: | ||
4914 | 25 | from urllib.parse import urlparse, urlunparse | ||
4915 | 26 | else: | ||
4916 | 27 | from urlparse import urlparse, urlunparse | ||
4917 | 28 | |||
4918 | 29 | |||
4919 | 30 | # The order of this list is very important. Handlers should be listed in from | ||
4920 | 31 | # least- to most-specific URL matching. | ||
4921 | 32 | FETCH_HANDLERS = ( | ||
4922 | 33 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
4923 | 34 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
4924 | 35 | 'charmhelpers.fetch.giturl.GitUrlFetchHandler', | ||
4925 | 36 | ) | ||
4926 | 37 | |||
4927 | 38 | |||
4928 | 39 | class SourceConfigError(Exception): | ||
4929 | 40 | pass | ||
4930 | 41 | |||
4931 | 42 | |||
4932 | 43 | class UnhandledSource(Exception): | ||
4933 | 44 | pass | ||
4934 | 45 | |||
4935 | 46 | |||
4936 | 47 | class AptLockError(Exception): | ||
4937 | 48 | pass | ||
4938 | 49 | |||
4939 | 50 | |||
4940 | 51 | class BaseFetchHandler(object): | ||
4941 | 52 | |||
4942 | 53 | """Base class for FetchHandler implementations in fetch plugins""" | ||
4943 | 54 | |||
4944 | 55 | def can_handle(self, source): | ||
4945 | 56 | """Returns True if the source can be handled. Otherwise returns | ||
4946 | 57 | a string explaining why it cannot""" | ||
4947 | 58 | return "Wrong source type" | ||
4948 | 59 | |||
4949 | 60 | def install(self, source): | ||
4950 | 61 | """Try to download and unpack the source. Return the path to the | ||
4951 | 62 | unpacked files or raise UnhandledSource.""" | ||
4952 | 63 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
4953 | 64 | |||
4954 | 65 | def parse_url(self, url): | ||
4955 | 66 | return urlparse(url) | ||
4956 | 67 | |||
4957 | 68 | def base_url(self, url): | ||
4958 | 69 | """Return url without querystring or fragment""" | ||
4959 | 70 | parts = list(self.parse_url(url)) | ||
4960 | 71 | parts[4:] = ['' for i in parts[4:]] | ||
4961 | 72 | return urlunparse(parts) | ||
4962 | 73 | |||
4963 | 74 | |||
4964 | 75 | __platform__ = get_platform() | ||
4965 | 76 | module = "charmhelpers.fetch.%s" % __platform__ | ||
4966 | 77 | fetch = importlib.import_module(module) | ||
4967 | 78 | |||
4968 | 79 | filter_installed_packages = fetch.filter_installed_packages | ||
4969 | 80 | install = fetch.install | ||
4970 | 81 | upgrade = fetch.upgrade | ||
4971 | 82 | update = fetch.update | ||
4972 | 83 | purge = fetch.purge | ||
4973 | 84 | add_source = fetch.add_source | ||
4974 | 85 | |||
4975 | 86 | if __platform__ == "ubuntu": | ||
4976 | 87 | apt_cache = fetch.apt_cache | ||
4977 | 88 | apt_install = fetch.install | ||
4978 | 89 | apt_update = fetch.update | ||
4979 | 90 | apt_upgrade = fetch.upgrade | ||
4980 | 91 | apt_purge = fetch.purge | ||
4981 | 92 | apt_mark = fetch.apt_mark | ||
4982 | 93 | apt_hold = fetch.apt_hold | ||
4983 | 94 | apt_unhold = fetch.apt_unhold | ||
4984 | 95 | get_upstream_version = fetch.get_upstream_version | ||
4985 | 96 | elif __platform__ == "centos": | ||
4986 | 97 | yum_search = fetch.yum_search | ||
4987 | 98 | |||
4988 | 99 | |||
4989 | 100 | def configure_sources(update=False, | ||
4990 | 101 | sources_var='install_sources', | ||
4991 | 102 | keys_var='install_keys'): | ||
4992 | 103 | """Configure multiple sources from charm configuration. | ||
4993 | 104 | |||
4994 | 105 | The lists are encoded as yaml fragments in the configuration. | ||
4995 | 106 | The fragment needs to be included as a string. Sources and their | ||
4996 | 107 | corresponding keys are of the types supported by add_source(). | ||
4997 | 108 | |||
4998 | 109 | Example config: | ||
4999 | 110 | install_sources: | | ||
5000 | 111 | - "ppa:foo" |