Merge lp:~brad-marshall/charms/trusty/neutron-api/add-haproxy-nrpe-fix-servicegroups into lp:~openstack-charmers-archive/charms/trusty/neutron-api/next
- Trusty Tahr (14.04)
- add-haproxy-nrpe-fix-servicegroups
- Merge into next
Proposed by
Brad Marshall
Status: | Merged |
---|---|
Merged at revision: | 81 |
Proposed branch: | lp:~brad-marshall/charms/trusty/neutron-api/add-haproxy-nrpe-fix-servicegroups |
Merge into: | lp:~openstack-charmers-archive/charms/trusty/neutron-api/next |
Diff against target: |
1455 lines (+264/-499) 16 files modified
Makefile (+1/-1) config.yaml (+6/-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/context.py (+28/-9) 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/templates/zeromq (+14/-0) hooks/charmhelpers/contrib/openstack/utils.py (+1/-0) hooks/charmhelpers/core/fstab.py (+2/-2) hooks/charmhelpers/core/strutils.py (+42/-0) hooks/charmhelpers/core/unitdata.py (+0/-477) hooks/neutron_api_hooks.py (+2/-0) |
To merge this branch: | bzr merge lp:~brad-marshall/charms/trusty/neutron-api/add-haproxy-nrpe-fix-servicegroups |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Liam Young (community) | Approve | ||
Review via email: mp+250705@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.
- 80. By Edward Hope-Morley
-
[trivial] charmhelpers sync
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 #2009 neutron-api-next for brad-marshall mp250705
UNIT OK: passed
Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote : | # |
charm_amulet_test #2166 neutron-api-next for brad-marshall mp250705
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://
- 81. By Brad Marshall
-
[bradm] Fixed merge conflicts
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === modified file 'Makefile' | |||
2 | --- Makefile 2015-02-17 07:10:15 +0000 | |||
3 | +++ Makefile 2015-02-26 04:23:37 +0000 | |||
4 | @@ -15,7 +15,7 @@ | |||
5 | 15 | > bin/charm_helpers_sync.py | 15 | > bin/charm_helpers_sync.py |
6 | 16 | 16 | ||
7 | 17 | sync: bin/charm_helpers_sync.py | 17 | sync: bin/charm_helpers_sync.py |
9 | 18 | # @$(PYTHON) bin/charm_helpers_sync.py -c charm-helpers-hooks.yaml | 18 | @$(PYTHON) bin/charm_helpers_sync.py -c charm-helpers-hooks.yaml |
10 | 19 | @$(PYTHON) bin/charm_helpers_sync.py -c charm-helpers-tests.yaml | 19 | @$(PYTHON) bin/charm_helpers_sync.py -c charm-helpers-tests.yaml |
11 | 20 | 20 | ||
12 | 21 | test: | 21 | test: |
13 | 22 | 22 | ||
14 | === modified file 'config.yaml' | |||
15 | --- config.yaml 2015-01-13 14:43:04 +0000 | |||
16 | +++ config.yaml 2015-02-26 04:23:37 +0000 | |||
17 | @@ -213,3 +213,9 @@ | |||
18 | 213 | juju-myservice-0 | 213 | juju-myservice-0 |
19 | 214 | If you're running multiple environments with the same services in them | 214 | If you're running multiple environments with the same services in them |
20 | 215 | this allows you to differentiate between them. | 215 | this allows you to differentiate between them. |
21 | 216 | nagios_servicegroups: | ||
22 | 217 | default: "" | ||
23 | 218 | type: string | ||
24 | 219 | description: | | ||
25 | 220 | A comma-separated list of nagios servicegroups. | ||
26 | 221 | If left empty, the nagios_context will be used as the servicegroup | ||
27 | 216 | 222 | ||
28 | === modified file 'hooks/charmhelpers/contrib/charmsupport/nrpe.py' | |||
29 | --- hooks/charmhelpers/contrib/charmsupport/nrpe.py 2015-01-26 09:44:26 +0000 | |||
30 | +++ hooks/charmhelpers/contrib/charmsupport/nrpe.py 2015-02-26 04:23:37 +0000 | |||
31 | @@ -24,6 +24,8 @@ | |||
32 | 24 | import pwd | 24 | import pwd |
33 | 25 | import grp | 25 | import grp |
34 | 26 | import os | 26 | import os |
35 | 27 | import glob | ||
36 | 28 | import shutil | ||
37 | 27 | import re | 29 | import re |
38 | 28 | import shlex | 30 | import shlex |
39 | 29 | import yaml | 31 | import yaml |
40 | @@ -161,7 +163,7 @@ | |||
41 | 161 | log('Check command not found: {}'.format(parts[0])) | 163 | log('Check command not found: {}'.format(parts[0])) |
42 | 162 | return '' | 164 | return '' |
43 | 163 | 165 | ||
45 | 164 | def write(self, nagios_context, hostname, nagios_servicegroups=None): | 166 | def write(self, nagios_context, hostname, nagios_servicegroups): |
46 | 165 | nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format( | 167 | nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format( |
47 | 166 | self.command) | 168 | self.command) |
48 | 167 | with open(nrpe_check_file, 'w') as nrpe_check_config: | 169 | with open(nrpe_check_file, 'w') as nrpe_check_config: |
49 | @@ -177,14 +179,11 @@ | |||
50 | 177 | nagios_servicegroups) | 179 | nagios_servicegroups) |
51 | 178 | 180 | ||
52 | 179 | def write_service_config(self, nagios_context, hostname, | 181 | def write_service_config(self, nagios_context, hostname, |
54 | 180 | nagios_servicegroups=None): | 182 | nagios_servicegroups): |
55 | 181 | for f in os.listdir(NRPE.nagios_exportdir): | 183 | for f in os.listdir(NRPE.nagios_exportdir): |
56 | 182 | if re.search('.*{}.cfg'.format(self.command), f): | 184 | if re.search('.*{}.cfg'.format(self.command), f): |
57 | 183 | os.remove(os.path.join(NRPE.nagios_exportdir, f)) | 185 | os.remove(os.path.join(NRPE.nagios_exportdir, f)) |
58 | 184 | 186 | ||
59 | 185 | if not nagios_servicegroups: | ||
60 | 186 | nagios_servicegroups = nagios_context | ||
61 | 187 | |||
62 | 188 | templ_vars = { | 187 | templ_vars = { |
63 | 189 | 'nagios_hostname': hostname, | 188 | 'nagios_hostname': hostname, |
64 | 190 | 'nagios_servicegroup': nagios_servicegroups, | 189 | 'nagios_servicegroup': nagios_servicegroups, |
65 | @@ -211,10 +210,10 @@ | |||
66 | 211 | super(NRPE, self).__init__() | 210 | super(NRPE, self).__init__() |
67 | 212 | self.config = config() | 211 | self.config = config() |
68 | 213 | self.nagios_context = self.config['nagios_context'] | 212 | self.nagios_context = self.config['nagios_context'] |
70 | 214 | if 'nagios_servicegroups' in self.config: | 213 | if 'nagios_servicegroups' in self.config and self.config['nagios_servicegroups']: |
71 | 215 | self.nagios_servicegroups = self.config['nagios_servicegroups'] | 214 | self.nagios_servicegroups = self.config['nagios_servicegroups'] |
72 | 216 | else: | 215 | else: |
74 | 217 | self.nagios_servicegroups = 'juju' | 216 | self.nagios_servicegroups = self.nagios_context |
75 | 218 | self.unit_name = local_unit().replace('/', '-') | 217 | self.unit_name = local_unit().replace('/', '-') |
76 | 219 | if hostname: | 218 | if hostname: |
77 | 220 | self.hostname = hostname | 219 | self.hostname = hostname |
78 | @@ -322,3 +321,38 @@ | |||
79 | 322 | check_cmd='check_status_file.py -f ' | 321 | check_cmd='check_status_file.py -f ' |
80 | 323 | '/var/lib/nagios/service-check-%s.txt' % svc, | 322 | '/var/lib/nagios/service-check-%s.txt' % svc, |
81 | 324 | ) | 323 | ) |
82 | 324 | |||
83 | 325 | |||
84 | 326 | def copy_nrpe_checks(): | ||
85 | 327 | """ | ||
86 | 328 | Copy the nrpe checks into place | ||
87 | 329 | |||
88 | 330 | """ | ||
89 | 331 | NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' | ||
90 | 332 | nrpe_files_dir = os.path.join(os.getenv('CHARM_DIR'), 'hooks', | ||
91 | 333 | 'charmhelpers', 'contrib', 'openstack', | ||
92 | 334 | 'files') | ||
93 | 335 | |||
94 | 336 | if not os.path.exists(NAGIOS_PLUGINS): | ||
95 | 337 | os.makedirs(NAGIOS_PLUGINS) | ||
96 | 338 | for fname in glob.glob(os.path.join(nrpe_files_dir, "check_*")): | ||
97 | 339 | if os.path.isfile(fname): | ||
98 | 340 | shutil.copy2(fname, | ||
99 | 341 | os.path.join(NAGIOS_PLUGINS, os.path.basename(fname))) | ||
100 | 342 | |||
101 | 343 | |||
102 | 344 | def add_haproxy_checks(nrpe, unit_name): | ||
103 | 345 | """ | ||
104 | 346 | Add checks for each service in list | ||
105 | 347 | |||
106 | 348 | :param NRPE nrpe: NRPE object to add check to | ||
107 | 349 | :param str unit_name: Unit name to use in check description | ||
108 | 350 | """ | ||
109 | 351 | nrpe.add_check( | ||
110 | 352 | shortname='haproxy_servers', | ||
111 | 353 | description='Check HAProxy {%s}' % unit_name, | ||
112 | 354 | check_cmd='check_haproxy.sh') | ||
113 | 355 | nrpe.add_check( | ||
114 | 356 | shortname='haproxy_queue', | ||
115 | 357 | description='Check HAProxy queue depth {%s}' % unit_name, | ||
116 | 358 | check_cmd='check_haproxy_queue_depth.sh') | ||
117 | 325 | 359 | ||
118 | === modified file 'hooks/charmhelpers/contrib/hahelpers/cluster.py' | |||
119 | --- hooks/charmhelpers/contrib/hahelpers/cluster.py 2015-01-26 09:44:26 +0000 | |||
120 | +++ hooks/charmhelpers/contrib/hahelpers/cluster.py 2015-02-26 04:23:37 +0000 | |||
121 | @@ -48,6 +48,9 @@ | |||
122 | 48 | from charmhelpers.core.decorators import ( | 48 | from charmhelpers.core.decorators import ( |
123 | 49 | retry_on_exception, | 49 | retry_on_exception, |
124 | 50 | ) | 50 | ) |
125 | 51 | from charmhelpers.core.strutils import ( | ||
126 | 52 | bool_from_string, | ||
127 | 53 | ) | ||
128 | 51 | 54 | ||
129 | 52 | 55 | ||
130 | 53 | class HAIncompleteConfig(Exception): | 56 | class HAIncompleteConfig(Exception): |
131 | @@ -164,7 +167,8 @@ | |||
132 | 164 | . | 167 | . |
133 | 165 | returns: boolean | 168 | returns: boolean |
134 | 166 | ''' | 169 | ''' |
136 | 167 | if config_get('use-https') == "yes": | 170 | use_https = config_get('use-https') |
137 | 171 | if use_https and bool_from_string(use_https): | ||
138 | 168 | return True | 172 | return True |
139 | 169 | if config_get('ssl_cert') and config_get('ssl_key'): | 173 | if config_get('ssl_cert') and config_get('ssl_key'): |
140 | 170 | return True | 174 | return True |
141 | 171 | 175 | ||
142 | === modified file 'hooks/charmhelpers/contrib/openstack/amulet/deployment.py' | |||
143 | --- hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-01-26 09:44:26 +0000 | |||
144 | +++ hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-02-26 04:23:37 +0000 | |||
145 | @@ -71,16 +71,19 @@ | |||
146 | 71 | services.append(this_service) | 71 | services.append(this_service) |
147 | 72 | use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph', | 72 | use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph', |
148 | 73 | 'ceph-osd', 'ceph-radosgw'] | 73 | 'ceph-osd', 'ceph-radosgw'] |
149 | 74 | # Openstack subordinate charms do not expose an origin option as that | ||
150 | 75 | # is controlled by the principle | ||
151 | 76 | ignore = ['neutron-openvswitch'] | ||
152 | 74 | 77 | ||
153 | 75 | if self.openstack: | 78 | if self.openstack: |
154 | 76 | for svc in services: | 79 | for svc in services: |
156 | 77 | if svc['name'] not in use_source: | 80 | if svc['name'] not in use_source + ignore: |
157 | 78 | config = {'openstack-origin': self.openstack} | 81 | config = {'openstack-origin': self.openstack} |
158 | 79 | self.d.configure(svc['name'], config) | 82 | self.d.configure(svc['name'], config) |
159 | 80 | 83 | ||
160 | 81 | if self.source: | 84 | if self.source: |
161 | 82 | for svc in services: | 85 | for svc in services: |
163 | 83 | if svc['name'] in use_source: | 86 | if svc['name'] in use_source and svc['name'] not in ignore: |
164 | 84 | config = {'source': self.source} | 87 | config = {'source': self.source} |
165 | 85 | self.d.configure(svc['name'], config) | 88 | self.d.configure(svc['name'], config) |
166 | 86 | 89 | ||
167 | 87 | 90 | ||
168 | === modified file 'hooks/charmhelpers/contrib/openstack/context.py' | |||
169 | --- hooks/charmhelpers/contrib/openstack/context.py 2015-01-26 09:44:26 +0000 | |||
170 | +++ hooks/charmhelpers/contrib/openstack/context.py 2015-02-26 04:23:37 +0000 | |||
171 | @@ -279,9 +279,25 @@ | |||
172 | 279 | class IdentityServiceContext(OSContextGenerator): | 279 | class IdentityServiceContext(OSContextGenerator): |
173 | 280 | interfaces = ['identity-service'] | 280 | interfaces = ['identity-service'] |
174 | 281 | 281 | ||
175 | 282 | def __init__(self, service=None, service_user=None): | ||
176 | 283 | self.service = service | ||
177 | 284 | self.service_user = service_user | ||
178 | 285 | |||
179 | 282 | def __call__(self): | 286 | def __call__(self): |
180 | 283 | log('Generating template context for identity-service', level=DEBUG) | 287 | log('Generating template context for identity-service', level=DEBUG) |
181 | 284 | ctxt = {} | 288 | ctxt = {} |
182 | 289 | |||
183 | 290 | if self.service and self.service_user: | ||
184 | 291 | # This is required for pki token signing if we don't want /tmp to | ||
185 | 292 | # be used. | ||
186 | 293 | cachedir = '/var/cache/%s' % (self.service) | ||
187 | 294 | if not os.path.isdir(cachedir): | ||
188 | 295 | log("Creating service cache dir %s" % (cachedir), level=DEBUG) | ||
189 | 296 | mkdir(path=cachedir, owner=self.service_user, | ||
190 | 297 | group=self.service_user, perms=0o700) | ||
191 | 298 | |||
192 | 299 | ctxt['signing_dir'] = cachedir | ||
193 | 300 | |||
194 | 285 | for rid in relation_ids('identity-service'): | 301 | for rid in relation_ids('identity-service'): |
195 | 286 | for unit in related_units(rid): | 302 | for unit in related_units(rid): |
196 | 287 | rdata = relation_get(rid=rid, unit=unit) | 303 | rdata = relation_get(rid=rid, unit=unit) |
197 | @@ -291,15 +307,16 @@ | |||
198 | 291 | auth_host = format_ipv6_addr(auth_host) or auth_host | 307 | auth_host = format_ipv6_addr(auth_host) or auth_host |
199 | 292 | svc_protocol = rdata.get('service_protocol') or 'http' | 308 | svc_protocol = rdata.get('service_protocol') or 'http' |
200 | 293 | auth_protocol = rdata.get('auth_protocol') or 'http' | 309 | auth_protocol = rdata.get('auth_protocol') or 'http' |
210 | 294 | ctxt = {'service_port': rdata.get('service_port'), | 310 | ctxt.update({'service_port': rdata.get('service_port'), |
211 | 295 | 'service_host': serv_host, | 311 | 'service_host': serv_host, |
212 | 296 | 'auth_host': auth_host, | 312 | 'auth_host': auth_host, |
213 | 297 | 'auth_port': rdata.get('auth_port'), | 313 | 'auth_port': rdata.get('auth_port'), |
214 | 298 | 'admin_tenant_name': rdata.get('service_tenant'), | 314 | 'admin_tenant_name': rdata.get('service_tenant'), |
215 | 299 | 'admin_user': rdata.get('service_username'), | 315 | 'admin_user': rdata.get('service_username'), |
216 | 300 | 'admin_password': rdata.get('service_password'), | 316 | 'admin_password': rdata.get('service_password'), |
217 | 301 | 'service_protocol': svc_protocol, | 317 | 'service_protocol': svc_protocol, |
218 | 302 | 'auth_protocol': auth_protocol} | 318 | 'auth_protocol': auth_protocol}) |
219 | 319 | |||
220 | 303 | if context_complete(ctxt): | 320 | if context_complete(ctxt): |
221 | 304 | # NOTE(jamespage) this is required for >= icehouse | 321 | # NOTE(jamespage) this is required for >= icehouse |
222 | 305 | # so a missing value just indicates keystone needs | 322 | # so a missing value just indicates keystone needs |
223 | @@ -1021,6 +1038,8 @@ | |||
224 | 1021 | for unit in related_units(rid): | 1038 | for unit in related_units(rid): |
225 | 1022 | ctxt['zmq_nonce'] = relation_get('nonce', unit, rid) | 1039 | ctxt['zmq_nonce'] = relation_get('nonce', unit, rid) |
226 | 1023 | ctxt['zmq_host'] = relation_get('host', unit, rid) | 1040 | ctxt['zmq_host'] = relation_get('host', unit, rid) |
227 | 1041 | ctxt['zmq_redis_address'] = relation_get( | ||
228 | 1042 | 'zmq_redis_address', unit, rid) | ||
229 | 1024 | 1043 | ||
230 | 1025 | return ctxt | 1044 | return ctxt |
231 | 1026 | 1045 | ||
232 | 1027 | 1046 | ||
233 | === added directory 'hooks/charmhelpers/contrib/openstack/files' | |||
234 | === added file 'hooks/charmhelpers/contrib/openstack/files/__init__.py' | |||
235 | --- hooks/charmhelpers/contrib/openstack/files/__init__.py 1970-01-01 00:00:00 +0000 | |||
236 | +++ hooks/charmhelpers/contrib/openstack/files/__init__.py 2015-02-26 04:23:37 +0000 | |||
237 | @@ -0,0 +1,18 @@ | |||
238 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
239 | 2 | # | ||
240 | 3 | # This file is part of charm-helpers. | ||
241 | 4 | # | ||
242 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
243 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
244 | 7 | # published by the Free Software Foundation. | ||
245 | 8 | # | ||
246 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
247 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
248 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
249 | 12 | # GNU Lesser General Public License for more details. | ||
250 | 13 | # | ||
251 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
252 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
253 | 16 | |||
254 | 17 | # dummy __init__.py to fool syncer into thinking this is a syncable python | ||
255 | 18 | # module | ||
256 | 0 | 19 | ||
257 | === added file 'hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh' | |||
258 | --- hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh 1970-01-01 00:00:00 +0000 | |||
259 | +++ hooks/charmhelpers/contrib/openstack/files/check_haproxy.sh 2015-02-26 04:23:37 +0000 | |||
260 | @@ -0,0 +1,32 @@ | |||
261 | 1 | #!/bin/bash | ||
262 | 2 | #-------------------------------------------- | ||
263 | 3 | # This file is managed by Juju | ||
264 | 4 | #-------------------------------------------- | ||
265 | 5 | # | ||
266 | 6 | # Copyright 2009,2012 Canonical Ltd. | ||
267 | 7 | # Author: Tom Haddon | ||
268 | 8 | |||
269 | 9 | CRITICAL=0 | ||
270 | 10 | NOTACTIVE='' | ||
271 | 11 | LOGFILE=/var/log/nagios/check_haproxy.log | ||
272 | 12 | AUTH=$(grep -r "stats auth" /etc/haproxy | head -1 | awk '{print $4}') | ||
273 | 13 | |||
274 | 14 | for appserver in $(grep ' server' /etc/haproxy/haproxy.cfg | awk '{print $2'}); | ||
275 | 15 | do | ||
276 | 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') | ||
277 | 17 | if [ $? != 0 ]; then | ||
278 | 18 | date >> $LOGFILE | ||
279 | 19 | echo $output >> $LOGFILE | ||
280 | 20 | /usr/lib/nagios/plugins/check_http -a ${AUTH} -I 127.0.0.1 -p 8888 -v | grep $appserver >> $LOGFILE 2>&1 | ||
281 | 21 | CRITICAL=1 | ||
282 | 22 | NOTACTIVE="${NOTACTIVE} $appserver" | ||
283 | 23 | fi | ||
284 | 24 | done | ||
285 | 25 | |||
286 | 26 | if [ $CRITICAL = 1 ]; then | ||
287 | 27 | echo "CRITICAL:${NOTACTIVE}" | ||
288 | 28 | exit 2 | ||
289 | 29 | fi | ||
290 | 30 | |||
291 | 31 | echo "OK: All haproxy instances looking good" | ||
292 | 32 | exit 0 | ||
293 | 0 | 33 | ||
294 | === added file 'hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh' | |||
295 | --- hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh 1970-01-01 00:00:00 +0000 | |||
296 | +++ hooks/charmhelpers/contrib/openstack/files/check_haproxy_queue_depth.sh 2015-02-26 04:23:37 +0000 | |||
297 | @@ -0,0 +1,30 @@ | |||
298 | 1 | #!/bin/bash | ||
299 | 2 | #-------------------------------------------- | ||
300 | 3 | # This file is managed by Juju | ||
301 | 4 | #-------------------------------------------- | ||
302 | 5 | # | ||
303 | 6 | # Copyright 2009,2012 Canonical Ltd. | ||
304 | 7 | # Author: Tom Haddon | ||
305 | 8 | |||
306 | 9 | # These should be config options at some stage | ||
307 | 10 | CURRQthrsh=0 | ||
308 | 11 | MAXQthrsh=100 | ||
309 | 12 | |||
310 | 13 | AUTH=$(grep -r "stats auth" /etc/haproxy | head -1 | awk '{print $4}') | ||
311 | 14 | |||
312 | 15 | HAPROXYSTATS=$(/usr/lib/nagios/plugins/check_http -a ${AUTH} -I 127.0.0.1 -p 8888 -u '/;csv' -v) | ||
313 | 16 | |||
314 | 17 | for BACKEND in $(echo $HAPROXYSTATS| xargs -n1 | grep BACKEND | awk -F , '{print $1}') | ||
315 | 18 | do | ||
316 | 19 | CURRQ=$(echo "$HAPROXYSTATS" | grep $BACKEND | grep BACKEND | cut -d , -f 3) | ||
317 | 20 | MAXQ=$(echo "$HAPROXYSTATS" | grep $BACKEND | grep BACKEND | cut -d , -f 4) | ||
318 | 21 | |||
319 | 22 | if [[ $CURRQ -gt $CURRQthrsh || $MAXQ -gt $MAXQthrsh ]] ; then | ||
320 | 23 | echo "CRITICAL: queue depth for $BACKEND - CURRENT:$CURRQ MAX:$MAXQ" | ||
321 | 24 | exit 2 | ||
322 | 25 | fi | ||
323 | 26 | done | ||
324 | 27 | |||
325 | 28 | echo "OK: All haproxy queue depths looking good" | ||
326 | 29 | exit 0 | ||
327 | 30 | |||
328 | 0 | 31 | ||
329 | === modified file 'hooks/charmhelpers/contrib/openstack/ip.py' | |||
330 | --- hooks/charmhelpers/contrib/openstack/ip.py 2015-01-26 09:44:26 +0000 | |||
331 | +++ hooks/charmhelpers/contrib/openstack/ip.py 2015-02-26 04:23:37 +0000 | |||
332 | @@ -26,6 +26,8 @@ | |||
333 | 26 | ) | 26 | ) |
334 | 27 | from charmhelpers.contrib.hahelpers.cluster import is_clustered | 27 | from charmhelpers.contrib.hahelpers.cluster import is_clustered |
335 | 28 | 28 | ||
336 | 29 | from functools import partial | ||
337 | 30 | |||
338 | 29 | PUBLIC = 'public' | 31 | PUBLIC = 'public' |
339 | 30 | INTERNAL = 'int' | 32 | INTERNAL = 'int' |
340 | 31 | ADMIN = 'admin' | 33 | ADMIN = 'admin' |
341 | @@ -107,3 +109,38 @@ | |||
342 | 107 | "clustered=%s)" % (net_type, clustered)) | 109 | "clustered=%s)" % (net_type, clustered)) |
343 | 108 | 110 | ||
344 | 109 | return resolved_address | 111 | return resolved_address |
345 | 112 | |||
346 | 113 | |||
347 | 114 | def endpoint_url(configs, url_template, port, endpoint_type=PUBLIC, | ||
348 | 115 | override=None): | ||
349 | 116 | """Returns the correct endpoint URL to advertise to Keystone. | ||
350 | 117 | |||
351 | 118 | This method provides the correct endpoint URL which should be advertised to | ||
352 | 119 | the keystone charm for endpoint creation. This method allows for the url to | ||
353 | 120 | be overridden to force a keystone endpoint to have specific URL for any of | ||
354 | 121 | the defined scopes (admin, internal, public). | ||
355 | 122 | |||
356 | 123 | :param configs: OSTemplateRenderer config templating object to inspect | ||
357 | 124 | for a complete https context. | ||
358 | 125 | :param url_template: str format string for creating the url template. Only | ||
359 | 126 | two values will be passed - the scheme+hostname | ||
360 | 127 | returned by the canonical_url and the port. | ||
361 | 128 | :param endpoint_type: str endpoint type to resolve. | ||
362 | 129 | :param override: str the name of the config option which overrides the | ||
363 | 130 | endpoint URL defined by the charm itself. None will | ||
364 | 131 | disable any overrides (default). | ||
365 | 132 | """ | ||
366 | 133 | if override: | ||
367 | 134 | # Return any user-defined overrides for the keystone endpoint URL. | ||
368 | 135 | user_value = config(override) | ||
369 | 136 | if user_value: | ||
370 | 137 | return user_value.strip() | ||
371 | 138 | |||
372 | 139 | return url_template % (canonical_url(configs, endpoint_type), port) | ||
373 | 140 | |||
374 | 141 | |||
375 | 142 | public_endpoint = partial(endpoint_url, endpoint_type=PUBLIC) | ||
376 | 143 | |||
377 | 144 | internal_endpoint = partial(endpoint_url, endpoint_type=INTERNAL) | ||
378 | 145 | |||
379 | 146 | admin_endpoint = partial(endpoint_url, endpoint_type=ADMIN) | ||
380 | 110 | 147 | ||
381 | === added file 'hooks/charmhelpers/contrib/openstack/templates/zeromq' | |||
382 | --- hooks/charmhelpers/contrib/openstack/templates/zeromq 1970-01-01 00:00:00 +0000 | |||
383 | +++ hooks/charmhelpers/contrib/openstack/templates/zeromq 2015-02-26 04:23:37 +0000 | |||
384 | @@ -0,0 +1,14 @@ | |||
385 | 1 | {% if zmq_host -%} | ||
386 | 2 | # ZeroMQ configuration (restart-nonce: {{ zmq_nonce }}) | ||
387 | 3 | rpc_backend = zmq | ||
388 | 4 | rpc_zmq_host = {{ zmq_host }} | ||
389 | 5 | {% if zmq_redis_address -%} | ||
390 | 6 | rpc_zmq_matchmaker = oslo.messaging._drivers.matchmaker_redis.MatchMakerRedis | ||
391 | 7 | matchmaker_heartbeat_freq = 15 | ||
392 | 8 | matchmaker_heartbeat_ttl = 30 | ||
393 | 9 | [matchmaker_redis] | ||
394 | 10 | host = {{ zmq_redis_address }} | ||
395 | 11 | {% else -%} | ||
396 | 12 | rpc_zmq_matchmaker = oslo.messaging._drivers.matchmaker_ring.MatchMakerRing | ||
397 | 13 | {% endif -%} | ||
398 | 14 | {% endif -%} | ||
399 | 0 | 15 | ||
400 | === modified file 'hooks/charmhelpers/contrib/openstack/utils.py' | |||
401 | --- hooks/charmhelpers/contrib/openstack/utils.py 2015-01-26 09:44:26 +0000 | |||
402 | +++ hooks/charmhelpers/contrib/openstack/utils.py 2015-02-26 04:23:37 +0000 | |||
403 | @@ -103,6 +103,7 @@ | |||
404 | 103 | ('2.1.0', 'juno'), | 103 | ('2.1.0', 'juno'), |
405 | 104 | ('2.2.0', 'juno'), | 104 | ('2.2.0', 'juno'), |
406 | 105 | ('2.2.1', 'kilo'), | 105 | ('2.2.1', 'kilo'), |
407 | 106 | ('2.2.2', 'kilo'), | ||
408 | 106 | ]) | 107 | ]) |
409 | 107 | 108 | ||
410 | 108 | DEFAULT_LOOPBACK_SIZE = '5G' | 109 | DEFAULT_LOOPBACK_SIZE = '5G' |
411 | 109 | 110 | ||
412 | === modified file 'hooks/charmhelpers/core/fstab.py' | |||
413 | --- hooks/charmhelpers/core/fstab.py 2015-02-17 07:10:15 +0000 | |||
414 | +++ hooks/charmhelpers/core/fstab.py 2015-02-26 04:23:37 +0000 | |||
415 | @@ -77,7 +77,7 @@ | |||
416 | 77 | for line in self.readlines(): | 77 | for line in self.readlines(): |
417 | 78 | line = line.decode('us-ascii') | 78 | line = line.decode('us-ascii') |
418 | 79 | try: | 79 | try: |
420 | 80 | if line.strip() and not line.startswith("#"): | 80 | if line.strip() and not line.strip().startswith("#"): |
421 | 81 | yield self._hydrate_entry(line) | 81 | yield self._hydrate_entry(line) |
422 | 82 | except ValueError: | 82 | except ValueError: |
423 | 83 | pass | 83 | pass |
424 | @@ -104,7 +104,7 @@ | |||
425 | 104 | 104 | ||
426 | 105 | found = False | 105 | found = False |
427 | 106 | for index, line in enumerate(lines): | 106 | for index, line in enumerate(lines): |
429 | 107 | if not line.startswith("#"): | 107 | if line.strip() and not line.strip().startswith("#"): |
430 | 108 | if self._hydrate_entry(line) == entry: | 108 | if self._hydrate_entry(line) == entry: |
431 | 109 | found = True | 109 | found = True |
432 | 110 | break | 110 | break |
433 | 111 | 111 | ||
434 | === added file 'hooks/charmhelpers/core/strutils.py' | |||
435 | --- hooks/charmhelpers/core/strutils.py 1970-01-01 00:00:00 +0000 | |||
436 | +++ hooks/charmhelpers/core/strutils.py 2015-02-26 04:23:37 +0000 | |||
437 | @@ -0,0 +1,42 @@ | |||
438 | 1 | #!/usr/bin/env python | ||
439 | 2 | # -*- coding: utf-8 -*- | ||
440 | 3 | |||
441 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
442 | 5 | # | ||
443 | 6 | # This file is part of charm-helpers. | ||
444 | 7 | # | ||
445 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
446 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
447 | 10 | # published by the Free Software Foundation. | ||
448 | 11 | # | ||
449 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
450 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
451 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
452 | 15 | # GNU Lesser General Public License for more details. | ||
453 | 16 | # | ||
454 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
455 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
456 | 19 | |||
457 | 20 | import six | ||
458 | 21 | |||
459 | 22 | |||
460 | 23 | def bool_from_string(value): | ||
461 | 24 | """Interpret string value as boolean. | ||
462 | 25 | |||
463 | 26 | Returns True if value translates to True otherwise False. | ||
464 | 27 | """ | ||
465 | 28 | if isinstance(value, six.string_types): | ||
466 | 29 | value = six.text_type(value) | ||
467 | 30 | else: | ||
468 | 31 | msg = "Unable to interpret non-string value '%s' as boolean" % (value) | ||
469 | 32 | raise ValueError(msg) | ||
470 | 33 | |||
471 | 34 | value = value.strip().lower() | ||
472 | 35 | |||
473 | 36 | if value in ['y', 'yes', 'true', 't']: | ||
474 | 37 | return True | ||
475 | 38 | elif value in ['n', 'no', 'false', 'f']: | ||
476 | 39 | return False | ||
477 | 40 | |||
478 | 41 | msg = "Unable to interpret string value '%s' as boolean" % (value) | ||
479 | 42 | raise ValueError(msg) | ||
480 | 0 | 43 | ||
481 | === added file 'hooks/charmhelpers/core/unitdata.py' | |||
482 | --- hooks/charmhelpers/core/unitdata.py 1970-01-01 00:00:00 +0000 | |||
483 | +++ hooks/charmhelpers/core/unitdata.py 2015-02-26 04:23:37 +0000 | |||
484 | @@ -0,0 +1,477 @@ | |||
485 | 1 | #!/usr/bin/env python | ||
486 | 2 | # -*- coding: utf-8 -*- | ||
487 | 3 | # | ||
488 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
489 | 5 | # | ||
490 | 6 | # This file is part of charm-helpers. | ||
491 | 7 | # | ||
492 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
493 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
494 | 10 | # published by the Free Software Foundation. | ||
495 | 11 | # | ||
496 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
497 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
498 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
499 | 15 | # GNU Lesser General Public License for more details. | ||
500 | 16 | # | ||
501 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
502 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
503 | 19 | # | ||
504 | 20 | # | ||
505 | 21 | # Authors: | ||
506 | 22 | # Kapil Thangavelu <kapil.foss@gmail.com> | ||
507 | 23 | # | ||
508 | 24 | """ | ||
509 | 25 | Intro | ||
510 | 26 | ----- | ||
511 | 27 | |||
512 | 28 | A simple way to store state in units. This provides a key value | ||
513 | 29 | storage with support for versioned, transactional operation, | ||
514 | 30 | and can calculate deltas from previous values to simplify unit logic | ||
515 | 31 | when processing changes. | ||
516 | 32 | |||
517 | 33 | |||
518 | 34 | Hook Integration | ||
519 | 35 | ---------------- | ||
520 | 36 | |||
521 | 37 | There are several extant frameworks for hook execution, including | ||
522 | 38 | |||
523 | 39 | - charmhelpers.core.hookenv.Hooks | ||
524 | 40 | - charmhelpers.core.services.ServiceManager | ||
525 | 41 | |||
526 | 42 | The storage classes are framework agnostic, one simple integration is | ||
527 | 43 | via the HookData contextmanager. It will record the current hook | ||
528 | 44 | execution environment (including relation data, config data, etc.), | ||
529 | 45 | setup a transaction and allow easy access to the changes from | ||
530 | 46 | previously seen values. One consequence of the integration is the | ||
531 | 47 | reservation of particular keys ('rels', 'unit', 'env', 'config', | ||
532 | 48 | 'charm_revisions') for their respective values. | ||
533 | 49 | |||
534 | 50 | Here's a fully worked integration example using hookenv.Hooks:: | ||
535 | 51 | |||
536 | 52 | from charmhelper.core import hookenv, unitdata | ||
537 | 53 | |||
538 | 54 | hook_data = unitdata.HookData() | ||
539 | 55 | db = unitdata.kv() | ||
540 | 56 | hooks = hookenv.Hooks() | ||
541 | 57 | |||
542 | 58 | @hooks.hook | ||
543 | 59 | def config_changed(): | ||
544 | 60 | # Print all changes to configuration from previously seen | ||
545 | 61 | # values. | ||
546 | 62 | for changed, (prev, cur) in hook_data.conf.items(): | ||
547 | 63 | print('config changed', changed, | ||
548 | 64 | 'previous value', prev, | ||
549 | 65 | 'current value', cur) | ||
550 | 66 | |||
551 | 67 | # Get some unit specific bookeeping | ||
552 | 68 | if not db.get('pkg_key'): | ||
553 | 69 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
554 | 70 | db.set('pkg_key', key) | ||
555 | 71 | |||
556 | 72 | # Directly access all charm config as a mapping. | ||
557 | 73 | conf = db.getrange('config', True) | ||
558 | 74 | |||
559 | 75 | # Directly access all relation data as a mapping | ||
560 | 76 | rels = db.getrange('rels', True) | ||
561 | 77 | |||
562 | 78 | if __name__ == '__main__': | ||
563 | 79 | with hook_data(): | ||
564 | 80 | hook.execute() | ||
565 | 81 | |||
566 | 82 | |||
567 | 83 | A more basic integration is via the hook_scope context manager which simply | ||
568 | 84 | manages transaction scope (and records hook name, and timestamp):: | ||
569 | 85 | |||
570 | 86 | >>> from unitdata import kv | ||
571 | 87 | >>> db = kv() | ||
572 | 88 | >>> with db.hook_scope('install'): | ||
573 | 89 | ... # do work, in transactional scope. | ||
574 | 90 | ... db.set('x', 1) | ||
575 | 91 | >>> db.get('x') | ||
576 | 92 | 1 | ||
577 | 93 | |||
578 | 94 | |||
579 | 95 | Usage | ||
580 | 96 | ----- | ||
581 | 97 | |||
582 | 98 | Values are automatically json de/serialized to preserve basic typing | ||
583 | 99 | and complex data struct capabilities (dicts, lists, ints, booleans, etc). | ||
584 | 100 | |||
585 | 101 | Individual values can be manipulated via get/set:: | ||
586 | 102 | |||
587 | 103 | >>> kv.set('y', True) | ||
588 | 104 | >>> kv.get('y') | ||
589 | 105 | True | ||
590 | 106 | |||
591 | 107 | # We can set complex values (dicts, lists) as a single key. | ||
592 | 108 | >>> kv.set('config', {'a': 1, 'b': True'}) | ||
593 | 109 | |||
594 | 110 | # Also supports returning dictionaries as a record which | ||
595 | 111 | # provides attribute access. | ||
596 | 112 | >>> config = kv.get('config', record=True) | ||
597 | 113 | >>> config.b | ||
598 | 114 | True | ||
599 | 115 | |||
600 | 116 | |||
601 | 117 | Groups of keys can be manipulated with update/getrange:: | ||
602 | 118 | |||
603 | 119 | >>> kv.update({'z': 1, 'y': 2}, prefix="gui.") | ||
604 | 120 | >>> kv.getrange('gui.', strip=True) | ||
605 | 121 | {'z': 1, 'y': 2} | ||
606 | 122 | |||
607 | 123 | When updating values, its very helpful to understand which values | ||
608 | 124 | have actually changed and how have they changed. The storage | ||
609 | 125 | provides a delta method to provide for this:: | ||
610 | 126 | |||
611 | 127 | >>> data = {'debug': True, 'option': 2} | ||
612 | 128 | >>> delta = kv.delta(data, 'config.') | ||
613 | 129 | >>> delta.debug.previous | ||
614 | 130 | None | ||
615 | 131 | >>> delta.debug.current | ||
616 | 132 | True | ||
617 | 133 | >>> delta | ||
618 | 134 | {'debug': (None, True), 'option': (None, 2)} | ||
619 | 135 | |||
620 | 136 | Note the delta method does not persist the actual change, it needs to | ||
621 | 137 | be explicitly saved via 'update' method:: | ||
622 | 138 | |||
623 | 139 | >>> kv.update(data, 'config.') | ||
624 | 140 | |||
625 | 141 | Values modified in the context of a hook scope retain historical values | ||
626 | 142 | associated to the hookname. | ||
627 | 143 | |||
628 | 144 | >>> with db.hook_scope('config-changed'): | ||
629 | 145 | ... db.set('x', 42) | ||
630 | 146 | >>> db.gethistory('x') | ||
631 | 147 | [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'), | ||
632 | 148 | (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')] | ||
633 | 149 | |||
634 | 150 | """ | ||
635 | 151 | |||
636 | 152 | import collections | ||
637 | 153 | import contextlib | ||
638 | 154 | import datetime | ||
639 | 155 | import json | ||
640 | 156 | import os | ||
641 | 157 | import pprint | ||
642 | 158 | import sqlite3 | ||
643 | 159 | import sys | ||
644 | 160 | |||
645 | 161 | __author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>' | ||
646 | 162 | |||
647 | 163 | |||
648 | 164 | class Storage(object): | ||
649 | 165 | """Simple key value database for local unit state within charms. | ||
650 | 166 | |||
651 | 167 | Modifications are automatically committed at hook exit. That's | ||
652 | 168 | currently regardless of exit code. | ||
653 | 169 | |||
654 | 170 | To support dicts, lists, integer, floats, and booleans values | ||
655 | 171 | are automatically json encoded/decoded. | ||
656 | 172 | """ | ||
657 | 173 | def __init__(self, path=None): | ||
658 | 174 | self.db_path = path | ||
659 | 175 | if path is None: | ||
660 | 176 | self.db_path = os.path.join( | ||
661 | 177 | os.environ.get('CHARM_DIR', ''), '.unit-state.db') | ||
662 | 178 | self.conn = sqlite3.connect('%s' % self.db_path) | ||
663 | 179 | self.cursor = self.conn.cursor() | ||
664 | 180 | self.revision = None | ||
665 | 181 | self._closed = False | ||
666 | 182 | self._init() | ||
667 | 183 | |||
668 | 184 | def close(self): | ||
669 | 185 | if self._closed: | ||
670 | 186 | return | ||
671 | 187 | self.flush(False) | ||
672 | 188 | self.cursor.close() | ||
673 | 189 | self.conn.close() | ||
674 | 190 | self._closed = True | ||
675 | 191 | |||
676 | 192 | def _scoped_query(self, stmt, params=None): | ||
677 | 193 | if params is None: | ||
678 | 194 | params = [] | ||
679 | 195 | return stmt, params | ||
680 | 196 | |||
681 | 197 | def get(self, key, default=None, record=False): | ||
682 | 198 | self.cursor.execute( | ||
683 | 199 | *self._scoped_query( | ||
684 | 200 | 'select data from kv where key=?', [key])) | ||
685 | 201 | result = self.cursor.fetchone() | ||
686 | 202 | if not result: | ||
687 | 203 | return default | ||
688 | 204 | if record: | ||
689 | 205 | return Record(json.loads(result[0])) | ||
690 | 206 | return json.loads(result[0]) | ||
691 | 207 | |||
692 | 208 | def getrange(self, key_prefix, strip=False): | ||
693 | 209 | stmt = "select key, data from kv where key like '%s%%'" % key_prefix | ||
694 | 210 | self.cursor.execute(*self._scoped_query(stmt)) | ||
695 | 211 | result = self.cursor.fetchall() | ||
696 | 212 | |||
697 | 213 | if not result: | ||
698 | 214 | return None | ||
699 | 215 | if not strip: | ||
700 | 216 | key_prefix = '' | ||
701 | 217 | return dict([ | ||
702 | 218 | (k[len(key_prefix):], json.loads(v)) for k, v in result]) | ||
703 | 219 | |||
704 | 220 | def update(self, mapping, prefix=""): | ||
705 | 221 | for k, v in mapping.items(): | ||
706 | 222 | self.set("%s%s" % (prefix, k), v) | ||
707 | 223 | |||
708 | 224 | def unset(self, key): | ||
709 | 225 | self.cursor.execute('delete from kv where key=?', [key]) | ||
710 | 226 | if self.revision and self.cursor.rowcount: | ||
711 | 227 | self.cursor.execute( | ||
712 | 228 | 'insert into kv_revisions values (?, ?, ?)', | ||
713 | 229 | [key, self.revision, json.dumps('DELETED')]) | ||
714 | 230 | |||
715 | 231 | def set(self, key, value): | ||
716 | 232 | serialized = json.dumps(value) | ||
717 | 233 | |||
718 | 234 | self.cursor.execute( | ||
719 | 235 | 'select data from kv where key=?', [key]) | ||
720 | 236 | exists = self.cursor.fetchone() | ||
721 | 237 | |||
722 | 238 | # Skip mutations to the same value | ||
723 | 239 | if exists: | ||
724 | 240 | if exists[0] == serialized: | ||
725 | 241 | return value | ||
726 | 242 | |||
727 | 243 | if not exists: | ||
728 | 244 | self.cursor.execute( | ||
729 | 245 | 'insert into kv (key, data) values (?, ?)', | ||
730 | 246 | (key, serialized)) | ||
731 | 247 | else: | ||
732 | 248 | self.cursor.execute(''' | ||
733 | 249 | update kv | ||
734 | 250 | set data = ? | ||
735 | 251 | where key = ?''', [serialized, key]) | ||
736 | 252 | |||
737 | 253 | # Save | ||
738 | 254 | if not self.revision: | ||
739 | 255 | return value | ||
740 | 256 | |||
741 | 257 | self.cursor.execute( | ||
742 | 258 | 'select 1 from kv_revisions where key=? and revision=?', | ||
743 | 259 | [key, self.revision]) | ||
744 | 260 | exists = self.cursor.fetchone() | ||
745 | 261 | |||
746 | 262 | if not exists: | ||
747 | 263 | self.cursor.execute( | ||
748 | 264 | '''insert into kv_revisions ( | ||
749 | 265 | revision, key, data) values (?, ?, ?)''', | ||
750 | 266 | (self.revision, key, serialized)) | ||
751 | 267 | else: | ||
752 | 268 | self.cursor.execute( | ||
753 | 269 | ''' | ||
754 | 270 | update kv_revisions | ||
755 | 271 | set data = ? | ||
756 | 272 | where key = ? | ||
757 | 273 | and revision = ?''', | ||
758 | 274 | [serialized, key, self.revision]) | ||
759 | 275 | |||
760 | 276 | return value | ||
761 | 277 | |||
762 | 278 | def delta(self, mapping, prefix): | ||
763 | 279 | """ | ||
764 | 280 | return a delta containing values that have changed. | ||
765 | 281 | """ | ||
766 | 282 | previous = self.getrange(prefix, strip=True) | ||
767 | 283 | if not previous: | ||
768 | 284 | pk = set() | ||
769 | 285 | else: | ||
770 | 286 | pk = set(previous.keys()) | ||
771 | 287 | ck = set(mapping.keys()) | ||
772 | 288 | delta = DeltaSet() | ||
773 | 289 | |||
774 | 290 | # added | ||
775 | 291 | for k in ck.difference(pk): | ||
776 | 292 | delta[k] = Delta(None, mapping[k]) | ||
777 | 293 | |||
778 | 294 | # removed | ||
779 | 295 | for k in pk.difference(ck): | ||
780 | 296 | delta[k] = Delta(previous[k], None) | ||
781 | 297 | |||
782 | 298 | # changed | ||
783 | 299 | for k in pk.intersection(ck): | ||
784 | 300 | c = mapping[k] | ||
785 | 301 | p = previous[k] | ||
786 | 302 | if c != p: | ||
787 | 303 | delta[k] = Delta(p, c) | ||
788 | 304 | |||
789 | 305 | return delta | ||
790 | 306 | |||
791 | 307 | @contextlib.contextmanager | ||
792 | 308 | def hook_scope(self, name=""): | ||
793 | 309 | """Scope all future interactions to the current hook execution | ||
794 | 310 | revision.""" | ||
795 | 311 | assert not self.revision | ||
796 | 312 | self.cursor.execute( | ||
797 | 313 | 'insert into hooks (hook, date) values (?, ?)', | ||
798 | 314 | (name or sys.argv[0], | ||
799 | 315 | datetime.datetime.utcnow().isoformat())) | ||
800 | 316 | self.revision = self.cursor.lastrowid | ||
801 | 317 | try: | ||
802 | 318 | yield self.revision | ||
803 | 319 | self.revision = None | ||
804 | 320 | except: | ||
805 | 321 | self.flush(False) | ||
806 | 322 | self.revision = None | ||
807 | 323 | raise | ||
808 | 324 | else: | ||
809 | 325 | self.flush() | ||
810 | 326 | |||
811 | 327 | def flush(self, save=True): | ||
812 | 328 | if save: | ||
813 | 329 | self.conn.commit() | ||
814 | 330 | elif self._closed: | ||
815 | 331 | return | ||
816 | 332 | else: | ||
817 | 333 | self.conn.rollback() | ||
818 | 334 | |||
819 | 335 | def _init(self): | ||
820 | 336 | self.cursor.execute(''' | ||
821 | 337 | create table if not exists kv ( | ||
822 | 338 | key text, | ||
823 | 339 | data text, | ||
824 | 340 | primary key (key) | ||
825 | 341 | )''') | ||
826 | 342 | self.cursor.execute(''' | ||
827 | 343 | create table if not exists kv_revisions ( | ||
828 | 344 | key text, | ||
829 | 345 | revision integer, | ||
830 | 346 | data text, | ||
831 | 347 | primary key (key, revision) | ||
832 | 348 | )''') | ||
833 | 349 | self.cursor.execute(''' | ||
834 | 350 | create table if not exists hooks ( | ||
835 | 351 | version integer primary key autoincrement, | ||
836 | 352 | hook text, | ||
837 | 353 | date text | ||
838 | 354 | )''') | ||
839 | 355 | self.conn.commit() | ||
840 | 356 | |||
841 | 357 | def gethistory(self, key, deserialize=False): | ||
842 | 358 | self.cursor.execute( | ||
843 | 359 | ''' | ||
844 | 360 | select kv.revision, kv.key, kv.data, h.hook, h.date | ||
845 | 361 | from kv_revisions kv, | ||
846 | 362 | hooks h | ||
847 | 363 | where kv.key=? | ||
848 | 364 | and kv.revision = h.version | ||
849 | 365 | ''', [key]) | ||
850 | 366 | if deserialize is False: | ||
851 | 367 | return self.cursor.fetchall() | ||
852 | 368 | return map(_parse_history, self.cursor.fetchall()) | ||
853 | 369 | |||
854 | 370 | def debug(self, fh=sys.stderr): | ||
855 | 371 | self.cursor.execute('select * from kv') | ||
856 | 372 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
857 | 373 | self.cursor.execute('select * from kv_revisions') | ||
858 | 374 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
859 | 375 | |||
860 | 376 | |||
861 | 377 | def _parse_history(d): | ||
862 | 378 | return (d[0], d[1], json.loads(d[2]), d[3], | ||
863 | 379 | datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f")) | ||
864 | 380 | |||
865 | 381 | |||
866 | 382 | class HookData(object): | ||
867 | 383 | """Simple integration for existing hook exec frameworks. | ||
868 | 384 | |||
869 | 385 | Records all unit information, and stores deltas for processing | ||
870 | 386 | by the hook. | ||
871 | 387 | |||
872 | 388 | Sample:: | ||
873 | 389 | |||
874 | 390 | from charmhelper.core import hookenv, unitdata | ||
875 | 391 | |||
876 | 392 | changes = unitdata.HookData() | ||
877 | 393 | db = unitdata.kv() | ||
878 | 394 | hooks = hookenv.Hooks() | ||
879 | 395 | |||
880 | 396 | @hooks.hook | ||
881 | 397 | def config_changed(): | ||
882 | 398 | # View all changes to configuration | ||
883 | 399 | for changed, (prev, cur) in changes.conf.items(): | ||
884 | 400 | print('config changed', changed, | ||
885 | 401 | 'previous value', prev, | ||
886 | 402 | 'current value', cur) | ||
887 | 403 | |||
888 | 404 | # Get some unit specific bookeeping | ||
889 | 405 | if not db.get('pkg_key'): | ||
890 | 406 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
891 | 407 | db.set('pkg_key', key) | ||
892 | 408 | |||
893 | 409 | if __name__ == '__main__': | ||
894 | 410 | with changes(): | ||
895 | 411 | hook.execute() | ||
896 | 412 | |||
897 | 413 | """ | ||
898 | 414 | def __init__(self): | ||
899 | 415 | self.kv = kv() | ||
900 | 416 | self.conf = None | ||
901 | 417 | self.rels = None | ||
902 | 418 | |||
903 | 419 | @contextlib.contextmanager | ||
904 | 420 | def __call__(self): | ||
905 | 421 | from charmhelpers.core import hookenv | ||
906 | 422 | hook_name = hookenv.hook_name() | ||
907 | 423 | |||
908 | 424 | with self.kv.hook_scope(hook_name): | ||
909 | 425 | self._record_charm_version(hookenv.charm_dir()) | ||
910 | 426 | delta_config, delta_relation = self._record_hook(hookenv) | ||
911 | 427 | yield self.kv, delta_config, delta_relation | ||
912 | 428 | |||
913 | 429 | def _record_charm_version(self, charm_dir): | ||
914 | 430 | # Record revisions.. charm revisions are meaningless | ||
915 | 431 | # to charm authors as they don't control the revision. | ||
916 | 432 | # so logic dependnent on revision is not particularly | ||
917 | 433 | # useful, however it is useful for debugging analysis. | ||
918 | 434 | charm_rev = open( | ||
919 | 435 | os.path.join(charm_dir, 'revision')).read().strip() | ||
920 | 436 | charm_rev = charm_rev or '0' | ||
921 | 437 | revs = self.kv.get('charm_revisions', []) | ||
922 | 438 | if charm_rev not in revs: | ||
923 | 439 | revs.append(charm_rev.strip() or '0') | ||
924 | 440 | self.kv.set('charm_revisions', revs) | ||
925 | 441 | |||
926 | 442 | def _record_hook(self, hookenv): | ||
927 | 443 | data = hookenv.execution_environment() | ||
928 | 444 | self.conf = conf_delta = self.kv.delta(data['conf'], 'config') | ||
929 | 445 | self.rels = rels_delta = self.kv.delta(data['rels'], 'rels') | ||
930 | 446 | self.kv.set('env', data['env']) | ||
931 | 447 | self.kv.set('unit', data['unit']) | ||
932 | 448 | self.kv.set('relid', data.get('relid')) | ||
933 | 449 | return conf_delta, rels_delta | ||
934 | 450 | |||
935 | 451 | |||
936 | 452 | class Record(dict): | ||
937 | 453 | |||
938 | 454 | __slots__ = () | ||
939 | 455 | |||
940 | 456 | def __getattr__(self, k): | ||
941 | 457 | if k in self: | ||
942 | 458 | return self[k] | ||
943 | 459 | raise AttributeError(k) | ||
944 | 460 | |||
945 | 461 | |||
946 | 462 | class DeltaSet(Record): | ||
947 | 463 | |||
948 | 464 | __slots__ = () | ||
949 | 465 | |||
950 | 466 | |||
951 | 467 | Delta = collections.namedtuple('Delta', ['previous', 'current']) | ||
952 | 468 | |||
953 | 469 | |||
954 | 470 | _KV = None | ||
955 | 471 | |||
956 | 472 | |||
957 | 473 | def kv(): | ||
958 | 474 | global _KV | ||
959 | 475 | if _KV is None: | ||
960 | 476 | _KV = Storage() | ||
961 | 477 | return _KV | ||
962 | 0 | 478 | ||
963 | === removed file 'hooks/charmhelpers/core/unitdata.py' | |||
964 | --- hooks/charmhelpers/core/unitdata.py 2015-02-17 07:10:15 +0000 | |||
965 | +++ hooks/charmhelpers/core/unitdata.py 1970-01-01 00:00:00 +0000 | |||
966 | @@ -1,477 +0,0 @@ | |||
967 | 1 | #!/usr/bin/env python | ||
968 | 2 | # -*- coding: utf-8 -*- | ||
969 | 3 | # | ||
970 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
971 | 5 | # | ||
972 | 6 | # This file is part of charm-helpers. | ||
973 | 7 | # | ||
974 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
975 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
976 | 10 | # published by the Free Software Foundation. | ||
977 | 11 | # | ||
978 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
979 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
980 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
981 | 15 | # GNU Lesser General Public License for more details. | ||
982 | 16 | # | ||
983 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
984 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
985 | 19 | # | ||
986 | 20 | # | ||
987 | 21 | # Authors: | ||
988 | 22 | # Kapil Thangavelu <kapil.foss@gmail.com> | ||
989 | 23 | # | ||
990 | 24 | """ | ||
991 | 25 | Intro | ||
992 | 26 | ----- | ||
993 | 27 | |||
994 | 28 | A simple way to store state in units. This provides a key value | ||
995 | 29 | storage with support for versioned, transactional operation, | ||
996 | 30 | and can calculate deltas from previous values to simplify unit logic | ||
997 | 31 | when processing changes. | ||
998 | 32 | |||
999 | 33 | |||
1000 | 34 | Hook Integration | ||
1001 | 35 | ---------------- | ||
1002 | 36 | |||
1003 | 37 | There are several extant frameworks for hook execution, including | ||
1004 | 38 | |||
1005 | 39 | - charmhelpers.core.hookenv.Hooks | ||
1006 | 40 | - charmhelpers.core.services.ServiceManager | ||
1007 | 41 | |||
1008 | 42 | The storage classes are framework agnostic, one simple integration is | ||
1009 | 43 | via the HookData contextmanager. It will record the current hook | ||
1010 | 44 | execution environment (including relation data, config data, etc.), | ||
1011 | 45 | setup a transaction and allow easy access to the changes from | ||
1012 | 46 | previously seen values. One consequence of the integration is the | ||
1013 | 47 | reservation of particular keys ('rels', 'unit', 'env', 'config', | ||
1014 | 48 | 'charm_revisions') for their respective values. | ||
1015 | 49 | |||
1016 | 50 | Here's a fully worked integration example using hookenv.Hooks:: | ||
1017 | 51 | |||
1018 | 52 | from charmhelper.core import hookenv, unitdata | ||
1019 | 53 | |||
1020 | 54 | hook_data = unitdata.HookData() | ||
1021 | 55 | db = unitdata.kv() | ||
1022 | 56 | hooks = hookenv.Hooks() | ||
1023 | 57 | |||
1024 | 58 | @hooks.hook | ||
1025 | 59 | def config_changed(): | ||
1026 | 60 | # Print all changes to configuration from previously seen | ||
1027 | 61 | # values. | ||
1028 | 62 | for changed, (prev, cur) in hook_data.conf.items(): | ||
1029 | 63 | print('config changed', changed, | ||
1030 | 64 | 'previous value', prev, | ||
1031 | 65 | 'current value', cur) | ||
1032 | 66 | |||
1033 | 67 | # Get some unit specific bookeeping | ||
1034 | 68 | if not db.get('pkg_key'): | ||
1035 | 69 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
1036 | 70 | db.set('pkg_key', key) | ||
1037 | 71 | |||
1038 | 72 | # Directly access all charm config as a mapping. | ||
1039 | 73 | conf = db.getrange('config', True) | ||
1040 | 74 | |||
1041 | 75 | # Directly access all relation data as a mapping | ||
1042 | 76 | rels = db.getrange('rels', True) | ||
1043 | 77 | |||
1044 | 78 | if __name__ == '__main__': | ||
1045 | 79 | with hook_data(): | ||
1046 | 80 | hook.execute() | ||
1047 | 81 | |||
1048 | 82 | |||
1049 | 83 | A more basic integration is via the hook_scope context manager which simply | ||
1050 | 84 | manages transaction scope (and records hook name, and timestamp):: | ||
1051 | 85 | |||
1052 | 86 | >>> from unitdata import kv | ||
1053 | 87 | >>> db = kv() | ||
1054 | 88 | >>> with db.hook_scope('install'): | ||
1055 | 89 | ... # do work, in transactional scope. | ||
1056 | 90 | ... db.set('x', 1) | ||
1057 | 91 | >>> db.get('x') | ||
1058 | 92 | 1 | ||
1059 | 93 | |||
1060 | 94 | |||
1061 | 95 | Usage | ||
1062 | 96 | ----- | ||
1063 | 97 | |||
1064 | 98 | Values are automatically json de/serialized to preserve basic typing | ||
1065 | 99 | and complex data struct capabilities (dicts, lists, ints, booleans, etc). | ||
1066 | 100 | |||
1067 | 101 | Individual values can be manipulated via get/set:: | ||
1068 | 102 | |||
1069 | 103 | >>> kv.set('y', True) | ||
1070 | 104 | >>> kv.get('y') | ||
1071 | 105 | True | ||
1072 | 106 | |||
1073 | 107 | # We can set complex values (dicts, lists) as a single key. | ||
1074 | 108 | >>> kv.set('config', {'a': 1, 'b': True'}) | ||
1075 | 109 | |||
1076 | 110 | # Also supports returning dictionaries as a record which | ||
1077 | 111 | # provides attribute access. | ||
1078 | 112 | >>> config = kv.get('config', record=True) | ||
1079 | 113 | >>> config.b | ||
1080 | 114 | True | ||
1081 | 115 | |||
1082 | 116 | |||
1083 | 117 | Groups of keys can be manipulated with update/getrange:: | ||
1084 | 118 | |||
1085 | 119 | >>> kv.update({'z': 1, 'y': 2}, prefix="gui.") | ||
1086 | 120 | >>> kv.getrange('gui.', strip=True) | ||
1087 | 121 | {'z': 1, 'y': 2} | ||
1088 | 122 | |||
1089 | 123 | When updating values, its very helpful to understand which values | ||
1090 | 124 | have actually changed and how have they changed. The storage | ||
1091 | 125 | provides a delta method to provide for this:: | ||
1092 | 126 | |||
1093 | 127 | >>> data = {'debug': True, 'option': 2} | ||
1094 | 128 | >>> delta = kv.delta(data, 'config.') | ||
1095 | 129 | >>> delta.debug.previous | ||
1096 | 130 | None | ||
1097 | 131 | >>> delta.debug.current | ||
1098 | 132 | True | ||
1099 | 133 | >>> delta | ||
1100 | 134 | {'debug': (None, True), 'option': (None, 2)} | ||
1101 | 135 | |||
1102 | 136 | Note the delta method does not persist the actual change, it needs to | ||
1103 | 137 | be explicitly saved via 'update' method:: | ||
1104 | 138 | |||
1105 | 139 | >>> kv.update(data, 'config.') | ||
1106 | 140 | |||
1107 | 141 | Values modified in the context of a hook scope retain historical values | ||
1108 | 142 | associated to the hookname. | ||
1109 | 143 | |||
1110 | 144 | >>> with db.hook_scope('config-changed'): | ||
1111 | 145 | ... db.set('x', 42) | ||
1112 | 146 | >>> db.gethistory('x') | ||
1113 | 147 | [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'), | ||
1114 | 148 | (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')] | ||
1115 | 149 | |||
1116 | 150 | """ | ||
1117 | 151 | |||
1118 | 152 | import collections | ||
1119 | 153 | import contextlib | ||
1120 | 154 | import datetime | ||
1121 | 155 | import json | ||
1122 | 156 | import os | ||
1123 | 157 | import pprint | ||
1124 | 158 | import sqlite3 | ||
1125 | 159 | import sys | ||
1126 | 160 | |||
1127 | 161 | __author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>' | ||
1128 | 162 | |||
1129 | 163 | |||
1130 | 164 | class Storage(object): | ||
1131 | 165 | """Simple key value database for local unit state within charms. | ||
1132 | 166 | |||
1133 | 167 | Modifications are automatically committed at hook exit. That's | ||
1134 | 168 | currently regardless of exit code. | ||
1135 | 169 | |||
1136 | 170 | To support dicts, lists, integer, floats, and booleans values | ||
1137 | 171 | are automatically json encoded/decoded. | ||
1138 | 172 | """ | ||
1139 | 173 | def __init__(self, path=None): | ||
1140 | 174 | self.db_path = path | ||
1141 | 175 | if path is None: | ||
1142 | 176 | self.db_path = os.path.join( | ||
1143 | 177 | os.environ.get('CHARM_DIR', ''), '.unit-state.db') | ||
1144 | 178 | self.conn = sqlite3.connect('%s' % self.db_path) | ||
1145 | 179 | self.cursor = self.conn.cursor() | ||
1146 | 180 | self.revision = None | ||
1147 | 181 | self._closed = False | ||
1148 | 182 | self._init() | ||
1149 | 183 | |||
1150 | 184 | def close(self): | ||
1151 | 185 | if self._closed: | ||
1152 | 186 | return | ||
1153 | 187 | self.flush(False) | ||
1154 | 188 | self.cursor.close() | ||
1155 | 189 | self.conn.close() | ||
1156 | 190 | self._closed = True | ||
1157 | 191 | |||
1158 | 192 | def _scoped_query(self, stmt, params=None): | ||
1159 | 193 | if params is None: | ||
1160 | 194 | params = [] | ||
1161 | 195 | return stmt, params | ||
1162 | 196 | |||
1163 | 197 | def get(self, key, default=None, record=False): | ||
1164 | 198 | self.cursor.execute( | ||
1165 | 199 | *self._scoped_query( | ||
1166 | 200 | 'select data from kv where key=?', [key])) | ||
1167 | 201 | result = self.cursor.fetchone() | ||
1168 | 202 | if not result: | ||
1169 | 203 | return default | ||
1170 | 204 | if record: | ||
1171 | 205 | return Record(json.loads(result[0])) | ||
1172 | 206 | return json.loads(result[0]) | ||
1173 | 207 | |||
1174 | 208 | def getrange(self, key_prefix, strip=False): | ||
1175 | 209 | stmt = "select key, data from kv where key like '%s%%'" % key_prefix | ||
1176 | 210 | self.cursor.execute(*self._scoped_query(stmt)) | ||
1177 | 211 | result = self.cursor.fetchall() | ||
1178 | 212 | |||
1179 | 213 | if not result: | ||
1180 | 214 | return None | ||
1181 | 215 | if not strip: | ||
1182 | 216 | key_prefix = '' | ||
1183 | 217 | return dict([ | ||
1184 | 218 | (k[len(key_prefix):], json.loads(v)) for k, v in result]) | ||
1185 | 219 | |||
1186 | 220 | def update(self, mapping, prefix=""): | ||
1187 | 221 | for k, v in mapping.items(): | ||
1188 | 222 | self.set("%s%s" % (prefix, k), v) | ||
1189 | 223 | |||
1190 | 224 | def unset(self, key): | ||
1191 | 225 | self.cursor.execute('delete from kv where key=?', [key]) | ||
1192 | 226 | if self.revision and self.cursor.rowcount: | ||
1193 | 227 | self.cursor.execute( | ||
1194 | 228 | 'insert into kv_revisions values (?, ?, ?)', | ||
1195 | 229 | [key, self.revision, json.dumps('DELETED')]) | ||
1196 | 230 | |||
1197 | 231 | def set(self, key, value): | ||
1198 | 232 | serialized = json.dumps(value) | ||
1199 | 233 | |||
1200 | 234 | self.cursor.execute( | ||
1201 | 235 | 'select data from kv where key=?', [key]) | ||
1202 | 236 | exists = self.cursor.fetchone() | ||
1203 | 237 | |||
1204 | 238 | # Skip mutations to the same value | ||
1205 | 239 | if exists: | ||
1206 | 240 | if exists[0] == serialized: | ||
1207 | 241 | return value | ||
1208 | 242 | |||
1209 | 243 | if not exists: | ||
1210 | 244 | self.cursor.execute( | ||
1211 | 245 | 'insert into kv (key, data) values (?, ?)', | ||
1212 | 246 | (key, serialized)) | ||
1213 | 247 | else: | ||
1214 | 248 | self.cursor.execute(''' | ||
1215 | 249 | update kv | ||
1216 | 250 | set data = ? | ||
1217 | 251 | where key = ?''', [serialized, key]) | ||
1218 | 252 | |||
1219 | 253 | # Save | ||
1220 | 254 | if not self.revision: | ||
1221 | 255 | return value | ||
1222 | 256 | |||
1223 | 257 | self.cursor.execute( | ||
1224 | 258 | 'select 1 from kv_revisions where key=? and revision=?', | ||
1225 | 259 | [key, self.revision]) | ||
1226 | 260 | exists = self.cursor.fetchone() | ||
1227 | 261 | |||
1228 | 262 | if not exists: | ||
1229 | 263 | self.cursor.execute( | ||
1230 | 264 | '''insert into kv_revisions ( | ||
1231 | 265 | revision, key, data) values (?, ?, ?)''', | ||
1232 | 266 | (self.revision, key, serialized)) | ||
1233 | 267 | else: | ||
1234 | 268 | self.cursor.execute( | ||
1235 | 269 | ''' | ||
1236 | 270 | update kv_revisions | ||
1237 | 271 | set data = ? | ||
1238 | 272 | where key = ? | ||
1239 | 273 | and revision = ?''', | ||
1240 | 274 | [serialized, key, self.revision]) | ||
1241 | 275 | |||
1242 | 276 | return value | ||
1243 | 277 | |||
1244 | 278 | def delta(self, mapping, prefix): | ||
1245 | 279 | """ | ||
1246 | 280 | return a delta containing values that have changed. | ||
1247 | 281 | """ | ||
1248 | 282 | previous = self.getrange(prefix, strip=True) | ||
1249 | 283 | if not previous: | ||
1250 | 284 | pk = set() | ||
1251 | 285 | else: | ||
1252 | 286 | pk = set(previous.keys()) | ||
1253 | 287 | ck = set(mapping.keys()) | ||
1254 | 288 | delta = DeltaSet() | ||
1255 | 289 | |||
1256 | 290 | # added | ||
1257 | 291 | for k in ck.difference(pk): | ||
1258 | 292 | delta[k] = Delta(None, mapping[k]) | ||
1259 | 293 | |||
1260 | 294 | # removed | ||
1261 | 295 | for k in pk.difference(ck): | ||
1262 | 296 | delta[k] = Delta(previous[k], None) | ||
1263 | 297 | |||
1264 | 298 | # changed | ||
1265 | 299 | for k in pk.intersection(ck): | ||
1266 | 300 | c = mapping[k] | ||
1267 | 301 | p = previous[k] | ||
1268 | 302 | if c != p: | ||
1269 | 303 | delta[k] = Delta(p, c) | ||
1270 | 304 | |||
1271 | 305 | return delta | ||
1272 | 306 | |||
1273 | 307 | @contextlib.contextmanager | ||
1274 | 308 | def hook_scope(self, name=""): | ||
1275 | 309 | """Scope all future interactions to the current hook execution | ||
1276 | 310 | revision.""" | ||
1277 | 311 | assert not self.revision | ||
1278 | 312 | self.cursor.execute( | ||
1279 | 313 | 'insert into hooks (hook, date) values (?, ?)', | ||
1280 | 314 | (name or sys.argv[0], | ||
1281 | 315 | datetime.datetime.utcnow().isoformat())) | ||
1282 | 316 | self.revision = self.cursor.lastrowid | ||
1283 | 317 | try: | ||
1284 | 318 | yield self.revision | ||
1285 | 319 | self.revision = None | ||
1286 | 320 | except: | ||
1287 | 321 | self.flush(False) | ||
1288 | 322 | self.revision = None | ||
1289 | 323 | raise | ||
1290 | 324 | else: | ||
1291 | 325 | self.flush() | ||
1292 | 326 | |||
1293 | 327 | def flush(self, save=True): | ||
1294 | 328 | if save: | ||
1295 | 329 | self.conn.commit() | ||
1296 | 330 | elif self._closed: | ||
1297 | 331 | return | ||
1298 | 332 | else: | ||
1299 | 333 | self.conn.rollback() | ||
1300 | 334 | |||
1301 | 335 | def _init(self): | ||
1302 | 336 | self.cursor.execute(''' | ||
1303 | 337 | create table if not exists kv ( | ||
1304 | 338 | key text, | ||
1305 | 339 | data text, | ||
1306 | 340 | primary key (key) | ||
1307 | 341 | )''') | ||
1308 | 342 | self.cursor.execute(''' | ||
1309 | 343 | create table if not exists kv_revisions ( | ||
1310 | 344 | key text, | ||
1311 | 345 | revision integer, | ||
1312 | 346 | data text, | ||
1313 | 347 | primary key (key, revision) | ||
1314 | 348 | )''') | ||
1315 | 349 | self.cursor.execute(''' | ||
1316 | 350 | create table if not exists hooks ( | ||
1317 | 351 | version integer primary key autoincrement, | ||
1318 | 352 | hook text, | ||
1319 | 353 | date text | ||
1320 | 354 | )''') | ||
1321 | 355 | self.conn.commit() | ||
1322 | 356 | |||
1323 | 357 | def gethistory(self, key, deserialize=False): | ||
1324 | 358 | self.cursor.execute( | ||
1325 | 359 | ''' | ||
1326 | 360 | select kv.revision, kv.key, kv.data, h.hook, h.date | ||
1327 | 361 | from kv_revisions kv, | ||
1328 | 362 | hooks h | ||
1329 | 363 | where kv.key=? | ||
1330 | 364 | and kv.revision = h.version | ||
1331 | 365 | ''', [key]) | ||
1332 | 366 | if deserialize is False: | ||
1333 | 367 | return self.cursor.fetchall() | ||
1334 | 368 | return map(_parse_history, self.cursor.fetchall()) | ||
1335 | 369 | |||
1336 | 370 | def debug(self, fh=sys.stderr): | ||
1337 | 371 | self.cursor.execute('select * from kv') | ||
1338 | 372 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
1339 | 373 | self.cursor.execute('select * from kv_revisions') | ||
1340 | 374 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
1341 | 375 | |||
1342 | 376 | |||
1343 | 377 | def _parse_history(d): | ||
1344 | 378 | return (d[0], d[1], json.loads(d[2]), d[3], | ||
1345 | 379 | datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f")) | ||
1346 | 380 | |||
1347 | 381 | |||
1348 | 382 | class HookData(object): | ||
1349 | 383 | """Simple integration for existing hook exec frameworks. | ||
1350 | 384 | |||
1351 | 385 | Records all unit information, and stores deltas for processing | ||
1352 | 386 | by the hook. | ||
1353 | 387 | |||
1354 | 388 | Sample:: | ||
1355 | 389 | |||
1356 | 390 | from charmhelper.core import hookenv, unitdata | ||
1357 | 391 | |||
1358 | 392 | changes = unitdata.HookData() | ||
1359 | 393 | db = unitdata.kv() | ||
1360 | 394 | hooks = hookenv.Hooks() | ||
1361 | 395 | |||
1362 | 396 | @hooks.hook | ||
1363 | 397 | def config_changed(): | ||
1364 | 398 | # View all changes to configuration | ||
1365 | 399 | for changed, (prev, cur) in changes.conf.items(): | ||
1366 | 400 | print('config changed', changed, | ||
1367 | 401 | 'previous value', prev, | ||
1368 | 402 | 'current value', cur) | ||
1369 | 403 | |||
1370 | 404 | # Get some unit specific bookeeping | ||
1371 | 405 | if not db.get('pkg_key'): | ||
1372 | 406 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
1373 | 407 | db.set('pkg_key', key) | ||
1374 | 408 | |||
1375 | 409 | if __name__ == '__main__': | ||
1376 | 410 | with changes(): | ||
1377 | 411 | hook.execute() | ||
1378 | 412 | |||
1379 | 413 | """ | ||
1380 | 414 | def __init__(self): | ||
1381 | 415 | self.kv = kv() | ||
1382 | 416 | self.conf = None | ||
1383 | 417 | self.rels = None | ||
1384 | 418 | |||
1385 | 419 | @contextlib.contextmanager | ||
1386 | 420 | def __call__(self): | ||
1387 | 421 | from charmhelpers.core import hookenv | ||
1388 | 422 | hook_name = hookenv.hook_name() | ||
1389 | 423 | |||
1390 | 424 | with self.kv.hook_scope(hook_name): | ||
1391 | 425 | self._record_charm_version(hookenv.charm_dir()) | ||
1392 | 426 | delta_config, delta_relation = self._record_hook(hookenv) | ||
1393 | 427 | yield self.kv, delta_config, delta_relation | ||
1394 | 428 | |||
1395 | 429 | def _record_charm_version(self, charm_dir): | ||
1396 | 430 | # Record revisions.. charm revisions are meaningless | ||
1397 | 431 | # to charm authors as they don't control the revision. | ||
1398 | 432 | # so logic dependnent on revision is not particularly | ||
1399 | 433 | # useful, however it is useful for debugging analysis. | ||
1400 | 434 | charm_rev = open( | ||
1401 | 435 | os.path.join(charm_dir, 'revision')).read().strip() | ||
1402 | 436 | charm_rev = charm_rev or '0' | ||
1403 | 437 | revs = self.kv.get('charm_revisions', []) | ||
1404 | 438 | if charm_rev not in revs: | ||
1405 | 439 | revs.append(charm_rev.strip() or '0') | ||
1406 | 440 | self.kv.set('charm_revisions', revs) | ||
1407 | 441 | |||
1408 | 442 | def _record_hook(self, hookenv): | ||
1409 | 443 | data = hookenv.execution_environment() | ||
1410 | 444 | self.conf = conf_delta = self.kv.delta(data['conf'], 'config') | ||
1411 | 445 | self.rels = rels_delta = self.kv.delta(data['rels'], 'rels') | ||
1412 | 446 | self.kv.set('env', data['env']) | ||
1413 | 447 | self.kv.set('unit', data['unit']) | ||
1414 | 448 | self.kv.set('relid', data.get('relid')) | ||
1415 | 449 | return conf_delta, rels_delta | ||
1416 | 450 | |||
1417 | 451 | |||
1418 | 452 | class Record(dict): | ||
1419 | 453 | |||
1420 | 454 | __slots__ = () | ||
1421 | 455 | |||
1422 | 456 | def __getattr__(self, k): | ||
1423 | 457 | if k in self: | ||
1424 | 458 | return self[k] | ||
1425 | 459 | raise AttributeError(k) | ||
1426 | 460 | |||
1427 | 461 | |||
1428 | 462 | class DeltaSet(Record): | ||
1429 | 463 | |||
1430 | 464 | __slots__ = () | ||
1431 | 465 | |||
1432 | 466 | |||
1433 | 467 | Delta = collections.namedtuple('Delta', ['previous', 'current']) | ||
1434 | 468 | |||
1435 | 469 | |||
1436 | 470 | _KV = None | ||
1437 | 471 | |||
1438 | 472 | |||
1439 | 473 | def kv(): | ||
1440 | 474 | global _KV | ||
1441 | 475 | if _KV is None: | ||
1442 | 476 | _KV = Storage() | ||
1443 | 477 | return _KV | ||
1444 | 478 | 0 | ||
1445 | === modified file 'hooks/neutron_api_hooks.py' | |||
1446 | --- hooks/neutron_api_hooks.py 2015-02-13 15:02:52 +0000 | |||
1447 | +++ hooks/neutron_api_hooks.py 2015-02-26 04:23:37 +0000 | |||
1448 | @@ -382,7 +382,9 @@ | |||
1449 | 382 | hostname = nrpe.get_nagios_hostname() | 382 | hostname = nrpe.get_nagios_hostname() |
1450 | 383 | current_unit = nrpe.get_nagios_unit_name() | 383 | current_unit = nrpe.get_nagios_unit_name() |
1451 | 384 | nrpe_setup = nrpe.NRPE(hostname=hostname) | 384 | nrpe_setup = nrpe.NRPE(hostname=hostname) |
1452 | 385 | nrpe.copy_nrpe_checks() | ||
1453 | 385 | nrpe.add_init_service_checks(nrpe_setup, services(), current_unit) | 386 | nrpe.add_init_service_checks(nrpe_setup, services(), current_unit) |
1454 | 387 | nrpe.add_haproxy_checks(nrpe_setup, current_unit) | ||
1455 | 386 | nrpe_setup.write() | 388 | nrpe_setup.write() |
1456 | 387 | 389 | ||
1457 | 388 | 390 |
charm_lint_check #2220 neutron-api-next for brad-marshall mp250705
LINT OK: passed
Build: http:// 10.245. 162.77: 8080/job/ charm_lint_ check/2220/