/
__init__.py
2968 lines (2460 loc) · 108 KB
/
__init__.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
"""A set of tasks for automating interactions with Satellite servers.
Many commands are affected by environment variables. Unless stated otherwise,
all environment variables are required.
"""
from __future__ import print_function
import os
import random
import socket
import sys
import time
from io import StringIO
from re import MULTILINE, search
from automation_tools.bz import bz_bug_is_open
from automation_tools.repository import (
create_custom_repos, disable_repos, disable_beaker_repos, enable_repos, enable_satellite_repos,
)
from automation_tools.utils import distro_info, run_command, update_packages, version
from fabric.api import cd, env, execute, get, hide, local, put, run, settings, sudo
from six.moves.urllib.parse import urljoin
from six.moves.urllib.parse import urlsplit
LIBVIRT_IMAGES_DIR = '/var/lib/libvirt/images'
def unsubscribe():
"""Unregisters a machine from Red Hat"""
run('subscription-manager unregister', warn_only=True)
run('subscription-manager clean')
def subscribe(autosubscribe=False, stage=False):
"""Registers and subscribes machine to Red Hat.
The following environment variables affect this command:
RHN_USERNAME
Red Hat Network username.
RHN_PASSWORD
Red Hat Network password.
RHN_POOLID
Optional. Red Hat Network pool ID. Determines what software will be
available from RHN.
:param bool stage: Subscribe to stage
"""
# Registration and subscription is only meaningful for Red Hat Enterprise
# Linux systems.
distro, major_version, _ = distro_info()
if distro.lower() != 'rhel':
return
for env_var in ('RHN_USERNAME', 'RHN_PASSWORD'):
if env_var not in os.environ:
print('The {0} environment variable must be set.'.format(env_var))
sys.exit(1)
# Clean and reset subscription manager to CDN defaults
clean_rhsm()
# Point subscription manager to stage if requested
if stage:
update_rhsm_stage()
# Register the system
with hide('running'):
run(
'subscription-manager register --force --user={0} --password={1} {2} {3}'.format(
os.environ['RHN_USERNAME'],
os.environ['RHN_PASSWORD'],
# set release to "6Server", "7Server" or "8" accordingly
'--release="{0}{1}"'.format(major_version, 'Server' if major_version < 8 else ''),
'--auto-attach' if autosubscribe else ''
)
)
# Subscribe the system if a pool ID was provided
# Multiple pool IDs can be provided as space seprated list
rhn_poolid = os.environ.get('RHN_POOLID')
if rhn_poolid:
has_pool_msg = (
'This unit has already had the subscription matching pool ID'
)
attach_cmd = 'subscription-manager attach {0}'.format(
' '.join(['--pool={0}'.format(id) for id in rhn_poolid.split()])
)
for _ in range(10):
result = run(attach_cmd, warn_only=True)
if result.succeeded or has_pool_msg in result:
return
time.sleep(5)
print('Unable to attach system to pool. Aborting.')
sys.exit(1)
def subscribe_dogfood(clean_beaker=True):
"""Registers and subscribes machine to dogfood Satellite.
The following environment variables affect this command:
DOGFOOD_URL
URL for the Candlepin Cert RPM.
DOGFOOD_ORG
ORG for the sat63 to subscribe to.
DOGFOOD_ACTIVATIONKEY
AK for the sat63 to subscribe to.
"""
# DOGFOOD Url
dogfood_url = os.getenv('DOGFOOD_URL')
if not dogfood_url:
print('You need to provide the Dogfood Url.')
sys.exit(1)
# Org
org = os.getenv('DOGFOOD_ORG')
if not org:
print('You need to provide the Organization to subscribe.')
sys.exit(1)
# Activation Key
act_key = os.getenv('DOGFOOD_ACTIVATIONKEY')
if not act_key:
print('You need to provide an activationkey.')
sys.exit(1)
# If this is a Beaker box, 'disable' Beaker repos
if clean_beaker is True:
disable_beaker_repos(silent=True)
# Clean up and install with basic packages.
clean_rhsm()
# Install the cert file
run('yum -y localinstall {0}/pub/katello-ca-consumer-latest.noarch.rpm'
.format(dogfood_url), warn_only=True)
# Register and subscribe
print('Register/Subscribe using Subscription-manager.')
cmd = (
'subscription-manager register --force --org="{0}" '
'--activationkey="{1}"'.format(org, act_key)
)
run(cmd)
# Refresh subscriptions and clean up YUM
print('Refreshing Subscription-manager.')
run('subscription-manager refresh')
print('Performing yum clean up.')
run('yum clean all', quiet=True)
def setup_ddns(entry_domain, host_ip):
"""Task to setup DDNS client
The following environment variables affect this command:
* `DDNS_HASH`
* `DDNS_PACKAGE_URL`
* `INTERNAL_CERT_URL`
:param str entry_domain: the FQDN of the host
:param str entry_hash: host FQDN DDNS entry hash
:param str host_ip: host IP address
"""
ddns_hash = os.environ.get('DDNS_HASH')
if ddns_hash is None:
print('The DDNS_HASH environment variable should be defined')
sys.exit(1)
# subscribed, because ddns pacakge requires java
try:
execute(subscribe, host=host_ip)
ddns_package_url = os.environ.get('DDNS_PACKAGE_URL')
if ddns_package_url is None:
print('The DDNS_PACKAGE_URL environment variable should be defined')
sys.exit(1)
os_version = distro_info()[1]
target, domain = entry_domain.split('.', 1)
if os_version >= 7:
internal_cert_url = os.environ.get('internal_cert_url')
if internal_cert_url is None:
print('The internal_cert_url environment variable should be defined')
sys.exit(1)
run('yum localinstall -y {0}'.format(internal_cert_url))
run('yum localinstall -y {0}'.format(ddns_package_url))
if os_version >= 7:
run('echo "{0} {1} {2}" >> /etc/redhat-internal-ddns/hosts'.format(
target, domain, ddns_hash))
fix_hostname(entry_domain, host_ip)
run('redhat-internal-ddns-client.sh enable')
run('redhat-internal-ddns-client.sh update')
else:
run('echo "{0} {1} {2}" >> /etc/redhat-ddns/hosts'.format(
target, domain, ddns_hash))
fix_hostname(entry_domain, host_ip)
run('redhat-ddns-client enable')
run('redhat-ddns-client')
# unsubscribe and removed java as it will conflict satellite installation
except Exception as error:
print("An exception occurred: ", error)
raise Exception("Failed to setup ddns client")
finally:
unsubscribe()
run('yum remove -y java*')
def setup_proxy(run_katello_installer=True):
"""Task to setup a proxy and block non-proxy traffic from your foreman
server.
Proxy information is passed using the PROXY_INFO environmental variable.
The expected format is::
PROXY_INFO=proxy://<username>:<password>@<hostname>:<port>
``username`` and ``password`` fields can be omitted if the proxy does not
require authentication, for example::
PROXY_INFO=proxy://<hostname>:<port>
:param bool run_katello_installer: Should the task run installer or just pass installer options
"""
if isinstance(run_katello_installer, str):
run_katello_installer = (run_katello_installer.lower() == 'true')
proxy_info = os.environ.get('PROXY_INFO')
if proxy_info is None:
print('The PROXY_INFO environment variable should be defined')
sys.exit(1)
proxy_info = urlsplit(proxy_info)
if not proxy_info.hostname or not proxy_info.port:
raise Exception(
'Proxy configuration should include at least the hostname and port'
)
installer_options = {
'katello-proxy-url': 'http://{0}'.format(proxy_info.hostname),
'katello-proxy-port': proxy_info.port,
}
if proxy_info.username is not None:
installer_options['katello-proxy-username'] = proxy_info.username
if proxy_info.password is not None:
installer_options['katello-proxy-password'] = proxy_info.password
if run_katello_installer:
katello_installer(**installer_options)
else:
return installer_options
def setup_avahi_discovery():
"""Task to setup avahi discovery used to discover VMs deployed to a VLAN
by 'ping vm.local' run at Satellite
"""
os_version = distro_info()[1]
if run('rpm -q nss-mdns', warn_only=True).failed:
epel_present = run('rpm -q epel-release', warn_only=True).return_code == 0
if not epel_present:
run('yum -y install https://dl.fedoraproject.org/pub/epel/'
'epel-release-latest-{0}.noarch.rpm'.format(os_version))
run('yum -y install nss-mdns') # also pulls in avahi
if not epel_present: # we installed epel, so removing afterwards
run('rpm -e epel-release')
run('firewall-cmd --add-service mdns --permanent')
run('firewall-cmd --add-service mdns')
run('service avahi-daemon restart')
def setup_default_docker():
"""Task to configure system to support Docker as a valid
Compute Resource for provisioning containers.
"""
os_version = distro_info()[1]
# Enable required repository
if os_version == 7:
enable_repos('rhel-{0}-server-extras-rpms'.format(os_version))
# Install "docker" package. On RHEL8 alias for "podman-docker"
run('yum -y --disableplugin=foreman-protector install docker')
# Disable 'extras' repo after installing Docker
if os_version == 7:
disable_repos('rhel-{0}-server-extras-rpms'.format(os_version))
run('groupadd docker', warn_only=True)
run('usermod -aG docker foreman')
# SElinux workaround let us use ``http://localhost:2375`` for Docker Compute Resurce.
run('sed -i -e "s|^OPTIONS=.*|OPTIONS=\'{0}\'|" /etc/sysconfig/docker'.format(
' '.join([
'--selinux-enabled=true',
'--host tcp://0.0.0.0:2375',
'--host unix:///var/run/docker.sock',
'-G docker',
])
))
# Restart and enable ``docker`` service
manage_daemon('enable', 'docker')
manage_daemon('restart', 'docker')
def setup_default_capsule(interface=None, run_katello_installer=True):
"""Task to setup a the default capsule for Satellite
:param str interface: Network interface name to be used
:param bool run_katello_installer: Should the task run installer or just pass installer options
"""
if isinstance(run_katello_installer, str):
run_katello_installer = (run_katello_installer.lower() == 'true')
forwarders = run(
'cat /etc/resolv.conf | grep "^nameserver" | awk \'{print $2}\'',
quiet=True
).split('\n')
forwarders = [forwarder.strip() for forwarder in forwarders]
if len(forwarders) == 0:
print('Was not possible to fetch nameserver information')
sys.exit(1)
hostname = run('hostname', quiet=True).strip()
if len(hostname) == 0:
print('Was not possible to fetch hostname information')
sys.exit(1)
if '.' not in hostname:
print('Please make sure the hostname is configured with a FQDN')
sys.exit(1)
domain = hostname.split('.', 1)[1]
if len(domain) == 0:
print('Was not possible to fetch domain information')
sys.exit(1)
if interface is None:
if len(interface) == 0:
print('Was not possible to fetch interface information')
sys.exit(1)
installer_options = {
'foreman-proxy-dns': 'true',
'foreman-proxy-dns-forwarders': forwarders,
'foreman-proxy-dns-interface': interface,
'foreman-proxy-dns-zone': domain,
'foreman-proxy-dhcp': 'true',
'foreman-proxy-dhcp-interface': interface,
'foreman-proxy-tftp': 'true',
'foreman-proxy-tftp-servername': hostname,
'foreman-proxy-register-in-foreman': 'true',
}
installer_options[
'foreman-proxy-dhcp-range'
] = os.environ.get('DHCP_RANGE', '192.168.100.10 192.168.100.254')
gateway = os.environ.get('GATEWAY', '192.168.100.1')
installer_options['foreman-proxy-dhcp-gateway'] = gateway
zone = gateway.rpartition('.')[0]
reversed_zone = '.'.join(reversed(zone.split('.')))
dns_reverse_zone = '{0}.in-addr.arpa'.format(reversed_zone)
installer_options['foreman-proxy-dns-reverse'] = dns_reverse_zone
if run_katello_installer:
katello_installer(**installer_options)
else:
return installer_options
def setup_external_capsule():
"""Task to setup an external Capsule for Satellite."""
interface = os.environ.get('INTERFACE', 'virbr0')
gateway = os.environ.get('GATEWAY', '192.168.200.1')
if 'virbr' in interface:
setup_default_libvirt(ip_address=gateway)
install_options = setup_default_capsule(
interface=interface,
run_katello_installer=False)
katello_installer(scenario="capsule", **install_options)
def setup_default_libvirt(bridge=None, ip_address="192.168.100.1"):
"""Task to setup a the default capsule for Satellite
:param str interface: Network interface name to be used
"""
run('yum install -y libvirt libvirt-daemon-kvm virt-install qemu-kvm')
run('lsmod | grep kvm_', warn_only=True)
run('sed -i \'s/^#*\\s*LIBVIRTD_ARGS=.*/LIBVIRTD_ARGS=--listen/\' /etc/sysconfig/libvirtd')
run('sed -i \'s/^#*\\s*listen_tls\\s*=.*/listen_tls = 0/\' /etc/libvirt/libvirtd.conf')
run('sed -i \'s/^#*\\s*listen_tcp\\s*=.*/listen_tcp = 1/\' /etc/libvirt/libvirtd.conf')
run('sed -i \'s/^#*\\s*auth_tcp\\s*=.*/auth_tcp = "none"/\' /etc/libvirt/libvirtd.conf')
manage_daemon('enable', 'libvirtd')
manage_daemon('restart', 'libvirtd')
if 'default' in run('virsh net-list'):
run('virsh net-destroy default')
run('virsh net-undefine default')
# Setup foreman libvirt network
if 'foreman' not in run('virsh net-list --all'):
run('virsh net-define <(echo "\n'
'<network>\n'
' <name>foreman</name>\n'
' <forward mode=\'nat\'>\n'
' <nat>\n'
' <port start=\'1024\' end=\'65535\'/>\n'
' </nat>\n'
' </forward>\n' +
(' <bridge name=\'{}\' stp=\'on\' delay=\'0\'/>\n'.format(bridge)
if bridge else '') +
(' <ip address=\'{0}\' netmask=\'255.255.255.0\'>\n'
.format(ip_address)) +
' </ip>\n'
'</network>")')
run('virsh net-start foreman')
run('virsh net-autostart foreman')
os_version = distro_info()[1]
if os_version >= 7:
manage_daemon('start', 'firewalld')
run('firewall-cmd --add-service vnc-server --permanent')
run('firewall-cmd --service=vnc-server --add-port=5901-5999/tcp '
'--permanent')
run('firewall-cmd --reload')
else:
run('iptables -I INPUT -m state --state NEW -p tcp --dport 5901:5999 '
'-j ACCEPT')
# To make the changes persistent across reboots
manage_daemon('save', 'iptables')
# Fetch virtual bridge information
interface = run('virsh net-info foreman | awk \'/Bridge:/{printf$2}\'')
return interface
def setup_http_proxy(proxy_info):
"""Postinstall task to set http_proxy and content_default_http_proxy settings for
Satellite >= 6.7
Proxy information is passed using the PROXY_INFO environmental variable.
The expected format is::
PROXY_INFO=proxy://<username>:<password>@<hostname>:<port>
``username`` and ``password`` fields can be omitted if the proxy does not
require authentication, for example::
PROXY_INFO=proxy://<hostname>:<port>
"""
admin_password = os.environ.get('ADMIN_PASSWORD', 'changeme')
command = (
'hammer -u admin -p {0} settings set --name "http_proxy" --value {1}'
).format(admin_password, proxy_info.replace('proxy:', 'http:'))
run(command, warn_only=True)
proxy_info = urlsplit(proxy_info)
url = 'http://{0}:{1}'.format(proxy_info.hostname, proxy_info.port)
command = (
'hammer -u admin -p {0} http-proxy create --name {1} --url {2}'
).format(admin_password, proxy_info.hostname, url)
if proxy_info.username and proxy_info.password:
creds = ' --username {0} --password {1}'.format(proxy_info.username, proxy_info.password)
command = command + creds
run(command, warn_only=True)
command = (
'hammer -u admin -p {0} settings set --name "content_default_http_proxy" --value {1}'
).format(
admin_password, proxy_info.hostname)
run(command, warn_only=True)
def setup_default_subnet():
"""Postinstall task to setup default subnet within Satellite
Expects the following environment variables:
SUBNET
The network address that Internal Capsule resides in
NETMASK
The netmask of the subnet
GATEWAY
The gateway in the subnet
DHCP_RANGE
The range in the subnet operated by DHCP Capsule
"""
dhcp_range = os.environ.get('DHCP_RANGE', '192.168.100.10 192.168.100.254').split()
options = {
'password': os.environ.get('ADMIN_PASSWORD', 'changeme'),
'network': os.environ.get('SUBNET', '192.168.100.0'),
'mask': os.environ.get('NETMASK', '255.255.255.0'),
'gateway': os.environ.get('GATEWAY', '192.168.100.1'),
'from': dhcp_range[0], 'to': dhcp_range[1],
}
command = (
'hammer -u admin -p {password} subnet create --name "Default Subnet" '
'--network {network} --mask {mask} '
'--gateway {gateway} --dns-primary {gateway} '
'--ipam DHCP --from {from} --to {to} '
'--dhcp-id 1 --dns-id 1 --tftp-id 1 --discovery-id 1'
).format(**options)
# create or update if failed
if run(command, warn_only=True).failed:
run(command.replace(' create ', ' update ', 1))
def setup_bfa_prevention(bfa_limit=0):
"""Postinstall task to set the `failed_login_attempts_limit` global setting
to control brute-force-attack prevention.
Expects the following environment variables:
:param int bfa_limit: number of failed login attempts in 5 minute to trigger BFA prevention
0 (default) disables BFA prevention
"""
command = (
'hammer -u admin -p {0} settings set --name "failed_login_attempts_limit" --value {1}'
).format(os.environ.get('ADMIN_PASSWORD', 'changeme'), bfa_limit)
run(command, warn_only=True)
def setup_email_notification(smtp=None):
"""Configures system to handle email notification.
NOTE: this task needs a 'katello-service restart', so choose wisely when to
call it, preferably before another task that restarts the stack, such as
the 'setup_default_capsule' task.
:param str smtp: A valid URL to a SMTP server.
"""
# edit the config file
if smtp is not None:
run('sed -i -e "s|address.*|address: {0}|" '
'/etc/foreman/email.yaml'.format(smtp))
run('echo " enable_starttls_auto: false" '
'>> /etc/foreman/email.yaml')
def setup_fake_manifest_certificate(certificate_url=None):
"""Task to setup a fake manifest certificate
Allows accepting modified (UUID) redhat-manifest by using a
fake-manifest-ca.crt
"""
certificate_url = certificate_url or os.environ.get(
'FAKE_MANIFEST_CERT_URL')
if certificate_url is None:
print('You should specify the fake certificate URL')
sys.exit(1)
run('wget -O /etc/candlepin/certs/upstream/fake_manifest.crt '
'{certificate_url}'.format(certificate_url=certificate_url))
manage_daemon('restart', 'tomcat6' if distro_info()[1] <= 6 else 'tomcat')
def setup_firewall(definitions=None, flush=True):
"""Setup firewall rules based on the ``definitions``.
:param definitions: A dict containing the definitions for the
firewall rules, for example::
definitions = {
'tcp': (
42,
9090,
),
'udp': (
4242,
4422,
),
}
:param flush: If ``True`` will clean up all rules before adding the rules
specified by ``definitions``.
"""
if definitions is None:
return
os_version = distro_info()[1]
if os_version < 7:
exists_command = r'iptables -nL INPUT | grep -E "^ACCEPT\s+{0}.*{1}"'
command = (
'iptables -I INPUT -m state --state NEW -p {0} --dport {1} '
'-j ACCEPT'
)
if flush:
run('iptables --flush')
else:
if run('rpm -q firewalld', quiet=True).failed:
run(package_install('firewalld'))
if run('systemctl --no-pager status firewalld', quiet=True).failed:
run('systemctl enable firewalld')
run('systemctl start firewalld')
exists_command = 'firewall-cmd --permanent --query-port="{1}/{0}"'
command = ['firewall-cmd --permanent']
if flush:
ports = run('firewall-cmd --permanent --list-ports').split()
flush_cmd = 'firewall-cmd --permanent {0}'.format(
' '.join(['--remove-port="{0}"'.format(p) for p in ports])
)
if ports:
run(flush_cmd)
for protocol in definitions:
for port in definitions[protocol]:
rule_exists = False if flush else run(
exists_command.format(protocol, port), quiet=True
).succeeded
if not rule_exists:
if os_version < 7:
run(command.format(protocol, port))
else:
# rhel7: only build command
command.append(
'--add-port="{1}/{0}"'.format(protocol, port)
)
if os_version >= 7 and len(command) > 1:
# rhel7: run built command since it was appended
run(' '.join(command))
if os_version < 7:
# To make the changes persistent across reboots
manage_daemon('save', 'iptables')
manage_daemon('enable', 'iptables')
else:
# To activate persistent settings as the current ones
run('firewall-cmd --reload')
def setup_satellite_firewall():
"""Setup firewall rules that Satellite 6 needs to work properly."""
setup_firewall({
'tcp': (
# Port 80 for HTTP (WWW) must be open to download the bootstrap
# files.
80,
# Port 443 for HTTPS (secure WWW) must be open for incoming
# connections.
443,
# Ports 5646 and 5647 for qpidd
5646,
5647,
# Port 5671 must be open for SSL communication with managed
# systems.
5671,
# Port 8000 for foreman-proxy service
8000,
# Port 8140 must be open for incoming Puppet connections with the
# managed systems.
8140,
# Port 8443 for Katello access the Isolated Capsule
8443,
# Port 9090 must be open for Foreman Smart Proxy connections with
# the managed systems.
9090,
# Automation controls machine via ssh
22,
# Local docker listens on 2375/tcp (done by setup_default_docker)
2375,
# Port 5000 must be open for Docker registry communication.
5000,
# Local libvirt listens on 16509/tcp (done by katellovirt module)
16509,
),
'udp': (
# Port 53 must be open for DNS Capsule Feature.
53,
# Port 69 must be open for TFTP Capsule Feature.
69,
),
})
def setup_capsule_firewall():
"""Setup firewall rules that a Satellite 6 Capsule needs to work
properly.
"""
setup_firewall({
'tcp': (
# Connections to the proxy in the Capsule and sending
# generated SCAP reports to the proxy in the Capsule for
# spooling
9090,
# Queries to the DNS service
53,
# Anaconda, yum, and for obtaining Katello certificate updates
80,
# Anaconda, yum, Telemetry Services, and Puppet
443,
# The Katello agent to communicate with the Capsule's Qpid dispatch
# router
5647,
# Anaconda to download kickstart templates to hosts, and for
# downloading iPXE firmware
8000,
# Puppet agent to Puppet master connections
8140,
# Subscription Management Services connection to the reverse proxy
# for the certificate-based API
8443,
5000,
),
'udp': (
# Queries to the DNS service
53,
# For Client provisioning from the Capsule
67,
68,
# Downloading PXE boot image files
69,
),
})
def setup_abrt():
"""Task to setup abrt on foreman
Currently only available on RHEL7, check BZ #1150197 for more info
"""
# Check if rubygem-smart_proxy_abrt package is available
result = run('yum list rubygem-smart_proxy_abrt', quiet=True)
if result.failed:
print('WARNING: ABRT was not set up')
return
# Install required packages for the installation
packages = [
'abrt-cli',
'rubygem-smart_proxy_abrt',
'rubygem-smart_proxy_pulp',
'ruby193-rubygem-foreman_abrt'
]
for package in packages:
run('yum install -y {0}'.format(package))
manage_daemon('restart', 'foreman')
# workaround as sometimes foreman service does not restart with systemctl
run('touch /usr/share/foreman/tmp/restart.txt')
# edit the config files
host = env['host']
run('echo ":foreman_url: https://{0}" >> /etc/foreman-proxy/settings.yml'
''.format(host))
run('sed -i -e "s/^:enabled: false.*/:enabled: true/" '
'/etc/foreman-proxy/settings.d/abrt.yml')
# run the required commands
manage_daemon('start', 'abrtd')
manage_daemon('start', 'abrt-ccpp')
# edit the config files
run('sed -i -e "s|^URL = .*|URL = https://{0}:8443/abrt/|" '
'/etc/libreport/plugins/ureport.conf'.format(host))
run('sed -i -e "s|# SSLVerify = no|SSLVerify = yes|" '
'/etc/libreport/plugins/ureport.conf')
run('sed -i -e "s|# SSLClientAuth = .*|SSLClientAuth = puppet|" '
'/etc/libreport/plugins/ureport.conf')
run('cp /var/lib/puppet/ssl/certs/ca.pem '
'/etc/pki/ca-trust/source/anchors/')
run('update-ca-trust')
run('abrt-auto-reporting enabled')
def setup_python_code_coverage():
"""Task to setup python code coverage on Satellite 6."""
os_version = distro_info()[1]
run('mkdir -p /etc/coverage')
coveragerc_file = StringIO()
coveragerc_file.write(u'[run]\n')
coveragerc_file.write(u'source=\n')
coveragerc_file.write(u' pulp\n')
coveragerc_file.write(u' pulp_deb=\n')
coveragerc_file.write(u' pulp_docker\n')
coveragerc_file.write(u' pulp_openstack\n')
coveragerc_file.write(u' pulp_ostree\n')
coveragerc_file.write(u' pulp_puppet\n')
coveragerc_file.write(u' pulp_python\n')
coveragerc_file.write(u' pulp_rpm\n')
coveragerc_file.write(u'\n')
coveragerc_file.write(u'data_file=/etc/coverage/.coverage\n')
coveragerc_file.write(u'\n')
coveragerc_file.write(u'parallel=true\n')
coveragerc_file.write(u'\n')
coveragerc_file.write(u'concurrency=\n')
coveragerc_file.write(u' multiprocessing\n')
coveragerc_file.write(u' thread\n')
coveragerc_file.write(u'\n')
coveragerc_file.write(u'[xml]\n')
coveragerc_file.write(u'output=/etc/coverage/coverage.xml\n')
put(local_path=coveragerc_file,
remote_path='/etc/coverage/.coveragerc')
coveragerc_file.close()
sitecustomize_file = StringIO()
sitecustomize_file.write(u'import os\n')
sitecustomize_file.write(u'os.environ[\'COVERAGE_PROCESS_START\']')
sitecustomize_file.write(u' = \'/etc/coverage/.coveragerc\'\n')
sitecustomize_file.write(u'# Import coverage after editing environment\n')
sitecustomize_file.write(u'import coverage\n')
sitecustomize_file.write(u'coverage.process_startup()\n')
if os_version == 7:
put(local_path=sitecustomize_file,
remote_path='/usr/lib/python2.7/site-packages/sitecustomize.py')
sitecustomize_file.close()
# install python2 compatible pip (pip<21)
# easy_install is obsoleted and stopped working - use wget to work around failing download
run('wget -nv https://files.pythonhosted.org/packages/'
'53/7f/55721ad0501a9076dbc354cc8c63ffc2d6f1ef360f49ad0fbcce19d68538/pip-20.3.4.tar.gz')
run('easy_install pip-20.3.4.tar.gz')
run('pip install -U coverage')
run('chcon -R -u system_u -t httpd_sys_rw_content_t /etc/coverage')
run('chmod -R 777 /etc/coverage ; chown -R apache.apache /etc/coverage')
def setup_ruby_code_coverage():
"""Task to setup ruby code coverage on Satellite 6."""
os_version = distro_info()[1]
# Install ruby-devel package from the rhel optional installation
# Enable required repository
run('subscription-manager repos --enable rhel-{0}-server-optional-rpms'
.format(os_version))
run('yum -y install ruby-devel')
# Install gcc package so that we can install the ruby gems.
run('yum -y install gcc')
# Installing simplecov and simplecov-rcov rubygems for system folder.
run('gem install simplecov ; gem install simplecov-rcov')
# Installing simplecov and simplecov-rcov rubygems for scl - tfm.
run('scl enable tfm \'gem install simplecov\'')
# Installing simplecov and simplecov-rcov rubygems for scl - tfm.
run('scl enable tfm \'gem install simplecov-rcov\'')
# Installing for dependencies.
run('scl enable tfm \'gem install docile\'')
run('scl enable tfm \'gem install json\'', quiet=True)
run('echo "export RUBY_SYS_COVERAGE_CONFIG=/etc/coverage/ruby/sys/'
'config_sys.yml" >> ~/.bashrc')
run('echo "export RUBY_TFM_COVERAGE_CONFIG=/etc/coverage/ruby/tfm/'
'config_tfm.yml" >> ~/.bashrc')
run('for i in `find / -name simplecov-html.rb`; do sed -i -e '
'"s/puts output_message(result)/# puts output_message(result)/"'
' $i; done')
# This function sets up the ruby code coverage around satellite-installer and
# the proxy. This mostly deals with system rubygems.
def setup_rubysys_code_coverage():
"""Task to setup ruby code coverage for system file on Satellite 6.
The following environment variables affect this task:
* `RUBY_SYS_COVERAGE_URL`
"""
run('mkdir -p /etc/coverage/ruby/sys/')
coverageruby_file = StringIO()
coverageruby_file.write(u'---\n')
coverageruby_file.write(u'project_folder_name :')
coverageruby_file.write(u' \'/usr/share/gems/gems/\'\n')
coverageruby_file.write(u'report_directory :')
coverageruby_file.write(u' \'/etc/coverage/ruby/sys/reports/\'\n')
coverageruby_file.write(u'analysis_name : \'ruby_subprocess_coverage\'\n')
coverageruby_file.write(u'...\n')
put(local_path=coverageruby_file,
remote_path='/etc/coverage/ruby/sys/config_sys.yml')
coverageruby_file.close()
coverage_sys_url = os.getenv('RUBY_SYS_COVERAGE_URL')
coverage_sys_file = '/root/coverage_sys.rb'
coverage_sys_rubygems = '/usr/share/rubygems/rubygems.rb'
if not coverage_sys_url:
print('You need to provide the SYS Coverage Url.')
sys.exit(1)
run('wget -O {0} {1}'.format(coverage_sys_file, coverage_sys_url))
run('cat {0} >> {1}'.format(coverage_sys_file, coverage_sys_rubygems))
# This function sets up the ruby code coverage around foreman and katello(tfm).
# This mostly deals with tfm rubygems from RedHat software collections (scl).
def setup_rubytfm_code_coverage():
"""Task to setup ruby code coverage for tfm files on Satellite 6.
The following environment variables affect this task:
* `RUBY_TFM_COVERAGE_URL`
"""
run('mkdir -p /etc/coverage/ruby/tfm/')
coverageruby_file = StringIO()
coverageruby_file.write(u'---\n')
coverageruby_file.write(u'project_folder_name :')
coverageruby_file.write(u' \'/opt/theforeman/tfm')
coverageruby_file.write(u'/root/usr/share/gems/gems/\'\n')
coverageruby_file.write(u'report_directory :')
coverageruby_file.write(u' \'/etc/coverage/ruby/tfm/reports/\'\n')
coverageruby_file.write(u'analysis_name : \'ruby_subprocess_coverage\'\n')
coverageruby_file.write(u'...\n')
put(local_path=coverageruby_file,
remote_path='/etc/coverage/ruby/tfm/config_tfm.yml')
coverageruby_file.close()
coverage_tfm_url = os.getenv('RUBY_TFM_COVERAGE_URL')
coverage_tfm_file = '/root/coverage_tfm.rb'
coverage_tfm_rubygems = (
'/opt/rh/rh-ruby23/root'
'/usr/share/rubygems/rubygems.rb')
if not coverage_tfm_url:
print('You need to provide the TFM Coverage Url.')
sys.exit(1)
run('wget -O {0} {1}'.format(coverage_tfm_file, coverage_tfm_url))
run('cat {0} >> {1}'.format(coverage_tfm_file, coverage_tfm_rubygems))
def configure_sonarqube():
"""Task to configure SonarQube.
The following environment variables affect this task:
* `HTTP_SERVER_HOSTNAME`
* `SONAR_SERVER_URL`
* `SATELLITE_VERSION`
* `BUILD_LABEL`
* `SONAR_LOGIN`
* `SONAR_PASSWORD`
"""
http_server = os.environ.get('HTTP_SERVER_HOSTNAME')
sonar_server = os.environ.get('SONAR_SERVER_URL')
satellite_version = os.environ.get('SATELLITE_VERSION')
build_label = os.environ.get('BUILD_LABEL')
sonar_login = os.environ.get('SONAR_LOGIN')
sonar_password = os.environ.get('SONAR_PASSWORD')
# Sonar Scanner requires Java1.8 to be able to upload content to SonarQube
run('yum -y install java-1.8.0-openjdk')
# Download and Install Sonar-Scanner 2.6
run('wget {0}/pub/sonar-scanner-2.6-SNAPSHOT.zip'.format(http_server))
run('unzip sonar-scanner-2.6-SNAPSHOT.zip')
# Run the Sonar-Scanner to actually upload the results to SonarQube.
run('sonar-scanner-2.6-SNAPSHOT/bin/sonar-scanner -X -e '
'-Dsonar.host.url={0} -Dsonar.language=py -Dsonar.ws.timeout=180 '
'-Dsonar.projectVersion={1} '
'"-Dsonar.projectName=Satellite{2} Pulp Python Analysis" '
'"-Dsonar.python.coverage.reportPath=/etc/coverage/coverage.xml" '
'"-Dsonar.projectKey=Satellite{2}_pulp_python_full_analysis" '
'-Dsonar.projectBaseDir=/usr/lib/python2.7/site-packages/ '
'-Dsonar.sources=pulp,pulp_docker,pulp_katello,pulp_ostree,pulp_puppet'
',pulp_rpm "-Dsonar.exclusions=pulp_docker/plugins/distributors/'
'distributor_export.py,pulp_rpm/extensions/*.py" '
'"-Dsonar.login={3}" "-Dsonar.password={4}"'
.format(
sonar_server, build_label, satellite_version,
sonar_login, sonar_password))
if os.environ.get('RUBY_CODE_COVERAGE') == 'true':
run('sonar-scanner-2.6-SNAPSHOT/bin/sonar-scanner -X -e '
'-Dsonar.host.url={0} -Dsonar.language=ruby '
'-Dsonar.ws.timeout=180 -Dsonar.projectVersion={1} '
'"-Dsonar.projectName=Satellite{2} TFM Ruby Analysis" '
'"-Dsonar.simplecovrcov.reportPath=/etc/coverage'
'/ruby/tfm/reports/results.json" '
'"-Dsonar.projectKey=Satellite{2}_tfm_ruby_full_analysis" '
'-Dsonar.projectBaseDir=/opt/theforeman/tfm/root'
'/usr/share/gems/gems/ '
'-Dsonar.sources=/opt/theforeman/tfm/root/usr/share/gems/gems/ '
'"-Dsonar.login={3}" "-Dsonar.password={4}"'
.format(
sonar_server, build_label, satellite_version,
sonar_login, sonar_password))
def install_ansible_scap_client():
"""Task to install ansiblerole-foreman_scap_client."""
# Install required packages for the installation
run('yum -y install ansiblerole-foreman_scap_client')
def oscap_content():