Merge lp:~1chb1n/charms/trusty/nova-cell/next-amulet-debug-and-makefile into lp:~openstack-charmers/charms/trusty/nova-cell/next

Proposed by Ryan Beisner
Status: Merged
Merged at revision: 65
Proposed branch: lp:~1chb1n/charms/trusty/nova-cell/next-amulet-debug-and-makefile
Merge into: lp:~openstack-charmers/charms/trusty/nova-cell/next
Diff against target: 2271 lines (+1460/-208)
20 files modified
hooks/charmhelpers/contrib/network/ip.py (+84/-1)
hooks/charmhelpers/contrib/openstack/amulet/deployment.py (+34/-5)
hooks/charmhelpers/contrib/openstack/context.py (+289/-15)
hooks/charmhelpers/contrib/openstack/files/__init__.py (+18/-0)
hooks/charmhelpers/contrib/openstack/ip.py (+37/-0)
hooks/charmhelpers/contrib/openstack/neutron.py (+83/-0)
hooks/charmhelpers/contrib/openstack/utils.py (+142/-141)
hooks/charmhelpers/contrib/python/packages.py (+2/-2)
hooks/charmhelpers/core/fstab.py (+4/-4)
hooks/charmhelpers/core/hookenv.py (+40/-1)
hooks/charmhelpers/core/host.py (+10/-6)
hooks/charmhelpers/core/services/helpers.py (+12/-4)
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)
tests/charmhelpers/contrib/amulet/utils.py (+125/-3)
tests/charmhelpers/contrib/openstack/amulet/deployment.py (+34/-5)
To merge this branch: bzr merge lp:~1chb1n/charms/trusty/nova-cell/next-amulet-debug-and-makefile
Reviewer Review Type Date Requested Status
OpenStack Charmers Pending
Review via email: mp+256591@code.launchpad.net

Description of the change

auto sync charmhelpers

To post a comment you must log in.
Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_lint_check #3526 nova-cell-next for 1chb1n mp256591
    LINT OK: passed

Build: http://10.245.162.77:8080/job/charm_lint_check/3526/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_unit_test #3314 nova-cell-next for 1chb1n mp256591
    UNIT OK: passed

Build: http://10.245.162.77:8080/job/charm_unit_test/3314/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_amulet_test #3281 nova-cell-next for 1chb1n mp256591
    AMULET FAIL: amulet-test failed

AMULET Results (max last 2 lines):
make: *** [test] Error 1
ERROR:root:Make target returned non-zero.

Full amulet test output: http://paste.ubuntu.com/10835609/
Build: http://10.245.162.77:8080/job/charm_amulet_test/3281/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_lint_check #3550 nova-cell-next for 1chb1n mp256591
    LINT OK: passed

Build: http://10.245.162.77:8080/job/charm_lint_check/3550/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_lint_check #3560 nova-cell-next for 1chb1n mp256591
    LINT OK: passed

Build: http://10.245.162.77:8080/job/charm_lint_check/3560/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_unit_test #3348 nova-cell-next for 1chb1n mp256591
    UNIT OK: passed

Build: http://10.245.162.77:8080/job/charm_unit_test/3348/

Revision history for this message
uosci-testing-bot (uosci-testing-bot) wrote :

charm_amulet_test #3317 nova-cell-next for 1chb1n mp256591
    AMULET FAIL: amulet-test failed

AMULET Results (max last 2 lines):
make: *** [test] Error 1
ERROR:root:Make target returned non-zero.

Full amulet test output: http://paste.ubuntu.com/10838482/
Build: http://10.245.162.77:8080/job/charm_amulet_test/3317/

Revision history for this message
Ryan Beisner (1chb1n) wrote :

The amulet fail is actually due to missing / no tests in this charm.

00:01:08.349 juju-test CRITICAL: No tests were found

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'hooks/charmhelpers/contrib/network/ip.py'
--- hooks/charmhelpers/contrib/network/ip.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/contrib/network/ip.py 2015-04-16 21:56:47 +0000
@@ -17,13 +17,16 @@
17import glob17import glob
18import re18import re
19import subprocess19import subprocess
20import six
21import socket
2022
21from functools import partial23from functools import partial
2224
23from charmhelpers.core.hookenv import unit_get25from charmhelpers.core.hookenv import unit_get
24from charmhelpers.fetch import apt_install26from charmhelpers.fetch import apt_install
25from charmhelpers.core.hookenv import (27from charmhelpers.core.hookenv import (
26 log28 log,
29 WARNING,
27)30)
2831
29try:32try:
@@ -365,3 +368,83 @@
365 return True368 return True
366369
367 return False370 return False
371
372
373def is_ip(address):
374 """
375 Returns True if address is a valid IP address.
376 """
377 try:
378 # Test to see if already an IPv4 address
379 socket.inet_aton(address)
380 return True
381 except socket.error:
382 return False
383
384
385def ns_query(address):
386 try:
387 import dns.resolver
388 except ImportError:
389 apt_install('python-dnspython')
390 import dns.resolver
391
392 if isinstance(address, dns.name.Name):
393 rtype = 'PTR'
394 elif isinstance(address, six.string_types):
395 rtype = 'A'
396 else:
397 return None
398
399 answers = dns.resolver.query(address, rtype)
400 if answers:
401 return str(answers[0])
402 return None
403
404
405def get_host_ip(hostname, fallback=None):
406 """
407 Resolves the IP for a given hostname, or returns
408 the input if it is already an IP.
409 """
410 if is_ip(hostname):
411 return hostname
412
413 ip_addr = ns_query(hostname)
414 if not ip_addr:
415 try:
416 ip_addr = socket.gethostbyname(hostname)
417 except:
418 log("Failed to resolve hostname '%s'" % (hostname),
419 level=WARNING)
420 return fallback
421 return ip_addr
422
423
424def get_hostname(address, fqdn=True):
425 """
426 Resolves hostname for given IP, or returns the input
427 if it is already a hostname.
428 """
429 if is_ip(address):
430 try:
431 import dns.reversename
432 except ImportError:
433 apt_install("python-dnspython")
434 import dns.reversename
435
436 rev = dns.reversename.from_address(address)
437 result = ns_query(rev)
438 if not result:
439 return None
440 else:
441 result = address
442
443 if fqdn:
444 # strip trailing .
445 if result.endswith('.'):
446 return result[:-1]
447 else:
448 return result
449 else:
450 return result.split('.')[0]
368451
=== modified file 'hooks/charmhelpers/contrib/openstack/amulet/deployment.py'
--- hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/contrib/openstack/amulet/deployment.py 2015-04-16 21:56:47 +0000
@@ -15,6 +15,7 @@
15# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.15# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
1616
17import six17import six
18from collections import OrderedDict
18from charmhelpers.contrib.amulet.deployment import (19from charmhelpers.contrib.amulet.deployment import (
19 AmuletDeployment20 AmuletDeployment
20)21)
@@ -43,7 +44,7 @@
43 Determine if the local branch being tested is derived from its44 Determine if the local branch being tested is derived from its
44 stable or next (dev) branch, and based on this, use the corresonding45 stable or next (dev) branch, and based on this, use the corresonding
45 stable or next branches for the other_services."""46 stable or next branches for the other_services."""
46 base_charms = ['mysql', 'mongodb', 'rabbitmq-server']47 base_charms = ['mysql', 'mongodb']
4748
48 if self.stable:49 if self.stable:
49 for svc in other_services:50 for svc in other_services:
@@ -71,16 +72,19 @@
71 services.append(this_service)72 services.append(this_service)
72 use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph',73 use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph',
73 'ceph-osd', 'ceph-radosgw']74 'ceph-osd', 'ceph-radosgw']
75 # Openstack subordinate charms do not expose an origin option as that
76 # is controlled by the principle
77 ignore = ['neutron-openvswitch']
7478
75 if self.openstack:79 if self.openstack:
76 for svc in services:80 for svc in services:
77 if svc['name'] not in use_source:81 if svc['name'] not in use_source + ignore:
78 config = {'openstack-origin': self.openstack}82 config = {'openstack-origin': self.openstack}
79 self.d.configure(svc['name'], config)83 self.d.configure(svc['name'], config)
8084
81 if self.source:85 if self.source:
82 for svc in services:86 for svc in services:
83 if svc['name'] in use_source:87 if svc['name'] in use_source and svc['name'] not in ignore:
84 config = {'source': self.source}88 config = {'source': self.source}
85 self.d.configure(svc['name'], config)89 self.d.configure(svc['name'], config)
8690
@@ -97,12 +101,37 @@
97 """101 """
98 (self.precise_essex, self.precise_folsom, self.precise_grizzly,102 (self.precise_essex, self.precise_folsom, self.precise_grizzly,
99 self.precise_havana, self.precise_icehouse,103 self.precise_havana, self.precise_icehouse,
100 self.trusty_icehouse) = range(6)104 self.trusty_icehouse, self.trusty_juno, self.trusty_kilo,
105 self.utopic_juno, self.vivid_kilo) = range(10)
101 releases = {106 releases = {
102 ('precise', None): self.precise_essex,107 ('precise', None): self.precise_essex,
103 ('precise', 'cloud:precise-folsom'): self.precise_folsom,108 ('precise', 'cloud:precise-folsom'): self.precise_folsom,
104 ('precise', 'cloud:precise-grizzly'): self.precise_grizzly,109 ('precise', 'cloud:precise-grizzly'): self.precise_grizzly,
105 ('precise', 'cloud:precise-havana'): self.precise_havana,110 ('precise', 'cloud:precise-havana'): self.precise_havana,
106 ('precise', 'cloud:precise-icehouse'): self.precise_icehouse,111 ('precise', 'cloud:precise-icehouse'): self.precise_icehouse,
107 ('trusty', None): self.trusty_icehouse}112 ('trusty', None): self.trusty_icehouse,
113 ('trusty', 'cloud:trusty-juno'): self.trusty_juno,
114 ('trusty', 'cloud:trusty-kilo'): self.trusty_kilo,
115 ('utopic', None): self.utopic_juno,
116 ('vivid', None): self.vivid_kilo}
108 return releases[(self.series, self.openstack)]117 return releases[(self.series, self.openstack)]
118
119 def _get_openstack_release_string(self):
120 """Get openstack release string.
121
122 Return a string representing the openstack release.
123 """
124 releases = OrderedDict([
125 ('precise', 'essex'),
126 ('quantal', 'folsom'),
127 ('raring', 'grizzly'),
128 ('saucy', 'havana'),
129 ('trusty', 'icehouse'),
130 ('utopic', 'juno'),
131 ('vivid', 'kilo'),
132 ])
133 if self.openstack:
134 os_origin = self.openstack.split(':')[1]
135 return os_origin.split('%s-' % self.series)[1].split('/')[0]
136 else:
137 return releases[self.series]
109138
=== modified file 'hooks/charmhelpers/contrib/openstack/context.py'
--- hooks/charmhelpers/contrib/openstack/context.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/contrib/openstack/context.py 2015-04-16 21:56:47 +0000
@@ -16,11 +16,13 @@
1616
17import json17import json
18import os18import os
19import re
19import time20import time
20from base64 import b64decode21from base64 import b64decode
21from subprocess import check_call22from subprocess import check_call
2223
23import six24import six
25import yaml
2426
25from charmhelpers.fetch import (27from charmhelpers.fetch import (
26 apt_install,28 apt_install,
@@ -45,8 +47,11 @@
45)47)
4648
47from charmhelpers.core.sysctl import create as sysctl_create49from charmhelpers.core.sysctl import create as sysctl_create
50from charmhelpers.core.strutils import bool_from_string
4851
49from charmhelpers.core.host import (52from charmhelpers.core.host import (
53 list_nics,
54 get_nic_hwaddr,
50 mkdir,55 mkdir,
51 write_file,56 write_file,
52)57)
@@ -63,16 +68,22 @@
63)68)
64from charmhelpers.contrib.openstack.neutron import (69from charmhelpers.contrib.openstack.neutron import (
65 neutron_plugin_attribute,70 neutron_plugin_attribute,
71 parse_data_port_mappings,
72)
73from charmhelpers.contrib.openstack.ip import (
74 resolve_address,
75 INTERNAL,
66)76)
67from charmhelpers.contrib.network.ip import (77from charmhelpers.contrib.network.ip import (
68 get_address_in_network,78 get_address_in_network,
79 get_ipv4_addr,
69 get_ipv6_addr,80 get_ipv6_addr,
70 get_netmask_for_address,81 get_netmask_for_address,
71 format_ipv6_addr,82 format_ipv6_addr,
72 is_address_in_network,83 is_address_in_network,
84 is_bridge_member,
73)85)
74from charmhelpers.contrib.openstack.utils import get_host_ip86from charmhelpers.contrib.openstack.utils import get_host_ip
75
76CA_CERT_PATH = '/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt'87CA_CERT_PATH = '/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt'
77ADDRESS_TYPES = ['admin', 'internal', 'public']88ADDRESS_TYPES = ['admin', 'internal', 'public']
7889
@@ -104,9 +115,41 @@
104def config_flags_parser(config_flags):115def config_flags_parser(config_flags):
105 """Parses config flags string into dict.116 """Parses config flags string into dict.
106117
118 This parsing method supports a few different formats for the config
119 flag values to be parsed:
120
121 1. A string in the simple format of key=value pairs, with the possibility
122 of specifying multiple key value pairs within the same string. For
123 example, a string in the format of 'key1=value1, key2=value2' will
124 return a dict of:
125 {'key1': 'value1',
126 'key2': 'value2'}.
127
128 2. A string in the above format, but supporting a comma-delimited list
129 of values for the same key. For example, a string in the format of
130 'key1=value1, key2=value3,value4,value5' will return a dict of:
131 {'key1', 'value1',
132 'key2', 'value2,value3,value4'}
133
134 3. A string containing a colon character (:) prior to an equal
135 character (=) will be treated as yaml and parsed as such. This can be
136 used to specify more complex key value pairs. For example,
137 a string in the format of 'key1: subkey1=value1, subkey2=value2' will
138 return a dict of:
139 {'key1', 'subkey1=value1, subkey2=value2'}
140
107 The provided config_flags string may be a list of comma-separated values141 The provided config_flags string may be a list of comma-separated values
108 which themselves may be comma-separated list of values.142 which themselves may be comma-separated list of values.
109 """143 """
144 # If we find a colon before an equals sign then treat it as yaml.
145 # Note: limit it to finding the colon first since this indicates assignment
146 # for inline yaml.
147 colon = config_flags.find(':')
148 equals = config_flags.find('=')
149 if colon > 0:
150 if colon < equals or equals < 0:
151 return yaml.safe_load(config_flags)
152
110 if config_flags.find('==') >= 0:153 if config_flags.find('==') >= 0:
111 log("config_flags is not in expected format (key=value)", level=ERROR)154 log("config_flags is not in expected format (key=value)", level=ERROR)
112 raise OSContextError155 raise OSContextError
@@ -191,7 +234,7 @@
191 unit=local_unit())234 unit=local_unit())
192 if set_hostname != access_hostname:235 if set_hostname != access_hostname:
193 relation_set(relation_settings={hostname_key: access_hostname})236 relation_set(relation_settings={hostname_key: access_hostname})
194 return ctxt # Defer any further hook execution for now....237 return None # Defer any further hook execution for now....
195238
196 password_setting = 'password'239 password_setting = 'password'
197 if self.relation_prefix:240 if self.relation_prefix:
@@ -277,12 +320,29 @@
277320
278321
279class IdentityServiceContext(OSContextGenerator):322class IdentityServiceContext(OSContextGenerator):
280 interfaces = ['identity-service']323
324 def __init__(self, service=None, service_user=None, rel_name='identity-service'):
325 self.service = service
326 self.service_user = service_user
327 self.rel_name = rel_name
328 self.interfaces = [self.rel_name]
281329
282 def __call__(self):330 def __call__(self):
283 log('Generating template context for identity-service', level=DEBUG)331 log('Generating template context for ' + self.rel_name, level=DEBUG)
284 ctxt = {}332 ctxt = {}
285 for rid in relation_ids('identity-service'):333
334 if self.service and self.service_user:
335 # This is required for pki token signing if we don't want /tmp to
336 # be used.
337 cachedir = '/var/cache/%s' % (self.service)
338 if not os.path.isdir(cachedir):
339 log("Creating service cache dir %s" % (cachedir), level=DEBUG)
340 mkdir(path=cachedir, owner=self.service_user,
341 group=self.service_user, perms=0o700)
342
343 ctxt['signing_dir'] = cachedir
344
345 for rid in relation_ids(self.rel_name):
286 for unit in related_units(rid):346 for unit in related_units(rid):
287 rdata = relation_get(rid=rid, unit=unit)347 rdata = relation_get(rid=rid, unit=unit)
288 serv_host = rdata.get('service_host')348 serv_host = rdata.get('service_host')
@@ -291,15 +351,16 @@
291 auth_host = format_ipv6_addr(auth_host) or auth_host351 auth_host = format_ipv6_addr(auth_host) or auth_host
292 svc_protocol = rdata.get('service_protocol') or 'http'352 svc_protocol = rdata.get('service_protocol') or 'http'
293 auth_protocol = rdata.get('auth_protocol') or 'http'353 auth_protocol = rdata.get('auth_protocol') or 'http'
294 ctxt = {'service_port': rdata.get('service_port'),354 ctxt.update({'service_port': rdata.get('service_port'),
295 'service_host': serv_host,355 'service_host': serv_host,
296 'auth_host': auth_host,356 'auth_host': auth_host,
297 'auth_port': rdata.get('auth_port'),357 'auth_port': rdata.get('auth_port'),
298 'admin_tenant_name': rdata.get('service_tenant'),358 'admin_tenant_name': rdata.get('service_tenant'),
299 'admin_user': rdata.get('service_username'),359 'admin_user': rdata.get('service_username'),
300 'admin_password': rdata.get('service_password'),360 'admin_password': rdata.get('service_password'),
301 'service_protocol': svc_protocol,361 'service_protocol': svc_protocol,
302 'auth_protocol': auth_protocol}362 'auth_protocol': auth_protocol})
363
303 if context_complete(ctxt):364 if context_complete(ctxt):
304 # NOTE(jamespage) this is required for >= icehouse365 # NOTE(jamespage) this is required for >= icehouse
305 # so a missing value just indicates keystone needs366 # so a missing value just indicates keystone needs
@@ -398,6 +459,11 @@
398459
399 ctxt['rabbitmq_hosts'] = ','.join(sorted(rabbitmq_hosts))460 ctxt['rabbitmq_hosts'] = ','.join(sorted(rabbitmq_hosts))
400461
462 oslo_messaging_flags = conf.get('oslo-messaging-flags', None)
463 if oslo_messaging_flags:
464 ctxt['oslo_messaging_flags'] = config_flags_parser(
465 oslo_messaging_flags)
466
401 if not context_complete(ctxt):467 if not context_complete(ctxt):
402 return {}468 return {}
403469
@@ -677,7 +743,14 @@
677 'endpoints': [],743 'endpoints': [],
678 'ext_ports': []}744 'ext_ports': []}
679745
680 for cn in self.canonical_names():746 cns = self.canonical_names()
747 if cns:
748 for cn in cns:
749 self.configure_cert(cn)
750 else:
751 # Expect cert/key provided in config (currently assumed that ca
752 # uses ip for cn)
753 cn = resolve_address(endpoint_type=INTERNAL)
681 self.configure_cert(cn)754 self.configure_cert(cn)
682755
683 addresses = self.get_network_addresses()756 addresses = self.get_network_addresses()
@@ -740,6 +813,19 @@
740813
741 return ovs_ctxt814 return ovs_ctxt
742815
816 def nuage_ctxt(self):
817 driver = neutron_plugin_attribute(self.plugin, 'driver',
818 self.network_manager)
819 config = neutron_plugin_attribute(self.plugin, 'config',
820 self.network_manager)
821 nuage_ctxt = {'core_plugin': driver,
822 'neutron_plugin': 'vsp',
823 'neutron_security_groups': self.neutron_security_groups,
824 'local_ip': unit_private_ip(),
825 'config': config}
826
827 return nuage_ctxt
828
743 def nvp_ctxt(self):829 def nvp_ctxt(self):
744 driver = neutron_plugin_attribute(self.plugin, 'driver',830 driver = neutron_plugin_attribute(self.plugin, 'driver',
745 self.network_manager)831 self.network_manager)
@@ -823,6 +909,8 @@
823 ctxt.update(self.n1kv_ctxt())909 ctxt.update(self.n1kv_ctxt())
824 elif self.plugin == 'Calico':910 elif self.plugin == 'Calico':
825 ctxt.update(self.calico_ctxt())911 ctxt.update(self.calico_ctxt())
912 elif self.plugin == 'vsp':
913 ctxt.update(self.nuage_ctxt())
826914
827 alchemy_flags = config('neutron-alchemy-flags')915 alchemy_flags = config('neutron-alchemy-flags')
828 if alchemy_flags:916 if alchemy_flags:
@@ -833,6 +921,48 @@
833 return ctxt921 return ctxt
834922
835923
924class NeutronPortContext(OSContextGenerator):
925 NIC_PREFIXES = ['eth', 'bond']
926
927 def resolve_ports(self, ports):
928 """Resolve NICs not yet bound to bridge(s)
929
930 If hwaddress provided then returns resolved hwaddress otherwise NIC.
931 """
932 if not ports:
933 return None
934
935 hwaddr_to_nic = {}
936 hwaddr_to_ip = {}
937 for nic in list_nics(self.NIC_PREFIXES):
938 hwaddr = get_nic_hwaddr(nic)
939 hwaddr_to_nic[hwaddr] = nic
940 addresses = get_ipv4_addr(nic, fatal=False)
941 addresses += get_ipv6_addr(iface=nic, fatal=False)
942 hwaddr_to_ip[hwaddr] = addresses
943
944 resolved = []
945 mac_regex = re.compile(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', re.I)
946 for entry in ports:
947 if re.match(mac_regex, entry):
948 # NIC is in known NICs and does NOT hace an IP address
949 if entry in hwaddr_to_nic and not hwaddr_to_ip[entry]:
950 # If the nic is part of a bridge then don't use it
951 if is_bridge_member(hwaddr_to_nic[entry]):
952 continue
953
954 # Entry is a MAC address for a valid interface that doesn't
955 # have an IP address assigned yet.
956 resolved.append(hwaddr_to_nic[entry])
957 else:
958 # If the passed entry is not a MAC address, assume it's a valid
959 # interface, and that the user put it there on purpose (we can
960 # trust it to be the real external network).
961 resolved.append(entry)
962
963 return resolved
964
965
836class OSConfigFlagContext(OSContextGenerator):966class OSConfigFlagContext(OSContextGenerator):
837 """Provides support for user-defined config flags.967 """Provides support for user-defined config flags.
838968
@@ -1021,6 +1151,8 @@
1021 for unit in related_units(rid):1151 for unit in related_units(rid):
1022 ctxt['zmq_nonce'] = relation_get('nonce', unit, rid)1152 ctxt['zmq_nonce'] = relation_get('nonce', unit, rid)
1023 ctxt['zmq_host'] = relation_get('host', unit, rid)1153 ctxt['zmq_host'] = relation_get('host', unit, rid)
1154 ctxt['zmq_redis_address'] = relation_get(
1155 'zmq_redis_address', unit, rid)
10241156
1025 return ctxt1157 return ctxt
10261158
@@ -1052,3 +1184,145 @@
1052 sysctl_create(sysctl_dict,1184 sysctl_create(sysctl_dict,
1053 '/etc/sysctl.d/50-{0}.conf'.format(charm_name()))1185 '/etc/sysctl.d/50-{0}.conf'.format(charm_name()))
1054 return {'sysctl': sysctl_dict}1186 return {'sysctl': sysctl_dict}
1187
1188
1189class NeutronAPIContext(OSContextGenerator):
1190 '''
1191 Inspects current neutron-plugin-api relation for neutron settings. Return
1192 defaults if it is not present.
1193 '''
1194 interfaces = ['neutron-plugin-api']
1195
1196 def __call__(self):
1197 self.neutron_defaults = {
1198 'l2_population': {
1199 'rel_key': 'l2-population',
1200 'default': False,
1201 },
1202 'overlay_network_type': {
1203 'rel_key': 'overlay-network-type',
1204 'default': 'gre',
1205 },
1206 'neutron_security_groups': {
1207 'rel_key': 'neutron-security-groups',
1208 'default': False,
1209 },
1210 'network_device_mtu': {
1211 'rel_key': 'network-device-mtu',
1212 'default': None,
1213 },
1214 'enable_dvr': {
1215 'rel_key': 'enable-dvr',
1216 'default': False,
1217 },
1218 'enable_l3ha': {
1219 'rel_key': 'enable-l3ha',
1220 'default': False,
1221 },
1222 }
1223 ctxt = self.get_neutron_options({})
1224 for rid in relation_ids('neutron-plugin-api'):
1225 for unit in related_units(rid):
1226 rdata = relation_get(rid=rid, unit=unit)
1227 if 'l2-population' in rdata:
1228 ctxt.update(self.get_neutron_options(rdata))
1229
1230 return ctxt
1231
1232 def get_neutron_options(self, rdata):
1233 settings = {}
1234 for nkey in self.neutron_defaults.keys():
1235 defv = self.neutron_defaults[nkey]['default']
1236 rkey = self.neutron_defaults[nkey]['rel_key']
1237 if rkey in rdata.keys():
1238 if type(defv) is bool:
1239 settings[nkey] = bool_from_string(rdata[rkey])
1240 else:
1241 settings[nkey] = rdata[rkey]
1242 else:
1243 settings[nkey] = defv
1244 return settings
1245
1246
1247class ExternalPortContext(NeutronPortContext):
1248
1249 def __call__(self):
1250 ctxt = {}
1251 ports = config('ext-port')
1252 if ports:
1253 ports = [p.strip() for p in ports.split()]
1254 ports = self.resolve_ports(ports)
1255 if ports:
1256 ctxt = {"ext_port": ports[0]}
1257 napi_settings = NeutronAPIContext()()
1258 mtu = napi_settings.get('network_device_mtu')
1259 if mtu:
1260 ctxt['ext_port_mtu'] = mtu
1261
1262 return ctxt
1263
1264
1265class DataPortContext(NeutronPortContext):
1266
1267 def __call__(self):
1268 ports = config('data-port')
1269 if ports:
1270 portmap = parse_data_port_mappings(ports)
1271 ports = portmap.values()
1272 resolved = self.resolve_ports(ports)
1273 normalized = {get_nic_hwaddr(port): port for port in resolved
1274 if port not in ports}
1275 normalized.update({port: port for port in resolved
1276 if port in ports})
1277 if resolved:
1278 return {bridge: normalized[port] for bridge, port in
1279 six.iteritems(portmap) if port in normalized.keys()}
1280
1281 return None
1282
1283
1284class PhyNICMTUContext(DataPortContext):
1285
1286 def __call__(self):
1287 ctxt = {}
1288 mappings = super(PhyNICMTUContext, self).__call__()
1289 if mappings and mappings.values():
1290 ports = mappings.values()
1291 napi_settings = NeutronAPIContext()()
1292 mtu = napi_settings.get('network_device_mtu')
1293 if mtu:
1294 ctxt["devs"] = '\\n'.join(ports)
1295 ctxt['mtu'] = mtu
1296
1297 return ctxt
1298
1299
1300class NetworkServiceContext(OSContextGenerator):
1301
1302 def __init__(self, rel_name='quantum-network-service'):
1303 self.rel_name = rel_name
1304 self.interfaces = [rel_name]
1305
1306 def __call__(self):
1307 for rid in relation_ids(self.rel_name):
1308 for unit in related_units(rid):
1309 rdata = relation_get(rid=rid, unit=unit)
1310 ctxt = {
1311 'keystone_host': rdata.get('keystone_host'),
1312 'service_port': rdata.get('service_port'),
1313 'auth_port': rdata.get('auth_port'),
1314 'service_tenant': rdata.get('service_tenant'),
1315 'service_username': rdata.get('service_username'),
1316 'service_password': rdata.get('service_password'),
1317 'quantum_host': rdata.get('quantum_host'),
1318 'quantum_port': rdata.get('quantum_port'),
1319 'quantum_url': rdata.get('quantum_url'),
1320 'region': rdata.get('region'),
1321 'service_protocol':
1322 rdata.get('service_protocol') or 'http',
1323 'auth_protocol':
1324 rdata.get('auth_protocol') or 'http',
1325 }
1326 if context_complete(ctxt):
1327 return ctxt
1328 return {}
10551329
=== added directory 'hooks/charmhelpers/contrib/openstack/files'
=== added file 'hooks/charmhelpers/contrib/openstack/files/__init__.py'
--- hooks/charmhelpers/contrib/openstack/files/__init__.py 1970-01-01 00:00:00 +0000
+++ hooks/charmhelpers/contrib/openstack/files/__init__.py 2015-04-16 21:56:47 +0000
@@ -0,0 +1,18 @@
1# Copyright 2014-2015 Canonical Limited.
2#
3# This file is part of charm-helpers.
4#
5# charm-helpers is free software: you can redistribute it and/or modify
6# it under the terms of the GNU Lesser General Public License version 3 as
7# published by the Free Software Foundation.
8#
9# charm-helpers is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Lesser General Public License for more details.
13#
14# You should have received a copy of the GNU Lesser General Public License
15# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
16
17# dummy __init__.py to fool syncer into thinking this is a syncable python
18# module
019
=== modified file 'hooks/charmhelpers/contrib/openstack/ip.py'
--- hooks/charmhelpers/contrib/openstack/ip.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/contrib/openstack/ip.py 2015-04-16 21:56:47 +0000
@@ -26,6 +26,8 @@
26)26)
27from charmhelpers.contrib.hahelpers.cluster import is_clustered27from charmhelpers.contrib.hahelpers.cluster import is_clustered
2828
29from functools import partial
30
29PUBLIC = 'public'31PUBLIC = 'public'
30INTERNAL = 'int'32INTERNAL = 'int'
31ADMIN = 'admin'33ADMIN = 'admin'
@@ -107,3 +109,38 @@
107 "clustered=%s)" % (net_type, clustered))109 "clustered=%s)" % (net_type, clustered))
108110
109 return resolved_address111 return resolved_address
112
113
114def endpoint_url(configs, url_template, port, endpoint_type=PUBLIC,
115 override=None):
116 """Returns the correct endpoint URL to advertise to Keystone.
117
118 This method provides the correct endpoint URL which should be advertised to
119 the keystone charm for endpoint creation. This method allows for the url to
120 be overridden to force a keystone endpoint to have specific URL for any of
121 the defined scopes (admin, internal, public).
122
123 :param configs: OSTemplateRenderer config templating object to inspect
124 for a complete https context.
125 :param url_template: str format string for creating the url template. Only
126 two values will be passed - the scheme+hostname
127 returned by the canonical_url and the port.
128 :param endpoint_type: str endpoint type to resolve.
129 :param override: str the name of the config option which overrides the
130 endpoint URL defined by the charm itself. None will
131 disable any overrides (default).
132 """
133 if override:
134 # Return any user-defined overrides for the keystone endpoint URL.
135 user_value = config(override)
136 if user_value:
137 return user_value.strip()
138
139 return url_template % (canonical_url(configs, endpoint_type), port)
140
141
142public_endpoint = partial(endpoint_url, endpoint_type=PUBLIC)
143
144internal_endpoint = partial(endpoint_url, endpoint_type=INTERNAL)
145
146admin_endpoint = partial(endpoint_url, endpoint_type=ADMIN)
110147
=== modified file 'hooks/charmhelpers/contrib/openstack/neutron.py'
--- hooks/charmhelpers/contrib/openstack/neutron.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/contrib/openstack/neutron.py 2015-04-16 21:56:47 +0000
@@ -16,6 +16,7 @@
1616
17# Various utilies for dealing with Neutron and the renaming from Quantum.17# Various utilies for dealing with Neutron and the renaming from Quantum.
1818
19import six
19from subprocess import check_output20from subprocess import check_output
2021
21from charmhelpers.core.hookenv import (22from charmhelpers.core.hookenv import (
@@ -179,6 +180,19 @@
179 'nova-api-metadata']],180 'nova-api-metadata']],
180 'server_packages': ['neutron-server', 'calico-control'],181 'server_packages': ['neutron-server', 'calico-control'],
181 'server_services': ['neutron-server']182 'server_services': ['neutron-server']
183 },
184 'vsp': {
185 'config': '/etc/neutron/plugins/nuage/nuage_plugin.ini',
186 'driver': 'neutron.plugins.nuage.plugin.NuagePlugin',
187 'contexts': [
188 context.SharedDBContext(user=config('neutron-database-user'),
189 database=config('neutron-database'),
190 relation_prefix='neutron',
191 ssl_dir=NEUTRON_CONF_DIR)],
192 'services': [],
193 'packages': [],
194 'server_packages': ['neutron-server', 'neutron-plugin-nuage'],
195 'server_services': ['neutron-server']
182 }196 }
183 }197 }
184 if release >= 'icehouse':198 if release >= 'icehouse':
@@ -237,3 +251,72 @@
237 else:251 else:
238 # ensure accurate naming for all releases post-H252 # ensure accurate naming for all releases post-H
239 return 'neutron'253 return 'neutron'
254
255
256def parse_mappings(mappings):
257 parsed = {}
258 if mappings:
259 mappings = mappings.split(' ')
260 for m in mappings:
261 p = m.partition(':')
262 if p[1] == ':':
263 parsed[p[0].strip()] = p[2].strip()
264
265 return parsed
266
267
268def parse_bridge_mappings(mappings):
269 """Parse bridge mappings.
270
271 Mappings must be a space-delimited list of provider:bridge mappings.
272
273 Returns dict of the form {provider:bridge}.
274 """
275 return parse_mappings(mappings)
276
277
278def parse_data_port_mappings(mappings, default_bridge='br-data'):
279 """Parse data port mappings.
280
281 Mappings must be a space-delimited list of bridge:port mappings.
282
283 Returns dict of the form {bridge:port}.
284 """
285 _mappings = parse_mappings(mappings)
286 if not _mappings:
287 if not mappings:
288 return {}
289
290 # For backwards-compatibility we need to support port-only provided in
291 # config.
292 _mappings = {default_bridge: mappings.split(' ')[0]}
293
294 bridges = _mappings.keys()
295 ports = _mappings.values()
296 if len(set(bridges)) != len(bridges):
297 raise Exception("It is not allowed to have more than one port "
298 "configured on the same bridge")
299
300 if len(set(ports)) != len(ports):
301 raise Exception("It is not allowed to have the same port configured "
302 "on more than one bridge")
303
304 return _mappings
305
306
307def parse_vlan_range_mappings(mappings):
308 """Parse vlan range mappings.
309
310 Mappings must be a space-delimited list of provider:start:end mappings.
311
312 Returns dict of the form {provider: (start, end)}.
313 """
314 _mappings = parse_mappings(mappings)
315 if not _mappings:
316 return {}
317
318 mappings = {}
319 for p, r in six.iteritems(_mappings):
320 mappings[p] = tuple(r.split(':'))
321
322 return mappings
240323
=== modified file 'hooks/charmhelpers/contrib/openstack/utils.py'
--- hooks/charmhelpers/contrib/openstack/utils.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/contrib/openstack/utils.py 2015-04-16 21:56:47 +0000
@@ -23,12 +23,17 @@
23import subprocess23import subprocess
24import json24import json
25import os25import os
26import socket
27import sys26import sys
2827
29import six28import six
30import yaml29import yaml
3130
31from charmhelpers.contrib.network import ip
32
33from charmhelpers.core import (
34 unitdata,
35)
36
32from charmhelpers.core.hookenv import (37from charmhelpers.core.hookenv import (
33 config,38 config,
34 log as juju_log,39 log as juju_log,
@@ -103,6 +108,7 @@
103 ('2.1.0', 'juno'),108 ('2.1.0', 'juno'),
104 ('2.2.0', 'juno'),109 ('2.2.0', 'juno'),
105 ('2.2.1', 'kilo'),110 ('2.2.1', 'kilo'),
111 ('2.2.2', 'kilo'),
106])112])
107113
108DEFAULT_LOOPBACK_SIZE = '5G'114DEFAULT_LOOPBACK_SIZE = '5G'
@@ -328,6 +334,21 @@
328 error_out("Invalid openstack-release specified: %s" % rel)334 error_out("Invalid openstack-release specified: %s" % rel)
329335
330336
337def config_value_changed(option):
338 """
339 Determine if config value changed since last call to this function.
340 """
341 hook_data = unitdata.HookData()
342 with hook_data():
343 db = unitdata.kv()
344 current = config(option)
345 saved = db.get(option)
346 db.set(option, current)
347 if saved is None:
348 return False
349 return current != saved
350
351
331def save_script_rc(script_path="scripts/scriptrc", **env_vars):352def save_script_rc(script_path="scripts/scriptrc", **env_vars):
332 """353 """
333 Write an rc file in the charm-delivered directory containing354 Write an rc file in the charm-delivered directory containing
@@ -420,77 +441,10 @@
420 else:441 else:
421 zap_disk(block_device)442 zap_disk(block_device)
422443
423444is_ip = ip.is_ip
424def is_ip(address):445ns_query = ip.ns_query
425 """446get_host_ip = ip.get_host_ip
426 Returns True if address is a valid IP address.447get_hostname = ip.get_hostname
427 """
428 try:
429 # Test to see if already an IPv4 address
430 socket.inet_aton(address)
431 return True
432 except socket.error:
433 return False
434
435
436def ns_query(address):
437 try:
438 import dns.resolver
439 except ImportError:
440 apt_install('python-dnspython')
441 import dns.resolver
442
443 if isinstance(address, dns.name.Name):
444 rtype = 'PTR'
445 elif isinstance(address, six.string_types):
446 rtype = 'A'
447 else:
448 return None
449
450 answers = dns.resolver.query(address, rtype)
451 if answers:
452 return str(answers[0])
453 return None
454
455
456def get_host_ip(hostname):
457 """
458 Resolves the IP for a given hostname, or returns
459 the input if it is already an IP.
460 """
461 if is_ip(hostname):
462 return hostname
463
464 return ns_query(hostname)
465
466
467def get_hostname(address, fqdn=True):
468 """
469 Resolves hostname for given IP, or returns the input
470 if it is already a hostname.
471 """
472 if is_ip(address):
473 try:
474 import dns.reversename
475 except ImportError:
476 apt_install('python-dnspython')
477 import dns.reversename
478
479 rev = dns.reversename.from_address(address)
480 result = ns_query(rev)
481 if not result:
482 return None
483 else:
484 result = address
485
486 if fqdn:
487 # strip trailing .
488 if result.endswith('.'):
489 return result[:-1]
490 else:
491 return result
492 else:
493 return result.split('.')[0]
494448
495449
496def get_matchmaker_map(mm_file='/etc/oslo/matchmaker_ring.json'):450def get_matchmaker_map(mm_file='/etc/oslo/matchmaker_ring.json'):
@@ -534,82 +488,106 @@
534488
535489
536def git_install_requested():490def git_install_requested():
537 """Returns true if openstack-origin-git is specified."""491 """
538 return config('openstack-origin-git') != "None"492 Returns true if openstack-origin-git is specified.
493 """
494 return config('openstack-origin-git') is not None
539495
540496
541requirements_dir = None497requirements_dir = None
542498
543499
544def git_clone_and_install(file_name, core_project):500def git_clone_and_install(projects_yaml, core_project):
545 """Clone/install all OpenStack repos specified in yaml config file."""501 """
502 Clone/install all specified OpenStack repositories.
503
504 The expected format of projects_yaml is:
505 repositories:
506 - {name: keystone,
507 repository: 'git://git.openstack.org/openstack/keystone.git',
508 branch: 'stable/icehouse'}
509 - {name: requirements,
510 repository: 'git://git.openstack.org/openstack/requirements.git',
511 branch: 'stable/icehouse'}
512 directory: /mnt/openstack-git
513 http_proxy: http://squid.internal:3128
514 https_proxy: https://squid.internal:3128
515
516 The directory, http_proxy, and https_proxy keys are optional.
517 """
546 global requirements_dir518 global requirements_dir
519 parent_dir = '/mnt/openstack-git'
547520
548 if file_name == "None":521 if not projects_yaml:
549 return522 return
550523
551 yaml_file = os.path.join(charm_dir(), file_name)524 projects = yaml.load(projects_yaml)
552525 _git_validate_projects_yaml(projects, core_project)
553 # clone/install the requirements project first526
554 installed = _git_clone_and_install_subset(yaml_file,527 old_environ = dict(os.environ)
555 whitelist=['requirements'])528
556 if 'requirements' not in installed:529 if 'http_proxy' in projects.keys():
557 error_out('requirements git repository must be specified')530 os.environ['http_proxy'] = projects['http_proxy']
558531 if 'https_proxy' in projects.keys():
559 # clone/install all other projects except requirements and the core project532 os.environ['https_proxy'] = projects['https_proxy']
560 blacklist = ['requirements', core_project]533
561 _git_clone_and_install_subset(yaml_file, blacklist=blacklist,534 if 'directory' in projects.keys():
562 update_requirements=True)535 parent_dir = projects['directory']
563536
564 # clone/install the core project537 for p in projects['repositories']:
565 whitelist = [core_project]538 repo = p['repository']
566 installed = _git_clone_and_install_subset(yaml_file, whitelist=whitelist,539 branch = p['branch']
567 update_requirements=True)540 if p['name'] == 'requirements':
568 if core_project not in installed:541 repo_dir = _git_clone_and_install_single(repo, branch, parent_dir,
569 error_out('{} git repository must be specified'.format(core_project))542 update_requirements=False)
570543 requirements_dir = repo_dir
571544 else:
572def _git_clone_and_install_subset(yaml_file, whitelist=[], blacklist=[],545 repo_dir = _git_clone_and_install_single(repo, branch, parent_dir,
573 update_requirements=False):546 update_requirements=True)
574 """Clone/install subset of OpenStack repos specified in yaml config file."""547
575 global requirements_dir548 os.environ = old_environ
576 installed = []549
577550
578 with open(yaml_file, 'r') as fd:551def _git_validate_projects_yaml(projects, core_project):
579 projects = yaml.load(fd)552 """
580 for proj, val in projects.items():553 Validate the projects yaml.
581 # The project subset is chosen based on the following 3 rules:554 """
582 # 1) If project is in blacklist, we don't clone/install it, period.555 _git_ensure_key_exists('repositories', projects)
583 # 2) If whitelist is empty, we clone/install everything else.556
584 # 3) If whitelist is not empty, we clone/install everything in the557 for project in projects['repositories']:
585 # whitelist.558 _git_ensure_key_exists('name', project.keys())
586 if proj in blacklist:559 _git_ensure_key_exists('repository', project.keys())
587 continue560 _git_ensure_key_exists('branch', project.keys())
588 if whitelist and proj not in whitelist:561
589 continue562 if projects['repositories'][0]['name'] != 'requirements':
590 repo = val['repository']563 error_out('{} git repo must be specified first'.format('requirements'))
591 branch = val['branch']564
592 repo_dir = _git_clone_and_install_single(repo, branch,565 if projects['repositories'][-1]['name'] != core_project:
593 update_requirements)566 error_out('{} git repo must be specified last'.format(core_project))
594 if proj == 'requirements':567
595 requirements_dir = repo_dir568
596 installed.append(proj)569def _git_ensure_key_exists(key, keys):
597 return installed570 """
598571 Ensure that key exists in keys.
599572 """
600def _git_clone_and_install_single(repo, branch, update_requirements=False):573 if key not in keys:
601 """Clone and install a single git repository."""574 error_out('openstack-origin-git key \'{}\' is missing'.format(key))
602 dest_parent_dir = "/mnt/openstack-git/"575
603 dest_dir = os.path.join(dest_parent_dir, os.path.basename(repo))576
604577def _git_clone_and_install_single(repo, branch, parent_dir, update_requirements):
605 if not os.path.exists(dest_parent_dir):578 """
606 juju_log('Host dir not mounted at {}. '579 Clone and install a single git repository.
607 'Creating directory there instead.'.format(dest_parent_dir))580 """
608 os.mkdir(dest_parent_dir)581 dest_dir = os.path.join(parent_dir, os.path.basename(repo))
582
583 if not os.path.exists(parent_dir):
584 juju_log('Directory already exists at {}. '
585 'No need to create directory.'.format(parent_dir))
586 os.mkdir(parent_dir)
609587
610 if not os.path.exists(dest_dir):588 if not os.path.exists(dest_dir):
611 juju_log('Cloning git repo: {}, branch: {}'.format(repo, branch))589 juju_log('Cloning git repo: {}, branch: {}'.format(repo, branch))
612 repo_dir = install_remote(repo, dest=dest_parent_dir, branch=branch)590 repo_dir = install_remote(repo, dest=parent_dir, branch=branch)
613 else:591 else:
614 repo_dir = dest_dir592 repo_dir = dest_dir
615593
@@ -626,16 +604,39 @@
626604
627605
628def _git_update_requirements(package_dir, reqs_dir):606def _git_update_requirements(package_dir, reqs_dir):
629 """Update from global requirements.607 """
608 Update from global requirements.
630609
631 Update an OpenStack git directory's requirements.txt and610 Update an OpenStack git directory's requirements.txt and
632 test-requirements.txt from global-requirements.txt."""611 test-requirements.txt from global-requirements.txt.
612 """
633 orig_dir = os.getcwd()613 orig_dir = os.getcwd()
634 os.chdir(reqs_dir)614 os.chdir(reqs_dir)
635 cmd = "python update.py {}".format(package_dir)615 cmd = ['python', 'update.py', package_dir]
636 try:616 try:
637 subprocess.check_call(cmd.split(' '))617 subprocess.check_call(cmd)
638 except subprocess.CalledProcessError:618 except subprocess.CalledProcessError:
639 package = os.path.basename(package_dir)619 package = os.path.basename(package_dir)
640 error_out("Error updating {} from global-requirements.txt".format(package))620 error_out("Error updating {} from global-requirements.txt".format(package))
641 os.chdir(orig_dir)621 os.chdir(orig_dir)
622
623
624def git_src_dir(projects_yaml, project):
625 """
626 Return the directory where the specified project's source is located.
627 """
628 parent_dir = '/mnt/openstack-git'
629
630 if not projects_yaml:
631 return
632
633 projects = yaml.load(projects_yaml)
634
635 if 'directory' in projects.keys():
636 parent_dir = projects['directory']
637
638 for p in projects['repositories']:
639 if p['name'] == project:
640 return os.path.join(parent_dir, os.path.basename(p['repository']))
641
642 return None
642643
=== modified file 'hooks/charmhelpers/contrib/python/packages.py'
--- hooks/charmhelpers/contrib/python/packages.py 2015-01-29 13:15:20 +0000
+++ hooks/charmhelpers/contrib/python/packages.py 2015-04-16 21:56:47 +0000
@@ -17,8 +17,6 @@
17# You should have received a copy of the GNU Lesser General Public License17# You should have received a copy of the GNU Lesser General Public License
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/>.
1919
20__author__ = "Jorge Niedbalski <jorge.niedbalski@canonical.com>"
21
22from charmhelpers.fetch import apt_install, apt_update20from charmhelpers.fetch import apt_install, apt_update
23from charmhelpers.core.hookenv import log21from charmhelpers.core.hookenv import log
2422
@@ -29,6 +27,8 @@
29 apt_install('python-pip')27 apt_install('python-pip')
30 from pip import main as pip_execute28 from pip import main as pip_execute
3129
30__author__ = "Jorge Niedbalski <jorge.niedbalski@canonical.com>"
31
3232
33def parse_options(given, available):33def parse_options(given, available):
34 """Given a set of options, check if available"""34 """Given a set of options, check if available"""
3535
=== modified file 'hooks/charmhelpers/core/fstab.py'
--- hooks/charmhelpers/core/fstab.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/core/fstab.py 2015-04-16 21:56:47 +0000
@@ -17,11 +17,11 @@
17# You should have received a copy of the GNU Lesser General Public License17# You should have received a copy of the GNU Lesser General Public License
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/>.
1919
20__author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>'
21
22import io20import io
23import os21import os
2422
23__author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>'
24
2525
26class Fstab(io.FileIO):26class Fstab(io.FileIO):
27 """This class extends file in order to implement a file reader/writer27 """This class extends file in order to implement a file reader/writer
@@ -77,7 +77,7 @@
77 for line in self.readlines():77 for line in self.readlines():
78 line = line.decode('us-ascii')78 line = line.decode('us-ascii')
79 try:79 try:
80 if line.strip() and not line.startswith("#"):80 if line.strip() and not line.strip().startswith("#"):
81 yield self._hydrate_entry(line)81 yield self._hydrate_entry(line)
82 except ValueError:82 except ValueError:
83 pass83 pass
@@ -104,7 +104,7 @@
104104
105 found = False105 found = False
106 for index, line in enumerate(lines):106 for index, line in enumerate(lines):
107 if not line.startswith("#"):107 if line.strip() and not line.strip().startswith("#"):
108 if self._hydrate_entry(line) == entry:108 if self._hydrate_entry(line) == entry:
109 found = True109 found = True
110 break110 break
111111
=== modified file 'hooks/charmhelpers/core/hookenv.py'
--- hooks/charmhelpers/core/hookenv.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/core/hookenv.py 2015-04-16 21:56:47 +0000
@@ -20,11 +20,13 @@
20# Authors:20# Authors:
21# Charm Helpers Developers <juju@lists.ubuntu.com>21# Charm Helpers Developers <juju@lists.ubuntu.com>
2222
23from __future__ import print_function
23import os24import os
24import json25import json
25import yaml26import yaml
26import subprocess27import subprocess
27import sys28import sys
29import errno
28from subprocess import CalledProcessError30from subprocess import CalledProcessError
2931
30import six32import six
@@ -87,7 +89,18 @@
87 if not isinstance(message, six.string_types):89 if not isinstance(message, six.string_types):
88 message = repr(message)90 message = repr(message)
89 command += [message]91 command += [message]
90 subprocess.call(command)92 # Missing juju-log should not cause failures in unit tests
93 # Send log output to stderr
94 try:
95 subprocess.call(command)
96 except OSError as e:
97 if e.errno == errno.ENOENT:
98 if level:
99 message = "{}: {}".format(level, message)
100 message = "juju-log: {}".format(message)
101 print(message, file=sys.stderr)
102 else:
103 raise
91104
92105
93class Serializable(UserDict):106class Serializable(UserDict):
@@ -566,3 +579,29 @@
566def charm_dir():579def charm_dir():
567 """Return the root directory of the current charm"""580 """Return the root directory of the current charm"""
568 return os.environ.get('CHARM_DIR')581 return os.environ.get('CHARM_DIR')
582
583
584@cached
585def action_get(key=None):
586 """Gets the value of an action parameter, or all key/value param pairs"""
587 cmd = ['action-get']
588 if key is not None:
589 cmd.append(key)
590 cmd.append('--format=json')
591 action_data = json.loads(subprocess.check_output(cmd).decode('UTF-8'))
592 return action_data
593
594
595def action_set(values):
596 """Sets the values to be returned after the action finishes"""
597 cmd = ['action-set']
598 for k, v in list(values.items()):
599 cmd.append('{}={}'.format(k, v))
600 subprocess.check_call(cmd)
601
602
603def action_fail(message):
604 """Sets the action status to failed and sets the error message.
605
606 The results set by action_set are preserved."""
607 subprocess.check_call(['action-fail', message])
569608
=== modified file 'hooks/charmhelpers/core/host.py'
--- hooks/charmhelpers/core/host.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/core/host.py 2015-04-16 21:56:47 +0000
@@ -191,11 +191,11 @@
191191
192192
193def write_file(path, content, owner='root', group='root', perms=0o444):193def write_file(path, content, owner='root', group='root', perms=0o444):
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."""
195 log("Writing file {} {}:{} {:o}".format(path, owner, group, perms))195 log("Writing file {} {}:{} {:o}".format(path, owner, group, perms))
196 uid = pwd.getpwnam(owner).pw_uid196 uid = pwd.getpwnam(owner).pw_uid
197 gid = grp.getgrnam(group).gr_gid197 gid = grp.getgrnam(group).gr_gid
198 with open(path, 'w') as target:198 with open(path, 'wb') as target:
199 os.fchown(target.fileno(), uid, gid)199 os.fchown(target.fileno(), uid, gid)
200 os.fchmod(target.fileno(), perms)200 os.fchmod(target.fileno(), perms)
201 target.write(content)201 target.write(content)
@@ -305,11 +305,11 @@
305 ceph_client_changed function.305 ceph_client_changed function.
306 """306 """
307 def wrap(f):307 def wrap(f):
308 def wrapped_f(*args):308 def wrapped_f(*args, **kwargs):
309 checksums = {}309 checksums = {}
310 for path in restart_map:310 for path in restart_map:
311 checksums[path] = file_hash(path)311 checksums[path] = file_hash(path)
312 f(*args)312 f(*args, **kwargs)
313 restarts = []313 restarts = []
314 for path in restart_map:314 for path in restart_map:
315 if checksums[path] != file_hash(path):315 if checksums[path] != file_hash(path):
@@ -339,12 +339,16 @@
339def pwgen(length=None):339def pwgen(length=None):
340 """Generate a random pasword."""340 """Generate a random pasword."""
341 if length is None:341 if length is None:
342 # A random length is ok to use a weak PRNG
342 length = random.choice(range(35, 45))343 length = random.choice(range(35, 45))
343 alphanumeric_chars = [344 alphanumeric_chars = [
344 l for l in (string.ascii_letters + string.digits)345 l for l in (string.ascii_letters + string.digits)
345 if l not in 'l0QD1vAEIOUaeiou']346 if l not in 'l0QD1vAEIOUaeiou']
347 # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
348 # actual password
349 random_generator = random.SystemRandom()
346 random_chars = [350 random_chars = [
347 random.choice(alphanumeric_chars) for _ in range(length)]351 random_generator.choice(alphanumeric_chars) for _ in range(length)]
348 return(''.join(random_chars))352 return(''.join(random_chars))
349353
350354
@@ -361,7 +365,7 @@
361 ip_output = (line for line in ip_output if line)365 ip_output = (line for line in ip_output if line)
362 for line in ip_output:366 for line in ip_output:
363 if line.split()[1].startswith(int_type):367 if line.split()[1].startswith(int_type):
364 matched = re.search('.*: (bond[0-9]+\.[0-9]+)@.*', line)368 matched = re.search('.*: (' + int_type + r'[0-9]+\.[0-9]+)@.*', line)
365 if matched:369 if matched:
366 interface = matched.groups()[0]370 interface = matched.groups()[0]
367 else:371 else:
368372
=== modified file 'hooks/charmhelpers/core/services/helpers.py'
--- hooks/charmhelpers/core/services/helpers.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/core/services/helpers.py 2015-04-16 21:56:47 +0000
@@ -45,12 +45,14 @@
45 """45 """
46 name = None46 name = None
47 interface = None47 interface = None
48 required_keys = []
4948
50 def __init__(self, name=None, additional_required_keys=None):49 def __init__(self, name=None, additional_required_keys=None):
50 if not hasattr(self, 'required_keys'):
51 self.required_keys = []
52
51 if name is not None:53 if name is not None:
52 self.name = name54 self.name = name
53 if additional_required_keys is not None:55 if additional_required_keys:
54 self.required_keys.extend(additional_required_keys)56 self.required_keys.extend(additional_required_keys)
55 self.get_data()57 self.get_data()
5658
@@ -134,7 +136,10 @@
134 """136 """
135 name = 'db'137 name = 'db'
136 interface = 'mysql'138 interface = 'mysql'
137 required_keys = ['host', 'user', 'password', 'database']139
140 def __init__(self, *args, **kwargs):
141 self.required_keys = ['host', 'user', 'password', 'database']
142 RelationContext.__init__(self, *args, **kwargs)
138143
139144
140class HttpRelation(RelationContext):145class HttpRelation(RelationContext):
@@ -146,7 +151,10 @@
146 """151 """
147 name = 'website'152 name = 'website'
148 interface = 'http'153 interface = 'http'
149 required_keys = ['host', 'port']154
155 def __init__(self, *args, **kwargs):
156 self.required_keys = ['host', 'port']
157 RelationContext.__init__(self, *args, **kwargs)
150158
151 def provide_data(self):159 def provide_data(self):
152 return {160 return {
153161
=== added file 'hooks/charmhelpers/core/strutils.py'
--- hooks/charmhelpers/core/strutils.py 1970-01-01 00:00:00 +0000
+++ hooks/charmhelpers/core/strutils.py 2015-04-16 21:56:47 +0000
@@ -0,0 +1,42 @@
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# Copyright 2014-2015 Canonical Limited.
5#
6# This file is part of charm-helpers.
7#
8# charm-helpers is free software: you can redistribute it and/or modify
9# it under the terms of the GNU Lesser General Public License version 3 as
10# published by the Free Software Foundation.
11#
12# charm-helpers is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU Lesser General Public License for more details.
16#
17# You should have received a copy of the GNU Lesser General Public License
18# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
19
20import six
21
22
23def bool_from_string(value):
24 """Interpret string value as boolean.
25
26 Returns True if value translates to True otherwise False.
27 """
28 if isinstance(value, six.string_types):
29 value = six.text_type(value)
30 else:
31 msg = "Unable to interpret non-string value '%s' as boolean" % (value)
32 raise ValueError(msg)
33
34 value = value.strip().lower()
35
36 if value in ['y', 'yes', 'true', 't', 'on']:
37 return True
38 elif value in ['n', 'no', 'false', 'f', 'off']:
39 return False
40
41 msg = "Unable to interpret string value '%s' as boolean" % (value)
42 raise ValueError(msg)
043
=== modified file 'hooks/charmhelpers/core/sysctl.py'
--- hooks/charmhelpers/core/sysctl.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/core/sysctl.py 2015-04-16 21:56:47 +0000
@@ -17,8 +17,6 @@
17# You should have received a copy of the GNU Lesser General Public License17# You should have received a copy of the GNU Lesser General Public License
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/>.
1919
20__author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>'
21
22import yaml20import yaml
2321
24from subprocess import check_call22from subprocess import check_call
@@ -26,25 +24,33 @@
26from charmhelpers.core.hookenv import (24from charmhelpers.core.hookenv import (
27 log,25 log,
28 DEBUG,26 DEBUG,
27 ERROR,
29)28)
3029
30__author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>'
31
3132
32def create(sysctl_dict, sysctl_file):33def create(sysctl_dict, sysctl_file):
33 """Creates a sysctl.conf file from a YAML associative array34 """Creates a sysctl.conf file from a YAML associative array
3435
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 }"
36 :type sysctl_dict: dict37 :type sysctl_dict: str
37 :param sysctl_file: path to the sysctl file to be saved38 :param sysctl_file: path to the sysctl file to be saved
38 :type sysctl_file: str or unicode39 :type sysctl_file: str or unicode
39 :returns: None40 :returns: None
40 """41 """
41 sysctl_dict = yaml.load(sysctl_dict)42 try:
43 sysctl_dict_parsed = yaml.safe_load(sysctl_dict)
44 except yaml.YAMLError:
45 log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict),
46 level=ERROR)
47 return
4248
43 with open(sysctl_file, "w") as fd:49 with open(sysctl_file, "w") as fd:
44 for key, value in sysctl_dict.items():50 for key, value in sysctl_dict_parsed.items():
45 fd.write("{}={}\n".format(key, value))51 fd.write("{}={}\n".format(key, value))
4652
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),
48 level=DEBUG)54 level=DEBUG)
4955
50 check_call(["sysctl", "-p", sysctl_file])56 check_call(["sysctl", "-p", sysctl_file])
5157
=== modified file 'hooks/charmhelpers/core/templating.py'
--- hooks/charmhelpers/core/templating.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/core/templating.py 2015-04-16 21:56:47 +0000
@@ -21,7 +21,7 @@
2121
2222
23def render(source, target, context, owner='root', group='root',23def render(source, target, context, owner='root', group='root',
24 perms=0o444, templates_dir=None):24 perms=0o444, templates_dir=None, encoding='UTF-8'):
25 """25 """
26 Render a template.26 Render a template.
2727
@@ -64,5 +64,5 @@
64 level=hookenv.ERROR)64 level=hookenv.ERROR)
65 raise e65 raise e
66 content = template.render(context)66 content = template.render(context)
67 host.mkdir(os.path.dirname(target), owner, group)67 host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
68 host.write_file(target, content, owner, group, perms)68 host.write_file(target, content.encode(encoding), owner, group, perms)
6969
=== added file 'hooks/charmhelpers/core/unitdata.py'
--- hooks/charmhelpers/core/unitdata.py 1970-01-01 00:00:00 +0000
+++ hooks/charmhelpers/core/unitdata.py 2015-04-16 21:56:47 +0000
@@ -0,0 +1,477 @@
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2014-2015 Canonical Limited.
5#
6# This file is part of charm-helpers.
7#
8# charm-helpers is free software: you can redistribute it and/or modify
9# it under the terms of the GNU Lesser General Public License version 3 as
10# published by the Free Software Foundation.
11#
12# charm-helpers is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU Lesser General Public License for more details.
16#
17# You should have received a copy of the GNU Lesser General Public License
18# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
19#
20#
21# Authors:
22# Kapil Thangavelu <kapil.foss@gmail.com>
23#
24"""
25Intro
26-----
27
28A simple way to store state in units. This provides a key value
29storage with support for versioned, transactional operation,
30and can calculate deltas from previous values to simplify unit logic
31when processing changes.
32
33
34Hook Integration
35----------------
36
37There are several extant frameworks for hook execution, including
38
39 - charmhelpers.core.hookenv.Hooks
40 - charmhelpers.core.services.ServiceManager
41
42The storage classes are framework agnostic, one simple integration is
43via the HookData contextmanager. It will record the current hook
44execution environment (including relation data, config data, etc.),
45setup a transaction and allow easy access to the changes from
46previously seen values. One consequence of the integration is the
47reservation of particular keys ('rels', 'unit', 'env', 'config',
48'charm_revisions') for their respective values.
49
50Here's a fully worked integration example using hookenv.Hooks::
51
52 from charmhelper.core import hookenv, unitdata
53
54 hook_data = unitdata.HookData()
55 db = unitdata.kv()
56 hooks = hookenv.Hooks()
57
58 @hooks.hook
59 def config_changed():
60 # Print all changes to configuration from previously seen
61 # values.
62 for changed, (prev, cur) in hook_data.conf.items():
63 print('config changed', changed,
64 'previous value', prev,
65 'current value', cur)
66
67 # Get some unit specific bookeeping
68 if not db.get('pkg_key'):
69 key = urllib.urlopen('https://example.com/pkg_key').read()
70 db.set('pkg_key', key)
71
72 # Directly access all charm config as a mapping.
73 conf = db.getrange('config', True)
74
75 # Directly access all relation data as a mapping
76 rels = db.getrange('rels', True)
77
78 if __name__ == '__main__':
79 with hook_data():
80 hook.execute()
81
82
83A more basic integration is via the hook_scope context manager which simply
84manages transaction scope (and records hook name, and timestamp)::
85
86 >>> from unitdata import kv
87 >>> db = kv()
88 >>> with db.hook_scope('install'):
89 ... # do work, in transactional scope.
90 ... db.set('x', 1)
91 >>> db.get('x')
92 1
93
94
95Usage
96-----
97
98Values are automatically json de/serialized to preserve basic typing
99and complex data struct capabilities (dicts, lists, ints, booleans, etc).
100
101Individual values can be manipulated via get/set::
102
103 >>> kv.set('y', True)
104 >>> kv.get('y')
105 True
106
107 # We can set complex values (dicts, lists) as a single key.
108 >>> kv.set('config', {'a': 1, 'b': True'})
109
110 # Also supports returning dictionaries as a record which
111 # provides attribute access.
112 >>> config = kv.get('config', record=True)
113 >>> config.b
114 True
115
116
117Groups of keys can be manipulated with update/getrange::
118
119 >>> kv.update({'z': 1, 'y': 2}, prefix="gui.")
120 >>> kv.getrange('gui.', strip=True)
121 {'z': 1, 'y': 2}
122
123When updating values, its very helpful to understand which values
124have actually changed and how have they changed. The storage
125provides a delta method to provide for this::
126
127 >>> data = {'debug': True, 'option': 2}
128 >>> delta = kv.delta(data, 'config.')
129 >>> delta.debug.previous
130 None
131 >>> delta.debug.current
132 True
133 >>> delta
134 {'debug': (None, True), 'option': (None, 2)}
135
136Note the delta method does not persist the actual change, it needs to
137be explicitly saved via 'update' method::
138
139 >>> kv.update(data, 'config.')
140
141Values modified in the context of a hook scope retain historical values
142associated to the hookname.
143
144 >>> with db.hook_scope('config-changed'):
145 ... db.set('x', 42)
146 >>> db.gethistory('x')
147 [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'),
148 (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')]
149
150"""
151
152import collections
153import contextlib
154import datetime
155import json
156import os
157import pprint
158import sqlite3
159import sys
160
161__author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>'
162
163
164class Storage(object):
165 """Simple key value database for local unit state within charms.
166
167 Modifications are automatically committed at hook exit. That's
168 currently regardless of exit code.
169
170 To support dicts, lists, integer, floats, and booleans values
171 are automatically json encoded/decoded.
172 """
173 def __init__(self, path=None):
174 self.db_path = path
175 if path is None:
176 self.db_path = os.path.join(
177 os.environ.get('CHARM_DIR', ''), '.unit-state.db')
178 self.conn = sqlite3.connect('%s' % self.db_path)
179 self.cursor = self.conn.cursor()
180 self.revision = None
181 self._closed = False
182 self._init()
183
184 def close(self):
185 if self._closed:
186 return
187 self.flush(False)
188 self.cursor.close()
189 self.conn.close()
190 self._closed = True
191
192 def _scoped_query(self, stmt, params=None):
193 if params is None:
194 params = []
195 return stmt, params
196
197 def get(self, key, default=None, record=False):
198 self.cursor.execute(
199 *self._scoped_query(
200 'select data from kv where key=?', [key]))
201 result = self.cursor.fetchone()
202 if not result:
203 return default
204 if record:
205 return Record(json.loads(result[0]))
206 return json.loads(result[0])
207
208 def getrange(self, key_prefix, strip=False):
209 stmt = "select key, data from kv where key like '%s%%'" % key_prefix
210 self.cursor.execute(*self._scoped_query(stmt))
211 result = self.cursor.fetchall()
212
213 if not result:
214 return None
215 if not strip:
216 key_prefix = ''
217 return dict([
218 (k[len(key_prefix):], json.loads(v)) for k, v in result])
219
220 def update(self, mapping, prefix=""):
221 for k, v in mapping.items():
222 self.set("%s%s" % (prefix, k), v)
223
224 def unset(self, key):
225 self.cursor.execute('delete from kv where key=?', [key])
226 if self.revision and self.cursor.rowcount:
227 self.cursor.execute(
228 'insert into kv_revisions values (?, ?, ?)',
229 [key, self.revision, json.dumps('DELETED')])
230
231 def set(self, key, value):
232 serialized = json.dumps(value)
233
234 self.cursor.execute(
235 'select data from kv where key=?', [key])
236 exists = self.cursor.fetchone()
237
238 # Skip mutations to the same value
239 if exists:
240 if exists[0] == serialized:
241 return value
242
243 if not exists:
244 self.cursor.execute(
245 'insert into kv (key, data) values (?, ?)',
246 (key, serialized))
247 else:
248 self.cursor.execute('''
249 update kv
250 set data = ?
251 where key = ?''', [serialized, key])
252
253 # Save
254 if not self.revision:
255 return value
256
257 self.cursor.execute(
258 'select 1 from kv_revisions where key=? and revision=?',
259 [key, self.revision])
260 exists = self.cursor.fetchone()
261
262 if not exists:
263 self.cursor.execute(
264 '''insert into kv_revisions (
265 revision, key, data) values (?, ?, ?)''',
266 (self.revision, key, serialized))
267 else:
268 self.cursor.execute(
269 '''
270 update kv_revisions
271 set data = ?
272 where key = ?
273 and revision = ?''',
274 [serialized, key, self.revision])
275
276 return value
277
278 def delta(self, mapping, prefix):
279 """
280 return a delta containing values that have changed.
281 """
282 previous = self.getrange(prefix, strip=True)
283 if not previous:
284 pk = set()
285 else:
286 pk = set(previous.keys())
287 ck = set(mapping.keys())
288 delta = DeltaSet()
289
290 # added
291 for k in ck.difference(pk):
292 delta[k] = Delta(None, mapping[k])
293
294 # removed
295 for k in pk.difference(ck):
296 delta[k] = Delta(previous[k], None)
297
298 # changed
299 for k in pk.intersection(ck):
300 c = mapping[k]
301 p = previous[k]
302 if c != p:
303 delta[k] = Delta(p, c)
304
305 return delta
306
307 @contextlib.contextmanager
308 def hook_scope(self, name=""):
309 """Scope all future interactions to the current hook execution
310 revision."""
311 assert not self.revision
312 self.cursor.execute(
313 'insert into hooks (hook, date) values (?, ?)',
314 (name or sys.argv[0],
315 datetime.datetime.utcnow().isoformat()))
316 self.revision = self.cursor.lastrowid
317 try:
318 yield self.revision
319 self.revision = None
320 except:
321 self.flush(False)
322 self.revision = None
323 raise
324 else:
325 self.flush()
326
327 def flush(self, save=True):
328 if save:
329 self.conn.commit()
330 elif self._closed:
331 return
332 else:
333 self.conn.rollback()
334
335 def _init(self):
336 self.cursor.execute('''
337 create table if not exists kv (
338 key text,
339 data text,
340 primary key (key)
341 )''')
342 self.cursor.execute('''
343 create table if not exists kv_revisions (
344 key text,
345 revision integer,
346 data text,
347 primary key (key, revision)
348 )''')
349 self.cursor.execute('''
350 create table if not exists hooks (
351 version integer primary key autoincrement,
352 hook text,
353 date text
354 )''')
355 self.conn.commit()
356
357 def gethistory(self, key, deserialize=False):
358 self.cursor.execute(
359 '''
360 select kv.revision, kv.key, kv.data, h.hook, h.date
361 from kv_revisions kv,
362 hooks h
363 where kv.key=?
364 and kv.revision = h.version
365 ''', [key])
366 if deserialize is False:
367 return self.cursor.fetchall()
368 return map(_parse_history, self.cursor.fetchall())
369
370 def debug(self, fh=sys.stderr):
371 self.cursor.execute('select * from kv')
372 pprint.pprint(self.cursor.fetchall(), stream=fh)
373 self.cursor.execute('select * from kv_revisions')
374 pprint.pprint(self.cursor.fetchall(), stream=fh)
375
376
377def _parse_history(d):
378 return (d[0], d[1], json.loads(d[2]), d[3],
379 datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f"))
380
381
382class HookData(object):
383 """Simple integration for existing hook exec frameworks.
384
385 Records all unit information, and stores deltas for processing
386 by the hook.
387
388 Sample::
389
390 from charmhelper.core import hookenv, unitdata
391
392 changes = unitdata.HookData()
393 db = unitdata.kv()
394 hooks = hookenv.Hooks()
395
396 @hooks.hook
397 def config_changed():
398 # View all changes to configuration
399 for changed, (prev, cur) in changes.conf.items():
400 print('config changed', changed,
401 'previous value', prev,
402 'current value', cur)
403
404 # Get some unit specific bookeeping
405 if not db.get('pkg_key'):
406 key = urllib.urlopen('https://example.com/pkg_key').read()
407 db.set('pkg_key', key)
408
409 if __name__ == '__main__':
410 with changes():
411 hook.execute()
412
413 """
414 def __init__(self):
415 self.kv = kv()
416 self.conf = None
417 self.rels = None
418
419 @contextlib.contextmanager
420 def __call__(self):
421 from charmhelpers.core import hookenv
422 hook_name = hookenv.hook_name()
423
424 with self.kv.hook_scope(hook_name):
425 self._record_charm_version(hookenv.charm_dir())
426 delta_config, delta_relation = self._record_hook(hookenv)
427 yield self.kv, delta_config, delta_relation
428
429 def _record_charm_version(self, charm_dir):
430 # Record revisions.. charm revisions are meaningless
431 # to charm authors as they don't control the revision.
432 # so logic dependnent on revision is not particularly
433 # useful, however it is useful for debugging analysis.
434 charm_rev = open(
435 os.path.join(charm_dir, 'revision')).read().strip()
436 charm_rev = charm_rev or '0'
437 revs = self.kv.get('charm_revisions', [])
438 if charm_rev not in revs:
439 revs.append(charm_rev.strip() or '0')
440 self.kv.set('charm_revisions', revs)
441
442 def _record_hook(self, hookenv):
443 data = hookenv.execution_environment()
444 self.conf = conf_delta = self.kv.delta(data['conf'], 'config')
445 self.rels = rels_delta = self.kv.delta(data['rels'], 'rels')
446 self.kv.set('env', dict(data['env']))
447 self.kv.set('unit', data['unit'])
448 self.kv.set('relid', data.get('relid'))
449 return conf_delta, rels_delta
450
451
452class Record(dict):
453
454 __slots__ = ()
455
456 def __getattr__(self, k):
457 if k in self:
458 return self[k]
459 raise AttributeError(k)
460
461
462class DeltaSet(Record):
463
464 __slots__ = ()
465
466
467Delta = collections.namedtuple('Delta', ['previous', 'current'])
468
469
470_KV = None
471
472
473def kv():
474 global _KV
475 if _KV is None:
476 _KV = Storage()
477 return _KV
0478
=== modified file 'hooks/charmhelpers/fetch/archiveurl.py'
--- hooks/charmhelpers/fetch/archiveurl.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/fetch/archiveurl.py 2015-04-16 21:56:47 +0000
@@ -18,6 +18,16 @@
18import hashlib18import hashlib
19import re19import re
2020
21from charmhelpers.fetch import (
22 BaseFetchHandler,
23 UnhandledSource
24)
25from charmhelpers.payload.archive import (
26 get_archive_handler,
27 extract,
28)
29from charmhelpers.core.host import mkdir, check_hash
30
21import six31import six
22if six.PY3:32if six.PY3:
23 from urllib.request import (33 from urllib.request import (
@@ -35,16 +45,6 @@
35 )45 )
36 from urlparse import urlparse, urlunparse, parse_qs46 from urlparse import urlparse, urlunparse, parse_qs
3747
38from charmhelpers.fetch import (
39 BaseFetchHandler,
40 UnhandledSource
41)
42from charmhelpers.payload.archive import (
43 get_archive_handler,
44 extract,
45)
46from charmhelpers.core.host import mkdir, check_hash
47
4848
49def splituser(host):49def splituser(host):
50 '''urllib.splituser(), but six's support of this seems broken'''50 '''urllib.splituser(), but six's support of this seems broken'''
5151
=== modified file 'hooks/charmhelpers/fetch/giturl.py'
--- hooks/charmhelpers/fetch/giturl.py 2015-01-29 13:02:55 +0000
+++ hooks/charmhelpers/fetch/giturl.py 2015-04-16 21:56:47 +0000
@@ -32,7 +32,7 @@
32 apt_install("python-git")32 apt_install("python-git")
33 from git import Repo33 from git import Repo
3434
35from git.exc import GitCommandError35from git.exc import GitCommandError # noqa E402
3636
3737
38class GitUrlFetchHandler(BaseFetchHandler):38class GitUrlFetchHandler(BaseFetchHandler):
3939
=== modified file 'tests/charmhelpers/contrib/amulet/utils.py'
--- tests/charmhelpers/contrib/amulet/utils.py 2015-01-29 13:02:55 +0000
+++ tests/charmhelpers/contrib/amulet/utils.py 2015-04-16 21:56:47 +0000
@@ -118,6 +118,9 @@
118 longs, or can be a function that evaluate a variable and returns a118 longs, or can be a function that evaluate a variable and returns a
119 bool.119 bool.
120 """120 """
121 self.log.debug('actual: {}'.format(repr(actual)))
122 self.log.debug('expected: {}'.format(repr(expected)))
123
121 for k, v in six.iteritems(expected):124 for k, v in six.iteritems(expected):
122 if k in actual:125 if k in actual:
123 if (isinstance(v, six.string_types) or126 if (isinstance(v, six.string_types) or
@@ -134,7 +137,6 @@
134 def validate_relation_data(self, sentry_unit, relation, expected):137 def validate_relation_data(self, sentry_unit, relation, expected):
135 """Validate actual relation data based on expected relation data."""138 """Validate actual relation data based on expected relation data."""
136 actual = sentry_unit.relation(relation[0], relation[1])139 actual = sentry_unit.relation(relation[0], relation[1])
137 self.log.debug('actual: {}'.format(repr(actual)))
138 return self._validate_dict_data(expected, actual)140 return self._validate_dict_data(expected, actual)
139141
140 def _validate_list_data(self, expected, actual):142 def _validate_list_data(self, expected, actual):
@@ -169,8 +171,13 @@
169 cmd = 'pgrep -o -f {}'.format(service)171 cmd = 'pgrep -o -f {}'.format(service)
170 else:172 else:
171 cmd = 'pgrep -o {}'.format(service)173 cmd = 'pgrep -o {}'.format(service)
172 proc_dir = '/proc/{}'.format(sentry_unit.run(cmd)[0].strip())174 cmd = cmd + ' | grep -v pgrep || exit 0'
173 return self._get_dir_mtime(sentry_unit, proc_dir)175 cmd_out = sentry_unit.run(cmd)
176 self.log.debug('CMDout: ' + str(cmd_out))
177 if cmd_out[0]:
178 self.log.debug('Pid for %s %s' % (service, str(cmd_out[0])))
179 proc_dir = '/proc/{}'.format(cmd_out[0].strip())
180 return self._get_dir_mtime(sentry_unit, proc_dir)
174181
175 def service_restarted(self, sentry_unit, service, filename,182 def service_restarted(self, sentry_unit, service, filename,
176 pgrep_full=False, sleep_time=20):183 pgrep_full=False, sleep_time=20):
@@ -187,6 +194,121 @@
187 else:194 else:
188 return False195 return False
189196
197 def service_restarted_since(self, sentry_unit, mtime, service,
198 pgrep_full=False, sleep_time=20,
199 retry_count=2):
200 """Check if service was been started after a given time.
201
202 Args:
203 sentry_unit (sentry): The sentry unit to check for the service on
204 mtime (float): The epoch time to check against
205 service (string): service name to look for in process table
206 pgrep_full (boolean): Use full command line search mode with pgrep
207 sleep_time (int): Seconds to sleep before looking for process
208 retry_count (int): If service is not found, how many times to retry
209
210 Returns:
211 bool: True if service found and its start time it newer than mtime,
212 False if service is older than mtime or if service was
213 not found.
214 """
215 self.log.debug('Checking %s restarted since %s' % (service, mtime))
216 time.sleep(sleep_time)
217 proc_start_time = self._get_proc_start_time(sentry_unit, service,
218 pgrep_full)
219 while retry_count > 0 and not proc_start_time:
220 self.log.debug('No pid file found for service %s, will retry %i '
221 'more times' % (service, retry_count))
222 time.sleep(30)
223 proc_start_time = self._get_proc_start_time(sentry_unit, service,
224 pgrep_full)
225 retry_count = retry_count - 1
226
227 if not proc_start_time:
228 self.log.warn('No proc start time found, assuming service did '
229 'not start')
230 return False
231 if proc_start_time >= mtime:
232 self.log.debug('proc start time is newer than provided mtime'
233 '(%s >= %s)' % (proc_start_time, mtime))
234 return True
235 else:
236 self.log.warn('proc start time (%s) is older than provided mtime '
237 '(%s), service did not restart' % (proc_start_time,
238 mtime))
239 return False
240
241 def config_updated_since(self, sentry_unit, filename, mtime,
242 sleep_time=20):
243 """Check if file was modified after a given time.
244
245 Args:
246 sentry_unit (sentry): The sentry unit to check the file mtime on
247 filename (string): The file to check mtime of
248 mtime (float): The epoch time to check against
249 sleep_time (int): Seconds to sleep before looking for process
250
251 Returns:
252 bool: True if file was modified more recently than mtime, False if
253 file was modified before mtime,
254 """
255 self.log.debug('Checking %s updated since %s' % (filename, mtime))
256 time.sleep(sleep_time)
257 file_mtime = self._get_file_mtime(sentry_unit, filename)
258 if file_mtime >= mtime:
259 self.log.debug('File mtime is newer than provided mtime '
260 '(%s >= %s)' % (file_mtime, mtime))
261 return True
262 else:
263 self.log.warn('File mtime %s is older than provided mtime %s'
264 % (file_mtime, mtime))
265 return False
266
267 def validate_service_config_changed(self, sentry_unit, mtime, service,
268 filename, pgrep_full=False,
269 sleep_time=20, retry_count=2):
270 """Check service and file were updated after mtime
271
272 Args:
273 sentry_unit (sentry): The sentry unit to check for the service on
274 mtime (float): The epoch time to check against
275 service (string): service name to look for in process table
276 filename (string): The file to check mtime of
277 pgrep_full (boolean): Use full command line search mode with pgrep
278 sleep_time (int): Seconds to sleep before looking for process
279 retry_count (int): If service is not found, how many times to retry
280
281 Typical Usage:
282 u = OpenStackAmuletUtils(ERROR)
283 ...
284 mtime = u.get_sentry_time(self.cinder_sentry)
285 self.d.configure('cinder', {'verbose': 'True', 'debug': 'True'})
286 if not u.validate_service_config_changed(self.cinder_sentry,
287 mtime,
288 'cinder-api',
289 '/etc/cinder/cinder.conf')
290 amulet.raise_status(amulet.FAIL, msg='update failed')
291 Returns:
292 bool: True if both service and file where updated/restarted after
293 mtime, False if service is older than mtime or if service was
294 not found or if filename was modified before mtime.
295 """
296 self.log.debug('Checking %s restarted since %s' % (service, mtime))
297 time.sleep(sleep_time)
298 service_restart = self.service_restarted_since(sentry_unit, mtime,
299 service,
300 pgrep_full=pgrep_full,
301 sleep_time=0,
302 retry_count=retry_count)
303 config_update = self.config_updated_since(sentry_unit, filename, mtime,
304 sleep_time=0)
305 return service_restart and config_update
306
307 def get_sentry_time(self, sentry_unit):
308 """Return current epoch time on a sentry"""
309 cmd = "date +'%s'"
310 return float(sentry_unit.run(cmd)[0])
311
190 def relation_error(self, name, data):312 def relation_error(self, name, data):
191 return 'unexpected relation data in {} - {}'.format(name, data)313 return 'unexpected relation data in {} - {}'.format(name, data)
192314
193315
=== modified file 'tests/charmhelpers/contrib/openstack/amulet/deployment.py'
--- tests/charmhelpers/contrib/openstack/amulet/deployment.py 2015-01-29 13:02:55 +0000
+++ tests/charmhelpers/contrib/openstack/amulet/deployment.py 2015-04-16 21:56:47 +0000
@@ -15,6 +15,7 @@
15# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.15# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
1616
17import six17import six
18from collections import OrderedDict
18from charmhelpers.contrib.amulet.deployment import (19from charmhelpers.contrib.amulet.deployment import (
19 AmuletDeployment20 AmuletDeployment
20)21)
@@ -43,7 +44,7 @@
43 Determine if the local branch being tested is derived from its44 Determine if the local branch being tested is derived from its
44 stable or next (dev) branch, and based on this, use the corresonding45 stable or next (dev) branch, and based on this, use the corresonding
45 stable or next branches for the other_services."""46 stable or next branches for the other_services."""
46 base_charms = ['mysql', 'mongodb', 'rabbitmq-server']47 base_charms = ['mysql', 'mongodb']
4748
48 if self.stable:49 if self.stable:
49 for svc in other_services:50 for svc in other_services:
@@ -71,16 +72,19 @@
71 services.append(this_service)72 services.append(this_service)
72 use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph',73 use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph',
73 'ceph-osd', 'ceph-radosgw']74 'ceph-osd', 'ceph-radosgw']
75 # Openstack subordinate charms do not expose an origin option as that
76 # is controlled by the principle
77 ignore = ['neutron-openvswitch']
7478
75 if self.openstack:79 if self.openstack:
76 for svc in services:80 for svc in services:
77 if svc['name'] not in use_source:81 if svc['name'] not in use_source + ignore:
78 config = {'openstack-origin': self.openstack}82 config = {'openstack-origin': self.openstack}
79 self.d.configure(svc['name'], config)83 self.d.configure(svc['name'], config)
8084
81 if self.source:85 if self.source:
82 for svc in services:86 for svc in services:
83 if svc['name'] in use_source:87 if svc['name'] in use_source and svc['name'] not in ignore:
84 config = {'source': self.source}88 config = {'source': self.source}
85 self.d.configure(svc['name'], config)89 self.d.configure(svc['name'], config)
8690
@@ -97,12 +101,37 @@
97 """101 """
98 (self.precise_essex, self.precise_folsom, self.precise_grizzly,102 (self.precise_essex, self.precise_folsom, self.precise_grizzly,
99 self.precise_havana, self.precise_icehouse,103 self.precise_havana, self.precise_icehouse,
100 self.trusty_icehouse) = range(6)104 self.trusty_icehouse, self.trusty_juno, self.trusty_kilo,
105 self.utopic_juno, self.vivid_kilo) = range(10)
101 releases = {106 releases = {
102 ('precise', None): self.precise_essex,107 ('precise', None): self.precise_essex,
103 ('precise', 'cloud:precise-folsom'): self.precise_folsom,108 ('precise', 'cloud:precise-folsom'): self.precise_folsom,
104 ('precise', 'cloud:precise-grizzly'): self.precise_grizzly,109 ('precise', 'cloud:precise-grizzly'): self.precise_grizzly,
105 ('precise', 'cloud:precise-havana'): self.precise_havana,110 ('precise', 'cloud:precise-havana'): self.precise_havana,
106 ('precise', 'cloud:precise-icehouse'): self.precise_icehouse,111 ('precise', 'cloud:precise-icehouse'): self.precise_icehouse,
107 ('trusty', None): self.trusty_icehouse}112 ('trusty', None): self.trusty_icehouse,
113 ('trusty', 'cloud:trusty-juno'): self.trusty_juno,
114 ('trusty', 'cloud:trusty-kilo'): self.trusty_kilo,
115 ('utopic', None): self.utopic_juno,
116 ('vivid', None): self.vivid_kilo}
108 return releases[(self.series, self.openstack)]117 return releases[(self.series, self.openstack)]
118
119 def _get_openstack_release_string(self):
120 """Get openstack release string.
121
122 Return a string representing the openstack release.
123 """
124 releases = OrderedDict([
125 ('precise', 'essex'),
126 ('quantal', 'folsom'),
127 ('raring', 'grizzly'),
128 ('saucy', 'havana'),
129 ('trusty', 'icehouse'),
130 ('utopic', 'juno'),
131 ('vivid', 'kilo'),
132 ])
133 if self.openstack:
134 os_origin = self.openstack.split(':')[1]
135 return os_origin.split('%s-' % self.series)[1].split('/')[0]
136 else:
137 return releases[self.series]

Subscribers

People subscribed via source and target branches