9
from lib.openstack_common import(
6
from base64 import b64encode
7
from collections import OrderedDict
8
from copy import deepcopy
10
from charmhelpers.contrib.hahelpers.cluster import(
17
from charmhelpers.contrib.openstack import context, templating
19
from charmhelpers.contrib.openstack.utils import (
20
configure_installation_source,
10
22
get_os_codename_install_source,
11
get_os_codename_package,
13
configure_installation_source
24
save_script_rc as _save_script_rc)
26
import charmhelpers.contrib.unison as unison
28
from charmhelpers.core.hookenv import (
37
from charmhelpers.fetch import (
42
import keystone_context
16
43
import keystone_ssl as ssl
17
import lib.unison as unison
18
import lib.utils as utils
19
import lib.cluster_utils as cluster
22
keystone_conf = "/etc/keystone/keystone.conf"
23
stored_passwd = "/var/lib/keystone/keystone.passwd"
24
stored_token = "/var/lib/keystone/keystone.token"
45
TEMPLATES = 'templates/'
47
# removed from original: charm-helper-sh
52
'python-keystoneclient',
64
'keystone-admin': config('admin-port'),
65
'keystone-public': config('service-port')
68
KEYSTONE_CONF = "/etc/keystone/keystone.conf"
69
STORED_PASSWD = "/var/lib/keystone/keystone.passwd"
70
STORED_TOKEN = "/var/lib/keystone/keystone.token"
25
71
SERVICE_PASSWD_PATH = '/var/lib/keystone/services.passwd'
73
HAPROXY_CONF = '/etc/haproxy/haproxy.cfg'
74
APACHE_CONF = '/etc/apache2/sites-available/openstack_https_frontend'
75
APACHE_24_CONF = '/etc/apache2/sites-available/openstack_https_frontend.conf'
27
77
SSL_DIR = '/var/lib/keystone/juju_ssl/'
28
78
SSL_CA_NAME = 'Ubuntu Cloud'
29
79
CLUSTER_RES = 'res_ks_vip'
30
80
SSH_USER = 'juju_keystone'
33
def execute(cmd, die=False, echo=False):
34
""" Executes a command
36
if die=True, script will exit(1) if command does not return 0
37
if echo=True, output of command will be printed to stdout
39
returns a tuple: (stdout, stderr, return code)
41
p = subprocess.Popen(cmd.split(" "),
42
stdout=subprocess.PIPE,
43
stdin=subprocess.PIPE,
44
stderr=subprocess.PIPE)
53
for l in iter(p.stdout.readline, ''):
56
for l in iter(p.stderr.readline, ''):
64
error_out("ERROR: command %s return non-zero.\n" % cmd)
65
return (stdout, stderr, rc)
69
""" Obtain the units config via 'config-get'
70
Returns a dict representing current config.
71
private-address and IP of the unit is also tacked on for
74
output = execute("config-get --format json")[0]
75
config = json.loads(output)
76
# make sure no config element is blank after config-get
77
for c in config.keys():
79
error_out("ERROR: Config option has no paramter: %s" % c)
80
# tack on our private address and ip
81
config["hostname"] = utils.unit_get('private-address')
82
BASE_RESOURCE_MAP = OrderedDict([
84
'services': BASE_SERVICES,
85
'contexts': [keystone_context.KeystoneContext(),
86
context.SharedDBContext(),
87
context.SyslogContext(),
88
keystone_context.HAProxyContext()],
91
'contexts': [context.HAProxyContext(),
92
keystone_context.HAProxyContext()],
93
'services': ['haproxy'],
96
'contexts': [keystone_context.ApacheSSLContext()],
97
'services': ['apache2'],
100
'contexts': [keystone_context.ApacheSSLContext()],
101
'services': ['apache2'],
105
CA_CERT_PATH = '/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt'
110
"desc": "Nova Compute Service"
114
"desc": "Nova Volume Service"
118
"desc": "Cinder Volume Service"
122
"desc": "EC2 Compatibility Layer"
126
"desc": "Glance Image Service"
130
"desc": "S3 Compatible object-store"
133
"type": "object-store",
134
"desc": "Swift Object Storage Service"
138
"desc": "Quantum Networking Service"
142
"desc": "Oxygen Cloud Image Service"
146
"desc": "Ceilometer Metering Service"
149
"type": "orchestration",
150
"desc": "Heat Orchestration API"
153
"type": "cloudformation",
154
"desc": "Heat CloudFormation API"
160
Dynamically generate a map of resources that will be managed for a single
163
resource_map = deepcopy(BASE_RESOURCE_MAP)
165
if os.path.exists('/etc/apache2/conf-available'):
166
resource_map.pop(APACHE_CONF)
168
resource_map.pop(APACHE_24_CONF)
172
def register_configs():
173
release = os_release('keystone')
174
configs = templating.OSConfigRenderer(templates_dir=TEMPLATES,
175
openstack_release=release)
176
for cfg, rscs in resource_map().iteritems():
177
configs.register(cfg, rscs['contexts'])
182
return OrderedDict([(cfg, v['services'])
183
for cfg, v in resource_map().iteritems()
187
def determine_ports():
188
'''Assemble a list of API ports for services we are managing'''
189
ports = [config('admin-port'), config('service-port')]
190
return list(set(ports))
193
def api_port(service):
194
return API_PORTS[service]
197
def determine_packages():
198
# currently all packages match service names
199
packages = [] + BASE_PACKAGES
200
for k, v in resource_map().iteritems():
201
packages.extend(v['services'])
202
return list(set(packages))
205
def save_script_rc():
206
env_vars = {'OPENSTACK_SERVICE_KEYSTONE': 'keystone',
207
'OPENSTACK_PORT_ADMIN': determine_api_port(
208
api_port('keystone-admin')),
209
'OPENSTACK_PORT_PUBLIC': determine_api_port(
210
api_port('keystone-public'))}
211
_save_script_rc(**env_vars)
214
def do_openstack_upgrade(configs):
215
new_src = config('openstack-origin')
216
new_os_rel = get_os_codename_install_source(new_src)
217
log('Performing OpenStack upgrade to %s.' % (new_os_rel))
219
configure_installation_source(new_src)
223
'--option', 'Dpkg::Options::=--force-confnew',
224
'--option', 'Dpkg::Options::=--force-confdef',
227
apt_install(packages=determine_packages(), options=dpkg_opts, fatal=True)
229
# set CONFIGS to load templates from new release and regenerate config
230
configs.set_release(openstack_release=new_os_rel)
233
if eligible_leader(CLUSTER_RES):
236
def migrate_database():
237
'''Runs keystone-manage to initialize a new database or migrate existing'''
238
log('Migrating the keystone database.', level=INFO)
239
cmd = ['keystone-manage', 'db_sync']
240
subprocess.check_output(cmd)
86
245
def get_local_endpoint():
87
246
""" Returns the URL for the local end-point bypassing haproxy/ssl """
88
247
local_endpoint = 'http://localhost:{}/v2.0/'.format(
89
cluster.determine_api_port(utils.config_get('admin-port'))
248
determine_api_port(api_port('keystone-admin'))
91
250
return local_endpoint
94
def set_admin_token(admin_token):
253
def set_admin_token(admin_token='None'):
95
254
"""Set admin token according to deployment config or use a randomly
96
255
generated token if none is specified (default).
98
257
if admin_token != 'None':
99
utils.juju_log('INFO',
100
'Configuring Keystone to use'
101
' a pre-configured admin token.')
258
log('Configuring Keystone to use a pre-configured admin token.')
102
259
token = admin_token
104
utils.juju_log('INFO',
105
'Configuring Keystone to use a random admin token.')
106
if os.path.isfile(stored_token):
261
log('Configuring Keystone to use a random admin token.')
262
if os.path.isfile(STORED_TOKEN):
107
263
msg = 'Loading a previously generated' \
108
' admin token from %s' % stored_token
109
utils.juju_log('INFO', msg)
110
f = open(stored_token, 'r')
264
' admin token from %s' % STORED_TOKEN
266
f = open(STORED_TOKEN, 'r')
111
267
token = f.read().strip()
114
token = execute('pwgen -c 32 1', die=True)[0].strip()
115
out = open(stored_token, 'w')
270
cmd = ['pwgen', '-c', '32', '1']
271
token = str(subprocess.check_output(cmd)).strip()
272
out = open(STORED_TOKEN, 'w')
116
273
out.write('%s\n' % token)
118
update_config_block('DEFAULT', admin_token=token)
121
278
def get_admin_token():
122
279
"""Temporary utility to grab the admin token as configured in
125
with open(keystone_conf, 'r') as f:
282
with open(KEYSTONE_CONF, 'r') as f:
126
283
for l in f.readlines():
127
284
if l.split(' ')[0] == 'admin_token':
129
286
return l.split('=')[1].strip()
131
288
error_out('Could not parse admin_token line from %s' %
133
error_out('Could not find admin_token line in %s' % keystone_conf)
136
# Track all updated config settings.
137
_config_dirty = [False]
140
return True in _config_dirty
142
def update_config_block(section, **kwargs):
143
""" Updates keystone.conf blocks given kwargs.
144
Update a config setting in a specific setting of a config
145
file (/etc/keystone/keystone.conf, by default)
148
conf_file = kwargs['file']
151
conf_file = keystone_conf
152
config = ConfigParser.RawConfigParser()
153
config.read(conf_file)
155
if section != 'DEFAULT' and not config.has_section(section):
156
config.add_section(section)
157
_config_dirty[0] = True
159
for k, v in kwargs.iteritems():
161
cur = config.get(section, k)
163
_config_dirty[0] = True
164
except (ConfigParser.NoSectionError,
165
ConfigParser.NoOptionError):
166
_config_dirty[0] = True
167
config.set(section, k, v)
168
with open(conf_file, 'wb') as out:
290
error_out('Could not find admin_token line in %s' % KEYSTONE_CONF)
172
293
def create_service_entry(service_name, service_type, service_desc, owner=None):
337
434
create_tenant("admin")
338
create_tenant(config["service-tenant"])
435
create_tenant(config("service-tenant"))
341
if config["admin-password"] != "None":
342
passwd = config["admin-password"]
343
elif os.path.isfile(stored_passwd):
344
utils.juju_log('INFO', "Loading stored passwd from %s" % stored_passwd)
345
passwd = open(stored_passwd, 'r').readline().strip('\n')
438
if config("admin-password") != "None":
439
passwd = config("admin-password")
440
elif os.path.isfile(STORED_PASSWD):
441
log("Loading stored passwd from %s" % STORED_PASSWD)
442
passwd = open(STORED_PASSWD, 'r').readline().strip('\n')
347
utils.juju_log('INFO', "Generating new passwd for user: %s" % \
348
config["admin-user"])
349
passwd = execute("pwgen -c 16 1", die=True)[0]
350
open(stored_passwd, 'w+').writelines("%s\n" % passwd)
444
log("Generating new passwd for user: %s" % \
445
config("admin-user"))
446
cmd = ['pwgen', '-c', '16', '1']
447
passwd = str(subprocess.check_output(cmd)).strip()
448
open(STORED_PASSWD, 'w+').writelines("%s\n" % passwd)
352
create_user(config['admin-user'], passwd, tenant='admin')
353
update_user_password(config['admin-user'], passwd)
354
create_role(config['admin-role'], config['admin-user'], 'admin')
450
create_user(config('admin-user'), passwd, tenant='admin')
451
update_user_password(config('admin-user'), passwd)
452
create_role(config('admin-role'), config('admin-user'), 'admin')
355
453
# TODO(adam_g): The following roles are likely not needed since redux merge
356
create_role("KeystoneAdmin", config["admin-user"], 'admin')
357
create_role("KeystoneServiceAdmin", config["admin-user"], 'admin')
454
create_role("KeystoneAdmin", config("admin-user"), 'admin')
455
create_role("KeystoneServiceAdmin", config("admin-user"), 'admin')
358
456
create_service_entry("keystone", "identity", "Keystone Identity Service")
360
if cluster.is_clustered():
361
utils.juju_log('INFO', "Creating endpoint for clustered configuration")
362
service_host = auth_host = config["vip"]
459
log("Creating endpoint for clustered configuration")
460
service_host = auth_host = config("vip")
364
utils.juju_log('INFO', "Creating standard endpoint")
365
service_host = auth_host = config["hostname"]
462
log("Creating standard endpoint")
463
service_host = auth_host = unit_private_ip()
367
for region in config['region'].split():
465
for region in config('region').split():
368
466
create_keystone_endpoint(service_host=service_host,
369
service_port=config["service-port"],
467
service_port=config("service-port"),
370
468
auth_host=auth_host,
371
auth_port=config["admin-port"],
469
auth_port=config("admin-port"),
375
473
def create_keystone_endpoint(service_host, service_port,
376
474
auth_host, auth_port, region):
377
public_url = "http://%s:%s/v2.0" % (service_host, service_port)
378
admin_url = "http://%s:%s/v2.0" % (auth_host, auth_port)
379
internal_url = "http://%s:%s/v2.0" % (service_host, service_port)
477
log("Setting https keystone endpoint")
479
public_url = "%s://%s:%s/v2.0" % (proto, service_host, service_port)
480
admin_url = "%s://%s:%s/v2.0" % (proto, auth_host, auth_port)
481
internal_url = "%s://%s:%s/v2.0" % (proto, service_host, service_port)
380
482
create_endpoint_template(region, "keystone", public_url,
381
483
admin_url, internal_url)
428
def configure_pki_tokens(config):
429
'''Configure PKI token signing, if enabled.'''
430
if config['enable-pki'] not in ['True', 'true']:
431
update_config_block('signing', token_format='UUID')
433
utils.juju_log('INFO', 'TODO: PKI Support, setting to UUID for now.')
434
update_config_block('signing', token_format='UUID')
437
def do_openstack_upgrade(install_src, packages):
438
'''Upgrade packages from a given install src.'''
440
config = config_get()
441
old_vers = get_os_codename_package('keystone')
442
new_vers = get_os_codename_install_source(install_src)
444
utils.juju_log('INFO',
445
"Beginning Keystone upgrade: %s -> %s" % \
446
(old_vers, new_vers))
448
# Backup previous config.
449
utils.juju_log('INFO', "Backing up contents of /etc/keystone.")
450
stamp = time.strftime('%Y%m%d%H%M')
451
cmd = 'tar -pcf /var/lib/juju/keystone-backup-%s.tar /etc/keystone' % stamp
452
execute(cmd, die=True, echo=True)
454
configure_installation_source(install_src)
455
execute('apt-get update', die=True, echo=True)
456
os.environ['DEBIAN_FRONTEND'] = 'noninteractive'
457
cmd = 'apt-get --option Dpkg::Options::=--force-confnew -y '\
458
'install %s' % packages
459
execute(cmd, echo=True, die=True)
461
# we have new, fresh config files that need updating.
462
# set the admin token, which is still stored in config.
463
set_admin_token(config['admin-token'])
465
# set the sql connection string if a shared-db relation is found.
466
ids = utils.relation_ids('shared-db')
470
for unit in utils.relation_list(rid):
471
utils.juju_log('INFO',
472
'Configuring new keystone.conf for '
473
'database access on existing database'
474
' relation to %s' % unit)
475
relation_data = utils.relation_get_dict(relation_id=rid,
478
update_config_block('sql', connection="mysql://%s:%s@%s/%s" %
479
(config["database-user"],
480
relation_data["password"],
481
relation_data["private-address"],
484
utils.stop('keystone')
485
if (cluster.eligible_leader(CLUSTER_RES)):
486
utils.juju_log('INFO',
487
'Running database migrations for %s' % new_vers)
488
execute('keystone-manage db_sync', echo=True, die=True)
490
utils.juju_log('INFO',
491
'Not cluster leader; snoozing whilst'
492
' leader upgrades DB')
494
utils.start('keystone')
496
utils.juju_log('INFO',
497
'Completed Keystone upgrade: '
498
'%s -> %s' % (old_vers, new_vers))
501
530
def synchronize_service_credentials():
503
532
Broadcast service credentials to peers or consume those that have been
504
533
broadcasted by peer, depending on hook context.
506
if (not cluster.eligible_leader(CLUSTER_RES) or
535
if (not eligible_leader(CLUSTER_RES) or
507
536
not os.path.isfile(SERVICE_PASSWD_PATH)):
509
utils.juju_log('INFO', 'Synchronizing service passwords to all peers.')
510
unison.sync_to_peers(peer_interface='cluster',
511
paths=[SERVICE_PASSWD_PATH], user=SSH_USER,
538
log('Synchronizing service passwords to all peers.')
540
unison.sync_to_peers(peer_interface='cluster',
541
paths=[SERVICE_PASSWD_PATH], user=SSH_USER,
530
560
'%s_root_ca' % d_name))
531
561
# SSL_DIR is synchronized via all peers over unison+ssh, need
532
562
# to ensure permissions.
533
execute('chown -R %s.%s %s' % (user, group, SSL_DIR))
534
execute('chmod -R g+rwx %s' % SSL_DIR)
563
subprocess.check_output(['chown', '-R', '%s.%s' % (user, group),
565
subprocess.check_output(['chmod', '-R', 'g+rwx', '%s' % SSL_DIR])
540
if (utils.config_get('https-service-endpoints') in ["yes", "true", "True"]
570
def relation_list(rid):
575
result = str(subprocess.check_output(cmd)).split()
581
def add_service_to_keystone():
582
settings = relation_get()
583
# the minimum settings needed per endpoint
584
single = set(['service', 'region', 'public_url', 'admin_url',
586
if single.issubset(settings):
587
# other end of relation advertised only one endpoint
588
if 'None' in [v for k, v in settings.iteritems()]:
589
# Some backend services advertise no endpoint but require a
590
# hook execution to update auth strategy.
592
# Check if clustered and use vip + haproxy ports if so
594
relation_data["auth_host"] = config('vip')
595
relation_data["service_host"] = config('vip')
597
relation_data["auth_host"] = config('hostname')
598
relation_data["service_host"] = config('hostname')
599
relation_data["auth_port"] = config('admin-port')
600
relation_data["service_port"] = config('service-port')
601
if config('https-service-endpoints') in ['True', 'true']:
602
# Pass CA cert as client will need it to
603
# verify https connections
604
ca = get_ca(user=SSH_USER)
605
ca_bundle = ca.get_ca_bundle()
606
relation_data['https_keystone'] = 'True'
607
relation_data['ca_cert'] = b64encode(ca_bundle)
608
# Allow the remote service to request creation of any additional
609
# roles. Currently used by Horizon
610
for role in get_requested_roles(settings):
611
log("Creating requested role: %s" % role)
613
relation_set(**relation_data)
616
ensure_valid_service(settings['service'])
617
add_endpoint(region=settings['region'],
618
service=settings['service'],
619
publicurl=settings['public_url'],
620
adminurl=settings['admin_url'],
621
internalurl=settings['internal_url'])
622
service_username = settings['service']
623
https_cn = urlparse.urlparse(settings['internal_url'])
624
https_cn = https_cn.hostname
626
# assemble multiple endpoints from relation data. service name
627
# should be prepended to setting name, ie:
628
# realtion-set ec2_service=$foo ec2_region=$foo ec2_public_url=$foo
629
# relation-set nova_service=$foo nova_region=$foo nova_public_url=$foo
630
# Results in a dict that looks like:
643
for k, v in settings.iteritems():
645
x = '_'.join(k.split('_')[1:])
646
if ep not in endpoints:
652
# weed out any unrelated relation stuff Juju might have added
653
# by ensuring each possible endpiont has appropriate fields
654
# ['service', 'region', 'public_url', 'admin_url', 'internal_url']
655
if single.issubset(endpoints[ep]):
656
ensure_valid_service(ep['service'])
658
add_endpoint(region=ep['region'], service=ep['service'],
659
publicurl=ep['public_url'],
660
adminurl=ep['admin_url'],
661
internalurl=ep['internal_url'])
662
services.append(ep['service'])
664
https_cn = urlparse.urlparse(ep['internal_url'])
665
https_cn = https_cn.hostname
666
service_username = '_'.join(services)
668
if 'None' in [v for k, v in settings.iteritems()]:
671
if not service_username:
674
token = get_admin_token()
675
log("Creating service credentials for '%s'" % service_username)
677
service_password = get_service_password(service_username)
678
create_user(service_username, service_password, config('service-tenant'))
679
grant_role(service_username, config('admin-role'),
680
config('service-tenant'))
682
# Allow the remote service to request creation of any additional roles.
683
# Currently used by Swift and Ceilometer.
684
for role in get_requested_roles(settings):
685
log("Creating requested role: %s" % role)
686
create_role(role, service_username,
687
config('service-tenant'))
689
# As of https://review.openstack.org/#change,4675, all nodes hosting
690
# an endpoint(s) needs a service username and password assigned to
691
# the service tenant and granted admin role.
692
# note: config('service-tenant') is created in utils.ensure_initial_admin()
693
# we return a token, information about our API endpoints, and the generated
694
# service credentials
696
"admin_token": token,
697
"service_host": config("hostname"),
698
"service_port": config("service-port"),
699
"auth_host": config("hostname"),
700
"auth_port": config("admin-port"),
701
"service_username": service_username,
702
"service_password": service_password,
703
"service_tenant": config('service-tenant'),
704
"https_keystone": "False",
710
# Check if clustered and use vip + haproxy ports if so
712
relation_data["auth_host"] = config('vip')
713
relation_data["service_host"] = config('vip')
715
# generate or get a new cert/key for service if set to manage certs.
716
if config('https-service-endpoints') in ['True', 'true']:
717
ca = get_ca(user=SSH_USER)
718
cert, key = ca.get_cert_and_key(common_name=https_cn)
719
ca_bundle = ca.get_ca_bundle()
720
relation_data['ssl_cert'] = b64encode(cert)
721
relation_data['ssl_key'] = b64encode(key)
722
relation_data['ca_cert'] = b64encode(ca_bundle)
723
relation_data['https_keystone'] = 'True'
725
unison.sync_to_peers(peer_interface='cluster',
726
paths=[SSL_DIR], user=SSH_USER, verbose=True)
727
relation_set(**relation_data)
730
def ensure_valid_service(service):
731
if service not in valid_services.keys():
732
log("Invalid service requested: '%s'" % service)
733
relation_set(admin_token=-1)
737
def add_endpoint(region, service, publicurl, adminurl, internalurl):
738
desc = valid_services[service]["desc"]
739
service_type = valid_services[service]["type"]
740
create_service_entry(service, service_type, desc)
741
create_endpoint_template(region=region, service=service,
744
internalurl=internalurl)
747
def get_requested_roles(settings):
748
''' Retrieve any valid requested_roles from dict settings '''
749
if ('requested_roles' in settings and
750
settings['requested_roles'] not in ['None', None]):
751
return settings['requested_roles'].split(',')