Merge lp:~brad-marshall/charms/trusty/ceilometer/add-haproxy-nrpe-fix-servicegroups into lp:~openstack-charmers-archive/charms/trusty/ceilometer/next
- Trusty Tahr (14.04)
- add-haproxy-nrpe-fix-servicegroups
- Merge into next
Proposed by
Brad Marshall
Status: | Merged |
---|---|
Merged at revision: | 70 |
Proposed branch: | lp:~brad-marshall/charms/trusty/ceilometer/add-haproxy-nrpe-fix-servicegroups |
Merge into: | lp:~openstack-charmers-archive/charms/trusty/ceilometer/next |
Diff against target: |
1082 lines (+734/-42) 19 files modified
config.yaml (+6/-0) hooks/ceilometer_hooks.py (+2/-0) hooks/charmhelpers/contrib/charmsupport/nrpe.py (+41/-7) hooks/charmhelpers/contrib/hahelpers/cluster.py (+5/-1) hooks/charmhelpers/contrib/openstack/amulet/deployment.py (+5/-2) hooks/charmhelpers/contrib/openstack/files/__init__.py (+18/-0) hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh (+32/-0) hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh (+30/-0) hooks/charmhelpers/contrib/openstack/ip.py (+37/-0) hooks/charmhelpers/contrib/openstack/utils.py (+1/-0) hooks/charmhelpers/contrib/python/packages.py (+2/-2) hooks/charmhelpers/core/fstab.py (+4/-4) hooks/charmhelpers/core/host.py (+5/-5) hooks/charmhelpers/core/strutils.py (+42/-0) hooks/charmhelpers/core/sysctl.py (+13/-7) hooks/charmhelpers/core/templating.py (+3/-3) hooks/charmhelpers/core/unitdata.py (+477/-0) hooks/charmhelpers/fetch/archiveurl.py (+10/-10) hooks/charmhelpers/fetch/giturl.py (+1/-1) |
To merge this branch: | bzr merge lp:~brad-marshall/charms/trusty/ceilometer/add-haproxy-nrpe-fix-servicegroups |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Liam Young (community) | Approve | ||
Review via email: mp+250713@code.launchpad.net |
Commit message
Description of the change
Synced charmhelpers, added nagios_servicegroup config option, and added haproxy nrpe checks.
To post a comment you must log in.
Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote : | # |
Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote : | # |
charm_unit_test #2017 ceilometer-next for brad-marshall mp250713
UNIT OK: passed
Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote : | # |
charm_amulet_test #2174 ceilometer-next for brad-marshall mp250713
AMULET FAIL: amulet-test missing
AMULET Results (max last 2 lines):
INFO:root:Search string not found in makefile target commands.
ERROR:root:No make target was executed.
Full amulet test output: http://
Build: http://
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === modified file 'config.yaml' | |||
2 | --- config.yaml 2015-01-09 16:27:03 +0000 | |||
3 | +++ config.yaml 2015-02-24 06:29:10 +0000 | |||
4 | @@ -68,6 +68,12 @@ | |||
5 | 68 | juju-myservice-0 | 68 | juju-myservice-0 |
6 | 69 | If you're running multiple environments with the same services in them | 69 | If you're running multiple environments with the same services in them |
7 | 70 | this allows you to differentiate between them. | 70 | this allows you to differentiate between them. |
8 | 71 | nagios_servicegroups: | ||
9 | 72 | default: "" | ||
10 | 73 | type: string | ||
11 | 74 | description: | | ||
12 | 75 | A comma-separated list of nagios servicegroups. | ||
13 | 76 | If left empty, the nagios_context will be used as the servicegroup | ||
14 | 71 | # Network configuration options | 77 | # Network configuration options |
15 | 72 | # by default all access is over 'private-address' | 78 | # by default all access is over 'private-address' |
16 | 73 | os-admin-network: | 79 | os-admin-network: |
17 | 74 | 80 | ||
18 | === modified file 'hooks/ceilometer_hooks.py' | |||
19 | --- hooks/ceilometer_hooks.py 2015-01-12 12:03:58 +0000 | |||
20 | +++ hooks/ceilometer_hooks.py 2015-02-24 06:29:10 +0000 | |||
21 | @@ -289,7 +289,9 @@ | |||
22 | 289 | hostname = nrpe.get_nagios_hostname() | 289 | hostname = nrpe.get_nagios_hostname() |
23 | 290 | current_unit = nrpe.get_nagios_unit_name() | 290 | current_unit = nrpe.get_nagios_unit_name() |
24 | 291 | nrpe_setup = nrpe.NRPE(hostname=hostname) | 291 | nrpe_setup = nrpe.NRPE(hostname=hostname) |
25 | 292 | nrpe.copy_nrpe_checks() | ||
26 | 292 | nrpe.add_init_service_checks(nrpe_setup, services(), current_unit) | 293 | nrpe.add_init_service_checks(nrpe_setup, services(), current_unit) |
27 | 294 | nrpe.add_haproxy_checks(nrpe_setup, current_unit) | ||
28 | 293 | nrpe_setup.write() | 295 | nrpe_setup.write() |
29 | 294 | 296 | ||
30 | 295 | 297 | ||
31 | 296 | 298 | ||
32 | === modified file 'hooks/charmhelpers/contrib/charmsupport/nrpe.py' | |||
33 | --- hooks/charmhelpers/contrib/charmsupport/nrpe.py 2015-01-26 09:48:14 +0000 | |||
34 | +++ hooks/charmhelpers/contrib/charmsupport/nrpe.py 2015-02-24 06:29:10 +0000 | |||
35 | @@ -24,6 +24,8 @@ | |||
36 | 24 | import pwd | 24 | import pwd |
37 | 25 | import grp | 25 | import grp |
38 | 26 | import os | 26 | import os |
39 | 27 | import glob | ||
40 | 28 | import shutil | ||
41 | 27 | import re | 29 | import re |
42 | 28 | import shlex | 30 | import shlex |
43 | 29 | import yaml | 31 | import yaml |
44 | @@ -161,7 +163,7 @@ | |||
45 | 161 | log('Check command not found: {}'.format(parts[0])) | 163 | log('Check command not found: {}'.format(parts[0])) |
46 | 162 | return '' | 164 | return '' |
47 | 163 | 165 | ||
49 | 164 | def write(self, nagios_context, hostname, nagios_servicegroups=None): | 166 | def write(self, nagios_context, hostname, nagios_servicegroups): |
50 | 165 | nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format( | 167 | nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format( |
51 | 166 | self.command) | 168 | self.command) |
52 | 167 | with open(nrpe_check_file, 'w') as nrpe_check_config: | 169 | with open(nrpe_check_file, 'w') as nrpe_check_config: |
53 | @@ -177,14 +179,11 @@ | |||
54 | 177 | nagios_servicegroups) | 179 | nagios_servicegroups) |
55 | 178 | 180 | ||
56 | 179 | def write_service_config(self, nagios_context, hostname, | 181 | def write_service_config(self, nagios_context, hostname, |
58 | 180 | nagios_servicegroups=None): | 182 | nagios_servicegroups): |
59 | 181 | for f in os.listdir(NRPE.nagios_exportdir): | 183 | for f in os.listdir(NRPE.nagios_exportdir): |
60 | 182 | if re.search('.*{}.cfg'.format(self.command), f): | 184 | if re.search('.*{}.cfg'.format(self.command), f): |
61 | 183 | os.remove(os.path.join(NRPE.nagios_exportdir, f)) | 185 | os.remove(os.path.join(NRPE.nagios_exportdir, f)) |
62 | 184 | 186 | ||
63 | 185 | if not nagios_servicegroups: | ||
64 | 186 | nagios_servicegroups = nagios_context | ||
65 | 187 | |||
66 | 188 | templ_vars = { | 187 | templ_vars = { |
67 | 189 | 'nagios_hostname': hostname, | 188 | 'nagios_hostname': hostname, |
68 | 190 | 'nagios_servicegroup': nagios_servicegroups, | 189 | 'nagios_servicegroup': nagios_servicegroups, |
69 | @@ -211,10 +210,10 @@ | |||
70 | 211 | super(NRPE, self).__init__() | 210 | super(NRPE, self).__init__() |
71 | 212 | self.config = config() | 211 | self.config = config() |
72 | 213 | self.nagios_context = self.config['nagios_context'] | 212 | self.nagios_context = self.config['nagios_context'] |
74 | 214 | if 'nagios_servicegroups' in self.config: | 213 | if 'nagios_servicegroups' in self.config and self.config['nagios_servicegroups']: |
75 | 215 | self.nagios_servicegroups = self.config['nagios_servicegroups'] | 214 | self.nagios_servicegroups = self.config['nagios_servicegroups'] |
76 | 216 | else: | 215 | else: |
78 | 217 | self.nagios_servicegroups = 'juju' | 216 | self.nagios_servicegroups = self.nagios_context |
79 | 218 | self.unit_name = local_unit().replace('/', '-') | 217 | self.unit_name = local_unit().replace('/', '-') |
80 | 219 | if hostname: | 218 | if hostname: |
81 | 220 | self.hostname = hostname | 219 | self.hostname = hostname |
82 | @@ -322,3 +321,38 @@ | |||
83 | 322 | check_cmd='check_status_file.py -f ' | 321 | check_cmd='check_status_file.py -f ' |
84 | 323 | '/var/lib/nagios/service-check-%s.txt' % svc, | 322 | '/var/lib/nagios/service-check-%s.txt' % svc, |
85 | 324 | ) | 323 | ) |
86 | 324 | |||
87 | 325 | |||
88 | 326 | def copy_nrpe_checks(): | ||
89 | 327 | """ | ||
90 | 328 | Copy the nrpe checks into place | ||
91 | 329 | |||
92 | 330 | """ | ||
93 | 331 | NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' | ||
94 | 332 | nrpe_files_dir = os.path.join(os.getenv('CHARM_DIR'), 'hooks', | ||
95 | 333 | 'charmhelpers', 'contrib', 'openstack', | ||
96 | 334 | 'files') | ||
97 | 335 | |||
98 | 336 | if not os.path.exists(NAGIOS_PLUGINS): | ||
99 | 337 | os.makedirs(NAGIOS_PLUGINS) | ||
100 | 338 | for fname in glob.glob(os.path.join(nrpe_files_dir, "check_*")): | ||
101 | 339 | if os.path.isfile(fname): | ||
102 | 340 | shutil.copy2(fname, | ||
103 | 341 | os.path.join(NAGIOS_PLUGINS, os.path.basename(fname))) | ||
104 | 342 | |||
105 | 343 | |||
106 | 344 | def add_haproxy_checks(nrpe, unit_name): | ||
107 | 345 | """ | ||
108 | 346 | Add checks for each service in list | ||
109 | 347 | |||
110 | 348 | :param NRPE nrpe: NRPE object to add check to | ||
111 | 349 | :param str unit_name: Unit name to use in check description | ||
112 | 350 | """ | ||
113 | 351 | nrpe.add_check( | ||
114 | 352 | shortname='haproxy_servers', | ||
115 | 353 | description='Check HAProxy {%s}' % unit_name, | ||
116 | 354 | check_cmd='check_haproxy.sh') | ||
117 | 355 | nrpe.add_check( | ||
118 | 356 | shortname='haproxy_queue', | ||
119 | 357 | description='Check HAProxy queue depth {%s}' % unit_name, | ||
120 | 358 | check_cmd='check_haproxy_queue_depth.sh') | ||
121 | 325 | 359 | ||
122 | === modified file 'hooks/charmhelpers/contrib/hahelpers/cluster.py' | |||
123 | --- hooks/charmhelpers/contrib/hahelpers/cluster.py 2015-01-26 09:48:14 +0000 | |||
124 | +++ hooks/charmhelpers/contrib/hahelpers/cluster.py 2015-02-24 06:29:10 +0000 | |||
125 | @@ -48,6 +48,9 @@ | |||
126 | 48 | from charmhelpers.core.decorators import ( | 48 | from charmhelpers.core.decorators import ( |
127 | 49 | retry_on_exception, | 49 | retry_on_exception, |
128 | 50 | ) | 50 | ) |
129 | 51 | from charmhelpers.core.strutils import ( | ||
130 | 52 | bool_from_string, | ||
131 | 53 | ) | ||
132 | 51 | 54 | ||
133 | 52 | 55 | ||
134 | 53 | class HAIncompleteConfig(Exception): | 56 | class HAIncompleteConfig(Exception): |
135 | @@ -164,7 +167,8 @@ | |||
136 | 164 | . | 167 | . |
137 | 165 | returns: boolean | 168 | returns: boolean |
138 | 166 | ''' | 169 | ''' |
140 | 167 | if config_get('use-https') == "yes": | 170 | use_https = config_get('use-https') |
141 | 171 | if use_https and bool_from_string(use_https): | ||
142 | 168 | return True | 172 | return True |
143 | 169 | if config_get('ssl_cert') and config_get('ssl_key'): | 173 | if config_get('ssl_cert') and config_get('ssl_key'): |
144 | 170 | return True | 174 | return True |
145 | 171 | 175 | ||
146 | === modified file 'hooks/charmhelpers/contrib/openstack/amulet/deployment.py' | |||
147 | --- hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-01-26 09:48:14 +0000 | |||
148 | +++ hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-02-24 06:29:10 +0000 | |||
149 | @@ -71,16 +71,19 @@ | |||
150 | 71 | services.append(this_service) | 71 | services.append(this_service) |
151 | 72 | use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph', | 72 | use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph', |
152 | 73 | 'ceph-osd', 'ceph-radosgw'] | 73 | 'ceph-osd', 'ceph-radosgw'] |
153 | 74 | # Openstack subordinate charms do not expose an origin option as that | ||
154 | 75 | # is controlled by the principle | ||
155 | 76 | ignore = ['neutron-openvswitch'] | ||
156 | 74 | 77 | ||
157 | 75 | if self.openstack: | 78 | if self.openstack: |
158 | 76 | for svc in services: | 79 | for svc in services: |
160 | 77 | if svc['name'] not in use_source: | 80 | if svc['name'] not in use_source + ignore: |
161 | 78 | config = {'openstack-origin': self.openstack} | 81 | config = {'openstack-origin': self.openstack} |
162 | 79 | self.d.configure(svc['name'], config) | 82 | self.d.configure(svc['name'], config) |
163 | 80 | 83 | ||
164 | 81 | if self.source: | 84 | if self.source: |
165 | 82 | for svc in services: | 85 | for svc in services: |
167 | 83 | if svc['name'] in use_source: | 86 | if svc['name'] in use_source and svc['name'] not in ignore: |
168 | 84 | config = {'source': self.source} | 87 | config = {'source': self.source} |
169 | 85 | self.d.configure(svc['name'], config) | 88 | self.d.configure(svc['name'], config) |
170 | 86 | 89 | ||
171 | 87 | 90 | ||
172 | === added directory 'hooks/charmhelpers/contrib/openstack/files' | |||
173 | === added file 'hooks/charmhelpers/contrib/openstack/files/__init__.py' | |||
174 | --- hooks/charmhelpers/contrib/openstack/files/__init__.py 1970-01-01 00:00:00 +0000 | |||
175 | +++ hooks/charmhelpers/contrib/openstack/files/__init__.py 2015-02-24 06:29:10 +0000 | |||
176 | @@ -0,0 +1,18 @@ | |||
177 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
178 | 2 | # | ||
179 | 3 | # This file is part of charm-helpers. | ||
180 | 4 | # | ||
181 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
182 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
183 | 7 | # published by the Free Software Foundation. | ||
184 | 8 | # | ||
185 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
186 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
187 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
188 | 12 | # GNU Lesser General Public License for more details. | ||
189 | 13 | # | ||
190 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
191 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
192 | 16 | |||
193 | 17 | # dummy __init__.py to fool syncer into thinking this is a syncable python | ||
194 | 18 | # module | ||
195 | 0 | 19 | ||
196 | === added file 'hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh' | |||
197 | --- hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh 1970-01-01 00:00:00 +0000 | |||
198 | +++ hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh 2015-02-24 06:29:10 +0000 | |||
199 | @@ -0,0 +1,32 @@ | |||
200 | 1 | #!/bin/bash | ||
201 | 2 | #-------------------------------------------- | ||
202 | 3 | # This file is managed by Juju | ||
203 | 4 | #-------------------------------------------- | ||
204 | 5 | # | ||
205 | 6 | # Copyright 2009,2012 Canonical Ltd. | ||
206 | 7 | # Author: Tom Haddon | ||
207 | 8 | |||
208 | 9 | CRITICAL=0 | ||
209 | 10 | NOTACTIVE='' | ||
210 | 11 | LOGFILE=/var/log/nagios/check_haproxy.log | ||
211 | 12 | AUTH=$(grep -r "stats auth" /etc/haproxy | head -1 | awk '{print $4}') | ||
212 | 13 | |||
213 | 14 | for appserver in $(grep ' server' /etc/haproxy/haproxy.cfg | awk '{print $2'}); | ||
214 | 15 | do | ||
215 | 16 | output=$(/usr/lib/nagios/plugins/check_http -a ${AUTH} -I 127.0.0.1 -p 8888 --regex="class=\"(active|backup)(2|3).*${appserver}" -e ' 200 OK') | ||
216 | 17 | if [ $? != 0 ]; then | ||
217 | 18 | date >> $LOGFILE | ||
218 | 19 | echo $output >> $LOGFILE | ||
219 | 20 | /usr/lib/nagios/plugins/check_http -a ${AUTH} -I 127.0.0.1 -p 8888 -v | grep $appserver >> $LOGFILE 2>&1 | ||
220 | 21 | CRITICAL=1 | ||
221 | 22 | NOTACTIVE="${NOTACTIVE} $appserver" | ||
222 | 23 | fi | ||
223 | 24 | done | ||
224 | 25 | |||
225 | 26 | if [ $CRITICAL = 1 ]; then | ||
226 | 27 | echo "CRITICAL:${NOTACTIVE}" | ||
227 | 28 | exit 2 | ||
228 | 29 | fi | ||
229 | 30 | |||
230 | 31 | echo "OK: All haproxy instances looking good" | ||
231 | 32 | exit 0 | ||
232 | 0 | 33 | ||
233 | === added file 'hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh' | |||
234 | --- hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh 1970-01-01 00:00:00 +0000 | |||
235 | +++ hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh 2015-02-24 06:29:10 +0000 | |||
236 | @@ -0,0 +1,30 @@ | |||
237 | 1 | #!/bin/bash | ||
238 | 2 | #-------------------------------------------- | ||
239 | 3 | # This file is managed by Juju | ||
240 | 4 | #-------------------------------------------- | ||
241 | 5 | # | ||
242 | 6 | # Copyright 2009,2012 Canonical Ltd. | ||
243 | 7 | # Author: Tom Haddon | ||
244 | 8 | |||
245 | 9 | # These should be config options at some stage | ||
246 | 10 | CURRQthrsh=0 | ||
247 | 11 | MAXQthrsh=100 | ||
248 | 12 | |||
249 | 13 | AUTH=$(grep -r "stats auth" /etc/haproxy | head -1 | awk '{print $4}') | ||
250 | 14 | |||
251 | 15 | HAPROXYSTATS=$(/usr/lib/nagios/plugins/check_http -a ${AUTH} -I 127.0.0.1 -p 8888 -u '/;csv' -v) | ||
252 | 16 | |||
253 | 17 | for BACKEND in $(echo $HAPROXYSTATS| xargs -n1 | grep BACKEND | awk -F , '{print $1}') | ||
254 | 18 | do | ||
255 | 19 | CURRQ=$(echo "$HAPROXYSTATS" | grep $BACKEND | grep BACKEND | cut -d , -f 3) | ||
256 | 20 | MAXQ=$(echo "$HAPROXYSTATS" | grep $BACKEND | grep BACKEND | cut -d , -f 4) | ||
257 | 21 | |||
258 | 22 | if [[ $CURRQ -gt $CURRQthrsh || $MAXQ -gt $MAXQthrsh ]] ; then | ||
259 | 23 | echo "CRITICAL: queue depth for $BACKEND - CURRENT:$CURRQ MAX:$MAXQ" | ||
260 | 24 | exit 2 | ||
261 | 25 | fi | ||
262 | 26 | done | ||
263 | 27 | |||
264 | 28 | echo "OK: All haproxy queue depths looking good" | ||
265 | 29 | exit 0 | ||
266 | 30 | |||
267 | 0 | 31 | ||
268 | === modified file 'hooks/charmhelpers/contrib/openstack/ip.py' | |||
269 | --- hooks/charmhelpers/contrib/openstack/ip.py 2015-01-26 09:48:14 +0000 | |||
270 | +++ hooks/charmhelpers/contrib/openstack/ip.py 2015-02-24 06:29:10 +0000 | |||
271 | @@ -26,6 +26,8 @@ | |||
272 | 26 | ) | 26 | ) |
273 | 27 | from charmhelpers.contrib.hahelpers.cluster import is_clustered | 27 | from charmhelpers.contrib.hahelpers.cluster import is_clustered |
274 | 28 | 28 | ||
275 | 29 | from functools import partial | ||
276 | 30 | |||
277 | 29 | PUBLIC = 'public' | 31 | PUBLIC = 'public' |
278 | 30 | INTERNAL = 'int' | 32 | INTERNAL = 'int' |
279 | 31 | ADMIN = 'admin' | 33 | ADMIN = 'admin' |
280 | @@ -107,3 +109,38 @@ | |||
281 | 107 | "clustered=%s)" % (net_type, clustered)) | 109 | "clustered=%s)" % (net_type, clustered)) |
282 | 108 | 110 | ||
283 | 109 | return resolved_address | 111 | return resolved_address |
284 | 112 | |||
285 | 113 | |||
286 | 114 | def endpoint_url(configs, url_template, port, endpoint_type=PUBLIC, | ||
287 | 115 | override=None): | ||
288 | 116 | """Returns the correct endpoint URL to advertise to Keystone. | ||
289 | 117 | |||
290 | 118 | This method provides the correct endpoint URL which should be advertised to | ||
291 | 119 | the keystone charm for endpoint creation. This method allows for the url to | ||
292 | 120 | be overridden to force a keystone endpoint to have specific URL for any of | ||
293 | 121 | the defined scopes (admin, internal, public). | ||
294 | 122 | |||
295 | 123 | :param configs: OSTemplateRenderer config templating object to inspect | ||
296 | 124 | for a complete https context. | ||
297 | 125 | :param url_template: str format string for creating the url template. Only | ||
298 | 126 | two values will be passed - the scheme+hostname | ||
299 | 127 | returned by the canonical_url and the port. | ||
300 | 128 | :param endpoint_type: str endpoint type to resolve. | ||
301 | 129 | :param override: str the name of the config option which overrides the | ||
302 | 130 | endpoint URL defined by the charm itself. None will | ||
303 | 131 | disable any overrides (default). | ||
304 | 132 | """ | ||
305 | 133 | if override: | ||
306 | 134 | # Return any user-defined overrides for the keystone endpoint URL. | ||
307 | 135 | user_value = config(override) | ||
308 | 136 | if user_value: | ||
309 | 137 | return user_value.strip() | ||
310 | 138 | |||
311 | 139 | return url_template % (canonical_url(configs, endpoint_type), port) | ||
312 | 140 | |||
313 | 141 | |||
314 | 142 | public_endpoint = partial(endpoint_url, endpoint_type=PUBLIC) | ||
315 | 143 | |||
316 | 144 | internal_endpoint = partial(endpoint_url, endpoint_type=INTERNAL) | ||
317 | 145 | |||
318 | 146 | admin_endpoint = partial(endpoint_url, endpoint_type=ADMIN) | ||
319 | 110 | 147 | ||
320 | === modified file 'hooks/charmhelpers/contrib/openstack/utils.py' | |||
321 | --- hooks/charmhelpers/contrib/openstack/utils.py 2015-01-26 09:48:14 +0000 | |||
322 | +++ hooks/charmhelpers/contrib/openstack/utils.py 2015-02-24 06:29:10 +0000 | |||
323 | @@ -103,6 +103,7 @@ | |||
324 | 103 | ('2.1.0', 'juno'), | 103 | ('2.1.0', 'juno'), |
325 | 104 | ('2.2.0', 'juno'), | 104 | ('2.2.0', 'juno'), |
326 | 105 | ('2.2.1', 'kilo'), | 105 | ('2.2.1', 'kilo'), |
327 | 106 | ('2.2.2', 'kilo'), | ||
328 | 106 | ]) | 107 | ]) |
329 | 107 | 108 | ||
330 | 108 | DEFAULT_LOOPBACK_SIZE = '5G' | 109 | DEFAULT_LOOPBACK_SIZE = '5G' |
331 | 109 | 110 | ||
332 | === modified file 'hooks/charmhelpers/contrib/python/packages.py' | |||
333 | --- hooks/charmhelpers/contrib/python/packages.py 2015-01-26 09:48:14 +0000 | |||
334 | +++ hooks/charmhelpers/contrib/python/packages.py 2015-02-24 06:29:10 +0000 | |||
335 | @@ -17,8 +17,6 @@ | |||
336 | 17 | # You should have received a copy of the GNU Lesser General Public License | 17 | # You should have received a copy of the GNU Lesser General Public License |
337 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. |
338 | 19 | 19 | ||
339 | 20 | __author__ = "Jorge Niedbalski <jorge.niedbalski@canonical.com>" | ||
340 | 21 | |||
341 | 22 | from charmhelpers.fetch import apt_install, apt_update | 20 | from charmhelpers.fetch import apt_install, apt_update |
342 | 23 | from charmhelpers.core.hookenv import log | 21 | from charmhelpers.core.hookenv import log |
343 | 24 | 22 | ||
344 | @@ -29,6 +27,8 @@ | |||
345 | 29 | apt_install('python-pip') | 27 | apt_install('python-pip') |
346 | 30 | from pip import main as pip_execute | 28 | from pip import main as pip_execute |
347 | 31 | 29 | ||
348 | 30 | __author__ = "Jorge Niedbalski <jorge.niedbalski@canonical.com>" | ||
349 | 31 | |||
350 | 32 | 32 | ||
351 | 33 | def parse_options(given, available): | 33 | def parse_options(given, available): |
352 | 34 | """Given a set of options, check if available""" | 34 | """Given a set of options, check if available""" |
353 | 35 | 35 | ||
354 | === modified file 'hooks/charmhelpers/core/fstab.py' | |||
355 | --- hooks/charmhelpers/core/fstab.py 2015-01-26 09:48:14 +0000 | |||
356 | +++ hooks/charmhelpers/core/fstab.py 2015-02-24 06:29:10 +0000 | |||
357 | @@ -17,11 +17,11 @@ | |||
358 | 17 | # You should have received a copy of the GNU Lesser General Public License | 17 | # You should have received a copy of the GNU Lesser General Public License |
359 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. |
360 | 19 | 19 | ||
361 | 20 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
362 | 21 | |||
363 | 22 | import io | 20 | import io |
364 | 23 | import os | 21 | import os |
365 | 24 | 22 | ||
366 | 23 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
367 | 24 | |||
368 | 25 | 25 | ||
369 | 26 | class Fstab(io.FileIO): | 26 | class Fstab(io.FileIO): |
370 | 27 | """This class extends file in order to implement a file reader/writer | 27 | """This class extends file in order to implement a file reader/writer |
371 | @@ -77,7 +77,7 @@ | |||
372 | 77 | for line in self.readlines(): | 77 | for line in self.readlines(): |
373 | 78 | line = line.decode('us-ascii') | 78 | line = line.decode('us-ascii') |
374 | 79 | try: | 79 | try: |
376 | 80 | if line.strip() and not line.startswith("#"): | 80 | if line.strip() and not line.strip().startswith("#"): |
377 | 81 | yield self._hydrate_entry(line) | 81 | yield self._hydrate_entry(line) |
378 | 82 | except ValueError: | 82 | except ValueError: |
379 | 83 | pass | 83 | pass |
380 | @@ -104,7 +104,7 @@ | |||
381 | 104 | 104 | ||
382 | 105 | found = False | 105 | found = False |
383 | 106 | for index, line in enumerate(lines): | 106 | for index, line in enumerate(lines): |
385 | 107 | if not line.startswith("#"): | 107 | if line.strip() and not line.strip().startswith("#"): |
386 | 108 | if self._hydrate_entry(line) == entry: | 108 | if self._hydrate_entry(line) == entry: |
387 | 109 | found = True | 109 | found = True |
388 | 110 | break | 110 | break |
389 | 111 | 111 | ||
390 | === modified file 'hooks/charmhelpers/core/host.py' | |||
391 | --- hooks/charmhelpers/core/host.py 2015-01-26 09:48:14 +0000 | |||
392 | +++ hooks/charmhelpers/core/host.py 2015-02-24 06:29:10 +0000 | |||
393 | @@ -191,11 +191,11 @@ | |||
394 | 191 | 191 | ||
395 | 192 | 192 | ||
396 | 193 | def write_file(path, content, owner='root', group='root', perms=0o444): | 193 | def write_file(path, content, owner='root', group='root', perms=0o444): |
398 | 194 | """Create or overwrite a file with the contents of a string""" | 194 | """Create or overwrite a file with the contents of a byte string.""" |
399 | 195 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) | 195 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) |
400 | 196 | uid = pwd.getpwnam(owner).pw_uid | 196 | uid = pwd.getpwnam(owner).pw_uid |
401 | 197 | gid = grp.getgrnam(group).gr_gid | 197 | gid = grp.getgrnam(group).gr_gid |
403 | 198 | with open(path, 'w') as target: | 198 | with open(path, 'wb') as target: |
404 | 199 | os.fchown(target.fileno(), uid, gid) | 199 | os.fchown(target.fileno(), uid, gid) |
405 | 200 | os.fchmod(target.fileno(), perms) | 200 | os.fchmod(target.fileno(), perms) |
406 | 201 | target.write(content) | 201 | target.write(content) |
407 | @@ -305,11 +305,11 @@ | |||
408 | 305 | ceph_client_changed function. | 305 | ceph_client_changed function. |
409 | 306 | """ | 306 | """ |
410 | 307 | def wrap(f): | 307 | def wrap(f): |
412 | 308 | def wrapped_f(*args): | 308 | def wrapped_f(*args, **kwargs): |
413 | 309 | checksums = {} | 309 | checksums = {} |
414 | 310 | for path in restart_map: | 310 | for path in restart_map: |
415 | 311 | checksums[path] = file_hash(path) | 311 | checksums[path] = file_hash(path) |
417 | 312 | f(*args) | 312 | f(*args, **kwargs) |
418 | 313 | restarts = [] | 313 | restarts = [] |
419 | 314 | for path in restart_map: | 314 | for path in restart_map: |
420 | 315 | if checksums[path] != file_hash(path): | 315 | if checksums[path] != file_hash(path): |
421 | @@ -361,7 +361,7 @@ | |||
422 | 361 | ip_output = (line for line in ip_output if line) | 361 | ip_output = (line for line in ip_output if line) |
423 | 362 | for line in ip_output: | 362 | for line in ip_output: |
424 | 363 | if line.split()[1].startswith(int_type): | 363 | if line.split()[1].startswith(int_type): |
426 | 364 | matched = re.search('.*: (bond[0-9]+\.[0-9]+)@.*', line) | 364 | matched = re.search('.*: (' + int_type + r'[0-9]+\.[0-9]+)@.*', line) |
427 | 365 | if matched: | 365 | if matched: |
428 | 366 | interface = matched.groups()[0] | 366 | interface = matched.groups()[0] |
429 | 367 | else: | 367 | else: |
430 | 368 | 368 | ||
431 | === added file 'hooks/charmhelpers/core/strutils.py' | |||
432 | --- hooks/charmhelpers/core/strutils.py 1970-01-01 00:00:00 +0000 | |||
433 | +++ hooks/charmhelpers/core/strutils.py 2015-02-24 06:29:10 +0000 | |||
434 | @@ -0,0 +1,42 @@ | |||
435 | 1 | #!/usr/bin/env python | ||
436 | 2 | # -*- coding: utf-8 -*- | ||
437 | 3 | |||
438 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
439 | 5 | # | ||
440 | 6 | # This file is part of charm-helpers. | ||
441 | 7 | # | ||
442 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
443 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
444 | 10 | # published by the Free Software Foundation. | ||
445 | 11 | # | ||
446 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
447 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
448 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
449 | 15 | # GNU Lesser General Public License for more details. | ||
450 | 16 | # | ||
451 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
452 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
453 | 19 | |||
454 | 20 | import six | ||
455 | 21 | |||
456 | 22 | |||
457 | 23 | def bool_from_string(value): | ||
458 | 24 | """Interpret string value as boolean. | ||
459 | 25 | |||
460 | 26 | Returns True if value translates to True otherwise False. | ||
461 | 27 | """ | ||
462 | 28 | if isinstance(value, six.string_types): | ||
463 | 29 | value = six.text_type(value) | ||
464 | 30 | else: | ||
465 | 31 | msg = "Unable to interpret non-string value '%s' as boolean" % (value) | ||
466 | 32 | raise ValueError(msg) | ||
467 | 33 | |||
468 | 34 | value = value.strip().lower() | ||
469 | 35 | |||
470 | 36 | if value in ['y', 'yes', 'true', 't']: | ||
471 | 37 | return True | ||
472 | 38 | elif value in ['n', 'no', 'false', 'f']: | ||
473 | 39 | return False | ||
474 | 40 | |||
475 | 41 | msg = "Unable to interpret string value '%s' as boolean" % (value) | ||
476 | 42 | raise ValueError(msg) | ||
477 | 0 | 43 | ||
478 | === modified file 'hooks/charmhelpers/core/sysctl.py' | |||
479 | --- hooks/charmhelpers/core/sysctl.py 2015-01-26 09:48:14 +0000 | |||
480 | +++ hooks/charmhelpers/core/sysctl.py 2015-02-24 06:29:10 +0000 | |||
481 | @@ -17,8 +17,6 @@ | |||
482 | 17 | # You should have received a copy of the GNU Lesser General Public License | 17 | # You should have received a copy of the GNU Lesser General Public License |
483 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. |
484 | 19 | 19 | ||
485 | 20 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
486 | 21 | |||
487 | 22 | import yaml | 20 | import yaml |
488 | 23 | 21 | ||
489 | 24 | from subprocess import check_call | 22 | from subprocess import check_call |
490 | @@ -26,25 +24,33 @@ | |||
491 | 26 | from charmhelpers.core.hookenv import ( | 24 | from charmhelpers.core.hookenv import ( |
492 | 27 | log, | 25 | log, |
493 | 28 | DEBUG, | 26 | DEBUG, |
494 | 27 | ERROR, | ||
495 | 29 | ) | 28 | ) |
496 | 30 | 29 | ||
497 | 30 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
498 | 31 | |||
499 | 31 | 32 | ||
500 | 32 | def create(sysctl_dict, sysctl_file): | 33 | def create(sysctl_dict, sysctl_file): |
501 | 33 | """Creates a sysctl.conf file from a YAML associative array | 34 | """Creates a sysctl.conf file from a YAML associative array |
502 | 34 | 35 | ||
505 | 35 | :param sysctl_dict: a dict of sysctl options eg { 'kernel.max_pid': 1337 } | 36 | :param sysctl_dict: a YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" |
506 | 36 | :type sysctl_dict: dict | 37 | :type sysctl_dict: str |
507 | 37 | :param sysctl_file: path to the sysctl file to be saved | 38 | :param sysctl_file: path to the sysctl file to be saved |
508 | 38 | :type sysctl_file: str or unicode | 39 | :type sysctl_file: str or unicode |
509 | 39 | :returns: None | 40 | :returns: None |
510 | 40 | """ | 41 | """ |
512 | 41 | sysctl_dict = yaml.load(sysctl_dict) | 42 | try: |
513 | 43 | sysctl_dict_parsed = yaml.safe_load(sysctl_dict) | ||
514 | 44 | except yaml.YAMLError: | ||
515 | 45 | log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict), | ||
516 | 46 | level=ERROR) | ||
517 | 47 | return | ||
518 | 42 | 48 | ||
519 | 43 | with open(sysctl_file, "w") as fd: | 49 | with open(sysctl_file, "w") as fd: |
521 | 44 | for key, value in sysctl_dict.items(): | 50 | for key, value in sysctl_dict_parsed.items(): |
522 | 45 | fd.write("{}={}\n".format(key, value)) | 51 | fd.write("{}={}\n".format(key, value)) |
523 | 46 | 52 | ||
525 | 47 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict), | 53 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict_parsed), |
526 | 48 | level=DEBUG) | 54 | level=DEBUG) |
527 | 49 | 55 | ||
528 | 50 | check_call(["sysctl", "-p", sysctl_file]) | 56 | check_call(["sysctl", "-p", sysctl_file]) |
529 | 51 | 57 | ||
530 | === modified file 'hooks/charmhelpers/core/templating.py' | |||
531 | --- hooks/charmhelpers/core/templating.py 2015-01-26 09:48:14 +0000 | |||
532 | +++ hooks/charmhelpers/core/templating.py 2015-02-24 06:29:10 +0000 | |||
533 | @@ -21,7 +21,7 @@ | |||
534 | 21 | 21 | ||
535 | 22 | 22 | ||
536 | 23 | def render(source, target, context, owner='root', group='root', | 23 | def render(source, target, context, owner='root', group='root', |
538 | 24 | perms=0o444, templates_dir=None): | 24 | perms=0o444, templates_dir=None, encoding='UTF-8'): |
539 | 25 | """ | 25 | """ |
540 | 26 | Render a template. | 26 | Render a template. |
541 | 27 | 27 | ||
542 | @@ -64,5 +64,5 @@ | |||
543 | 64 | level=hookenv.ERROR) | 64 | level=hookenv.ERROR) |
544 | 65 | raise e | 65 | raise e |
545 | 66 | content = template.render(context) | 66 | content = template.render(context) |
548 | 67 | host.mkdir(os.path.dirname(target), owner, group) | 67 | host.mkdir(os.path.dirname(target), owner, group, perms=0o755) |
549 | 68 | host.write_file(target, content, owner, group, perms) | 68 | host.write_file(target, content.encode(encoding), owner, group, perms) |
550 | 69 | 69 | ||
551 | === added file 'hooks/charmhelpers/core/unitdata.py' | |||
552 | --- hooks/charmhelpers/core/unitdata.py 1970-01-01 00:00:00 +0000 | |||
553 | +++ hooks/charmhelpers/core/unitdata.py 2015-02-24 06:29:10 +0000 | |||
554 | @@ -0,0 +1,477 @@ | |||
555 | 1 | #!/usr/bin/env python | ||
556 | 2 | # -*- coding: utf-8 -*- | ||
557 | 3 | # | ||
558 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
559 | 5 | # | ||
560 | 6 | # This file is part of charm-helpers. | ||
561 | 7 | # | ||
562 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
563 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
564 | 10 | # published by the Free Software Foundation. | ||
565 | 11 | # | ||
566 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
567 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
568 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
569 | 15 | # GNU Lesser General Public License for more details. | ||
570 | 16 | # | ||
571 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
572 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
573 | 19 | # | ||
574 | 20 | # | ||
575 | 21 | # Authors: | ||
576 | 22 | # Kapil Thangavelu <kapil.foss@gmail.com> | ||
577 | 23 | # | ||
578 | 24 | """ | ||
579 | 25 | Intro | ||
580 | 26 | ----- | ||
581 | 27 | |||
582 | 28 | A simple way to store state in units. This provides a key value | ||
583 | 29 | storage with support for versioned, transactional operation, | ||
584 | 30 | and can calculate deltas from previous values to simplify unit logic | ||
585 | 31 | when processing changes. | ||
586 | 32 | |||
587 | 33 | |||
588 | 34 | Hook Integration | ||
589 | 35 | ---------------- | ||
590 | 36 | |||
591 | 37 | There are several extant frameworks for hook execution, including | ||
592 | 38 | |||
593 | 39 | - charmhelpers.core.hookenv.Hooks | ||
594 | 40 | - charmhelpers.core.services.ServiceManager | ||
595 | 41 | |||
596 | 42 | The storage classes are framework agnostic, one simple integration is | ||
597 | 43 | via the HookData contextmanager. It will record the current hook | ||
598 | 44 | execution environment (including relation data, config data, etc.), | ||
599 | 45 | setup a transaction and allow easy access to the changes from | ||
600 | 46 | previously seen values. One consequence of the integration is the | ||
601 | 47 | reservation of particular keys ('rels', 'unit', 'env', 'config', | ||
602 | 48 | 'charm_revisions') for their respective values. | ||
603 | 49 | |||
604 | 50 | Here's a fully worked integration example using hookenv.Hooks:: | ||
605 | 51 | |||
606 | 52 | from charmhelper.core import hookenv, unitdata | ||
607 | 53 | |||
608 | 54 | hook_data = unitdata.HookData() | ||
609 | 55 | db = unitdata.kv() | ||
610 | 56 | hooks = hookenv.Hooks() | ||
611 | 57 | |||
612 | 58 | @hooks.hook | ||
613 | 59 | def config_changed(): | ||
614 | 60 | # Print all changes to configuration from previously seen | ||
615 | 61 | # values. | ||
616 | 62 | for changed, (prev, cur) in hook_data.conf.items(): | ||
617 | 63 | print('config changed', changed, | ||
618 | 64 | 'previous value', prev, | ||
619 | 65 | 'current value', cur) | ||
620 | 66 | |||
621 | 67 | # Get some unit specific bookeeping | ||
622 | 68 | if not db.get('pkg_key'): | ||
623 | 69 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
624 | 70 | db.set('pkg_key', key) | ||
625 | 71 | |||
626 | 72 | # Directly access all charm config as a mapping. | ||
627 | 73 | conf = db.getrange('config', True) | ||
628 | 74 | |||
629 | 75 | # Directly access all relation data as a mapping | ||
630 | 76 | rels = db.getrange('rels', True) | ||
631 | 77 | |||
632 | 78 | if __name__ == '__main__': | ||
633 | 79 | with hook_data(): | ||
634 | 80 | hook.execute() | ||
635 | 81 | |||
636 | 82 | |||
637 | 83 | A more basic integration is via the hook_scope context manager which simply | ||
638 | 84 | manages transaction scope (and records hook name, and timestamp):: | ||
639 | 85 | |||
640 | 86 | >>> from unitdata import kv | ||
641 | 87 | >>> db = kv() | ||
642 | 88 | >>> with db.hook_scope('install'): | ||
643 | 89 | ... # do work, in transactional scope. | ||
644 | 90 | ... db.set('x', 1) | ||
645 | 91 | >>> db.get('x') | ||
646 | 92 | 1 | ||
647 | 93 | |||
648 | 94 | |||
649 | 95 | Usage | ||
650 | 96 | ----- | ||
651 | 97 | |||
652 | 98 | Values are automatically json de/serialized to preserve basic typing | ||
653 | 99 | and complex data struct capabilities (dicts, lists, ints, booleans, etc). | ||
654 | 100 | |||
655 | 101 | Individual values can be manipulated via get/set:: | ||
656 | 102 | |||
657 | 103 | >>> kv.set('y', True) | ||
658 | 104 | >>> kv.get('y') | ||
659 | 105 | True | ||
660 | 106 | |||
661 | 107 | # We can set complex values (dicts, lists) as a single key. | ||
662 | 108 | >>> kv.set('config', {'a': 1, 'b': True'}) | ||
663 | 109 | |||
664 | 110 | # Also supports returning dictionaries as a record which | ||
665 | 111 | # provides attribute access. | ||
666 | 112 | >>> config = kv.get('config', record=True) | ||
667 | 113 | >>> config.b | ||
668 | 114 | True | ||
669 | 115 | |||
670 | 116 | |||
671 | 117 | Groups of keys can be manipulated with update/getrange:: | ||
672 | 118 | |||
673 | 119 | >>> kv.update({'z': 1, 'y': 2}, prefix="gui.") | ||
674 | 120 | >>> kv.getrange('gui.', strip=True) | ||
675 | 121 | {'z': 1, 'y': 2} | ||
676 | 122 | |||
677 | 123 | When updating values, its very helpful to understand which values | ||
678 | 124 | have actually changed and how have they changed. The storage | ||
679 | 125 | provides a delta method to provide for this:: | ||
680 | 126 | |||
681 | 127 | >>> data = {'debug': True, 'option': 2} | ||
682 | 128 | >>> delta = kv.delta(data, 'config.') | ||
683 | 129 | >>> delta.debug.previous | ||
684 | 130 | None | ||
685 | 131 | >>> delta.debug.current | ||
686 | 132 | True | ||
687 | 133 | >>> delta | ||
688 | 134 | {'debug': (None, True), 'option': (None, 2)} | ||
689 | 135 | |||
690 | 136 | Note the delta method does not persist the actual change, it needs to | ||
691 | 137 | be explicitly saved via 'update' method:: | ||
692 | 138 | |||
693 | 139 | >>> kv.update(data, 'config.') | ||
694 | 140 | |||
695 | 141 | Values modified in the context of a hook scope retain historical values | ||
696 | 142 | associated to the hookname. | ||
697 | 143 | |||
698 | 144 | >>> with db.hook_scope('config-changed'): | ||
699 | 145 | ... db.set('x', 42) | ||
700 | 146 | >>> db.gethistory('x') | ||
701 | 147 | [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'), | ||
702 | 148 | (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')] | ||
703 | 149 | |||
704 | 150 | """ | ||
705 | 151 | |||
706 | 152 | import collections | ||
707 | 153 | import contextlib | ||
708 | 154 | import datetime | ||
709 | 155 | import json | ||
710 | 156 | import os | ||
711 | 157 | import pprint | ||
712 | 158 | import sqlite3 | ||
713 | 159 | import sys | ||
714 | 160 | |||
715 | 161 | __author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>' | ||
716 | 162 | |||
717 | 163 | |||
718 | 164 | class Storage(object): | ||
719 | 165 | """Simple key value database for local unit state within charms. | ||
720 | 166 | |||
721 | 167 | Modifications are automatically committed at hook exit. That's | ||
722 | 168 | currently regardless of exit code. | ||
723 | 169 | |||
724 | 170 | To support dicts, lists, integer, floats, and booleans values | ||
725 | 171 | are automatically json encoded/decoded. | ||
726 | 172 | """ | ||
727 | 173 | def __init__(self, path=None): | ||
728 | 174 | self.db_path = path | ||
729 | 175 | if path is None: | ||
730 | 176 | self.db_path = os.path.join( | ||
731 | 177 | os.environ.get('CHARM_DIR', ''), '.unit-state.db') | ||
732 | 178 | self.conn = sqlite3.connect('%s' % self.db_path) | ||
733 | 179 | self.cursor = self.conn.cursor() | ||
734 | 180 | self.revision = None | ||
735 | 181 | self._closed = False | ||
736 | 182 | self._init() | ||
737 | 183 | |||
738 | 184 | def close(self): | ||
739 | 185 | if self._closed: | ||
740 | 186 | return | ||
741 | 187 | self.flush(False) | ||
742 | 188 | self.cursor.close() | ||
743 | 189 | self.conn.close() | ||
744 | 190 | self._closed = True | ||
745 | 191 | |||
746 | 192 | def _scoped_query(self, stmt, params=None): | ||
747 | 193 | if params is None: | ||
748 | 194 | params = [] | ||
749 | 195 | return stmt, params | ||
750 | 196 | |||
751 | 197 | def get(self, key, default=None, record=False): | ||
752 | 198 | self.cursor.execute( | ||
753 | 199 | *self._scoped_query( | ||
754 | 200 | 'select data from kv where key=?', [key])) | ||
755 | 201 | result = self.cursor.fetchone() | ||
756 | 202 | if not result: | ||
757 | 203 | return default | ||
758 | 204 | if record: | ||
759 | 205 | return Record(json.loads(result[0])) | ||
760 | 206 | return json.loads(result[0]) | ||
761 | 207 | |||
762 | 208 | def getrange(self, key_prefix, strip=False): | ||
763 | 209 | stmt = "select key, data from kv where key like '%s%%'" % key_prefix | ||
764 | 210 | self.cursor.execute(*self._scoped_query(stmt)) | ||
765 | 211 | result = self.cursor.fetchall() | ||
766 | 212 | |||
767 | 213 | if not result: | ||
768 | 214 | return None | ||
769 | 215 | if not strip: | ||
770 | 216 | key_prefix = '' | ||
771 | 217 | return dict([ | ||
772 | 218 | (k[len(key_prefix):], json.loads(v)) for k, v in result]) | ||
773 | 219 | |||
774 | 220 | def update(self, mapping, prefix=""): | ||
775 | 221 | for k, v in mapping.items(): | ||
776 | 222 | self.set("%s%s" % (prefix, k), v) | ||
777 | 223 | |||
778 | 224 | def unset(self, key): | ||
779 | 225 | self.cursor.execute('delete from kv where key=?', [key]) | ||
780 | 226 | if self.revision and self.cursor.rowcount: | ||
781 | 227 | self.cursor.execute( | ||
782 | 228 | 'insert into kv_revisions values (?, ?, ?)', | ||
783 | 229 | [key, self.revision, json.dumps('DELETED')]) | ||
784 | 230 | |||
785 | 231 | def set(self, key, value): | ||
786 | 232 | serialized = json.dumps(value) | ||
787 | 233 | |||
788 | 234 | self.cursor.execute( | ||
789 | 235 | 'select data from kv where key=?', [key]) | ||
790 | 236 | exists = self.cursor.fetchone() | ||
791 | 237 | |||
792 | 238 | # Skip mutations to the same value | ||
793 | 239 | if exists: | ||
794 | 240 | if exists[0] == serialized: | ||
795 | 241 | return value | ||
796 | 242 | |||
797 | 243 | if not exists: | ||
798 | 244 | self.cursor.execute( | ||
799 | 245 | 'insert into kv (key, data) values (?, ?)', | ||
800 | 246 | (key, serialized)) | ||
801 | 247 | else: | ||
802 | 248 | self.cursor.execute(''' | ||
803 | 249 | update kv | ||
804 | 250 | set data = ? | ||
805 | 251 | where key = ?''', [serialized, key]) | ||
806 | 252 | |||
807 | 253 | # Save | ||
808 | 254 | if not self.revision: | ||
809 | 255 | return value | ||
810 | 256 | |||
811 | 257 | self.cursor.execute( | ||
812 | 258 | 'select 1 from kv_revisions where key=? and revision=?', | ||
813 | 259 | [key, self.revision]) | ||
814 | 260 | exists = self.cursor.fetchone() | ||
815 | 261 | |||
816 | 262 | if not exists: | ||
817 | 263 | self.cursor.execute( | ||
818 | 264 | '''insert into kv_revisions ( | ||
819 | 265 | revision, key, data) values (?, ?, ?)''', | ||
820 | 266 | (self.revision, key, serialized)) | ||
821 | 267 | else: | ||
822 | 268 | self.cursor.execute( | ||
823 | 269 | ''' | ||
824 | 270 | update kv_revisions | ||
825 | 271 | set data = ? | ||
826 | 272 | where key = ? | ||
827 | 273 | and revision = ?''', | ||
828 | 274 | [serialized, key, self.revision]) | ||
829 | 275 | |||
830 | 276 | return value | ||
831 | 277 | |||
832 | 278 | def delta(self, mapping, prefix): | ||
833 | 279 | """ | ||
834 | 280 | return a delta containing values that have changed. | ||
835 | 281 | """ | ||
836 | 282 | previous = self.getrange(prefix, strip=True) | ||
837 | 283 | if not previous: | ||
838 | 284 | pk = set() | ||
839 | 285 | else: | ||
840 | 286 | pk = set(previous.keys()) | ||
841 | 287 | ck = set(mapping.keys()) | ||
842 | 288 | delta = DeltaSet() | ||
843 | 289 | |||
844 | 290 | # added | ||
845 | 291 | for k in ck.difference(pk): | ||
846 | 292 | delta[k] = Delta(None, mapping[k]) | ||
847 | 293 | |||
848 | 294 | # removed | ||
849 | 295 | for k in pk.difference(ck): | ||
850 | 296 | delta[k] = Delta(previous[k], None) | ||
851 | 297 | |||
852 | 298 | # changed | ||
853 | 299 | for k in pk.intersection(ck): | ||
854 | 300 | c = mapping[k] | ||
855 | 301 | p = previous[k] | ||
856 | 302 | if c != p: | ||
857 | 303 | delta[k] = Delta(p, c) | ||
858 | 304 | |||
859 | 305 | return delta | ||
860 | 306 | |||
861 | 307 | @contextlib.contextmanager | ||
862 | 308 | def hook_scope(self, name=""): | ||
863 | 309 | """Scope all future interactions to the current hook execution | ||
864 | 310 | revision.""" | ||
865 | 311 | assert not self.revision | ||
866 | 312 | self.cursor.execute( | ||
867 | 313 | 'insert into hooks (hook, date) values (?, ?)', | ||
868 | 314 | (name or sys.argv[0], | ||
869 | 315 | datetime.datetime.utcnow().isoformat())) | ||
870 | 316 | self.revision = self.cursor.lastrowid | ||
871 | 317 | try: | ||
872 | 318 | yield self.revision | ||
873 | 319 | self.revision = None | ||
874 | 320 | except: | ||
875 | 321 | self.flush(False) | ||
876 | 322 | self.revision = None | ||
877 | 323 | raise | ||
878 | 324 | else: | ||
879 | 325 | self.flush() | ||
880 | 326 | |||
881 | 327 | def flush(self, save=True): | ||
882 | 328 | if save: | ||
883 | 329 | self.conn.commit() | ||
884 | 330 | elif self._closed: | ||
885 | 331 | return | ||
886 | 332 | else: | ||
887 | 333 | self.conn.rollback() | ||
888 | 334 | |||
889 | 335 | def _init(self): | ||
890 | 336 | self.cursor.execute(''' | ||
891 | 337 | create table if not exists kv ( | ||
892 | 338 | key text, | ||
893 | 339 | data text, | ||
894 | 340 | primary key (key) | ||
895 | 341 | )''') | ||
896 | 342 | self.cursor.execute(''' | ||
897 | 343 | create table if not exists kv_revisions ( | ||
898 | 344 | key text, | ||
899 | 345 | revision integer, | ||
900 | 346 | data text, | ||
901 | 347 | primary key (key, revision) | ||
902 | 348 | )''') | ||
903 | 349 | self.cursor.execute(''' | ||
904 | 350 | create table if not exists hooks ( | ||
905 | 351 | version integer primary key autoincrement, | ||
906 | 352 | hook text, | ||
907 | 353 | date text | ||
908 | 354 | )''') | ||
909 | 355 | self.conn.commit() | ||
910 | 356 | |||
911 | 357 | def gethistory(self, key, deserialize=False): | ||
912 | 358 | self.cursor.execute( | ||
913 | 359 | ''' | ||
914 | 360 | select kv.revision, kv.key, kv.data, h.hook, h.date | ||
915 | 361 | from kv_revisions kv, | ||
916 | 362 | hooks h | ||
917 | 363 | where kv.key=? | ||
918 | 364 | and kv.revision = h.version | ||
919 | 365 | ''', [key]) | ||
920 | 366 | if deserialize is False: | ||
921 | 367 | return self.cursor.fetchall() | ||
922 | 368 | return map(_parse_history, self.cursor.fetchall()) | ||
923 | 369 | |||
924 | 370 | def debug(self, fh=sys.stderr): | ||
925 | 371 | self.cursor.execute('select * from kv') | ||
926 | 372 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
927 | 373 | self.cursor.execute('select * from kv_revisions') | ||
928 | 374 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
929 | 375 | |||
930 | 376 | |||
931 | 377 | def _parse_history(d): | ||
932 | 378 | return (d[0], d[1], json.loads(d[2]), d[3], | ||
933 | 379 | datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f")) | ||
934 | 380 | |||
935 | 381 | |||
936 | 382 | class HookData(object): | ||
937 | 383 | """Simple integration for existing hook exec frameworks. | ||
938 | 384 | |||
939 | 385 | Records all unit information, and stores deltas for processing | ||
940 | 386 | by the hook. | ||
941 | 387 | |||
942 | 388 | Sample:: | ||
943 | 389 | |||
944 | 390 | from charmhelper.core import hookenv, unitdata | ||
945 | 391 | |||
946 | 392 | changes = unitdata.HookData() | ||
947 | 393 | db = unitdata.kv() | ||
948 | 394 | hooks = hookenv.Hooks() | ||
949 | 395 | |||
950 | 396 | @hooks.hook | ||
951 | 397 | def config_changed(): | ||
952 | 398 | # View all changes to configuration | ||
953 | 399 | for changed, (prev, cur) in changes.conf.items(): | ||
954 | 400 | print('config changed', changed, | ||
955 | 401 | 'previous value', prev, | ||
956 | 402 | 'current value', cur) | ||
957 | 403 | |||
958 | 404 | # Get some unit specific bookeeping | ||
959 | 405 | if not db.get('pkg_key'): | ||
960 | 406 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
961 | 407 | db.set('pkg_key', key) | ||
962 | 408 | |||
963 | 409 | if __name__ == '__main__': | ||
964 | 410 | with changes(): | ||
965 | 411 | hook.execute() | ||
966 | 412 | |||
967 | 413 | """ | ||
968 | 414 | def __init__(self): | ||
969 | 415 | self.kv = kv() | ||
970 | 416 | self.conf = None | ||
971 | 417 | self.rels = None | ||
972 | 418 | |||
973 | 419 | @contextlib.contextmanager | ||
974 | 420 | def __call__(self): | ||
975 | 421 | from charmhelpers.core import hookenv | ||
976 | 422 | hook_name = hookenv.hook_name() | ||
977 | 423 | |||
978 | 424 | with self.kv.hook_scope(hook_name): | ||
979 | 425 | self._record_charm_version(hookenv.charm_dir()) | ||
980 | 426 | delta_config, delta_relation = self._record_hook(hookenv) | ||
981 | 427 | yield self.kv, delta_config, delta_relation | ||
982 | 428 | |||
983 | 429 | def _record_charm_version(self, charm_dir): | ||
984 | 430 | # Record revisions.. charm revisions are meaningless | ||
985 | 431 | # to charm authors as they don't control the revision. | ||
986 | 432 | # so logic dependnent on revision is not particularly | ||
987 | 433 | # useful, however it is useful for debugging analysis. | ||
988 | 434 | charm_rev = open( | ||
989 | 435 | os.path.join(charm_dir, 'revision')).read().strip() | ||
990 | 436 | charm_rev = charm_rev or '0' | ||
991 | 437 | revs = self.kv.get('charm_revisions', []) | ||
992 | 438 | if charm_rev not in revs: | ||
993 | 439 | revs.append(charm_rev.strip() or '0') | ||
994 | 440 | self.kv.set('charm_revisions', revs) | ||
995 | 441 | |||
996 | 442 | def _record_hook(self, hookenv): | ||
997 | 443 | data = hookenv.execution_environment() | ||
998 | 444 | self.conf = conf_delta = self.kv.delta(data['conf'], 'config') | ||
999 | 445 | self.rels = rels_delta = self.kv.delta(data['rels'], 'rels') | ||
1000 | 446 | self.kv.set('env', data['env']) | ||
1001 | 447 | self.kv.set('unit', data['unit']) | ||
1002 | 448 | self.kv.set('relid', data.get('relid')) | ||
1003 | 449 | return conf_delta, rels_delta | ||
1004 | 450 | |||
1005 | 451 | |||
1006 | 452 | class Record(dict): | ||
1007 | 453 | |||
1008 | 454 | __slots__ = () | ||
1009 | 455 | |||
1010 | 456 | def __getattr__(self, k): | ||
1011 | 457 | if k in self: | ||
1012 | 458 | return self[k] | ||
1013 | 459 | raise AttributeError(k) | ||
1014 | 460 | |||
1015 | 461 | |||
1016 | 462 | class DeltaSet(Record): | ||
1017 | 463 | |||
1018 | 464 | __slots__ = () | ||
1019 | 465 | |||
1020 | 466 | |||
1021 | 467 | Delta = collections.namedtuple('Delta', ['previous', 'current']) | ||
1022 | 468 | |||
1023 | 469 | |||
1024 | 470 | _KV = None | ||
1025 | 471 | |||
1026 | 472 | |||
1027 | 473 | def kv(): | ||
1028 | 474 | global _KV | ||
1029 | 475 | if _KV is None: | ||
1030 | 476 | _KV = Storage() | ||
1031 | 477 | return _KV | ||
1032 | 0 | 478 | ||
1033 | === modified file 'hooks/charmhelpers/fetch/archiveurl.py' | |||
1034 | --- hooks/charmhelpers/fetch/archiveurl.py 2015-01-26 09:48:14 +0000 | |||
1035 | +++ hooks/charmhelpers/fetch/archiveurl.py 2015-02-24 06:29:10 +0000 | |||
1036 | @@ -18,6 +18,16 @@ | |||
1037 | 18 | import hashlib | 18 | import hashlib |
1038 | 19 | import re | 19 | import re |
1039 | 20 | 20 | ||
1040 | 21 | from charmhelpers.fetch import ( | ||
1041 | 22 | BaseFetchHandler, | ||
1042 | 23 | UnhandledSource | ||
1043 | 24 | ) | ||
1044 | 25 | from charmhelpers.payload.archive import ( | ||
1045 | 26 | get_archive_handler, | ||
1046 | 27 | extract, | ||
1047 | 28 | ) | ||
1048 | 29 | from charmhelpers.core.host import mkdir, check_hash | ||
1049 | 30 | |||
1050 | 21 | import six | 31 | import six |
1051 | 22 | if six.PY3: | 32 | if six.PY3: |
1052 | 23 | from urllib.request import ( | 33 | from urllib.request import ( |
1053 | @@ -35,16 +45,6 @@ | |||
1054 | 35 | ) | 45 | ) |
1055 | 36 | from urlparse import urlparse, urlunparse, parse_qs | 46 | from urlparse import urlparse, urlunparse, parse_qs |
1056 | 37 | 47 | ||
1057 | 38 | from charmhelpers.fetch import ( | ||
1058 | 39 | BaseFetchHandler, | ||
1059 | 40 | UnhandledSource | ||
1060 | 41 | ) | ||
1061 | 42 | from charmhelpers.payload.archive import ( | ||
1062 | 43 | get_archive_handler, | ||
1063 | 44 | extract, | ||
1064 | 45 | ) | ||
1065 | 46 | from charmhelpers.core.host import mkdir, check_hash | ||
1066 | 47 | |||
1067 | 48 | 48 | ||
1068 | 49 | def splituser(host): | 49 | def splituser(host): |
1069 | 50 | '''urllib.splituser(), but six's support of this seems broken''' | 50 | '''urllib.splituser(), but six's support of this seems broken''' |
1070 | 51 | 51 | ||
1071 | === modified file 'hooks/charmhelpers/fetch/giturl.py' | |||
1072 | --- hooks/charmhelpers/fetch/giturl.py 2015-01-26 09:48:14 +0000 | |||
1073 | +++ hooks/charmhelpers/fetch/giturl.py 2015-02-24 06:29:10 +0000 | |||
1074 | @@ -32,7 +32,7 @@ | |||
1075 | 32 | apt_install("python-git") | 32 | apt_install("python-git") |
1076 | 33 | from git import Repo | 33 | from git import Repo |
1077 | 34 | 34 | ||
1079 | 35 | from git.exc import GitCommandError | 35 | from git.exc import GitCommandError # noqa E402 |
1080 | 36 | 36 | ||
1081 | 37 | 37 | ||
1082 | 38 | class GitUrlFetchHandler(BaseFetchHandler): | 38 | class GitUrlFetchHandler(BaseFetchHandler): |
charm_lint_check #2228 ceilometer-next for brad-marshall mp250713
LINT OK: passed
Build: http:// 10.245. 162.77: 8080/job/ charm_lint_ check/2228/