How to use _dnf_tool method in lisa

Best Python code snippet using lisa_python

operating_system.py

Source:operating_system.py Github

copy

Full Screen

...955 if self._first_time_installation:956 self._initialize_package_installation()957 self._first_time_installation = False958 repo_list_str = self._node.execute(959 f"{self._dnf_tool()} repolist", sudo=True960 ).stdout.splitlines()961 # skip to the first entry in the output962 for index, repo_str in enumerate(repo_list_str):963 if repo_str.startswith("repo id"):964 header_index = index965 break966 repo_list_str = repo_list_str[header_index + 1 :]967 repositories: List[RepositoryInfo] = []968 for line in repo_list_str:969 repo_info = self._rpm_repository_info_pattern.search(line)970 if repo_info:971 repositories.append(972 RPMRepositoryInfo(973 name=repo_info.group("name"), id=repo_info.group("id").lower()974 )975 )976 return repositories977 def add_repository(978 self,979 repo: str,980 no_gpgcheck: bool = True,981 repo_name: Optional[str] = None,982 keys_location: Optional[List[str]] = None,983 ) -> None:984 self._node.tools[YumConfigManager].add_repository(repo, no_gpgcheck)985 def _get_package_information(self, package_name: str) -> VersionInfo:986 rpm_info = self._node.execute(987 f"rpm -q {package_name}",988 expected_exit_code=0,989 expected_exit_code_failure_message=(990 f"Could not find package information for package {package_name}"991 ),992 )993 # rpm package should be of format (package_name)-(version)994 matches = self._rpm_version_splitter_regex.search(rpm_info.stdout)995 if not matches:996 raise LisaException(997 f"Could not parse package version {rpm_info} for {package_name}"998 )999 self._node.log.debug(f"Attempting to parse version string: {rpm_info.stdout}")1000 version_info = self._get_version_info_from_named_regex_match(1001 package_name, matches1002 )1003 return self._cache_and_return_version_info(package_name, version_info)1004 def _install_packages(1005 self,1006 packages: List[str],1007 signed: bool = True,1008 timeout: int = 600,1009 extra_args: Optional[List[str]] = None,1010 ) -> None:1011 add_args = self._process_extra_package_args(extra_args)1012 command = f"{self._dnf_tool()} install {add_args} -y {' '.join(packages)}"1013 if not signed:1014 command += " --nogpgcheck"1015 self._node.execute(1016 command,1017 shell=True,1018 sudo=True,1019 timeout=timeout,1020 expected_exit_code=0,1021 expected_exit_code_failure_message=f"Failed to install {packages}.",1022 )1023 self._log.debug(f"{packages} is/are installed successfully.")1024 def _package_exists(self, package: str) -> bool:1025 command = f"{self._dnf_tool()} list installed {package}"1026 result = self._node.execute(command, sudo=True)1027 if result.exit_code == 0:1028 for row in result.stdout.splitlines():1029 if package in row:1030 return True1031 return False1032 def _is_package_in_repo(self, package: str) -> bool:1033 command = f"{self._dnf_tool()} list {package} -y"1034 result = self._node.execute(command, sudo=True, shell=True)1035 return 0 == result.exit_code1036 def _dnf_tool(self) -> str:1037 return "dnf"1038 def _update_packages(self, packages: Optional[List[str]] = None) -> None:1039 command = f"{self._dnf_tool()} -y --nogpgcheck update "1040 if packages:1041 command += " ".join(packages)1042 self._node.execute(command, sudo=True, timeout=3600)1043class Fedora(RPMDistro):1044 # Red Hat Enterprise Linux Server 7.8 (Maipo) => 7.81045 _fedora_release_pattern_version = re.compile(r"^.*release\s+([0-9\.]+).*$")1046 # 305.40.1.el8_4.x86_641047 # 240.el8.x86_641048 __kernel_version_parts_pattern = re.compile(1049 r"^(?P<part1>\d+)\.(?P<part2>\d+)?\.?(?P<part3>\d+)?\.?"1050 r"(?P<distro>.*?)\.(?P<platform>.*?)$"1051 )1052 @classmethod1053 def name_pattern(cls) -> Pattern[str]:1054 return re.compile("^Fedora|fedora$")1055 def get_kernel_information(self, force_run: bool = False) -> KernelInformation:1056 kernel_information = super().get_kernel_information(force_run)1057 # original parts: version_parts=['4', '18', '0', '305.40.1.el8_4.x86_64', '']1058 # target parts: version_parts=['4', '18', '0', '305', '40', '1', 'el8_4',1059 # 'x86_64']1060 groups = find_group_in_lines(1061 kernel_information.version_parts[3], self.__kernel_version_parts_pattern1062 )1063 new_parts = kernel_information.version_parts[:3]1064 # the default '1' is trying to build a meaningful Redhat version number.1065 new_parts.extend(1066 [1067 groups["part1"],1068 groups["part2"],1069 groups["part3"],1070 groups["distro"],1071 groups["platform"],1072 ]1073 )1074 for index, part in enumerate(new_parts):1075 if part is None:1076 new_parts[index] = ""1077 kernel_information.version_parts = new_parts1078 return kernel_information1079 def install_epel(self) -> None:1080 # Extra Packages for Enterprise Linux (EPEL) is a special interest group1081 # (SIG) from the Fedora Project that provides a set of additional packages1082 # for RHEL (and CentOS, and others) from the Fedora sources.1083 major = self._node.os.information.version.major1084 assert_that(major).described_as(1085 "Fedora/RedHat version must be greater than 7"1086 ).is_greater_than_or_equal_to(7)1087 epel_release_rpm_name = f"epel-release-latest-{major}.noarch.rpm"1088 self.install_packages(1089 f"https://dl.fedoraproject.org/pub/epel/{epel_release_rpm_name}"1090 )1091 # replace $releasever to 8 for 8.x1092 if major == 8:1093 sed = self._node.tools[Sed]1094 sed.substitute("$releasever", "8", "/etc/yum.repos.d/epel*.repo", sudo=True)1095 def _verify_package_result(self, result: ExecutableResult, packages: Any) -> None:1096 # yum returns exit_code=1 if DNF handled an error with installation.1097 # We do not want to fail if exit_code=1, but warn since something may1098 # potentially have gone wrong.1099 if result.exit_code == 1:1100 self._log.debug(f"DNF handled error with installation of {packages}")1101 elif result.exit_code == 0:1102 self._log.debug(f"{packages} is/are installed successfully.")1103 else:1104 raise LisaException(1105 f"Failed to install {packages}. exit_code: {result.exit_code}"1106 )1107 def group_install_packages(self, group_name: str) -> None:1108 # trigger to run _initialize_package_installation1109 self._get_package_list(group_name)1110 result = self._node.execute(f'yum -y groupinstall "{group_name}"', sudo=True)1111 self._verify_package_result(result, group_name)1112 def _get_information(self) -> OsInformation:1113 cmd_result = self._node.execute(1114 # Typical output of 'cat /etc/fedora-release' is -1115 # Fedora release 22 (Twenty Two)1116 cmd="cat /etc/fedora-release",1117 no_error_log=True,1118 expected_exit_code=0,1119 expected_exit_code_failure_message="error on get os information",1120 )1121 full_version = cmd_result.stdout1122 if "Fedora" not in full_version:1123 raise LisaException("OS version information not found")1124 vendor = "Fedora"1125 release = get_matched_str(full_version, self._fedora_release_pattern_version)1126 codename = get_matched_str(full_version, self._distro_codename_pattern)1127 information = OsInformation(1128 version=self._parse_version(release),1129 vendor=vendor,1130 release=release,1131 codename=codename,1132 full_version=full_version,1133 )1134 return information1135class Redhat(Fedora):1136 # Red Hat Enterprise Linux Server release 6.9 (Santiago)1137 # CentOS release 6.9 (Final)1138 # CentOS Linux release 8.3.20111139 __legacy_redhat_information_pattern = re.compile(1140 r"^(?P<vendor>.*?)?(?: Enterprise Linux Server)?(?: Linux)?"1141 r"(?: release)? (?P<version>[0-9\.]+)(?: \((?P<codename>.*).*\))?$"1142 )1143 # Oracle Linux Server1144 # Red Hat Enterprise Linux Server1145 # Red Hat Enterprise Linux1146 __vendor_pattern = re.compile(1147 r"^(?P<vendor>.*?)?(?: Enterprise)?(?: Linux)?(?: Server)?$"1148 )1149 @classmethod1150 def name_pattern(cls) -> Pattern[str]:1151 return re.compile("^rhel|Red|AlmaLinux|Rocky|Scientific|acronis|Actifio$")1152 def replace_boot_kernel(self, kernel_version: str) -> None:1153 # Redhat kernel is replaced when installing RPM. For source code1154 # installation, it's implemented in source code installer.1155 ...1156 def capture_system_information(self, saved_path: Path) -> None:1157 super().capture_system_information(saved_path)1158 self._node.shell.copy_back(1159 self._node.get_pure_path("/etc/redhat-release"),1160 saved_path / "redhat-release.txt",1161 )1162 @retry(tries=10, delay=5)1163 def _initialize_package_installation(self) -> None:1164 information = self._get_information()1165 # We may hit issue when run any yum command, caused by out of date1166 # rhui-microsoft-azure-rhel package.1167 # Use below command to update rhui-microsoft-azure-rhel package from microsoft1168 # repo to resolve the issue.1169 # Details please refer https://docs.microsoft.com/en-us/azure/virtual-machines/workloads/redhat/redhat-rhui#azure-rhui-infrastructure # noqa: E5011170 if "Red Hat" == information.vendor:1171 self._node.execute(1172 "yum update -y --disablerepo='*' --enablerepo='*microsoft*' ",1173 sudo=True,1174 expected_exit_code=0,1175 )1176 def _install_packages(1177 self,1178 packages: List[str],1179 signed: bool = True,1180 timeout: int = 600,1181 extra_args: Optional[List[str]] = None,1182 ) -> None:1183 add_args = self._process_extra_package_args(extra_args)1184 command = f"yum install {add_args} -y {' '.join(packages)}"1185 if not signed:1186 command += " --nogpgcheck"1187 install_result = self._node.execute(1188 command, shell=True, sudo=True, timeout=timeout1189 )1190 # RedHat will fail package installation is a single missing package is1191 # detected, therefore we check the output to see if we were missing1192 # a package. If so, fail. Otherwise we will warn in verify package result.1193 if install_result.exit_code == 1:1194 missing_packages = []1195 for line in install_result.stdout.splitlines():1196 if line.startswith("No match for argument:"):1197 package = line.split(":")[1].strip()1198 missing_packages.append(package)1199 if missing_packages:1200 raise MissingPackagesException(missing_packages)1201 super()._verify_package_result(install_result, packages)1202 def _package_exists(self, package: str) -> bool:1203 command = f"yum list installed {package}"1204 result = self._node.execute(command, sudo=True)1205 if result.exit_code == 0:1206 return True1207 return False1208 def _is_package_in_repo(self, package: str) -> bool:1209 command = f"yum --showduplicates list {package}"1210 result = self._node.execute(command, sudo=True, shell=True)1211 return 0 == result.exit_code1212 def _get_information(self) -> OsInformation:1213 # The higher version above 7.0 support os-version.1214 try:1215 information = super(Fedora, self)._get_information()1216 # remove Linux Server in vendor1217 information.vendor = get_matched_str(1218 information.vendor, self.__vendor_pattern1219 )1220 except Exception:1221 # Parse /etc/redhat-release to support 6.x and 8.x. Refer to1222 # examples of __legacy_redhat_information_pattern.1223 cmd_result = self._node.execute(1224 cmd="cat /etc/redhat-release", no_error_log=True, expected_exit_code=01225 )1226 full_version = cmd_result.stdout1227 matches = self.__legacy_redhat_information_pattern.match(full_version)1228 assert matches, f"cannot match version information from: {full_version}"1229 assert matches.group("vendor")1230 information = OsInformation(1231 version=self._parse_version(matches.group("version")),1232 vendor=matches.group("vendor"),1233 release=matches.group("version"),1234 codename=matches.group("codename"),1235 full_version=full_version,1236 )1237 return information1238 def _update_packages(self, packages: Optional[List[str]] = None) -> None:1239 command = "yum -y --nogpgcheck update "1240 if packages:1241 command += " ".join(packages)1242 # older images cost much longer time when update packages1243 # smaller sizes cost much longer time when update packages, e.g.1244 # Basic_A1, Standard_A5, Standard_A1_v2, Standard_D11245 # redhat rhel 7-lvm 7.7.2019102813 Basic_A1 cost 2371.568 seconds1246 # redhat rhel 8.1 8.1.2020020415 Basic_A0 cost 2409.116 seconds1247 self._node.execute(command, sudo=True, timeout=3600)1248 def _dnf_tool(self) -> str:1249 return "yum"1250class CentOs(Redhat):1251 @classmethod1252 def name_pattern(cls) -> Pattern[str]:1253 return re.compile("^CentOS|Centos|centos|clear-linux-os$")1254 def capture_system_information(self, saved_path: Path) -> None:1255 super(Linux, self).capture_system_information(saved_path)1256 self._node.shell.copy_back(1257 self._node.get_pure_path("/etc/centos-release"),1258 saved_path / "centos-release.txt",1259 )1260 def _initialize_package_installation(self) -> None:1261 information = self._get_information()1262 if 8 == information.version.major:1263 # refer https://www.centos.org/centos-linux-eol/ CentOS 8 is EOL,1264 # old repo mirror was moved to vault.centos.org1265 # CentOS-AppStream.repo, CentOS-Base.repo may contain non-existed1266 # repo use skip_if_unavailable to avoid installation issues brought1267 # in by above issue1268 cmd_results = self._node.execute("yum repolist -v", sudo=True)1269 if 0 != cmd_results.exit_code:1270 self._node.tools[YumConfigManager].set_opt("skip_if_unavailable=true")1271class Oracle(Redhat):1272 @classmethod1273 def name_pattern(cls) -> Pattern[str]:1274 # The name is "Oracle Linux Server", which doesn't support the default1275 # full match.1276 return re.compile("^Oracle")1277class CBLMariner(RPMDistro):1278 @classmethod1279 def name_pattern(cls) -> Pattern[str]:1280 return re.compile("^Common Base Linux Mariner|mariner$")1281 def __init__(self, node: Any) -> None:1282 super().__init__(node)1283 self._dnf_tool_name: str1284 def _initialize_package_installation(self) -> None:1285 result = self._node.execute("command -v dnf", no_info_log=True, shell=True)1286 if result.exit_code == 0:1287 self._dnf_tool_name = "dnf"1288 return1289 self._dnf_tool_name = "tdnf -q"1290 def _dnf_tool(self) -> str:1291 return self._dnf_tool_name1292@dataclass1293# `zypper lr` repolist is of the form1294# `<id>|<alias>|<name>|<enabled>|<gpg_check>|<refresh>`1295# Example:1296# # 4 | repo-oss | Main Repository | Yes | (r ) Yes | Yes1297class SuseRepositoryInfo(RepositoryInfo):1298 # id for the repository. Example: 41299 id: str1300 # alias for the repository. Example: repo-oss1301 alias: str1302 # is repository enabled. Example: True/False1303 enabled: bool1304 # is gpg_check enabled. Example: True/False...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run lisa automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful