summaryrefslogtreecommitdiff
path: root/instack_undercloud/undercloud.py
blob: 92e51448633bc416963d38f1c78471ac3fd6c2c7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
# Copyright 2015 Red Hat Inc.
#
# 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.

from __future__ import print_function

import copy
import errno
import getpass
import glob
import hashlib
import json
import logging
import os
import platform
import socket
import subprocess
import sys
import tempfile
import time
import uuid
import yaml

from keystoneauth1 import session
from keystoneauth1 import exceptions as ks_exceptions
from keystoneclient import discover
import keystoneauth1.identity.generic as ks_auth
from mistralclient.api import client as mistralclient
import novaclient as nc
from novaclient import client as novaclient
from novaclient import exceptions
from oslo_config import cfg
import psutil
import pystache
import six
from swiftclient import client as swiftclient

from instack_undercloud import validator


# Making these values properties on a class allows us to delay their lookup,
# which makes testing code that interacts with these files much easier.
# NOTE(bnemec): The unit tests rely on these paths being in ~.  If they are
# ever moved the tests may need to be updated to avoid overwriting real files.
class Paths(object):
    @property
    def CONF_PATH(self):
        return os.path.expanduser('~/undercloud.conf')

    # NOTE(bnemec): Deprecated
    @property
    def ANSWERS_PATH(self):
        return os.path.expanduser('~/instack.answers')

    @property
    def PASSWORD_PATH(self):
        return os.path.expanduser('~/undercloud-passwords.conf')

    @property
    def LOG_FILE(self):
        return os.path.expanduser('~/.instack/install-undercloud.log')


PATHS = Paths()
DEFAULT_LOG_LEVEL = logging.DEBUG
DEFAULT_LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
LOG = None
CONF = cfg.CONF
COMPLETION_MESSAGE = """
#############################################################################
Undercloud %(undercloud_operation)s complete.

The file containing this installation's passwords is at
%(password_path)s.

There is also a stackrc file at %(stackrc_path)s.

These files are needed to interact with the OpenStack services, and should be
secured.

#############################################################################
"""
FAILURE_MESSAGE = """
#############################################################################
Undercloud %(undercloud_operation)s failed.

Reason: %(exception)s

See the previous output for details about what went wrong.  The full install
log can be found at %(log_file)s.

#############################################################################
"""
# We need 8 GB, leave a little room for variation in what 8 GB means on
# different platforms.
REQUIRED_MB = 7680


# When adding new options to the lists below, make sure to regenerate the
# sample config by running "tox -e genconfig" in the project root.
_opts = [
    cfg.StrOpt('undercloud_hostname',
               help=('Fully qualified hostname (including domain) to set on '
                     'the Undercloud. If left unset, the '
                     'current hostname will be used, but the user is '
                     'responsible for configuring all system hostname '
                     'settings appropriately.  If set, the undercloud install '
                     'will configure all system hostname settings.'),
               ),
    cfg.StrOpt('local_ip',
               default='192.168.24.1/24',
               help=('IP information for the interface on the Undercloud '
                     'that will be handling the PXE boots and DHCP for '
                     'Overcloud instances.  The IP portion of the value will '
                     'be assigned to the network interface defined by '
                     'local_interface, with the netmask defined by the '
                     'prefix portion of the value.')
               ),
    cfg.StrOpt('network_gateway',
               default='192.168.24.1',
               help=('Network gateway for the Neutron-managed network for '
                     'Overcloud instances. This should match the local_ip '
                     'above when using masquerading.')
               ),
    cfg.StrOpt('undercloud_public_host',
               deprecated_name='undercloud_public_vip',
               default='192.168.24.2',
               help=('Virtual IP or DNS address to use for the public '
                     'endpoints of Undercloud services. Only used with SSL.')
               ),
    cfg.StrOpt('undercloud_admin_host',
               deprecated_name='undercloud_admin_vip',
               default='192.168.24.3',
               help=('Virtual IP or DNS address to use for the admin '
                     'endpoints of Undercloud services. Only used with SSL.')
               ),
    cfg.ListOpt('undercloud_nameservers',
                default=[],
                help=('DNS nameserver(s) to use for the undercloud node.'),
                ),
    cfg.ListOpt('undercloud_ntp_servers',
                default=[],
                help=('List of ntp servers to use.')),
    cfg.StrOpt('overcloud_domain_name',
               default='localdomain',
               help=('DNS domain name to use when deploying the overcloud. '
                     'The overcloud parameter "CloudDomain" must be set to a '
                     'matching value.')
               ),
    cfg.StrOpt('undercloud_service_certificate',
               default='',
               help=('Certificate file to use for OpenStack service SSL '
                     'connections.  Setting this enables SSL for the '
                     'OpenStack API endpoints, leaving it unset disables SSL.')
               ),
    cfg.BoolOpt('generate_service_certificate',
                default=False,
                help=('When set to True, an SSL certificate will be generated '
                      'as part of the undercloud install and this certificate '
                      'will be used in place of the value for '
                      'undercloud_service_certificate.  The resulting '
                      'certificate will be written to '
                      '/etc/pki/tls/certs/undercloud-[undercloud_public_host].'
                      'pem.  This certificate is signed by CA selected by the '
                      '"certificate_generation_ca" option.')
                ),
    cfg.StrOpt('certificate_generation_ca',
               default='local',
               help=('The certmonger nickname of the CA from which the '
                     'certificate will be requested. This is used only if '
                     'the generate_service_certificate option is set. '
                     'Note that if the "local" CA is selected the '
                     'certmonger\'s local CA certificate will be extracted to '
                     '/etc/pki/ca-trust/source/anchors/cm-local-ca.pem and '
                     'subsequently added to the trust chain.')

               ),
    cfg.StrOpt('service_principal',
               default='',
               help=('The kerberos principal for the service that will use '
                     'the certificate. This is only needed if your CA '
                     'requires a kerberos principal. e.g. with FreeIPA.')
               ),
    cfg.StrOpt('local_interface',
               default='eth1',
               help=('Network interface on the Undercloud that will be '
                     'handling the PXE boots and DHCP for Overcloud '
                     'instances.')
               ),
    cfg.IntOpt('local_mtu',
               default=1500,
               help=('MTU to use for the local_interface.')
               ),
    cfg.StrOpt('network_cidr',
               default='192.168.24.0/24',
               help=('Network CIDR for the Neutron-managed network for '
                     'Overcloud instances. This should be the subnet used '
                     'for PXE booting.')
               ),
    cfg.StrOpt('masquerade_network',
               default='192.168.24.0/24',
               help=('Network that will be masqueraded for external access, '
                     'if required. This should be the subnet used for PXE '
                     'booting.')
               ),
    cfg.StrOpt('dhcp_start',
               default='192.168.24.5',
               help=('Start of DHCP allocation range for PXE and DHCP of '
                     'Overcloud instances.')
               ),
    cfg.StrOpt('dhcp_end',
               default='192.168.24.24',
               help=('End of DHCP allocation range for PXE and DHCP of '
                     'Overcloud instances.')
               ),
    cfg.StrOpt('hieradata_override',
               default='',
               help=('Path to hieradata override file. If set, the file will '
                     'be copied under /etc/puppet/hieradata and set as the '
                     'first file in the hiera hierarchy. This can be used '
                     'to custom configure services beyond what '
                     'undercloud.conf provides')
               ),
    cfg.StrOpt('net_config_override',
               default='',
               help=('Path to network config override template. If set, this '
                     'template will be used to configure the networking via '
                     'os-net-config. Must be in json format. '
                     'Templated tags can be used within the '
                     'template, see '
                     'instack-undercloud/elements/undercloud-stack-config/'
                     'net-config.json.template for example tags')
               ),
    cfg.StrOpt('inspection_interface',
               default='br-ctlplane',
               deprecated_name='discovery_interface',
               help=('Network interface on which inspection dnsmasq will '
                     'listen.  If in doubt, use the default value.')
               ),
    cfg.StrOpt('inspection_iprange',
               default='192.168.24.100,192.168.24.120',
               deprecated_name='discovery_iprange',
               help=('Temporary IP range that will be given to nodes during '
                     'the inspection process.  Should not overlap with the '
                     'range defined by dhcp_start and dhcp_end, but should '
                     'be in the same network.')
               ),
    cfg.BoolOpt('inspection_extras',
                default=True,
                help=('Whether to enable extra hardware collection during '
                      'the inspection process. Requires python-hardware or '
                      'python-hardware-detect package on the introspection '
                      'image.')),
    cfg.BoolOpt('inspection_runbench',
                default=False,
                deprecated_name='discovery_runbench',
                help=('Whether to run benchmarks when inspecting nodes. '
                      'Requires inspection_extras set to True.')
                ),
    cfg.BoolOpt('inspection_enable_uefi',
                default=True,
                help=('Whether to support introspection of nodes that have '
                      'UEFI-only firmware.')
                ),
    cfg.BoolOpt('enable_node_discovery',
                default=False,
                help=('Makes ironic-inspector enroll any unknown node that '
                      'PXE-boots introspection ramdisk in Ironic. By default, '
                      'the "fake" driver is used for new nodes (it is '
                      'automatically enabled when this option is set to True).'
                      ' Set discovery_default_driver to override. '
                      'Introspection rules can also be used to specify driver '
                      'information for newly enrolled nodes.')
                ),
    cfg.StrOpt('discovery_default_driver',
               default='pxe_ipmitool',
               help=('The default driver to use for newly discovered nodes '
                     '(requires enable_node_discovery set to True). This '
                     'driver is automatically added to enabled_drivers.')
               ),
    cfg.BoolOpt('undercloud_debug',
                default=True,
                help=('Whether to enable the debug log level for Undercloud '
                      'OpenStack services.')
                ),
    cfg.BoolOpt('undercloud_update_packages',
                default=True,
                help=('Whether to update packages during the Undercloud '
                      'install.')
                ),
    cfg.BoolOpt('enable_tempest',
                default=True,
                help=('Whether to install Tempest in the Undercloud.')
                ),
    cfg.BoolOpt('enable_telemetry',
                default=False,
                help=('Whether to install Telemetry services '
                      '(ceilometer, gnocchi, aodh, panko ) in the Undercloud.')
                ),
    cfg.BoolOpt('enable_ui',
                default=True,
                help=('Whether to install the TripleO UI.')
                ),
    cfg.BoolOpt('enable_validations',
                default=True,
                help=('Whether to install requirements to run the TripleO '
                      'validations.')
                ),
    cfg.BoolOpt('enable_cinder',
                default=False,
                help=('Whether to install the Volume service. It is not '
                      'currently used in the undercloud.')),
    cfg.BoolOpt('enable_legacy_ceilometer_api',
                default=False,
                help=('Whether to enable legacy ceilometer api '
                      'in the Undercloud. '
                      'Note: Ceilometer API has been deprecated and will be '
                      'removed in future release. Please consider moving to '
                      'gnocchi/Aodh/Panko API instead.')
                ),
    cfg.BoolOpt('enable_legacy_ceilometer_collector',
                default=False,
                help=('Whether to enable legacy ceilometer collector '
                      'in the Undercloud. '
                      'Note: Ceilometer collector has been deprecated and '
                      'will be removed in future release.')
                ),
    cfg.BoolOpt('enable_novajoin',
                default=False,
                help=('Whether to install novajoin metadata service in '
                      'the Undercloud.')
                ),
    cfg.BoolOpt('enable_container_images_build',
                default=True,
                help=('Whether to enable docker container images to be build '
                      'on the undercloud.')
                ),
    cfg.StrOpt('ipa_otp',
               default='',
               help=('One Time Password to register Undercloud node with '
                     'an IPA server.  '
                     'Required when enable_novajoin = True.')
               ),
    cfg.BoolOpt('ipxe_enabled',
                default=True,
                help=('Whether to use iPXE for deploy and inspection.'),
                deprecated_name='ipxe_deploy',
                ),
    cfg.IntOpt('scheduler_max_attempts',
               default=30, min=1,
               help=('Maximum number of attempts the scheduler will make '
                     'when deploying the instance. You should keep it '
                     'greater or equal to the number of bare metal nodes '
                     'you expect to deploy at once to work around '
                     'potential race condition when scheduling.')),
    cfg.BoolOpt('clean_nodes',
                default=False,
                help=('Whether to clean overcloud nodes (wipe the hard drive) '
                      'between deployments and after the introspection.')),
    cfg.ListOpt('enabled_drivers',
                default=['pxe_ipmitool', 'pxe_drac', 'pxe_ilo'],
                help=('List of enabled bare metal drivers.')),
    cfg.ListOpt('enabled_hardware_types',
                default=['ipmi', 'redfish'],
                help=('List of enabled bare metal hardware types (next '
                      'generation drivers).')),
    cfg.StrOpt('docker_registry_mirror',
               default='',
               help=('An optional docker \'registry-mirror\' that will be'
                     'configured in /etc/docker/daemon.json.')
               ),
]

# Passwords, tokens, hashes
_auth_opts = [
    cfg.StrOpt('undercloud_db_password',
               help=('Password used for MySQL databases. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_admin_token',
               help=('Keystone admin token. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_admin_password',
               help=('Keystone admin password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_glance_password',
               help=('Glance service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_heat_encryption_key',
               help=('Heat db encryption key(must be 16, 24, or 32 characters.'
                     ' If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_heat_password',
               help=('Heat service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_heat_cfn_password',
               help=('Heat cfn service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_neutron_password',
               help=('Neutron service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_nova_password',
               help=('Nova service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_ironic_password',
               help=('Ironic service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_aodh_password',
               help=('Aodh service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_gnocchi_password',
               help=('Gnocchi service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_ceilometer_password',
               help=('Ceilometer service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_panko_password',
               help=('Panko service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_ceilometer_metering_secret',
               help=('Ceilometer metering secret. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_ceilometer_snmpd_user',
               default='ro_snmp_user',
               help=('Ceilometer snmpd read-only user. If this value is '
                     'changed from the default, the new value must be passed '
                     'in the overcloud environment as the parameter '
                     'SnmpdReadonlyUserName. This value must be between '
                     '1 and 32 characters long.')
               ),
    cfg.StrOpt('undercloud_ceilometer_snmpd_password',
               help=('Ceilometer snmpd password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_swift_password',
               help=('Swift service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_mistral_password',
               help=('Mistral service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_rabbit_cookie',
               help=('Rabbitmq cookie. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_rabbit_password',
               help=('Rabbitmq password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_rabbit_username',
               help=('Rabbitmq username. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_heat_stack_domain_admin_password',
               help=('Heat stack domain admin password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_swift_hash_suffix',
               help=('Swift hash suffix. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_haproxy_stats_password',
               help=('HAProxy stats password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_zaqar_password',
               help=('Zaqar password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_horizon_secret_key',
               help=('Horizon secret key. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_cinder_password',
               help=('Cinder service password. '
                     'If left unset, one will be automatically generated.')
               ),
    cfg.StrOpt('undercloud_novajoin_password',
               help=('Novajoin vendordata plugin service password. '
                     'If left unset, one will be automatically generated.')
               ),
]
CONF.register_opts(_opts)
CONF.register_opts(_auth_opts, group='auth')


def list_opts():
    return [(None, copy.deepcopy(_opts)),
            ('auth', copy.deepcopy(_auth_opts)),
            ]


def _configure_logging(level, filename):
    """Does the initial logging configuration

    This should only ever be called once.  If further changes to the logging
    config are needed they should be made directly on the LOG object.

    :param level: The desired logging level
    :param filename: The log file.  Set to None to disable file logging.
    """
    try:
        os.makedirs(os.path.dirname(PATHS.LOG_FILE))
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    logging.basicConfig(filename=filename,
                        format=DEFAULT_LOG_FORMAT,
                        level=level)
    global LOG
    LOG = logging.getLogger(__name__)
    if os.environ.get('OS_LOG_CAPTURE') != '1':
        handler = logging.StreamHandler()
        formatter = logging.Formatter(DEFAULT_LOG_FORMAT)
        handler.setFormatter(formatter)
        LOG.addHandler(handler)


def _load_config():
    conf_params = []
    if os.path.isfile(PATHS.PASSWORD_PATH):
        conf_params += ['--config-file', PATHS.PASSWORD_PATH]
    if os.path.isfile(PATHS.CONF_PATH):
        conf_params += ['--config-file', PATHS.CONF_PATH]
    CONF(conf_params)


def _run_command(args, env=None, name=None):
    """Run the command defined by args and return its output

    :param args: List of arguments for the command to be run.
    :param env: Dict defining the environment variables. Pass None to use
        the current environment.
    :param name: User-friendly name for the command being run. A value of
        None will cause args[0] to be used.
    """
    if name is None:
        name = args[0]
    try:
        return subprocess.check_output(args,
                                       stderr=subprocess.STDOUT,
                                       env=env).decode('utf-8')
    except subprocess.CalledProcessError as e:
        LOG.error('%s failed: %s', name, e.output)
        raise


def _run_live_command(args, env=None, name=None):
    """Run the command defined by args and log its output

    Takes the same arguments as _run_command, but runs the process
    asynchronously so the output can be logged while the process is still
    running.
    """
    if name is None:
        name = args[0]
    process = subprocess.Popen(args, env=env,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)
    while True:
        line = process.stdout.readline().decode('utf-8')
        if line:
            LOG.info(line.rstrip())
        if line == '' and process.poll() is not None:
            break
    if process.returncode != 0:
        raise RuntimeError('%s failed. See log for details.' % name)


def _check_hostname():
    """Check system hostname configuration

    Rabbit and Puppet require pretty specific hostname configuration. This
    function ensures that the system hostname settings are valid before
    continuing with the installation.
    """
    if CONF.undercloud_hostname is not None:
        args = ['sudo', 'hostnamectl', 'set-hostname',
                CONF.undercloud_hostname]
        _run_command(args, name='hostnamectl')

    LOG.info('Checking for a FQDN hostname...')
    args = ['sudo', 'hostnamectl', '--static']
    detected_static_hostname = _run_command(args, name='hostnamectl').rstrip()
    LOG.info('Static hostname detected as %s', detected_static_hostname)
    args = ['sudo', 'hostnamectl', '--transient']
    detected_transient_hostname = _run_command(args,
                                               name='hostnamectl').rstrip()
    LOG.info('Transient hostname detected as %s', detected_transient_hostname)
    if detected_static_hostname != detected_transient_hostname:
        LOG.error('Static hostname "%s" does not match transient hostname '
                  '"%s".', detected_static_hostname,
                  detected_transient_hostname)
        LOG.error('Use hostnamectl to set matching hostnames.')
        raise RuntimeError('Static and transient hostnames do not match')
    with open('/etc/hosts') as hosts_file:
        for line in hosts_file:
            if (not line.lstrip().startswith('#') and
                    detected_static_hostname in line.split()):
                break
        else:
            short_hostname = detected_static_hostname.split('.')[0]
            if short_hostname == detected_static_hostname:
                raise RuntimeError('Configured hostname is not fully '
                                   'qualified.')
            echo_cmd = ('echo 127.0.0.1 %s %s >> /etc/hosts' %
                        (detected_static_hostname, short_hostname))
            args = ['sudo', '/bin/bash', '-c', echo_cmd]
            _run_command(args, name='hostname-to-etc-hosts')
            LOG.info('Added hostname %s to /etc/hosts',
                     detected_static_hostname)


def _check_memory():
    """Check system memory

    The undercloud will not run properly in less than 8 GB of memory.
    This function verifies that at least that much is available before
    proceeding with install.
    """
    mem = psutil.virtual_memory()
    swap = psutil.swap_memory()
    total_mb = (mem.total + swap.total) / 1024 / 1024
    if total_mb < REQUIRED_MB:
        LOG.error('At least %d MB of memory is required for undercloud '
                  'installation.  A minimum of 8 GB is recommended. '
                  'Only detected %d MB' % (REQUIRED_MB, total_mb))
        raise RuntimeError('Insufficient memory available')


def _check_ipv6_enabled():
    """Test if IPv6 is enabled

    If /proc/net/if_inet6 exist ipv6 sysctl settings are available.
    """
    return os.path.isfile('/proc/net/if_inet6')


def _check_sysctl():
    """Check sysctl option availability

    The undercloud will not install properly if some of the expected sysctl
    values are not available to be set.
    """
    options = ['net.ipv4.ip_forward', 'net.ipv4.ip_nonlocal_bind']
    if _check_ipv6_enabled():
        options.append('net.ipv6.ip_nonlocal_bind')

    not_available = []
    for option in options:
        path = '/proc/sys/{opt}'.format(opt=option.replace('.', '/'))
        if not os.path.isfile(path):
            not_available.append(option)

    if not_available:
        LOG.error('Required sysctl options are not available. Check '
                  'that your kernel is up to date. Missing: '
                  '{options}'.format(options=", ".join(not_available)))
        raise RuntimeError('Missing sysctl options')


def _validate_network():
    def error_handler(message):
        LOG.error('Undercloud configuration validation failed: %s', message)
        raise validator.FailedValidation(message)

    params = {opt.name: CONF[opt.name] for opt in _opts}
    validator.validate_config(params, error_handler)


def _validate_no_ip_change():
    """Disallow provisioning interface IP changes

    Changing the provisioning network IP causes a number of issues, so we
    need to disallow it early in the install before configurations start to
    be changed.
    """
    os_net_config_file = '/etc/os-net-config/config.json'
    # Nothing to do if we haven't already installed
    if not os.path.isfile(
            os.path.expanduser(os_net_config_file)):
        return
    with open(os_net_config_file) as f:
        network_config = json.loads(f.read())
    try:
        ctlplane = [i for i in network_config.get('network_config', [])
                    if i['name'] == 'br-ctlplane'][0]
    except IndexError:
        # Nothing to check if br-ctlplane wasn't configured
        return
    existing_ip = ctlplane['addresses'][0]['ip_netmask']
    if existing_ip != CONF.local_ip:
        message = ('Changing the local_ip is not allowed.  Existing IP: '
                   '%s, Configured IP: %s') % (existing_ip,
                                               CONF.network_cidr)
        LOG.error(message)
        raise validator.FailedValidation(message)


def _validate_configuration():
    try:
        _check_hostname()
        _check_memory()
        _check_sysctl()
        _validate_network()
        _validate_no_ip_change()
    except RuntimeError as e:
        LOG.error('An error occurred during configuration validation, '
                  'please check your host configuration and try again. '
                  'Error message: {error}'.format(error=e))
        sys.exit(1)


def _generate_password(length=40):
    """Create a random password

    Copied from rdomanager-oscplugin.  This should eventually live in
    tripleo-common.
    """
    uuid_str = six.text_type(uuid.uuid4()).encode("UTF-8")
    return hashlib.sha1(uuid_str).hexdigest()[:length]


def _get_service_endpoints(name, format_str, public, internal, admin=None,
                           public_proto='http', internal_proto='http'):
    endpoints = {}
    upper_name = name.upper().replace('-', '_')
    public_port_key = 'port'

    if not admin:
        admin = internal
    if public_proto in ['https', 'wss']:
        public_port_key = 'ssl_port'

    endpoints['UNDERCLOUD_ENDPOINT_%s_PUBLIC' % upper_name] = (
        format_str % (public_proto, public['host'], public[public_port_key]))
    endpoints['UNDERCLOUD_ENDPOINT_%s_INTERNAL' % upper_name] = (
        format_str % (internal_proto, internal['host'], internal['port']))
    endpoints['UNDERCLOUD_ENDPOINT_%s_ADMIN' % upper_name] = (
        format_str % (internal_proto, admin['host'], admin['port']))
    return endpoints


def _generate_endpoints(instack_env):
    local_host = instack_env['LOCAL_IP']
    public_host = local_host
    public_proto = 'http'
    internal_host = local_host
    internal_proto = 'http'
    zaqar_ws_public_proto = 'ws'
    zaqar_ws_internal_proto = 'ws'

    if (CONF.undercloud_service_certificate or
            CONF.generate_service_certificate):
        public_host = CONF.undercloud_public_host
        internal_host = CONF.undercloud_admin_host
        public_proto = 'https'
        zaqar_ws_public_proto = 'wss'

    endpoints = {}

    endpoint_list = [
        ('heat',
            '%s://%s:%d/v1/%%(tenant_id)s',
            {'host': public_host, 'port': 8004, 'ssl_port': 13004},
            {'host': internal_host, 'port': 8004}),
        ('heat-cfn',
            '%s://%s:%d/v1/%%(tenant_id)s',
            {'host': public_host, 'port': 8000, 'ssl_port': 13800},
            {'host': internal_host, 'port': 8000}),
        ('heat-ui-proxy',
            '%s://%s:%d',
            {'host': public_host, 'port': 8004, 'ssl_port': 13004},
            {'host': internal_host, 'port': 8004}),
        ('heat-ui-config',
            '%s://%s:%d/heat/v1/%%(project_id)s',
            {'host': public_host, 'port': 3000, 'ssl_port': 443},
            {'host': internal_host, 'port': 3000}),
        ('neutron',
            '%s://%s:%d',
            {'host': public_host, 'port': 9696, 'ssl_port': 13696},
            {'host': internal_host, 'port': 9696}),
        ('glance',
            '%s://%s:%d',
            {'host': public_host, 'port': 9292, 'ssl_port': 13292},
            {'host': internal_host, 'port': 9292}),
        ('nova',
            '%s://%s:%d/v2.1',
            {'host': public_host, 'port': 8774, 'ssl_port': 13774},
            {'host': internal_host, 'port': 8774}),
        ('placement',
            '%s://%s:%d/placement',
            {'host': public_host, 'port': 8778, 'ssl_port': 13778},
            {'host': internal_host, 'port': 8778}),
        ('ceilometer',
            '%s://%s:%d',
            {'host': public_host, 'port': 8777, 'ssl_port': 13777},
            {'host': internal_host, 'port': 8777}),
        ('keystone',
            '%s://%s:%d',
            {'host': public_host, 'port': 5000, 'ssl_port': 13000},
            {'host': internal_host, 'port': 5000},
            {'host': internal_host, 'port': 35357}),
        ('keystone-ui-config',
            '%s://%s:%d/keystone/v3',
            {'host': public_host, 'port': 3000, 'ssl_port': 443},
            {'host': internal_host, 'port': 3000},
            {'host': internal_host, 'port': 35357}),
        ('swift',
            '%s://%s:%d/v1/AUTH_%%(tenant_id)s',
            {'host': public_host, 'port': 8080, 'ssl_port': 13808},
            {'host': internal_host, 'port': 8080}),
        ('swift-ui-proxy',
            '%s://%s:%d',
            {'host': public_host, 'port': 8080, 'ssl_port': 13808},
            {'host': internal_host, 'port': 8080}),
        ('swift-ui-config',
            '%s://%s:%d/swift/v1/AUTH_%%(project_id)s',
            {'host': public_host, 'port': 3000, 'ssl_port': 443},
            {'host': internal_host, 'port': 3000}),
        ('ironic',
            '%s://%s:%d',
            {'host': public_host, 'port': 6385, 'ssl_port': 13385},
            {'host': internal_host, 'port': 6385}),
        ('ironic-ui-config',
            '%s://%s:%d/ironic',
            {'host': public_host, 'port': 3000, 'ssl_port': 443},
            {'host': internal_host, 'port': 3000}),
        ('ironic_inspector',
            '%s://%s:%d',
            {'host': public_host, 'port': 5050, 'ssl_port': 13050},
            {'host': internal_host, 'port': 5050}),
        ('aodh',
            '%s://%s:%d',
            {'host': public_host, 'port': 8042, 'ssl_port': 13042},
            {'host': internal_host, 'port': 8042}),
        ('gnocchi',
            '%s://%s:%d',
            {'host': public_host, 'port': 8041, 'ssl_port': 13041},
            {'host': internal_host, 'port': 8041}),
        ('panko',
            '%s://%s:%d',
            {'host': public_host, 'port': 8779, 'ssl_port': 13779},
            {'host': internal_host, 'port': 8779}),
        ('mistral',
            '%s://%s:%d/v2',
            {'host': public_host, 'port': 8989, 'ssl_port': 13989},
            {'host': internal_host, 'port': 8989}),
        ('mistral-ui-proxy',
            '%s://%s:%d',
            {'host': public_host, 'port': 8989, 'ssl_port': 13989},
            {'host': internal_host, 'port': 8989}),
        ('mistral-ui-config',
            '%s://%s:%d/mistral/v2',
            {'host': public_host, 'port': 3000, 'ssl_port': 443},
            {'host': internal_host, 'port': 3000}),
        ('zaqar',
            '%s://%s:%d',
            {'host': public_host, 'port': 8888, 'ssl_port': 13888},
            {'host': internal_host, 'port': 8888}),
        ('cinder',
            '%s://%s:%d/v1/%%(tenant_id)s',
            {'host': public_host, 'port': 8776, 'ssl_port': 13776},
            {'host': internal_host, 'port': 8776}),
        ('cinder_v2',
            '%s://%s:%d/v2/%%(tenant_id)s',
            {'host': public_host, 'port': 8776, 'ssl_port': 13776},
            {'host': internal_host, 'port': 8776}),
        ('cinder_v3',
            '%s://%s:%d/v3/%%(tenant_id)s',
            {'host': public_host, 'port': 8776, 'ssl_port': 13776},
            {'host': internal_host, 'port': 8776}),
    ]
    for endpoint_data in endpoint_list:
        endpoints.update(
            _get_service_endpoints(*endpoint_data,
                                   public_proto=public_proto,
                                   internal_proto=internal_proto))

    # Zaqar's websocket endpoint
    # NOTE(jaosorior): Zaqar's websocket endpoint doesn't support being proxied
    # on a different port. If that's done it will ignore the handshake and
    # won't work.
    endpoints.update(_get_service_endpoints(
        'zaqar-websocket',
        '%s://%s:%d',
        {'host': public_host, 'port': 9000, 'ssl_port': 9000},
        {'host': internal_host, 'port': 9000},
        public_proto=zaqar_ws_public_proto,
        internal_proto=zaqar_ws_internal_proto))

    endpoints.update(_get_service_endpoints(
        'zaqar-ui-proxy',
        '%s://%s:%d',
        {'host': public_host, 'port': 9000, 'ssl_port': 443,
         'zaqar_ws_public_proto': 'ws'},
        {'host': internal_host, 'port': 9000},
        public_proto=zaqar_ws_public_proto,
        internal_proto=zaqar_ws_internal_proto))

    endpoints.update(_get_service_endpoints(
        'zaqar-ui-config',
        '%s://%s:%d/zaqar',
        {'host': public_host, 'port': 3000, 'ssl_port': 443,
         'zaqar_ws_public_proto': 'wss'},
        {'host': internal_host, 'port': 3000},
        public_proto=zaqar_ws_public_proto,
        internal_proto=zaqar_ws_internal_proto))

    # The swift admin endpoint has a different format from the others
    endpoints['UNDERCLOUD_ENDPOINT_SWIFT_ADMIN'] = (
        '%s://%s:%s' % (internal_proto, internal_host, 8080))
    instack_env.update(endpoints)


def _write_password_file(instack_env):
    with open(PATHS.PASSWORD_PATH, 'w') as password_file:
        password_file.write('[auth]\n')
        for opt in _auth_opts:
            env_name = opt.name.upper()
            value = CONF.auth[opt.name]
            if not value:
                # Heat requires this encryption key to be a specific length
                if env_name == 'UNDERCLOUD_HEAT_ENCRYPTION_KEY':
                    value = _generate_password(32)
                else:
                    value = _generate_password()
                LOG.info('Generated new password for %s', opt.name)
            instack_env[env_name] = value
            password_file.write('%s=%s\n' % (opt.name, value))
    os.chmod(PATHS.PASSWORD_PATH, 0o600)


def _member_role_exists():
    # This is a workaround for puppet removing the deprecated _member_
    # role on upgrade - if it exists we must restore role assignments
    # or trusts stored in the undercloud heat will break
    user, password, project, auth_url = _get_auth_values()
    auth_kwargs = {
        'auth_url': auth_url,
        'username': user,
        'password': password,
        'project_name': project,
        'project_domain_name': 'Default',
        'user_domain_name': 'Default',
    }
    auth_plugin = ks_auth.Password(**auth_kwargs)
    sess = session.Session(auth=auth_plugin)
    disc = discover.Discover(session=sess)
    c = disc.create_client()
    try:
        member_role = [r for r in c.roles.list() if r.name == '_member_'][0]
    except IndexError:
        # Do nothing if there is no _member_ role
        return
    if c.version == 'v2.0':
        client_projects = c.tenants
    else:
        client_projects = c.projects
    admin_project = [t for t in client_projects.list() if t.name == 'admin'][0]
    admin_user = [u for u in c.users.list() if u.name == 'admin'][0]
    if c.version == 'v2.0':
        try:
            c.roles.add_user_role(admin_user, member_role, admin_project.id)
            LOG.info('Added _member_ role to admin user')
        except ks_exceptions.http.Conflict:
            # They already had the role
            pass
    else:
        try:
            c.roles.grant(member_role,
                          user=admin_user,
                          project=admin_project.id)
            LOG.info('Added _member_ role to admin user')
        except ks_exceptions.http.Conflict:
            # They already had the role
            pass


class InstackEnvironment(dict):
    """An environment to pass to Puppet with some safety checks.

    Keeps lists of variables we add to the operating system environment,
    and ensures that we don't anything not defined there.
    """

    INSTACK_KEYS = {'HOSTNAME', 'ELEMENTS_PATH', 'NODE_DIST', 'JSONFILE',
                    'REG_METHOD', 'REG_HALT_UNREGISTER', 'PUBLIC_INTERFACE_IP'}
    """The variables instack and/or used elements can read."""

    DYNAMIC_KEYS = {'INSPECTION_COLLECTORS', 'INSPECTION_KERNEL_ARGS',
                    'INSPECTION_NODE_NOT_FOUND_HOOK',
                    'TRIPLEO_INSTALL_USER', 'TRIPLEO_UNDERCLOUD_CONF_FILE',
                    'TRIPLEO_UNDERCLOUD_PASSWORD_FILE',
                    'ENABLED_POWER_INTERFACES',
                    'ENABLED_MANAGEMENT_INTERFACES', 'SYSCTL_SETTINGS'}
    """The variables we calculate in _generate_environment call."""

    PUPPET_KEYS = DYNAMIC_KEYS | {opt.name.upper() for _, group in list_opts()
                                  for opt in group}
    """Keys we pass for formatting the resulting hieradata."""

    SET_ALLOWED_KEYS = DYNAMIC_KEYS | INSTACK_KEYS | PUPPET_KEYS
    """Keys which we allow to add/change in this environment."""

    def __init__(self):
        super(InstackEnvironment, self).__init__(os.environ)

    def __setitem__(self, key, value):
        if key not in self.SET_ALLOWED_KEYS:
            raise KeyError('Key %s is not allowed for an InstackEnvironment' %
                           key)
        return super(InstackEnvironment, self).__setitem__(key, value)


def _make_list(values):
    """Generate a list suitable to pass to templates."""
    return '[%s]' % ', '.join('"%s"' % item for item in values)


def _generate_sysctl_settings():
    sysctl_settings = {}
    sysctl_settings.update({"net.ipv4.ip_nonlocal_bind": {"value": 1}})
    if _check_ipv6_enabled():
        sysctl_settings.update({"net.ipv6.ip_nonlocal_bind": {"value": 1}})
    return json.dumps(sysctl_settings)


def _generate_environment(instack_root):
    """Generate an environment dict for instack

    The returned dict will have the necessary values for use as the env
    parameter when calling instack via the subprocess module.

    :param instack_root: The path containing the instack-undercloud elements
        and json files.
    """
    instack_env = InstackEnvironment()
    # Rabbit uses HOSTNAME, so we need to make sure it's right
    instack_env['HOSTNAME'] = CONF.undercloud_hostname or socket.gethostname()

    # Find the paths we need
    json_file_dir = '/usr/share/instack-undercloud/json-files'
    if not os.path.isdir(json_file_dir):
        json_file_dir = os.path.join(instack_root, 'json-files')
    instack_undercloud_elements = '/usr/share/instack-undercloud'
    if not os.path.isdir(instack_undercloud_elements):
        instack_undercloud_elements = os.path.join(instack_root, 'elements')
    tripleo_puppet_elements = '/usr/share/tripleo-puppet-elements'
    if not os.path.isdir(tripleo_puppet_elements):
        tripleo_puppet_elements = os.path.join(os.getcwd(),
                                               'tripleo-puppet-elements',
                                               'elements')
    if 'ELEMENTS_PATH' in os.environ:
        instack_env['ELEMENTS_PATH'] = os.environ['ELEMENTS_PATH']
    else:
        instack_env['ELEMENTS_PATH'] = (
            '%s:%s:'
            '/usr/share/tripleo-image-elements:'
            '/usr/share/diskimage-builder/elements'
        ) % (tripleo_puppet_elements, instack_undercloud_elements)

    # Distro-specific values
    distro = platform.linux_distribution()[0]
    if distro.startswith('Red Hat Enterprise Linux'):
        instack_env['NODE_DIST'] = os.environ.get('NODE_DIST') or 'rhel7'
        instack_env['JSONFILE'] = (
            os.environ.get('JSONFILE') or
            os.path.join(json_file_dir, 'rhel-7-undercloud-packages.json')
        )
        instack_env['REG_METHOD'] = 'disable'
        instack_env['REG_HALT_UNREGISTER'] = '1'
    elif distro.startswith('CentOS'):
        instack_env['NODE_DIST'] = os.environ.get('NODE_DIST') or 'centos7'
        instack_env['JSONFILE'] = (
            os.environ.get('JSONFILE') or
            os.path.join(json_file_dir, 'centos-7-undercloud-packages.json')
        )
    elif distro.startswith('Fedora'):
        instack_env['NODE_DIST'] = os.environ.get('NODE_DIST') or 'fedora'
        raise RuntimeError('Fedora is not currently supported')
    else:
        raise RuntimeError('%s is not supported' % distro)

    # Convert conf opts to env values
    for opt in _opts:
        env_name = opt.name.upper()
        instack_env[env_name] = six.text_type(CONF[opt.name])
    # Opts that needs extra processing
    if CONF.inspection_runbench and not CONF.inspection_extras:
        raise RuntimeError('inspection_extras must be enabled for '
                           'inspection_runbench to work')
    if CONF.inspection_extras:
        instack_env['INSPECTION_COLLECTORS'] = 'default,extra-hardware,logs'
    else:
        instack_env['INSPECTION_COLLECTORS'] = 'default,logs'

    inspection_kernel_args = []
    if CONF.undercloud_debug:
        inspection_kernel_args.append('ipa-debug=1')
    if CONF.inspection_runbench:
        inspection_kernel_args.append('ipa-inspection-benchmarks=cpu,mem,disk')
    if CONF.inspection_extras:
        inspection_kernel_args.append('ipa-inspection-dhcp-all-interfaces=1')
        inspection_kernel_args.append('ipa-collect-lldp=1')

    instack_env['INSPECTION_KERNEL_ARGS'] = ' '.join(inspection_kernel_args)

    # Ensure correct rendering of the list and uniqueness of the items
    enabled_drivers = set(CONF.enabled_drivers)
    enabled_hardware_types = set(CONF.enabled_hardware_types)
    if CONF.enable_node_discovery:
        if (CONF.discovery_default_driver not in (enabled_drivers |
                                                  enabled_hardware_types)):
            enabled_drivers.add(CONF.discovery_default_driver)
        instack_env['INSPECTION_NODE_NOT_FOUND_HOOK'] = 'enroll'
    else:
        instack_env['INSPECTION_NODE_NOT_FOUND_HOOK'] = ''

    # In most cases power and management interfaces are called the same, so we
    # use one variable for them.
    enabled_interfaces = set()
    if 'ipmi' in enabled_hardware_types:
        enabled_interfaces.add('ipmitool')
    if 'redfish' in enabled_hardware_types:
        enabled_interfaces.add('redfish')

    instack_env['ENABLED_DRIVERS'] = _make_list(enabled_drivers)
    instack_env['ENABLED_HARDWARE_TYPES'] = _make_list(enabled_hardware_types)

    enabled_interfaces = _make_list(enabled_interfaces)
    instack_env['ENABLED_POWER_INTERFACES'] = enabled_interfaces
    instack_env['ENABLED_MANAGEMENT_INTERFACES'] = enabled_interfaces

    instack_env['SYSCTL_SETTINGS'] = _generate_sysctl_settings()

    if CONF.docker_registry_mirror:
        instack_env['DOCKER_REGISTRY_MIRROR'] = CONF.docker_registry_mirror

    instack_env['PUBLIC_INTERFACE_IP'] = instack_env['LOCAL_IP']
    instack_env['LOCAL_IP'] = instack_env['LOCAL_IP'].split('/')[0]
    if instack_env['UNDERCLOUD_SERVICE_CERTIFICATE']:
        instack_env['UNDERCLOUD_SERVICE_CERTIFICATE'] = os.path.abspath(
            instack_env['UNDERCLOUD_SERVICE_CERTIFICATE'])
    # We're not in a chroot so this doesn't make sense, and it causes weird
    # errors if it's set.
    if instack_env.get('DIB_YUM_REPO_CONF'):
        del instack_env['DIB_YUM_REPO_CONF']

    instack_env['TRIPLEO_INSTALL_USER'] = getpass.getuser()
    instack_env['TRIPLEO_UNDERCLOUD_CONF_FILE'] = PATHS.CONF_PATH
    instack_env['TRIPLEO_UNDERCLOUD_PASSWORD_FILE'] = PATHS.PASSWORD_PATH

    # Mustache conditional logic requires ENABLE_NOVAJOIN to be undefined
    # when novajoin is not enabled.
    if instack_env['ENABLE_NOVAJOIN'].lower() == 'false':
        del instack_env['ENABLE_NOVAJOIN']

    _generate_endpoints(instack_env)

    _write_password_file(instack_env)

    if CONF.generate_service_certificate:
        public_host = CONF.undercloud_public_host
        instack_env['UNDERCLOUD_SERVICE_CERTIFICATE'] = (
            '/etc/pki/tls/certs/undercloud-%s.pem' % public_host)

    return instack_env


def _get_template_path(template):
    local_template_path = os.path.join(
        os.path.dirname(__file__),
        '..',
        'templates',
        template)
    installed_template_path = os.path.join(
        '/usr/share/instack-undercloud/templates',
        template)
    if os.path.exists(local_template_path):
        return local_template_path
    else:
        return installed_template_path


def _generate_init_data(instack_env):
    context = instack_env.copy()

    if CONF.hieradata_override:
        hiera_entry = os.path.splitext(
            os.path.basename(CONF.hieradata_override))[0]
        dst = os.path.join('/etc/puppet/hieradata',
                           os.path.basename(CONF.hieradata_override))
        _run_command(['sudo', 'mkdir', '-p', '/etc/puppet/hieradata'])
        _run_command(['sudo', 'cp', CONF.hieradata_override, dst])
        _run_command(['sudo', 'chmod', '0644', dst])
    else:
        hiera_entry = ''

    if CONF.net_config_override:
        net_config_json = open(CONF.net_config_override).read()
    else:
        net_config_json = \
            open(_get_template_path('net-config.json.template')).read()

    context['HIERADATA_OVERRIDE'] = hiera_entry
    context['UNDERCLOUD_NAMESERVERS'] = json.dumps(
        CONF.undercloud_nameservers)
    partials = {'net_config': net_config_json}
    renderer = pystache.Renderer(partials=partials)
    template = _get_template_path('config.json.template')

    with open(template) as f:
        config_json = renderer.render(f.read(), context)

    config_json = config_json.replace('&quot;', '"')
    cfn_path = '/var/lib/heat-cfntools/cfn-init-data'
    tmp_json = tempfile.mkstemp()[1]
    with open(tmp_json, 'w') as f:
        print(config_json, file=f)

    if not os.path.exists(os.path.dirname(cfn_path)):
        _run_command(['sudo', 'mkdir', '-p', os.path.dirname(cfn_path)])

    _run_command(['sudo', 'mv', tmp_json, cfn_path])
    _run_command(['sudo', 'chmod', '0644', cfn_path])


def _run_instack(instack_env):
    args = ['sudo', '-E', 'instack', '-p', instack_env['ELEMENTS_PATH'],
            '-j', instack_env['JSONFILE'],
            ]
    LOG.info('Running instack')
    _run_live_command(args, instack_env, 'instack')
    LOG.info('Instack completed successfully')


def _run_yum_clean_all(instack_env):
    args = ['sudo', 'yum', 'clean', 'all']
    LOG.info('Running yum clean all')
    _run_live_command(args, instack_env, 'yum-clean-all')
    LOG.info('yum-clean-all completed successfully')


def _run_yum_update(instack_env):
    args = ['sudo', 'yum', 'update', '-y']
    LOG.info('Running yum update')
    _run_live_command(args, instack_env, 'yum-update')
    LOG.info('yum-update completed successfully')


def _run_orc(instack_env):
    args = ['sudo', 'os-refresh-config']
    LOG.info('Running os-refresh-config')
    _run_live_command(args, instack_env, 'os-refresh-config')
    LOG.info('os-refresh-config completed successfully')


def _extract_from_stackrc(name):
    """Extract authentication values from stackrc

    :param name: The value to be extracted.  For example: OS_USERNAME or
        OS_AUTH_URL.
    """
    with open(os.path.expanduser('~/stackrc')) as f:
        for line in f:
            if name in line:
                parts = line.split('=')
                return parts[1].rstrip()


def _ensure_user_identity(id_path):
    if not os.path.isfile(id_path):
        args = ['ssh-keygen', '-t', 'rsa', '-N', '', '-f', id_path]
        _run_command(args)
        LOG.info('Generated new ssh key in ~/.ssh/id_rsa')


def _get_auth_values():
    """Get auth values from stackrc

    Returns the user, password, project and auth_url as read from stackrc,
    in that order as a tuple.
    """
    user = _extract_from_stackrc('OS_USERNAME')
    password = _run_command(['sudo', 'hiera', 'admin_password']).rstrip()
    project = _extract_from_stackrc('OS_PROJECT_NAME')
    auth_url = _extract_from_stackrc('OS_AUTH_URL')
    return user, password, project, auth_url


def _configure_ssh_keys(nova):
    """Configure default ssh keypair in Nova

    Generates a new ssh key for the current user if one does not already
    exist, then uploads that to Nova as the 'default' keypair.
    """
    id_path = os.path.expanduser('~/.ssh/id_rsa')
    _ensure_user_identity(id_path)

    try:
        nova.keypairs.get('default')
    except exceptions.NotFound:
        with open(id_path + '.pub') as pubkey:
            nova.keypairs.create('default', pubkey.read().rstrip())


def _delete_default_flavors(nova):
    """Delete the default flavors from Nova

    The m1.tiny, m1.small, etc. flavors are not useful on an undercloud.
    """
    to_delete = ['m1.tiny', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge']
    for f in nova.flavors.list():
        if f.name in to_delete:
            nova.flavors.delete(f.id)


def _ensure_flavor(nova, name, profile=None):
    try:
        flavor = nova.flavors.create(name, 4096, 1, 40)
    except exceptions.Conflict:
        LOG.info('Not creating flavor "%s" because it already exists.', name)
        return
    keys = {'capabilities:boot_option': 'local'}
    if profile is not None:
        keys['capabilities:profile'] = profile
    flavor.set_keys(keys)
    message = 'Created flavor "%s" with profile "%s"'
    LOG.info(message, name, profile)


def _copy_stackrc():
    args = ['sudo', 'cp', '/root/stackrc', os.path.expanduser('~')]
    try:
        _run_command(args, name='Copy stackrc')
    except subprocess.CalledProcessError:
        LOG.info("/root/stackrc not found, this is OK on initial deploy")
    args = ['sudo', 'chown', getpass.getuser() + ':',
            os.path.expanduser('~/stackrc')]
    _run_command(args, name='Chown stackrc')


def _clean_os_refresh_config():
    orc_dirs = glob.glob('/usr/libexec/os-refresh-config/*')
    args = ['sudo', 'rm', '-rf'] + orc_dirs
    _run_command(args, name='Clean os-refresh-config')


def _clean_os_collect_config():
    occ_dir = '/var/lib/os-collect-config'
    args = ['sudo', 'rm', '-fr', occ_dir]
    _run_command(args, name='Clean os-collect-config')


def _create_mistral_config_environment(instack_env, mistral):
    # Store the snmpd password in a Mistral environment so it can be accessed
    # by the Mistral actions.
    snmpd_password = instack_env["UNDERCLOUD_CEILOMETER_SNMPD_PASSWORD"]

    env_name = "tripleo.undercloud-config"
    try:
        mistral.environments.get(env_name)
    except ks_exceptions.NotFound:
        mistral.environments.create(
            name=env_name,
            variables=json.dumps({
                "undercloud_ceilometer_snmpd_password": snmpd_password
            }))


def _migrate_plans(mistral, swift, plans):
    """Migrate plan environments from Mistral to Swift."""
    plan_env_filename = 'plan-environment.yaml'

    for plan in plans:
        headers, objects = swift.get_container(plan)

        if headers.get('x-container-meta-usage-tripleo') != 'plan':
            continue

        try:
            swift.get_object(plan, plan_env_filename)
        except swiftclient.ClientException:
            LOG.info('Migrating environment for plan %s to Swift.' % plan)
            env = mistral.environments.get(plan).variables
            yaml_string = yaml.safe_dump(env, default_flow_style=False)
            swift.put_object(plan, plan_env_filename, yaml_string)
            mistral.environments.delete(plan)


def _create_default_plan(mistral, plans, timeout=360):
    plan_name = 'overcloud'
    queue_name = str(uuid.uuid4())

    if plan_name in plans:
        LOG.info('Not creating default plan "%s" because it already exists.',
                 plan_name)
        return

    execution = mistral.executions.create(
        'tripleo.plan_management.v1.create_default_deployment_plan',
        workflow_input={'container': plan_name, 'queue_name': queue_name}
    )

    timeout_at = time.time() + timeout

    while time.time() < timeout_at:
        exe = mistral.executions.get(execution.id)
        if exe.state == "RUNNING":
            time.sleep(5)
            continue
        if exe.state == "SUCCESS":
            return
        else:
            raise RuntimeError(
                "Failed to create the default Deployment Plan. Please check "
                "the create_default_deployment_plan execution in Mistral with "
                "`openstack workflow execution list`.")
    else:
        exe = mistral.executions.get(execution.id)
        LOG.error("Timed out waiting for execution %s to finish. State: %s",
                  exe.id, exe.state)
        raise RuntimeError(
            "Timed out creating the default Deployment Plan. Please check "
            "the create_default_deployment_plan execution in Mistral with "
            "`openstack workflow execution list`.")


def _prepare_ssh_environment(mistral):
    mistral.executions.create('tripleo.validations.v1.copy_ssh_key')


def _post_config_mistral(instack_env, mistral, swift):
    plans = [container["name"] for container in swift.get_account()[1]]

    _create_mistral_config_environment(instack_env, mistral)
    _migrate_plans(mistral, swift, plans)
    _create_default_plan(mistral, plans)

    if CONF.enable_validations:
        _prepare_ssh_environment(mistral)


def _post_config(instack_env):
    _copy_stackrc()
    user, password, project, auth_url = _get_auth_values()
    auth_kwargs = {
        'auth_url': auth_url,
        'username': user,
        'password': password,
        'project_name': project,
        'project_domain_name': 'Default',
        'user_domain_name': 'Default',
    }
    auth_plugin = ks_auth.Password(**auth_kwargs)
    sess = session.Session(auth=auth_plugin)
    # TODO(andreykurilin): remove this check with support of novaclient 6.0.0
    if nc.__version__[0] == "6":
        nova = novaclient.Client(2, user, password, project, auth_url=auth_url)
    else:
        nova = novaclient.Client(2, user, password, auth_url=auth_url,
                                 project_name=project)

    _configure_ssh_keys(nova)
    _delete_default_flavors(nova)

    _ensure_flavor(nova, 'baremetal')
    _ensure_flavor(nova, 'control', 'control')
    _ensure_flavor(nova, 'compute', 'compute')
    _ensure_flavor(nova, 'ceph-storage', 'ceph-storage')
    _ensure_flavor(nova, 'block-storage', 'block-storage')
    _ensure_flavor(nova, 'swift-storage', 'swift-storage')

    mistral_url = instack_env['UNDERCLOUD_ENDPOINT_MISTRAL_PUBLIC']
    mistral = mistralclient.client(
        mistral_url=mistral_url,
        session=sess)
    swift = swiftclient.Connection(
        authurl=auth_url,
        session=sess
    )
    _post_config_mistral(instack_env, mistral, swift)
    _member_role_exists()


def _handle_upgrade_fact(upgrade=False):
    """Create an upgrade fact for use in puppet

    Since we don't run different puppets depending on if it's an upgrade or
    not, we need to be able to pass a flag into puppet to let it know if
    we're doing an upgrade. This is helpful when trying to handle state
    transitions from an already installed undercloud. This function creates
    a static fact named undercloud_upgrade only after the install has occurred.
    When invoked with upgrade=True, the $::undercloud_upgrade fact should
    be set to true.

    :param upgrade: Boolean indicating if this is an upgrade action or not
    """

    fact_string = 'undercloud_upgrade={}'.format(upgrade)
    fact_path = '/etc/facter/facts.d/undercloud_upgrade.txt'
    if not os.path.exists(os.path.dirname(fact_path)) and upgrade:
        _run_command(['sudo', 'mkdir', '-p', os.path.dirname(fact_path)])

    # We only need to ensure the fact is correct when we've already installed
    # the undercloud.
    if os.path.exists(os.path.dirname(fact_path)):
        tmp_fact = tempfile.mkstemp()[1]
        with open(tmp_fact, 'w') as f:
            f.write(fact_string.lower())
        _run_command(['sudo', 'mv', tmp_fact, fact_path])
        _run_command(['sudo', 'chmod', '0644', fact_path])


def _die_tuskar_die():
    """Remove tuskar* packages

    Make sure to remove tuskar https://bugs.launchpad.net/tripleo/+bug/1691744
    # openstack-[tuskar, tuskar-ui, tuskar-ui-extras] & python-tuskarclient
    """
    try:
        _run_command(['sudo', 'yum', 'remove', '-y', '*tuskar*'])
    except subprocess.CalledProcessError as e:
        LOG.error('Error with tuskar removal task %s - continuing', e.output)


def install(instack_root, upgrade=False):
    """Install the undercloud

    :param instack_root: The path containing the instack-undercloud elements
        and json files.
    """
    undercloud_operation = "upgrade" if upgrade else "install"
    try:
        _configure_logging(DEFAULT_LOG_LEVEL, PATHS.LOG_FILE)
        LOG.info('Logging to %s', PATHS.LOG_FILE)
        _load_config()
        _clean_os_refresh_config()
        _clean_os_collect_config()
        _validate_configuration()
        instack_env = _generate_environment(instack_root)
        _generate_init_data(instack_env)
        if upgrade:
            # We didn't complete the M->N upgrades correctly with a
            # `nova-manage db online_data_migrations` command before. This
            # could cause the post-upgrade db sync to fail. Better be safe
            # than sorry and run it before package upgrade.
            _run_command(['sudo', '/usr/bin/nova-manage', 'db',
                          'online_data_migrations'])
            # Even if we backport https://review.openstack.org/#/c/457478/
            # into stable branches of puppet-ironic, we still need a way
            # to handle existing deployments.
            # This task will fix ironic-dbsync.log ownership on existing
            # deployments during an upgrade. It can be removed after we
            # release Pike.
            _run_command(['sudo', '/usr/bin/chown', 'ironic:ironic',
                          '/var/log/ironic/ironic-dbsync.log'])
            _die_tuskar_die()
        if CONF.undercloud_update_packages:
            _run_yum_clean_all(instack_env)
            _run_yum_update(instack_env)
        _handle_upgrade_fact(upgrade)
        _run_instack(instack_env)
        _run_orc(instack_env)
        _post_config(instack_env)
        _run_command(['sudo', 'rm', '-f', '/tmp/svc-map-services'], None, 'rm')
    except Exception as e:
        LOG.debug("An exception occurred", exc_info=True)
        LOG.error(FAILURE_MESSAGE,
                  {'undercloud_operation': undercloud_operation,
                   'exception': six.text_type(e),
                   'log_file': PATHS.LOG_FILE})
        if CONF.undercloud_debug:
            raise
        sys.exit(1)
    else:
        LOG.info(COMPLETION_MESSAGE,
                 {'undercloud_operation': undercloud_operation,
                  'password_path': PATHS.PASSWORD_PATH,
                  'stackrc_path': os.path.expanduser('~/stackrc')})