Coverage for pyanaconda/core/util.py: 0%

# Coverage for pyanaconda/core/util.py : 0%

## 604 statements 0 run 604 missing 0 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 | # # util.py - generic install utility functions # # Copyright (C) 1999-2014 # Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import glob import os import stat import os.path import subprocess import unicodedata # Used for ascii_lowercase, ascii_uppercase constants import string # pylint: disable=deprecated-module import shutil import tempfile import re from urllib.parse import quote, unquote import gettext import signal import sys import imp import types import inspect import functools import requests from requests_file import FileAdapter from requests_ftp import FTPAdapter from pyanaconda.flags import flags from pyanaconda.core.process_watchers import WatchProcesses from pyanaconda.core.constants import DRACUT_SHUTDOWN_EJECT, TRANSLATIONS_UPDATE_DIR, \ UNSUPPORTED_HW, IPMI_ABORTED, X_TIMEOUT from pyanaconda.core.constants import SCREENSHOTS_DIRECTORY, SCREENSHOTS_TARGET_DIRECTORY from pyanaconda.core.regexes import URL_PARSE from pyanaconda.errors import RemovedModuleError, ExitError from pyanaconda.core.i18n import _ from pyanaconda.anaconda_logging import program_log_lock from pyanaconda.anaconda_loggers import get_module_logger, get_program_logger log = get_module_logger(__name__) program_log = get_program_logger() from pykickstart.constants import KS_SCRIPT_ONERROR _child_env = {} def setenv(name, value): """ Set an environment variable to be used by child processes. This method does not modify os.environ for the running process, which is not thread-safe. If setenv has already been called for a particular variable name, the old value is overwritten. :param str name: The name of the environment variable :param str value: The value of the environment variable """ _child_env[name] = value def augmentEnv(): env = os.environ.copy() env.update({"ANA_INSTALL_PATH": getSysroot()}) env.update(_child_env) return env _root_path = "/mnt/sysimage" def getTargetPhysicalRoot(): """Returns the path to the "physical" storage root, traditionally /mnt/sysimage. This may be distinct from the sysroot, which could be a chroot-type subdirectory of the physical root. This is used for example by all OSTree-based installations. """ # We always use the traditional /mnt/sysimage - the physical OS # target is never mounted anywhere else. This API call just # allows us to have a clean "git grep ROOT_PATH" in other parts of # the code. return _root_path def setTargetPhysicalRoot(path): """Change the physical root path :param string path: Path to use instead of /mnt/sysimage/ """ global _root_path _root_path = path _sysroot = _root_path def getSysroot(): """Returns the path to the target OS installation. For ordinary package-based installations, this is the same as the target root. """ return _sysroot def setSysroot(path): """Change the OS root path. :param path: The new OS root path This should only be used by Payload subclasses which install operating systems to non-default roots. """ global _sysroot _sysroot = path def startProgram(argv, root='/', stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env_prune=None, env_add=None, reset_handlers=True, reset_lang=True, **kwargs): """ Start an external program and return the Popen object. The root and reset_handlers arguments are handled by passing a preexec_fn argument to subprocess.Popen, but an additional preexec_fn can still be specified and will be run. The user preexec_fn will be run last. :param argv: The command to run and argument :param root: The directory to chroot to before running command. :param stdin: The file object to read stdin from. :param stdout: The file object to write stdout to. :param stderr: The file object to write stderr to. :param env_prune: environment variables to remove before execution :param env_add: environment variables to add before execution :param reset_handlers: whether to reset to SIG_DFL any signal handlers set to SIG_IGN :param reset_lang: whether to set the locale of the child process to C :param kwargs: Additional parameters to pass to subprocess.Popen :return: A Popen object for the running command. """ if env_prune is None: env_prune = [] # Transparently redirect callers requesting root=_root_path to the # configured system root. target_root = root if target_root == _root_path: target_root = getSysroot() # Check for and save a preexec_fn argument preexec_fn = kwargs.pop("preexec_fn", None) # Map reset_handlers to the restore_signals Popen argument. # restore_signals handles SIGPIPE, and preexec below handles any additional # signals ignored by anaconda. restore_signals = reset_handlers def preexec(): # If a target root was specificed, chroot into it if target_root and target_root != '/': os.chroot(target_root) os.chdir("/") # Signal handlers set to SIG_IGN persist across exec. Reset # these to SIG_DFL if requested. In particular this will include the # SIGPIPE handler set by python. if reset_handlers: for signum in range(1, signal.NSIG): if signal.getsignal(signum) == signal.SIG_IGN: signal.signal(signum, signal.SIG_DFL) # If the user specified an additional preexec_fn argument, run it if preexec_fn is not None: preexec_fn() with program_log_lock: if target_root != '/': program_log.info("Running in chroot '%s'... %s", target_root, " ".join(argv)) else: program_log.info("Running... %s", " ".join(argv)) env = augmentEnv() for var in env_prune: env.pop(var, None) if reset_lang: env.update({"LC_ALL": "C"}) if env_add: env.update(env_add) return subprocess.Popen(argv, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=True, restore_signals=restore_signals, preexec_fn=preexec, cwd=root, env=env, **kwargs) def startX(argv, output_redirect=None, timeout=X_TIMEOUT): """ Start X and return once X is ready to accept connections. X11, if SIGUSR1 is set to SIG_IGN, will send SIGUSR1 to the parent process once it is ready to accept client connections. This method sets that up and waits for the signal or bombs out if nothing happens for a minute. The process will also be added to the list of watched processes. :param argv: The command line to run, as a list :param output_redirect: file or file descriptor to redirect stdout and stderr to :param timeout: Number of seconds to timing out. """ # Use a list so the value can be modified from the handler function x11_started = [False] def sigusr1_handler(num, frame): log.debug("X server has signalled a successful start.") x11_started[0] = True # Fail after, let's say a minute, in case something weird happens # and we don't receive SIGUSR1 def sigalrm_handler(num, frame): # Check that it didn't make it under the wire if x11_started[0]: return log.error("Timeout trying to start %s", argv[0]) raise ExitError("Timeout trying to start %s" % argv[0]) # preexec_fn to add the SIGUSR1 handler in the child def sigusr1_preexec(): signal.signal(signal.SIGUSR1, signal.SIG_IGN) try: old_sigusr1_handler = signal.signal(signal.SIGUSR1, sigusr1_handler) old_sigalrm_handler = signal.signal(signal.SIGALRM, sigalrm_handler) # Start the timer log.debug("Setting timeout %s seconds for starting X.", timeout) signal.alarm(timeout) childproc = startProgram(argv, stdout=output_redirect, stderr=output_redirect, preexec_fn=sigusr1_preexec) WatchProcesses.watch_process(childproc, argv[0]) # Wait for SIGUSR1 while not x11_started[0]: signal.pause() finally: # Put everything back where it was signal.alarm(0) signal.signal(signal.SIGUSR1, old_sigusr1_handler) signal.signal(signal.SIGALRM, old_sigalrm_handler) def _run_program(argv, root='/', stdin=None, stdout=None, env_prune=None, log_output=True, binary_output=False, filter_stderr=False): """ Run an external program, log the output and return it to the caller NOTE/WARNING: UnicodeDecodeError will be raised if the output of the of the external command can't be decoded as UTF-8. :param argv: The command to run and argument :param root: The directory to chroot to before running command. :param stdin: The file object to read stdin from. :param stdout: Optional file object to write the output to. :param env_prune: environment variable to remove before execution :param log_output: whether to log the output of command :param binary_output: whether to treat the output of command as binary data :param filter_stderr: whether to exclude the contents of stderr from the returned output :return: The return code of the command and the output """ try: if filter_stderr: stderr = subprocess.PIPE else: stderr = subprocess.STDOUT proc = startProgram(argv, root=root, stdin=stdin, stdout=subprocess.PIPE, stderr=stderr, env_prune=env_prune) (output_string, err_string) = proc.communicate() if not binary_output: output_string = output_string.decode("utf-8") if output_string and output_string[-1] != "\n": output_string = output_string + "\n" if log_output: with program_log_lock: if binary_output: # try to decode as utf-8 and replace all undecodable data by # "safe" printable representations when logging binary output decoded_output_lines = output_string.decode("utf-8", "replace") else: # output_string should already be a Unicode string decoded_output_lines = output_string.splitlines(True) for line in decoded_output_lines: program_log.info(line.strip()) if stdout: stdout.write(output_string) # If stderr was filtered, log it separately if filter_stderr and err_string and log_output: # try to decode as utf-8 and replace all undecodable data by # "safe" printable representations when logging binary output decoded_err_string = err_string.decode("utf-8", "replace") err_lines = decoded_err_string.splitlines(True) with program_log_lock: for line in err_lines: program_log.info(line.strip()) except OSError as e: with program_log_lock: program_log.error("Error running %s: %s", argv[0], e.strerror) raise with program_log_lock: program_log.debug("Return code: %d", proc.returncode) return (proc.returncode, output_string) def execInSysroot(command, argv, stdin=None): """ Run an external program in the target root. :param command: The command to run :param argv: The argument list :param stdin: The file object to read stdin from. :return: The return code of the command """ return execWithRedirect(command, argv, stdin=stdin, root=getSysroot()) def execWithRedirect(command, argv, stdin=None, stdout=None, root='/', env_prune=None, log_output=True, binary_output=False): """ Run an external program and redirect the output to a file. :param command: The command to run :param argv: The argument list :param stdin: The file object to read stdin from. :param stdout: Optional file object to redirect stdout and stderr to. :param root: The directory to chroot to before running command. :param env_prune: environment variable to remove before execution :param log_output: whether to log the output of command :param binary_output: whether to treat the output of command as binary data :return: The return code of the command """ if flags.testing: log.info("not running command because we're testing: %s %s", command, " ".join(argv)) return 0 argv = [command] + argv return _run_program(argv, stdin=stdin, stdout=stdout, root=root, env_prune=env_prune, log_output=log_output, binary_output=binary_output)[0] def execWithCapture(command, argv, stdin=None, root='/', log_output=True, filter_stderr=False): """ Run an external program and capture standard out and err. :param command: The command to run :param argv: The argument list :param stdin: The file object to read stdin from. :param root: The directory to chroot to before running command. :param log_output: Whether to log the output of command :param filter_stderr: Whether stderr should be excluded from the returned output :return: The output of the command """ if flags.testing: log.info("not running command because we're testing: %s %s", command, " ".join(argv)) return "" argv = [command] + argv return _run_program(argv, stdin=stdin, root=root, log_output=log_output, filter_stderr=filter_stderr)[1] def execWithCaptureBinary(command, argv, stdin=None, root='/', log_output=False, filter_stderr=False): """ Run an external program and capture standard out and err as binary data. The binary data output is not logged by default but logging can be enabled. :param command: The command to run :param argv: The argument list :param stdin: The file object to read stdin from. :param root: The directory to chroot to before running command. :param log_output: Whether to log the binary output of the command :param filter_stderr: Whether stderr should be excluded from the returned output :return: The output of the command """ if flags.testing: log.info("not running command because we're testing: %s %s", command, " ".join(argv)) return "" argv = [command] + argv return _run_program(argv, stdin=stdin, root=root, log_output=log_output, filter_stderr=filter_stderr, binary_output=True)[1] def execReadlines(command, argv, stdin=None, root='/', env_prune=None, filter_stderr=False): """ Execute an external command and return the line output of the command in real-time. This method assumes that there is a reasonably low delay between the end of output and the process exiting. If the child process closes stdout and then keeps on truckin' there will be problems. NOTE/WARNING: UnicodeDecodeError will be raised if the output of the external command can't be decoded as UTF-8. :param command: The command to run :param argv: The argument list :param stdin: The file object to read stdin from. :param stdout: Optional file object to redirect stdout and stderr to. :param root: The directory to chroot to before running command. :param env_prune: environment variable to remove before execution :param filter_stderr: Whether stderr should be excluded from the returned output Output from the file is not logged to program.log This returns an iterator with the lines from the command until it has finished """ class ExecLineReader(object): """Iterator class for returning lines from a process and cleaning up the process when the output is no longer needed. """ def __init__(self, proc, argv): self._proc = proc self._argv = argv def __iter__(self): return self def __del__(self): # See if the process is still running if self._proc.poll() is None: # Stop the process and ignore any problems that might arise try: self._proc.terminate() except OSError: pass def __next__(self): # Read the next line, blocking if a line is not yet available line = self._proc.stdout.readline().decode("utf-8") if line == '': # Output finished, wait for the process to end self._proc.communicate() # Check for successful exit if self._proc.returncode < 0: raise OSError("process '%s' was killed by signal %s" % (self._argv, -self._proc.returncode)) elif self._proc.returncode > 0: raise OSError("process '%s' exited with status %s" % (self._argv, self._proc.returncode)) raise StopIteration return line.strip() argv = [command] + argv if filter_stderr: stderr = subprocess.DEVNULL else: stderr = subprocess.STDOUT try: proc = startProgram(argv, root=root, stdin=stdin, stderr=stderr, env_prune=env_prune, bufsize=1) except OSError as e: with program_log_lock: program_log.error("Error running %s: %s", argv[0], e.strerror) raise return ExecLineReader(proc, argv) ## Run a shell. def execConsole(): try: proc = startProgram(["/bin/sh"], stdout=None, stderr=None, reset_lang=False) proc.wait() except OSError as e: raise RuntimeError("Error running /bin/sh: " + e.strerror) def getDirSize(directory): """ Get the size of a directory and all its subdirectories. :param dir: The name of the directory to find the size of. :return: The size of the directory in kilobytes. """ def getSubdirSize(directory): # returns size in bytes try: mydev = os.lstat(directory)[stat.ST_DEV] except OSError as e: log.debug("failed to stat %s: %s", directory, e) return 0 try: dirlist = os.listdir(directory) except OSError as e: log.debug("failed to listdir %s: %s", directory, e) return 0 dsize = 0 for f in dirlist: curpath = '%s/%s' % (directory, f) try: sinfo = os.lstat(curpath) except OSError as e: log.debug("failed to stat %s/%s: %s", directory, f, e) continue if stat.S_ISDIR(sinfo[stat.ST_MODE]): if os.path.ismount(curpath): continue if mydev == sinfo[stat.ST_DEV]: dsize += getSubdirSize(curpath) elif stat.S_ISREG(sinfo[stat.ST_MODE]): dsize += sinfo[stat.ST_SIZE] return dsize return getSubdirSize(directory) // 1024 ## Create a directory path. Don't fail if the directory already exists. def mkdirChain(directory): """ Make a directory and all of its parents. Don't fail if part or of it already exists. :param str directory: The directory path to create """ os.makedirs(directory, 0o755, exist_ok=True) def get_active_console(dev="console"): '''Find the active console device. Some tty devices (/dev/console, /dev/tty0) aren't actual devices; they just redirect input and output to the real console device(s). These 'fake' ttys have an 'active' sysfs attribute, which lists the real console device(s). (If there's more than one, the *last* one in the list is the primary console.) ''' # If there's an 'active' attribute, this is a fake console.. while os.path.exists("/sys/class/tty/%s/active" % dev): # So read the name of the real, primary console out of the file. console_path = "/sys/class/tty/%s/active" % dev active = open(console_path, "rt").read() if active.split(): # the active attribute seems to be pointing to another console dev = active.split()[-1] else: # At least some consoles on PPC have the "active" attribute, but it is empty. # (see rhbz#1569045 for more details) log.warning("%s is empty while console name is expected", console_path) # We can't continue to a next console if active is empty, so set dev to "" # and break the search loop. dev = "" break return dev def isConsoleOnVirtualTerminal(dev="console"): console = get_active_console(dev) # e.g. 'tty1', 'ttyS0', 'hvc1' consoletype = console.rstrip('0123456789') # remove the number return consoletype == 'tty' def reIPL(ipldev): try: rc = execWithRedirect("chreipl", ["node", "/dev/" + ipldev]) except RuntimeError as e: rc = True log.info("Unable to set reIPL device to %s: %s", ipldev, e) if rc: log.info("reIPL configuration failed") else: log.info("reIPL configuration successful") def resetRpmDb(): for rpmfile in glob.glob("%s/var/lib/rpm/__db.*" % getSysroot()): try: os.unlink(rpmfile) except OSError as e: log.debug("error %s removing file: %s", e, rpmfile) def parseNfsUrl(nfsurl): options = '' host = '' path = '' if nfsurl: s = nfsurl.split(":") s.pop(0) if len(s) >= 3: (options, host, path) = s[:3] elif len(s) == 2: (host, path) = s else: host = s[0] return (options, host, path) def add_po_path(directory): """ Looks to see what translations are under a given path and tells the gettext module to use that path as the base dir """ for d in os.listdir(directory): if not os.path.isdir("%s/%s" % (directory, d)): continue if not os.path.exists("%s/%s/LC_MESSAGES" % (directory, d)): continue for basename in os.listdir("%s/%s/LC_MESSAGES" % (directory, d)): if not basename.endswith(".mo"): continue log.info("setting %s as translation source for %s", directory, basename[:-3]) gettext.bindtextdomain(basename[:-3], directory) def setup_translations(): if os.path.isdir(TRANSLATIONS_UPDATE_DIR): add_po_path(TRANSLATIONS_UPDATE_DIR) gettext.textdomain("anaconda") def _run_systemctl(command, service, root="/"): """ Runs 'systemctl command service.service' :return: exit status of the systemctl """ args = [command, service] if root != "/": args += ["--root", root] ret = execWithRedirect("systemctl", args) return ret def start_service(service): return _run_systemctl("start", service) def stop_service(service): return _run_systemctl("stop", service) def restart_service(service): return _run_systemctl("restart", service) def service_running(service): ret = _run_systemctl("status", service) return ret == 0 def enable_service(service): """ Enable a systemd service in the sysroot """ ret = _run_systemctl("enable", service, root=getSysroot()) if ret != 0: raise ValueError("Error enabling service %s: %s" % (service, ret)) def disable_service(service): """ Disable a systemd service in the sysroot """ # we ignore the error so we can disable services even if they don't # exist, because that's effectively disabled ret = _run_systemctl("disable", service, root=getSysroot()) if ret != 0: log.warning("Disabling %s failed. It probably doesn't exist", service) def dracut_eject(device): """ Use dracut shutdown hook to eject media after the system is shutdown. This is needed because we are running from the squashfs.img on the media so ejecting too early will crash the installer. """ if not device: return try: if not os.path.exists(DRACUT_SHUTDOWN_EJECT): mkdirChain(os.path.dirname(DRACUT_SHUTDOWN_EJECT)) f = open_with_perm(DRACUT_SHUTDOWN_EJECT, "w", 0o755) f.write("#!/bin/sh\n") f.write("# Created by Anaconda\n") else: f = open(DRACUT_SHUTDOWN_EJECT, "a") f.write("eject %s\n" % (device,)) f.close() log.info("Wrote dracut shutdown eject hook for %s", device) except (IOError, OSError) as e: log.error("Error writing dracut shutdown eject hook for %s: %s", device, e) def vtActivate(num): """ Try to switch to tty number $num. :type num: int :return: whether the switch was successful or not :rtype: bool """ try: ret = execWithRedirect("chvt", [str(num)]) except OSError as oserr: ret = -1 log.error("Failed to run chvt: %s", oserr.strerror) if ret != 0: log.error("Failed to switch to tty%d", num) return ret == 0 class ProxyStringError(Exception): pass class ProxyString(object): """ Handle a proxy url """ def __init__(self, url=None, protocol="http://", host=None, port="3128", username=None, password=None): """ Initialize with either url ([protocol://][username[:password]@]host[:port]) or pass host and optionally: protocol http, https, ftp host hostname without protocol port port number (defaults to 3128) username username password password The str() of the object is the full proxy url ProxyString.url is the full url including username:password@ ProxyString.noauth_url is the url without username:password@ """ self.url = ensure_str(url, keep_none=True) self.protocol = ensure_str(protocol, keep_none=True) self.host = ensure_str(host, keep_none=True) self.port = str(port) self.username = ensure_str(username, keep_none=True) self.password = ensure_str(password, keep_none=True) self.proxy_auth = "" self.noauth_url = None if url: self.parse_url() elif not host: raise ProxyStringError(_("No host url")) else: self.parse_components() def parse_url(self): """ Parse the proxy url into its component pieces """ # NOTE: If this changes, update tests/regex/proxy.py # # proxy=[protocol://][username[:password]@]host[:port][path][?query][#fragment] # groups (both named and numbered) # 1 = protocol # 2 = username # 3 = password # 4 = host # 5 = port # 6 = path # 7 = query # 8 = fragment m = URL_PARSE.match(self.url) if not m: raise ProxyStringError(_("malformed URL, cannot parse it.")) # If no protocol was given default to http. self.protocol = m.group("protocol") or "http://" if m.group("username"): self.username = ensure_str(unquote(m.group("username"))) if m.group("password"): self.password = ensure_str(unquote(m.group("password"))) if m.group("host"): self.host = m.group("host") if m.group("port"): self.port = m.group("port") else: raise ProxyStringError(_("URL has no host component")) self.parse_components() def parse_components(self): """ Parse the components of a proxy url into url and noauth_url """ if self.username or self.password: self.proxy_auth = "%s:%s@" % (quote(self.username or ""), quote(self.password or "")) self.url = self.protocol + self.proxy_auth + self.host + ":" + self.port self.noauth_url = self.protocol + self.host + ":" + self.port def __str__(self): return self.url def strip_accents(s): """This function takes arbitrary unicode string and returns it with all the diacritics removed. :param s: arbitrary string :type s: str :return: s with diacritics removed :rtype: str """ return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') def cmp_obj_attrs(obj1, obj2, attr_list): """ Compare attributes of 2 objects for changes Missing attrs are considered a mismatch :param obj1: First object to compare :type obj1: Any object :param obj2: Second object to compare :type obj2: Any object :param attr_list: List of attributes to compare :type attr_list: list or tuple of strings :returns: True if the attrs all match :rtype: bool """ for attr in attr_list: if hasattr(obj1, attr) and hasattr(obj2, attr): if getattr(obj1, attr) != getattr(obj2, attr): return False else: return False return True def dir_tree_map(root, func, files=True, dirs=True): """ Apply the given function to all files and directories in the directory tree under the given root directory. :param root: root of the directory tree the function should be mapped to :type root: str :param func: a function taking the directory/file path :type func: path -> None :param files: whether to apply the function to the files in the dir. tree :type files: bool :param dirs: whether to apply the function to the directories in the dir. tree :type dirs: bool TODO: allow using globs and thus more trees? """ for (dir_ent, _dir_items, file_items) in os.walk(root): if dirs: # try to call the function on the directory entry try: func(dir_ent) except OSError: pass if files: # try to call the function on the files in the directory entry for file_ent in (os.path.join(dir_ent, f) for f in file_items): try: func(file_ent) except OSError: pass # directories under the directory entry will appear as directory entries # in the loop def chown_dir_tree(root, uid, gid, from_uid_only=None, from_gid_only=None): """ Change owner (uid and gid) of the files and directories under the given directory tree (recursively). :param root: root of the directory tree that should be chown'ed :type root: str :param uid: UID that should be set as the owner :type uid: int :param gid: GID that should be set as the owner :type gid: int :param from_uid_only: if given, the owner is changed only for the files and directories owned by that UID :type from_uid_only: int or None :param from_gid_only: if given, the owner is changed only for the files and directories owned by that GID :type from_gid_only: int or None """ def conditional_chown(path, uid, gid, from_uid=None, from_gid=None): stats = os.stat(path) if (from_uid and stats.st_uid != from_uid) or \ (from_gid and stats.st_gid != from_gid): # owner UID or GID not matching, do nothing return # UID and GID matching or not required os.chown(path, uid, gid) if not from_uid_only and not from_gid_only: # the easy way dir_tree_map(root, lambda path: os.chown(path, uid, gid)) else: # conditional chown dir_tree_map(root, lambda path: conditional_chown(path, uid, gid, from_uid_only, from_gid_only)) def is_unsupported_hw(): """ Check to see if the hardware is supported or not. :returns: ``True`` if this is unsupported hardware, ``False`` otherwise :rtype: bool """ try: tainted = int(open("/proc/sys/kernel/tainted").read()) except (IOError, ValueError): tainted = 0 status = bool(tainted & UNSUPPORTED_HW) if status: log.debug("Installing on Unsupported Hardware") return status def ensure_str(str_or_bytes, keep_none=True): """ Returns a str instance for given string or ``None`` if requested to keep it. :param str_or_bytes: string to be kept or converted to str type :type str_or_bytes: str or bytes :param bool keep_none: whether to keep None as it is or raise ValueError if ``None`` is passed :raises ValueError: if applied on an object not being of type bytes nor str (nor NoneType if ``keep_none`` is ``False``) """ if keep_none and str_or_bytes is None: return None elif isinstance(str_or_bytes, str): return str_or_bytes elif isinstance(str_or_bytes, bytes): return str_or_bytes.decode(sys.getdefaultencoding()) else: raise ValueError("str_or_bytes must be of type 'str' or 'bytes', not '%s'" % type(str_or_bytes)) # Define translations between ASCII uppercase and lowercase for # locale-independent string conversions. The tables are 256-byte string used # with str.translate. If str.translate is used with a unicode string, # even if the string contains only 7-bit characters, str.translate will # raise a UnicodeDecodeError. _ASCIIlower_table = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) _ASCIIupper_table = str.maketrans(string.ascii_lowercase, string.ascii_uppercase) def _toASCII(s): """Convert a unicode string to ASCII""" if isinstance(s, str): # Decompose the string using the NFK decomposition, which in addition # to the canonical decomposition replaces characters based on # compatibility equivalence (e.g., ROMAN NUMERAL ONE has its own code # point but it's really just a capital I), so that we can keep as much # of the ASCII part of the string as possible. s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode("ascii") elif not isinstance(s, bytes): s = '' return s def upperASCII(s): """Convert a string to uppercase using only ASCII character definitions. The returned string will contain only ASCII characters. This function is locale-independent. """ # XXX: Python 3 has str.maketrans() and bytes.maketrans() so we should # ideally use one or the other depending on the type of 's'. But it turns # out we expect this function to always return string even if given bytes. s = ensure_str(s) return str.translate(_toASCII(s), _ASCIIupper_table) def lowerASCII(s): """Convert a string to lowercase using only ASCII character definitions. The returned string will contain only ASCII characters. This function is locale-independent. """ # XXX: Python 3 has str.maketrans() and bytes.maketrans() so we should # ideally use one or the other depending on the type of 's'. But it turns # out we expect this function to always return string even if given bytes. s = ensure_str(s) return str.translate(_toASCII(s), _ASCIIlower_table) def upcase_first_letter(text): """ Helper function that upcases the first letter of the string. Python's standard string.capitalize() not only upcases the first letter but also lowercases all the others. string.title() capitalizes all words in the string. :type text: str :return: the given text with the first letter upcased :rtype: str """ if not text: # cannot change anything return text elif len(text) == 1: return text.upper() else: return text[0].upper() + text[1:] def get_mount_paths(devnode): '''given a device node, return a list of all active mountpoints.''' devno = os.stat(devnode).st_rdev majmin = "%d:%d" % (os.major(devno), os.minor(devno)) mountinfo = (line.split() for line in open("/proc/self/mountinfo")) return [info[4] for info in mountinfo if info[2] == majmin] def have_word_match(str1, str2): """Tells if all words from str1 exist in str2 or not.""" if str1 is None or str2 is None: # None never matches return False if str1 == "": # empty string matches everything except from None return True elif str2 == "": # non-empty string cannot be found in an empty string return False # Convert both arguments to string if not already str1 = ensure_str(str1) str2 = ensure_str(str2) str1 = str1.lower() str1_words = str1.split() str2 = str2.lower() return all(word in str2 for word in str1_words) def xprogressive_delay(): """ A delay generator, the delay starts short and gets longer as the internal counter increases. For example for 10 retries, the delay will increases from 0.5 to 256 seconds. :param int retry_number: retry counter :returns float: time to wait in seconds """ counter = 1 while True: yield 0.25 * (2 ** counter) counter += 1 def get_platform_groupid(): """ Return a platform group id string This runs systemd-detect-virt and if the result is not 'none' it prefixes the lower case result with "platform-" for use as a group id. :returns: Empty string or a group id for the detected platform :rtype: str """ try: platform = execWithCapture("systemd-detect-virt", []).strip() except (IOError, AttributeError): return "" if platform == "none": return "" return "platform-" + platform.lower() def persistent_root_image(): """:returns: whether we are running from a persistent (not in RAM) root.img""" for line in execReadlines("losetup", ["--list"]): # if there is an active loop device for a curl-fetched file that has # been deleted, it means we run from a non-persistent root image # EXAMPLE line: # /dev/loop0 0 0 0 1 /tmp/curl_fetch_url0/my_comps_squashfs.img (deleted) if re.match(r'.*curl_fetch_url.*\(deleted\)\s*$', line): return False return True _supports_ipmi = None def ipmi_report(event): global _supports_ipmi if _supports_ipmi is None: _supports_ipmi = os.path.exists("/dev/ipmi0") and os.path.exists("/usr/bin/ipmitool") if not _supports_ipmi: return (fd, path) = tempfile.mkstemp() # EVM revision - always 0x4 # Sensor type - always 0x1F for Base OS Boot/Installation Status # Sensor num - always 0x0 for us # Event dir & type - always 0x6f for us # Event data 1 - the event code passed in # Event data 2 & 3 - always 0x0 for us event_string = "0x4 0x1F 0x0 0x6f %#x 0x0 0x0\n" % event os.write(fd, event_string.encode("utf-8")) os.close(fd) execWithCapture("ipmitool", ["event", "file", path]) os.remove(path) def ipmi_abort(scripts=None): ipmi_report(IPMI_ABORTED) runOnErrorScripts(scripts) def runOnErrorScripts(scripts): if not scripts: return log.info("Running kickstart %%onerror script(s)") for script in filter(lambda s: s.type == KS_SCRIPT_ONERROR, scripts): script.run("/") log.info("All kickstart %%onerror script(s) have been run") def parent_dir(directory): """Return the parent's path""" return "/".join(os.path.normpath(directory).split("/")[:-1]) def requests_session(): """Return a requests.Session object with file and ftp support.""" session = requests.Session() session.mount("file://", FileAdapter()) session.mount("ftp://", FTPAdapter()) return session def open_with_perm(path, mode='r', perm=0o777, **kwargs): """Open a file with the given permission bits. This is more or less the same as using os.open(path, flags, perm), but with the builtin open() semantics and return type instead of a file descriptor. :param str path: The path of the file to be opened :param str mode: The same thing as the mode argument to open() :param int perm: What permission bits to use if creating a new file """ def _opener(path, open_flags): return os.open(path, open_flags, perm) return open(path, mode, opener=_opener, **kwargs) def id_generator(): """ Id numbers generator. Generating numbers from 0 to X and increments after every call. :returns: Generator which gives you unique numbers. """ actual_id = 0 while(True): yield actual_id actual_id += 1 def sysroot_path(path): """Make the given relative or absolute path "sysrooted" :param str path: path to be sysrooted :returns: sysrooted path :rtype: str """ return os.path.join(getSysroot(), path.lstrip(os.path.sep)) def save_screenshots(): """Save screenshots to the installed system""" if not os.path.exists(SCREENSHOTS_DIRECTORY): # there are no screenshots to copy return target_path = sysroot_path(SCREENSHOTS_TARGET_DIRECTORY) log.info("saving screenshots taken during the installation to: %s", target_path) try: # create the screenshots directory mkdirChain(target_path) # copy all screenshots for filename in os.listdir(SCREENSHOTS_DIRECTORY): shutil.copy(os.path.join(SCREENSHOTS_DIRECTORY, filename), target_path) except OSError: log.exception("saving screenshots to installed system failed") def touch(file_path): """Create an empty file.""" # this misrrors how touch works - it does not # throw an error if the given path exists, # even when the path points to dirrectory if not os.path.exists(file_path): os.mknod(file_path) def collect(module_pattern, path, pred): """Traverse the directory (given by path), import all files as a module module_pattern % filename and find all classes within that match the given predicate. This is then returned as a list of classes. It is suggested you use collect_categories or collect_spokes instead of this lower-level method. :param module_pattern: the full name pattern (pyanaconda.ui.gui.spokes.%s) we want to assign to imported modules :type module_pattern: string :param path: the directory we are picking up modules from :type path: string :param pred: function which marks classes as good to import :type pred: function with one argument returning True or False """ retval = [] try: contents = os.listdir(path) # when the directory "path" does not exist except OSError: return [] for module_file in contents: if (not module_file.endswith(".py")) and \ (not module_file.endswith(".so")): continue if module_file == "__init__.py": continue try: mod_name = module_file[:module_file.rindex(".")] except ValueError: mod_name = module_file mod_info = None module = None module_path = None try: imp.acquire_lock() (fo, module_path, module_flags) = imp.find_module(mod_name, [path]) module = sys.modules.get(module_pattern % mod_name) # do not load module if any module with the same name # is already imported if not module: # try importing the module the standard way first # uses sys.path and the module's full name! try: __import__(module_pattern % mod_name) module = sys.modules[module_pattern % mod_name] # if it fails (package-less addon?) try importing single file # and filling up the package structure voids except ImportError: # prepare dummy modules to prevent RuntimeWarnings module_parts = (module_pattern % mod_name).split(".") # remove the last name as it will be inserted by the import module_parts.pop() # make sure all "parent" modules are in sys.modules for l in range(len(module_parts)): module_part_name = ".".join(module_parts[:l + 1]) if module_part_name not in sys.modules: module_part = types.ModuleType(module_part_name) module_part.__path__ = [path] sys.modules[module_part_name] = module_part # load the collected module module = imp.load_module(module_pattern % mod_name, fo, module_path, module_flags) # get the filenames without the extensions so we can compare those # with the .py[co]? equivalence in mind # - we do not have to care about files without extension as the # condition at the beginning of the for loop filters out those # - module_flags[0] contains the extension of the module imp found candidate_name = module_path[:module_path.rindex(module_flags[0])] loaded_name, loaded_ext = module.__file__.rsplit(".", 1) # restore the extension dot eaten by split loaded_ext = "." + loaded_ext # do not collect classes when the module is already imported # from different path than we are traversing # this condition checks the module name without file extension if candidate_name != loaded_name: continue # if the candidate file is .py[co]? and the loaded is not (.so) # skip the file as well if module_flags[0].startswith(".py") and not loaded_ext.startswith(".py"): continue # if the candidate file is not .py[co]? and the loaded is # skip the file as well if not module_flags[0].startswith(".py") and loaded_ext.startswith(".py"): continue except RemovedModuleError: # collected some removed module continue except ImportError as imperr: # pylint: disable=unsupported-membership-test if module_path and "pyanaconda" in module_path: # failure when importing our own module: raise log.error("Failed to import module %s from path %s in collect: %s", mod_name, module_path, imperr) continue finally: imp.release_lock() if mod_info and mod_info[0]: # pylint: disable=unsubscriptable-object mod_info[0].close() # pylint: disable=unsubscriptable-object p = lambda obj: inspect.isclass(obj) and pred(obj) # if __all__ is defined in the module, use it if not hasattr(module, "__all__"): members = inspect.getmembers(module, p) else: members = [(name, getattr(module, name)) for name in module.__all__ if p(getattr(module, name))] for (_name, val) in members: retval.append(val) return retval def item_counter(item_count): """A generator for easy counting of items. :param int item_count: number of items The general idea is to initialize the generator with the number of items and then activating it every time an item is being processed. The generator produces strings in the <index>/<item count> format, for example: 1/20 2/20 3/20 And so on. Such strings can be easily used to add a current/total counter to log messages when tasks and task queues are processed. """ if item_count < 0: raise ValueError("Item count can't be negative.") index = 1 while index <= item_count: yield "%d/%d" % (index, item_count) index += 1 def synchronized(wrapped): """A locking decorator for methods. The decorator is only intended for methods and the class providing the method also needs to have a Lock/RLock instantiated in self._lock. The decorator prevents the wrapped method from being executed until self._lock can be acquired. Once available, it acquires the lock and prevents other decorated methods & other users of self._lock from executing until the wrapped method finishes running. """ @functools.wraps(wrapped) def _wrapper(self, *args, **kwargs): with self._lock: return wrapped(self, *args, **kwargs) return _wrapper