forked from couchbase/ns_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbcollect_info
executable file
·2275 lines (1893 loc) · 84.3 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 io
import configparser
from datetime import datetime, timedelta, tzinfo
from io import BytesIO, StringIO
from collections import namedtuple
CollectedFile = namedtuple('CollectedFile', ['filename', 'relative_name'])
# 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 FSyncedFile(object):
SYNC_BYTES = 16 * 1024 * 1024
def __init__(self, *args, **kwargs):
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 close(self):
self._sync()
self._file.close()
def write(self, buf):
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 = None
local_url_addr = 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 = 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:
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"],
['/_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:
rexes = [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:%s\n' \
% generate_hash(self.salt + self.salt).hexdigest()
else:
return self._process_line(line)
class LogRedactor:
def __init__(self, salt, tmpdir, default_name):
self.default_name = default_name
self.target_dir = os.path.join(tmpdir, "redacted")
os.makedirs(self.target_dir)
self.access_log = AccessLogProcessor(salt)
self.couchbase_log = CouchbaseLogProcessor(salt)
self.regular_log = RegularLogProcessor(salt)
def _process_file(self, ifile, ofile, processor):
# Don't try to catch any errors here as we want failures (e.g.
# due to disk full) to abort the collection. This will allow
# the cause of the failure to be fixed and collection retried.
# The one exception is when creating the directory for the output
# file which may already exist (e.g. stats related files in the
# same directory).
with open(ifile, 'r', newline='', encoding=LATIN1) as inp:
try:
os.makedirs(os.path.dirname(ofile))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with FSyncedFile(ofile, 'w+', newline='', encoding=LATIN1) as out:
for line in inp:
out.write(processor.do(line))
def redact_file(self, name, ifile, relative_name):
ofile = os.path.join(self.target_dir, relative_name)
if "http_access" in name:
self._process_file(ifile, ofile, self.access_log)
elif name == self.default_name:
self._process_file(ifile, ofile, self.couchbase_log)
else:
self._process_file(ifile, ofile, self.regular_log)
return ofile
class Task(object):
privileged = False
no_header = False
num_samples = 1
interval = 0
def __init__(self, description, command, timeout=None, **kwargs):
self.description = description
self.command = command
self.timeout = timeout
self.__dict__.update(kwargs)
self._is_posix = (os.name == 'posix')
def _platform_popen_flags(self):
flags = {}
if self._is_posix:
flags['preexec_fn'] = os.setpgrp
return flags
def _can_kill(self, p):
if self._is_posix:
return True
return hasattr(p, 'kill')
def _kill(self, p):
if self._is_posix:
group_pid = os.getpgid(p.pid)
os.killpg(group_pid, signal.SIGKILL)
else:
p.kill()
def _env_flags(self):
flags = {}
if hasattr(self, 'addenv'):
env = os.environ.copy()
env.update(self.addenv)
flags['env'] = env
return flags
def _cwd_flags(self):
flags = {}
if getattr(self, 'change_dir', False):
cwd = self._task_runner.tmpdir
if isinstance(self.change_dir, str):
cwd = self.change_dir
flags['cwd'] = cwd
return flags
def _extra_flags(self):
flags = self._env_flags()
flags.update(self._platform_popen_flags())
flags.update(self._cwd_flags())
return flags
def set_task_runner(self, runner):
self._task_runner = runner
def execute(self, fp):
"""Run the task"""
use_shell = not isinstance(self.command, list)
extra_flags = self._extra_flags()
try:
p = subprocess.Popen(self.command, bufsize=-1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=use_shell,
**extra_flags)
if hasattr(self, 'to_stdin'):
p.stdin.write(self.to_stdin.encode())
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".
fp.write(f"Failed to execute {self.command}: {e}\n".encode())
return 127
except IOError as e:
if e.errno == errno.EPIPE:
fp.write(f"Ignoring broken pipe on stdin for {self.command}\n".encode())
else:
raise
from threading import Timer, Event
timer = None
timer_fired = 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()
last_char_written = None
try:
while True:
data = p.stdout.read(64 * 1024)
if not data:
break
fp.write(data)
last_char_written = data[-1:]
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.isSet():
fp.write(f"`{self.command}` timed out after {self.timeout} seconds\n".encode())
log("[Command timed out after %s seconds] - " %
(self.timeout), new_line=False)
self.maybe_append_newline(fp, last_char_written)
return p.wait()
def maybe_append_newline(self, fp, last_char):
"""Append a newline (if appropriate) to ensure that the next
header starts on a new line.
"""
if hasattr(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 != b'\n':
fp.write(b'\n')
def will_run(self):
"""Determine if this task will run on this platform."""
return sys.platform in self.platforms
class TaskRunner(object):
default_name = "couchbase.log"
def __init__(self, verbosity=0, task_regexp='', tmp_dir=None,
salt_value=""):
# A dictionary with an instance of CollectedFile as the key and
# full path name as the value
self.files = {}
self._fps = {}
self.verbosity = verbosity
self.start_time = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
self.salt_value = salt_value
# Depending on platform, mkdtemp() may act unpredictably if passed an
# empty string.
if not tmp_dir:
tmp_dir = None
else:
tmp_dir = os.path.abspath(os.path.expanduser(tmp_dir))
try:
self.tmpdir = tempfile.mkdtemp(dir=tmp_dir)
except OSError as e:
log("Could not use temporary dir {0}: {1}".format(tmp_dir, e))
sys.exit(1)
# If a dir wasn't passed by --tmp-dir, check if the env var was set and
# if we were able to use it
if not tmp_dir and os.getenv("TMPDIR") and os.path.split(
self.tmpdir)[0] != os.getenv("TMPDIR"):
log("Could not use TMPDIR {0}".format(os.getenv("TMPDIR")))
log("Using temporary dir {0}".format(os.path.split(self.tmpdir)[0]))
self.task_regexp = re.compile(task_regexp)
AltExit.register(self.finalize)
def close_files(self):
for fp in self._fps.values():
try:
fp.close()
except:
pass
def finalize(self):
shutil.rmtree(self.tmpdir, ignore_errors=True)
def collect_file(self, filename, relative_name=None):
"""Add a file to the list of files collected. Used to capture the exact
file (including timestamps) from the Couchbase instance.
filename - Absolute path to file to collect.
relative_name - Path to use in the final .zip bundle. Typically this
is the basename of the path. But can include a
directory structure if that is wanted in the bundle.
"""
if relative_name is None:
relative_name = os.path.basename(filename)
collected_file = CollectedFile(filename, relative_name)
if collected_file not in self.files:
if os.path.isfile(filename):
self.files[collected_file] = filename
else:
log(f"Failed to collect file {filename}: file does not exist")
else:
log("Unable to collect file '%s' - already collected." % filename)
def collect_dir(self, directory_path, relative_path_base):
for dirpath, dirnames, filenames in os.walk(directory_path):
for f in filenames:
full_path = os.path.join(dirpath, f)
relative_path = os.path.relpath(full_path, directory_path)
path_in_zip = os.path.join(relative_path_base, relative_path)
self.collect_file(full_path, path_in_zip)
def header(self, fp, title, subtitle):
separator = '=' * 78
if isinstance(subtitle, list):
subtitle = " ".join(subtitle)
message = f"{separator}\n{title}\n{subtitle}\n{separator}\n"
fp.write(message.encode())
fp.flush()
def log_result(self, result):
if result == 0:
log("OK")
else:
log("Exit code %d" % result)
def run_tasks(self, tasks):
for task in tasks:
self.run(task)
def run(self, task):
if self.task_regexp.match(task.description) is None:
log("Skipping task %s because "
"it doesn't match '%s'" % (task.description,
self.task_regexp.pattern))
else:
self._run(task)
def _get_fp(self, path):
if path not in self._fps:
self._fps[path] = FSyncedFile(path, 'wb+')
return self._fps[path]
def _run(self, task):
"""Run a task with a file descriptor corresponding to its log file"""
if task.will_run():
log("%s (%s) - " % (task.description, task.command), new_line=False)
if task.privileged and os.getuid() != 0:
log("skipped (needs root privs)")
return
task.set_task_runner(self)
filename = getattr(task, 'log_file', self.default_name)
collected_file = CollectedFile(filename, os.path.basename(filename))
fullname = os.path.join(self.tmpdir, collected_file.filename)
self.files.setdefault(collected_file, fullname)
fp = self._get_fp(fullname)
if not task.no_header:
self.header(fp, task.description, task.command)
for i in range(task.num_samples):
if i > 0:
log("Taking sample %d after %f seconds - " %
(i + 1, task.interval), new_line=False)
time.sleep(task.interval)
result = task.execute(fp)
self.log_result(result)
for artifact in getattr(task, 'artifacts', []):
path = artifact
if not os.path.isabs(path):
# We assume that "relative" artifacts are produced
# in the self.tmpdir
path = os.path.join(self.tmpdir, path)
self.collect_file(path)
elif self.verbosity >= 2:
log('Skipping "%s" (%s): not for platform %s' %
(task.description, task.command, sys.platform))
def literal(self, description, value, **kwargs):
self.run(LiteralTask(description, value, **kwargs))
def redact_and_zip(self, filename, node):
files = []
redactor = LogRedactor(self.salt_value, self.tmpdir, self.default_name)
for collected_file, fullname in self.files.items():
name = collected_file.filename
if "users.dets" in name:
continue
elif name.lower().endswith(('.gz', '.dmp')):
files.append((fullname, collected_file.relative_name))
else:
redacted_file = redactor.redact_file(
name, fullname, collected_file.relative_name)
files.append((redacted_file, collected_file.relative_name))
prefix = f"cbcollect_info_{node}_{self.start_time}"
TaskRunner.make_zip(prefix, filename, files)
def zip(self, filename, node):
prefix = f"cbcollect_info_{node}_{self.start_time}"
files = []
for collected_file, fullname in self.files.items():
files.append((fullname, collected_file.relative_name))
TaskRunner.make_zip(prefix, filename, files)
@staticmethod
def make_zip(prefix, filename, files):
from zipfile import ZipFile, ZIP_DEFLATED
with FSyncedFile(filename, 'w+b') as fp:
zf = ZipFile(fp, mode='w', compression=ZIP_DEFLATED)
try:
for name, relative_name in files:
try:
zf.write(name, f"{prefix}/{relative_name}")
except IOError as e:
# Skipping file(s) we cannot zip. The file may have been
# purged from under us.
log("Failed to zip file %s, error (%s): %s" %
(name, e.errno, e.strerror))
finally:
zf.close()
class SolarisTask(Task):
platforms = ['sunos5', 'solaris']
class LinuxTask(Task):
platforms = ['linux']
class WindowsTask(Task):
platforms = ['win32', 'cygwin']
class MacOSXTask(Task):
platforms = ['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):
def __init__(self, description, literal, **kwargs):
self.description = description
self.command = ''
self.literal = literal
self.__dict__.update(kwargs)
def execute(self, fp):
fp.write(self.literal.encode() + b'\n')
return 0
class CollectDirectory(AllOsTask):
def __init__(self, description, dir_path, relative_output_path, **kwargs):
self.description = description
self.command = ''
self.dir_path = dir_path
self.relative_output_path = relative_output_path
self.__dict__.update(kwargs)
def execute(self, fp):
self._task_runner.collect_dir(self.dir_path, self.relative_output_path)
fp.write(f"Collected directory {self.dir_path}\n".encode())
return 0
class CollectFile(AllOsTask):
def __init__(self, description, file_path, **kwargs):
self.description = description
self.command = ''
self.file_path = file_path
self.__dict__.update(kwargs)
def execute(self, fp):
self._task_runner.collect_file(self.file_path)
fp.write(f"Collected file {self.file_path}\n".encode())
return 0
def make_curl_task(name, user, password, url,
timeout=60, log_file="couchbase.log", base_task=AllOsTask,
**kwargs):
return base_task(name, ["curl", "-sS", "--proxy", "", "-K-", url],
timeout=timeout,
log_file=log_file,
to_stdin="--user %s:%s" % (user, password),
**kwargs)
def make_curl_post_task(name, user, password, url, timeout=60,
log_file="couchbase.log", post_data="",
base_task=AllOsTask, **kwargs):
return base_task(name, ["curl", "-sS", "-X", "POST", "--proxy", "", "-K-",
url],
timeout=timeout,
log_file=log_file,
to_stdin=f"--user {user}:{password}\n --data {post_data}",
**kwargs)
def make_cbstats_task(kind, memcached_pass, guts):
port = read_guts(guts, "memcached_dedicated_port")
user = read_guts(guts, "memcached_admin")
return AllOsTask("memcached stats %s" % kind,
flatten(["cbstats", "-a", "%s:%s" %
(local_url_addr, port), kind, "-u", user]),
log_file="stats.log",
timeout=60,
addenv=[("CB_PASSWORD", memcached_pass)])
def get_local_token(guts):
path = read_guts(guts, "localtoken_path")
token = ""
try:
with open(path, 'r') as f:
token = f.read().rstrip('\n')
except IOError as e:
log("I/O error(%s): %s" % (e.errno, e.strerror))
return token
def get_diag_password(guts):
port = read_guts(guts, "rest_port")
pwd = get_local_token(guts)
url = "http://%s:%s/diag/password" % (local_url_addr, port)
command = ["curl", "-sS", "--proxy", "", "-u", "@localtoken:%s" % pwd, url]
# Don't append a newline to the result, since that would corrupt
# the password.
task = AllOsTask("get diag password", command, timeout=60,
suppress_append_newline=True)
output_bytes = BytesIO()
status = task.execute(output_bytes)
output = output_bytes.getvalue().decode(LATIN1)
if status == 0:
return output
log(output)
return ""
def make_query_statement_task(statement, user, password, port,
logfile="couchbase.log", **kwargs):
url = "http://%s:%s/query/service?statement=%s" % (
local_url_addr, port, urllib.parse.quote(statement))
return make_curl_task(name="Result of query statement \'%s\'" % statement,
user=user, password=password, url=url,
log_file=logfile, **kwargs)
def make_cbas_statement_task(statement, user, password, port):
url = "http://%s:%s/analytics/service/diagnostics?statement=%s" % (
local_url_addr, port, urllib.parse.quote(statement))
return make_curl_task(name="Result of query statement \'%s\'" % statement,
user=user, password=password, url=url)
def make_index_task(name, api, passwd, index_port, logfile="couchbase.log", **kwargs):
index_url = f'http://{local_url_addr}:{index_port}/{api}'
return make_curl_task(name, "@", passwd, index_url, log_file=logfile, **kwargs)
def make_golang_profile_tasks(service_name, passwd, port, log_prefix, no_header=True, **kwargs):
"""
Helper function to create the various tasks needed to collect profiling
information from Golang components
:param service_name: The service name, for example 'Query'
:param passwd: The password used to auth against the API
:param port: The port used to connect to the API on
:param log_prefix: String to append to the start of each log file
:param no_header: Whether to append the usual command header to the
log file, defaults to True
:returns: A list of tasks to run
"""
# A list of tuples containing the APIs that we are going to hit.
# The tuple is in the format (Description, Log Postfix, API URL).
# If new profiling is ever needed, can add a new item to this list.
apis = [('Go Routine Dump', '_pprof', 'debug/pprof/goroutine?debug=1'),
('CPU Profile', '_cprof', 'debug/pprof/profile?seconds=30'),
('Memory Profile', '_mprof', 'debug/pprof/heap?debug=1')]
# Iterate through each API, create the full URL, and then append the
# resulting cURL task to the list of tasks
base_url = f'http://{local_url_addr}:{port}'
tasks = []
for descr, postfix, api in apis:
api_url = f'{base_url}/{api}'
name = f'{service_name} {descr}: '
logfile = f'{log_prefix}{postfix}.log'
tasks.append(make_curl_task(name, '@', passwd, api_url, log_file=logfile,
no_header=no_header, **kwargs))
return tasks
def make_redaction_task():
return LiteralTask("Log Redaction", "RedactLevel:none")
def basedir():
# We are installed in $INSTALL_DIR/lib/python, so need to go up three
# levels
return os.path.normpath(
os.path.join(
os.path.abspath(__file__),
'..', '..', '..'
)
)
def make_event_log_task():
from datetime import datetime, timedelta
# I found that wmic ntevent can be extremely slow; so limiting the output
# to approximately last month
limit = datetime.today() - timedelta(days=31)
limit = limit.strftime('%Y%m%d000000.000000-000')
return WindowsTask(
"Event log",
"wmic ntevent where "
"\""
"(LogFile='application' or LogFile='system') and "
"EventType<3 and TimeGenerated>'%(limit)s'"
"\" "
"get TimeGenerated,LogFile,SourceName,EventType,Message "
"/FORMAT:list" %
locals())
def make_os_tasks():
programs = " ".join(["moxi", "memcached", "beam.smp",
"couch_compact", "godu", "sigar_port",
"cbq-engine", "indexer", "projector", "goxdcr",
"cbft", "eventing-producer", "eventing-consumer"])
_tasks = [
UnixTask("uname", "uname -a"),
UnixTask("time and TZ", "date; date -u"),
UnixTask("ntp time",
"ntpdate -q pool.ntp.org || "
"nc time.nist.gov 13 || "
"netcat time.nist.gov 13", timeout=60),
UnixTask("ntp peers", "ntpq -p"),
UnixTask("raw /etc/sysconfig/clock", "cat /etc/sysconfig/clock"),
UnixTask("raw /etc/timezone", "cat /etc/timezone"),
WindowsTask("System information", "systeminfo"),
WindowsTask("Computer system", "wmic computersystem"),
WindowsTask("Computer OS", "wmic os"),
LinuxTask("System Hardware", "lshw -json || lshw"),
SolarisTask("Process list snapshot",
"prstat -a -c -n 100 -t -v -L 1 10"),
SolarisTask("Process list", "ps -ef"),
SolarisTask("Service configuration", "svcs -a"),
SolarisTask("Swap configuration", "swap -l"),
SolarisTask("Disk activity", "zpool iostat 1 10"),
SolarisTask("Disk activity", "iostat -E 1 10"),
LinuxTask("Process list snapshot",
"export TERM=''; top -Hb -n1 || top -H n1"),
LinuxTask(
"Process list",
"ps -AwwL -o user,pid,lwp,ppid,nlwp,pcpu,maj_flt,min_flt,pri,nice,vsize,rss,tty,stat,wchan:12,start,"
"bsdtime,comm,command"),
LinuxTask("Raw /proc/buddyinfo", "cat /proc/buddyinfo"),
LinuxTask("Raw /proc/meminfo", "cat /proc/meminfo"),
LinuxTask("Raw /proc/pagetypeinfo", "cat /proc/pagetypeinfo"),
LinuxTask("Raw /proc/zoneinfo", "cat /proc/zoneinfo"),
LinuxTask("Raw /proc/vmstat", "cat /proc/vmstat"),
LinuxTask("Raw /proc/mounts", "cat /proc/mounts"),
LinuxTask("Raw /proc/partitions", "cat /proc/partitions"),
LinuxTask("Raw /proc/diskstats",
"cat /proc/diskstats; echo ''", num_samples=10, interval=1),
LinuxTask("Raw /proc/interrupts", "cat /proc/interrupts"),
LinuxTask("Swap configuration", "free -t"),
LinuxTask("Swap configuration", "swapon -s"),
LinuxTask("Kernel modules", "lsmod"),
LinuxTask("Distro version", "cat /etc/redhat-release"),
LinuxTask("Distro version", "cat /etc/oracle-release"),
LinuxTask("Distro version", "lsb_release -a"),
LinuxTask("Distro version", "cat /etc/SuSE-release"),
LinuxTask("Distro version", "cat /etc/issue"),
LinuxTask("Distro version", "cat /etc/os-release"),
LinuxTask("Distro version", "cat /etc/system-release"),
LinuxTask("Installed software", "rpm -qa"),
LinuxTask("Ksplice updates", "uptrack-show"),
LinuxTask("Hot fix list", "rpm -V couchbase-server"),
# NOTE: AFAIK columns _was_ necessary, but it doesn't appear to be
# required anymore. I.e. dpkg -l correctly detects stdout as not a
# tty and stops playing smart on formatting. Lets keep it for few
# years and then drop, however.
LinuxTask("Installed software", "COLUMNS=300 dpkg -l"),
# NOTE: -V is supported only from dpkg v1.17.2 onwards.
LinuxTask("Hot fix list", "COLUMNS=300 dpkg -V couchbase-server"),
LinuxTask(
"Extended iostat",
"iostat -x -p ALL 1 10 || iostat -x 1 10"),
LinuxTask("Core dump settings",
"find /proc/sys/kernel -type f -name '*core*' -print -exec cat '{}' ';'"),
UnixTask("sysctl settings", "sysctl -a"),
LinuxTask("Relevant lsof output",
"echo %(programs)s | xargs -n1 pgrep | xargs -n1 -r -- lsof -n -p" % locals()),
LinuxTask("LVM info", "lvdisplay"),
LinuxTask("LVM info", "vgdisplay"),
LinuxTask("LVM info", "pvdisplay"),
LinuxTask("Block device queue settings",
"find /sys/block/*/queue /sys/block/*/device/queue_* -type f | xargs grep -vH xxxx | sort"),
MacOSXTask("Process list snapshot", "top -l 1"),
MacOSXTask("Disk activity", "iostat 1 10"),
MacOSXTask("Process list",
"ps -Aww -o user,pid,lwp,ppid,nlwp,pcpu,pri,nice,vsize,rss,tty,"
"stat,wchan:12,start,bsdtime,command"),