summaryrefslogtreecommitdiff
path: root/buildscripts/resmokelib/hang_analyzer/dumper.py
blob: 385dfa8827905ad2bb93049f8c25e132ba9ef6df (plain)
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
"""Tools to dump debug info for each OS."""

import itertools
import logging
import os
import sys
import tempfile
from abc import ABCMeta, abstractmethod
from collections import namedtuple
from distutils import spawn  # pylint: disable=no-name-in-module

from buildscripts.resmokelib.hang_analyzer.process import call, callo, find_program
from buildscripts.resmokelib.hang_analyzer.process_list import Pinfo

Dumpers = namedtuple('Dumpers', ['dbg', 'jstack'])


def get_dumpers(root_logger: logging.Logger, dbg_output: str):
    """
    Return OS-appropriate dumpers.

    :param root_logger: Top-level logger
    :param dbg_output: 'stdout' or 'file'
    """

    dbg = None
    jstack = None
    if sys.platform.startswith("linux"):
        dbg = GDBDumper(root_logger, dbg_output)
        jstack = JstackDumper()
    elif sys.platform == "win32" or sys.platform == "cygwin":
        dbg = WindowsDumper(root_logger, dbg_output)
        jstack = JstackWindowsDumper()
    elif sys.platform == "darwin":
        dbg = LLDBDumper(root_logger, dbg_output)
        jstack = JstackDumper()

    return Dumpers(dbg=dbg, jstack=jstack)


class Dumper(metaclass=ABCMeta):
    """
    Abstract base class for OS-specific dumpers.

    :param dbg_output: 'stdout' or 'file'
    :param root_logger: Top-level logger
    """

    def __init__(self, root_logger: logging.Logger, dbg_output: str):
        """Initialize dumper."""
        self._root_logger = root_logger
        self._dbg_output = dbg_output

    @abstractmethod
    def dump_info(  # pylint: disable=too-many-arguments,too-many-locals
            self,
            pinfo: Pinfo,
            take_dump: bool,
    ):
        """
        Perform dump for a process.

        :param pinfo: A Pinfo describing the process
        :param take_dump: Whether to take a core dump
        """
        raise NotImplementedError("dump_info must be implemented in OS-specific subclasses")

    @abstractmethod
    def get_dump_ext(self):
        """Return the dump file extension."""
        raise NotImplementedError("get_dump_ext must be implemented in OS-specific subclasses")

    @abstractmethod
    def _find_debugger(self, debugger):
        """
        Find the installed debugger.

        :param debugger: debugger executable.
        """
        raise NotImplementedError("_find_debugger must be implemented in OS-specific subclasses")

    @abstractmethod
    def _prefix(self):
        """Return the commands to set up a debugger process."""
        raise NotImplementedError("_prefix must be implemented in OS-specific subclasses")

    @abstractmethod
    def _process_specific(self, pinfo: Pinfo, take_dump: bool, logger: logging.Logger = None):
        """
        Return the commands that attach to each process, dump info and detach.

        :param pinfo: A Pinfo describing the process
        :param take_dump: Whether to take a core dump
        :param logger: Logger to output dump info to
        """
        raise NotImplementedError("_process_specific must be implemented in OS-specific subclasses")

    @abstractmethod
    def _postfix(self):
        """Return the commands to exit the debugger."""
        raise NotImplementedError("_postfix must be implemented in OS-specific subclasses")


class WindowsDumper(Dumper):
    """WindowsDumper class."""

    def _find_debugger(self, debugger):
        """Find the installed debugger."""
        # We are looking for c:\Program Files (x86)\Windows Kits\8.1\Debuggers\x64
        cdb = spawn.find_executable(debugger)
        if cdb is not None:
            return cdb
        from win32com.shell import shell, shellcon

        # Cygwin via sshd does not expose the normal environment variables
        # Use the shell api to get the variable instead
        root_dir = shell.SHGetFolderPath(0, shellcon.CSIDL_PROGRAM_FILESX86, None, 0)

        # Construct the debugger search paths in most-recent order
        debugger_paths = [os.path.join(root_dir, "Windows Kits", "10", "Debuggers", "x64")]
        for idx in reversed(range(0, 2)):
            debugger_paths.append(
                os.path.join(root_dir, "Windows Kits", "8." + str(idx), "Debuggers", "x64"))

        for dbg_path in debugger_paths:
            self._root_logger.info("Checking for debugger in %s", dbg_path)
            if os.path.exists(dbg_path):
                return os.path.join(dbg_path, debugger)

        return None

    def _prefix(self):
        """Return the commands to set up a debugger process."""
        cmds = [
            ".symfix",  # Fixup symbol path
            "!sym noisy",  # Enable noisy symbol loading
            ".symopt +0x10",  # Enable line loading (off by default in CDB, on by default in WinDBG)
            ".reload",  # Reload symbols
        ]

        return cmds

    def _process_specific(self, pinfo, take_dump, logger=None):
        """Return the commands that attach to each process, dump info and detach."""
        assert isinstance(pinfo.pidv, int)

        dump_command = ""
        if take_dump:
            # Dump to file, dump_<process name>.<pid>.mdmp
            dump_file = "dump_%s.%d.%s" % (os.path.splitext(pinfo.name)[0], pinfo.pidv,
                                           self.get_dump_ext())
            dump_command = ".dump /ma %s" % dump_file
            self._root_logger.info("Dumping core to %s", dump_file)

        cmds = [
            "!peb",  # Dump current exe, & environment variables
            "lm",  # Dump loaded modules
            dump_command,
            "!uniqstack -pn",  # Dump All unique Threads with function arguments
            "!cs -l",  # Dump all locked critical sections
            ".detach",  # Detach
        ]

        return cmds

    def _postfix(self):
        """Return the commands to exit the debugger."""
        cmds = [
            "q"  # Quit
        ]

        return cmds

    def dump_info(  # pylint: disable=too-many-arguments
            self, pinfo, take_dump):
        """Dump useful information to the console."""
        debugger = "cdb.exe"
        dbg = self._find_debugger(debugger)

        if dbg is None:
            self._root_logger.warning("Debugger %s not found, skipping dumping of %s", debugger,
                                      str(pinfo.pidv))
            return

        self._root_logger.info("Debugger %s, analyzing %s processes with PIDs %s", dbg, pinfo.name,
                               str(pinfo.pidv))

        # TODO: SERVER-48449
        for pid in pinfo.pidv:
            logger = _get_process_logger(self._dbg_output, pinfo.name, pid=pid)

            process = Pinfo(name=pinfo.name, pidv=pid)
            cmds = self._prefix() + self._process_specific(process, take_dump) + self._postfix()

            call([dbg, '-c', ";".join(cmds), '-p', str(pid)], logger)

            self._root_logger.info("Done analyzing %s process with PID %d", pinfo.name, pid)

    def get_dump_ext(self):
        """Return the dump file extension."""
        return "mdmp"


# LLDB dumper is for MacOS X
class LLDBDumper(Dumper):
    """LLDBDumper class."""

    @staticmethod
    def _find_debugger(debugger):
        """Find the installed debugger."""
        return find_program(debugger, ['/usr/bin'])

    def _prefix(self):
        pass

    def _process_specific(self, pinfo, take_dump, logger=None):
        """Return the commands that attach to each process, dump info and detach."""
        cmds = []
        dump_files = self._dump_files(pinfo)
        for pid in pinfo.pidv:
            dump_command = ""
            if take_dump:
                # Dump to file, dump_<process name>.<pid>.core
                dump_file = dump_files[pid]
                dump_command = "process save-core %s" % dump_file
                self._root_logger.info("Dumping core to %s", dump_file)

            cmds += [
                "platform shell kill -CONT %d" % pid,
                "attach -p %d" % pid,
                "target modules list",
                "thread backtrace all",
                dump_command,
                "process detach",
                "platform shell kill -STOP %d" % pid,
            ]

        return cmds

    def _postfix(self):
        """Return the commands to exit the debugger."""
        cmds = [
            "settings set interpreter.prompt-on-quit false",
            "quit",
        ]

        return cmds

    def dump_info(self, pinfo, take_dump):
        """Dump info."""
        debugger = "lldb"
        dbg = self._find_debugger(debugger)
        logger = _get_process_logger(self._dbg_output, pinfo.name)

        if dbg is None:
            self._root_logger.warning("Debugger %s not found, skipping dumping of %s", debugger,
                                      str(pinfo.pidv))
            return

        self._root_logger.info("Debugger %s, analyzing %s processes with PIDs %s", dbg, pinfo.name,
                               str(pinfo.pidv))

        lldb_version = callo([dbg, "--version"], logger)

        logger.info(lldb_version)

        # Do we have the XCode or LLVM version of lldb?
        # Old versions of lldb do not work well when taking commands via a file
        # XCode (7.2): lldb-340.4.119
        # LLVM - lldb version 3.7.0 ( revision )

        if 'version' not in lldb_version:
            # We have XCode's lldb
            lldb_version = lldb_version[lldb_version.index("lldb-"):]
            lldb_version = lldb_version.replace('lldb-', '')
            lldb_major_version = int(lldb_version[:lldb_version.index('.')])
            if lldb_major_version < 340:
                logger.warning("Debugger lldb is too old, please upgrade to XCode 7.2")
                return

        cmds = self._process_specific(pinfo, take_dump) + self._postfix()

        tf = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')

        for cmd in cmds:
            tf.write(cmd + "\n")

        tf.flush()

        # Works on in MacOS 10.9 & later
        #call([dbg] +  list( itertools.chain.from_iterable([['-o', b] for b in cmds])), logger)
        call(['cat', tf.name], logger)
        call([dbg, '--source', tf.name], logger)

        self._root_logger.info("Done analyzing %s processes with PIDs %s", pinfo.name,
                               str(pinfo.pidv))

        if take_dump:
            need_sigabrt = {}
            files = self._dump_files(pinfo)
            for pid in files:
                if not os.path.exists(files[pid]):
                    need_sigabrt[pid] = files[pid]
            if need_sigabrt:
                raise DumpError(need_sigabrt)

    def get_dump_ext(self):
        """Return the dump file extension."""
        return "core"

    def _dump_files(self, pinfo):
        """Return a dict mapping pids to core dump filenames that this dumper can create."""
        files = {}
        for pid in pinfo.pidv:
            files[pid] = "dump_%s.%d.%s" % (pinfo.name, pid, self.get_dump_ext())
        return files


# GDB dumper is for Linux
class GDBDumper(Dumper):
    """GDBDumper class."""

    def _find_debugger(self, debugger):
        """Find the installed debugger."""
        return find_program(debugger, ['/opt/mongodbtoolchain/gdb/bin', '/usr/bin'])

    def _prefix(self):
        """Return the commands to set up a debugger process."""
        script_dir = "buildscripts"
        gdb_dir = os.path.join(script_dir, "gdb")
        mongo_script = os.path.join(gdb_dir, "mongo.py")
        mongo_printers_script = os.path.join(gdb_dir, "mongo_printers.py")
        mongo_lock_script = os.path.join(gdb_dir, "mongo_lock.py")

        source_mongo = "source %s" % mongo_script
        source_mongo_printers = "source %s" % mongo_printers_script
        source_mongo_lock = "source %s" % mongo_lock_script

        cmds = [
            "set interactive-mode off",
            "set print thread-events off",  # Suppress GDB messages of threads starting/finishing.
            "set python print-stack full",
            source_mongo,
            source_mongo_printers,
            source_mongo_lock,
        ]
        return cmds

    def _process_specific(  # pylint: disable=too-many-locals
            self, pinfo, take_dump, logger=None):
        """Return the commands that attach to each process, dump info and detach."""
        mongodb_dump_locks = "mongodb-dump-locks"
        mongodb_show_locks = "mongodb-show-locks"
        mongodb_uniqstack = "mongodb-uniqstack mongodb-bt-if-active"
        mongodb_javascript_stack = "mongodb-javascript-stack"
        mongod_dump_sessions = "mongod-dump-sessions"
        mongodb_dump_mutexes = "mongodb-dump-mutexes"
        mongodb_dump_recovery_units = "mongodb-dump-recovery-units"

        cmds = []
        for pid in pinfo.pidv:
            if not logger.mongo_process_filename:
                raw_stacks_commands = []
            else:
                base, ext = os.path.splitext(logger.mongo_process_filename)
                raw_stacks_filename = "%s_%d_raw_stacks%s" % (base, pid, ext)
                raw_stacks_commands = [
                    'echo \\nWriting raw stacks to %s.\\n' % raw_stacks_filename,
                    # This sends output to log file rather than stdout until we turn logging off.
                    'set logging redirect on',
                    'set logging file ' + raw_stacks_filename,
                    'set logging on',
                    'thread apply all bt',
                    'set logging off',
                ]

            dump_command = ""
            if take_dump:
                # Dump to file, dump_<process name>.<pid>.core
                dump_file = "dump_%s.%d.%s" % (pinfo.name, pid, self.get_dump_ext())
                dump_command = "gcore %s" % dump_file
                self._root_logger.info("Dumping core to %s", dump_file)

            mongodb_waitsfor_graph = "mongodb-waitsfor-graph debugger_waitsfor_%s_%d.gv" % \
                (pinfo.name, pid)

            cmds += [
                "attach %d" % pid,
                "handle SIGSTOP ignore noprint",
                "info sharedlibrary",
                "info threads",  # Dump a simple list of commands to get the thread name
            ] + raw_stacks_commands + [
                mongodb_uniqstack,
                # Lock the scheduler, before running commands, which execute code in the attached process.
                "set scheduler-locking on",
                dump_command,
                mongodb_dump_locks,
                mongodb_show_locks,
                mongodb_waitsfor_graph,
                mongodb_javascript_stack,
                mongod_dump_sessions,
                mongodb_dump_mutexes,
                mongodb_dump_recovery_units,
                "detach",
            ]

        return cmds

    def _postfix(self):
        """Return the commands to exit the debugger."""
        cmds = ["set confirm off", "quit"]
        return cmds

    def dump_info(self, pinfo, take_dump):
        """Dump info."""
        debugger = "gdb"
        dbg = self._find_debugger(debugger)
        logger = _get_process_logger(self._dbg_output, pinfo.name)

        if dbg is None:
            self._root_logger.warning("Debugger %s not found, skipping dumping of %s", debugger,
                                      str(pinfo.pidv))
            return

        self._root_logger.info("Debugger %s, analyzing %s processes with PIDs %s", dbg, pinfo.name,
                               str(pinfo.pidv))

        call([dbg, "--version"], logger)

        cmds = self._prefix() + self._process_specific(pinfo, take_dump, logger) + self._postfix()

        call([dbg, "--quiet", "--nx"] + list(
            itertools.chain.from_iterable([['-ex', b] for b in cmds])), logger)

        self._root_logger.info("Done analyzing %s processes with PIDs %s", pinfo.name,
                               str(pinfo.pidv))

    def get_dump_ext(self):
        """Return the dump file extension."""
        return "core"

    @staticmethod
    def _find_gcore():
        """Find the installed gcore."""
        dbg = "/usr/bin/gcore"
        if os.path.exists(dbg):
            return dbg

        return None


# jstack is a JDK utility
class JstackDumper(object):
    """JstackDumper class."""

    @staticmethod
    def _find_debugger(debugger):
        """Find the installed jstack debugger."""
        return find_program(debugger, ['/usr/bin'])

    def dump_info(self, root_logger, dbg_output, pid, process_name):
        """Dump java thread stack traces to the console."""
        debugger = "jstack"
        jstack = self._find_debugger(debugger)
        logger = _get_process_logger(dbg_output, process_name, pid=pid)

        if jstack is None:
            logger.warning("Debugger %s not found, skipping dumping of %d", debugger, pid)
            return

        root_logger.info("Debugger %s, analyzing %s process with PID %d", jstack, process_name, pid)

        call([jstack, "-l", str(pid)], logger)

        root_logger.info("Done analyzing %s process with PID %d", process_name, pid)


# jstack is a JDK utility
class JstackWindowsDumper(object):
    """JstackWindowsDumper class."""

    @staticmethod
    def dump_info(root_logger, pid):
        """Dump java thread stack traces to the logger."""

        root_logger.warning("Debugger jstack not supported, skipping dumping of %d", pid)


def _get_process_logger(dbg_output, pname: str, pid: int = None):
    """Return the process logger from options specified."""
    process_logger = logging.Logger("process", level=logging.DEBUG)
    process_logger.mongo_process_filename = None

    if 'stdout' in dbg_output:
        s_handler = logging.StreamHandler(sys.stdout)
        s_handler.setFormatter(logging.Formatter(fmt="%(message)s"))
        process_logger.addHandler(s_handler)

    if 'file' in dbg_output:
        if pid:
            filename = "debugger_%s_%d.log" % (os.path.splitext(pname)[0], pid)
        else:
            filename = "debugger_%s.log" % (os.path.splitext(pname)[0])
        process_logger.mongo_process_filename = filename
        f_handler = logging.FileHandler(filename=filename, mode="w")
        f_handler.setFormatter(logging.Formatter(fmt="%(message)s"))
        process_logger.addHandler(f_handler)

    return process_logger


class DumpError(Exception):
    """
    Exception raised for errors while dumping processes.

    Tracks what cores still need to be generated.
    """

    def __init__(self, dump_pids, message=("Failed to create core dumps for some processes,"
                                           " SIGABRT will be sent as a fallback if -k is set.")):
        """Initialize error."""
        self.dump_pids = dump_pids
        self.message = message
        super().__init__(self.message)