/
keystone_utils.py
2378 lines (2010 loc) · 82.2 KB
/
keystone_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright 2016 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import shutil
import subprocess
import tempfile
import time
import urllib.parse
import uuid
from itertools import chain
from collections import OrderedDict
from copy import deepcopy
from charmhelpers.contrib.hahelpers.cluster import (
is_elected_leader,
determine_api_port,
https,
get_hacluster_config,
)
from charmhelpers.contrib.openstack import context, templating
from charmhelpers.contrib.network.ip import (
is_ipv6,
get_ipv6_addr
)
from charmhelpers.contrib.openstack.ha.utils import (
expect_ha,
)
from charmhelpers.contrib.openstack.ip import (
resolve_address,
PUBLIC,
INTERNAL,
ADMIN
)
from charmhelpers.contrib.openstack.utils import (
configure_installation_source,
error_out,
get_os_codename_install_source,
os_release,
save_script_rc as _save_script_rc,
pause_unit,
resume_unit,
make_assess_status_func,
os_application_version_set,
CompareOpenStackReleases,
reset_os_release,
snap_install_requested,
install_os_snaps,
get_snaps_install_info_from_origin,
enable_memcache,
is_unit_paused_set,
)
from charmhelpers.core.decorators import (
retry_on_exception,
)
from charmhelpers.core.hookenv import (
atexit,
cached,
config,
expected_peer_units,
expected_related_units,
is_leader,
leader_get,
leader_set,
log,
local_unit,
metadata,
relation_get,
relation_set,
relation_id,
relation_ids,
related_units,
DEBUG,
INFO,
ERROR,
WARNING,
status_set,
)
from charmhelpers.fetch import (
apt_install,
apt_update,
apt_upgrade,
apt_purge,
apt_autoremove,
add_source,
filter_missing_packages,
)
from charmhelpers.core.host import (
mkdir,
service_restart,
service_stop,
service_start,
pwgen,
lsb_release,
CompareHostReleases,
write_file,
)
from charmhelpers.contrib.peerstorage import (
peer_store_and_set,
)
import keystone_context
import uds_comms as uds
TEMPLATES = 'templates/'
# removed from original: charm-helper-sh
BASE_PACKAGES = [
'apache2',
'haproxy',
'keystone',
'openssl',
'python-keystoneclient',
'python-mysqldb',
'python-psycopg2',
'python3-six',
'pwgen',
'uuid',
]
PY3_PACKAGES = [
'python3-keystone',
'python3-keystoneclient',
'python3-memcache',
'python3-six',
'libapache2-mod-wsgi-py3',
]
BASE_PACKAGES_SNAP = [
'haproxy',
'openssl',
'python3-six',
'pwgen',
'uuid',
]
VERSION_PACKAGE = 'keystone'
if snap_install_requested():
SNAP_BASE_DIR = "/snap/keystone/current"
SNAP_COMMON_DIR = "/var/snap/keystone/common"
SNAP_COMMON_ETC_DIR = "{}/etc".format(SNAP_COMMON_DIR)
SNAP_COMMON_KEYSTONE_DIR = "{}/keystone".format(SNAP_COMMON_ETC_DIR)
KEYSTONE_USER = 'root'
KEYSTONE_CONF = ('{}/keystone.conf.d/keystone.conf'
''.format(SNAP_COMMON_KEYSTONE_DIR))
KEYSTONE_CONF_DIR = os.path.dirname(KEYSTONE_CONF)
KEYSTONE_NGINX_SITE_CONF = ("{}/nginx/sites-enabled/keystone-nginx.conf"
"".format(SNAP_COMMON_ETC_DIR))
KEYSTONE_NGINX_CONF = "{}/nginx/nginx.conf".format(SNAP_COMMON_ETC_DIR)
KEYSTONE_LOGGER_CONF = "{}/logging.conf".format(SNAP_COMMON_KEYSTONE_DIR)
SNAP_LIB_DIR = '{}/lib'.format(SNAP_COMMON_DIR)
STORED_PASSWD = "{}/keystone.passwd".format(SNAP_LIB_DIR)
STORED_TOKEN = "{}/keystone.token".format(SNAP_LIB_DIR)
STORED_ADMIN_DOMAIN_ID = ("{}/keystone.admin_domain_id"
"".format(SNAP_LIB_DIR))
STORED_DEFAULT_DOMAIN_ID = ("{}/keystone.default_domain_id"
"".format(SNAP_LIB_DIR))
SERVICE_PASSWD_PATH = '{}/services.passwd'.format(SNAP_LIB_DIR)
POLICY_JSON = ('{}/keystone.conf.d/policy.json'
''.format(SNAP_COMMON_KEYSTONE_DIR))
BASE_SERVICES = ['snap.keystone.uwsgi', 'snap.keystone.nginx']
else:
APACHE_SSL_DIR = '/etc/apache2/ssl/keystone'
KEYSTONE_USER = 'keystone'
KEYSTONE_CONF = "/etc/keystone/keystone.conf"
KEYSTONE_NGINX_CONF = None
KEYSTONE_NGINX_SITE_CONF = None
KEYSTONE_LOGGER_CONF = "/etc/keystone/logging.conf"
KEYSTONE_CONF_DIR = os.path.dirname(KEYSTONE_CONF)
STORED_PASSWD = "/var/lib/keystone/keystone.passwd"
STORED_TOKEN = "/var/lib/keystone/keystone.token"
STORED_ADMIN_DOMAIN_ID = "/var/lib/keystone/keystone.admin_domain_id"
STORED_DEFAULT_DOMAIN_ID = "/var/lib/keystone/keystone.default_domain_id"
SERVICE_PASSWD_PATH = '/var/lib/keystone/services.passwd'
POLICY_JSON = '/etc/keystone/policy.json'
BASE_SERVICES = [
'keystone',
]
HAPROXY_CONF = '/etc/haproxy/haproxy.cfg'
APACHE_CONF = '/etc/apache2/sites-available/openstack_https_frontend'
APACHE_24_CONF = '/etc/apache2/sites-available/openstack_https_frontend.conf'
MEMCACHED_CONF = '/etc/memcached.conf'
CLUSTER_RES = 'grp_ks_vips'
ADMIN_DOMAIN = 'admin_domain'
ADMIN_PROJECT = 'admin'
DEFAULT_DOMAIN = 'default'
SERVICE_DOMAIN = 'service_domain'
TOKEN_FLUSH_CRON_FILE = '/etc/cron.d/keystone-token-flush'
KEY_SETUP_FILE = '/etc/keystone/key-setup'
CREDENTIAL_KEY_REPOSITORY = '/etc/keystone/credential-keys/'
FERNET_KEY_REPOSITORY = '/etc/keystone/fernet-keys/'
FERNET_KEY_ROTATE_SYNC_CRON_FILE = '/etc/cron.d/keystone-fernet-rotate-sync'
WSGI_KEYSTONE_API_CONF = '/etc/apache2/sites-enabled/wsgi-openstack-api.conf'
UNUSED_APACHE_SITE_FILES = ['/etc/apache2/sites-enabled/keystone.conf',
'/etc/apache2/sites-enabled/wsgi-keystone.conf']
BASE_RESOURCE_MAP = OrderedDict([
(KEYSTONE_CONF, {
'services': BASE_SERVICES,
'contexts': [keystone_context.KeystoneContext(),
context.SharedDBContext(ssl_dir=KEYSTONE_CONF_DIR),
context.SyslogContext(),
keystone_context.HAProxyContext(),
context.BindHostContext(),
context.WorkerConfigContext(),
context.MemcacheContext(package='keystone'),
keystone_context.KeystoneFIDServiceProviderContext(),
keystone_context.WebSSOTrustedDashboardContext(),
keystone_context.context.SubordinateConfigContext(
interface=['keystone-middleware'],
service='keystone',
config_file=KEYSTONE_CONF),
keystone_context.MiddlewareContext(),
keystone_context.AuthMethods()]
}),
(KEYSTONE_LOGGER_CONF, {
'contexts': [keystone_context.KeystoneLoggingContext()],
'services': BASE_SERVICES,
}),
(HAPROXY_CONF, {
'contexts': [context.HAProxyContext(singlenode_mode=True),
keystone_context.HAProxyContext()],
'services': ['haproxy'],
}),
(KEYSTONE_NGINX_CONF, {
'services': BASE_SERVICES,
'contexts': [keystone_context.KeystoneContext(),
keystone_context.NginxSSLContext(),
context.SharedDBContext(ssl_dir=KEYSTONE_CONF_DIR),
context.SyslogContext(),
keystone_context.HAProxyContext(),
context.BindHostContext(),
context.WorkerConfigContext()],
}),
(KEYSTONE_NGINX_SITE_CONF, {
'services': BASE_SERVICES,
'contexts': [keystone_context.KeystoneContext(),
context.SharedDBContext(ssl_dir=KEYSTONE_CONF_DIR),
context.SyslogContext(),
keystone_context.HAProxyContext(),
keystone_context.NginxSSLContext(),
context.BindHostContext(),
context.WorkerConfigContext()],
}),
(APACHE_CONF, {
'contexts': [keystone_context.ApacheSSLContext()],
'services': ['apache2'],
}),
(APACHE_24_CONF, {
'contexts': [keystone_context.ApacheSSLContext()],
'services': ['apache2'],
}),
(POLICY_JSON, {
'contexts': [keystone_context.KeystoneContext()],
'services': BASE_SERVICES,
}),
(TOKEN_FLUSH_CRON_FILE, {
'contexts': [keystone_context.TokenFlushContext(),
context.SyslogContext()],
'services': [],
}),
(FERNET_KEY_ROTATE_SYNC_CRON_FILE, {
'contexts': [keystone_context.FernetCronContext(),
context.SyslogContext()],
'services': [],
}),
])
valid_services = {
"nova": {
"type": "compute",
"desc": "Nova Compute Service"
},
"nova-volume": {
"type": "volume",
"desc": "Nova Volume Service"
},
"cinder": {
"type": "volume",
"desc": "Cinder Volume Service v1"
},
"cinderv2": {
"type": "volumev2",
"desc": "Cinder Volume Service v2"
},
"cinderv3": {
"type": "volumev3",
"desc": "Cinder Volume Service v3"
},
"contrail-api": {
"type": "ApiServer",
"desc": "Contrail API Service"
},
"contrail-analytics": {
"type": "OpServer",
"desc": "Contrail Analytics Service"
},
"dmapi": {
"type": "datamover",
"desc": "Trilio DataMover API Service"
},
"ec2": {
"type": "ec2",
"desc": "EC2 Compatibility Layer"
},
"glance": {
"type": "image",
"desc": "Glance Image Service"
},
"s3": {
"type": "s3",
"desc": "S3 Compatible object-store"
},
"swift": {
"type": "object-store",
"desc": "Swift Object Storage Service"
},
"quantum": {
"type": "network",
"desc": "Quantum Networking Service"
},
"neutron": {
"type": "network",
"desc": "Neutron Networking Service"
},
"oxygen": {
"type": "oxygen",
"desc": "Oxygen Cloud Image Service"
},
"ceilometer": {
"type": "metering",
"desc": "Ceilometer Metering Service"
},
"heat": {
"type": "orchestration",
"desc": "Heat Orchestration API"
},
"heat-cfn": {
"type": "cloudformation",
"desc": "Heat CloudFormation API"
},
"image-stream": {
"type": "product-streams",
"desc": "Ubuntu Product Streams"
},
"midonet": {
"type": "network-overlay",
"desc": "MidoNet low-level API"
},
"cloudkitty": {
"type": "rating",
"desc": "CloudKitty Rating API"
},
"ironic": {
"type": "baremetal",
"desc": "Ironic bare metal provisioning service"
},
"designate": {
"type": "dns",
"desc": "Designate DNS service"
},
"astara": {
"type": "astara",
"desc": "Astara Network Orchestration Service",
},
"aodh": {
"type": "alarming",
"desc": "Aodh Alarming Service",
},
"gnocchi": {
"type": "metric",
"desc": "Gnocchi Metric Service",
},
"panko": {
"type": "event",
"desc": "Panko Event Service",
},
"barbican": {
"type": "key-manager",
"desc": "Barbican secrets management service"
},
"congress": {
"type": "policy",
"desc": "Congress policy management service"
},
"trove": {
"type": "database",
"desc": "Database as a service"
},
"manila": {
"type": "share",
"desc": "Shared Filesystem service"
},
"manilav2": {
"type": "sharev2",
"desc": "Shared Filesystem service v2"
},
"murano": {
"type": "application-catalog",
"desc": "Application Catalog for OpenStack"
},
"mistral": {
"type": "workflowv2",
"desc": "Workflow Service for OpenStack"
},
"zaqar": {
"type": "messaging",
"desc": "Messaging Service for OpenStack"
},
"placement": {
"type": "placement",
"desc": "Nova Placement Service"
},
"octavia": {
"type": "load-balancer",
"desc": "Octavia Load Balancer as a Service for OpenStack",
},
"masakari": {
"type": "instance-ha",
"desc": "Masakari instance HA for Openstack"
},
}
# The interface is said to be satisfied if anyone of the interfaces in the
# list has a complete context.
REQUIRED_INTERFACES = {
'database': ['shared-db'],
}
def filter_null(settings, null='__null__'):
"""Replace null values with None in provided settings dict.
When storing values in the peer relation, it might be necessary at some
future point to flush these values. We therefore need to use a real
(non-None or empty string) value to represent an unset settings. This value
then needs to be converted to None when applying to a non-cluster relation
so that the value is actually unset.
"""
filtered = {}
for k, v in settings.items():
if v == null:
filtered[k] = None
else:
filtered[k] = v
return filtered
def resource_map():
"""Dynamically generate a map of resources that will be managed for a
single hook execution.
"""
resource_map = deepcopy(BASE_RESOURCE_MAP)
release = os_release('keystone')
if CompareOpenStackReleases(release) < 'liberty':
resource_map.pop(POLICY_JSON)
if os.path.exists('/etc/apache2/conf-available'):
resource_map.pop(APACHE_CONF)
else:
resource_map.pop(APACHE_24_CONF)
if snap_install_requested():
if APACHE_CONF in resource_map:
resource_map.pop(APACHE_CONF)
if APACHE_24_CONF in resource_map:
resource_map.pop(APACHE_24_CONF)
else:
if KEYSTONE_NGINX_CONF in resource_map:
resource_map.pop(KEYSTONE_NGINX_CONF)
if KEYSTONE_NGINX_SITE_CONF in resource_map:
resource_map.pop(KEYSTONE_NGINX_SITE_CONF)
if snap_install_requested():
for cfile in resource_map:
svcs = resource_map[cfile]['services']
if 'apache2' in svcs:
svcs.remove('apache2')
if 'keystone' in svcs:
svcs.remove('keystone')
svcs.append('snap.keystone.nginx')
svcs.append('snap.keystone.uwsgi')
if run_in_apache():
if not snap_install_requested():
for cfile in resource_map:
svcs = resource_map[cfile]['services']
if 'keystone' in svcs:
svcs.remove('keystone')
if 'apache2' not in svcs:
svcs.append('apache2')
resource_map[WSGI_KEYSTONE_API_CONF] = {
'contexts': [
context.WSGIWorkerConfigContext(
name="keystone",
admin_script='/usr/bin/keystone-wsgi-admin',
public_script='/usr/bin/keystone-wsgi-public'),
keystone_context.KeystoneContext()],
'services': ['apache2']
}
if enable_memcache(release=release):
resource_map[MEMCACHED_CONF] = {
'contexts': [context.MemcacheContext()],
'services': ['memcached']}
return resource_map
def restart_pid_check(service_name, ptable_string=None):
"""Stop a service, check the processes are gone, start service
@param service_name: service name as init system knows it
@param ptable_string: string to look for in process table to match service
"""
@retry_on_exception(5, base_delay=3, exc_type=AssertionError)
def check_pids_gone(svc_string):
log("Checking no pids for {} exist".format(svc_string), level=INFO)
assert(subprocess.call(["pgrep", svc_string, "--nslist", "pid",
"--ns", str(os.getpid())]) == 1)
if not ptable_string:
ptable_string = service_name
service_stop(service_name)
check_pids_gone(ptable_string)
service_start(service_name)
def restart_function_map():
"""Return a dict of services with any custom functions that should be
used to restart that service
:returns: dict of {'svc1': restart_func, 'svc2', other_func, ...}
:rtype: Dict[str, Callable]
"""
rfunc_map = {}
rfunc_map[keystone_service()] = restart_keystone
return rfunc_map
def restart_keystone(*args):
"""Restart the keystone process.
This will either keystone or apache2 depending on OpenStack version.
Also stop the ManagerServer (and thus manager.py script) which will
reconnect to keystone on next usage of the ManagerServer.
Note, as restart_keystone is used in the restart_functions map, when it is
called it is passed the service name. However, this function determines
the actual service name to call, so that is discarded, hence the *args in
the function signature.
"""
if not is_unit_paused_set():
if snap_install_requested():
service_restart('snap.keystone.*')
else:
if run_in_apache():
restart_pid_check(keystone_service())
else:
service_restart(keystone_service())
stop_manager_instance()
def run_in_apache(release=None):
"""Return true if keystone API is run under apache2 with mod_wsgi in
this release.
"""
release = release or os_release('keystone')
return (CompareOpenStackReleases(release) >= 'liberty' and
not snap_install_requested())
def disable_unused_apache_sites():
"""Ensure that unused apache configurations are disabled to prevent them
from conflicting with the charm-provided version.
"""
for apache_site_file in UNUSED_APACHE_SITE_FILES:
apache_site = apache_site_file.split('/')[-1].split('.')[0]
if os.path.exists(apache_site_file):
try:
# Try it cleanly
log('Disabling unused apache configs')
status_set('maintenance', 'Disabling unused apache configs')
subprocess.check_call(['a2dissite', apache_site])
except subprocess.CalledProcessError:
# Remove the file
os.remove(apache_site_file)
def register_configs():
release = os_release('keystone')
configs = templating.OSConfigRenderer(templates_dir=TEMPLATES,
openstack_release=release)
for cfg, rscs in resource_map().items():
configs.register(cfg, rscs['contexts'])
return configs
def restart_map():
restart_map = OrderedDict([(cfg, v['services'])
for cfg, v in resource_map().items()
if v['services']])
if os.path.isdir(APACHE_SSL_DIR):
restart_map['{}/*'.format(APACHE_SSL_DIR)] = ['apache2']
return restart_map
def services():
"""Returns a list of (unique) services associated with this charm"""
return list(set(chain(*restart_map().values())))
def determine_ports():
"""Assemble a list of API ports for services we are managing"""
ports = [config('admin-port'), config('service-port')]
return sorted(list(set(ports)))
def api_port(service):
return {
'keystone-admin': config('admin-port'),
'keystone-public': config('service-port')
}[service]
def determine_packages():
release = CompareOpenStackReleases(os_release('keystone'))
# currently all packages match service names
if snap_install_requested():
pkgs = deepcopy(BASE_PACKAGES_SNAP)
if enable_memcache(release=os_release('keystone')):
pkgs = pkgs + ['memcached']
return sorted(pkgs)
else:
packages = set(services()).union(BASE_PACKAGES)
if release >= 'rocky':
packages = [p for p in packages if not p.startswith('python-')]
packages.extend(PY3_PACKAGES)
elif run_in_apache():
packages.add('libapache2-mod-wsgi')
return sorted(packages)
def determine_purge_packages():
'''
Determine list of packages that where previously installed which are no
longer needed.
:returns: list of package names
'''
release = CompareOpenStackReleases(os_release('keystone'))
if release >= 'rocky':
pkgs = [p for p in BASE_PACKAGES if p.startswith('python-')]
pkgs.extend(['python-keystone', 'python-memcache'])
return pkgs
return []
def remove_old_packages():
'''Purge any packages that need to be removed.
:returns: bool Whether packages were removed.
'''
installed_packages = filter_missing_packages(determine_purge_packages())
if installed_packages:
log('Removing apt packages')
status_set('maintenance', 'Removing apt packages')
apt_purge(installed_packages, fatal=True)
apt_autoremove(purge=True, fatal=True)
return bool(installed_packages)
def save_script_rc():
env_vars = {'OPENSTACK_SERVICE_KEYSTONE': 'keystone',
'OPENSTACK_PORT_ADMIN': determine_api_port(
api_port('keystone-admin'), singlenode_mode=True),
'OPENSTACK_PORT_PUBLIC': determine_api_port(
api_port('keystone-public'),
singlenode_mode=True)}
_save_script_rc(**env_vars)
def do_openstack_upgrade_reexec(configs):
do_openstack_upgrade(configs)
log("Re-execing hook to pickup upgraded packages", level=INFO)
os.execl('/usr/bin/env', 'python3', './hooks/config-changed-postupgrade')
def do_openstack_upgrade(configs):
new_src = config('openstack-origin')
new_os_rel = get_os_codename_install_source(new_src)
log('Performing OpenStack upgrade to %s.' % (new_os_rel))
if not snap_install_requested():
configure_installation_source(new_src)
apt_update()
dpkg_opts = [
'--option', 'Dpkg::Options::=--force-confnew',
'--option', 'Dpkg::Options::=--force-confdef',
]
apt_upgrade(options=dpkg_opts, fatal=True, dist=True)
reset_os_release()
apt_install(packages=determine_packages(),
options=dpkg_opts, fatal=True)
remove_old_packages()
else:
# TODO: Add support for upgrade from deb->snap
# NOTE(thedac): Setting devmode until LP#1719636 is fixed
install_os_snaps(
get_snaps_install_info_from_origin(
['keystone'],
new_src,
mode='devmode'),
refresh=True)
post_snap_install()
reset_os_release()
# set CONFIGS to load templates from new release and regenerate config
configs.set_release(openstack_release=new_os_rel)
configs.write_all()
if run_in_apache():
disable_unused_apache_sites()
if is_elected_leader(CLUSTER_RES):
if is_db_ready():
migrate_database()
else:
log("Database not ready - deferring to shared-db relation",
level=INFO)
def is_db_initialised():
if leader_get('db-initialised'):
log("Database is initialised", level=DEBUG)
return True
log("Database is NOT initialised", level=DEBUG)
return False
def keystone_service():
return {True: 'apache2', False: 'keystone'}[run_in_apache()]
# NOTE(jamespage): Retry deals with sync issues during one-shot HA deploys.
# mysql might be restarting or suchlike.
@retry_on_exception(5, base_delay=3, exc_type=subprocess.CalledProcessError)
def migrate_database():
"""Runs keystone-manage to initialize a new database or migrate existing"""
log('Migrating the keystone database.', level=INFO)
status_set('maintenance', 'Migrating the keystone database')
if snap_install_requested():
service_stop('snap.keystone.*')
else:
service_stop(keystone_service())
# NOTE(jamespage) > icehouse creates a log file as root so use
# sudo to execute as keystone otherwise keystone won't start
# afterwards.
# NOTE(coreycb): Can just use keystone-manage when snap has alias support.
# Also can run as keystone once snap has drop privs support.
if snap_install_requested():
cmd = ['/snap/bin/keystone-manage', 'db_sync']
else:
cmd = ['sudo', '-u', 'keystone', 'keystone-manage', 'db_sync']
subprocess.check_output(cmd)
if snap_install_requested():
service_start('snap.keystone.nginx')
service_start('snap.keystone.uwsgi')
else:
service_start(keystone_service())
time.sleep(10)
leader_set({'db-initialised': True})
stop_manager_instance()
# OLD
def get_api_suffix():
return 'v2.0' if get_api_version() == 2 else 'v3'
def get_local_endpoint(api_suffix=None):
"""Returns the URL for the local end-point bypassing haproxy/ssl"""
if not api_suffix:
api_suffix = get_api_suffix()
keystone_port = determine_api_port(api_port('keystone-admin'),
singlenode_mode=True)
if config('prefer-ipv6'):
ipv6_addr = get_ipv6_addr(exc_list=[config('vip')])[0]
local_endpoint = 'http://[{}]:{}/{}/'.format(
ipv6_addr,
keystone_port,
api_suffix)
else:
local_endpoint = 'http://localhost:{}/{}/'.format(
keystone_port,
api_suffix)
return local_endpoint
def set_admin_token(admin_token='None'):
"""Set admin token according to deployment config or use a randomly
generated token if none is specified (default).
"""
if admin_token != 'None':
log('Configuring Keystone to use a pre-configured admin token.')
token = admin_token
else:
log('Configuring Keystone to use a random admin token.')
if os.path.isfile(STORED_TOKEN):
msg = 'Loading a previously generated' \
' admin token from %s' % STORED_TOKEN
log(msg)
with open(STORED_TOKEN, 'r') as f:
token = f.read().strip()
else:
token = pwgen(length=64)
with open(STORED_TOKEN, 'w') as out:
out.write('%s\n' % token)
return(token)
def get_admin_token():
"""Temporary utility to grab the admin token as configured in
keystone.conf
"""
with open(KEYSTONE_CONF, 'r') as f:
for l in f.readlines():
if l.split(' ')[0] == 'admin_token':
try:
return l.split('=')[1].strip()
except:
error_out('Could not parse admin_token line from %s' %
KEYSTONE_CONF)
error_out('Could not find admin_token line in %s' % KEYSTONE_CONF)
def is_service_present(service_name, service_type):
manager = get_manager()
service_id = manager.resolve_service_id(service_name, service_type)
return service_id is not None
def delete_service_entry(service_name, service_type):
""" Delete a service from keystone"""
manager = get_manager()
service_id = manager.resolve_service_id(service_name, service_type)
if service_id:
manager.delete_service_by_id(service_id)
log("Deleted service entry '{}'".format(service_name), level=DEBUG)
def create_service_entry(service_name, service_type, service_desc, owner=None):
""" Add a new service entry to keystone if one does not already exist """
manager = get_manager()
for service in manager.list_services():
if service['name'] == service_name:
log("Service entry for '{}' already exists.".format(service_name),
level=DEBUG)
return
manager.create_service(service_name, service_type,
description=service_desc)
log("Created new service entry '{}'".format(service_name), level=DEBUG)
def create_endpoint_template(region, service, publicurl, adminurl,
internalurl):
manager = get_manager()
# this needs to be a round-trip to the manager.py script to discover what
# the "current" api_version might be, as it can't just be asserted.
if manager.resolved_api_version() == 2:
create_endpoint_template_v2(manager, region, service, publicurl,
adminurl, internalurl)
else:
create_endpoint_template_v3(manager, region, service, publicurl,
adminurl, internalurl)
def create_endpoint_template_v2(manager, region, service, publicurl, adminurl,
internalurl):
""" Create a new endpoint template for service if one does not already
exist matching name *and* region """
service_id = manager.resolve_service_id(service)
for ep in manager.list_endpoints():
if ep['service_id'] == service_id and ep['region'] == region:
log("Endpoint template already exists for '%s' in '%s'"
% (service, region))
up_to_date = True
for k in ['publicurl', 'adminurl', 'internalurl']:
if ep.get(k) != locals()[k]:
up_to_date = False
if up_to_date:
return
else:
# delete endpoint and recreate if endpoint urls need updating.
log("Updating endpoint template with new endpoint urls.")
manager.delete_endpoint_by_id(ep['id'])
manager.create_endpoints(region=region,
service_id=service_id,
publicurl=publicurl,
adminurl=adminurl,
internalurl=internalurl)
log("Created new endpoint template for '{}' in '{}'"
.format(region, service), level=DEBUG)
def create_endpoint_template_v3(manager, region, service, publicurl, adminurl,
internalurl):
service_id = manager.resolve_service_id(service)
endpoints = {
'public': publicurl,
'admin': adminurl,
'internal': internalurl,
}
for ep_type in endpoints.keys():
# Delete endpoint if its has changed
ep_deleted = manager.delete_old_endpoint_v3(
ep_type,
service_id,
region,
endpoints[ep_type]
)
ep_exists = manager.find_endpoint_v3(
ep_type,
service_id,
region
)
if ep_deleted or not ep_exists:
manager.create_endpoint_by_type(
region=region,
service_id=service_id,
interface=ep_type,
endpoint=endpoints[ep_type],
)
def create_tenant(name, domain):
"""Creates a tenant if it does not already exist"""
manager = get_manager()
tenant = manager.resolve_tenant_id(name, domain=domain)
if not tenant:
manager.create_tenant(tenant_name=name,
domain=domain,
description='Created by Juju')
log("Created new tenant '{}' in domain '{}'".format(name, domain),
level=DEBUG)
return
log("Tenant '{}' already exists.".format(name), level=DEBUG)
def create_or_show_domain(name):
"""Creates a domain if it does not already exist"""
manager = get_manager()
domain_id = manager.resolve_domain_id(name)
if domain_id:
log("Domain '{}' already exists.".format(name), level=DEBUG)
else: