Exemplo n.º 1
0
    def __init__(self, component, message):
        """Parses an "initialize" request or response and extracts the feature flags.

        For every "X" in self.PROPERTIES, sets self["X"] to the corresponding value
        from message.payload if it's present there, or to the default value otherwise.
        """

        assert message.is_request("initialize") or message.is_response(
            "initialize")

        self.component = component

        payload = message.payload
        for name, validate in self.PROPERTIES.items():
            value = payload.get(name, ())
            if not callable(validate):
                validate = json.default(validate)

            try:
                value = validate(value)
            except Exception as exc:
                raise message.isnt_valid("{0!j} {1}", name, exc)

            assert value != (), fmt(
                "{0!j} must provide a default value for missing properties.",
                validate)
            self[name] = value

        log.debug("{0}", self)
Exemplo n.º 2
0
Arquivo: api.py Projeto: int19h/ptvsd
    def debug(address, log_dir=None, multiprocess=True):
        if log_dir:
            log.log_dir = log_dir

        log.to_file(prefix="ptvsd.server")
        log.describe_environment("ptvsd.server debug start environment:")
        log.debug("{0}{1!r}", func.__name__, (address, log_dir, multiprocess))

        if is_attached():
            log.info("{0}() ignored - already attached.", func.__name__)
            return options.host, options.port

        # Ensure port is int
        if address is not options:
            host, port = address
            options.host, options.port = (host, int(port))

        if multiprocess is not options:
            options.multiprocess = multiprocess

        ptvsd_path, _, _ = get_abs_path_real_path_and_base_from_file(ptvsd.__file__)
        ptvsd_path = os.path.dirname(ptvsd_path)
        start_patterns = (ptvsd_path,)
        end_patterns = ("ptvsd_launcher.py",)
        log.info(
            "Won't trace filenames starting with: {0!j}\n"
            "Won't trace filenames ending with: {1!j}",
            start_patterns,
            end_patterns,
        )

        try:
            return func(start_patterns, end_patterns)
        except Exception:
            raise log.exception("{0}() failed:", func.__name__, level="info")
Exemplo n.º 3
0
 def _propagate_deferred_events(self):
     log.debug("Propagating deferred events to {0}...", self.ide)
     for event in self._deferred_events:
         log.debug("Propagating deferred {0}", event.describe())
         self.ide.channel.propagate(event)
     log.info("All deferred events propagated to {0}.", self.ide)
     self._deferred_events = None
Exemplo n.º 4
0
    def close(self):
        sock = self._socket
        if sock:
            self._socket = None
            log.debug("Closing {0} client socket...", self)
            try:
                sock.shutdown(socket.SHUT_RDWR)
            except Exception:
                pass
            try:
                sock.close()
            except Exception:
                pass

        server_socket = self._server_socket
        if server_socket:
            self._server_socket = None
            log.debug("Closing {0} server socket...", self)
            try:
                server_socket.shutdown(socket.SHUT_RDWR)
            except Exception:
                pass
            try:
                server_socket.close()
            except Exception:
                pass
Exemplo n.º 5
0
def test_targets(target_kind, client, wait, subprocesses, extra):
    args = ["--host", "localhost", "--port", "8888"]

    if client:
        args += ["--client"]

    if wait:
        args += ["--wait"]

    if not subprocesses:
        args += ["--no-subprocesses"]

    if target_kind == "file":
        target = "spam.py"
        args += [target]
    elif target_kind == "module":
        target = "spam"
        args += ["-m", target]
    elif target_kind == "code":
        target = "123"
        args += ["-c", target]
    else:
        pytest.fail(target_kind)

    if extra:
        extra = [
            "ham",
            "--client",
            "--wait",
            "-y",
            "spam",
            "--",
            "--host",
            "--port",
            "-c",
            "--something",
            "-m",
        ]
        args += extra
    else:
        extra = []

    log.debug("args = {0!r}", args)
    reload(options)
    rest = list(cli.parse(args))
    assert rest == extra

    expected_options = {
        "target_kind": target_kind,
        "target": target,
        "host": "localhost",
        "port": 8888,
        "wait": bool(wait),
        "multiprocess": bool(subprocesses),
    }
    actual_options = {name: vars(options)[name] for name in expected_options}
    assert expected_options == actual_options
Exemplo n.º 6
0
def enabled(filename):
    os.environ["PYDEVD_DEBUG"] = "True"
    os.environ["PYDEVD_DEBUG_FILE"] = filename
    log.debug("pydevd log will be at {0}", filename)
    try:
        yield
    finally:
        del os.environ["PYDEVD_DEBUG"]
        del os.environ["PYDEVD_DEBUG_FILE"]
Exemplo n.º 7
0
Arquivo: api.py Projeto: int19h/ptvsd
def wait_for_attach():
    log.debug("wait_for_attach()")
    dbg = get_global_debugger()
    if dbg is None:
        raise RuntimeError("wait_for_attach() called before enable_attach()")

    cancel_event = threading.Event()
    ptvsd.wait_for_attach.cancel = wait_for_attach.cancel = cancel_event.set
    pydevd._wait_for_attach(cancel=cancel_event)
Exemplo n.º 8
0
 def propagate_after_start(self, event):
     # pydevd starts sending events as soon as we connect, but the IDE doesn't
     # expect to see any until it receives the response to "launch" or "attach"
     # request. If IDE is not ready yet, save the event instead of propagating
     # it immediately.
     if self._deferred_events is not None:
         self._deferred_events.append(event)
         log.debug("Propagation deferred.")
     else:
         self.ide.channel.propagate(event)
Exemplo n.º 9
0
 def wait(self, timeout=None):
     """Wait for all remaining output to be captured.
     """
     if not self._worker_threads:
         return
     log.debug("Waiting for remaining {0} output...",
               self.session.debuggee_id)
     for t in self._worker_threads:
         t.join(timeout)
     self._worker_threads[:] = []
Exemplo n.º 10
0
def setup_debug_server(argv_0):
    # We need to set up sys.argv[0] before invoking attach() or enable_attach(),
    # because they use it to report the "process" event. Thus, we can't rely on
    # run_path() and run_module() doing that, even though they will eventually.
    sys.argv[0] = compat.filename(argv_0)
    log.debug("sys.argv after patching: {0!r}", sys.argv)

    debug = ptvsd.attach if options.client else ptvsd.enable_attach
    debug(address=options, multiprocess=options)

    if options.wait:
        ptvsd.wait_for_attach()
Exemplo n.º 11
0
def run_file():
    setup_debug_server(options.target)

    # run_path has one difference with invoking Python from command-line:
    # if the target is a file (rather than a directory), it does not add its
    # parent directory to sys.path. Thus, importing other modules from the
    # same directory is broken unless sys.path is patched here.
    if os.path.isfile(options.target):
        dir = os.path.dirname(options.target)
        sys.path.insert(0, dir)
    else:
        log.debug("Not a file: {0!j}", options.target)

    log.describe_environment("Pre-launch environment:")
    log.info("Running file {0!j}", options.target)
    runpy.run_path(options.target, run_name="__main__")
Exemplo n.º 12
0
    def close(self):
        if self._socket:
            log.debug("Closing {0} socket of {1}...", self, self.session)
            try:
                self._socket.shutdown(socket.SHUT_RDWR)
            except Exception:
                pass
            self._socket = None

        if self._server_socket:
            log.debug("Closing {0} server socket of {1}...", self,
                      self.session)
            try:
                self._server_socket.shutdown(socket.SHUT_RDWR)
            except Exception:
                pass
            self._server_socket = None
Exemplo n.º 13
0
def _wait_for_user_input():
    if sys.stdout and sys.stdin:
        from ptvsd.common import log

        can_getch = sys.stdin.isatty()
        if can_getch:
            try:
                import msvcrt
            except ImportError:
                can_getch = False

        if can_getch:
            log.debug("msvcrt available - waiting for user input via getch()")
            sys.stdout.write("Press any key to continue . . . ")
            sys.stdout.flush()
            msvcrt.getch()
        else:
            log.debug("msvcrt not available - waiting for user input via read()")
            sys.stdout.write("Press Enter to continue . . . ")
            sys.stdout.flush()
            sys.stdin.read(1)
Exemplo n.º 14
0
def break_into_debugger():
    log.debug("break_into_debugger()")

    if not is_attached():
        log.info("break_into_debugger() ignored - debugger not attached")
        return

    # Get the first frame in the stack that's not an internal frame.
    global_debugger = get_global_debugger()
    stop_at_frame = sys._getframe().f_back
    while (stop_at_frame is not None
           and global_debugger.get_file_type(stop_at_frame)
           == global_debugger.PYDEV_FILE):
        stop_at_frame = stop_at_frame.f_back

    _settrace(
        suspend=True,
        trace_only_current_thread=True,
        patch_multiprocessing=False,
        stop_at_frame=stop_at_frame,
    )
    stop_at_frame = None
Exemplo n.º 15
0
    def parse(args):
        log.debug("Parsing argv: {0!r}", args)
        try:
            output = subprocess.check_output(
                [sys.executable, "-u", cli_parser.strpath] + args)
            argv, options = pickle.loads(output)
        except subprocess.CalledProcessError as exc:
            raise pickle.loads(exc.output)

        log.debug("Adjusted sys.argv: {0!r}", argv)
        log.debug("Parsed options: {0!r}", options)
        return argv, options
Exemplo n.º 16
0
    def worker():
        messages = MessageFactory()

        worker_can_proceed.wait()
        worker_can_proceed.clear()
        timeline.record_event(messages.event("dum", {}))
        log.debug("dum")

        worker_can_proceed.wait()
        timeline.record_event(messages.event("dee", {}))
        log.debug("dee")

        timeline.record_event(messages.event("dum", {}))
        log.debug("dum")
Exemplo n.º 17
0
 def _log_message(self, dir, data):
     format_string = "{0} {1} " + ("{2!j:indent=None}" if isinstance(
         data, list) else "{2!j}")
     return log.debug(format_string, self.name, dir, data)
Exemplo n.º 18
0
Arquivo: api.py Projeto: int19h/ptvsd
def debug_this_thread():
    log.debug("debug_this_thread()")
    _settrace(suspend=False)
Exemplo n.º 19
0
Arquivo: api.py Projeto: int19h/ptvsd
def _settrace(*args, **kwargs):
    log.debug("pydevd.settrace(*{0!r}, **{1!r})", args, kwargs)
    return pydevd.settrace(*args, **kwargs)