Пример #1
0
 def start_thread(self):
     self._update_thread = IntervalTimer(self.update_config,
                                         1,
                                         "eapm conf updater",
                                         daemon=True,
                                         evaluate_function_interval=True)
     self._update_thread.start()
Пример #2
0
 def start_thread(self, pid=None):
     self._update_thread = IntervalTimer(self.update_config,
                                         1,
                                         "eapm conf updater",
                                         daemon=True,
                                         evaluate_function_interval=True)
     self._update_thread.start()
     super(VersionedConfig, self).start_thread(pid=pid)
Пример #3
0
 def _start_collect_timer(self, timeout=None):
     timeout = timeout or self._collect_interval
     self._collect_timer = IntervalTimer(self.collect,
                                         timeout,
                                         name="eapm metrics collect timer",
                                         daemon=True)
     logger.debug("Starting metrics collect timer")
     self._collect_timer.start()
Пример #4
0
 def start_thread(self, pid=None):
     super(MetricsRegistry, self).start_thread(pid=pid)
     if self.client.config.metrics_interval:
         self._collect_timer = IntervalTimer(
             self.collect, self.collect_interval, name="eapm metrics collect timer", daemon=True
         )
         logger.debug("Starting metrics collect timer")
         self._collect_timer.start()
Пример #5
0
 def start_thread(self):
     if self._collect_interval:
         self._collect_timer = IntervalTimer(
             self.collect,
             self._collect_interval,
             name="eapm metrics collect timer",
             daemon=True)
         logger.debug("Starting metrics collect timer")
         self._collect_timer.start()
Пример #6
0
def test_interval_timer_exception(caplog):
    def my_func():
        return 1 / 0

    with caplog.at_level("ERROR", "elasticapm.utils.threading"):
        timer = IntervalTimer(function=my_func, interval=0.1)
        timer.start()
        time.sleep(0.25)
        assert timer.is_alive()
    timer.cancel()
    assert_any_record_contains(caplog.records,
                               "Exception in interval timer function")
Пример #7
0
def test_interval_timer():
    func = mock.Mock()
    timer = IntervalTimer(function=func, interval=0.1, args=(1,), kwargs={"a": "b"})
    timer.start()
    time.sleep(0.25)
    try:
        assert func.call_count == 2
        for call in func.call_args_list:
            assert call == ((1,), {"a": "b"})
    finally:
        timer.cancel()
    time.sleep(0.05)
    assert not timer.is_alive()
Пример #8
0
def test_interval_timer_interval_override_non_number():
    func = mock.Mock()
    func.return_value = "foo"
    timer = IntervalTimer(function=func,
                          interval=0.1,
                          evaluate_function_interval=True)
    timer.start()
    time.sleep(0.25)
    try:
        assert func.call_count == 2
    finally:
        timer.cancel()
    time.sleep(0.05)
    assert not timer.is_alive()
Пример #9
0
    def __init__(self, config=None, **inline):
        # configure loggers first
        cls = self.__class__
        self.logger = get_logger("%s.%s" % (cls.__module__, cls.__name__))
        self.error_logger = get_logger("elasticapm.errors")

        self.tracer = None
        self.processors = []
        self.filter_exception_types_dict = {}
        self._service_info = None

        config = Config(config, inline_dict=inline)
        if config.errors:
            for msg in config.errors.values():
                self.error_logger.error(msg)
            config.disable_send = True
        self.config = VersionedConfig(config, version=None)

        # Insert the log_record_factory into the logging library
        # The LogRecordFactory functionality is only available on python 3.2+
        if compat.PY3 and not self.config.disable_log_record_factory:
            record_factory = logging.getLogRecordFactory()
            # Only way to know if it's wrapped is to create a log record
            throwaway_record = record_factory(__name__, logging.DEBUG, __file__, 252, "dummy_msg", [], None)
            if not hasattr(throwaway_record, "elasticapm_labels"):
                self.logger.debug("Inserting elasticapm log_record_factory into logging")

                # Late import due to circular imports
                import elasticapm.handlers.logging as elastic_logging

                new_factory = elastic_logging.log_record_factory(record_factory)
                logging.setLogRecordFactory(new_factory)

        headers = {
            "Content-Type": "application/x-ndjson",
            "Content-Encoding": "gzip",
            "User-Agent": "elasticapm-python/%s" % elasticapm.VERSION,
        }

        if self.config.secret_token:
            headers["Authorization"] = "Bearer %s" % self.config.secret_token
        transport_kwargs = {
            "metadata": self._build_metadata(),
            "headers": headers,
            "verify_server_cert": self.config.verify_server_cert,
            "server_cert": self.config.server_cert,
            "timeout": self.config.server_timeout,
            "max_flush_time": self.config.api_request_time / 1000.0,
            "max_buffer_size": self.config.api_request_size,
            "processors": self.load_processors(),
        }
        self._api_endpoint_url = compat.urlparse.urljoin(
            self.config.server_url if self.config.server_url.endswith("/") else self.config.server_url + "/",
            constants.EVENTS_API_PATH,
        )
        self._transport = import_string(self.config.transport_class)(self._api_endpoint_url, **transport_kwargs)

        for exc_to_filter in self.config.filter_exception_types or []:
            exc_to_filter_type = exc_to_filter.split(".")[-1]
            exc_to_filter_module = ".".join(exc_to_filter.split(".")[:-1])
            self.filter_exception_types_dict[exc_to_filter_type] = exc_to_filter_module

        if platform.python_implementation() == "PyPy":
            # PyPy introduces a `_functools.partial.__call__` frame due to our use
            # of `partial` in AbstractInstrumentedModule
            skip_modules = ("elasticapm.", "_functools")
        else:
            skip_modules = ("elasticapm.",)

        self.tracer = Tracer(
            frames_collector_func=lambda: list(
                stacks.iter_stack_frames(
                    start_frame=inspect.currentframe(), skip_top_modules=skip_modules, config=self.config
                )
            ),
            frames_processing_func=lambda frames: self._get_stack_info_for_trace(
                frames,
                library_frame_context_lines=self.config.source_lines_span_library_frames,
                in_app_frame_context_lines=self.config.source_lines_span_app_frames,
                with_locals=self.config.collect_local_variables in ("all", "transactions"),
                locals_processor_func=lambda local_var: varmap(
                    lambda k, v: shorten(
                        v,
                        list_length=self.config.local_var_list_max_length,
                        string_length=self.config.local_var_max_length,
                        dict_length=self.config.local_var_dict_max_length,
                    ),
                    local_var,
                ),
            ),
            queue_func=self.queue,
            config=self.config,
            agent=self,
        )
        self.include_paths_re = stacks.get_path_regex(self.config.include_paths) if self.config.include_paths else None
        self.exclude_paths_re = stacks.get_path_regex(self.config.exclude_paths) if self.config.exclude_paths else None
        self._metrics = MetricsRegistry(
            self.config.metrics_interval / 1000.0, self.queue, ignore_patterns=self.config.disable_metrics
        )
        for path in self.config.metrics_sets:
            self._metrics.register(path)
        if self.config.breakdown_metrics:
            self._metrics.register("elasticapm.metrics.sets.breakdown.BreakdownMetricSet")
        compat.atexit_register(self.close)
        if self.config.central_config:
            self._config_updater = IntervalTimer(
                update_config, 1, "eapm conf updater", daemon=True, args=(self,), evaluate_function_interval=True
            )
            self._config_updater.start()
        else:
            self._config_updater = None