forked from SatelliteQE/robottelo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhosts.py
More file actions
3519 lines (3124 loc) · 145 KB
/
Copy pathhosts.py
File metadata and controls
3519 lines (3124 loc) · 145 KB
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 base64
from configparser import ConfigParser
import contextlib
from contextlib import contextmanager
from datetime import UTC, datetime
from functools import cached_property, lru_cache
import importlib
import io
import json
from pathlib import Path, PurePath
import random
import re
import subprocess
import sys
from tempfile import NamedTemporaryFile
import time
from urllib.parse import urljoin, urlparse, urlunsplit
import apypie
from box import Box
from broker import Broker
from broker.helpers import FileLock
from broker.hosts import Host
from dynaconf.vendor.box.exceptions import BoxKeyError
from fauxfactory import gen_alpha, gen_string
from nailgun import entities
from packaging.version import Version
import pytest
import requests
from ssh2.exceptions import AuthenticationError
from wait_for import TimedOutError, wait_for
from wrapanapi.entities.vm import VmState
import yaml
from robottelo import constants
from robottelo.cli.base import Base
from robottelo.config import (
configure_airgun,
configure_nailgun,
robottelo_tmp_dir,
settings,
)
from robottelo.constants import (
CONTAINER_CERTS_PATH,
CUSTOM_PUPPET_MODULE_REPOS,
CUSTOM_PUPPET_MODULE_REPOS_PATH,
CUSTOM_PUPPET_MODULE_REPOS_VERSION,
HAMMER_CONFIG,
KEY_CLOAK_CLI,
RHBK_CLI,
RHSSO_NEW_GROUP,
RHSSO_NEW_USER,
RHSSO_RESET_PASSWORD,
RHSSO_USER_UPDATE,
SATELLITE_VERSION,
)
from robottelo.enums import InstallMethod, NetworkType
from robottelo.exceptions import (
CapsuleHostError,
CLIFactoryError,
CLIReturnCodeError,
ContentHostError,
DownloadFileError,
HostPingFailed,
IPAHostError,
ProxyHostError,
SatelliteHostError,
)
from robottelo.host_helpers import (
CapsuleMixins,
ContentHostMixins,
SatelliteMixins,
)
from robottelo.logging import logger
from robottelo.utils import validate_ssh_pub_key
from robottelo.utils.datafactory import valid_emails_list
from robottelo.utils.installer import InstallerCommand
POWER_OPERATIONS = {
VmState.RUNNING: 'running',
VmState.STOPPED: 'stopped',
'reboot': 'reboot',
# TODO paused, suspended, shelved?
}
@lru_cache
def lru_sat_ready_rhel(rhel_ver):
"""Deploy bare RHEL system ready for Satellite installation."""
rhel_version = rhel_ver or settings.server.version.rhel_version
deploy_args = settings.server.deploy_arguments | {
'deploy_rhel_version': rhel_version,
'deploy_flavor': settings.flavors.default,
'workflow': settings.server.deploy_workflows.os,
}
return Broker(**deploy_args, host_class=Satellite).checkout()
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) as err:
logger.warning('Failed to get Satellite version: %s', err)
if sat_version := str(settings.server.version.get('release')) == 'stream':
sat_version = str(settings.robottelo.get('satellite_version'))
if not sat_version:
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:
return Satellite().os_version
except (AuthenticationError, ContentHostError, BoxKeyError) as err:
logger.warning('Failed to get RHEL version from Satellite: %s', err)
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)
class ContentHost(Host, ContentHostMixins):
run = Host.execute
default_timeout = settings.server.ssh_client.command_timeout
# Extend the keep_keys tuple from the parent class
keep_keys = (*Host.keep_keys, 'net_type', 'blank')
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')
if nt := kwargs.get('net_type'):
self._net_type = NetworkType(nt)
self.blank = kwargs.get('blank', False)
super().__init__(hostname=hostname, **kwargs)
@property
def network_type(self):
if not hasattr(self, '_net_type'):
broker_args = getattr(self, '_broker_args', None) or {}
if nt := broker_args.get('net_type'):
self._net_type = NetworkType(nt)
else:
self._net_type = NetworkType(settings.content_host.network_type)
return self._net_type
@classmethod
def get_hosts_from_inventory(cls, filter):
"""Get an instance of a host from inventory using a filter"""
inv_hosts = Broker(host_class=cls).from_inventory(filter)
logger.debug('Found %s instances from inventory by filter: %s', len(inv_hosts), filter)
return inv_hosts
@classmethod
def get_host_by_hostname(cls, hostname):
"""Get an instance of a host from inventory by hostname"""
logger.info('Getting %s instance from inventory by hostname: %s', cls.__name__, hostname)
inv_hosts = cls.get_hosts_from_inventory(filter=f'@inv.hostname == "{hostname}"')
if not inv_hosts:
raise ContentHostError(f'No {cls.__name__} found in inventory by hostname {hostname}')
if len(inv_hosts) > 1:
raise ContentHostError(
f'Multiple {cls.__name__} found in inventory by hostname {hostname}'
)
return inv_hosts[0]
@property
def satellite(self):
if not self._satellite:
self._satellite = Satellite()
return self._satellite
@property
def _sat_host_record(self):
"""Provide access to this host's Host record if it exists."""
hosts = self.satellite.api.Host().search(query={'search': self.hostname})
if not hosts:
logger.debug('No host record found for %s on Satellite', self.hostname)
return None
return hosts[0]
def delete_host_record(self):
"""Delete the Host record of this host from Satellite."""
if h_record := self._sat_host_record:
logger.debug('Deleting host record for %s from Satellite', self.hostname)
h_record.delete()
@property
def nailgun_host(self):
"""If this host is subscribed, provide access to its nailgun object"""
if self.identity.get('registered_to') == self.satellite.hostname:
try:
host = self._sat_host_record
except Exception as err:
logger.error(f'Failed to get nailgun host for {self.hostname}: {err}')
host = None
return host
logger.warning(f'Host {self.hostname} not registered to {self.satellite.hostname}')
return None
@property
def subscribed(self):
"""Returns True if host is registered, False otherwise"""
result_status = self.execute('subscription-manager identity').status
if result_status not in [0, 1]:
raise ValueError(
'Unexpected output from subscription-manager identity, anything else than RC:0 or RC:1 is unexpected!'
)
return not bool(result_status)
@property
def identity(self):
"""A Dictionary containing RHSM identity attributes of the host"""
id_output = self.execute('subscription-manager identity').stdout
id_dict = {}
if id_output:
id_dict = {
i.split(':')[0].replace(' ', '_'): i.split(': ')[1]
for i in id_output.split('\n')[:-1]
}
regged_to = self.subscription_config['server']['hostname']
if regged_to:
id_dict['registered_to'] = regged_to
return id_dict
@property
def ip_addr(self):
ipv4, *ipv6 = self.execute('hostname -I').stdout.split()
return ipv4
@cached_property
def arch(self):
return self.get_facts().get('lscpu.architecture') or self.execute('uname -m').stdout.strip()
@cached_property
def _redhat_release(self):
"""Process redhat-release file for distro and version information
This is a fallback for when /etc/os-release is not available
"""
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<NAME>.+) release (?P<major>\d+)(.(?P<minor>\d+))?', result.stdout)
if match is None:
raise ContentHostError(f'Not able to parse release string "{result.stdout}"')
r_release = match.groupdict()
# /etc/os-release compatibility layer
r_release['VERSION_ID'] = r_release['major']
# not every release have a minor version
r_release['VERSION_ID'] += f'.{r_release["minor"]}' if r_release['minor'] else ''
distro_map = {
'Fedora': {'NAME': 'Fedora Linux', 'ID': 'fedora'},
'CentOS': {'ID': 'centos'},
'Red Hat Enterprise Linux': {'ID': 'rhel'},
}
# Use the version map to set the NAME and ID fields
for distro, properties in distro_map.items():
if distro in r_release['NAME']:
r_release.update(properties)
break
return r_release
@cached_property
def _os_release(self):
"""Process os-release file for distro and version information"""
facts = {}
regex = r'^(["\'])(.*)(\1)$'
result = self.execute('cat /etc/os-release')
if result.status != 0:
logger.info(
f'Not able to cat /etc/os-release "{result.stderr}", '
'falling back to /etc/redhat-release'
)
return self._redhat_release
for ln in [line for line in result.stdout.splitlines() if line.strip()]:
line = ln.strip()
if line.startswith('#'):
continue
key, value = line.split('=')
if key and value:
facts[key] = re.sub(regex, r'\2', value).replace('\\', '')
return facts
@property
def os_distro(self):
"""Get host's distro information"""
return self._os_release['NAME']
@property
def os_version(self):
"""Get host's OS version information
:return: A ``packaging.version.Version`` instance
"""
return Version(self._os_release['VERSION_ID'])
@property
def os_id(self):
"""Get host's OS ID information"""
return self._os_release['ID']
@cached_property
def is_el(self):
"""Boolean representation of whether this host is an EL host"""
return self.execute('stat /etc/redhat-release').status == 0
@property
def is_rhel(self):
"""Boolean representation of whether this host is a RHEL host"""
return self.os_id == 'rhel'
@property
def is_centos(self):
"""Boolean representation of whether this host is a CentOS host"""
return self.os_id == 'centos'
def list_cached_properties(self):
"""Return a list of cached property names of this class"""
import inspect
return [
name
for name, value in inspect.getmembers(self.__class__)
if isinstance(value, cached_property)
]
def get_cached_properties(self):
"""Return a dictionary of cached properties for this class"""
return {name: getattr(self, name) for name in self.list_cached_properties()}
def clean_cached_properties(self):
"""Delete all cached properties for this class"""
for name in self.list_cached_properties():
with contextlib.suppress(KeyError): # ignore if property is not cached
del self.__dict__[name]
def setup(self):
logger.debug('START: setting up host %s', self)
if not self.blank:
self.reset_rhsm()
logger.debug('END: setting up host %s', self)
def teardown(self):
logger.debug('START: tearing down host %s', self)
if not self.blank and not getattr(self, '_skip_context_checkin', False):
if (
hasattr(pytest, 'capsule_sanity')
and pytest.capsule_sanity is True
and type(self) is Capsule
):
logger.debug('END: Skipping tearing down capsule host %s for sanity', self)
return
self.unregister()
if type(self) is not Satellite: # do not delete Satellite's host record
self.delete_host_record()
logger.debug('END: tearing down host %s', self)
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
"""
if getattr(self, '_cont_inst', None):
raise NotImplementedError('Power control not supported for container instances')
try:
vm_operation = POWER_OPERATIONS.get(state)
workflow_name = settings.broker.host_workflows.power_control
except (AttributeError, KeyError) as err:
raise NotImplementedError(
'No workflow in broker.host_workflows for power control, '
'or VM operation not supported'
) from err
self.close()
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,
timeout=600,
retries=3,
delay=5,
handle_exception=True,
)
# really broad diaper here, but connection exceptions could be a ton of types
except TimedOutError as toe:
raise ContentHostError('Unable to connect to host that should be running') from toe
def wait_for_connection(self, timeout=180):
try:
wait_for(
self.connect,
fail_condition=lambda res: res is not None,
handle_exception=True,
raise_original=True,
timeout=timeout,
delay=1,
)
except (ConnectionRefusedError, ConnectionAbortedError, TimedOutError) as err:
raise ContentHostError(
f'Unable to establsh SSH connection to host {self} after {timeout} seconds'
) from err
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
:return: 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.
: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['rhsc8']['id'], constants.REPOS['rhsc9']['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}')
return None
def disable_repo(self, repo):
return self.execute(f'subscription-manager repos --disable {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_environments_set(
self,
env_names,
username=settings.server.admin_username,
password=settings.server.admin_password,
):
"""
Reassign the host to the specified content view environments
"""
assert isinstance(env_names, str)
return self.execute(
f'subscription-manager environments --set="{env_names}" --username={username} --password={password}'
)
@property
def subscription_config(self):
"Returns subscription config for the host as ConfigParser object"
config = self.execute('cat /etc/rhsm/rhsm.conf').stdout
cp = ConfigParser()
cp.read_file(io.StringIO(config))
return cp
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}]\nname={name}\nbaseurl={url}\nenabled=1\ngpgcheck=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_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 reset_rhsm(self):
"""Global Registration points the host's sub-man to talk to the Sattelite's Candlepin
but saves the original rhsm.conf. Reset the rhsm.conf so that it points back to the CDN.
"""
self.execute(r'\cp -f /etc/rhsm/rhsm.conf{.bak,}')
self.execute('subscription-manager clean')
self._satellite = None
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,
org,
loc,
activation_keys,
target,
setup_insights=False,
setup_remote_execution=True,
setup_remote_execution_pull=False,
operating_system=None,
packages=None,
repo_data=None,
remote_execution_interface=None,
update_packages=False,
ignore_subman_errors=False,
force=False,
insecure=True,
hostgroup=None,
auth_username=None,
auth_password=None,
download_utility=None,
setup_container_certs=None,
):
"""Registers content host to the Satellite or Capsule server
using a global registration template.
:param org: Organization to register content host to. Previously required, pass None to omit
:param loc: Location to register content host for, Previously required, pass None to omit.
:param activation_keys: Activation key name to register content host with, required.
:param target: Satellite or Capsule object to register to, 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 operating_system: Operating system.
:param packages: A list of packages to install on the host when registered.
:param repo_data: Array with repository URL and corresponding GPG key 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 hostgroup: hostgroup to register with
:param auth_username: username required if non-admin user
:param auth_password: password required if non-admin user
:param setup_container_certs: Use certificates for container registry authentication.
:return: SSHCommandResult instance filled with the result of the registration
"""
options = {
'activation-keys': activation_keys,
'insecure': str(insecure).lower(),
'update-packages': str(update_packages).lower(),
}
if org is not None:
if isinstance(org, dict):
options['organization-id'] = org['id']
elif hasattr(org, 'id'):
options['organization-id'] = org.id
else:
raise ValueError('org must be a dict or an Organization object')
if loc is not None:
if isinstance(loc, dict):
options['location-id'] = loc['id']
elif hasattr(loc, 'id'):
options['location-id'] = loc.id
else:
raise ValueError('loc must be a dict or a Location object')
if target.__class__.__name__ == 'Capsule':
options['smart-proxy'] = target.hostname
elif target is not None and target.__class__.__name__ not in ['Capsule', 'Satellite']:
raise ValueError('Global registration method can be used with Satellite/Capsule only')
if operating_system is not None:
options['operatingsystem-id'] = operating_system.id
if hostgroup is not None:
options['hostgroup-id'] = hostgroup.id
if packages is not None:
options['packages'] = '+'.join(packages)
if repo_data is not None:
options['repo-data'] = repo_data
if setup_insights is not None:
options['setup-insights'] = str(setup_insights).lower()
if setup_remote_execution is not None:
options['setup-remote-execution'] = str(setup_remote_execution).lower()
if setup_remote_execution_pull is not None:
options['setup-remote-execution-pull'] = str(setup_remote_execution_pull).lower()
if remote_execution_interface is not None:
options['remote-execution-interface'] = remote_execution_interface
if ignore_subman_errors:
options['ignore-subman-errors'] = str(ignore_subman_errors).lower()
if force:
options['force'] = str(force).lower()
if download_utility is not None:
options['download-utility'] = download_utility
if setup_container_certs:
options['setup-container-registry-certs'] = str(setup_container_certs).lower()
self._satellite = target.satellite
if auth_username and auth_password:
user = target.satellite.cli.User.list({'search': f'login={auth_username}'})
if user:
register_role = target.satellite.cli.Role.info({'name': 'Register hosts'})
target.satellite.cli.User.add_role(
{'id': user[0]['id'], 'role-id': register_role['id']}
)
cmd = target.satellite.cli.HostRegistration.with_user(
auth_username, auth_password
).generate_command(options)
else:
raise CLIFactoryError(f'User {auth_username} doesn\'t exist')
else:
cmd = target.satellite.cli.HostRegistration.generate_command(options)
return self.execute(cmd.strip('\n'))
def api_register(self, target, **kwargs):
"""Register a content host using global registration through API.
:param target: Satellite or Capsule object to register to.
:param kwargs: Additional keyword arguments to pass to the API call.
:return: The result of the API call.
"""
kwargs['insecure'] = kwargs.get('insecure', True)
kwargs['setup_insights'] = kwargs.get('setup_insights', False)
self._satellite = target.satellite
command = target.satellite.api.RegistrationCommand(**kwargs).create()
return self.execute(command.strip('\n'))
def register_contenthost(
self,
org='Default_Organization',
activation_key=None,
lce='Library',
environments=None,
consumerid=None,
force=True,
releasever=None,
name=None,
username=settings.server.admin_username,
password=settings.server.admin_password,
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 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.
"""
userpass = f' --username {username} --password {password}' if username and password else ''
# 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 environments:
cmd += f' --environments {environments}{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 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 configure_podman_cert_auth(self, sat):
"""Configure podman cert-based authentication.
Host needs to be registered to the Satellite."""
assert self.subscribed
pki_path = '/etc/pki/entitlement/'
certs_path = f'{CONTAINER_CERTS_PATH}{sat.hostname}/'
self.execute(f'mkdir {certs_path}')
key = self.execute(f'ls {pki_path}*-key.pem | head -n1').stdout.strip()
assert key
cert = self.execute(f'ls {pki_path}*.pem | grep -v -- "-key.pem" | head -n1').stdout.strip()
assert cert
assert self.execute(f'ln -sf {key} {certs_path}client.key').status == 0
assert self.execute(f'ln -sf {cert} {certs_path}client.cert').status == 0
assert (
self.execute(f'ln -s /etc/pki/tls/certs/ca-bundle.crt {certs_path}ca-bundle.crt').status
== 0
)
def reset_podman_cert_auth(self, sat=None):
"""Reset podman cert-based authentication for given Satellite or for all"""
trail = sat.hostname if sat else '*'
self.execute(f'rm -rf {CONTAINER_CERTS_PATH}{trail}')
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, temp_file=False):
"""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 temp_file:
with NamedTemporaryFile(dir=robottelo_tmp_dir) as content_file:
content_file.write(str.encode(local_path))
content_file.flush()
self.session.sftp_write(source=content_file.name, destination=remote_path)
elif 'utils.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=str(local_path), destination=str(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 enable_rhsm_proxy(self, hostname, port=None):
"""Configures HTTP proxy for subscription manager"""
cmd = f"subscription-manager config --server.proxy_hostname={hostname}"
if port:
cmd += f' --server.proxy_port={port}'
logger.info(f'Configuring {hostname} HTTP proxy for subscription manager.')
self.execute(cmd)
def enable_dnf_proxy(self, hostname, scheme=None, port=None):
"""Configures HTTP proxy for dnf"""
if not scheme:
scheme = 'http'
cmd = f"echo -e 'proxy = {scheme}://{hostname}"
if port:
cmd += f':{port}'
if self.execute('test -f /etc/dnf/dnf.conf').status == 0:
cmd += "' >> /etc/dnf/dnf.conf"
else:
cmd += "' >> /etc/yum.conf"
logger.info(f'Configuring {hostname} HTTP proxy for dnf.')
self.execute(cmd)
def enable_ipv6_rhsm_proxy(self):
"""Execute procedures for enabling rhsm IPv6 HTTP Proxy"""
if not self.network_type.has_ipv4:
url = urlparse(settings.http_proxy.http_proxy_ipv6_url)
self.enable_rhsm_proxy(url.hostname, url.port)
def enable_ipv6_dnf_proxy(self):
"""Execute procedures for enabling dnf IPv6 HTTP Proxy"""
if not self.network_type.has_ipv4:
url = urlparse(settings.http_proxy.http_proxy_ipv6_url)
self.enable_dnf_proxy(url.hostname, url.scheme, url.port)
def enable_ipv6_system_proxy(self):
"""Execute procedures for enabling IPv6 HTTP Proxy on system"""
if not self.network_type.has_ipv4:
self.execute(
f'echo "export HTTPS_PROXY={settings.http_proxy.http_proxy_ipv6_url}" >> ~/.bashrc'
)
def enable_ipv6_podman_proxy(self):
"""Execute procedures for enabling IPv6 HTTP Proxy on Podman engine"""
if not self.network_type.has_ipv4:
container_cfg = '/etc/containers/containers.conf'
proxy_url = settings.http_proxy.http_proxy_ipv6_url
if self.execute(f'grep -q "https_proxy" {container_cfg}').status != 0:
proxy_env = (
'[engine]\\nenv = ['
f'\\"https_proxy={proxy_url}\\"]\\n'
'[containers]\\nhttp_proxy=false'
)
assert self.execute(f'echo -e "{proxy_env}" >> {container_cfg}').status == 0
def disable_rhsm_proxy(self):
"""Disables HTTP proxy for subscription manager"""
self.execute('subscription-manager remove server.proxy_hostname server.proxy_port')
def disable_dnf_proxy(self):
"""Disable HTTP proxy for dnf"""
self.execute('sed -i "/^proxy/d" /etc/dnf/dnf.conf')
def enable_ipv6_dnf_and_rhsm_proxy(self):
"""Execute procedures for enabling rhsm and dnf IPv6 HTTP Proxy"""
if not self.network_type.has_ipv4:
self.enable_ipv6_rhsm_proxy()
self.enable_ipv6_dnf_proxy()
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(f"grep -q '{key_content}' {auth_file} || echo '{key_content}' >> {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}'