def test_lambda_no_error_with_invalid_flush_timeout(self):

        test_env_patch = mock.patch.dict(
            "os.environ",
            {
                **os.environ,
                # NOT Active Tracing
                _X_AMZN_TRACE_ID: MOCK_XRAY_TRACE_CONTEXT_NOT_SAMPLED,
                # NOT using the X-Ray Propagator
                OTEL_PROPAGATORS: "tracecontext",
                OTEL_INSTRUMENTATION_AWS_LAMBDA_FLUSH_TIMEOUT: "invalid-timeout-string",
            },
        )
        test_env_patch.start()

        AwsLambdaInstrumentor().instrument()

        mock_execute_lambda()

        spans = self.memory_exporter.get_finished_spans()

        assert spans

        self.assertEqual(len(spans), 1)

        test_env_patch.stop()
Beispiel #2
0
    def test_lambda_handles_multiple_consumers(self):
        test_env_patch = mock.patch.dict(
            "os.environ",
            {
                **os.environ,
                # NOT Active Tracing
                _X_AMZN_TRACE_ID: MOCK_XRAY_TRACE_CONTEXT_NOT_SAMPLED,
                # NOT using the X-Ray Propagator
                OTEL_PROPAGATORS: "tracecontext",
            },
        )
        test_env_patch.start()

        AwsLambdaInstrumentor().instrument()

        mock_execute_lambda({"Records": [{"eventSource": "aws:sqs"}]})
        mock_execute_lambda({"Records": [{"eventSource": "aws:s3"}]})
        mock_execute_lambda({"Records": [{"eventSource": "aws:sns"}]})
        mock_execute_lambda({"Records": [{"eventSource": "aws:dynamodb"}]})

        spans = self.memory_exporter.get_finished_spans()

        assert spans

        test_env_patch.stop()
Beispiel #3
0
    def test_uninstrument(self):
        AwsLambdaInstrumentor().uninstrument()

        lambda_handler("event", self._mock_context)

        spans = self.memory_exporter.get_finished_spans()
        assert not spans
        self.assertEqual(len(spans), 0)
    def setUp(self):
        super().setUp()
        os.environ[
            "_X_AMZN_TRACE_ID"] = "Root=1-5f9f8bb1-3d0f7a5ef4dc8aa04da2bf6a;Parent=7e2d794cd396c754;Sampled=1"
        current_module = sys.modules[__name__]
        os.environ["_HANDLER"] = current_module.__name__ + ".lambda_handler"

        AwsLambdaInstrumentor().instrument()

        self._mock_context = MockLambdaContext()
        self._mock_context.invoked_function_arn = "arn://lambda-function-arn"
        self._mock_context.aws_request_id = "aws_request_id"
    def test_using_custom_extractor(self):
        def custom_event_context_extractor(lambda_event):
            return get_global_textmap().extract(lambda_event["foo"]["headers"])

        test_env_patch = mock.patch.dict(
            "os.environ",
            {
                **os.environ,
                # NOT Active Tracing
                _X_AMZN_TRACE_ID: MOCK_XRAY_TRACE_CONTEXT_NOT_SAMPLED,
                # NOT using the X-Ray Propagator
                OTEL_PROPAGATORS: "tracecontext",
            },
        )
        test_env_patch.start()

        AwsLambdaInstrumentor().instrument(
            event_context_extractor=custom_event_context_extractor,
        )

        mock_execute_lambda(
            {
                "foo": {
                    "headers": {
                        TraceContextTextMapPropagator._TRACEPARENT_HEADER_NAME: MOCK_W3C_TRACE_CONTEXT_SAMPLED,
                        TraceContextTextMapPropagator._TRACESTATE_HEADER_NAME: f"{MOCK_W3C_TRACE_STATE_KEY}={MOCK_W3C_TRACE_STATE_VALUE},foo=1,bar=2",
                    }
                }
            }
        )

        spans = self.memory_exporter.get_finished_spans()

        assert spans

        self.assertEqual(len(spans), 1)
        span = spans[0]
        self.assertEqual(span.get_span_context().trace_id, MOCK_W3C_TRACE_ID)

        parent_context = span.parent
        self.assertEqual(
            parent_context.trace_id, span.get_span_context().trace_id
        )
        self.assertEqual(parent_context.span_id, MOCK_W3C_PARENT_SPAN_ID)
        self.assertEqual(len(parent_context.trace_state), 3)
        self.assertEqual(
            parent_context.trace_state.get(MOCK_W3C_TRACE_STATE_KEY),
            MOCK_W3C_TRACE_STATE_VALUE,
        )
        self.assertTrue(parent_context.is_remote)

        test_env_patch.stop()
    def test_instrumen_wrapper_handler(self):
        current_module = sys.modules[__name__]
        os.environ["ORIG_HANDLER"] = (current_module.__name__ +
                                      ".lambda_handler")
        os.environ["_HANDLER"] = current_module.__name__ + ".lambda_handler"

        AwsLambdaInstrumentor().instrument()

        wrapper_handler("event", self._mock_context)

        spans = self.memory_exporter.get_finished_spans()

        assert spans
        span = spans[0]

        self.assertEqual(len(spans), 1)
        self.assertEqual(span.attributes["faas.execution"], "aws_request_id")
Beispiel #7
0
    def test_active_tracing(self):
        test_env_patch = mock.patch.dict(
            "os.environ",
            {
                **os.environ,
                # Using Active tracing
                _X_AMZN_TRACE_ID:
                MOCK_XRAY_TRACE_CONTEXT_SAMPLED,
            },
        )
        test_env_patch.start()

        AwsLambdaInstrumentor().instrument()

        mock_execute_lambda()

        spans = self.memory_exporter.get_finished_spans()

        assert spans

        self.assertEqual(len(spans), 1)
        span = spans[0]
        self.assertEqual(span.name, os.environ[_HANDLER])
        self.assertEqual(span.get_span_context().trace_id, MOCK_XRAY_TRACE_ID)
        self.assertEqual(span.kind, SpanKind.SERVER)
        self.assertSpanHasAttributes(
            span,
            {
                ResourceAttributes.FAAS_ID:
                MOCK_LAMBDA_CONTEXT.invoked_function_arn,
                SpanAttributes.FAAS_EXECUTION:
                MOCK_LAMBDA_CONTEXT.aws_request_id,
            },
        )

        parent_context = span.parent
        self.assertEqual(parent_context.trace_id,
                         span.get_span_context().trace_id)
        self.assertEqual(parent_context.span_id, MOCK_XRAY_PARENT_SPAN_ID)
        self.assertTrue(parent_context.is_remote)

        test_env_patch.stop()
Beispiel #8
0
 def tearDown(self):
     AwsLambdaInstrumentor().uninstrument()
     super().tearDown()
    trace.get_tracer_provider().add_span_processor(
        SimpleExportSpanProcessor(ConsoleSpanExporter())
    )
    logger.info("Console exporter initialized.")

ci = os.environ.get("_ADOT_CI", None)
if ci is None:
    from opentelemetry.exporter.otlp.trace_exporter import OTLPSpanExporter

    otlp_exporter = OTLPSpanExporter(endpoint="localhost:55680", insecure=True)
    span_processor = BatchExportSpanProcessor(otlp_exporter)
    trace.get_tracer_provider().add_span_processor(span_processor)
    logger.info("Otlp exporter initialized.")


AwsLambdaInstrumentor().instrument()
# Load instrumentors from entry_points
for entry_point in iter_entry_points("opentelemetry_instrumentor"):
    print(entry_point)
    try:
        entry_point.load()().instrument()  # type: ignore
        logger.debug("Instrumented %s", entry_point.name)

    except Exception:
        logger.debug("Instrumenting of %s failed", entry_point.name)


def modify_module_name(module_name):
    """Returns a valid modified module to get imported"""
    return ".".join(module_name.split("/"))
 def tearDown(self):
     super().tearDown()
     self.common_env_patch.stop()
     AwsLambdaInstrumentor().uninstrument()
        except Exception as exc:  # pylint: disable=broad-except
            logger.info("Configuration of %s failed", entry_point.name)


def modify_module_name(module_name):
    """Returns a valid modified module to get imported"""
    return ".".join(module_name.split("/"))


class HandlerError(Exception):
    pass


_load_distros()
_load_configurators()
_load_instrumentors()
# TODO: move to python-contrib
AwsLambdaInstrumentor().instrument(skip_dep_check=True)

path = os.environ.get("ORIG_HANDLER", None)
if path is None:
    raise HandlerError("ORIG_HANDLER is not defined.")
parts = path.rsplit(".", 1)
if len(parts) != 2:
    raise HandlerError("Value %s for ORIG_HANDLER has invalid format." % path)

(mod_name, handler_name) = parts
modified_mod_name = modify_module_name(mod_name)
handler_module = import_module(modified_mod_name)
lambda_handler = getattr(handler_module, handler_name)