-
Notifications
You must be signed in to change notification settings - Fork 541
/
__init__.py
1855 lines (1682 loc) · 77.6 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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, bold,
sos_get_command_output, TIMEOUT_DEFAULT, listdir,
is_executable)
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,
'container_runtime': 'auto',
'keep_binary_files': False,
'desc': '',
'domains': [],
'disable_parsers': [],
'dry_run': False,
'estimate_only': False,
'experimental': False,
'enable_plugins': [],
'journal_size': 100,
'keywords': [],
'keyword_file': None,
'plugopts': [],
'label': '',
'list_plugins': False,
'list_presets': False,
'list_profiles': False,
'log_size': 25,
'low_priority': False,
'map_file': '/etc/sos/cleaner/default_mapping',
'skip_commands': [],
'skip_files': [],
'skip_plugins': [],
'namespaces': None,
'no_report': False,
'no_env_vars': False,
'no_postproc': False,
'no_update': False,
'note': '',
'only_plugins': [],
'preset': 'auto',
'plugin_timeout': TIMEOUT_DEFAULT,
'cmd_timeout': TIMEOUT_DEFAULT,
'profiles': [],
'since': None,
'verify': False,
'allow_system_changes': False,
'usernames': [],
'upload': False,
'upload_url': None,
'upload_directory': None,
'upload_user': None,
'upload_pass': None,
'upload_method': 'auto',
'upload_no_ssl_verify': False,
'upload_protocol': 'auto',
'upload_s3_endpoint': None,
'upload_s3_region': None,
'upload_s3_bucket': None,
'upload_s3_access_key': None,
'upload_s3_secret_key': None,
'upload_s3_object_prefix': 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.estimated_plugsizes = {}
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')
self._set_directories()
msg = "default"
self.sysroot = self.policy.sysroot
# set alternate system root directory
if self.opts.sysroot:
msg = "cmdline"
elif self.policy.in_container() and self.sysroot != os.sep:
msg = "policy"
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._check_container_runtime()
self._get_namespaces()
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("--container-runtime", default="auto",
help="Default container runtime to use for "
"collections. 'auto' for policy control.")
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("--estimate-only", action="store_true",
help="Approximate disk space requirements for "
"a real sos run; disables --clean and "
"--collect, sets --threads=1 and "
"--no-postproc")
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("--journal-size", type=int, default=100,
dest="journal_size",
help="limit the size of collected journals "
"in MiB")
report_grp.add_argument("-k", "--plugin-option", "--plugopts",
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 "
"(not journals) in MiB")
report_grp.add_argument("--low-priority", action="store_true",
default=False,
help="generate report with low system priority"
)
report_grp.add_argument("--namespaces", default=None,
help="limit number of namespaces to collect "
"output for - 0 means unlimited")
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="no_report", 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("--cmd-timeout", default=None,
help="set a command timeout for all plugins")
report_grp.add_argument("-p", "--profile", "--profiles",
action="extend", dest="profiles", type=str,
default=[],
help="enable plugins used by the given "
"profiles")
report_grp.add_argument('--skip-commands', default=[], action='extend',
dest='skip_commands',
help="do not execute these commands")
report_grp.add_argument('--skip-files', default=[], action='extend',
dest='skip_files',
help="do not collect these files")
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")
report_grp.add_argument("--upload-method", default='auto',
choices=['auto', 'put', 'post'],
help="HTTP method to use for uploading")
report_grp.add_argument("--upload-no-ssl-verify", default=False,
action='store_true',
help="Disable SSL verification for upload url")
report_grp.add_argument("--upload-s3-endpoint", default=None,
help="Endpoint to upload to for S3 bucket")
report_grp.add_argument("--upload-s3-region", default=None,
help="Region to upload to for S3 bucket")
report_grp.add_argument("--upload-s3-bucket", default=None,
help="Name of the S3 bucket to upload to")
report_grp.add_argument("--upload-s3-access-key", default=None,
help="Access key for the S3 bucket")
report_grp.add_argument("--upload-s3-secret-key", default=None,
help="Secret key for the S3 bucket")
report_grp.add_argument("--upload-s3-object-prefix", default=None,
help="Prefix for the S3 object/key")
report_grp.add_argument("--upload-protocol", default='auto',
choices=['auto', 'https', 'ftp', 'sftp',
's3'],
help="Manually specify the upload protocol")
# 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', '--cleaner', '--mask',
dest='clean',
default=False, action='store_true',
help='Obfuscate sensitive information')
cleaner_grp.add_argument('--domains', dest='domains', default=[],
action='extend',
help='Additional domain names to obfuscate')
cleaner_grp.add_argument('--disable-parsers', action='extend',
default=[], dest='disable_parsers',
help=('Disable specific parsers, so that '
'those elements are not obfuscated'))
cleaner_grp.add_argument('--keywords', action='extend', default=[],
dest='keywords',
help='List of keywords to obfuscate')
cleaner_grp.add_argument('--keyword-file', default=None,
dest='keyword_file',
help='Provide a file a 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-file', dest='map_file',
default='/etc/sos/cleaner/default_mapping',
help=('Provide a previously generated mapping'
' file for obfuscation'))
cleaner_grp.add_argument('--keep-binary-files', default=False,
action='store_true',
dest='keep_binary_files',
help='Keep unprocessable binary files in the '
'archive instead of removing them')
cleaner_grp.add_argument('--usernames', dest='usernames', default=[],
action='extend',
help='List of usernames to obfuscate')
@classmethod
def display_help(cls, section):
section.set_title('SoS Report Detailed Help')
section.add_text(
'The report command is the most common use case for SoS, and aims '
'to collect relevant diagnostic and troubleshooting data to assist'
' with issue analysis without actively performing that analysis on'
' the system while it is in use.'
)
section.add_text(
'Additionally, sos report archives can be used for ongoing '
'inspection for pre-emptive issue monitoring, such as that done '
'by the Insights project.'
)
section.add_text(
'The typical result of an execution of \'sos report\' is a tarball'
' that contains troubleshooting command output, copies of config '
'files, and copies of relevant sections of the host filesystem. '
'Root privileges are required for collections.'
)
psec = section.add_section(title='How Collections Are Determined')
psec.add_text(
'SoS report performs it\'s collections by way of \'plugins\' that '
'individually specify what files to copy and what commands to run.'
' Plugins typically map to specific components or software '
'packages.'
)
psec.add_text(
'Plugins may specify different collections on different distribu'
'tions, and some plugins may only be for specific distributions. '
'Distributions are represented within SoS by \'policies\' and may '
'influence how other SoS commands or options function. For example'
'policies can alter where the --upload option defaults to or '
'functions.'
)
ssec = section.add_section(title='See Also')
ssec.add_text(
"For information on available options for report, see %s and %s"
% (bold('sos report --help'), bold('man sos-report'))
)
ssec.add_text("The following %s sections may be of interest:\n"
% bold('sos help'))
help_lines = {
'report.plugins': 'Information on the plugin design of sos',
'report.plugins.$plugin': 'Information on a specific $plugin',
'policies': 'How sos operates on different distributions'
}
helpln = ''
for ln in help_lines:
ssec.add_text("\t{:<36}{}".format(ln, help_lines[ln]),
newline=False)
ssec.add_text(helpln)
def print_header(self):
print("\n%s\n" % _("sosreport (version %s)" % (__version__,)))
def _get_hardware_devices(self):
self.devices = {
'storage': {
'block': self._get_block_devs(),
'fibre': self._get_fibre_devs()
},
'network': self._get_network_devs(),
'namespaced_network': self._get_network_namespace_devices()
}
def _check_container_runtime(self):
"""Check the loaded container runtimes, and the policy default runtime
(if set), against any requested --container-runtime value. This can be
useful for systems that have multiple runtimes, such as RHCOS, but do
not have a clearly defined 'default' (or one that is determined based
entirely on configuration).
"""
if self.opts.container_runtime != 'auto':
crun = self.opts.container_runtime.lower()
if crun in ['none', 'off', 'diabled']:
self.policy.runtimes = {}
self.soslog.info(
"Disabled all container runtimes per user option."
)
elif not self.policy.runtimes:
msg = ("WARNING: No container runtimes are active, ignoring "
"option to set default runtime to '%s'\n" % crun)
self.soslog.warning(msg)
elif crun not in self.policy.runtimes.keys():
valid = ', '.join(p for p in self.policy.runtimes.keys()
if p != 'default')
raise Exception("Cannot use container runtime '%s': no such "
"runtime detected. Available runtimes: %s"
% (crun, valid))
else:
self.policy.runtimes['default'] = self.policy.runtimes[crun]
self.soslog.info(
"Set default container runtime to '%s'"
% self.policy.runtimes['default'].name
)
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_device_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_device_cmd() in the Plugin class.
"""
try:
device_list = ["/dev/%s" % d for d in os.listdir('/sys/block')]
loop_devices = sos_get_command_output('losetup --all --noheadings')
real_loop_devices = []
if loop_devices['status'] == 0:
for loop_dev in loop_devices['output'].splitlines():
loop_device = loop_dev.split()[0].replace(':', '')
real_loop_devices.append(loop_device)
ghost_loop_devs = [dev for dev in device_list
if dev.startswith("loop")
if dev not in real_loop_devices]
dev_list = list(set(device_list) - set(ghost_loop_devs))
return dev_list
except Exception as err:
self.soslog.error("Could not get block device list: %s" % err)
return []
def _get_namespaces(self):
self.namespaces = {
'network': self._get_network_namespaces()
}
def _get_network_devs(self):
"""Helper to encapsulate network devices probed by sos. Rather than
probing lists of distinct device types like we do for storage, we can
do some introspection of device enumeration where a single interface
may have multiple device types. E.G an 'ethernet' device could also be
a bond, and that is pertinent information for device iteration.
:returns: A collection of enumerated devices sorted by device type
:rtype: ``dict`` with keys being device types
"""
_devs = {
'ethernet': [],
'bridge': [],
'team': [],
'bond': []
}
try:
if is_executable('nmcli', sysroot=self.opts.sysroot):
_devs.update(self._get_nmcli_devs())
# if nmcli failed for some reason, fallback
if not _devs['ethernet']:
self.soslog.debug(
'Network devices not enumerated by nmcli. Will attempt to '
'manually compile list of devices.'
)
_devs.update(self._get_eth_devs())
_devs['bridge'] = self._get_bridge_devs()
except Exception as err:
self.soslog.warning(f"Could not enumerate network devices: {err}")
return _devs
def _get_network_namespace_devices(self):
"""Enumerate the network devices that exist within each network
namespace that exists on the system
"""
_nmdevs = {}
for nmsp in self.namespaces['network']:
_nmdevs[nmsp] = {
'ethernet': self._get_eth_devs(nmsp)
}
return _nmdevs
def _get_nmcli_devs(self):
"""Use nmcli, if available, to enumerate network devices. From this
output, manually grok together lists of devices.
"""
_devs = {}
try:
_ndevs = sos_get_command_output('nmcli --fields DEVICE,TYPE dev')
if _ndevs['status'] == 0:
for dev in _ndevs['output'].splitlines()[1:]:
dname, dtype = dev.split()
if dtype not in _devs:
_devs[dtype] = [dname]
else:
_devs[dtype].append(dname)
_devs['ethernet'].append(dname)
_devs['ethernet'] = list(set(_devs['ethernet']))
except Exception as err:
self.soslog.debug("Could not parse nmcli devices: %s" % err)
return _devs
def _get_eth_devs(self, namespace=None):
"""Enumerate a list of ethernet network devices so that plugins can
reliably iterate over the same set of devices without doing piecemeal
discovery.
These devices are used by `add_device_cmd()` when `devices` includes
"ethernet" or "network".
:param namespace: Inspect this existing network namespace, if
provided
:type namespace: ``str``
:returns: All valid ethernet devices found, potentially within a
given namespace
:rtype: ``list``
"""
filt_devs = ['bonding_masters']
_eth_devs = []
if not namespace:
try:
# Override checking sysroot here, as network devices will not
# be under the sysroot in live environments or in containers
# that are correctly setup to collect from the host
_eth_devs = [
dev for dev in listdir('/sys/class/net', None)
if dev not in filt_devs
]
except Exception as err:
self.soslog.warning(
f'Failed to manually determine network devices: {err}'
)
else:
try:
_nscmd = "ip netns exec %s ls /sys/class/net" % namespace
_nsout = sos_get_command_output(_nscmd)
if _nsout['status'] == 0:
for _nseth in _nsout['output'].split():
if _nseth not in filt_devs:
_eth_devs.append(_nseth)
except Exception as err:
self.soslog.warning(
"Could not determine network namespace '%s' devices: %s"
% (namespace, err)
)
return {
'ethernet': _eth_devs,
'bond': [bd for bd in _eth_devs if bd.startswith('bond')],
'tun': [td for td in _eth_devs if td.startswith('tun')]
}
def _get_bridge_devs(self):
"""Enumerate a list of bridge devices so that plugins can reliably
iterate over the same set of bridges.
These devices are used by `add_device_cmd()` when `devices` includes
"bridge" or "network".
"""
_bridges = []
try:
_bout = sos_get_command_output('brctl show', timeout=15)
except Exception as err:
self.soslog.warning("Unable to enumerate bridge devices: %s" % err)
if _bout['status'] == 0:
for _bline in _bout['output'].splitlines()[1:]:
try:
_bridges.append(_bline.split()[0])
except Exception as err:
self.soslog.info(
"Could not parse device from line '%s': %s"
% (_bline, err)
)
return _bridges
def _get_network_namespaces(self):
"""Enumerate a list of network namespaces on this system so that
plugins can iterate over them
Note that stderr is not collected, so no handling of error lines.
"""
out_ns = []
ip_netns = sos_get_command_output("ip netns")
if ip_netns['status'] == 0:
for line in ip_netns['output'].splitlines():
if line.isspace() or line[:1].isspace():
continue
out_ns.append(line.partition(' ')[0])
return out_ns
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,
'namespaces': self.namespaces
}
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 opt in plug.options.values():
if bool in opt.val_type:
opt.value = True
def _set_tunables(self):
if self.opts.plugopts:
opts = {}
for opt in self.opts.plugopts:
try:
opt, val = opt.split("=")
except ValueError:
val = True
if isinstance(val, str):
val = val.lower()
if val in ["on", "enable", "enabled", "true", "yes"]:
val = True
elif val in ["off", "disable", "disabled", "false", "no"]:
val = False
else:
# try to convert string "val" to int()
try:
val = int(val)
except ValueError:
pass
try:
plug, opt = opt.split(".")
except ValueError:
plug = opt
opt = True
try:
opts[plug]
except KeyError:
opts[plug] = {}
opts[plug][opt] = val
for plugname, plug in self.loaded_plugins:
if plugname in opts:
for opt in opts[plugname]:
if opt not in plug.options:
self.soslog.error('no such option "%s" for plugin '
'(%s)' % (opt, plugname))
self._exit(1)
try:
plug.options[opt].set_value(opts[plugname][opt])
self.soslog.debug(
"Set %s plugin option to %s"
% (plugname, plug.options[opt])
)
except Exception as err:
self.soslog.error(err)
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.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)
for plugin in self.opts.skip_plugins:
if plugin not in self.plugin_names:
self.soslog.warning(
"Requested to skip non-existing plugin '%s'." % plugin
)
def _set_plugin_options(self):
for plugin_name, plugin in self.loaded_plugins:
for opt in plugin.options:
self.all_options.append(plugin.options[opt])
def _set_estimate_only(self):
# set estimate-only mode by enforcing some options settings
# and return a corresponding log messages string
msg = "\nEstimate-only mode enabled"
ext_msg = []
if self.opts.threads > 1:
ext_msg += ["--threads=%s overriden to 1" % self.opts.threads, ]
self.opts.threads = 1
if not self.opts.build:
ext_msg += ["--build enabled", ]
self.opts.build = True
if not self.opts.no_postproc:
ext_msg += ["--no-postproc enabled", ]
self.opts.no_postproc = True
if self.opts.clean:
ext_msg += ["--clean disabled", ]
self.opts.clean = False
if self.opts.upload:
ext_msg += ["--upload* options disabled", ]
self.opts.upload = False
if ext_msg:
msg += ", which overrides some options:\n " + "\n ".join(ext_msg)
else:
msg += "."
msg += "\n\n"
return msg
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):