-
Notifications
You must be signed in to change notification settings - Fork 63
/
bootstrap.py
executable file
·1600 lines (1381 loc) · 72.5 KB
/
bootstrap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
Script to register a new host to Foreman/Satellite
or move it from Satellite 5 to 6.
Use `pydoc ./bootstrap.py` to get the documentation.
Use `awk -F'# >' 'NF>1 {print $2}' ./bootstrap.py` to see the flow.
Use `/usr/libexec/platform-python bootstrap.py` on RHEL8
"""
import getpass
try:
# pylint:disable=invalid-name
import urllib2
from urllib import urlencode
urllib_urlopen = urllib2.urlopen
urllib_urlerror = urllib2.URLError
urllib_httperror = urllib2.HTTPError
urllib_basehandler = urllib2.BaseHandler
urllib_request = urllib2.Request
urllib_build_opener = urllib2.build_opener
urllib_install_opener = urllib2.install_opener
except ImportError:
# pylint:disable=invalid-name,no-member
import urllib
import urllib.request
import urllib.error
from urllib.parse import urlencode
urllib_urlopen = urllib.request.urlopen
urllib_urlerror = urllib.error.URLError
urllib_httperror = urllib.error.HTTPError
urllib_basehandler = urllib.request.BaseHandler
urllib_request = urllib.request.Request
urllib_build_opener = urllib.request.build_opener
urllib_install_opener = urllib.request.install_opener
import base64
import sys
try:
from commands import getstatusoutput
NEED_STATUS_SHIFT = True
except ImportError:
from subprocess import getstatusoutput
NEED_STATUS_SHIFT = False
import platform
import socket
import os
import pwd
import glob
import shutil
import tempfile
from datetime import datetime
from optparse import OptionParser # pylint:disable=deprecated-module
try:
from ConfigParser import SafeConfigParser
except ImportError:
from configparser import ConfigParser as SafeConfigParser
try:
import yum # pylint:disable=import-error
USE_YUM = True
except ImportError:
import dnf # pylint:disable=import-error
USE_YUM = False
import rpm # pylint:disable=import-error
VERSION = '1.7.9'
# Python 2.4 only supports octal numbers by prefixing '0'
# Python 3 only support octal numbers by prefixing '0o'
# Therefore use the decimal notation for file permissions
OWNER_ONLY_DIR = 448 # octal: 700
OWNER_ONLY_FILE = 384 # octal: 600
def get_architecture():
"""
Helper function to get the architecture x86_64 vs. x86.
"""
return os.uname()[4]
ERROR_COLORS = {
"""Colors to be used by the multiple `print_*` functions."""
'HEADER': '\033[95m',
'OKBLUE': '\033[94m',
'OKGREEN': '\033[92m',
'WARNING': '\033[93m',
'FAIL': '\033[91m',
'ENDC': '\033[0m',
}
SUBSCRIPTION_MANAGER_SERVER_TIMEOUT_VERSION = '1.18.2'
SUBSCRIPTION_MANAGER_MIGRATION_MINIMAL_VERSION = '1.14.2'
SUBSCRIPTION_MANAGER_MIGRATION_REMOVE_PKGS_VERSION = '1.18.2'
def filter_string(string):
"""Helper function to filter out passwords from strings"""
if options.password:
string = string.replace(options.password, '******')
if options.legacy_password:
string = string.replace(options.legacy_password, '******')
return string
def print_error(msg):
"""Helper function to output an ERROR message."""
print_message(color_string('ERROR', 'FAIL'), 'EXITING: [%s] failed to execute properly.' % msg)
def print_warning(msg):
"""Helper function to output a WARNING message."""
print_message(color_string('WARNING', 'WARNING'), 'NON-FATAL: [%s] failed to execute properly.' % msg)
def print_success(msg):
"""Helper function to output a SUCCESS message."""
print_message(color_string('SUCCESS', 'OKGREEN'), '[%s], completed successfully.' % msg)
def print_running(msg):
"""Helper function to output a RUNNING message."""
print_message(color_string('RUNNING', 'OKBLUE'), '[%s]' % msg)
def print_generic(msg):
"""Helper function to output a NOTIFICATION message."""
print_message('NOTIFICATION', '[%s]' % msg)
def print_message(prefix, msg):
"""Helper function to output a message with a prefix"""
print("[%s], [%s], %s" % (prefix, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), msg))
def color_string(msg, color):
"""Helper function to add ANSII colors to a message"""
return '%s%s%s' % (ERROR_COLORS[color], msg, ERROR_COLORS['ENDC'])
def exec_failok(command):
"""Helper function to call a command with only warning if failing."""
return exec_command(command, True)
def exec_failexit(command):
"""Helper function to call a command with error and exit if failing."""
return exec_command(command, False)
def exec_command(command, failok=False):
"""Helper function to call a command and handle errors and output."""
filtered_command = filter_string(command)
print_running(filtered_command)
retcode, output = getstatusoutput(command)
if NEED_STATUS_SHIFT:
retcode = os.WEXITSTATUS(retcode)
print(output)
if retcode != 0:
if failok:
print_warning(filtered_command)
else:
print_error(filtered_command)
sys.exit(retcode)
else:
print_success(filtered_command)
return retcode
def delete_file(filename):
"""Helper function to delete files."""
if not os.path.exists(filename):
print_generic("%s does not exist - not removing" % filename)
return
try:
os.remove(filename)
print_success("Removing %s" % filename)
except OSError:
exception = sys.exc_info()[1]
print_generic("Error when removing %s - %s" % (filename, exception.strerror))
print_error("Removing %s" % filename)
sys.exit(1)
def delete_directory(directoryname):
"""Helper function to delete directories."""
if not os.path.exists(directoryname):
print_generic("%s does not exist - not removing" % directoryname)
return
try:
shutil.rmtree(directoryname)
print_success("Removing %s" % directoryname)
except OSError:
exception = sys.exc_info()[1]
print_generic("Error when removing %s - %s" % (directoryname, exception.strerror))
print_error("Removing %s" % directoryname)
sys.exit(1)
def call_yum(command, params="", failonerror=True):
"""
Helper function to call a yum command on a list of packages.
pass failonerror = False to make yum commands non-fatal
"""
exec_command("/usr/bin/yum -y %s %s" % (command, params), not failonerror)
def check_migration_version(required_version):
"""
Verify that the command 'subscription-manager-migration' isn't too old.
"""
status, err = check_package_version('subscription-manager-migration', required_version)
return (status, err)
def check_subman_version(required_version):
"""
Verify that the command 'subscription-manager' isn't too old.
"""
status, _ = check_package_version('subscription-manager', required_version)
return status
def check_package_version(package_name, package_version):
"""
Verify that the version of a package
"""
required_version = ('0', package_version, '1')
err = "%s not found" % package_name
transaction_set = rpm.TransactionSet()
db_result = transaction_set.dbMatch('name', package_name)
for package in db_result:
try:
p_name = package['name'].decode('ascii')
p_version = package['version'].decode('ascii')
except AttributeError:
p_name = package['name']
p_version = package['version']
if rpm.labelCompare(('0', p_version, '1'), required_version) < 0:
err = "%s %s is too old" % (p_name, p_version)
else:
err = None
return (err is None, err)
def setup_yum_repo(url, gpg_key):
"""
Configures a yum repository at /etc/yum.repos.d/katello-client-bootstrap-deps.repo
"""
submanrepoconfig = SafeConfigParser()
submanrepoconfig.add_section('kt-bootstrap')
submanrepoconfig.set('kt-bootstrap', 'name', 'Subscription-manager dependencies for katello-client-bootstrap')
submanrepoconfig.set('kt-bootstrap', 'baseurl', url)
submanrepoconfig.set('kt-bootstrap', 'enabled', '1')
submanrepoconfig.set('kt-bootstrap', 'gpgcheck', '1')
submanrepoconfig.set('kt-bootstrap', 'gpgkey', gpg_key)
submanrepoconfig.write(open('/etc/yum.repos.d/katello-client-bootstrap-deps.repo', 'w'))
print_generic('Building yum metadata cache. This may take a few minutes')
call_yum('makecache')
def install_prereqs():
"""
Install subscription manager and its prerequisites.
If subscription-manager is installed already, check to see if we are migrating. If yes, install subscription-manager-migration.
Else if subscription-manager and subscription-manager-migration are available in a configured repo, install them both.
Otherwise, exit and inform user that we cannot proceed
"""
print_generic("Checking subscription manager prerequisites")
if options.deps_repository_url:
print_generic("Enabling %s as a repository for dependency RPMs" % options.deps_repository_url)
setup_yum_repo(options.deps_repository_url, options.deps_repository_gpg_key)
if USE_YUM:
yum_base = yum.YumBase()
pkg_list = yum_base.doPackageLists(patterns=['subscription-manager'])
subman_installed = pkg_list.installed
subman_available = pkg_list.available
else:
dnf_base = dnf.Base()
dnf_base.conf.read()
dnf_base.conf.substitutions.update_from_etc('/')
dnf_base.read_all_repos()
dnf_base.fill_sack()
pkg_list = dnf_base.sack.query().filter(name='subscription-manager')
subman_installed = pkg_list.installed().run()
subman_available = pkg_list.available().run()
call_yum("remove", "subscription-manager-gnome", False)
if subman_installed:
if check_rhn_registration() and 'migration' not in options.skip:
print_generic("installing subscription-manager-migration")
call_yum("install", "'subscription-manager-migration-*'", False)
print_generic("subscription-manager is installed already. Attempting update")
call_yum("update", "subscription-manager", False)
call_yum("update", "'subscription-manager-migration-*'", False)
elif subman_available:
print_generic("subscription-manager NOT installed. Installing.")
call_yum("install", "subscription-manager")
call_yum("install", "'subscription-manager-migration-*'", False)
else:
print_error("Cannot find subscription-manager in any configured repository. Consider using the --deps-repository-url switch to specify a repository with the subscription-manager RPMs")
sys.exit(1)
if 'prereq-update' not in options.skip:
call_yum("update", "yum openssl python", False)
if options.deps_repository_url:
delete_file('/etc/yum.repos.d/katello-client-bootstrap-deps.repo')
def is_fips():
"""
Checks to see if the system is FIPS enabled.
"""
try:
fips_file = open("/proc/sys/crypto/fips_enabled", "r")
fips_status = fips_file.read(1)
except IOError:
fips_status = "0"
return fips_status == "1"
def get_rhsm_proxy():
"""
Return the proxy server settings from /etc/rhsm/rhsm.conf as dictionary proxy_config.
"""
rhsmconfig = SafeConfigParser()
rhsmconfig.read('/etc/rhsm/rhsm.conf')
proxy_options = [option for option in rhsmconfig.options('server') if option.startswith('proxy')]
proxy_config = {}
for option in proxy_options:
proxy_config[option] = rhsmconfig.get('server', option)
return proxy_config
def set_rhsm_proxy(proxy_config):
"""
Set proxy server settings in /etc/rhsm/rhsm.conf from dictionary saved_proxy_config.
"""
rhsmconfig = SafeConfigParser()
rhsmconfig.read('/etc/rhsm/rhsm.conf')
for option in proxy_config.keys():
rhsmconfig.set('server', option, proxy_config[option])
rhsmconfig.write(open('/etc/rhsm/rhsm.conf', 'w'))
def get_bootstrap_rpm(clean=False, unreg=True):
"""
Retrieve Client CA Certificate RPMs from the Satellite 6 server.
Uses --insecure options to curl(1) if instructed to download via HTTPS
This function is usually called with clean=options.force, which ensures
clean_katello_agent() is called if --force is specified. You can optionally
pass unreg=False to bypass unregistering a system (e.g. when moving between
capsules.
"""
if clean:
clean_katello_agent()
if os.path.exists('/etc/rhsm/ca/katello-server-ca.pem'):
print_generic("A Katello CA certificate is already installed. Assuming system is registered.")
print_generic("If you want to move the system to a different Content Proxy in the same setup, please use --new-capsule.")
print_generic("If you want to remove the old host record and all data associated with it, please use --force.")
print_generic("Exiting.")
sys.exit(1)
if os.path.exists('/etc/pki/consumer/cert.pem') and unreg:
print_generic('System appears to be registered via another entitlement server. Attempting unregister')
unregister_system()
if options.download_method == "https":
print_generic("Writing custom cURL configuration to allow download via HTTPS without certificate verification")
curl_config_dir = tempfile.mkdtemp()
curl_config = open(os.path.join(curl_config_dir, '.curlrc'), 'w')
curl_config.write("insecure")
curl_config.close()
os.environ["CURL_HOME"] = curl_config_dir
print_generic("Retrieving Client CA Certificate RPMs")
exec_failexit("rpm -Uvh https://%s/pub/katello-ca-consumer-latest.noarch.rpm" % options.foreman_fqdn)
print_generic("Deleting cURL configuration")
delete_directory(curl_config_dir)
os.environ.pop("CURL_HOME", None)
else:
print_generic("Retrieving Client CA Certificate RPMs")
exec_failexit("rpm -Uvh http://%s/pub/katello-ca-consumer-latest.noarch.rpm" % options.foreman_fqdn)
def disable_rhn_plugin():
"""
Disable the RHN plugin for Yum
"""
if os.path.exists('/etc/yum/pluginconf.d/rhnplugin.conf'):
rhnpluginconfig = SafeConfigParser()
rhnpluginconfig.read('/etc/yum/pluginconf.d/rhnplugin.conf')
if rhnpluginconfig.get('main', 'enabled') == '1':
print_generic("RHN yum plugin was enabled. Disabling...")
rhnpluginconfig.set('main', 'enabled', '0')
rhnpluginconfig.write(open('/etc/yum/pluginconf.d/rhnplugin.conf', 'w'))
if os.path.exists('/etc/sysconfig/rhn/systemid'):
os.rename('/etc/sysconfig/rhn/systemid', '/etc/sysconfig/rhn/systemid.bootstrap-bak')
def enable_rhsmcertd():
"""
Enable and restart the rhsmcertd service
"""
enable_service("rhsmcertd")
exec_service("rhsmcertd", "restart")
def is_registered():
"""
Check if all required certificates are in place (i.e. a system is
registered to begin with) before we start changing things
"""
return (os.path.exists('/etc/rhsm/ca/katello-server-ca.pem') and
os.path.exists('/etc/pki/consumer/cert.pem'))
def migrate_systems(org_name, activationkey):
"""
Call `rhn-migrate-classic-to-rhsm` to migrate the machine from Satellite
5 to 6 using the organization name/label and the given activation key, and
configure subscription manager with the baseurl of Satellite6's pulp.
This allows the administrator to override the URL provided in the
katello-ca-consumer-latest RPM, which is useful in scenarios where the
Capsules/Servers are load-balanced or using subjectAltName certificates.
If called with "--legacy-purge", uses "legacy-user" and "legacy-password"
to remove the machine.
Option "--force" is always passed so that `rhn-migrate-classic-to-rhsm`
does not fail on channels which cannot be mapped either because they
are cloned channels, custom channels, or do not exist in the destination.
"""
if 'foreman' in options.skip:
org_label = org_name
else:
org_label = return_matching_katello_key('organizations', 'name="%s"' % org_name, 'label', False)
print_generic("Calling rhn-migrate-classic-to-rhsm")
options.rhsmargs += " --force --destination-url=https://%s:%s/rhsm" % (options.foreman_fqdn, RHSM_PORT)
if options.legacy_purge:
options.rhsmargs += " --legacy-user '%s' --legacy-password '%s'" % (options.legacy_login, options.legacy_password)
if options.removepkgs and check_migration_version(SUBSCRIPTION_MANAGER_MIGRATION_REMOVE_PKGS_VERSION)[0]:
options.rhsmargs += " --remove-rhn-packages"
else:
options.rhsmargs += " --keep"
if check_subman_version(SUBSCRIPTION_MANAGER_SERVER_TIMEOUT_VERSION):
exec_failok("/usr/sbin/subscription-manager config --server.server_timeout=%s" % options.timeout)
exec_command("/usr/sbin/rhn-migrate-classic-to-rhsm --org %s --activation-key '%s' %s" % (org_label, activationkey, options.rhsmargs), options.ignore_registration_failures)
exec_command("subscription-manager config --rhsm.baseurl=https://%s/pulp/repos" % options.foreman_fqdn, options.ignore_registration_failures)
if options.release:
exec_failexit("subscription-manager release --set %s" % options.release)
enable_rhsmcertd()
# When rhn-migrate-classic-to-rhsm is called with --keep, it will leave the systemid
# file intact, which might confuse the (not yet removed) yum-rhn-plugin.
# Move the file to a backup name & disable the RHN plugin, so the user can still restore it if needed.
disable_rhn_plugin()
def register_systems(org_name, activationkey):
"""
Register the host to Satellite 6's organization using
`subscription-manager` and the given activation key.
Option "--force" is given further.
"""
if 'foreman' in options.skip:
org_label = org_name
else:
org_label = return_matching_katello_key('organizations', 'name="%s"' % org_name, 'label', False)
print_generic("Calling subscription-manager")
options.smargs += " --serverurl=https://%s:%s/rhsm --baseurl=https://%s/pulp/repos" % (options.foreman_fqdn, RHSM_PORT, options.foreman_fqdn)
if options.force:
options.smargs += " --force"
if options.release:
options.smargs += " --release %s" % options.release
if check_subman_version(SUBSCRIPTION_MANAGER_SERVER_TIMEOUT_VERSION):
exec_failok("/usr/sbin/subscription-manager config --server.server_timeout=%s" % options.timeout)
exec_command("/usr/sbin/subscription-manager register --org '%s' --name '%s' --activationkey '%s' %s" % (org_label, FQDN, activationkey, options.smargs), options.ignore_registration_failures)
enable_rhsmcertd()
def unregister_system():
"""Unregister the host using `subscription-manager`."""
print_generic("Cleaning old yum metadata")
call_yum("clean", "metadata dbcache", False)
print_generic("Unregistering")
exec_failok("/usr/sbin/subscription-manager unregister")
exec_failok("/usr/sbin/subscription-manager clean")
def clean_katello_agent():
"""Remove old Katello agent (aka Gofer) and certificate RPMs."""
print_generic("Removing old Katello agent and certs")
call_yum("remove", "'katello-ca-consumer-*' katello-agent gofer katello-host-tools katello-host-tools-fact-plugin", False)
delete_file("/etc/rhsm/ca/katello-server-ca.pem")
def install_katello_agent():
"""Install Katello agent (aka Gofer) and activate /start it."""
print_generic("Installing the Katello agent")
call_yum("install", "katello-agent")
enable_service("goferd")
exec_service("goferd", "restart")
def install_katello_host_tools():
"""Install Katello Host Tools"""
print_generic("Installing the Katello Host Tools")
call_yum("install", "katello-host-tools")
def clean_puppet():
"""Remove old Puppet Agent and its configuration"""
print_generic("Cleaning old Puppet Agent")
call_yum("remove", "puppet-agent", False)
delete_directory("/var/lib/puppet/")
delete_directory("/opt/puppetlabs/puppet/cache")
delete_directory("/etc/puppetlabs/puppet/ssl")
def clean_environment():
"""
Undefine `GEM_PATH`, `LD_LIBRARY_PATH` and `LD_PRELOAD` as many environments
have it defined non-sensibly.
"""
for key in ['GEM_PATH', 'LD_LIBRARY_PATH', 'LD_PRELOAD']:
os.environ.pop(key, None)
def generate_katello_facts():
"""
Write katello_facts file based on FQDN. Done after installation
of katello-ca-consumer RPM in case the script is overriding the
FQDN. Place the location if the location option is included
"""
print_generic("Writing FQDN katello-fact")
katellofacts = open('/etc/rhsm/facts/katello.facts', 'w')
katellofacts.write('{"network.hostname-override":"%s"}\n' % (FQDN))
katellofacts.close()
if options.location and 'foreman' in options.skip:
print_generic("Writing LOCATION RHSM fact")
locationfacts = open('/etc/rhsm/facts/location.facts', 'w')
locationfacts.write('{"foreman_location":"%s"}\n' % (options.location))
locationfacts.close()
def install_puppet_agent():
"""Install and configure, then enable and start the Puppet Agent"""
puppet_env = return_puppetenv_for_hg(return_matching_foreman_key('hostgroups', 'title="%s"' % options.hostgroup, 'id', False))
# If there is no Puppet environment, skip configuring Puppet
if puppet_env is None:
print_generic("No Puppet environment found, skipping Puppet setup.")
return
print_generic("Installing the Puppet Agent")
call_yum("install", "puppet-agent")
enable_service("puppet")
puppet_conf_file = '/etc/puppetlabs/puppet/puppet.conf'
main_section = """[main]
vardir = /opt/puppetlabs/puppet/cache
logdir = /var/log/puppetlabs/puppet
rundir = /var/run/puppetlabs
ssldir = /etc/puppetlabs/puppet/ssl
"""
if is_fips():
main_section += "digest_algorithm = sha256"
print_generic("System is in FIPS mode. Setting digest_algorithm to SHA256 in puppet.conf")
puppet_conf = open(puppet_conf_file, 'w')
# set puppet.conf certname to lowercase FQDN, as capitalized characters would
# get translated anyway generating our certificate
# * https://puppet.com/docs/puppet/3.8/configuration.html#certname
# * https://puppet.com/docs/puppet/4.10/configuration.html#certname
# * https://puppet.com/docs/puppet/5.5/configuration.html#certname
# other links mentioning capitalized characters related issues:
# * https://grokbase.com/t/gg/puppet-users/152s27374y/forcing-a-variable-to-be-lower-case
# * https://groups.google.com/forum/#!topic/puppet-users/vRAu092ppzs
puppet_conf.write("""
%s
[agent]
pluginsync = true
report = true
ignoreschedules = true
daemon = false
ca_server = %s
certname = %s
environment = %s
server = %s
""" % (main_section, options.puppet_ca_server, FQDN.lower(), puppet_env, options.puppet_server))
if options.puppet_ca_port:
puppet_conf.write("""ca_port = %s
""" % (options.puppet_ca_port))
if options.puppet_noop:
puppet_conf.write("""noop = true
""")
puppet_conf.close()
noop_puppet_signing_run()
if 'puppet-enable' not in options.skip:
enable_service("puppet")
exec_service("puppet", "restart")
def noop_puppet_signing_run():
"""
Execute Puppet with --noop to generate and sign certs
"""
print_generic("Running Puppet in noop mode to generate SSL certs")
print_generic("Visit the UI and approve this certificate via Infrastructure->Capsules")
print_generic("if auto-signing is disabled")
exec_failexit("/opt/puppetlabs/puppet/bin/puppet agent --test --noop --tags no_such_tag --waitforcert 10")
if 'puppet-enable' not in options.skip:
enable_service("puppet")
exec_service("puppet", "restart")
def remove_obsolete_packages():
"""Remove old RHN packages"""
print_generic("Removing old RHN packages")
call_yum("remove", "rhn-setup rhn-client-tools yum-rhn-plugin rhnsd rhn-check rhnlib spacewalk-abrt spacewalk-oscap osad 'rh-*-rhui-client' 'candlepin-cert-consumer-*'", False)
def fully_update_the_box():
"""Call `yum -y update` to upgrade the host."""
print_generic("Fully Updating The Box")
call_yum("update")
# curl https://satellite.example.com:9090/ssh/pubkey >> ~/.ssh/authorized_keys
# sort -u ~/.ssh/authorized_keys
def install_ssh_key_from_url(remote_url):
"""
Download and install Foreman's SSH public key.
"""
print_generic("Fetching Remote Execution SSH key from %s" % remote_url)
try:
if sys.version_info >= (2, 6):
foreman_ssh_key_req = urllib_urlopen(remote_url, timeout=options.timeout)
else:
foreman_ssh_key_req = urllib_urlopen(remote_url)
foreman_ssh_key = foreman_ssh_key_req.read()
if sys.version_info >= (3, 0):
foreman_ssh_key = foreman_ssh_key.decode(foreman_ssh_key_req.headers.get_content_charset('utf-8'))
except urllib_httperror:
exception = sys.exc_info()[1]
print_generic("The server was unable to fulfill the request. Error: %s - %s" % (exception.code, exception.reason))
print_generic("Please ensure the Remote Execution feature is configured properly")
print_warning("Installing Foreman SSH key")
return
except urllib_urlerror:
exception = sys.exc_info()[1]
print_generic("Could not reach the server. Error: %s" % exception.reason)
return
install_ssh_key_from_string(foreman_ssh_key)
def install_ssh_key_from_api():
"""
Download and install all Foreman's SSH public keys.
"""
print_generic("Fetching Remote Execution SSH keys from the Foreman API")
url = "https://" + options.foreman_fqdn + ":" + str(API_PORT) + "/api/v2/smart_proxies/"
smart_proxies = get_json(url)
for smart_proxy in smart_proxies['results']:
if 'remote_execution_pubkey' in smart_proxy:
install_ssh_key_from_string(smart_proxy['remote_execution_pubkey'])
def install_ssh_key_from_string(foreman_ssh_key):
"""
Install Foreman's SSH public key into the foreman user's
authorized keys file location, so that remote execution becomes possible.
If not set default is ~/.ssh/authorized_keys
"""
print_generic("Installing Remote Execution SSH key for user %s" % options.remote_exec_user)
foreman_ssh_key = foreman_ssh_key.strip()
userpw = pwd.getpwnam(options.remote_exec_user)
if not options.remote_exec_authpath:
options.remote_exec_authpath = os.path.join(userpw.pw_dir, '.ssh', 'authorized_keys')
foreman_ssh_dir = os.path.join(userpw.pw_dir, '.ssh')
if not os.path.isdir(foreman_ssh_dir):
os.mkdir(foreman_ssh_dir, OWNER_ONLY_DIR)
os.chown(foreman_ssh_dir, userpw.pw_uid, userpw.pw_gid)
elif os.path.exists(options.remote_exec_authpath) and not os.path.isfile(options.remote_exec_authpath):
print_error("Foreman's SSH key not installed. You need to provide a full path to an authorized_keys file, you provided: '%s'" % options.remote_exec_authpath)
return
if os.path.isfile(options.remote_exec_authpath):
if foreman_ssh_key in open(options.remote_exec_authpath, 'r').read():
print_generic("Foreman's SSH key already present in %s" % options.remote_exec_authpath)
return
output = os.fdopen(os.open(options.remote_exec_authpath, os.O_WRONLY | os.O_CREAT, OWNER_ONLY_FILE), 'a')
output.write("\n")
output.write(foreman_ssh_key)
output.write("\n")
os.chown(options.remote_exec_authpath, userpw.pw_uid, userpw.pw_gid)
print_generic("Foreman's SSH key added to %s" % options.remote_exec_authpath)
output.close()
class BetterHTTPErrorProcessor(urllib_basehandler):
"""
A substitute/supplement class to HTTPErrorProcessor
that doesn't raise exceptions on status codes 201,204,206
"""
# pylint:disable=unused-argument,no-self-use,no-init
def http_error_201(self, request, response, code, msg, hdrs):
"""Handle HTTP 201"""
return response
def http_error_204(self, request, response, code, msg, hdrs):
"""Handle HTTP 204"""
return response
def http_error_206(self, request, response, code, msg, hdrs):
"""Handle HTTP 206"""
return response
def call_api(url, data=None, method='GET'):
"""
Helper function to place an API call returning JSON results and doing
some error handling. Any error results in an exit.
"""
try:
request = urllib_request(url)
if options.verbose:
print('url: %s' % url)
print('method: %s' % method)
print('data: %s' % json.dumps(data, sort_keys=False, indent=2))
auth_string = '%s:%s' % (options.login, options.password)
base64string = base64.b64encode(auth_string.encode('utf-8')).decode().strip()
request.add_header("Authorization", "Basic %s" % base64string)
request.add_header("Content-Type", "application/json")
request.add_header("Accept", "application/json")
if data:
if hasattr(request, 'add_data'):
request.add_data(json.dumps(data))
else:
request.data = json.dumps(data).encode()
request.get_method = lambda: method
if sys.version_info >= (2, 6):
result = urllib_urlopen(request, timeout=options.timeout)
else:
result = urllib_urlopen(request)
jsonresult = json.load(result)
if options.verbose:
print('result: %s' % json.dumps(jsonresult, sort_keys=False, indent=2))
return jsonresult
except urllib_urlerror:
exception = sys.exc_info()[1]
print('An error occurred: %s' % exception)
print('url: %s' % url)
if isinstance(exception, urllib_httperror):
print('code: %s' % exception.code) # pylint:disable=no-member
if data:
print('data: %s' % json.dumps(data, sort_keys=False, indent=2))
try:
jsonerr = json.load(exception)
print('error: %s' % json.dumps(jsonerr, sort_keys=False, indent=2))
except: # noqa: E722, pylint:disable=bare-except
print('error: %s' % exception)
sys.exit(1)
except Exception: # pylint:disable=broad-except
exception = sys.exc_info()[1]
print("FATAL Error - %s" % (exception))
sys.exit(2)
def get_json(url):
"""Use `call_api` to place a "GET" REST API call."""
return call_api(url)
def post_json(url, jdata):
"""Use `call_api` to place a "POST" REST API call."""
return call_api(url, data=jdata, method='POST')
def delete_json(url):
"""Use `call_api` to place a "DELETE" REST API call."""
return call_api(url, method='DELETE')
def put_json(url, jdata=None):
"""Use `call_api` to place a "PUT" REST API call."""
return call_api(url, data=jdata, method='PUT')
def update_host_capsule_mapping(attribute, capsule_id, host_id):
"""
Update the host entry to point a feature to a new proxy
"""
url = "https://" + options.foreman_fqdn + ":" + str(API_PORT) + "/api/v2/hosts/" + str(host_id)
if attribute == 'content_source_id':
jdata = {"host": {"content_facet_attributes": {"content_source_id": capsule_id}, "content_source_id": capsule_id}}
else:
jdata = {"host": {attribute: capsule_id}}
return put_json(url, jdata)
def get_capsule_features(capsule_id):
"""
Fetch all features available on a proxy
"""
url = "https://" + options.foreman_fqdn + ":" + str(API_PORT) + "/api/smart_proxies/%s" % str(capsule_id)
return [feature['name'] for feature in get_json(url)['features']]
def update_host_config(attribute, value, host_id):
"""
Update a host config
"""
attribute_id = return_matching_foreman_key(attribute + 's', 'title="%s"' % value, 'id', False)
json_key = attribute + "_id"
jdata = {"host": {json_key: attribute_id}}
put_json("https://" + options.foreman_fqdn + ":" + API_PORT + "/api/hosts/%s" % host_id, jdata)
def return_matching_foreman_key(api_name, search_key, return_key, null_result_ok=False):
"""
Function uses `return_matching_key` to make an API call to Foreman.
"""
return return_matching_key("/api/v2/" + api_name, search_key, return_key, null_result_ok)
def return_matching_katello_key(api_name, search_key, return_key, null_result_ok=False):
"""
Function uses `return_matching_key` to make an API call to Katello.
"""
return return_matching_key("/katello/api/" + api_name, search_key, return_key, null_result_ok)
def return_matching_key(api_path, search_key, return_key, null_result_ok=False):
"""
Search in API given a search key, which must be unique, then returns the
field given in "return_key" as ID.
api_path is the path in url for API name, search_key must contain also
the key for search (name=, title=, ...).
The search_key must be quoted in advance.
"""
myurl = "https://" + options.foreman_fqdn + ":" + API_PORT + api_path + "/?" + urlencode([('search', '' + str(search_key))])
return_values = get_json(myurl)
result_len = len(return_values['results'])
if result_len == 1:
return_values_return_key = return_values['results'][0][return_key]
elif result_len == 0 and null_result_ok is True:
return_values_return_key = None
else:
print_error("%d element in array for search key '%s' in API '%s'. Please note that all searches are case-sensitive." % (result_len, search_key, api_path))
print_error("Please also ensure that the user has permissions to view the searched objects. Fatal error.")
sys.exit(2)
return return_values_return_key
def return_puppetenv_for_hg(hg_id):
"""
Return the Puppet environment of the given hostgroup ID, either directly
or inherited through its hierarchy. If no environment is found,
`None` is returned.
"""
myurl = "https://" + options.foreman_fqdn + ":" + API_PORT + "/api/v2/hostgroups/" + str(hg_id)
hostgroup = get_json(myurl)
environment_name = hostgroup.get('environment_name')
if not environment_name and hostgroup.get('ancestry'):
parent = hostgroup['ancestry'].split('/')[-1]
environment_name = return_puppetenv_for_hg(parent)
return environment_name
def create_domain(domain, orgid, locid):
"""
Call Foreman API to create a network domain associated with the given
organization and location.
"""
myurl = "https://" + options.foreman_fqdn + ":" + API_PORT + "/api/v2/domains"
domid = return_matching_foreman_key('domains', 'name="%s"' % domain, 'id', True)
if not domid:
jsondata = {"domain": {"name": domain, "organization_ids": [orgid], "location_ids": [locid]}}
print_running("Calling Foreman API to create domain %s associated with the org & location" % domain)
post_json(myurl, jsondata)
def create_host():
# pylint:disable=too-many-branches
# pylint:disable=too-many-statements
"""
Call Foreman API to create a host entry associated with the
host group, organization & location, domain and architecture.
"""
myhgid = return_matching_foreman_key('hostgroups', 'title="%s"' % options.hostgroup, 'id', False)
if options.location:
mylocid = return_matching_foreman_key('locations', 'title="%s"' % options.location, 'id', False)
else:
mylocid = None
myorgid = return_matching_foreman_key('organizations', 'name="%s"' % options.org, 'id', False)
if DOMAIN:
if options.add_domain:
create_domain(DOMAIN, myorgid, mylocid)
mydomainid = return_matching_foreman_key('domains', 'name="%s"' % DOMAIN, 'id', True)
if not mydomainid:
print_generic("Domain %s doesn't exist in Foreman, consider using the --add-domain option." % DOMAIN)
sys.exit(2)
domain_available_search = 'name="%s"&organization_id=%s' % (DOMAIN, myorgid)
if mylocid:
domain_available_search += '&location_id=%s' % (mylocid)
mydomainid = return_matching_foreman_key('domains', domain_available_search, 'id', True)
if not mydomainid:
print_generic("Domain %s exists in Foreman, but is not assigned to the requested Organization or Location." % DOMAIN)
sys.exit(2)
else:
mydomainid = None
if options.force_content_source:
my_content_src_id = return_matching_foreman_key(api_name='smart_proxies', search_key='name="%s"' % options.foreman_fqdn, return_key='id', null_result_ok=True)
if my_content_src_id is None:
print_warning("You requested to set the content source to %s, but we could not find such a Smart Proxy configured. The content source WILL NOT be updated!" % (options.foreman_fqdn,))
else:
my_content_src_id = None
architecture_id = return_matching_foreman_key('architectures', 'name="%s"' % ARCHITECTURE, 'id', False)
host_id = return_matching_foreman_key('hosts', 'name="%s"' % FQDN, 'id', True)
# create the starting json, to be filled below
jsondata = {"host": {"name": HOSTNAME, "hostgroup_id": myhgid, "organization_id": myorgid, "mac": MAC, "architecture_id": architecture_id, "build": False, "compute_resource_id": None}}
# optional parameters
if my_content_src_id:
jsondata['host']['content_facet_attributes'] = {'content_source_id': my_content_src_id}
if options.operatingsystem is not None:
operatingsystem_id = return_matching_foreman_key('operatingsystems', 'title="%s"' % options.operatingsystem, 'id', False)
jsondata['host']['operatingsystem_id'] = operatingsystem_id
if options.partitiontable is not None:
partitiontable_id = return_matching_foreman_key('ptables', 'name="%s"' % options.partitiontable, 'id', False)
jsondata['host']['ptable_id'] = partitiontable_id
if not options.unmanaged:
jsondata['host']['managed'] = 'true'
else:
jsondata['host']['managed'] = 'false'
if mylocid:
jsondata['host']['location_id'] = mylocid
if mydomainid:
jsondata['host']['domain_id'] = mydomainid
if options.ip:
jsondata['host']['ip'] = options.ip
if options.comment:
jsondata['host']['comment'] = options.comment
myurl = "https://" + options.foreman_fqdn + ":" + API_PORT + "/api/v2/hosts/"
if options.force and host_id is not None:
disassociate_host(host_id)
delete_host(host_id)
print_running("Calling Foreman API to create a host entry associated with the group & org")
post_json(myurl, jsondata)
print_success("Successfully created host %s" % FQDN)
def delete_host(host_id):
"""Call Foreman API to delete the current host."""
myurl = "https://" + options.foreman_fqdn + ":" + API_PORT + "/api/v2/hosts/"
print_running("Deleting host id %s for host %s" % (host_id, FQDN))
delete_json("%s/%s" % (myurl, host_id))
def disassociate_host(host_id):
"""
Call Foreman API to disassociate host from content host before deletion.
"""
myurl = "https://" + options.foreman_fqdn + ":" + API_PORT + "/api/v2/hosts/" + str(host_id) + "/disassociate"
print_running("Disassociating host id %s for host %s" % (host_id, FQDN))
put_json(myurl)
def configure_subscription_manager():
"""
Configure subscription-manager plugins in Yum
"""
productidconfig = SafeConfigParser()
productidconfig.read('/etc/yum/pluginconf.d/product-id.conf')
if productidconfig.get('main', 'enabled') == '0':
print_generic("Product-id yum plugin was disabled. Enabling...")
productidconfig.set('main', 'enabled', '1')
productidconfig.write(open('/etc/yum/pluginconf.d/product-id.conf', 'w'))
submanconfig = SafeConfigParser()
submanconfig.read('/etc/yum/pluginconf.d/subscription-manager.conf')
if submanconfig.get('main', 'enabled') == '0':
print_generic("subscription-manager yum plugin was disabled. Enabling...")
submanconfig.set('main', 'enabled', '1')
submanconfig.write(open('/etc/yum/pluginconf.d/subscription-manager.conf', 'w'))
def check_rhn_registration():
"""Helper function to check if host is registered to legacy RHN."""
if os.path.exists('/etc/sysconfig/rhn/systemid'):
retcode = getstatusoutput('rhn-channel -l')[0]
if NEED_STATUS_SHIFT:
retcode = os.WEXITSTATUS(retcode)
return retcode == 0
return False