/
hosts.py
1753 lines (1562 loc) · 72.2 KB
/
hosts.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
import re
import time
from contextlib import contextmanager
from functools import cached_property
from pathlib import Path
from pathlib import PurePath
from tempfile import NamedTemporaryFile
from urllib.parse import urlencode
from urllib.parse import urljoin
from urllib.parse import urlunsplit
import requests
from broker import Broker
from broker.hosts import Host
from dynaconf.vendor.box.exceptions import BoxKeyError
from fauxfactory import gen_alpha
from fauxfactory import gen_string
from nailgun import entities
from packaging.version import Version
from ssh2.exceptions import AuthenticationError
from wait_for import TimedOutError
from wait_for import wait_for
from wrapanapi.entities.vm import VmState
from robottelo import constants
from robottelo.api.utils import update_provisioning_template
from robottelo.cli.factory import CLIFactoryError
from robottelo.config import configure_airgun
from robottelo.config import configure_nailgun
from robottelo.config import robottelo_tmp_dir
from robottelo.config import settings
from robottelo.constants import CUSTOM_PUPPET_MODULE_REPOS
from robottelo.constants import CUSTOM_PUPPET_MODULE_REPOS_PATH
from robottelo.constants import CUSTOM_PUPPET_MODULE_REPOS_VERSION
from robottelo.constants import HAMMER_CONFIG
from robottelo.constants import SATELLITE_VERSION
from robottelo.errors import DownloadFileError
from robottelo.errors import HostPingFailed
from robottelo.host_helpers import CapsuleMixins
from robottelo.host_helpers import ContentHostMixins
from robottelo.host_helpers import SatelliteMixins
from robottelo.logging import logger
from robottelo.utils import validate_ssh_pub_key
from robottelo.utils.installer import InstallerCommand
POWER_OPERATIONS = {
VmState.RUNNING: 'running',
VmState.STOPPED: 'stopped',
'reboot': 'reboot'
# TODO paused, suspended, shelved?
}
def get_sat_version():
"""Try to read sat_version from envvar SATELLITE_VERSION
if not available fallback to ssh connection to get it."""
try:
sat_version = Satellite().version
except (AuthenticationError, ContentHostError, BoxKeyError):
if hasattr(settings.server.version, 'release'):
sat_version = str(settings.server.version.release)
elif hasattr(settings.robottelo, 'satellite_version'):
sat_version = settings.robottelo.satellite_version
else:
sat_version = SATELLITE_VERSION
return Version('9999' if 'nightly' in sat_version else sat_version)
def get_sat_rhel_version():
"""Try to read rhel_version from Satellite host
if not available fallback to robottelo configuration."""
try:
rhel_version = Satellite().os_version
except (AuthenticationError, ContentHostError, BoxKeyError):
if hasattr(settings.server.version, 'rhel_version'):
rhel_version = str(settings.server.version.rhel_version)
elif hasattr(settings.robottelo, 'rhel_version'):
rhel_version = settings.robottelo.rhel_version
return Version(rhel_version)
def setup_capsule(satellite, capsule, registration_args=None, installation_args=None):
"""Given satellite and capsule instances, run the commands needed to set up the capsule
Note: This does not perform content setup actions on the Satellite
:param satellite: An instance of this module's Satellite class
:param capsule: An instance of this module's Capsule class
:param registration_args: A dictionary mapping argument: value pairs for registration
:param installation_args: A dictionary mapping argument: value pairs for installation
:return: An ssh2-python result object for the installation command.
"""
if not registration_args:
registration_args = {}
file, cmd_args = satellite.capsule_certs_generate(capsule)
if installation_args:
cmd_args.update(installation_args)
satellite.execute(
f'sshpass -p "{capsule.password}" scp -o "StrictHostKeyChecking no" '
f'{file} root@{capsule.hostname}:{file}'
)
capsule.install_katello_ca(sat_hostname=satellite.hostname)
capsule.register_contenthost(**registration_args)
return capsule.install(**cmd_args)
class ContentHostError(Exception):
pass
class CapsuleHostError(Exception):
pass
class SatelliteHostError(Exception):
pass
class ContentHost(Host, ContentHostMixins):
run = Host.execute
default_timeout = settings.server.ssh_client.command_timeout
def __init__(self, hostname, auth=None, **kwargs):
"""ContentHost object with optional ssh connection
:param hostname: The fqdn of a ContentHost target
:param auth: ('root', 'rootpass') or '/path/to/keyfile.rsa'
:param satellite: optional parameter satellite object.
"""
if not hostname:
raise ContentHostError('A valid hostname must be provided')
if isinstance(auth, tuple):
# username/password-based auth
kwargs.update({'username': auth[0], 'password': auth[1]})
elif isinstance(auth, str):
# key file based authentication
kwargs.update({'key_filename': auth})
self._satellite = kwargs.get('satellite')
self.blank = kwargs.get('blank', False)
super().__init__(hostname=hostname, **kwargs)
@property
def satellite(self):
if not self._satellite:
self._satellite = Satellite()
return self._satellite
@property
def nailgun_host(self):
"""If this host is subscribed, provide access to its nailgun object"""
if self.subscribed:
try:
host_list = self.satellite.api.Host().search(query={'search': self.hostname})[0]
except Exception as err:
logger.error(f'Failed to get nailgun host for {self.hostname}: {err}')
host_list = None
return host_list
@property
def subscribed(self):
"""Boolean representation of a content host's subscription status"""
return 'Status: Unknown' not in self.execute('subscription-manager status').stdout
@property
def ip_addr(self):
ipv4, *ipv6 = self.execute('hostname -I').stdout.split()
return ipv4
@cached_property
def _redhat_release(self):
"""Process redhat-release file for distro and version information"""
result = self.execute('cat /etc/redhat-release')
if result.status != 0:
raise ContentHostError(f'Not able to cat /etc/redhat-release "{result.stderr}"')
match = re.match(r'(?P<distro>.+) release (?P<major>\d+)(.(?P<minor>\d+))?', result.stdout)
if match is None:
raise ContentHostError(f'Not able to parse release string "{result.stdout}"')
return match.groupdict()
@cached_property
def os_distro(self):
"""Get host's distro information"""
groups = self._redhat_release
return groups['distro']
@cached_property
def os_version(self):
"""Get host's OS version information
:returns: A ``packaging.version.Version`` instance
"""
groups = self._redhat_release
minor_version = '' if groups['minor'] is None else f'.{groups["minor"]}'
version_string = f'{groups["major"]}{minor_version}'
return Version(version=version_string)
def setup(self):
if not self.blank:
self.remove_katello_ca()
self.execute('subscription-manager clean')
def teardown(self):
if not self.blank:
if self.nailgun_host:
self.nailgun_host.delete()
self.unregister()
# Strip most unnecessary attributes from our instance for checkin
keep_keys = set(self.to_dict()) | {'release', '_prov_inst', '_cont_inst_p'}
self.__dict__ = {k: v for k, v in self.__dict__.items() if k in keep_keys}
self.__class__ = Host
def power_control(self, state=VmState.RUNNING, ensure=True):
"""Lookup the host workflow for power on and execute
Args:
state: A VmState from wrapanapi.entities.vm or 'reboot'
ensure: boolean indicating whether to try and connect to ensure power state
Raises:
NotImplementedError: if the workflow name isn't found in settings
BrokerError: various error types to do with broker execution
ContentHostError: if the workflow status isn't successful and broker didn't raise
"""
try:
vm_operation = POWER_OPERATIONS.get(state)
workflow_name = settings.broker.host_workflows.power_control
except (AttributeError, KeyError):
raise NotImplementedError(
'No workflow in broker.host_workflows for power control, '
'or VM operation not supported'
)
assert (
# TODO read the kwarg name from settings too?
Broker()
.execute(
workflow=workflow_name,
vm_operation=vm_operation,
source_vm=self.name,
)['status']
.lower()
== 'successful'
)
if ensure and state in [VmState.RUNNING, 'reboot']:
try:
wait_for(
self.connect, fail_condition=lambda res: res is not None, handle_exception=True
)
# really broad diaper here, but connection exceptions could be a ton of types
except TimedOutError:
raise ContentHostError('Unable to connect to host that should be running')
def download_file(self, file_url, local_path=None, file_name=None):
"""Downloads file from given fileurl to directory specified by local_path by given filename
on satellite.
If remote directory is not specified it downloads file to /tmp/.
:param str file_url: The complete server file path from where the
file will be downloaded.
:param str local_path: Name of directory where file will be saved. If not
provided file will be saved in /tmp/ directory.
:param str file_name: New name of the Downloaded file else its given from file_url
:returns: Returns list containing complete file path and name of downloaded file.
"""
file_name = PurePath(file_name or file_url).name
local_path = PurePath(local_path or '/tmp') / file_name
# download on server
result = self.execute(f'wget -O {local_path} {file_url}')
if result.status != 0:
raise DownloadFileError(f'Unable to download {file_name}: {result.stderr}')
return local_path, file_name
def download_install_rpm(self, repo_url, package_name):
"""Downloads and installs custom rpm on the broker virtual machine.
:param repo_url: URL to repository, where package is located.
:param package_name: Desired package name.
:return: None.
:raises robottelo.hosts.ContentHostError: If package wasn't installed.
"""
self.execute(f'curl -k -O {repo_url}/{package_name}.rpm')
result = self.execute(f'rpm -i {package_name}.rpm')
if result.status != 0:
raise ContentHostError(f'Failed to install {package_name} rpm.')
return result
def enable_repo(self, repo, force=False):
"""Enables specified Red Hat repository on the broker virtual machine.
Does nothing if downstream capsule or satellite tools repo was passed.
Custom repos are enabled by default when registering a host.
:param repo: Red Hat repository name.
:param force: enforce enabling command, even when custom repos are
detected for satellite tools or capsule.
:return: None.
"""
downstream_repo = None
if repo == constants.REPOS['rhst6']['id']:
downstream_repo = settings.repos.sattools_repo['rhel6']
elif repo == constants.REPOS['rhst7']['id']:
downstream_repo = settings.repos.sattools_repo['rhel7']
elif repo == constants.REPOS['rhst8']['id']:
downstream_repo = settings.repos.sattools_repo['rhel8']
elif repo in (constants.REPOS['rhsc6']['id'], constants.REPOS['rhsc7']['id']):
downstream_repo = settings.repos.capsule_repo
if force or settings.robottelo.cdn or not downstream_repo:
return self.execute(f'subscription-manager repos --enable {repo}')
def subscription_manager_list_repos(self):
return self.execute('subscription-manager repos --list')
def subscription_manager_status(self):
return self.execute('subscription-manager status')
def subscription_manager_list(self):
return self.execute('subscription-manager list')
def subscription_manager_get_pool(self, sub_list=[]):
"""
Return pool ids for the corresponding subscriptions in the list
"""
pool_ids = []
for sub in sub_list:
result = self.execute(
f'subscription-manager list --available --pool-only --matches="{sub}"'
)
result = result.stdout
result = result.split('\n')
result = ' '.join(result).split()
pool_ids.append(result)
return pool_ids
def subscription_manager_attach_pool(self, pool_list=[]):
"""
Attach pool ids to the host and return the result
"""
result = []
for pool in pool_list:
result.append(self.execute(f'subscription-manager attach --pool={pool}'))
return result
def create_custom_repos(self, **kwargs):
"""Create custom repofiles.
Each ``kwargs`` item will result in one repository file created. Where
the key is the repository filename and repository name, and the value
is the repository URL.
For example::
create_custom_repo(custom_repo='http://repourl.domain.com/path')
Will create a repository file named ``custom_repo.repo`` with
the following contents::
[custom_repo]
name=custom_repo
baseurl=http://repourl.domain.com/path
enabled=1
gpgcheck=0
"""
for name, url in kwargs.items():
content = f'[{name}]\n' f'name={name}\n' f'baseurl={url}\n' 'enabled=1\n' 'gpgcheck=0'
self.execute(f'echo "{content}" > /etc/yum.repos.d/{name}.repo')
def get_base_url_for_older_rhel_minor(self):
domain = settings.repos.rhel_os_repo_host
major = self.os_version.major
minor = self.os_version.minor - 1
if major == 8:
baseurl = (
f'{domain}/rhel-{major}/rel-eng/RHEL-{major}/'
f'latest-RHEL-{major}.{minor}.0/compose/AppStream/x86_64/os/'
)
elif major == 7:
baseurl = (
f'{domain}/rhel-{major}/rel-eng/RHEL-{major}/'
f'latest-RHEL-{major}.{minor}/compose/Server/x86_64/os/'
)
else:
raise ValueError('not supported major version')
return baseurl
def install_katello_agent(self):
"""Install katello-agent on the virtual machine.
:return: None.
:raises ContentHostError: if katello-agent is not installed.
"""
result = self.execute('yum install -y katello-agent')
if result.status != 0:
raise ContentHostError(f'Failed to install katello-agent: {result.stdout}')
if getattr(self, '_cont_inst', None):
# We're running in a container, goferd won't be running as a service
# so let's run it in the foreground, then detach from the exec
self._cont_inst.exec_run('goferd -f', detach=True)
else:
# We're in a traditional VM, so goferd should be running after katello-agent install
try:
wait_for(lambda: self.execute('service goferd status').status == 0)
except TimedOutError:
raise ContentHostError('katello-agent is not running')
def install_katello_host_tools(self):
"""Installs Katello host tools on the broker virtual machine
:raises robottelo.hosts.ContentHostError: If katello-host-tools wasn't
installed.
"""
result = self.execute('yum install -y katello-host-tools')
if result.status != 0:
raise ContentHostError('Failed to install katello-host-tools')
def install_katello_ca(self, satellite):
"""Downloads and installs katello-ca rpm on the content host.
:param str satellite: robottelo.hosts.Satellite instance
:return: None.
:raises robottelo.hosts.ContentHostError: If katello-ca wasn't
installed.
"""
self._satellite = satellite
self.execute(
f'curl --insecure --output katello-ca-consumer-latest.noarch.rpm \
{satellite.url_katello_ca_rpm}'
)
# check if the host is fips-enabled
result = self.execute('sysctl crypto.fips_enabled')
if 'crypto.fips_enabled = 1' in result.stdout:
self.execute('rpm -Uvh --nodigest --nofiledigest katello-ca-consumer-latest.noarch.rpm')
else:
self.execute('rpm -Uvh katello-ca-consumer-latest.noarch.rpm')
# Not checking the status here, as rpm could be installed before
# and installation may fail
result = self.execute(f'rpm -q katello-ca-consumer-{satellite.hostname}')
# Checking the status here to verify katello-ca rpm is actually
# present in the system
if satellite.hostname not in result.stdout:
raise ContentHostError('Failed to download and install the katello-ca rpm')
def remove_katello_ca(self):
"""Removes katello-ca rpm from the broker virtual machine.
:return: None.
:raises robottelo.hosts.ContentHostError: If katello-ca wasn't removed.
"""
# Not checking the status here, as rpm can be not even installed
# and deleting may fail
self.execute('yum erase -y $(rpm -qa |grep katello-ca-consumer)')
# Checking the status here to verify katello-ca rpm is actually
# not present in the system
result = self.execute('rpm -qa |grep katello-ca-consumer')
if result.status == 0:
raise ContentHostError(f'katello-ca rpm(s) are still installed: {result.stdout}')
self.execute('subscription-manager clean')
self._satellite = None
def install_capsule_katello_ca(self, capsule=None):
"""Downloads and installs katello-ca rpm on the broker virtual machine.
:param: str capsule: Capsule hostname
:raises robottelo.hosts.ContentHostError: If katello-ca wasn't
installed.
"""
url = urlunsplit(('http', capsule, 'pub/', '', ''))
ca_url = urljoin(url, 'katello-ca-consumer-latest.noarch.rpm')
result = self.execute(f'rpm -Uvh {ca_url}')
if result.status != 0:
raise ContentHostError('Failed to install the katello-ca rpm')
def install_cockpit(self):
"""Installs cockpit on the broker virtual machine.
:raises robottelo.hosts.ContentHostError: If cockpit wasn't
installed.
"""
result = self.execute('yum install cockpit -y')
if result.status != 0:
raise ContentHostError('Failed to install the cockpit')
def register(
self,
target,
org,
loc,
activation_keys,
setup_insights=False,
setup_remote_execution=True,
setup_remote_execution_pull=False,
lifecycle_environment=None,
operating_system=None,
packages=None,
repo=None,
repo_gpg_key_url=None,
remote_execution_interface=None,
update_packages=False,
ignore_subman_errors=True,
force=True,
insecure=True,
username=settings.server.admin_username,
password=settings.server.admin_password,
):
"""Registers content host to the Satellite or Capsule server
using a global registration template.
:param target: Satellite or Capusle hostname to register to, required.
:param org: Organization to register content host for, required.
:param loc: Location to register content host for, required.
:param activation_keys: Activation key name to register content host
with, required.
:param setup_insights: Install and register Insights client, requires OS repo.
:param setup_remote_execution: Copy remote execution SSH key.
:param setup_remote_execution_pull: Deploy pull provider client on host
:param lifecycle_environment: Lifecycle environment.
:param operating_system: Operating system.
:param packages: A list of packages to install on the host when registered.
:param repo: Repository to be added before the registration is performed, supply url.
:param repo_gpg_key_url: Public key to verify the package signatures, supply url.
:param remote_execution_interface: Identifier of the host interface for remote execution.
:param update_packages: Update all packages on the host.
:param ignore_subman_errors: Ignore subscription manager errors.
:param force: Register the content host even if it's already registered.
:param insecure: Don't verify server authenticity.
:param username: Satellite admin username
:param password: Satellite admin password
:return: SSHCommandResult instance filled with the result of the
registration.
"""
insights = (
# requires OS repo enabled for host
f'&setup_insights={str(setup_insights).lower()}'
if setup_insights is not None
else ''
)
rex = (
f'&setup_remote_execution={str(setup_remote_execution).lower()}'
if setup_remote_execution is not None
else ''
)
rex_pull = (
# requires Satellite Client repo enabled for host
f'&setup_remote_execution_pull={str(setup_remote_execution_pull).lower()}'
if setup_remote_execution_pull is not None
else ''
)
lce = (
f'&lifecycle_environment_id={lifecycle_environment.id}'
if lifecycle_environment is not None
else ''
)
os = f'&operating_system_id={operating_system.id}' if operating_system is not None else ''
pkgs = f'&packages={"+".join(packages)}' if packages is not None else ''
rex_iface = (
f'&remote_execution_interface={remote_execution_interface}'
if remote_execution_interface is not None
else ''
)
rp = f'&{urlencode({"repo": repo })}' if repo is not None else ''
gpg = (
f'&{urlencode({"repo_gpg_key_url": repo_gpg_key_url })}'
if repo_gpg_key_url is not None
else ''
)
cmd = (
'curl -sS '
f'-u {username}:{password} '
f'{"--insecure " if insecure else ""}'
f"'https://{target.hostname}:9090/register?"
f'activation_keys={activation_keys}'
f'&organization_id={org.id}'
f'&location_id={loc.id}'
f'{insights}'
f'{rex}'
f'&update_packages={"true" if update_packages else "false"}'
f'{rex_pull}'
f'{rex_iface}'
f'{lce}'
f'{os}'
f'{pkgs}'
f'{"&ignore_subman_errors=true" if ignore_subman_errors else ""}'
f'{"&force=true" if force else ""}'
f'{rp}'
f'{gpg}'
"' | bash"
)
return self.execute(cmd)
def register_contenthost(
self,
org='Default_Organization',
activation_key=None,
lce='Library',
consumerid=None,
force=True,
releasever=None,
name=None,
username=settings.server.admin_username,
password=settings.server.admin_password,
auto_attach=False,
serverurl=None,
baseurl=None,
):
"""Registers content host on foreman server either by specifying
organization name and activation key name or by specifying organization
name and lifecycle environment name (administrator credentials for
authentication will be passed automatically).
:param activation_key: Activation key name to register content host
with.
:param lce: lifecycle environment name to which register the content
host.
:param consumerid: uuid of content host, register to this content host,
content host has to be created before
:param org: Organization name to register content host for.
:param force: Register the content host even if it's already registered
:param releasever: Set a release version
:param username: a user name to register the content host with
:param password: the user password
:param auto_attach: automatically attach compatible subscriptions to
this system.
:param name: name of the system to register, defaults to the hostname
:param serverurl: name of the subscription service with which to
register the system
:param baseurl: name of the content delivery service to configure the
yum service to use to pull down packages
:return: SSHCommandResult instance filled with the result of the
registration.
"""
if username and password:
userpass = f' --username {username} --password {password}'
else:
userpass = ''
# Setup the base command
cmd = 'subscription-manager register'
if org:
cmd += f' --org {org}'
# Determine our registration path
if activation_key:
cmd += f' --activationkey {activation_key}'
elif lce:
cmd += f' --environment {lce}{userpass}'
elif consumerid:
cmd += f' --consumerid {consumerid}{userpass}'
else:
# if no other methods are provided, we can still try user/pass
cmd += userpass
# Additional registration modifiers
if auto_attach:
cmd += ' --auto-attach'
if releasever:
cmd += f' --release {releasever}'
if force:
cmd += ' --force'
if name:
cmd += f' --name {name}'
if serverurl:
cmd += f' --serverurl {serverurl}'
if baseurl:
cmd += f' --baseurl {baseurl}'
return self.execute(cmd)
def unregister(self):
"""Run subscription-manager unregister.
:return: SSHCommandResult instance filled with the result of the
unregistration.
"""
return self.execute('subscription-manager unregister')
def get(self, remote_path, local_path=None):
"""Get a remote file from the broker virtual machine."""
self.session.sftp_read(source=remote_path, destination=local_path)
def put(self, local_path, remote_path=None):
"""Put a local file to the broker virtual machine.
If local_path is a manifest object, write its contents to a temporary file
then continue with the upload.
"""
if 'manifests.Manifest' in str(local_path):
with NamedTemporaryFile(dir=robottelo_tmp_dir) as content_file:
content_file.write(local_path.content.read())
content_file.flush()
self.session.sftp_write(source=content_file.name, destination=remote_path)
else:
self.session.sftp_write(source=local_path, destination=remote_path)
def put_ssh_key(self, source_key_path, destination_key_name):
"""Copy ssh key to virtual machine ssh path and ensure proper permission is set
Args:
source_key_path: The ssh key file path to copy to vm
destination_key_name: The ssh key file name when copied to vm
"""
destination_key_path = f'/root/.ssh/{destination_key_name}'
self.put(local_path=source_key_path, remote_path=destination_key_path)
result = self.execute(f'chmod 600 {destination_key_path}')
if result.status != 0:
raise CLIFactoryError(f'Failed to chmod ssh key file:\n{result.stderr}')
def add_authorized_key(self, pub_key):
"""Inject a public key into the authorized keys file
Args:
pub_key: public key string, file-like object, or path string
Raises:
ValueError: if the pub_key isn't valid or found
"""
if getattr(pub_key, 'read', False): # key is a file-like object
key_content = pub_key.read()
elif validate_ssh_pub_key(pub_key): # key is a valid key-string
key_content = pub_key
# use expanduser here to handle relative paths with ~ resolving locally
elif Path(pub_key).expanduser().exists(): # key is a path to a pub key-file
key_content = Path(pub_key).expanduser().read_text()
else:
raise ValueError('Invalid key')
key_content = key_content.strip()
ssh_path = PurePath('~/.ssh')
auth_file = ssh_path.joinpath('authorized_keys')
# ensure ssh directory exists
self.execute(f'mkdir -p {ssh_path}')
# append the key if doesn't exists
self.execute(
"grep -q '{key}' {dest} || echo '{key}' >> {dest}".format(
key=key_content, dest=auth_file
)
)
# set proper permissions
self.execute(f'chmod 700 {ssh_path}')
self.execute(f'chmod 600 {auth_file}')
self.execute(f'chown -R {self.username} {ssh_path}')
# Restore SELinux context with restorecon, if it's available:
self.execute(f'command -v restorecon && restorecon -RvF {ssh_path} || true')
def add_rex_key(self, satellite, key_path=None):
"""Read a public key from the passed Satellite, and add it to authorized_keys
Args:
satellite: ``Capsule`` or ``Satellite`` instance
key_path: optional path to the key on the satellite
"""
if key_path is not None:
sat_key = satellite.execute(f'cat {key_path}').stdout.strip()
else:
sat_key = satellite.rex_pub_key
self.add_authorized_key(pub_key=sat_key)
def update_known_hosts(self, ssh_key_name, host, user=None):
"""Create host entry in vm ssh config and known_hosts files to allow vm
to access host via ssh without password prompt
:param robottelo.hosts.ContentHost vm: Virtual machine instance
:param str ssh_key_name: The ssh key file name to use to access host,
the file must already exist in /root/.ssh directory
:param str host: the hostname to setup that will be accessed from vm
:param str user: the user that will access the host
"""
user = user or 'root'
ssh_path = '/root/.ssh'
ssh_key_file_path = f'{ssh_path}/{ssh_key_name}'
# setup the config file
ssh_config_file_path = f'{ssh_path}/config'
result = self.execute(f'touch {ssh_config_file_path}')
if result.status != 0:
raise CLIFactoryError(f'Failed to create ssh config file:\n{result.stderr}')
result = self.execute(
f'echo "\nHost {host}\n\tHostname {host}\n\tUser {user}\n'
f'\tIdentityFile {ssh_key_file_path}\n" >> {ssh_config_file_path}'
)
if result.status != 0:
raise CLIFactoryError(f'Failed to write to ssh config file:\n{result.stderr}')
# add host entry to ssh known_hosts
result = self.execute(f'ssh-keyscan {host} >> {ssh_path}/known_hosts')
if result.status != 0:
raise CLIFactoryError(
f'Failed to put hostname in ssh known_hosts files:\n{result.stderr}'
)
def configure_puppet(self, proxy_hostname=None):
"""Configures puppet on the virtual machine/Host.
:param proxy_hostname: external capsule hostname
:return: None.
:raises robottelo.hosts.ContentHostError: If installation or configuration fails.
"""
if proxy_hostname is None:
proxy_hostname = settings.server.hostname
self.create_custom_repos(
sat_client=settings.repos['SATCLIENT_REPO'][f'RHEL{self.os_version.major}']
)
result = self.execute('yum install puppet-agent -y')
if result.status != 0:
raise ContentHostError('Failed to install the puppet-agent rpm')
cert_name = self.hostname
puppet_conf = (
'[main]\n'
'vardir = /opt/puppetlabs/puppet/cache\n'
'logdir = /var/log/puppetlabs/puppet\n'
'rundir = /var/run/puppetlabs\n'
'ssldir = /etc/puppetlabs/puppet/ssl\n'
'[agent]\n'
'pluginsync = true\n'
'report = true\n'
'ignoreschedules = true\n'
f'ca_server = {proxy_hostname}\n'
f'certname = {cert_name}\n'
'environment = production\n'
f'server = {proxy_hostname}\n'
)
self.execute(f'echo "{puppet_conf}" >> /etc/puppetlabs/puppet/puppet.conf')
# This particular puppet run on client would populate a cert on
# sat6 under the capsule --> certifcates or on capsule via cli "puppetserver
# ca list", so that we sign it.
self.execute('/opt/puppetlabs/bin/puppet agent -t')
proxy_host = Host(proxy_hostname)
proxy_host.execute(f'puppetserver ca sign --certname {cert_name}')
# This particular puppet run would create the host entity under
# 'All Hosts' and let's redirect stderr to /dev/null as errors at
# this stage can be ignored.
result = self.execute('/opt/puppetlabs/bin/puppet agent -t 2> /dev/null')
if result.status:
raise ContentHostError('Failed to configure puppet on the content host')
def execute_foreman_scap_client(self, policy_id=None):
"""Executes foreman_scap_client on the vm to create security audit report.
:param policy_id: The Id of the OSCAP policy.
:return: None.
"""
if policy_id is None:
result = self.execute(
'awk -F "/" \'/download_path/ {print $4}\' /etc/foreman_scap_client/config.yaml'
)
policy_id = result.stdout.strip()
result = self.execute(f'foreman_scap_client ds {policy_id}')
if result.status != 0:
data = self.execute(
'rpm -qa |grep scap; yum repolist;cat /etc/foreman_scap_client/config.yaml; '
'cat /etc/cron.d/foreman_scap_client_cron; tail -n 100 /var/log/messages'
)
raise ContentHostError(
f'Failed to execute foreman_scap_client run. '
f'Command exited with code: {result.status}, stderr: {result.stderr}, '
f'stdout: {result.stdout} host_data_stdout: {data.stdout}, '
f'and host_data_stderr: {data.stderr}'
)
def configure_rex(self, satellite, org, subnet_id=None, by_ip=True, register=True):
"""Setup a VM host for remote execution.
:param Satellite satellite: a hosts.Satellite instance
:param str org: The organization entity, label attr is used
:param int subnet: (Optional) Nailgun subnet entity id, to be used by the vm_client host.
:param bool by_ip: Whether remote execution will use ip or host name to access server.
:param bool register: Whether to register to the Satellite. Keyexchange done regardless
"""
if register:
self.install_katello_ca(satellite)
self.register_contenthost(org.label, lce='Library')
assert self.subscribed
self.add_rex_key(satellite=satellite)
if register and subnet_id is not None:
host = self.nailgun_host.read()
host.name = self.hostname
host.subnet_id = int(subnet_id)
host.update(['name', 'subnet_id'])
if register and by_ip:
# connect to host by ip
host = self.nailgun_host.read()
host_parameters = [
{
'name': 'remote_execution_connect_by_ip',
'value': 'True',
'parameter-type': 'boolean',
}
]
host.host_parameters_attributes = host_parameters
host.update(['host_parameters_attributes'])
def configure_rhai_client(
self, satellite, activation_key, org, rhel_distro, register_insights=True, register=True
):
"""Configures a Red Hat Access Insights service on the system by
installing the redhat-access-insights package and registering to the
service.
:param activation_key: Activation key to be used to register the
system to satellite
:param org: The org to which the system is required to be registered
:param rhel_distro: rhel distribution used by the vm
:param register: Whether to register client to insights
:return: None
"""
if register:
# Install Satellite CA rpm
self.install_katello_ca(satellite)
self.register_contenthost(org, activation_key)
# Red Hat Insights requires RHEL 6/7/8 repo and it is not
# possible to sync the repo during the tests, Adding repo file.
distro_repo_map = {
'rhel6': settings.repos.rhel6_os,
'rhel7': settings.repos.rhel7_os,
'rhel8': settings.repos.rhel8_os,
'rhel9': settings.repos.rhel9_os,
}
rhel_repo = distro_repo_map.get(rhel_distro)
if rhel_repo is None:
raise ContentHostError(f'Missing RHEL repository configuration for {rhel_distro}.')
if rhel_distro not in ('rhel6', 'rhel7'):
self.create_custom_repos(**rhel_repo)
else:
self.create_custom_repos(**{rhel_distro: rhel_repo})
# Install insights-client rpm
if self.execute('yum install -y insights-client').status != 0:
raise ContentHostError('Unable to install insights-client rpm')
if register_insights:
# Register client
if self.execute('insights-client --register').status != 0:
raise ContentHostError('Unable to register client to Insights through Satellite')
def unregister_insights(self):
"""Unregister insights client.
:return: None
"""
result = self.execute('insights-client --unregister')
if result.status != 0:
raise ContentHostError('Failed to unregister client from Insights through Satellite')
def set_infrastructure_type(self, infrastructure_type='physical'):
"""Force host to appear as bare-metal orbroker virtual machine in
subscription-manager fact.
:param str infrastructure_type: One of 'physical', 'virtual'
"""
script_path = '/usr/sbin/virt-what'
self.execute(f'cp -n {script_path} {script_path}.old')
script_content = ['#!/bin/sh -']
if infrastructure_type == 'virtual':
script_content.append('echo kvm')
script_content = '\n'.join(script_content)
self.execute(f"echo -e '{script_content}' > {script_path}")
def patch_os_release_version(self, distro='rhel7'):
"""Patch VM OS release version.
This is needed by yum package manager to generate the right RH
repositories urls.
"""
if distro == 'rhel7':
rh_product_os_releasever = constants.REPOS['rhel7']['releasever']
else:
raise ContentHostError('No distro package available to retrieve release version')
return self.execute(f"echo '{rh_product_os_releasever}' > /etc/yum/vars/releasever")
# What the heck to call this function?
def contenthost_setup(
self,
satellite,
org_label,
location_title=None,
rh_repo_ids=None,
repo_labels=None,
product_label=None,
lce=None,
activation_key=None,
patch_os_release_distro=None,
install_katello_agent=True,
):
"""
Setup a Content Host with basic components and tasks.
:param str org_label: The Organization label.
:param list rh_repo_ids: a list of RH repositories ids to enable.
:param list repo_labels: a list of custom repositories labels to enable.
:param str product_label: product label if repos_label is applicable.
:param str lce: Lifecycle environment label if applicable.
:param str activation_key: Activation key name if applicable.