3
# Common python helper functions used for OpenStack charms.
4
from collections import OrderedDict
12
from charmhelpers.core.hookenv import (
20
from charmhelpers.contrib.storage.linux.lvm import (
21
deactivate_lvm_volume_group,
22
is_lvm_physical_volume,
23
remove_lvm_physical_volume,
26
from charmhelpers.core.host import lsb_release, mounts, umount
27
from charmhelpers.fetch import apt_install
28
from charmhelpers.contrib.storage.linux.utils import is_block_device, zap_disk
29
from charmhelpers.contrib.storage.linux.loopback import ensure_loopback_device
31
CLOUD_ARCHIVE_URL = "http://ubuntu-cloud.archive.canonical.com/ubuntu"
32
CLOUD_ARCHIVE_KEY_ID = '5EDB1B62EC4926EA'
34
DISTRO_PROPOSED = ('deb http://archive.ubuntu.com/ubuntu/ %s-proposed '
35
'restricted main multiverse universe')
38
UBUNTU_OPENSTACK_RELEASE = OrderedDict([
39
('oneiric', 'diablo'),
41
('quantal', 'folsom'),
42
('raring', 'grizzly'),
44
('trusty', 'icehouse')
48
OPENSTACK_CODENAMES = OrderedDict([
52
('2013.1', 'grizzly'),
54
('2014.1', 'icehouse'),
58
SWIFT_CODENAMES = OrderedDict([
70
DEFAULT_LOOPBACK_SIZE = '5G'
74
juju_log("FATAL ERROR: %s" % msg, level='ERROR')
78
def get_os_codename_install_source(src):
79
'''Derive OpenStack release codename from a given installation source.'''
80
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
82
if src in ['distro', 'distro-proposed']:
84
rel = UBUNTU_OPENSTACK_RELEASE[ubuntu_rel]
86
e = 'Could not derive openstack release for '\
87
'this Ubuntu release: %s' % ubuntu_rel
91
if src.startswith('cloud:'):
92
ca_rel = src.split(':')[1]
93
ca_rel = ca_rel.split('%s-' % ubuntu_rel)[1].split('/')[0]
96
# Best guess match based on deb string provided
97
if src.startswith('deb') or src.startswith('ppa'):
98
for k, v in OPENSTACK_CODENAMES.iteritems():
103
def get_os_version_install_source(src):
104
codename = get_os_codename_install_source(src)
105
return get_os_version_codename(codename)
108
def get_os_codename_version(vers):
109
'''Determine OpenStack codename from version number.'''
111
return OPENSTACK_CODENAMES[vers]
113
e = 'Could not determine OpenStack codename for version %s' % vers
117
def get_os_version_codename(codename):
118
'''Determine OpenStack version number from codename.'''
119
for k, v in OPENSTACK_CODENAMES.iteritems():
122
e = 'Could not derive OpenStack version for '\
123
'codename: %s' % codename
127
def get_os_codename_package(package, fatal=True):
128
'''Derive OpenStack release codename from an installed package.'''
137
# the package is unknown to the current apt cache.
138
e = 'Could not determine version of package with no installation '\
139
'candidate: %s' % package
142
if not pkg.current_ver:
145
# package is known, but no version is currently installed.
146
e = 'Could not determine version of uninstalled package: %s' % package
149
vers = apt.upstream_version(pkg.current_ver.ver_str)
152
if 'swift' in pkg.name:
153
swift_vers = vers[:5]
154
if swift_vers not in SWIFT_CODENAMES:
155
# Deal with 1.10.0 upward
156
swift_vers = vers[:6]
157
return SWIFT_CODENAMES[swift_vers]
160
return OPENSTACK_CODENAMES[vers]
162
e = 'Could not determine OpenStack codename for version %s' % vers
166
def get_os_version_package(pkg, fatal=True):
167
'''Derive OpenStack version number from an installed package.'''
168
codename = get_os_codename_package(pkg, fatal=fatal)
174
vers_map = SWIFT_CODENAMES
176
vers_map = OPENSTACK_CODENAMES
178
for version, cname in vers_map.iteritems():
179
if cname == codename:
181
#e = "Could not determine OpenStack version for package: %s" % pkg
188
def os_release(package, base='essex'):
190
Returns OpenStack release codename from a cached global.
191
If the codename can not be determined from either an installed package or
192
the installation source, the earliest release supported by the charm should
198
os_rel = (get_os_codename_package(package, fatal=False) or
199
get_os_codename_install_source(config('openstack-origin')) or
204
def import_key(keyid):
205
cmd = "apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 " \
206
"--recv-keys %s" % keyid
208
subprocess.check_call(cmd.split(' '))
209
except subprocess.CalledProcessError:
210
error_out("Error importing repo key %s" % keyid)
213
def configure_installation_source(rel):
214
'''Configure apt installation source.'''
217
elif rel == 'distro-proposed':
218
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
219
with open('/etc/apt/sources.list.d/juju_deb.list', 'w') as f:
220
f.write(DISTRO_PROPOSED % ubuntu_rel)
221
elif rel[:4] == "ppa:":
223
subprocess.check_call(["add-apt-repository", "-y", src])
224
elif rel[:3] == "deb":
225
l = len(rel.split('|'))
227
src, key = rel.split('|')
228
juju_log("Importing PPA key from keyserver for %s" % src)
232
with open('/etc/apt/sources.list.d/juju_deb.list', 'w') as f:
234
elif rel[:6] == 'cloud:':
235
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
236
rel = rel.split(':')[1]
237
u_rel = rel.split('-')[0]
238
ca_rel = rel.split('-')[1]
240
if u_rel != ubuntu_rel:
241
e = 'Cannot install from Cloud Archive pocket %s on this Ubuntu '\
242
'version (%s)' % (ca_rel, ubuntu_rel)
245
if 'staging' in ca_rel:
246
# staging is just a regular PPA.
247
os_rel = ca_rel.split('/')[0]
248
ppa = 'ppa:ubuntu-cloud-archive/%s-staging' % os_rel
249
cmd = 'add-apt-repository -y %s' % ppa
250
subprocess.check_call(cmd.split(' '))
253
# map charm config options to actual archive pockets.
255
'folsom': 'precise-updates/folsom',
256
'folsom/updates': 'precise-updates/folsom',
257
'folsom/proposed': 'precise-proposed/folsom',
258
'grizzly': 'precise-updates/grizzly',
259
'grizzly/updates': 'precise-updates/grizzly',
260
'grizzly/proposed': 'precise-proposed/grizzly',
261
'havana': 'precise-updates/havana',
262
'havana/updates': 'precise-updates/havana',
263
'havana/proposed': 'precise-proposed/havana',
264
'icehouse': 'precise-updates/icehouse',
265
'icehouse/updates': 'precise-updates/icehouse',
266
'icehouse/proposed': 'precise-proposed/icehouse',
270
pocket = pockets[ca_rel]
272
e = 'Invalid Cloud Archive release specified: %s' % rel
275
src = "deb %s %s main" % (CLOUD_ARCHIVE_URL, pocket)
276
apt_install('ubuntu-cloud-keyring', fatal=True)
278
with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as f:
281
error_out("Invalid openstack-release specified: %s" % rel)
284
def save_script_rc(script_path="scripts/scriptrc", **env_vars):
286
Write an rc file in the charm-delivered directory containing
287
exported environment variables provided by env_vars. Any charm scripts run
288
outside the juju hook environment can source this scriptrc to obtain
289
updated config information necessary to perform health checks or
292
juju_rc_path = "%s/%s" % (charm_dir(), script_path)
293
if not os.path.exists(os.path.dirname(juju_rc_path)):
294
os.mkdir(os.path.dirname(juju_rc_path))
295
with open(juju_rc_path, 'wb') as rc_script:
298
[rc_script.write('export %s=%s\n' % (u, p))
299
for u, p in env_vars.iteritems() if u != "script_path"]
302
def openstack_upgrade_available(package):
304
Determines if an OpenStack upgrade is available from installation
305
source, based on version of installed package.
307
:param package: str: Name of installed package.
309
:returns: bool: : Returns True if configured installation source offers
310
a newer version of package.
314
src = config('openstack-origin')
315
cur_vers = get_os_version_package(package)
316
available_vers = get_os_version_install_source(src)
318
return apt.version_compare(available_vers, cur_vers) == 1
321
def ensure_block_device(block_device):
323
Confirm block_device, create as loopback if necessary.
325
:param block_device: str: Full path of block device to ensure.
327
:returns: str: Full path of ensured block device.
329
_none = ['None', 'none', None]
330
if (block_device in _none):
331
error_out('prepare_storage(): Missing required input: '
332
'block_device=%s.' % block_device, level=ERROR)
334
if block_device.startswith('/dev/'):
336
elif block_device.startswith('/'):
337
_bd = block_device.split('|')
342
size = DEFAULT_LOOPBACK_SIZE
343
bdev = ensure_loopback_device(bdev, size)
345
bdev = '/dev/%s' % block_device
347
if not is_block_device(bdev):
348
error_out('Failed to locate valid block device at %s' % bdev,
354
def clean_storage(block_device):
356
Ensures a block device is clean. That is:
358
- any lvm volume groups are deactivated
359
- any lvm physical device signatures removed
360
- partition table wiped
362
:param block_device: str: Full path to block device to clean.
364
for mp, d in mounts():
365
if d == block_device:
366
juju_log('clean_storage(): %s is mounted @ %s, unmounting.' %
368
umount(mp, persist=True)
370
if is_lvm_physical_volume(block_device):
371
deactivate_lvm_volume_group(block_device)
372
remove_lvm_physical_volume(block_device)
374
zap_disk(block_device)
379
Returns True if address is a valid IP address.
382
# Test to see if already an IPv4 address
383
socket.inet_aton(address)
389
def ns_query(address):
393
apt_install('python-dnspython')
396
if isinstance(address, dns.name.Name):
398
elif isinstance(address, basestring):
401
answers = dns.resolver.query(address, rtype)
403
return str(answers[0])
407
def get_host_ip(hostname):
409
Resolves the IP for a given hostname, or returns
410
the input if it is already an IP.
415
return ns_query(hostname)
418
def get_hostname(address, fqdn=True):
420
Resolves hostname for given IP, or returns the input
421
if it is already a hostname.
423
if not is_ip(address):
427
import dns.reversename
429
apt_install('python-dnspython')
430
import dns.reversename
432
rev = dns.reversename.from_address(address)
433
result = ns_query(rev)
439
if result.endswith('.'):
444
return result.split('.')[0]