forked from couchbase/ns_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbcollect_info
executable file
·2895 lines (2433 loc) · 106 KB
/
cbcollect_info
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
#!/usr/bin/env python3
# -*- python -*-
#
# @author Couchbase <[email protected]>
# @copyright 2011-Present Couchbase, Inc.
#
# Use of this software is governed by the Business Source License included in
# the file licenses/BSL-Couchbase.txt. As of the Change Date specified in that
# file, in accordance with the Business Source License, use of this software
# will be governed by the Apache License, Version 2.0, included in the file
# licenses/APL2.txt.
import os
import sys
import tempfile
import time
import subprocess
import re
import platform
import glob
import socket
import threading
import optparse
import atexit
import signal
import urllib.parse
import shutil
import errno
import hashlib
import uuid
import configparser
from datetime import datetime, timedelta, tzinfo
import array
import mmap
from io import BytesIO, StringIO
from typing import BinaryIO, Dict, List, Optional, Iterable, Pattern, Tuple, TypeVar, Union, IO, Any, Callable
from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
from enum import Enum, unique
from io import BytesIO, StringIO
from abc import ABC, abstractmethod
import gzip
""" Represents opaque 'data' from the C context """
_CData = TypeVar("_CData")
""" This is a copy of python's own type for allowed buffer type(s) """
ReadableBuffer = Union[bytes, bytearray, memoryview, array.array,
mmap.mmap, _CData]
""" A type representing one of the log processors """
LogProcessors = Union["RegularLogProcessor",
"AccessLogProcessor",
"CouchbaseLogProcessor"]
""" Type of allowed writers """
WriterType = Union[BytesIO, IO[bytes], "Writer"]
""" The default size of a single '.read()' operation """
READ_SIZE: int = 64 * 1024
""" The default log file """
DEFAULT_LOG: str = "couchbase.log"
""" Files that are included in redaction, but aren't ran through redactor """
BINARY_FILE_EXTS: Tuple[str, str] = (".gz", ".dmp")
""" Files in this list will be completely skipped in the redacted zip """
OMIT_IN_REDACT_ZIP: List[str] = ["users.dets"]
# This is a facility that provides a functionality similar to atexit from the
# standard library. We don't use the latter for the following reasons.
#
# When cbcollect_info is started with --watch-stdin flag, we start a thread
# monitoring stdin that terminates the process when stdin gets closed. The
# issue is many-fold:
#
# - sys.exit() can only be called from the main thread.
#
# - os._exit() doesn't invoke any of the cleanup functions registered by
# atexit.
#
# - It's possible for the stdin watcher thread to interrupt the main thread
# by calling _thread.interrupt_main(). This plays nicely with atexit. But
# the issue is that the thread can't always be interrupted. So it can take
# a noticeable amount of time for the main thread to terminate.
#
# So AltExitC is a solution to these issues. It terminates the process as soon
# as possible by calling os._exit(). The price is that the cleanup actions
# need to be registered with AltExitC and synchronization is a concern.
class AltExitC(object):
def __init__(self):
self.list = []
self.lock = threading.Lock()
atexit.register(self.at_exit_handler)
def register(self, f):
self.lock.acquire()
self.register_and_unlock(f)
def register_and_unlock(self, f):
try:
self.list.append(f)
finally:
self.lock.release()
def at_exit_handler(self):
self.lock.acquire()
self.list.reverse()
for f in self.list:
try:
f()
except BaseException:
# Continue exit handling in spite of any exceptions
pass
def exit(self, status):
self.at_exit_handler()
os._exit(status)
AltExit = AltExitC()
class Writer(ABC):
"""
Abstract base class for all of our writers. This is probably the "proper"
method to use instead of overriding things that don't fit quite right
for this use case. All our writers override this and combine in layers
to provide a unified, streaming, interface.
"""
def __init__(self) -> None:
super().__init__()
@abstractmethod
def write(self, buf: ReadableBuffer) -> int:
"""
This is the main method used by all the writers. It uses the same buffer
type as most of the common python ones, for maximum interop between
them.
"""
pass
@abstractmethod
def flush(self):
""""
Some writers may maintain internal buffers, so this allows callers to
flush out anything remaining in the buffer. This is especially useful
if you are finished reading from the source and need to write the final
bit that's still buffered.
"""
pass
def close(self):
"""
Close is not required because many of the implementors will be passed
in the underlying stream(s). If we were to close those inside the
object and outside of it, that would be problematic/needless.
"""
pass
class FSyncedFile(Writer):
SYNC_BYTES = 16 * 1024 * 1024
def __init__(self, *args, **kwargs):
super().__init__()
self._file = open(*args, **kwargs)
self._written = 0
def __getattr__(self, name):
return getattr(self._file, name)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def flush(self):
"""
Choosing not to fsync here so we don't do it too often.
"""
self._file.flush()
def close(self):
self._sync()
self._file.close()
def write(self, buf: ReadableBuffer):
n = self._file.write(buf)
self._written += n
if self._written >= self.SYNC_BYTES:
self._sync()
self._written = 0
return n
def _sync(self):
self._file.flush()
os.fsync(self._file.fileno())
# Currently we decode bytes in this file via LATIN1. The reason for this is that
# UTF8 (which is the default in python) is a decoding which can fail - i.e. not
# all sequences of bytes are valid UTF8 and we cannot currenlty guarantee that
# all bytes that will be run through cbcollect will be valid UTF8. (We need
# protections elsewhere to make this guarantee that currently don't exist.) By
# contrast, all byte sequences are valid LATIN1, almost all our content is ASCII
# and thus LATIN1, and python2 essentially decoded strings as LATIN1, thus we
# are backwards compatible with pre-6.5 behavior. See MB-33809.
# For cases in which one knows for certain UTF8 is being used, feel free
# to use it.
LATIN1 = 'latin1'
USAGE = """usage: %prog [options] output_file.zip
- Linux/Windows/OSX:
%prog output_file.zip
%prog -v output_file.zip"""
# adapted from pytz
class LocalTZ(tzinfo):
def __init__(self):
offset = time.localtime().tm_gmtoff
self._offset = timedelta(seconds=offset)
def utcoffset(self, dt):
return self._offset
def dst(self, dt):
return timedelta(0)
def tzname(self, dt):
return None
local_tz = LocalTZ()
log_stream = StringIO()
local_addr: Optional[str] = None
local_url_addr: Optional[str] = None
def set_local_addr(ipv6):
global local_addr
global local_url_addr
local_addr = "::1" if ipv6 else "127.0.0.1"
local_url_addr = "[::1]" if ipv6 else "127.0.0.1"
log_line: Optional[str] = None
def buffer_log_line(message, new_line):
global log_line
line = log_line
if line is None:
now = datetime.now(tz=local_tz)
line = '[%s] ' % now.isoformat()
line += message
if new_line:
log_line = None
return line
else:
log_line = line
return None
# Note: QE's collectinfo_test looks for "ERROR" or "Error" in the
# log messages and if found triggers a fatal error.
def log(message, new_line=True):
global log_stream
if new_line:
message += '\n'
bufline = buffer_log_line(message, new_line)
if bufline is not None:
log_stream.write(bufline)
sys.stderr.write(message)
sys.stderr.flush()
def generate_hash(val):
return hashlib.sha1(val.encode())
class AccessLogProcessor:
salt: str
column_parser: Pattern[str]
urls_to_redact: List[List[Any]]
def __init__(self, salt):
self.salt = salt
self.column_parser = re.compile(
r'(^\S* \S* )(\S*)( \[.*\] \"\S* )(\S*)( .*$)')
self.urls_to_redact = [['/settings/rbac/users',
re.compile(r'\/(?P<user>[^\/\s#&]+)([#&]|$)'),
self._process_user, "user"],
['/settings/rbac/lookupLDAPUser',
re.compile(r'\/(?P<user>[^\s#&]+)'),
self._process_user, "user"],
['/_cbauth/checkPermission',
re.compile(r'user=(?P<user>[^\s&#]+)'),
self._process_user, "user"],
['/pools/default/buckets',
re.compile(r'\/(?:[^\/\s#&]+)\/docs\/'
'(?P<docid>[^\\/\\s#&]+)$'),
self._process_docid, "docid"]]
def _process_url(self, surl):
for conf in self.urls_to_redact:
prefix = conf[0]
if surl[:len(prefix)] == prefix:
return prefix + self._process_url_tail(conf[1], conf[2],
conf[3],
surl[len(prefix):])
return surl
def _process_url_tail(self, rex, fn, key, s):
m = rex.search(s)
if m is not None:
return s[:m.start(key)] + fn(m.group(key)) + s[m.end(key):]
else:
return s
def _process_user(self, user):
if user == '-' or user[0] == '@':
return user
elif user[-3:] == "/UI":
return self._hash(user[:-3]) + "/UI"
else:
return self._hash(user)
def _process_docid(self, docid):
return self._hash(docid)
def _hash(self, token):
return generate_hash(self.salt + token).hexdigest()
def _repl_columns(self, matchobj):
return matchobj.group(1) + \
self._process_user(matchobj.group(2)) + \
matchobj.group(3) + \
self._process_url(matchobj.group(4)) + \
matchobj.group(5)
def do(self, line):
return self.column_parser.sub(self._repl_columns, line)
class RegularLogProcessor:
salt: str
rexes: List[Pattern[str]] = [
re.compile("(<ud>)(.+?)(</ud>)"),
# Redact the rest of the line in the case we encounter
# log-redaction-salt. Needed to redact pre-6.5 debug logs
# as well as occurence in couchbase.log
re.compile("(log-redaction-salt)(.+)")]
def __init__(self, salt):
self.salt = salt
def _hash(self, match):
result = match.group(1)
if match.lastindex == 3:
h = generate_hash(self.salt + match.group(2)).hexdigest()
result += h + match.group(3)
elif match.lastindex == 2:
result += " <redacted>"
return result
def _process_line(self, line):
for rex in self.rexes:
line = rex.sub(self._hash, line)
return line
def do(self, line):
return self._process_line(line)
class CouchbaseLogProcessor(RegularLogProcessor):
def do(self, line):
if "RedactLevel" in line:
# salt + salt to maintain consistency with other
# occurances of hashed salt in the logs.
return "RedactLevel:partial,HashOfSalt:" \
f"{generate_hash(self.salt + self.salt).hexdigest()}\n"
else:
return self._process_line(line)
class ZipStream:
"""
This is a wrapper around a normal ZipFile that offers an interface into it
that lets us systematically write to individual files, in a specific way.
Specifically, we must make sure to properly fill in the 'ZipInfo' with a
compress_type, despite setting it on the main ZipFile upon creation.
Otherwise the files will be written without compression.
Beneath this, the zipfile is given a stream into the underlying file
through the FSyncFile, so that we periodically sync to disk and don't just
do one large fsync at the end.
"""
_fp: FSyncedFile
_zipfile: ZipFile
_prefix: Optional[str]
def __init__(self, zipfile: str, prefix: Optional[str]):
self._fp = FSyncedFile(zipfile, "wb")
self._zipfile = ZipFile(self._fp, mode="w", compression=ZIP_DEFLATED)
self._prefix = prefix
def open(self, path: str) -> "ZippedFileStream":
"""
This will open a specific file in a ZipFile and return a
ZippedFileStream which can be written into.
"""
fullfilename = path
if self._prefix:
fullfilename = f"{self._prefix}/{path}"
zinfo = ZipInfo(fullfilename, date_time=self.get_time_tuple_now())
zinfo.compress_type = ZIP_DEFLATED
zfile: IO[bytes] = self._zipfile.open(zinfo, mode="w")
return ZippedFileStream(path, zfile)
def close(self):
self._fp.flush()
self._zipfile.close()
self._fp.close()
@staticmethod
def get_time_tuple_now():
now = datetime.now()
return (now.year, now.month, now.day, now.hour, now.minute, now.second)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
class ZippedFileStream(Writer):
"""
Individual file inside of a zipfile as a buffered stream object.
"""
_filename: str
_inner: IO[bytes]
def __init__(self, filename: str, inner: IO[bytes]):
super().__init__()
self._filename = filename
self._inner = inner
def write(self, b: ReadableBuffer) -> int:
"""
Overriden write function from Writer.
"""
return write_readable_buffer(b, self._inner)
def close(self):
self.flush()
return self._inner.close()
def flush(self):
return self._inner.flush()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.close()
def write_readable_buffer(b: ReadableBuffer, writer: WriterType) -> int:
return writer.write(convert_to_bytes(b))
def convert_to_bytes(b: ReadableBuffer) -> bytes:
"""
The only reason for this nasty 'if isinstance' chain is that technically
this interface takes a number of different types (as defined by the
ReadableBuffer type) and some require slight conversions before being
passed as bytes to the inner write which only takes bytes as input.
"""
if isinstance(b, (bytes, bytearray)):
return b
if isinstance(b, mmap.mmap):
return b.read()
if isinstance(b, (array.array, memoryview)):
return b.tobytes()
else:
raise Exception("Cannot support this input buffer type")
class RedactStream(Writer):
_inner: WriterType
_salt_value: str
_filename: str
_wraparound: List[str] = []
"""
The redaction stream - redacts lines of text that pass through it.
"""
def __init__(self, inner: WriterType, salt_value: str, filename: str):
super().__init__()
self._inner = inner
self._salt_value = salt_value
self._filename = filename
self._wraparound = []
def write(self, buf: ReadableBuffer) -> int:
"""
Overridden write function of Writer. Decide whether or not to apply the
redaction. Certain filetypes are categorically skipped (.gz, .dmp).
"""
# skip binary files (don't redact)
if self._filename.endswith(BINARY_FILE_EXTS):
return self.write_passthrough(buf)
# normal redaction path
return self.write_redacted(buf)
def write_redacted(self, buf: ReadableBuffer):
"""
Redact, and then write, the buffer. This is slightly more complex than
other parts of the streaming pipeline.
This function takes the buffer, converts it all to a string, and then
splits it into lines. If there are chunks at the end, that aren't
terminated by a newline, we hold onto it until we receive more data
that does.
This list of non-terminated strings will accumulate until we get a
newline, and we can combine all the chunks into a logical line and
pass that to the redactor, which requires the data to be in lines
and not just random chunks of text.
"""
chunk = convert_to_bytes(buf).decode(LATIN1)
lines = chunk.splitlines(keepends=True)
last = None
if not lines[-1].endswith(os.linesep):
last = lines.pop()
written: int = 0
for line in lines:
# if we have a portion leftover, write that first, and then clear
# it so we don't write it again
if self._wraparound:
combined = f"{''.join(self._wraparound)}{line}"
assert(combined.endswith(os.linesep))
written = written + \
write_readable_buffer(self.process_line(combined),
self._inner)
self._wraparound.clear()
else:
# write the normal line
written = written + \
write_readable_buffer(self.process_line(line), self._inner)
if last:
# Append any remaining string to our temporary list of non null
# terminated strings that will eventually be combined as a full
# line to be processed. In practice it doesn't seem like we
# generally end up with more than one chunk in the queue before
# flushing to redactors.
self._wraparound.append(last)
return written
def write_passthrough(self, chunk: ReadableBuffer):
return write_readable_buffer(chunk, self._inner)
def flush(self):
"""
Make sure we flush the remaining wrap-around data. This is especially
important when we finish with a file, but it didn't also end with a
newline.
"""
if self._wraparound:
self._inner.write(''.join(self._wraparound).encode(LATIN1))
self._wraparound.clear()
return self._inner.flush()
def process_line(self, line: str) -> bytes:
return self._redact_line(self._pick_redactor(self._filename),
line).encode(LATIN1)
def _pick_redactor(self, name: str):
if "http_access" in name:
return AccessLogProcessor(self._salt_value)
elif name == DEFAULT_LOG:
return CouchbaseLogProcessor(self._salt_value)
else:
return RegularLogProcessor(self._salt_value)
def _redact_line(self, redactor: LogProcessors, line: str) -> str:
return redactor.do(line)
class DoubleStream(Writer):
_first: Writer
_second: Writer
def __init__(self, first: Writer, second: Writer):
super().__init__()
self._first = first
self._second = second
def write(self, buf: ReadableBuffer) -> int:
first = self._first.write(buf)
second = self._second.write(buf)
self.flush()
return first or second or 0
def flush(self):
self._first.flush()
self._second.flush()
@unique
class Platform(Enum):
SUNOS5 = "sunos5"
SOLARIS = "solaris"
LINUX = "linux"
WIN32 = "win32"
CYGWIN = "cygwin"
DARWIN = "darwin"
class Task:
platforms: List[Platform] = []
output_file: str
description: str = ""
command: Union[str, List[str]] = ""
timeout: Optional[int] = None
use_shell: bool
artifacts: Optional[List[str]] = None
num_samples: int = 1
interval: int = 0
suppress_append_newline: bool = False
to_stdin: Optional[Union[str, Callable[[], str]]] = None
no_header: bool = False
change_dir: Union[bool, str] = False
addenv: Optional[Iterable[Tuple[str, Union[str, Callable[[], str]]]]] = None
privileged: bool = False
is_posix: bool = (os.name == "posix")
extra_flags: Dict[str, str] = {}
zip_relative_path: Optional[str] = None
_task_runner: Optional["TaskRunner"] = None
def __init__(self, description, command, timeout=None,
log_file=DEFAULT_LOG, artifacts=None, num_samples=1,
interval=0, suppress_append_newline=False, to_stdin=None,
no_header=False, change_dir=False, addenv=None,
privileged=False):
self.output_file = log_file
self.description = description
self.command = command
self.timeout = timeout
self.use_shell = not isinstance(self.command, list)
self.artifacts = artifacts
self.num_samples = num_samples
self.interval = interval
self.suppress_append_newline = suppress_append_newline
self.to_stdin = to_stdin
self.no_header = no_header
self.change_dir = change_dir
self.addenv = addenv
self.privileged = privileged
self.is_posix = (os.name == "posix")
def execute(self, outstream: Writer):
log(f"{self.description} ({self.command}) - ", new_line=False)
if not self.no_header:
self.header(outstream, self)
bad_result = None
for i in range(self.num_samples):
if i > 0:
log(f"Taking sample {i + 1} after {self.interval}"
" seconds - ", new_line=False)
time.sleep(self.interval)
res = self.on_execute(outstream)
if res != 0:
bad_result = res
if bad_result:
return bad_result
return 0
def on_execute(self, outstream: Writer):
p = None
extra_flags = self._extra_flags()
try:
p = subprocess.Popen(self.command, bufsize=-1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=self.use_shell,
**extra_flags)
if self.to_stdin and p.stdin:
s = self.to_stdin() if callable(self.to_stdin) else self.to_stdin
p.stdin.write(s.encode())
if p.stdin:
p.stdin.close()
except OSError as e:
# if use_shell is False then Popen may raise exception
# if binary is missing. In this case we mimic what
# shell does. Namely, complaining to stderr and
# setting non-zero status code. It's might also
# automatically handle things like "failed to fork due
# to some system limit".
outstream.write(
f"Failed to execute {self.command}: {e}\n".encode())
return 127
except IOError as e:
if e.errno == errno.EPIPE:
outstream.write(
f"Ignoring broken pipe on stdin for {self.command}\n".encode())
else:
raise
if p:
stdout = p.stdout
else:
raise Exception("No stdout attached to process")
from threading import Timer, Event
timer = None
timer_fired: Event = Event()
if self.timeout is not None and self.can_kill(p):
def on_timeout():
try:
self._kill(p)
except BaseException:
# the process might have died already
pass
timer_fired.set()
timer = Timer(self.timeout, on_timeout)
timer.start()
try:
last_char_written = None
while True and stdout is not None:
data: bytes = stdout.read(READ_SIZE)
if not data:
break
outstream.write(data)
last_char_written = data[-1:]
self.maybe_append_newline(outstream, last_char_written)
finally:
if timer is not None:
timer.cancel()
timer.join()
# there's a tiny chance that command succeeds just before
# timer is fired; that would result in a spurious timeout
# message
if timer_fired.is_set():
outstream.write(f"`{self.command}` timed out "
f"after {self.timeout} seconds\n".encode())
log(f"[Command timed out after {self.timeout} seconds] - ",
new_line=False)
if stdout:
stdout.close()
code = 0
if p:
code = p.wait()
if stdout:
stdout.close()
outstream.flush()
return code
def will_run(self):
"""Determine if this task will run on this platform."""
return Platform[sys.platform.upper()] in self.platforms
def satisfies_preconditions(self) -> bool:
if self.privileged and os.getuid() != 0:
log("skipped (needs root privs)")
return False
return True
def maybe_append_newline(self, fp, last_char: Optional[bytes]):
"""Append a newline (if appropriate) to ensure that the next
header starts on a new line.
"""
if self.suppress_append_newline:
return
if self.no_header:
# The "no_header" attribute indicates that this task
# produces a single result which does not contain a header.
# Thus, we shouldn't append a new line to the result.
return
if last_char and last_char.decode() != os.linesep:
fp.write(os.linesep.encode(LATIN1))
@staticmethod
def log_result(result):
if result == 0 or result is None:
log("OK")
else:
log(f"Exit code {result}")
@staticmethod
def header(fp: Writer, task: "Task"):
separator = "=" * 78
subtitle = task.command
if isinstance(task.command, list):
subtitle = " ".join(task.command)
message = f"{separator}\n{task.description}\n{subtitle}\n{separator}\n"
fp.write(message.encode())
def can_kill(self, p: subprocess.Popen):
if self.is_posix:
return True
return hasattr(p, "kill")
def set_task_runner(self, runner: "TaskRunner"):
self._task_runner = runner
def _kill(self, p: subprocess.Popen):
if self.is_posix:
group_pid = os.getpgid(p.pid)
os.killpg(group_pid, signal.SIGKILL)
else:
p.kill()
def _extra_flags(self) -> Dict[str, Any]:
flags = self._env_flags()
flags.update(self._platform_popen_flags())
flags.update(self._cwd_flags())
return flags
def _cwd_flags(self) -> Dict[str, str]:
flags = {}
if self.change_dir and self._task_runner:
cwd = self._task_runner.tmpdir
if isinstance(self.change_dir, str):
cwd = self.change_dir
flags["cwd"] = cwd
return flags
def _platform_popen_flags(self) -> Dict[str, Any]:
flags = {}
if self.is_posix:
flags["preexec_fn"] = os.setpgrp
return flags
def _env_flags(self) -> Dict[str, Any]:
flags = {}
if self.addenv:
addenv = []
for (k, v) in self.addenv:
addenv.append((k, v() if callable(v) else v))
env = os.environ.copy()
env.update(addenv)
flags["env"] = env
return flags
def __repr__(self):
return f"<{self.__class__.__qualname__}: {self.__dict__}>"
def __str__(self):
return f"<{self.__class__.__qualname__}: {self.__dict__}>"
class SolarisTask(Task):
platforms = [Platform.SUNOS5, Platform.SOLARIS]
class LinuxTask(Task):
platforms = [Platform.LINUX]
class WindowsTask(Task):
platforms = [Platform.WIN32, Platform.CYGWIN]
class MacOSXTask(Task):
platforms = [Platform.DARWIN]
class UnixTask(SolarisTask, LinuxTask, MacOSXTask):
platforms = SolarisTask.platforms + LinuxTask.platforms \
+ MacOSXTask.platforms
class AllOsTask(UnixTask, WindowsTask):
platforms = UnixTask.platforms + WindowsTask.platforms
class LiteralTask(AllOsTask):
literal: str
def __init__(self, description, literal, timeout=None,
log_file=DEFAULT_LOG, no_header=False):
self.description = description
self.literal = literal
self.timeout = timeout
self.output_file = log_file
self.no_header = no_header
def on_execute(self, outstream: Writer):
literal = f"{self.literal}\n"
outstream.write(literal.encode())
outstream.flush()
return 0
class CollectFileTask(AllOsTask):
def __init__(self, description, file_path, zip_relative: str = ""):
self.description = description
self.output_file = file_path
if zip_relative == "":
zip_relative = os.path.basename(file_path)
self.zip_relative_path = zip_relative
self.no_header = True
def on_execute(self, outstream: Writer):
try:
with open(self.output_file, "rb") as f:
while True:
res = f.read(READ_SIZE)
if not res:
break
outstream.write(res)
outstream.flush()
return 0
except FileNotFoundError:
log(f"File doesn't exist: {self.output_file} -- ", new_line=False)
return 1
@staticmethod
def create_directory_collection_tasks(dir_path, relative_path_base):
tasks = []
for dirpath, _, filenames in os.walk(dir_path):
for f in filenames:
full_path = os.path.join(dirpath, f)
relative_path = os.path.relpath(full_path, dir_path)
path_in_zip = os.path.join(relative_path_base, relative_path)
task = CollectFileTask(f"Collecting {full_path}",
full_path,
zip_relative=path_in_zip)
tasks.append(task)
return tasks
def satisfies_preconditions(self) -> bool:
return os.path.exists(self.output_file)
class CollectFFDCFileTask(CollectFileTask):
def __init__(self, description, file_path, redact, salt_value, zip_relative: str = ""):
if zip_relative == "":
zip_relative = os.path.basename(file_path.removesuffix(".gz"))
super().__init__(description, file_path, zip_relative)
self.salt_value = salt_value
self.redact = redact
def _copy_content(self, src, outstream: Writer):
file_content = src.read(READ_SIZE)
if file_content:
# only redact non-binary content (binary content should only be nested gzip)
if self.redact and not file_content.startswith(b'\x1f\x8b'):
rs = RedactStream(outstream, self.salt_value, self.output_file)
while file_content:
rs.write(file_content)
file_content = src.read(READ_SIZE)
rs.flush()
else:
while file_content:
outstream.write(file_content)
file_content = src.read(READ_SIZE)
outstream.flush()
def on_execute(self, outstream: Writer):
try:
with gzip.open(self.output_file, "rb") as src:
self._copy_content(src, outstream)
return 0
except gzip.BadGzipFile:
# if not a gzip file, open and copy as a regular file
with open(self.output_file, "rb") as src: