Esempio n. 1
0
 def test_tracer_context_provider_config(self):
     tracer = ddtrace.opentracer.Tracer("mysvc",
                                        scope_manager=GeventScopeManager())
     assert isinstance(
         tracer._dd_tracer.context_provider,
         ddtrace.contrib.gevent.provider.GeventContextProvider,
     )
Esempio n. 2
0
    def test_trace_spawn_multiple_greenlets_multiple_traces_ot(self):
        """OpenTracing version of the same test."""

        ot_tracer = init_tracer("my_svc", self.tracer, scope_manager=GeventScopeManager())

        def entrypoint():
            with ot_tracer.start_active_span("greenlet.main") as span:
                span.resource = "base"
                jobs = [gevent.spawn(green_1), gevent.spawn(green_2)]
                gevent.joinall(jobs)

        def green_1():
            with self.tracer.trace("greenlet.worker1") as span:
                span.set_tag("worker_id", "1")
                gevent.sleep(0.01)

        # note that replacing the `tracer.trace` call here with the
        # OpenTracing equivalent will cause the checks to fail
        def green_2():
            with ot_tracer.start_active_span("greenlet.worker2") as scope:
                scope.span.set_tag("worker_id", "2")
                gevent.sleep(0.01)

        gevent.spawn(entrypoint).join()

        spans = self.tracer.writer.pop()
        self._assert_spawn_multiple_greenlets(spans)
Esempio n. 3
0
def instrument_gevent():
    """ Adds context propagation to gevent greenlet spawning """
    try:
        logger.debug("Instrumenting gevent")

        import gevent
        from opentracing.scope_managers.gevent import GeventScopeManager
        from opentracing.scope_managers.gevent import _GeventScope

        def spawn_callback(new_greenlet):
            """ Handles context propagation for newly spawning greenlets """
            parent_scope = tracer.scope_manager.active
            if parent_scope is not None:
                # New greenlet, new clean slate.  Clone and make active in this new greenlet
                # the currently active scope (but don't finish() the span on close - it's a
                # clone/not the original and we don't want to close it prematurely)
                # TODO: Change to our own ScopeManagers
                parent_scope_clone = _GeventScope(parent_scope.manager, parent_scope.span, finish_on_close=False)
                tracer._scope_manager._set_greenlet_scope(parent_scope_clone, new_greenlet)

        logger.debug(" -> Updating tracer to use gevent based context management")
        tracer._scope_manager = GeventScopeManager()
        gevent.Greenlet.add_spawn_callback(spawn_callback)
    except:
        logger.debug("instrument_gevent: ", exc_info=True)
Esempio n. 4
0
def ot_tracer(ot_tracer_factory):
    """Fixture providing an opentracer configured for gevent usage."""
    # patch gevent
    patch()
    yield ot_tracer_factory("gevent_svc", {}, GeventScopeManager(), ddtrace.contrib.gevent.context_provider)
    # unpatch gevent
    unpatch()
Esempio n. 5
0
 def setUp(self):
     self.http = urllib3.HTTPConnectionPool('127.0.0.1',
                                            port=testenv["wsgi_port"],
                                            maxsize=20)
     self.recorder = tracer.recorder
     self.recorder.clear_spans()
     tracer._scope_manager = GeventScopeManager()
 def setUp(self):
     self.tracer = MockTracer(GeventScopeManager())
Esempio n. 7
0
 def scope_manager(self):
     return GeventScopeManager()
Esempio n. 8
0
 def test_get_context_provider_for_scope_manager_asyncio(self):
     scope_manager = GeventScopeManager()
     ctx_prov = get_context_provider_for_scope_manager(scope_manager)
     assert isinstance(
         ctx_prov, ddtrace.contrib.gevent.provider.GeventContextProvider)
 def setUp(self):
     self.tracer = MockTracer(GeventScopeManager())
     self.queue = gevent.queue.Queue()
     self.server = Server(tracer=self.tracer, queue=self.queue)
Esempio n. 10
0
def main(  # pylint: disable=too-many-arguments,too-many-locals
    private_key: PrivateKey,
    state_db: str,
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,
    confirmations: BlockTimeout,
    host: str,
    port: int,
    service_fee: TokenAmount,
    operator: str,
    info_message: str,
    enable_debug: bool,
    matrix_server: List[str],
    accept_disclaimer: bool,
    enable_tracing: bool,
    tracing_sampler: str,
    tracing_param: str,
) -> int:
    """The Pathfinding service for the Raiden Network."""
    log.info("Starting Raiden Pathfinding Service")
    click.secho(PFS_DISCLAIMER, fg="yellow")
    if not accept_disclaimer:
        click.confirm(CONFIRMATION_OF_UNDERSTANDING, abort=True)

    if not confirmations:
        chain_id = ChainID(web3.eth.chain_id)
        confirmations = (BlockTimeout(0) if "arbitrum" in ID_TO_CHAINNAME.get(
            chain_id, "") else DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS)
        log.info("Setting number of confirmation blocks",
                 confirmations=confirmations)

    log.info("Using RPC endpoint", rpc_url=get_web3_provider_info(web3))
    hex_addresses = {
        name: to_checksum_address(contract.address)
        for name, contract in contracts.items()
    }
    log.info("Contract information",
             addresses=hex_addresses,
             start_block=start_block)

    if enable_tracing:
        tracing_config = Config(
            config={
                "sampler": {
                    "type": tracing_sampler,
                    "param": tracing_param
                },
                "logging": True
            },
            service_name="pfs",
            scope_manager=GeventScopeManager(),
            validate=True,
        )
        # Tracer is stored in `opentracing.tracer`
        tracing_config.initialize_tracer()

        assert isinstance(web3.provider, HTTPProvider), MYPY_ANNOTATION
        assert web3.provider.endpoint_uri is not None, MYPY_ANNOTATION
        # Set `Web3` requests Session to use `SessionTracing`
        cache_session(
            web3.provider.endpoint_uri,
            SessionTracing(propagate=False, span_tags={"target": "ethnode"}),
        )

    service = None
    api = None
    try:
        service = PathfindingService(
            web3=web3,
            contracts=contracts,
            sync_start_block=start_block,
            required_confirmations=confirmations,
            private_key=private_key,
            poll_interval=DEFAULT_POLL_INTERVALL,
            db_filename=state_db,
            matrix_servers=matrix_server,
            enable_tracing=enable_tracing,
        )
        service.start()
        log.debug("Waiting for service to start before accepting API requests")
        try:
            service.startup_finished.get(timeout=PFS_START_TIMEOUT)
        except gevent.Timeout:
            raise Exception("PFS did not start within time.")

        log.debug("Starting API")
        api = PFSApi(
            pathfinding_service=service,
            service_fee=service_fee,
            debug_mode=enable_debug,
            one_to_n_address=to_canonical_address(
                contracts[CONTRACT_ONE_TO_N].address),
            operator=operator,
            info_message=info_message,
            enable_tracing=enable_tracing,
        )
        api.run(host=host, port=port)

        service.get()
    except (KeyboardInterrupt, SystemExit):
        print("Exiting...")
    finally:
        log.info("Stopping Pathfinding Service...")
        if api:
            api.stop()
        if service:
            service.stop()

    return 0
Esempio n. 11
0
 def setUp(self):
     self.tracer = MockTracer(GeventScopeManager())
     self.client = Client(RequestHandler(self.tracer))