/
nova_cc_utils.py
2114 lines (1794 loc) · 77.4 KB
/
nova_cc_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
# 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 base64
import collections
import configparser
import copy
import os
import subprocess
from urllib.parse import urlparse
import uuid
import charmhelpers.contrib.hahelpers.apache as ch_apache
import charmhelpers.contrib.hahelpers.cluster as ch_cluster
import charmhelpers.contrib.network.ip as ch_ip
import charmhelpers.contrib.openstack.cert_utils as ch_cert_utils
import charmhelpers.contrib.openstack.context as ch_context
import charmhelpers.contrib.openstack.ip as ch_openstack_ip
import charmhelpers.contrib.openstack.templating as ch_templating
import charmhelpers.contrib.openstack.utils as ch_utils
import charmhelpers.contrib.peerstorage as ch_peerstorage
import charmhelpers.core.decorators as ch_decorators
import charmhelpers.core.hookenv as hookenv
import charmhelpers.core.host as ch_host
import charmhelpers.core.unitdata as unitdata
import charmhelpers.fetch as ch_fetch
import hooks.nova_cc_common as common
import hooks.nova_cc_context as nova_cc_context
TEMPLATES = 'templates/'
CLUSTER_RES = 'grp_nova_vips'
SHARED_METADATA_SECRET_KEY = 'shared-metadata-secret'
# The interface is said to be satisfied if anyone of the interfaces in the
# list has a complete context.
REQUIRED_INTERFACES = {
'database': ['shared-db'],
'messaging': ['amqp'],
'identity': ['identity-service'],
'image': ['image-service'],
'compute': ['nova-compute', 'nova-cell-api'],
}
REQUIRED_INTERFACES_TRAIN = {
'placement': ['placement'],
}
# removed from original: charm-helper-sh
BASE_PACKAGES = [
'apache2',
'haproxy',
'libapache2-mod-wsgi',
'python-keystoneclient',
'python-mysqldb',
'python-psycopg2',
'python-psutil',
'python-memcache',
'uuid',
]
PY3_PACKAGES = [
'libapache2-mod-wsgi-py3',
'python3-nova',
'python3-novaclient',
'python3-keystoneclient',
'python3-psutil',
'python3-six',
'python3-memcache',
]
VERSION_PACKAGE = 'nova-common'
BASE_SERVICES = [
'nova-api-ec2',
'nova-api-os-compute',
'nova-placement-api',
'nova-objectstore',
'nova-cert',
'nova-scheduler',
'nova-conductor',
]
AWS_COMPAT_SERVICES = ['nova-api-ec2', 'nova-objectstore']
SERVICE_BLACKLIST = {
'liberty': AWS_COMPAT_SERVICES,
'newton': ['nova-cert'],
'train': ['nova-placement-api'],
}
# API_PORTS is now in nova_cc_common.py to break the circular dependency
# between nova_cc_utils.py and nova_cc_context.py
NOVA_CONF_DIR = "/etc/nova"
NEUTRON_CONF_DIR = "/etc/neutron"
NOVA_CONF = '%s/nova.conf' % NOVA_CONF_DIR
NOVA_API_PASTE = '%s/api-paste.ini' % NOVA_CONF_DIR
VENDORDATA_FILE = '%s/vendor_data.json' % NOVA_CONF_DIR
HAPROXY_CONF = '/etc/haproxy/haproxy.cfg'
APACHE_PORTS_CONF = '/etc/apache2/ports.conf'
APACHE_CONF = '/etc/apache2/sites-available/openstack_https_frontend'
APACHE_SSL_DIR = '/etc/apache2/ssl/nova'
MEMCACHED_CONF = '/etc/memcached.conf'
WSGI_NOVA_PLACEMENT_API_CONF = \
'/etc/apache2/sites-enabled/wsgi-placement-api.conf'
PACKAGE_NOVA_PLACEMENT_API_CONF = \
'/etc/apache2/sites-enabled/nova-placement-api.conf'
OLD_WSGI_NOVA_PLACEMENT_API_CONF = \
'/etc/apache2/sites-enabled/wsgi-openstack-api.conf'
WSGI_NOVA_METADATA_API_CONF = \
'/etc/apache2/sites-enabled/wsgi-openstack-metadata.conf'
PACKAGE_NOVA_API_OS_COMPUTE_CONF = \
'/etc/apache2/sites-available/nova-api-os-compute.conf'
WSGI_NOVA_API_OS_COMPUTE_CONF = \
'/etc/apache2/sites-enabled/wsgi-api-os-compute.conf'
def resolve_services():
_services = copy.deepcopy(BASE_SERVICES)
os_rel = ch_utils.os_release('nova-common')
cmp_os_release = ch_utils.CompareOpenStackReleases(os_rel)
for release in SERVICE_BLACKLIST:
if cmp_os_release >= release or hookenv.config('disable-aws-compat'):
for service in SERVICE_BLACKLIST[release]:
_services.remove(service)
return _services
# _BASE_RESOURCE_MAP is a caching global that is set up by
# get_base_resource_map()
_BASE_RESOURCE_MAP = None
def get_base_resource_map():
"""Return the base resource map. Note that it is cached in the
_BASE_RESOURCE_MAP global.
:returns: The base resource map
:rtype: collections.OrderedDict
"""
global _BASE_RESOURCE_MAP
if _BASE_RESOURCE_MAP is None:
_BASE_RESOURCE_MAP = collections.OrderedDict([
(NOVA_CONF, {
'services': resolve_services(),
'contexts': [
ch_context.AMQPContext(ssl_dir=NOVA_CONF_DIR),
ch_context.SharedDBContext(
relation_prefix='nova',
ssl_dir=NOVA_CONF_DIR),
ch_context.OSConfigFlagContext(
charm_flag='nova-alchemy-flags',
template_flag='nova_alchemy_flags'),
ch_context.ImageServiceContext(),
ch_context.OSConfigFlagContext(),
ch_context.SubordinateConfigContext(
interface='nova-vmware',
service='nova',
config_file=NOVA_CONF),
ch_context.SyslogContext(),
ch_context.LogLevelContext(),
nova_cc_context.HAProxyContext(),
nova_cc_context.IdentityServiceContext(
service='nova',
service_user='nova'),
nova_cc_context.VolumeServiceContext(),
ch_context.ZeroMQContext(),
ch_context.NotificationDriverContext(),
nova_cc_context.CinderConfigContext(),
nova_cc_context.NovaIPv6Context(),
nova_cc_context.NeutronCCContext(),
nova_cc_context.NovaConfigContext(),
nova_cc_context.RemoteMemcacheContext(),
nova_cc_context.InstanceConsoleContext(),
nova_cc_context.ConsoleSSLContext(),
nova_cc_context.CloudComputeContext(),
nova_cc_context.PlacementContext(),
ch_context.InternalEndpointContext(),
ch_context.VolumeAPIContext('nova-common'),
nova_cc_context.NeutronAPIContext(),
nova_cc_context.SerialConsoleContext(),
ch_context.MemcacheContext(),
nova_cc_context.NovaMetadataContext('nova-common')],
}),
(NOVA_API_PASTE, {
'services': [s for s in resolve_services() if 'api' in s],
'contexts': [nova_cc_context.IdentityServiceContext(),
nova_cc_context.APIRateLimitingContext()],
}),
(VENDORDATA_FILE, {
'services': [],
'contexts': [nova_cc_context.NovaMetadataJSONContext(
'nova-common')],
}),
(HAPROXY_CONF, {
'contexts': [
ch_context.HAProxyContext(singlenode_mode=True),
nova_cc_context.HAProxyContext()],
'services': ['haproxy'],
}),
(APACHE_CONF, {
'contexts': [nova_cc_context.ApacheSSLContext(
determine_ports)],
'services': ['apache2'],
}),
(nova_cc_context.APACHE_24_CONF, {
'contexts': [nova_cc_context.ApacheSSLContext(
determine_ports)],
'services': ['apache2'],
}),
(APACHE_PORTS_CONF, {
'contexts': [],
'services': ['apache2'],
}),
])
return _BASE_RESOURCE_MAP
NOVA_SSH_DIR = '/etc/nova/compute_ssh/'
SERIAL_CONSOLE = {
'packages': ['nova-serialproxy', 'websockify'],
'services': ['nova-serialproxy'],
}
def _replace_service_with_apache2(service, wsgi_script, wsgi_config,
resource_map, context):
for cfile in resource_map:
svcs = resource_map[cfile]['services']
if service in svcs:
svcs.remove(service)
if 'apache2' not in svcs:
svcs.append('apache2')
resource_map[wsgi_config] = {
'contexts': [
ch_context.WSGIWorkerConfigContext(
name=service,
script=wsgi_script,
user='nova',
group='nova'
),
context],
'services': ['apache2']}
def resource_map(actual_services=True):
'''
Dynamically generate a map of resources that will be managed for a single
hook execution.
:param actual_services: Whether to return the actual services that run on a
unit (ie. apache2) or the services defined in BASE_SERVICES
(ie.nova-placement-api).
'''
_resource_map = copy.deepcopy(get_base_resource_map())
if os.path.exists('/etc/apache2/conf-available'):
_resource_map.pop(APACHE_CONF)
else:
_resource_map.pop(nova_cc_context.APACHE_24_CONF)
_resource_map[NOVA_CONF]['contexts'].append(
nova_cc_context.NeutronCCContext())
release = ch_utils.os_release('nova-common')
cmp_os_release = ch_utils.CompareOpenStackReleases(release)
if cmp_os_release >= 'mitaka':
_resource_map[NOVA_CONF]['contexts'].append(
nova_cc_context.NovaAPISharedDBContext(relation_prefix='novaapi',
database='nova_api',
ssl_dir=NOVA_CONF_DIR)
)
if common.console_attributes('services'):
_resource_map[NOVA_CONF]['services'] += (
common.console_attributes('services'))
if is_serial_console_enabled(cmp_os_release):
_resource_map[NOVA_CONF]['services'] += SERIAL_CONSOLE['services']
if is_consoleauth_enabled(cmp_os_release):
_resource_map[NOVA_CONF]['services'] += ['nova-consoleauth']
# also manage any configs that are being updated by subordinates.
vmware_ctxt = ch_context.SubordinateConfigContext(
interface='nova-vmware', service='nova', config_file=NOVA_CONF)
vmware_ctxt = vmware_ctxt()
if vmware_ctxt and 'services' in vmware_ctxt:
for s in vmware_ctxt['services']:
if s not in _resource_map[NOVA_CONF]['services']:
_resource_map[NOVA_CONF]['services'].append(s)
if ch_utils.enable_memcache(release=release):
_resource_map[MEMCACHED_CONF] = {
'contexts': [ch_context.MemcacheContext()],
'services': ['memcached']}
if (actual_services and
ch_utils.CompareOpenStackReleases(release) >= 'rocky'):
# For Rocky we decided to switch from systemd to use apache2
# wsgi mod for the service nova-api-os-compute.
_replace_service_with_apache2(
'nova-api-os-compute',
'/usr/bin/nova-api-wsgi',
WSGI_NOVA_API_OS_COMPUTE_CONF,
_resource_map,
nova_cc_context.ComputeAPIHAProxyContext())
if actual_services and placement_api_enabled():
_replace_service_with_apache2(
'nova-placement-api',
'/usr/bin/nova-placement-api',
WSGI_NOVA_PLACEMENT_API_CONF,
_resource_map,
nova_cc_context.PlacementAPIHAProxyContext())
elif not placement_api_enabled():
for cfile in _resource_map:
svcs = _resource_map[cfile]['services']
if 'nova-placement-api' in svcs:
svcs.remove('nova-placement-api')
if enable_metadata_api():
if actual_services:
svcs = ['apache2']
else:
svcs = ['nova-api-metadata']
_resource_map[WSGI_NOVA_METADATA_API_CONF] = {
'contexts': [
ch_context.WSGIWorkerConfigContext(
name="nova_meta",
user='nova',
group='nova',
script='/usr/bin/nova-metadata-wsgi'),
nova_cc_context.MetaDataHAProxyContext(),
nova_cc_context.NeutronAPIContext()],
'services': svcs}
return _resource_map
def register_configs(release=None):
release = release or ch_utils.os_release('nova-common')
configs = ch_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(actual_services=True):
'''
Constructs a restart map of config files and corresponding services
:param actual_services: Whether to return the actual services that run on a
unit (ie. apache2) or the services defined in BASE_SERVICES
(ie.nova-placement-api).
'''
services = resource_map(actual_services)
restart_map = collections.OrderedDict(
[(cfg, v['services'])
for cfg, v in services.items()
if v['services']])
if os.path.isdir(APACHE_SSL_DIR):
_restart_svcs = services[NOVA_CONF]['services'] + ['apache2']
restart_map['{}/*'.format(APACHE_SSL_DIR)] = _restart_svcs
return restart_map
def services():
''' Returns a list of services associate with this charm '''
_services = []
for v in restart_map().values():
_services = _services + v
return list(set(_services))
def determine_ports():
'''Assemble a list of API ports for services we are managing'''
ports = []
for services in restart_map(actual_services=False).values():
for svc in services:
try:
ports.append(common.api_port(svc))
except KeyError:
pass
return list(set(ports))
def determine_packages():
# currently all packages match service names
release = ch_utils.CompareOpenStackReleases(
ch_utils.os_release('nova-common'))
packages = copy.deepcopy(BASE_PACKAGES)
for v in resource_map(actual_services=False).values():
packages.extend(v['services'])
# The nova-api-metadata service is served via wsgi and the package is
# only needed for the standalone service so remove it to avoid port
# clashes.
try:
packages.remove("nova-api-metadata")
except ValueError:
pass
if common.console_attributes('packages'):
packages.extend(common.console_attributes('packages'))
if is_serial_console_enabled(release):
packages.extend(SERIAL_CONSOLE['packages'])
if is_consoleauth_enabled(release):
packages.extend(['nova-consoleauth'])
packages.extend(
ch_utils.token_cache_pkgs(source=hookenv.config('openstack-origin')))
if release >= 'rocky':
packages = [p for p in packages if not p.startswith('python-')]
packages.extend(PY3_PACKAGES)
packages.remove('libapache2-mod-wsgi')
if release >= 'stein':
# NOTE(jamespage):
# workaround to deal with lack of functionality to update the db
# connection for Cell 0. At stein, the default SQLAlchemy dialect
# switched to mysqldb, which requires use of mysql+pymysql:// in
# all connection strings, but there is no way to update the
# db url for cell0 as stored in the nova_api DB.
packages.append('python3-mysqldb')
return list(set(packages))
def determine_purge_packages():
'''
Determine list of packages that where previously installed which are no
longer needed.
:returns: list of package names
'''
release = ch_utils.CompareOpenStackReleases(
ch_utils.os_release('keystone'))
if release >= 'rocky':
pkgs = [p for p in BASE_PACKAGES if p.startswith('python-')]
pkgs.extend(['python-nova', 'python-memcache', 'libapache2-mod-wsgi'])
return pkgs
return []
def remove_old_packages():
'''Purge any packages that need ot be removed.
:returns: bool Whether packages were removed.
'''
installed_packages = ch_fetch.filter_missing_packages(
determine_purge_packages())
if installed_packages:
ch_fetch.apt_purge(installed_packages, fatal=True)
ch_fetch.apt_autoremove(purge=True, fatal=True)
return bool(installed_packages)
def save_script_rc():
env_vars = {
'OPENSTACK_PORT_MCASTPORT': hookenv.config('ha-mcastport'),
'OPENSTACK_SERVICE_API_EC2': 'nova-api-ec2',
'OPENSTACK_SERVICE_API_OS_COMPUTE': 'nova-api-os-compute',
'OPENSTACK_SERVICE_CERT': 'nova-cert',
'OPENSTACK_SERVICE_CONDUCTOR': 'nova-conductor',
'OPENSTACK_SERVICE_OBJECTSTORE': 'nova-objectstore',
'OPENSTACK_SERVICE_SCHEDULER': 'nova-scheduler',
}
if hookenv.relation_ids('nova-volume-service'):
env_vars['OPENSTACK_SERVICE_API_OS_VOL'] = 'nova-api-os-volume'
ch_utils.save_script_rc(**env_vars)
def get_step_upgrade_source(new_src):
'''
Determine if upgrade skips a release and, if so, return source
of skipped release.
'''
sources = {
# target_src: (cur_pocket, step_src)
# NOTE: cur_pocket == * means all upgrades to target_src must step
# through step_src if step_src is higher than
# current release
'precise-icehouse': ('precise-updates/grizzly',
'cloud:precise-havana'),
'precise-icehouse/proposed': ('precise-proposed/grizzly',
'cloud:precise-havana/proposed'),
'trusty-liberty': ('*', 'cloud:trusty-kilo'),
'xenial-ocata': ('*', 'cloud:xenial-newton'), # LP: #1711209
}
try:
os_codename = ch_utils.get_os_codename_install_source(new_src)
ubuntu_series = ch_host.lsb_release()['DISTRIB_CODENAME'].lower()
cur_pocket, step_src = sources['%s-%s' % (ubuntu_series, os_codename)]
current_src = ch_utils.os_release('nova-common')
step_src_codename = ch_utils.get_os_codename_install_source(step_src)
if cur_pocket == '*' and step_src_codename > current_src:
return step_src
except KeyError:
pass
ch_utils.configure_installation_source(new_src)
# charmhelpers.contrib.openstack.utils.configure_installation_source()
# configures the repository in juju_deb.list, while
# charmhelpers.fetch.add_sources() uses cloud-archive.list, so both
# files need to read looking for the currently configured repo.
for fname in ['cloud-archive.list', 'juju_deb.list']:
fpath = os.path.join('/etc/apt/sources.list.d/', fname)
if not os.path.isfile(fpath):
hookenv.log('Missing %s skipping it' % fpath, level=hookenv.DEBUG)
continue
with open(fpath, 'rt') as f:
for line in f.readlines():
for target_src, (cur_pocket, step_src) in sources.items():
if target_src != new_src:
continue
if cur_pocket in line:
return step_src
return None
POLICY_RC_D = """#!/bin/bash
set -e
case $1 in
nova-*)
[ $2 = "start" ] && exit 101
;;
*)
;;
esac
exit 0
"""
def enable_policy_rcd():
with open('/usr/sbin/policy-rc.d', 'w') as policy:
policy.write(POLICY_RC_D)
os.chmod('/usr/sbin/policy-rc.d', 0o755)
def disable_policy_rcd():
os.unlink('/usr/sbin/policy-rc.d')
def is_serial_console_enabled(cmp_os_release=None):
"""Determine whether serial console is enabled in this deploy
:param cmp_os_release: Release comparison object.
:type cmp_os_release: charmhelpers.contrib.openstack.utils.
CompareOpenStackReleases
:returns: Whether serial console is enabled in this deploy
:rtype: bool
"""
if not cmp_os_release:
release = ch_utils.os_release('nova-common')
cmp_os_release = ch_utils.CompareOpenStackReleases(release)
return hookenv.config('enable-serial-console') and cmp_os_release >= 'juno'
def is_consoleauth_enabled(cmp_os_release=None):
"""Determine whether the ``consoleauth`` service is enabled in this deploy
Note that the fact that the service is enabled or not may not be tied to
the reality of Nova doing console access authorization.
Since OpenStack Rocky the console token authorization storage has been
moved to the database backend, and in OpenStack Train the service
was removed.
https://github.com/openstack/nova/blob/master/releasenotes/notes/deprecate-nova-consoleauth-ed6ccbc324a0fb10.yaml
:param cmp_os_release: Release comparison object.
:type cmp_os_release: charmhelpers.contrib.openstack.utils.
CompareOpenStackReleases
:returns: Whether ``consoleauth`` service is enabled in this deploy
:rtype: bool
"""
if not cmp_os_release:
release = ch_utils.os_release('nova-common')
cmp_os_release = ch_utils.CompareOpenStackReleases(release)
return cmp_os_release < 'train' and (bool(is_serial_console_enabled() or
hookenv.config(
'console-access-protocol')))
def is_db_initialised():
if hookenv.relation_ids('cluster'):
dbsync_state = ch_peerstorage.peer_retrieve('dbsync_state')
if dbsync_state == 'complete':
hookenv.log("Database is initialised", level=hookenv.DEBUG)
return True
hookenv.log("Database is NOT initialised", level=hookenv.DEBUG)
return False
def is_cellv2_init_ready():
"""Determine if we're ready to initialize the cell v2 databases
Cells v2 init requires transport_url and database connections to be set
in nova.conf.
"""
amqp = ch_context.AMQPContext()
shared_db = nova_cc_context.NovaCellV2SharedDBContext()
if (ch_utils.CompareOpenStackReleases(
ch_utils.os_release('nova-common')) >= 'ocata' and
amqp() and shared_db()):
return True
hookenv.log(
"OpenStack release, database, or rabbitmq not ready for Cells V2",
level=hookenv.DEBUG)
return False
def _do_openstack_upgrade(new_src):
enable_policy_rcd()
# All upgrades to Liberty are forced to step through Kilo. Liberty does
# not have the migrate_flavor_data option (Bug #1511466) available so it
# must be done pre-upgrade
if (ch_utils.CompareOpenStackReleases(
ch_utils.os_release('nova-common')) == 'kilo' and
hookenv.is_leader()):
migrate_nova_flavors()
# 'nova-manage db online_data_migrations' needs to be run before moving to
# the next release for environments upgraded using old charms where this
# step was not being executed (LP: #1711209).
online_data_migrations_if_needed()
new_os_rel = ch_utils.get_os_codename_install_source(new_src)
cmp_new_os_rel = ch_utils.CompareOpenStackReleases(new_os_rel)
hookenv.log('Performing OpenStack upgrade to %s.' % (new_os_rel))
ch_utils.configure_installation_source(new_src)
dpkg_opts = [
'--option', 'Dpkg::Options::=--force-confnew',
'--option', 'Dpkg::Options::=--force-confdef',
]
ch_fetch.apt_update(fatal=True)
ch_fetch.apt_upgrade(options=dpkg_opts, fatal=True, dist=True)
ch_utils.reset_os_release()
ch_fetch.apt_install(determine_packages(), fatal=True)
remove_old_packages()
disable_package_apache_site()
disable_policy_rcd()
stop_deprecated_services()
# NOTE(jamespage) upgrade with existing config files as the
# havana->icehouse migration enables new service_plugins which
# create issues with db upgrades
configs = register_configs(release=new_os_rel)
configs.write_all()
if cmp_new_os_rel >= 'mitaka' and not database_setup(prefix='novaapi'):
# NOTE: Defer service restarts and database migrations for now
# as nova_api database is not yet created
if (hookenv.relation_ids('cluster') and hookenv.is_leader()):
# NOTE: reset dbsync state so that migration will complete
# when the nova_api database is setup.
ch_peerstorage.peer_store('dbsync_state', None)
return configs
if cmp_new_os_rel >= 'ocata' and not database_setup(prefix='novacell0'):
# NOTE: Defer service restarts and database migrations for now
# as nova_cell0 database is not yet created
if (hookenv.relation_ids('cluster') and hookenv.is_leader()):
# NOTE: reset dbsync state so that migration will complete
# when the novacell0 database is setup.
ch_peerstorage.peer_store('dbsync_state', None)
return configs
if hookenv.is_leader():
hookenv.status_set('maintenance', 'Running nova db migration')
migrate_nova_databases()
if not ch_utils.is_unit_paused_set():
[ch_host.service_start(s) for s in services()]
return configs
def database_setup(prefix):
'''
Determine when a specific database is setup
and access is granted to the local unit.
This function only checks the MySQL shared-db
relation name using the provided prefix.
'''
key = '{}_allowed_units'.format(prefix)
for db_rid in hookenv.relation_ids('shared-db'):
for unit in hookenv.related_units(db_rid):
allowed_units = hookenv.relation_get(key, rid=db_rid, unit=unit)
if allowed_units and hookenv.local_unit() in allowed_units.split():
return True
return False
def do_openstack_upgrade(configs):
# If attempting to upgrade from Stein->Train, block until Placement
# charm is related. Status is set in check_optional_relations().
release = ch_utils.os_release('nova-common')
cmp_os_release = ch_utils.CompareOpenStackReleases(release)
if (cmp_os_release == 'stein' and not hookenv.relation_ids('placement')):
return None
new_src = hookenv.config('openstack-origin')
step_src = get_step_upgrade_source(new_src)
if step_src is not None:
_do_openstack_upgrade(step_src)
return _do_openstack_upgrade(new_src)
@ch_decorators.retry_on_exception(
5, base_delay=3, exc_type=subprocess.CalledProcessError)
def migrate_nova_flavors():
'''Runs nova-manage to migrate flavor data if needed'''
hookenv.log('Migrating nova flavour information in database.',
level=hookenv.INFO)
cmd = ['nova-manage', 'db', 'migrate_flavor_data']
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
hookenv.log('migrate_flavor_data failed\n{}'.format(e.output),
level=hookenv.ERROR)
raise
@ch_decorators.retry_on_exception(
5, base_delay=3, exc_type=subprocess.CalledProcessError)
def online_data_migrations_if_needed():
'''Runs nova-manage to run online data migrations available since Mitaka'''
if (hookenv.is_leader() and
ch_utils.CompareOpenStackReleases(
ch_utils.os_release('nova-common')) >= 'mitaka'):
hookenv.log('Running online_data_migrations', level=hookenv.INFO)
cmd = ['nova-manage', 'db', 'online_data_migrations']
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
hookenv.log('online_data_migrations failed\n{}'.format(e.output),
level=hookenv.ERROR)
raise
def migrate_nova_api_database():
'''Initialize or migrate the nova_api database'''
if ch_utils.CompareOpenStackReleases(
ch_utils.os_release('nova-common')) >= 'mitaka':
hookenv.log('Migrating the nova-api database.', level=hookenv.INFO)
cmd = ['nova-manage', 'api_db', 'sync']
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
# NOTE(coreycb): sync of api_db on upgrade from newton->ocata
# fails but cell init is successful.
hookenv.log('Ignoring CalledProcessError during nova-api database '
'migration\n{}'.format(e.output), level=hookenv.INFO)
def migrate_nova_database():
'''Initialize or migrate the nova database'''
hookenv.log('Migrating the nova database.', level=hookenv.INFO)
cmd = ['nova-manage', 'db', 'sync']
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
hookenv.log('db sync failed\n{}'.format(e.output), level=hookenv.ERROR)
raise
def initialize_cell_databases():
'''Initialize the cell0 and cell1 databases
cell0 is stored in the database named 'nova_cell0'.
cell1 is stored in the database named 'nova'.
'''
hookenv.log('Creating cell0 database records', level=hookenv.INFO)
cmd = ['nova-manage', 'cell_v2', 'map_cell0']
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
hookenv.log('map_cell0 failed\n{}'.format(e.output),
level=hookenv.ERROR)
raise
hookenv.log('Creating cell1 database records', level=hookenv.INFO)
cmd = ['nova-manage', 'cell_v2', 'create_cell', '--name', 'cell1',
'--verbose']
try:
subprocess.check_output(cmd)
hookenv.log('cell1 was successfully created', level=hookenv.INFO)
except subprocess.CalledProcessError as e:
if e.returncode == 1:
hookenv.log('Cell1 create_cell failed\n{}'.format(e.output),
level=hookenv.ERROR)
raise
elif e.returncode == 2:
hookenv.log(
'Cell1 create_cell failure ignored - a cell is already using '
'the transport_url/database combination.', level=hookenv.INFO)
def get_cell_uuid(cell, fatal=True):
'''Get cell uuid
:param cell: string cell name i.e. 'cell1'
:returns: string cell uuid
'''
hookenv.log("Listing cell, '{}'".format(cell), level=hookenv.INFO)
cells = get_cell_details()
cell_info = cells.get(cell)
if not cell_info:
if fatal:
raise Exception("Cannot find cell, '{}', in list_cells."
"".format(cell))
return None
return cell_info['uuid']
def get_cell_details():
'''Get cell details
:returns: string cell uuid
'''
hookenv.log("Getting details of cells", level=hookenv.INFO)
cells = {}
cmd = ['sudo', 'nova-manage', 'cell_v2', 'list_cells', '--verbose']
try:
out = subprocess.check_output(cmd).decode('utf-8')
except subprocess.CalledProcessError as e:
hookenv.log('list_cells failed\n{}'.format(e.output),
level=hookenv.ERROR)
raise
for line in out.split('\n'):
columns = line.split('|')
if len(columns) < 2:
continue
columns = [c.strip() for c in columns]
try:
uuid.UUID(columns[2].strip())
cells[columns[1]] = {
'uuid': columns[2],
'amqp': columns[3],
'db': columns[4]}
except ValueError:
pass
return cells
def update_cell_database():
'''Update the cell0 and cell1 database_connection/transport_url properties
This should be called whenever a database or rabbitmq-server relation is
changed to update the transport_url in the nova_api cell_mappings table.
The cell0 transport_url is always none:///.
The cell1 transport_url and database_connection are generated from the
config file's [DEFAULT]/transport_url and [database]/connection.
'''
cells = ['cell0', 'cell1']
for cell in cells:
hookenv.log('Updating {} properties'.format(cell), level=hookenv.INFO)
existing_cells = get_cell_details()
if not existing_cells.get(cell):
hookenv.log(
'Cell {} does not exist.'.format(cell), level=hookenv.DEBUG)
break
cell_uuid = existing_cells[cell]['uuid']
cmd = ['nova-manage', 'cell_v2', 'update_cell', '--cell_uuid',
cell_uuid]
if cell == 'cell0':
db_ctxt = ch_context.SharedDBContext(database='nova_cell0',
relation_prefix='novacell0',
ssl_dir=NOVA_CONF_DIR)()
if not db_ctxt:
hookenv.log(
'Defering updating cell {}, cell db relation not ready.'
.format(cell), level=hookenv.DEBUG)
break
sql_connection = get_sql_uri(db_ctxt)
cmd.extend([
'--transport-url', existing_cells[cell]['amqp'],
'--database_connection', sql_connection])
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
hookenv.log('{} update_cell failed\n{}'.format(cell, e.output),
level=hookenv.ERROR)
raise
else:
hookenv.log('{} was successfully updated'.format(cell),
level=hookenv.INFO)
def map_instances():
'''Map instances to cell
Updates nova_api.instance_mappings with pre-existing instances
:raises: Exception if Cell1 map_instances fails
'''
batch_size = '50000'
cell1_uuid = get_cell_uuid('cell1')
cmd = ['nova-manage', 'cell_v2', 'map_instances',
'--cell_uuid', cell1_uuid, '--max-count', batch_size]
iteration = 0
exit_code = 1
# Return code if 0 indicates all instances have been mapped. A return code
# of 1 indicates this batch is complete but there are more instances that
# still need mapping.
while exit_code == 1:
msg = 'Mapping instances. Batch number: {}'.format(iteration)
hookenv.status_set('maintenance', msg)
hookenv.log(msg, level=hookenv.INFO)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
exit_code = process.wait()
if exit_code not in [0, 1]:
msg = 'Cell1 map_instances failed\nstdout: {}\nstderr: {}'.format(
stdout,
stderr)
hookenv.log(msg, level=hookenv.ERROR)
raise Exception(msg)
iteration += 1
msg = 'Mapping instances complete'
hookenv.status_set('maintenance', msg)
hookenv.log(msg, level=hookenv.INFO)
def archive_deleted_rows(max_rows=None):
hookenv.log('Archiving deleted rows', level=hookenv.INFO)
cmd = ['nova-manage', 'db', 'archive_deleted_rows', '--verbose']
if max_rows:
cmd.extend(['--max_rows', str(max_rows)])
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
exit_code = process.wait()
if exit_code not in [0, 1]:
msg = 'Archiving deleted rows failed\nstdout: {}\nstderr: {}'.format(
stdout,
stderr)
hookenv.log(msg, level=hookenv.ERROR)
raise Exception(msg)
else:
return stdout
def add_hosts_to_cell():
'''Map compute hosts to cell'''
hookenv.log('Cell1 discover_hosts', level=hookenv.INFO)
cell1_uuid = get_cell_uuid('cell1')
cmd = ['nova-manage', 'cell_v2', 'discover_hosts', '--cell_uuid',
cell1_uuid, '--verbose']
try:
subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
hookenv.log('Cell1 discover_hosts failed\n{}'.format(e.output),
level=hookenv.ERROR)
raise
def finalize_migrate_nova_databases():
if hookenv.relation_ids('cluster'):
hookenv.log('Informing peers that dbsync is complete',
level=hookenv.INFO)
ch_peerstorage.peer_store('dbsync_state', 'complete')
hookenv.log('Enabling services', level=hookenv.INFO)
if not ch_utils.is_unit_paused_set():
for svc in services():
ch_host.service_resume(svc)
else:
hookenv.log('Unit is in paused state, not issuing start/resume to all '
'services')
# NOTE(jamespage): Retry deals with sync issues during one-shot HA deploys.
# mysql might be restarting or suchlike.
@ch_decorators.retry_on_exception(
5, base_delay=3, exc_type=subprocess.CalledProcessError)
def migrate_nova_databases():
'''Runs nova-manage to initialize new databases or migrate existing'''