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
|
# Copyright (C) 2006 Steve Conklin <sconklin@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.
import sys
import traceback
import os
import errno
import logging
from datetime import datetime
import glob
import sos.report.plugins
from sos.utilities import ImporterHelper, SoSTimeoutError
from shutil import rmtree
import hashlib
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import pdb
from sos import _sos as _
from sos import __version__
from sos.component import SoSComponent
import sos.policies
from sos.report.reporting import (Report, Section, Command, CopiedFile,
CreatedFile, Alert, Note, PlainTextReport,
JSONReport, HTMLReport)
from sos.cleaner import SoSCleaner
# file system errors that should terminate a run
fatal_fs_errors = (errno.ENOSPC, errno.EROFS)
def _format_list(first_line, items, indent=False, sep=", "):
lines = []
line = first_line
if indent:
newline = len(first_line) * ' '
else:
newline = ""
for item in items:
if len(line) + len(item) + len(sep) > 72:
lines.append(line)
line = newline
line = line + item + sep
if line[-len(sep):] == sep:
line = line[:-len(sep)]
lines.append(line)
return lines
def _format_since(date):
""" This function will format --since arg to append 0s if enduser
didn't. It's used in the _get_parser.
This will also be a good place to add human readable and relative
date parsing (like '2 days ago') in the future """
return datetime.strptime('{:<014s}'.format(date), '%Y%m%d%H%M%S')
# valid modes for --chroot
chroot_modes = ["auto", "always", "never"]
class SoSReport(SoSComponent):
"""Run a set of commands and file collections and save them to a report for
future analysis
"""
desc = "Collect files and command output in an archive"
root_required = True
arg_defaults = {
'alloptions': False,
'all_logs': False,
'build': False,
'case_id': '',
'chroot': 'auto',
'clean': False,
'desc': '',
'domains': [],
'dry_run': False,
'experimental': False,
'enable_plugins': [],
'keywords': [],
'plugopts': [],
'label': '',
'list_plugins': False,
'list_presets': False,
'list_profiles': False,
'log_size': 25,
'map_file': '/etc/sos/cleaner/default_mapping',
'skip_plugins': [],
'noreport': False,
'no_env_vars': False,
'no_postproc': False,
'no_update': False,
'note': '',
'only_plugins': [],
'preset': 'auto',
'plugin_timeout': 300,
'profiles': [],
'since': None,
'verify': False,
'allow_system_changes': False,
'upload': False,
'upload_url': None,
'upload_directory': None,
'upload_user': None,
'upload_pass': None,
'add_preset': '',
'del_preset': ''
}
def __init__(self, parser, args, cmdline):
super(SoSReport, self).__init__(parser, args, cmdline)
self.loaded_plugins = []
self.skipped_plugins = []
self.all_options = []
self.env_vars = set()
self.archive = None
self._args = args
self.sysroot = "/"
self.preset = None
self.print_header()
self._set_debug()
self._is_root = self.policy.is_root()
# add a manifest section for report
self.report_md = self.manifest.components.add_section('report')
# user specified command line preset
if self.opts.preset != self.arg_defaults["preset"]:
self.preset = self.policy.find_preset(self.opts.preset)
if not self.preset:
sys.stderr.write("Unknown preset: '%s'\n" % self.opts.preset)
self.preset = self.policy.probe_preset()
self.opts.list_presets = True
# --preset=auto
if not self.preset:
self.preset = self.policy.probe_preset()
# now merge preset options to self.opts
self.opts.merge(self.preset.opts)
# re-apply any cmdline overrides to the preset
self.opts = self.apply_options_from_cmdline(self.opts)
self._set_directories()
msg = "default"
host_sysroot = self.policy.host_sysroot()
# set alternate system root directory
if self.opts.sysroot:
msg = "cmdline"
self.sysroot = self.opts.sysroot
elif self.policy.in_container() and host_sysroot != os.sep:
msg = "policy"
self.sysroot = host_sysroot
self.soslog.debug("set sysroot to '%s' (%s)" % (self.sysroot, msg))
if self.opts.chroot not in chroot_modes:
self.soslog.error("invalid chroot mode: %s" % self.opts.chroot)
logging.shutdown()
self.tempfile_util.clean()
self._exit(1)
self._get_hardware_devices()
@classmethod
def add_parser_options(cls, parser):
report_grp = parser.add_argument_group(
'Report Options',
'These options control how report collects data'
)
report_grp.add_argument("-a", "--alloptions", action="store_true",
dest="alloptions", default=False,
help="enable all options for loaded plugins")
report_grp.add_argument("--all-logs", action="store_true",
dest="all_logs", default=False,
help="collect all available logs regardless "
"of size")
report_grp.add_argument("--since", action="store",
dest="since", default=None, type=_format_since,
help="Escapes archived files older than date. "
"This will also affect --all-logs. "
"Format: YYYYMMDD[HHMMSS]")
report_grp.add_argument("--build", action="store_true",
dest="build", default=False,
help="preserve the temporary directory and do "
"not package results")
report_grp.add_argument("--case-id", action="store", dest="case_id",
help="specify case identifier")
report_grp.add_argument("-c", "--chroot", action="store",
dest="chroot", default='auto',
help="chroot executed commands to SYSROOT "
"[auto, always, never] (default=auto)")
report_grp.add_argument("--desc", "--description", type=str,
action="store", default="",
help="Description for a new preset",)
report_grp.add_argument("--dry-run", action="store_true",
help="Run plugins but do not collect data")
report_grp.add_argument("--experimental", action="store_true",
dest="experimental", default=False,
help="enable experimental plugins")
report_grp.add_argument("-e", "--enable-plugins", action="extend",
dest="enable_plugins", type=str,
help="enable these plugins", default=[])
report_grp.add_argument("-k", "--plugin-option", action="extend",
dest="plugopts", type=str,
help="plugin options in plugname.option=value "
"format (see -l)", default=[])
report_grp.add_argument("--label", "--name", action="store",
dest="label",
help="specify an additional report label")
report_grp.add_argument("-l", "--list-plugins", action="store_true",
dest="list_plugins", default=False,
help="list plugins and available plugin "
"options")
report_grp.add_argument("--list-presets", action="store_true",
help="display a list of available presets")
report_grp.add_argument("--list-profiles", action="store_true",
dest="list_profiles", default=False,
help="display a list of available profiles and"
" plugins that they include")
report_grp.add_argument("--log-size", action="store", dest="log_size",
type=int, default=25,
help="limit the size of collected logs "
"(in MiB)")
report_grp.add_argument("-n", "--skip-plugins", action="extend",
dest="skip_plugins", type=str,
help="disable these plugins", default=[])
report_grp.add_argument("--no-report", action="store_true",
dest="noreport", default=False,
help="disable plaintext/HTML reporting")
report_grp.add_argument("--no-env-vars", action="store_true",
dest="no_env_vars", default=False,
help="Do not collect environment variables")
report_grp.add_argument("--no-postproc", default=False,
dest="no_postproc", action="store_true",
help="Disable all post-processing")
report_grp.add_argument("--note", type=str, action="store", default="",
help="Behaviour notes for new preset")
report_grp.add_argument("-o", "--only-plugins", action="extend",
dest="only_plugins", type=str,
help="enable these plugins only", default=[])
report_grp.add_argument("--preset", action="store", type=str,
help="A preset identifier", default="auto")
report_grp.add_argument("--plugin-timeout", default=None,
help="set a timeout for all plugins")
report_grp.add_argument("-p", "--profile", action="extend",
dest="profiles", type=str, default=[],
help="enable plugins used by the given "
"profiles")
report_grp.add_argument("--verify", action="store_true",
dest="verify", default=False,
help="perform data verification during "
"collection")
report_grp.add_argument("--allow-system-changes", action="store_true",
dest="allow_system_changes", default=False,
help="Run commands even if they can change the"
" system (e.g. load kernel modules)")
report_grp.add_argument("--upload", action="store_true", default=False,
help="Upload archive to a policy-default "
"location")
report_grp.add_argument("--upload-url", default=None,
help="Upload the archive to specified server")
report_grp.add_argument("--upload-directory", default=None,
help="Specify upload directory for archive")
report_grp.add_argument("--upload-user", default=None,
help="Username to authenticate to server with")
report_grp.add_argument("--upload-pass", default=None,
help="Password to authenticate to server with")
# Group to make add/del preset exclusive
preset_grp = report_grp.add_mutually_exclusive_group()
preset_grp.add_argument("--add-preset", type=str, action="store",
help="Add a new named command line preset")
preset_grp.add_argument("--del-preset", type=str, action="store",
help="Delete the named command line preset")
# Group the cleaner options together
cleaner_grp = parser.add_argument_group(
'Cleaner/Masking Options',
'These options control how data obfuscation is performed'
)
cleaner_grp.add_argument('--clean', '--mask', dest='clean',
default=False, action='store_true',
help='Obfuscate sensistive information')
cleaner_grp.add_argument('--domains', dest='domains', default=[],
action='extend',
help='Additional domain names to obfuscate')
cleaner_grp.add_argument('--keywords', action='extend', default=[],
dest='keywords',
help='List of keywords to obfuscate')
cleaner_grp.add_argument('--no-update', action='store_true',
default=False, dest='no_update',
help='Do not update the default cleaner map')
cleaner_grp.add_argument('--map', dest='map_file',
default='/etc/sos/cleaner/default_mapping',
help=('Provide a previously generated mapping'
' file for obfuscation'))
def print_header(self):
print("\n%s\n" % _("sosreport (version %s)" % (__version__,)))
def _get_hardware_devices(self):
self.devices = {
'block': self.get_block_devs(),
'fibre': self.get_fibre_devs()
}
# TODO: enumerate network devices, preferably with devtype info
def get_fibre_devs(self):
"""Enumerate a list of fibrechannel devices on this system so that
plugins can iterate over them
These devices are used by add_fibredev_cmd() in the Plugin class.
"""
try:
devs = []
devdirs = [
'fc_host',
'fc_transport',
'fc_remote_ports',
'fc_vports'
]
for devdir in devdirs:
if os.path.isdir("/sys/class/%s" % devdir):
devs.extend(glob.glob("/sys/class/%s/*" % devdir))
return devs
except Exception as err:
self.soslog.error("Could not get fibre device list: %s" % err)
return []
def get_block_devs(self):
"""Enumerate a list of block devices on this system so that plugins
can iterate over them
These devices are used by add_blockdev_cmd() in the Plugin class.
"""
try:
return os.listdir('/sys/block/')
except Exception as err:
self.soslog.error("Could not get block device list: %s" % err)
return []
def get_commons(self):
return {
'cmddir': self.cmddir,
'logdir': self.logdir,
'rptdir': self.rptdir,
'tmpdir': self.tmpdir,
'soslog': self.soslog,
'policy': self.policy,
'sysroot': self.sysroot,
'verbosity': self.opts.verbosity,
'cmdlineopts': self.opts,
'devices': self.devices
}
def get_temp_file(self):
return self.tempfile_util.new()
def _make_archive_paths(self):
self.archive.makedirs(self.cmddir, 0o755)
self.archive.makedirs(self.logdir, 0o755)
self.archive.makedirs(self.rptdir, 0o755)
def _set_directories(self):
self.cmddir = 'sos_commands'
self.logdir = 'sos_logs'
self.rptdir = 'sos_reports'
def _set_debug(self):
if self.opts.debug:
sys.excepthook = self._exception
self.raise_plugins = True
else:
self.raise_plugins = False
@staticmethod
def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
print()
# ...then start the debugger in post-mortem mode.
pdb.pm()
def handle_exception(self, plugname=None, func=None):
if self.raise_plugins or self.exit_process:
# retrieve exception info for the current thread and stack.
(etype, val, tb) = sys.exc_info()
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, val, tb, file=sys.stdout)
print()
# ...then start the debugger in post-mortem mode.
pdb.post_mortem(tb)
if plugname and func:
self._log_plugin_exception(plugname, func)
def _add_sos_logs(self):
# Make sure the log files are added before we remove the log
# handlers. This prevents "No handlers could be found.." messages
# from leaking to the console when running in --quiet mode when
# Archive classes attempt to acess the log API.
if getattr(self, "sos_log_file", None):
self.archive.add_file(self.sos_log_file,
dest=os.path.join('sos_logs', 'sos.log'))
if getattr(self, "sos_ui_log_file", None):
self.archive.add_file(self.sos_ui_log_file,
dest=os.path.join('sos_logs', 'ui.log'))
def _is_in_profile(self, plugin_class):
only_plugins = self.opts.only_plugins
if not len(self.opts.profiles):
return True
if not hasattr(plugin_class, "profiles"):
return False
if only_plugins and not self._is_not_specified(plugin_class.name()):
return True
return any([p in self.opts.profiles for p in plugin_class.profiles])
def _is_skipped(self, plugin_name):
return (plugin_name in self.opts.skip_plugins)
def _is_inactive(self, plugin_name, pluginClass):
return (not pluginClass(self.get_commons()).check_enabled() and
plugin_name not in self.opts.enable_plugins and
plugin_name not in self.opts.only_plugins)
def _is_not_default(self, plugin_name, pluginClass):
return (not pluginClass(self.get_commons()).default_enabled() and
plugin_name not in self.opts.enable_plugins and
plugin_name not in self.opts.only_plugins)
def _is_not_specified(self, plugin_name):
return (self.opts.only_plugins and
plugin_name not in self.opts.only_plugins)
def _skip(self, plugin_class, reason="unknown"):
self.skipped_plugins.append((
plugin_class.name(),
plugin_class(self.get_commons()),
reason
))
def _load(self, plugin_class):
self.loaded_plugins.append((
plugin_class.name(),
plugin_class(self.get_commons())
))
def load_plugins(self):
import_plugin = sos.report.plugins.import_plugin
helper = ImporterHelper(sos.report.plugins)
plugins = helper.get_modules()
self.plugin_names = []
self.profiles = set()
using_profiles = len(self.opts.profiles)
policy_classes = self.policy.valid_subclasses
extra_classes = []
if self.opts.experimental:
extra_classes.append(sos.report.plugins.ExperimentalPlugin)
valid_plugin_classes = tuple(policy_classes + extra_classes)
validate_plugin = self.policy.validate_plugin
remaining_profiles = list(self.opts.profiles)
# validate and load plugins
for plug in plugins:
plugbase, ext = os.path.splitext(plug)
try:
plugin_classes = import_plugin(plugbase, valid_plugin_classes)
if not len(plugin_classes):
# no valid plugin classes for this policy
continue
plugin_class = self.policy.match_plugin(plugin_classes)
if not validate_plugin(plugin_class,
experimental=self.opts.experimental):
self.soslog.warning(
_("plugin %s does not validate, skipping") % plug)
if self.opts.verbosity > 0:
self._skip(plugin_class, _("does not validate"))
continue
# plug-in is valid, let's decide whether run it or not
self.plugin_names.append(plugbase)
in_profile = self._is_in_profile(plugin_class)
if not in_profile:
self._skip(plugin_class, _("excluded"))
continue
if self._is_skipped(plugbase):
self._skip(plugin_class, _("skipped"))
continue
if self._is_inactive(plugbase, plugin_class):
self._skip(plugin_class, _("inactive"))
continue
if self._is_not_default(plugbase, plugin_class):
self._skip(plugin_class, _("optional"))
continue
# only add the plugin's profiles once we know it is usable
if hasattr(plugin_class, "profiles"):
self.profiles.update(plugin_class.profiles)
# true when the null (empty) profile is active
default_profile = not using_profiles and in_profile
if self._is_not_specified(plugbase) and default_profile:
self._skip(plugin_class, _("not specified"))
continue
for i in plugin_class.profiles:
if i in remaining_profiles:
remaining_profiles.remove(i)
self._load(plugin_class)
except Exception as e:
self.soslog.warning(_("plugin %s does not install, "
"skipping: %s") % (plug, e))
self.handle_exception()
if len(remaining_profiles) > 0:
self.soslog.error(_("Unknown or inactive profile(s) provided:"
" %s") % ", ".join(remaining_profiles))
self.list_profiles()
self._exit(1)
def _set_all_options(self):
if self.opts.alloptions:
for plugname, plug in self.loaded_plugins:
for name, parms in zip(plug.opt_names, plug.opt_parms):
if type(parms["enabled"]) == bool:
parms["enabled"] = True
def _set_tunables(self):
if self.opts.plugopts:
opts = {}
for opt in self.opts.plugopts:
# split up "general.syslogsize=5"
try:
opt, val = opt.split("=")
except ValueError:
val = True
else:
if val.lower() in ["off", "disable", "disabled", "false"]:
val = False
else:
# try to convert string "val" to int()
try:
val = int(val)
except ValueError:
pass
# split up "general.syslogsize"
try:
plug, opt = opt.split(".")
except ValueError:
plug = opt
opt = True
try:
opts[plug]
except KeyError:
opts[plug] = []
opts[plug].append((opt, val))
for plugname, plug in self.loaded_plugins:
if plugname in opts:
for opt, val in opts[plugname]:
if not plug.set_option(opt, val):
self.soslog.error('no such option "%s" for plugin '
'(%s)' % (opt, plugname))
self._exit(1)
del opts[plugname]
for plugname in opts.keys():
self.soslog.error('WARNING: unable to set option for disabled '
'or non-existing plugin (%s)' % (plugname))
# in case we printed warnings above, visually intend them from
# subsequent header text
if opts.keys():
self.soslog.error('')
def _check_for_unknown_plugins(self):
import itertools
for plugin in itertools.chain(self.opts.only_plugins,
self.opts.skip_plugins,
self.opts.enable_plugins):
plugin_name = plugin.split(".")[0]
if plugin_name not in self.plugin_names:
self.soslog.fatal('a non-existing plugin (%s) was specified '
'in the command line' % (plugin_name))
self._exit(1)
def _set_plugin_options(self):
for plugin_name, plugin in self.loaded_plugins:
names, parms = plugin.get_all_options()
for optname, optparm in zip(names, parms):
self.all_options.append((plugin, plugin_name, optname,
optparm))
def _report_profiles_and_plugins(self):
self.ui_log.info("")
if len(self.loaded_plugins):
self.ui_log.info(" %d profiles, %d plugins"
% (len(self.profiles), len(self.loaded_plugins)))
else:
# no valid plugins for this profile
self.ui_log.info(" %d profiles" % len(self.profiles))
self.ui_log.info("")
def list_plugins(self):
if not self.loaded_plugins and not self.skipped_plugins:
self.soslog.fatal(_("no valid plugins found"))
return
if self.loaded_plugins:
self.ui_log.info(_("The following plugins are currently enabled:"))
self.ui_log.info("")
for (plugname, plug) in self.loaded_plugins:
self.ui_log.info(" %-20s %s" % (plugname,
plug.get_description()))
else:
self.ui_log.info(_("No plugin enabled."))
self.ui_log.info("")
if self.skipped_plugins:
self.ui_log.info(_("The following plugins are currently "
"disabled:"))
self.ui_log.info("")
for (plugname, plugclass, reason) in self.skipped_plugins:
self.ui_log.info(" %-20s %-14s %s" % (
plugname,
reason,
plugclass.get_description()))
self.ui_log.info("")
if self.all_options:
self.ui_log.info(_("The following options are available for ALL "
"plugins:"))
for opt in self.all_options[0][0]._default_plug_opts:
self.ui_log.info(" %-25s %-15s %s" % (opt[0], opt[3], opt[1]))
self.ui_log.info("")
self.ui_log.info(_("The following plugin options are available:"))
for (plug, plugname, optname, optparm) in self.all_options:
if optname in ('timeout', 'postproc'):
continue
# format option value based on its type (int or bool)
if type(optparm["enabled"]) == bool:
if optparm["enabled"] is True:
tmpopt = "on"
else:
tmpopt = "off"
else:
tmpopt = optparm["enabled"]
self.ui_log.info(" %-25s %-15s %s" % (
plugname + "." + optname, tmpopt, optparm["desc"]))
else:
self.ui_log.info(_("No plugin options available."))
self.ui_log.info("")
profiles = list(self.profiles)
profiles.sort()
lines = _format_list("Profiles: ", profiles, indent=True)
for line in lines:
self.ui_log.info(" %s" % line)
self._report_profiles_and_plugins()
def list_profiles(self):
if not self.profiles:
self.soslog.fatal(_("no valid profiles found"))
return
self.ui_log.info(_("The following profiles are available:"))
self.ui_log.info("")
def _has_prof(c):
return hasattr(c, "profiles")
profiles = list(self.profiles)
profiles.sort()
for profile in profiles:
plugins = []
for name, plugin in self.loaded_plugins:
if _has_prof(plugin) and profile in plugin.profiles:
plugins.append(name)
lines = _format_list("%-15s " % profile, plugins, indent=True)
for line in lines:
self.ui_log.info(" %s" % line)
self._report_profiles_and_plugins()
def list_presets(self):
if not self.policy.presets:
self.soslog.fatal(_("no valid presets found"))
return
self.ui_log.info(_("The following presets are available:"))
self.ui_log.info("")
for preset in self.policy.presets.keys():
if not preset:
continue
preset = self.policy.find_preset(preset)
self.ui_log.info("%14s %s" % ("name:", preset.name))
self.ui_log.info("%14s %s" % ("description:", preset.desc))
if preset.note:
self.ui_log.info("%14s %s" % ("note:", preset.note))
if self.opts.verbosity > 0:
args = preset.opts.to_args()
options_str = "%14s " % "options:"
lines = _format_list(options_str, args, indent=True, sep=' ')
for line in lines:
self.ui_log.info(line)
self.ui_log.info("")
def add_preset(self, name, desc="", note=""):
"""Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise
"""
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self.cmdline.index("--add-preset")
args = self.cmdline[0:arg_index] + self.cmdline[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True
def del_preset(self, name):
"""Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise
"""
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True
def batch(self):
if self.opts.batch:
self.ui_log.info(self.policy.get_msg())
else:
msg = self.policy.get_msg()
msg += _("Press ENTER to continue, or CTRL-C to quit.\n")
try:
input(msg)
except KeyboardInterrupt:
self.ui_log.error("Exiting on user cancel")
self._exit(130)
except Exception as e:
self.ui_log.info("")
self.ui_log.error(e)
self._exit(e)
def _log_plugin_exception(self, plugin, method):
trace = traceback.format_exc()
msg = "caught exception in plugin method"
plugin_err_log = "%s-plugin-errors.txt" % plugin
logpath = os.path.join(self.logdir, plugin_err_log)
self.soslog.error('%s "%s.%s()"' % (msg, plugin, method))
self.soslog.error('writing traceback to %s' % logpath)
self.archive.add_string("%s\n" % trace, logpath, mode='a')
def prework(self):
self.policy.pre_work()
try:
self.ui_log.info(_(" Setting up archive ..."))
compression_methods = ('auto', 'bzip2', 'gzip', 'xz')
method = self.opts.compression_type
if method not in compression_methods:
compression_list = ', '.join(compression_methods)
self.ui_log.error("")
self.ui_log.error("Invalid compression specified: " + method)
self.ui_log.error("Valid types are: " + compression_list)
self.ui_log.error("")
self._exit(1)
self.setup_archive()
self._make_archive_paths()
return
except (OSError, IOError) as e:
# we must not use the logging subsystem here as it is potentially
# in an inconsistent or unreliable state (e.g. an EROFS for the
# file system containing our temporary log files).
if e.errno in fatal_fs_errors:
print("")
print(" %s while setting up archive" % e.strerror)
print("")
else:
print("Error setting up archive: %s" % e)
raise
except Exception as e:
self.ui_log.error("")
self.ui_log.error(" Unexpected exception setting up archive:")
traceback.print_exc()
self.ui_log.error(e)
self._exit(1)
def setup(self):
# Log command line options
msg = "[%s:%s] executing 'sos %s'"
self.soslog.info(msg % (__name__, "setup", " ".join(self.cmdline)))
# Log active preset defaults
preset_args = self.preset.opts.to_args()
msg = ("[%s:%s] using '%s' preset defaults (%s)" %
(__name__, "setup", self.preset.name, " ".join(preset_args)))
self.soslog.info(msg)
# Log effective options after applying preset defaults
self.soslog.info("[%s:%s] effective options now: %s" %
(__name__, "setup", " ".join(self.opts.to_args())))
self.ui_log.info(_(" Setting up plugins ..."))
for plugname, plug in self.loaded_plugins:
try:
self.report_md.plugins.add_section(plugname)
plug.set_plugin_manifest(getattr(self.report_md.plugins,
plugname))
start = datetime.now()
plug.manifest.add_field('setup_start', start)
plug.archive = self.archive
plug.add_default_collections()
plug.setup()
self.env_vars.update(plug._env_vars)
if self.opts.verify:
plug.setup_verify()
end = datetime.now()
plug.manifest.add_field('setup_end', end)
plug.manifest.add_field('setup_time', end - start)
except KeyboardInterrupt:
raise
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while setting up plugins"
% e.strerror)
self.ui_log.error("")
self._exit(1)
self.handle_exception(plugname, "setup")
except Exception:
self.handle_exception(plugname, "setup")
def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt')
def collect(self):
self.ui_log.info(_(" Running plugins. Please wait ..."))
self.ui_log.info("")
plugruncount = 0
self.pluglist = []
self.running_plugs = []
for i in self.loaded_plugins:
plugruncount += 1
self.pluglist.append((plugruncount, i[0]))
try:
self.plugpool = ThreadPoolExecutor(self.opts.threads)
# Pass the plugpool its own private copy of self.pluglist
results = self.plugpool.map(self._collect_plugin,
list(self.pluglist))
self.plugpool.shutdown(wait=True)
for res in results:
if not res:
self.soslog.debug("Unexpected plugin task result: %s" %
res)
self.ui_log.info("")
except KeyboardInterrupt:
# We may not be at a newline when the user issues Ctrl-C
self.ui_log.error("\nExiting on user cancel\n")
os._exit(1)
def _collect_plugin(self, plugin):
"""Wraps the collect_plugin() method so we can apply a timeout
against the plugin as a whole"""
with ThreadPoolExecutor(1) as pool:
try:
_plug = self.loaded_plugins[plugin[0]-1][1]
t = pool.submit(self.collect_plugin, plugin)
# Re-type int 0 to NoneType, as otherwise result() will treat
# it as a literal 0-second timeout
timeout = _plug.timeout or None
start = datetime.now()
_plug.manifest.add_field('start_time', start)
t.result(timeout=timeout)
end = datetime.now()
_plug.manifest.add_field('end_time', end)
_plug.manifest.add_field('run_time', end - start)
except TimeoutError:
self.ui_log.error("\n Plugin %s timed out\n" % plugin[1])
self.running_plugs.remove(plugin[1])
self.loaded_plugins[plugin[0]-1][1].set_timeout_hit()
pool._threads.clear()
return True
def collect_plugin(self, plugin):
try:
count, plugname = plugin
plug = self.loaded_plugins[count-1][1]
self.running_plugs.append(plugname)
except Exception:
return False
numplugs = len(self.loaded_plugins)
status_line = " Starting %-5s %-15s %s" % (
"%d/%d" % (count, numplugs),
plugname,
"[Running: %s]" % ' '.join(p for p in self.running_plugs)
)
self.ui_progress(status_line)
try:
plug.collect()
# certain exceptions can cause either of these lists to no
# longer contain the plugin, which will result in sos hanging
# so we can't blindly call remove() on these two.
try:
self.pluglist.remove(plugin)
except ValueError:
pass
try:
self.running_plugs.remove(plugname)
except ValueError:
pass
status = ''
if (len(self.pluglist) <= int(self.opts.threads) and
self.running_plugs):
status = " Finishing plugins %-12s %s" % (
" ",
"[Running: %s]" % (' '.join(p for p in self.running_plugs))
)
if not self.running_plugs and not self.pluglist:
status = "\n Finished running plugins"
if status:
self.ui_progress(status)
except SoSTimeoutError:
# we already log and handle the plugin timeout in the nested thread
# pool this is running in, so don't do anything here.
pass
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("\n %s while collecting plugin data"
% e.strerror)
self.ui_log.error(" Data collected still available at %s\n"
% self.tmpdir)
os._exit(1)
self.handle_exception(plugname, "collect")
except Exception:
self.handle_exception(plugname, "collect")
def ui_progress(self, status_line):
if self.opts.verbosity == 0 and not self.opts.batch:
status_line = "\r%s" % status_line.ljust(90)
else:
status_line = "%s\n" % status_line
if not self.opts.quiet:
sys.stdout.write(status_line)
sys.stdout.flush()
def collect_env_vars(self):
if not self.env_vars:
return
env = '\n'.join([
"%s=%s" % (name, val) for (name, val) in
[(name, '%s' % os.environ.get(name)) for name in self.env_vars if
os.environ.get(name) is not None]
]) + '\n'
self.archive.add_string(env, 'environment')
def generate_reports(self):
report = Report()
# generate report content
for plugname, plug in self.loaded_plugins:
section = Section(name=plugname)
for alert in plug.alerts:
section.add(Alert(alert))
if plug.custom_text:
section.add(Note(plug.custom_text))
for f in plug.copied_files:
section.add(CopiedFile(name=f['srcpath'],
href=".." + f['dstpath']))
for cmd in plug.executed_commands:
section.add(Command(name=cmd['cmd'], return_code=0,
href=os.path.join(
"..",
self.get_commons()['cmddir'],
cmd['file']
)))
for content, f in plug.copy_strings:
section.add(CreatedFile(name=f,
href=os.path.join(
"..",
"sos_strings",
plugname,
f)))
report.add(section)
# print it in text, JSON and HTML formats
formatlist = (
(PlainTextReport, "sos.txt", "text"),
(JSONReport, "sos.json", "JSON"),
(HTMLReport, "sos.html", "HTML")
)
for class_, filename, type_ in formatlist:
try:
fd = self.get_temp_file()
output = class_(report).unicode()
fd.write(output)
fd.flush()
self.archive.add_file(fd, dest=os.path.join('sos_reports',
filename))
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while writing %s report"
% (e.strerror, type_))
self.ui_log.error("")
self._exit(1)
def postproc(self):
for plugname, plug in self.loaded_plugins:
try:
if plug.get_option('postproc'):
plug.postproc()
else:
self.soslog.info("Skipping postproc for plugin %s"
% plugname)
except (OSError, IOError) as e:
if e.errno in fatal_fs_errors:
self.ui_log.error("")
self.ui_log.error(" %s while post-processing plugin data"
% e.strerror)
self.ui_log.error("")
self._exit(1)
self.handle_exception(plugname, "postproc")
except Exception:
self.handle_exception(plugname, "postproc")
def _create_checksum(self, archive, hash_name):
if not archive:
return False
try:
hash_size = 1024**2 # Hash 1MiB of content at a time.
archive_fp = open(archive, 'rb')
digest = hashlib.new(hash_name)
while True:
hashdata = archive_fp.read(hash_size)
if not hashdata:
break
digest.update(hashdata)
archive_fp.close()
except Exception:
self.handle_exception()
return digest.hexdigest()
def _write_checksum(self, archive, hash_name, checksum):
# store checksum into file
fp = open(archive + "." + hash_name, "w")
if checksum:
fp.write(checksum + "\n")
fp.close()
def final_work(self):
archive = None # archive path
directory = None # report directory path (--build)
map_file = None # path of the map file generated for the report
# use this instead of self.opts.clean beyond the initial check if
# cleaning was requested in case SoSCleaner fails for some reason
do_clean = False
if self.opts.clean:
try:
hook_commons = {
'policy': self.policy,
'tmpdir': self.tmpdir,
'sys_tmp': self.sys_tmp,
'options': self.opts,
'manifest': self.manifest
}
cleaner = SoSCleaner(in_place=True, hook_commons=hook_commons)
cleaner.set_target_path(self.archive.get_archive_path())
# ignore the returned paths here
map_file, _paths = cleaner.execute()
do_clean = True
except Exception as err:
print(_("ERROR: Unable to obfuscate report: %s" % err))
self._add_sos_logs()
if self.manifest is not None:
self.archive.add_final_manifest_data(self.opts.compression_type)
# Now, separately clean the log files that cleaner also wrote to
if do_clean:
_dir = os.path.join(self.tmpdir, self.archive._name)
cleaner.obfuscate_file(os.path.join(_dir, 'sos_logs', 'sos.log'),
short_name='sos.log')
cleaner.obfuscate_file(os.path.join(_dir, 'sos_logs', 'ui.log'),
short_name='ui.log')
cleaner.obfuscate_file(
os.path.join(_dir, 'sos_reports', 'manifest.json'),
short_name='manifest.json'
)
# package up and compress the results
if not self.opts.build:
old_umask = os.umask(0o077)
if not self.opts.quiet:
print(_("Creating compressed archive..."))
# compression could fail for a number of reasons
try:
if do_clean:
self.archive.rename_archive_root(cleaner)
archive = self.archive.finalize(
self.opts.compression_type)
except (OSError, IOError) as e:
print("")
print(_(" %s while finalizing archive %s" %
(e.strerror, self.archive.get_archive_path())))
print("")
if e.errno in fatal_fs_errors:
self._exit(1)
except Exception:
if self.opts.debug:
raise
else:
return False
finally:
os.umask(old_umask)
else:
# move the archive root out of the private tmp directory.
directory = self.archive.get_archive_path()
dir_name = os.path.basename(directory)
try:
final_dir = os.path.join(self.sys_tmp, dir_name)
if do_clean:
final_dir = cleaner.obfuscate_string(final_dir)
os.rename(directory, final_dir)
directory = final_dir
except (OSError, IOError):
print(_("Error moving directory: %s" % directory))
return False
checksum = None
if not self.opts.build:
# if creating archive file failed, report it and
# skip generating checksum
if not archive:
print("Creating archive tarball failed.")
else:
# compute and store the archive checksum
hash_name = self.policy.get_preferred_hash_name()
checksum = self._create_checksum(archive, hash_name)
try:
self._write_checksum(archive, hash_name, checksum)
except (OSError, IOError):
print(_("Error writing checksum for file: %s" % archive))
# output filename is in the private tmpdir - move it to the
# containing directory.
final_name = os.path.join(self.sys_tmp,
os.path.basename(archive))
if do_clean:
final_name = cleaner.obfuscate_string(
final_name.replace('.tar', '-obfuscated.tar')
)
# Get stat on the archive
archivestat = os.stat(archive)
archive_hash = archive + "." + hash_name
final_hash = final_name + "." + hash_name
# move the archive and checksum file
try:
os.rename(archive, final_name)
archive = final_name
except (OSError, IOError):
print(_("Error moving archive file: %s" % archive))
return False
# There is a race in the creation of the final checksum file:
# since the archive has already been published and the checksum
# file name is predictable once the archive name is known a
# malicious user could attempt to create a symbolic link in
# order to misdirect writes to a file of the attacker's choose.
#
# To mitigate this we write the checksum inside the private tmp
# directory and use an atomic rename that is guaranteed to
# either succeed or fail: at worst the move will fail and be
# reported to the user. The correct checksum value is still
# written to the terminal and nothing is written to a location
# under the control of the user creating the link.
try:
os.rename(archive_hash, final_hash)
except (OSError, IOError):
print(_("Error moving checksum file: %s" % archive_hash))
if not self.opts.build:
self.policy.display_results(archive, directory, checksum,
archivestat, map_file=map_file)
else:
self.policy.display_results(archive, directory, checksum,
map_file=map_file)
if self.opts.upload or self.opts.upload_url:
if not self.opts.build:
try:
self.policy.upload_archive(archive)
self.ui_log.info(_("Uploaded archive successfully"))
except Exception as err:
self.ui_log.error("Upload attempt failed: %s" % err)
else:
msg = ("Unable to upload archive when using --build as no "
"archive is created.")
self.ui_log.error(msg)
# clean up
logging.shutdown()
if self.tempfile_util:
self.tempfile_util.clean()
if self.tmpdir and os.path.isdir(self.tmpdir):
rmtree(self.tmpdir)
return True
def verify_plugins(self):
if not self.loaded_plugins:
self.soslog.error(_("no valid plugins were enabled"))
return False
return True
def add_manifest_data(self):
"""Add 'global' data to the manifest, that is any information that is
not plugin-specific
"""
self.report_md.add_field('sysroot', self.sysroot)
self.report_md.add_field('preset', self.preset.name if self.preset else
'unset')
self.report_md.add_list('profiles', self.opts.profiles)
self.report_md.add_section('devices')
for key, value in self.devices.items():
self.report_md.devices.add_list(key, value)
self.report_md.add_list('enabled_plugins', self.opts.enable_plugins)
self.report_md.add_list('disabled_plugins', self.opts.skip_plugins)
self.report_md.add_section('plugins')
def execute(self):
try:
self.policy.set_commons(self.get_commons())
self.load_plugins()
self._set_all_options()
self._set_tunables()
self._check_for_unknown_plugins()
self._set_plugin_options()
if self.opts.list_plugins:
self.list_plugins()
raise SystemExit
if self.opts.list_profiles:
self.list_profiles()
raise SystemExit
if self.opts.list_presets:
self.list_presets()
raise SystemExit
if self.opts.add_preset:
return self.add_preset(self.opts.add_preset)
if self.opts.del_preset:
return self.del_preset(self.opts.del_preset)
# verify that at least one plug-in is enabled
if not self.verify_plugins():
return False
self.add_manifest_data()
self.batch()
self.prework()
self.setup()
self.collect()
if not self.opts.no_env_vars:
self.collect_env_vars()
if not self.opts.noreport:
self.generate_reports()
if not self.opts.no_postproc:
self.postproc()
else:
self.ui_log.info("Skipping postprocessing of collected data")
self.version()
return self.final_work()
except (OSError):
if self.opts.debug:
raise
self.cleanup()
except (KeyboardInterrupt):
self.ui_log.error("\nExiting on user cancel")
self.cleanup()
self._exit(130)
except (SystemExit) as e:
self.cleanup()
sys.exit(e.code)
self._exit(1)
# vim: set et ts=4 sw=4 :
|