dt-extensions-sdk 1.1.8__py3-none-any.whl → 1.1.10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {dt_extensions_sdk-1.1.8.dist-info → dt_extensions_sdk-1.1.10.dist-info}/METADATA +2 -2
  2. dt_extensions_sdk-1.1.10.dist-info/RECORD +33 -0
  3. {dt_extensions_sdk-1.1.8.dist-info → dt_extensions_sdk-1.1.10.dist-info}/WHEEL +1 -1
  4. {dt_extensions_sdk-1.1.8.dist-info → dt_extensions_sdk-1.1.10.dist-info}/licenses/LICENSE.txt +9 -9
  5. dynatrace_extension/__about__.py +4 -4
  6. dynatrace_extension/__init__.py +27 -27
  7. dynatrace_extension/cli/__init__.py +5 -5
  8. dynatrace_extension/cli/create/__init__.py +1 -1
  9. dynatrace_extension/cli/create/create.py +76 -76
  10. dynatrace_extension/cli/create/extension_template/.gitignore.template +160 -160
  11. dynatrace_extension/cli/create/extension_template/README.md.template +33 -33
  12. dynatrace_extension/cli/create/extension_template/activation.json.template +15 -15
  13. dynatrace_extension/cli/create/extension_template/extension/activationSchema.json.template +118 -118
  14. dynatrace_extension/cli/create/extension_template/extension/extension.yaml.template +16 -16
  15. dynatrace_extension/cli/create/extension_template/extension_name/__main__.py.template +43 -43
  16. dynatrace_extension/cli/create/extension_template/setup.py.template +12 -12
  17. dynatrace_extension/cli/main.py +414 -414
  18. dynatrace_extension/cli/schema.py +129 -129
  19. dynatrace_extension/sdk/__init__.py +3 -3
  20. dynatrace_extension/sdk/activation.py +43 -43
  21. dynatrace_extension/sdk/callback.py +141 -141
  22. dynatrace_extension/sdk/communication.py +454 -446
  23. dynatrace_extension/sdk/event.py +19 -19
  24. dynatrace_extension/sdk/extension.py +1034 -1033
  25. dynatrace_extension/sdk/helper.py +191 -191
  26. dynatrace_extension/sdk/metric.py +118 -118
  27. dynatrace_extension/sdk/runtime.py +67 -67
  28. dynatrace_extension/sdk/vendor/mureq/LICENSE +13 -13
  29. dynatrace_extension/sdk/vendor/mureq/mureq.py +447 -447
  30. dt_extensions_sdk-1.1.8.dist-info/RECORD +0 -33
  31. {dt_extensions_sdk-1.1.8.dist-info → dt_extensions_sdk-1.1.10.dist-info}/entry_points.txt +0 -0
@@ -1,1033 +1,1034 @@
1
- # SPDX-FileCopyrightText: 2023-present Dynatrace LLC
2
- #
3
- # SPDX-License-Identifier: MIT
4
-
5
- import logging
6
- import sched
7
- import signal
8
- import sys
9
- import threading
10
- import time
11
- from argparse import ArgumentParser
12
- from concurrent.futures import ThreadPoolExecutor
13
- from datetime import datetime, timedelta, timezone
14
- from enum import Enum
15
- from itertools import chain
16
- from threading import Lock, RLock, active_count
17
- from typing import Any, Callable, ClassVar, Dict, List, NamedTuple, Optional, Union
18
-
19
- from ..__about__ import __version__
20
- from .activation import ActivationConfig, ActivationType
21
- from .callback import WrappedCallback
22
- from .communication import CommunicationClient, DebugClient, HttpClient, Status, StatusValue
23
- from .event import Severity
24
- from .metric import Metric, MetricType, SfmMetric, SummaryStat
25
- from .runtime import RuntimeProperties
26
-
27
- HEARTBEAT_INTERVAL = timedelta(seconds=30)
28
- METRIC_SENDING_INTERVAL = timedelta(seconds=30)
29
- SFM_METRIC_SENDING_INTERVAL = timedelta(seconds=60)
30
- TIME_DIFF_INTERVAL = timedelta(seconds=60)
31
-
32
- CALLBACKS_THREAD_POOL_SIZE = 100
33
- INTERNAL_THREAD_POOL_SIZE = 20
34
-
35
- RFC_3339_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
36
- DATASOURCE_TYPE = "python"
37
-
38
- logging.raiseExceptions = False
39
- formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s (%(threadName)s): %(message)s")
40
- error_handler = logging.StreamHandler()
41
- error_handler.addFilter(lambda record: record.levelno >= logging.ERROR)
42
- error_handler.setFormatter(formatter)
43
- std_handler = logging.StreamHandler(sys.stdout)
44
- std_handler.addFilter(lambda record: record.levelno < logging.ERROR)
45
- std_handler.setFormatter(formatter)
46
- extension_logger = logging.getLogger(__name__)
47
- extension_logger.setLevel(logging.INFO)
48
- extension_logger.addHandler(error_handler)
49
- extension_logger.addHandler(std_handler)
50
-
51
- api_logger = logging.getLogger("api")
52
- api_logger.setLevel(logging.INFO)
53
- api_logger.addHandler(error_handler)
54
- api_logger.addHandler(std_handler)
55
-
56
- DT_EVENT_SCHEMA = {
57
- "eventType": str,
58
- "title": str,
59
- "startTime": int,
60
- "endTime": int,
61
- "timeout": int,
62
- "entitySelector": str,
63
- "properties": dict,
64
- }
65
-
66
-
67
- class AggregationMode(Enum):
68
- ALL = "include_all"
69
- NONE = "include_none"
70
- LIST = "include_list"
71
-
72
-
73
- class DtEventType(str, Enum):
74
- """Event type.
75
-
76
- Note:
77
- Official API v2 documentation:
78
-
79
- https://docs.dynatrace.com/docs/dynatrace-api/environment-api/events-v2/post-event
80
- """
81
-
82
- CUSTOM_INFO = "CUSTOM_INFO"
83
- CUSTOM_ALERT = "CUSTOM_ALERT"
84
- CUSTOM_ANNOTATION = "CUSTOM_ANNOTATION"
85
- CUSTOM_CONFIGURATION = "CUSTOM_CONFIGURATION"
86
- CUSTOM_DEPLOYMENT = "CUSTOM_DEPLOYMENT"
87
- MARKED_FOR_TERMINATION = "MARKED_FOR_TERMINATION"
88
- ERROR_EVENT = "ERROR_EVENT"
89
- AVAILABILITY_EVENT = "AVAILABILITY_EVENT"
90
- RESOURCE_CONTENTION_EVENT = "RESOURCE_CONTENTION_EVENT"
91
-
92
-
93
- class CountMetricRegistrationEntry(NamedTuple):
94
- metric_key: str
95
- aggregation_mode: AggregationMode
96
- dimensions_list: list[str]
97
-
98
- @staticmethod
99
- def make_list(metric_key: str, dimensions_list: List[str]):
100
- """Build an entry that uses defined list of dimensions for aggregation.
101
-
102
- Args:
103
- metric_key: Metric key in string.
104
- dimensions_list: List of dimensions.
105
- """
106
- return CountMetricRegistrationEntry(metric_key, AggregationMode.LIST, dimensions_list)
107
-
108
- @staticmethod
109
- def make_all(metric_key: str):
110
- """Build an entry that uses all mint dimensions for aggregation.
111
-
112
- Args:
113
- metric_key: Metric key in string.
114
- """
115
- return CountMetricRegistrationEntry(metric_key, AggregationMode.ALL, [])
116
-
117
- @staticmethod
118
- def make_none(metric_key: str):
119
- """Build an entry that uses none of mint dimensions for aggregation.
120
-
121
- Args:
122
- metric_key: Metric key in string.
123
- """
124
- return CountMetricRegistrationEntry(metric_key, AggregationMode.NONE, [])
125
-
126
- def registration_items_dict(self):
127
- result = {"aggregation_mode": self.aggregation_mode.value}
128
- if self.aggregation_mode == AggregationMode.LIST:
129
- result["dimensions_list"] = self.dimensions_list
130
- return result
131
- else:
132
- return result
133
-
134
-
135
- def _add_sfm_metric(metric: Metric, sfm_metrics: Optional[List[Metric]] = None):
136
- if sfm_metrics is None:
137
- sfm_metrics = []
138
- metric.validate()
139
- sfm_metrics.append(metric)
140
-
141
-
142
- class Extension:
143
- """Base class for Python extensions.
144
-
145
- Attributes:
146
- logger: Embedded logger object for the extension.
147
- """
148
-
149
- _instance: ClassVar = None
150
- schedule_decorators: ClassVar = []
151
-
152
- def __new__(cls):
153
- if Extension._instance is None:
154
- Extension._instance = super(__class__, cls).__new__(cls)
155
- return Extension._instance
156
-
157
- def __init__(self) -> None:
158
- # do not initialize already created singleton
159
- if hasattr(self, "logger"):
160
- return
161
-
162
- # TODO - Move the logging implementation to its own file
163
- # TODO - Add sfm logging
164
- self.logger = extension_logger
165
-
166
- self.extension_config: str = ""
167
- self._feature_sets: dict[str, list[str]] = {}
168
-
169
- # Useful metadata, populated once the extension is started
170
- self.extension_name = "" # Needs to be set by the developer if they so decide
171
- self.extension_version = ""
172
- self.monitoring_config_name = ""
173
- self._task_id = "development_task_id"
174
- self._monitoring_config_id = "development_config_id"
175
-
176
- # The user can override default EEC enrichment for logs
177
- self.log_event_enrichment = True
178
-
179
- # The Communication client
180
- self._client: CommunicationClient = None # type: ignore
181
-
182
- # Set to true when --fastcheck is passed as a parameter
183
- self._is_fastcheck: bool = True
184
-
185
- # If this is true, we are running locally during development
186
- self._running_in_sim: bool = False
187
-
188
- # Response from EEC to /alive/ requests
189
- self._runtime_properties: RuntimeProperties = RuntimeProperties({})
190
-
191
- # The time difference between the local machine and the cluster time, used to sync callbacks with cluster
192
- self._cluster_time_diff: int = 0
193
-
194
- # Optional callback to be invoked during the fastcheck
195
- self._fast_check_callback: Optional[Callable[[ActivationConfig, str], Status]] = None
196
-
197
- # List of all scheduled callbacks we must run
198
- self._scheduled_callbacks: List[WrappedCallback] = []
199
- self._scheduled_callbacks_before_run: List[WrappedCallback] = []
200
-
201
- # Internal callbacks results, used to report statuses
202
- self._internal_callbacks_results: Dict[str, Status] = {}
203
- self._internal_callbacks_results_lock: Lock = Lock()
204
-
205
- # Running callbacks, used to get the callback info when reporting metrics
206
- self._running_callbacks: Dict[int, WrappedCallback] = {}
207
- self._running_callbacks_lock: Lock = Lock()
208
-
209
- self._scheduler = sched.scheduler(time.time, time.sleep)
210
-
211
- # Executors for the callbacks and internal methods
212
- self._callbacks_executor = ThreadPoolExecutor(max_workers=CALLBACKS_THREAD_POOL_SIZE)
213
- self._internal_executor = ThreadPoolExecutor(max_workers=INTERNAL_THREAD_POOL_SIZE)
214
-
215
- # Extension metrics
216
- self._metrics_lock = RLock()
217
- self._metrics: List[str] = []
218
-
219
- # Self monitoring metrics
220
- self._sfm_metrics_lock = Lock()
221
- self._callbackSfmReport: Dict[str, WrappedCallback] = {}
222
-
223
- # Count metric delta signals
224
- self._delta_signal_buffer: set[str] = set()
225
- self._registered_count_metrics: set[str] = set()
226
-
227
- # Self tech rule
228
- self._techrule = ""
229
-
230
- # Error message from caught exception in self.initialize()
231
- self._initialization_error: str = ""
232
-
233
- self._parse_args()
234
-
235
- for function, interval, args, activation_type in Extension.schedule_decorators:
236
- params = (self,)
237
- if args is not None:
238
- params = params + args
239
- self.schedule(function, interval, params, activation_type)
240
-
241
- api_logger.info("-----------------------------------------------------")
242
- api_logger.info(f"Starting {self.__class__} {self.extension_name}, version: {self.get_version()}")
243
-
244
- @property
245
- def is_helper(self) -> bool:
246
- """Internal property used by the EEC."""
247
-
248
- return False
249
-
250
- @property
251
- def task_id(self) -> str:
252
- """Internal property used by the EEC."""
253
-
254
- return self._task_id
255
-
256
- @property
257
- def monitoring_config_id(self) -> str:
258
- """Internal property used by the EEC.
259
-
260
- Represents a unique identifier of the monitoring configuration.
261
- that is assigned to this particular extension instance.
262
- """
263
-
264
- return self._monitoring_config_id
265
-
266
- def run(self):
267
- """Launch the extension instance.
268
-
269
- Calling this method starts the main loop of the extension.
270
-
271
- This method must be invoked once to start the extension,
272
-
273
- if `--fastcheck` is set, the extension will run in fastcheck mode,
274
- otherwise the main loop is started, which periodically runs:
275
-
276
- * The scheduled callbacks
277
- * The heartbeat method
278
- * The metrics publisher method
279
- """
280
-
281
- self._setup_signal_handlers()
282
- if self._is_fastcheck:
283
- return self._run_fastcheck()
284
- self._start_extension_loop()
285
-
286
- def _setup_signal_handlers(self):
287
- if sys.platform == "win32":
288
- signal.signal(signal.SIGBREAK, self._shutdown_signal_handler)
289
- signal.signal(signal.SIGINT, self._shutdown_signal_handler)
290
-
291
- def _shutdown_signal_handler(self, sig, frame): # noqa: ARG002
292
- api_logger.info(f"{signal.Signals(sig).name} captured. Flushing metrics and exiting...")
293
- self.on_shutdown()
294
- self._send_metrics()
295
- self._send_sfm_metrics()
296
- sys.exit(0)
297
-
298
- def on_shutdown(self):
299
- """Callback method to be invoked when the extension is shutting down.
300
-
301
- Called when extension exits after it has received shutdown signal from EEC
302
- This is executed before metrics are flushed to EEC
303
- """
304
- pass
305
-
306
- def _schedule_callback(self, callback: WrappedCallback):
307
- if callback.activation_type is not None and callback.activation_type != self.activation_config.type:
308
- api_logger.info(
309
- f"Skipping {callback} with activation type {callback.activation_type} because it is not {self.activation_config.type}"
310
- )
311
- return
312
-
313
- api_logger.debug(f"Scheduling callback {callback}")
314
-
315
- # These properties are updated after the extension starts
316
- # TODO - These should be part of an ext singleton object instead
317
- callback.cluster_time_diff = self._cluster_time_diff
318
- callback.running_in_sim = self._running_in_sim
319
- self._scheduled_callbacks.append(callback)
320
- self._scheduler.enter(callback.initial_wait_time(), 1, self._callback_iteration, (callback,))
321
-
322
- def schedule(
323
- self,
324
- callback: Callable,
325
- interval: Union[timedelta, int],
326
- args: Optional[tuple] = None,
327
- activation_type: Optional[ActivationType] = None,
328
- ) -> None:
329
- """Schedule a method to be executed periodically.
330
-
331
- The callback method will be periodically invoked in a separate thread.
332
- The callback method is always immediately scheduled for execution.
333
-
334
- Args:
335
- callback: The callback method to be invoked
336
- interval: The time interval between invocations, can be a timedelta object,
337
- or an int representing the number of seconds
338
- args: Arguments to the callback, if any
339
- activation_type: Optional activation type when this callback should run,
340
- can be 'ActivationType.LOCAL' or 'ActivationType.REMOTE'
341
- """
342
-
343
- if isinstance(interval, int):
344
- interval = timedelta(seconds=interval)
345
-
346
- callback = WrappedCallback(interval, callback, api_logger, args, activation_type=activation_type)
347
- if self._is_fastcheck:
348
- self._scheduled_callbacks_before_run.append(callback)
349
- else:
350
- self._schedule_callback(callback)
351
-
352
- def query(self):
353
- """Callback to be executed every minute by default.
354
-
355
- Optional method that can be implemented by subclasses.
356
- The query method is always scheduled to run every minute.
357
- """
358
- pass
359
-
360
- def initialize(self):
361
- """Callback to be executed when the extension starts.
362
-
363
- Called once after the extension starts and the processes arguments are parsed.
364
- Sometimes there are tasks the user needs to do that must happen before runtime,
365
- but after the activation config has been received, example: Setting the schedule frequency
366
- based on the user input on the monitoring configuration, this can be done on this method
367
- """
368
- pass
369
-
370
- def fastcheck(self) -> Status:
371
- """Callback executed when extension is launched.
372
-
373
- Called if the extension is run in the `fastcheck` mode. Only invoked for remote
374
- extensions.
375
- This method is not called if fastcheck callback was already registered with
376
- Extension.register_fastcheck().
377
-
378
- Returns:
379
- Status with optional message whether the fastcheck succeed or failed.
380
- """
381
- return Status(StatusValue.OK)
382
-
383
- def register_fastcheck(self, fast_check_callback: Callable[[ActivationConfig, str], Status]):
384
- """Registers fastcheck callback that is executed in the `fastcheck` mode.
385
-
386
- Extension.fastcheck() is not called if fastcheck callback is registered with this method
387
-
388
- Args:
389
- fast_check_callback: callable called with ActivationConfig and
390
- extension_config arguments. Must return the Status with optional message
391
- whether the fastcheck succeed or failed.
392
- """
393
- if self._fast_check_callback:
394
- api_logger.error("More than one function assigned to fastcheck, last registered one was kept.")
395
-
396
- self._fast_check_callback = fast_check_callback
397
-
398
- def _register_count_metrics(self, *count_metric_entries: CountMetricRegistrationEntry) -> None:
399
- """Send a count metric registration request to EEC.
400
-
401
- Args:
402
- count_metric_entries: CountMetricRegistrationEntry objects for each count metric to register
403
- """
404
- json_pattern = {
405
- metric_entry.metric_key: metric_entry.registration_items_dict() for metric_entry in count_metric_entries
406
- }
407
- self._client.register_count_metrics(json_pattern)
408
-
409
- def _send_count_delta_signal(self, metric_keys: set[str], force: bool = True) -> None:
410
- """Send calculate-delta signal to EEC monotonic converter.
411
-
412
- Args:
413
- metric_keys: List with metrics for which we want to calculate deltas
414
- force: If true, it forces the metrics from cache to be pushed into EEC and then delta signal request is
415
- sent. Otherwise, it puts delta signal request in cache and request is sent after nearest (in time) sending
416
- metrics to EEC event
417
- """
418
-
419
- with self._metrics_lock:
420
- if not force:
421
- for key in metric_keys:
422
- self._delta_signal_buffer.add(key)
423
- return
424
-
425
- self._send_metrics()
426
- self._client.send_count_delta_signal(metric_keys)
427
- self._delta_signal_buffer = {
428
- metric_key for metric_key in self._delta_signal_buffer if metric_key not in metric_keys
429
- }
430
-
431
- def report_metric(
432
- self,
433
- key: str,
434
- value: Union[float, str, int, SummaryStat],
435
- dimensions: Optional[Dict[str, str]] = None,
436
- techrule: Optional[str] = None,
437
- timestamp: Optional[datetime] = None,
438
- metric_type: MetricType = MetricType.GAUGE,
439
- ) -> None:
440
- """Report a metric.
441
-
442
- Metric is sent to EEC using an HTTP request and MINT protocol. EEC then
443
- sends the metrics to the tenant.
444
-
445
- By default, it reports a gauge metric.
446
-
447
- Args:
448
- key: The metric key, must follow the MINT specification
449
- value: The metric value, can be a simple value or a SummaryStat
450
- dimensions: A dictionary of dimensions
451
- techrule: The technology rule string set by self.techrule setter.
452
- timestamp: The timestamp of the metric, defaults to the current time
453
- metric_type: The type of the metric, defaults to MetricType.GAUGE
454
- """
455
-
456
- if techrule:
457
- if not dimensions:
458
- dimensions = {}
459
- if "dt.techrule.id" not in dimensions:
460
- dimensions["dt.techrule.id"] = techrule
461
-
462
- if metric_type == MetricType.COUNT and timestamp is None:
463
- # We must report a timestamp for count metrics
464
- timestamp = datetime.now()
465
-
466
- metric = Metric(key=key, value=value, dimensions=dimensions, metric_type=metric_type, timestamp=timestamp)
467
- self._add_metric(metric)
468
-
469
- def report_mint_lines(self, lines: List[str]) -> None:
470
- """Report mint lines using the MINT protocol
471
-
472
- Examples:
473
- Metric lines must comply with the MINT format.
474
-
475
- >>> self.report_mint_lines(["my_metric 1", "my_other_metric 2"])
476
-
477
- Args:
478
- lines: A list of mint lines
479
- """
480
- self._add_mint_lines(lines)
481
-
482
- def report_event(
483
- self,
484
- title: str,
485
- description: str,
486
- properties: Optional[dict] = None,
487
- timestamp: Optional[datetime] = None,
488
- severity: Union[Severity, str] = Severity.INFO,
489
- ) -> None:
490
- """Report an event using log ingest.
491
-
492
- Args:
493
- title: The title of the event
494
- description: The description of the event
495
- properties: A dictionary of extra event properties
496
- timestamp: The timestamp of the event, defaults to the current time
497
- severity: The severity of the event, defaults to Severity.INFO
498
- """
499
- if timestamp is None:
500
- timestamp = datetime.now(tz=timezone.utc)
501
-
502
- if properties is None:
503
- properties = {}
504
-
505
- event = {
506
- "content": f"{title}\n{description}",
507
- "title": title,
508
- "description": description,
509
- "timestamp": timestamp.strftime(RFC_3339_FORMAT),
510
- "severity": severity.value if isinstance(severity, Severity) else severity,
511
- **self._metadata,
512
- **properties,
513
- }
514
- self._send_events(event)
515
-
516
- def report_dt_event(
517
- self,
518
- event_type: DtEventType,
519
- title: str,
520
- start_time: Optional[int] = None,
521
- end_time: Optional[int] = None,
522
- timeout: Optional[int] = None,
523
- entity_selector: Optional[str] = None,
524
- properties: Optional[dict[str, str]] = None,
525
- ) -> None:
526
- """
527
- Reports an event using the v2 event ingest API.
528
-
529
- Unlike ``report_event``, this directly raises an event or even a problem
530
- based on the specified ``event_type``.
531
-
532
- Note:
533
- For reference see: https://www.dynatrace.com/support/help/dynatrace-api/environment-api/events-v2/post-event
534
-
535
- Args:
536
- event_type: The event type chosen from type Enum (required)
537
- title: The title of the event (required)
538
- start_time: The start time of event in UTC ms, if not set, current timestamp (optional)
539
- end_time: The end time of event in UTC ms, if not set, current timestamp + timeout (optional)
540
- timeout: The timeout of event in minutes, if not set, 15 (optional)
541
- entity_selector: The entity selector, if not set, the event is associated with environment entity (optional)
542
- properties: A map of event properties (optional)
543
- """
544
- event: Dict[str, Any] = {"eventType": event_type, "title": title}
545
- if start_time:
546
- event["startTime"] = start_time
547
- if end_time:
548
- event["endTime"] = end_time
549
- if timeout:
550
- event["timeout"] = timeout
551
- if entity_selector:
552
- event["entitySelector"] = entity_selector
553
- if properties:
554
- event["properties"] = properties
555
-
556
- self._send_dt_event(event)
557
-
558
- def report_dt_event_dict(self, event: dict):
559
- """Report an event using event ingest API with provided dictionary.
560
-
561
- Note:
562
- For reference see: https://www.dynatrace.com/support/help/dynatrace-api/environment-api/events-v2/post-event
563
-
564
- Format of the event dictionary::
565
-
566
- {
567
- "type": "object",
568
- "required": ["eventType", "title"],
569
- "properties": {
570
- "eventType": {
571
- "type": "string",
572
- "enum": [
573
- "CUSTOM_INFO",
574
- "CUSTOM_ANNOTATION",
575
- "CUSTOM_CONFIGURATION",
576
- "CUSTOM_DEPLOYMENT",
577
- "MARKED_FOR_TERMINATION",
578
- "ERROR_EVENT",
579
- "AVAILABILITY_EVENT",
580
- "PERFORMANCE_EVENT",
581
- "RESOURCE_CONTENTION_EVENT",
582
- "CUSTOM_ALERT"
583
- ]
584
- },
585
- "title": {
586
- "type": "string",
587
- "minLength": 1
588
- },
589
- "startTime": {"type": "integer"},
590
- "endTime": {"type": "integer"},
591
- "timeout": {"type": "integer"},
592
- "entitySelector": {"type": "string"},
593
- "properties": {
594
- "type": "object",
595
- "patternProperties": {
596
- "^.*$": {"type": "string"}
597
- }
598
- }
599
- }
600
- }
601
- """
602
-
603
- if "eventType" not in event or "title" not in event:
604
- raise ValueError('"eventType" not present' if "eventType" not in event else '"title" not present in event')
605
- for key, value in event.items():
606
- if DT_EVENT_SCHEMA[key] is None:
607
- msg = f'invalid member: "{key}"'
608
- raise ValueError(msg)
609
- if key == "eventType" and value not in list(DtEventType):
610
- msg = f"Event type must be a DtEventType enum value, got: {value}"
611
- raise ValueError(msg)
612
- if key == "properties":
613
- for prop_key, prop_val in event[key].items():
614
- if not isinstance(prop_key, str) or not isinstance(prop_val, str):
615
- msg = f'invalid "properties" member: {prop_key}: {prop_val}, required: "str": str'
616
- raise ValueError(msg)
617
- self._send_dt_event(event)
618
-
619
- def report_log_event(self, log_event: dict):
620
- """Report a custom log event using log ingest.
621
-
622
- Note:
623
- See reference: https://www.dynatrace.com/support/help/shortlink/log-monitoring-log-data-ingestion
624
-
625
- Args:
626
- log_event: The log event dictionary.
627
- """
628
- self._send_events(log_event)
629
-
630
- def report_log_events(self, log_events: List[dict]):
631
- """Report a list of custom log events using log ingest.
632
-
633
- Args:
634
- log_events: The list of log events
635
- """
636
- self._send_events(log_events)
637
-
638
- def report_log_lines(self, log_lines: List[Union[str, bytes]]):
639
- """Report a list of log lines using log ingest
640
-
641
- Args:
642
- log_lines: The list of log lines
643
- """
644
- events = [{"content": line} for line in log_lines]
645
- self._send_events(events)
646
-
647
- @property
648
- def enabled_feature_sets(self) -> dict[str, list[str]]:
649
- """Map of enabled feautre sets and corresponding metrics.
650
-
651
- Returns:
652
- Dictionary containing enabled feature sets with corresponding
653
- metrics defined in ``extension.yaml``.
654
- """
655
- return {
656
- feature_set_name: metric_keys
657
- for feature_set_name, metric_keys in self._feature_sets.items()
658
- if feature_set_name in self.activation_config.feature_sets
659
- }
660
-
661
- @property
662
- def enabled_feature_sets_names(self) -> list[str]:
663
- """Names of enabled feature sets.
664
-
665
- Returns:
666
- List containing names of enabled feature sets.
667
- """
668
- return self.activation_config.feature_sets
669
-
670
- @property
671
- def enabled_feature_sets_metrics(self) -> list[str]:
672
- """Enabled metrics.
673
-
674
- Returns:
675
- List of all metric keys from enabled feature sets
676
- """
677
- return list(chain(*self.enabled_feature_sets.values()))
678
-
679
- def _parse_args(self):
680
- parser = ArgumentParser(description="Python extension parameters")
681
-
682
- # Production parameters, these are passed by the EEC
683
- parser.add_argument("--dsid", required=False, default=None)
684
- parser.add_argument("--url", required=False)
685
- parser.add_argument("--idtoken", required=False)
686
- parser.add_argument(
687
- "--loglevel",
688
- help="Set extension log level. Info is default.",
689
- type=str,
690
- choices=["debug", "info"],
691
- default="info",
692
- )
693
- parser.add_argument("--fastcheck", action="store_true", default=False)
694
- parser.add_argument("--monitoring_config_id", required=False, default=None)
695
- parser.add_argument("--local-ingest", action="store_true", default=False)
696
- parser.add_argument("--local-ingest-port", required=False, default=14499)
697
-
698
- # Debug parameters, these are used when running the extension locally
699
- parser.add_argument("--extensionconfig", required=False, default=None)
700
- parser.add_argument("--activationconfig", required=False, default="activation.json")
701
-
702
- args, unknown = parser.parse_known_args()
703
- self._is_fastcheck = args.fastcheck
704
- if args.dsid is None:
705
- # DEV mode
706
- self._running_in_sim = True
707
- self._client = DebugClient(
708
- args.activationconfig, args.extensionconfig, api_logger, args.local_ingest, args.local_ingest_port
709
- )
710
- RuntimeProperties.set_default_log_level(args.loglevel)
711
- else:
712
- # EEC mode
713
- self._client = HttpClient(args.url, args.dsid, args.idtoken, api_logger)
714
- self._task_id = args.dsid
715
- self._monitoring_config_id = args.monitoring_config_id
716
- api_logger.info(f"DSID = {self.task_id}, monitoring config id = {self._monitoring_config_id}")
717
-
718
- self.activation_config = ActivationConfig(self._client.get_activation_config())
719
- self.extension_config = self._client.get_extension_config()
720
- self._feature_sets = self._client.get_feature_sets()
721
-
722
- self.monitoring_config_name = self.activation_config.description
723
- self.extension_version = self.activation_config.version
724
-
725
- if not self._is_fastcheck:
726
- try:
727
- self.initialize()
728
- if not self.is_helper:
729
- self.schedule(self.query, timedelta(minutes=1))
730
- except Exception as e:
731
- msg = f"Error running self.initialize {self}: {e!r}"
732
- api_logger.exception(msg)
733
- self._client.send_status(Status(StatusValue.GENERIC_ERROR, msg))
734
- self._initialization_error = msg
735
- raise e
736
-
737
- @property
738
- def _metadata(self) -> dict:
739
- return {
740
- "dt.extension.config.id": self._runtime_properties.extconfig,
741
- "dt.extension.ds": DATASOURCE_TYPE,
742
- "dt.extension.version": self.extension_version,
743
- "dt.extension.name": self.extension_name,
744
- "monitoring.configuration": self.monitoring_config_name,
745
- }
746
-
747
- def _run_fastcheck(self):
748
- api_logger.info(f"Running fastcheck for monitoring configuration '{self.monitoring_config_name}'")
749
- try:
750
- if self._fast_check_callback:
751
- status = self._fast_check_callback(self.activation_config, self.extension_config)
752
- api_logger.info(f"Sending fastcheck status: {status}")
753
- self._client.send_status(status)
754
- return
755
-
756
- status = self.fastcheck()
757
- api_logger.info(f"Sending fastcheck status: {status}")
758
- self._client.send_status(status)
759
- except Exception as e:
760
- status = Status(StatusValue.GENERIC_ERROR, f"Python datasource fastcheck error: {e!r}")
761
- api_logger.error(f"Error running fastcheck {self}: {e!r}")
762
- self._client.send_status(status)
763
- raise
764
-
765
- def _run_callback(self, callback: WrappedCallback):
766
- if not callback.running:
767
- # Add the callback to the list of running callbacks
768
- with self._running_callbacks_lock:
769
- current_thread_id = threading.get_ident()
770
- self._running_callbacks[current_thread_id] = callback
771
-
772
- callback(self.activation_config, self.extension_config)
773
-
774
- with self._sfm_metrics_lock:
775
- self._callbackSfmReport[callback.name()] = callback
776
- # Remove the callback from the list of running callbacks
777
- with self._running_callbacks_lock:
778
- self._running_callbacks.pop(current_thread_id, None)
779
-
780
- def _callback_iteration(self, callback: WrappedCallback):
781
- self._callbacks_executor.submit(self._run_callback, callback)
782
- self._scheduler.enter(callback.interval.total_seconds(), 1, self._callback_iteration, (callback,))
783
-
784
- def _start_extension_loop(self):
785
- api_logger.debug(f"Starting main loop for monitoring configuration: '{self.monitoring_config_name}'")
786
-
787
- # These were scheduled before the extension started, schedule them now
788
- for callback in self._scheduled_callbacks_before_run:
789
- self._schedule_callback(callback)
790
- self._heartbeat_iteration()
791
- self._metrics_iteration()
792
- self._sfm_metrics_iteration()
793
- self._timediff_iteration()
794
- self._scheduler.run()
795
-
796
- def _timediff_iteration(self):
797
- self._internal_executor.submit(self._update_cluster_time_diff)
798
- self._scheduler.enter(TIME_DIFF_INTERVAL.total_seconds(), 1, self._timediff_iteration)
799
-
800
- def _heartbeat_iteration(self):
801
- self._internal_executor.submit(self._heartbeat)
802
- self._scheduler.enter(HEARTBEAT_INTERVAL.total_seconds(), 1, self._heartbeat_iteration)
803
-
804
- def _metrics_iteration(self):
805
- self._internal_executor.submit(self._send_metrics)
806
- self._scheduler.enter(METRIC_SENDING_INTERVAL.total_seconds(), 1, self._metrics_iteration)
807
-
808
- def _sfm_metrics_iteration(self):
809
- self._internal_executor.submit(self._send_sfm_metrics)
810
- self._scheduler.enter(SFM_METRIC_SENDING_INTERVAL.total_seconds(), 1, self._sfm_metrics_iteration)
811
-
812
- def _send_metrics(self):
813
- # TODO - we might need to check size and number of lines before sending
814
- # Maybe break it down into multiple packets
815
- with self._metrics_lock and self._internal_callbacks_results_lock:
816
- if self._metrics:
817
- responses = self._client.send_metrics(self._metrics)
818
-
819
- self._internal_callbacks_results[self._send_metrics.__name__] = Status(StatusValue.OK)
820
- lines_invalid = sum(response.lines_invalid for response in responses)
821
- if lines_invalid > 0:
822
- message = f"{lines_invalid} invalid metric lines found"
823
- self._internal_callbacks_results[self._send_metrics.__name__] = Status(
824
- StatusValue.GENERIC_ERROR, message
825
- )
826
-
827
- api_logger.info(f"Sent {len(self._metrics)} metric lines to EEC: {responses}")
828
- self._metrics = []
829
-
830
- def _prepare_sfm_metrics(self) -> List[str]:
831
- """Prepare self monitoring metrics.
832
-
833
- Builds the list of mint metric lines to send as self monitoring metrics.
834
- """
835
-
836
- sfm_metrics: List[Metric] = []
837
- sfm_dimensions = {"dt.extension.config.id": self.monitoring_config_id}
838
- _add_sfm_metric(
839
- SfmMetric("threads", active_count(), sfm_dimensions, client_facing=True, metric_type=MetricType.DELTA),
840
- sfm_metrics,
841
- )
842
-
843
- for name, callback in self._callbackSfmReport.items():
844
- sfm_dimensions = {"callback": name, "dt.extension.config.id": self.monitoring_config_id}
845
- _add_sfm_metric(
846
- SfmMetric(
847
- "execution.time",
848
- f"{callback.duration_interval_total:.4f}",
849
- sfm_dimensions,
850
- client_facing=True,
851
- metric_type=MetricType.GAUGE,
852
- ),
853
- sfm_metrics,
854
- )
855
- _add_sfm_metric(
856
- SfmMetric(
857
- "execution.total.count",
858
- callback.executions_total,
859
- sfm_dimensions,
860
- client_facing=True,
861
- metric_type=MetricType.DELTA,
862
- ),
863
- sfm_metrics,
864
- )
865
- _add_sfm_metric(
866
- SfmMetric(
867
- "execution.count",
868
- callback.executions_per_interval,
869
- sfm_dimensions,
870
- client_facing=True,
871
- metric_type=MetricType.DELTA,
872
- ),
873
- sfm_metrics,
874
- )
875
- _add_sfm_metric(
876
- SfmMetric(
877
- "execution.ok.count",
878
- callback.ok_count,
879
- sfm_dimensions,
880
- client_facing=True,
881
- metric_type=MetricType.DELTA,
882
- ),
883
- sfm_metrics,
884
- )
885
- _add_sfm_metric(
886
- SfmMetric(
887
- "execution.timeout.count",
888
- callback.timeouts_count,
889
- sfm_dimensions,
890
- client_facing=True,
891
- metric_type=MetricType.DELTA,
892
- ),
893
- sfm_metrics,
894
- )
895
- _add_sfm_metric(
896
- SfmMetric(
897
- "execution.exception.count",
898
- callback.exception_count,
899
- sfm_dimensions,
900
- client_facing=True,
901
- metric_type=MetricType.DELTA,
902
- ),
903
- sfm_metrics,
904
- )
905
- callback.clear_sfm_metrics()
906
- return [metric.to_mint_line() for metric in sfm_metrics]
907
-
908
- def _send_sfm_metrics(self):
909
- with self._sfm_metrics_lock:
910
- lines = self._prepare_sfm_metrics()
911
- # Flushes the cache of metrics, maybe we should only flush if they were successfully sent
912
- self._callbackSfmReport.clear()
913
- response = self._client.send_sfm_metrics(lines)
914
-
915
- with self._internal_callbacks_results_lock:
916
- self._internal_callbacks_results[self._send_sfm_metrics.__name__] = Status(StatusValue.OK)
917
- if response.lines_invalid > 0:
918
- message = f"{response.lines_invalid} invalid metric lines found"
919
- self._internal_callbacks_results[self._send_sfm_metrics.__name__] = Status(
920
- StatusValue.GENERIC_ERROR, message
921
- )
922
-
923
- def _build_current_status(self):
924
- overall_status = Status(StatusValue.OK)
925
-
926
- if self._initialization_error:
927
- overall_status.status = StatusValue.GENERIC_ERROR
928
- overall_status.message = self._initialization_error
929
- return overall_status
930
-
931
- internal_callback_error = False
932
- messages = []
933
- with self._internal_callbacks_results_lock:
934
- for callback, result in self._internal_callbacks_results.items():
935
- if result.is_error():
936
- internal_callback_error = True
937
- overall_status.status = result.status
938
- messages.append(f"{callback}: {result.message}")
939
- if internal_callback_error:
940
- overall_status.message = "\n".join(messages)
941
- return overall_status
942
-
943
- for callback in self._scheduled_callbacks:
944
- overall_status.timestamp = int(callback.get_adjusted_metric_timestamp().timestamp() * 1000)
945
- if callback.status.is_error():
946
- overall_status.status = callback.status.status
947
- messages.append(f"{callback}: {callback.status.message}")
948
-
949
- overall_status.message = "\n".join(messages)
950
- return overall_status
951
-
952
- def _update_cluster_time_diff(self):
953
- self._cluster_time_diff = self._client.get_cluster_time_diff()
954
- for callback in self._scheduled_callbacks:
955
- callback.cluster_time_diff = self._cluster_time_diff
956
-
957
- def _heartbeat(self):
958
- response = bytes("not set", "utf-8")
959
- try:
960
- overall_status = self._build_current_status()
961
- response = self._client.send_status(overall_status)
962
- self._runtime_properties = RuntimeProperties(response)
963
- except Exception as e:
964
- api_logger.error(f"Heartbeat failed because {e}, response {response}", exc_info=True)
965
-
966
- def __del__(self):
967
- self._callbacks_executor.shutdown()
968
- self._internal_executor.shutdown()
969
-
970
- def _add_metric(self, metric: Metric):
971
- metric.validate()
972
-
973
- with self._running_callbacks_lock:
974
- current_thread_id = threading.get_ident()
975
- current_callback = self._running_callbacks.get(current_thread_id)
976
-
977
- if current_callback is not None and metric.timestamp is None:
978
- # Adjust the metric timestamp according to the callback start time
979
- # If the user manually set a metric timestamp, don't adjust it
980
- metric.timestamp = current_callback.get_adjusted_metric_timestamp()
981
- elif current_callback is None and metric.timestamp is None:
982
- api_logger.debug(
983
- f"Metric {metric} was added by unknown thread {current_thread_id}, cannot adjust the timestamp"
984
- )
985
-
986
- with self._metrics_lock:
987
- self._metrics.append(metric.to_mint_line())
988
-
989
- def _add_mint_lines(self, lines: List[str]):
990
- with self._metrics_lock:
991
- self._metrics.extend(lines)
992
-
993
- def _send_events_internal(self, events: Union[dict, List[dict]]):
994
- response = self._client.send_events(events, self.log_event_enrichment)
995
- with self._internal_callbacks_results_lock:
996
- self._internal_callbacks_results[self._send_events.__name__] = Status(StatusValue.OK)
997
- if not response or "error" not in response or "message" not in response["error"]:
998
- return
999
- self._internal_callbacks_results[self._send_events.__name__] = Status(
1000
- StatusValue.GENERIC_ERROR, response["error"]["message"]
1001
- )
1002
-
1003
- def _send_events(self, events: Union[dict, List[dict]]):
1004
- self._internal_executor.submit(self._send_events_internal, events)
1005
-
1006
- def _send_dt_event(self, event: dict[str, str | int | dict[str, str]]):
1007
- self._client.send_dt_event(event)
1008
-
1009
- def get_version(self) -> str:
1010
- """Return the version of extensions sdk library."""
1011
-
1012
- return __version__
1013
-
1014
- @property
1015
- def techrule(self) -> str:
1016
- """Internal property used by the EEC."""
1017
-
1018
- return self._techrule
1019
-
1020
- @techrule.setter
1021
- def techrule(self, value):
1022
- self._techrule = value
1023
-
1024
- def get_activation_config(self) -> ActivationConfig:
1025
- """Retrieve the activation config.
1026
-
1027
- Represents activation configuration assigned to this particular
1028
- extension instance.
1029
-
1030
- Returns:
1031
- ActivationConfig object.
1032
- """
1033
- return self.activation_config
1
+ # SPDX-FileCopyrightText: 2023-present Dynatrace LLC
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ import logging
6
+ import sched
7
+ import signal
8
+ import sys
9
+ import threading
10
+ import time
11
+ from argparse import ArgumentParser
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from datetime import datetime, timedelta, timezone
14
+ from enum import Enum
15
+ from itertools import chain
16
+ from threading import Lock, RLock, active_count
17
+ from typing import Any, Callable, ClassVar, Dict, List, NamedTuple, Optional, Union
18
+
19
+ from ..__about__ import __version__
20
+ from .activation import ActivationConfig, ActivationType
21
+ from .callback import WrappedCallback
22
+ from .communication import CommunicationClient, DebugClient, HttpClient, Status, StatusValue
23
+ from .event import Severity
24
+ from .metric import Metric, MetricType, SfmMetric, SummaryStat
25
+ from .runtime import RuntimeProperties
26
+
27
+ HEARTBEAT_INTERVAL = timedelta(seconds=30)
28
+ METRIC_SENDING_INTERVAL = timedelta(seconds=30)
29
+ SFM_METRIC_SENDING_INTERVAL = timedelta(seconds=60)
30
+ TIME_DIFF_INTERVAL = timedelta(seconds=60)
31
+
32
+ CALLBACKS_THREAD_POOL_SIZE = 100
33
+ INTERNAL_THREAD_POOL_SIZE = 20
34
+
35
+ RFC_3339_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
36
+ DATASOURCE_TYPE = "python"
37
+
38
+ logging.raiseExceptions = False
39
+ formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s (%(threadName)s): %(message)s")
40
+ error_handler = logging.StreamHandler()
41
+ error_handler.addFilter(lambda record: record.levelno >= logging.ERROR)
42
+ error_handler.setFormatter(formatter)
43
+ std_handler = logging.StreamHandler(sys.stdout)
44
+ std_handler.addFilter(lambda record: record.levelno < logging.ERROR)
45
+ std_handler.setFormatter(formatter)
46
+ extension_logger = logging.getLogger(__name__)
47
+ extension_logger.setLevel(logging.INFO)
48
+ extension_logger.addHandler(error_handler)
49
+ extension_logger.addHandler(std_handler)
50
+
51
+ api_logger = logging.getLogger("api")
52
+ api_logger.setLevel(logging.INFO)
53
+ api_logger.addHandler(error_handler)
54
+ api_logger.addHandler(std_handler)
55
+
56
+ DT_EVENT_SCHEMA = {
57
+ "eventType": str,
58
+ "title": str,
59
+ "startTime": int,
60
+ "endTime": int,
61
+ "timeout": int,
62
+ "entitySelector": str,
63
+ "properties": dict,
64
+ }
65
+
66
+
67
+ class AggregationMode(Enum):
68
+ ALL = "include_all"
69
+ NONE = "include_none"
70
+ LIST = "include_list"
71
+
72
+
73
+ class DtEventType(str, Enum):
74
+ """Event type.
75
+
76
+ Note:
77
+ Official API v2 documentation:
78
+
79
+ https://docs.dynatrace.com/docs/dynatrace-api/environment-api/events-v2/post-event
80
+ """
81
+
82
+ CUSTOM_INFO = "CUSTOM_INFO"
83
+ CUSTOM_ALERT = "CUSTOM_ALERT"
84
+ CUSTOM_ANNOTATION = "CUSTOM_ANNOTATION"
85
+ CUSTOM_CONFIGURATION = "CUSTOM_CONFIGURATION"
86
+ CUSTOM_DEPLOYMENT = "CUSTOM_DEPLOYMENT"
87
+ MARKED_FOR_TERMINATION = "MARKED_FOR_TERMINATION"
88
+ ERROR_EVENT = "ERROR_EVENT"
89
+ AVAILABILITY_EVENT = "AVAILABILITY_EVENT"
90
+ RESOURCE_CONTENTION_EVENT = "RESOURCE_CONTENTION_EVENT"
91
+
92
+
93
+ class CountMetricRegistrationEntry(NamedTuple):
94
+ metric_key: str
95
+ aggregation_mode: AggregationMode
96
+ dimensions_list: list[str]
97
+
98
+ @staticmethod
99
+ def make_list(metric_key: str, dimensions_list: List[str]):
100
+ """Build an entry that uses defined list of dimensions for aggregation.
101
+
102
+ Args:
103
+ metric_key: Metric key in string.
104
+ dimensions_list: List of dimensions.
105
+ """
106
+ return CountMetricRegistrationEntry(metric_key, AggregationMode.LIST, dimensions_list)
107
+
108
+ @staticmethod
109
+ def make_all(metric_key: str):
110
+ """Build an entry that uses all mint dimensions for aggregation.
111
+
112
+ Args:
113
+ metric_key: Metric key in string.
114
+ """
115
+ return CountMetricRegistrationEntry(metric_key, AggregationMode.ALL, [])
116
+
117
+ @staticmethod
118
+ def make_none(metric_key: str):
119
+ """Build an entry that uses none of mint dimensions for aggregation.
120
+
121
+ Args:
122
+ metric_key: Metric key in string.
123
+ """
124
+ return CountMetricRegistrationEntry(metric_key, AggregationMode.NONE, [])
125
+
126
+ def registration_items_dict(self):
127
+ result = {"aggregation_mode": self.aggregation_mode.value}
128
+ if self.aggregation_mode == AggregationMode.LIST:
129
+ result["dimensions_list"] = self.dimensions_list
130
+ return result
131
+ else:
132
+ return result
133
+
134
+
135
+ def _add_sfm_metric(metric: Metric, sfm_metrics: Optional[List[Metric]] = None):
136
+ if sfm_metrics is None:
137
+ sfm_metrics = []
138
+ metric.validate()
139
+ sfm_metrics.append(metric)
140
+
141
+
142
+ class Extension:
143
+ """Base class for Python extensions.
144
+
145
+ Attributes:
146
+ logger: Embedded logger object for the extension.
147
+ """
148
+
149
+ _instance: ClassVar = None
150
+ schedule_decorators: ClassVar = []
151
+
152
+ def __new__(cls):
153
+ if Extension._instance is None:
154
+ Extension._instance = super(__class__, cls).__new__(cls)
155
+ return Extension._instance
156
+
157
+ def __init__(self) -> None:
158
+ # do not initialize already created singleton
159
+ if hasattr(self, "logger"):
160
+ return
161
+
162
+ # TODO - Move the logging implementation to its own file
163
+ # TODO - Add sfm logging
164
+ self.logger = extension_logger
165
+
166
+ self.extension_config: str = ""
167
+ self._feature_sets: dict[str, list[str]] = {}
168
+
169
+ # Useful metadata, populated once the extension is started
170
+ self.extension_name = "" # Needs to be set by the developer if they so decide
171
+ self.extension_version = ""
172
+ self.monitoring_config_name = ""
173
+ self._task_id = "development_task_id"
174
+ self._monitoring_config_id = "development_config_id"
175
+
176
+ # The user can override default EEC enrichment for logs
177
+ self.log_event_enrichment = True
178
+
179
+ # The Communication client
180
+ self._client: CommunicationClient = None # type: ignore
181
+
182
+ # Set to true when --fastcheck is passed as a parameter
183
+ self._is_fastcheck: bool = True
184
+
185
+ # If this is true, we are running locally during development
186
+ self._running_in_sim: bool = False
187
+
188
+ # Response from EEC to /alive/ requests
189
+ self._runtime_properties: RuntimeProperties = RuntimeProperties({})
190
+
191
+ # The time difference between the local machine and the cluster time, used to sync callbacks with cluster
192
+ self._cluster_time_diff: int = 0
193
+
194
+ # Optional callback to be invoked during the fastcheck
195
+ self._fast_check_callback: Optional[Callable[[ActivationConfig, str], Status]] = None
196
+
197
+ # List of all scheduled callbacks we must run
198
+ self._scheduled_callbacks: List[WrappedCallback] = []
199
+ self._scheduled_callbacks_before_run: List[WrappedCallback] = []
200
+
201
+ # Internal callbacks results, used to report statuses
202
+ self._internal_callbacks_results: Dict[str, Status] = {}
203
+ self._internal_callbacks_results_lock: Lock = Lock()
204
+
205
+ # Running callbacks, used to get the callback info when reporting metrics
206
+ self._running_callbacks: Dict[int, WrappedCallback] = {}
207
+ self._running_callbacks_lock: Lock = Lock()
208
+
209
+ self._scheduler = sched.scheduler(time.time, time.sleep)
210
+
211
+ # Executors for the callbacks and internal methods
212
+ self._callbacks_executor = ThreadPoolExecutor(max_workers=CALLBACKS_THREAD_POOL_SIZE)
213
+ self._internal_executor = ThreadPoolExecutor(max_workers=INTERNAL_THREAD_POOL_SIZE)
214
+
215
+ # Extension metrics
216
+ self._metrics_lock = RLock()
217
+ self._metrics: List[str] = []
218
+
219
+ # Self monitoring metrics
220
+ self._sfm_metrics_lock = Lock()
221
+ self._callbackSfmReport: Dict[str, WrappedCallback] = {}
222
+
223
+ # Count metric delta signals
224
+ self._delta_signal_buffer: set[str] = set()
225
+ self._registered_count_metrics: set[str] = set()
226
+
227
+ # Self tech rule
228
+ self._techrule = ""
229
+
230
+ # Error message from caught exception in self.initialize()
231
+ self._initialization_error: str = ""
232
+
233
+ self._parse_args()
234
+
235
+ for function, interval, args, activation_type in Extension.schedule_decorators:
236
+ params = (self,)
237
+ if args is not None:
238
+ params = params + args
239
+ self.schedule(function, interval, params, activation_type)
240
+
241
+ api_logger.info("-----------------------------------------------------")
242
+ api_logger.info(f"Starting {self.__class__} {self.extension_name}, version: {self.get_version()}")
243
+
244
+ @property
245
+ def is_helper(self) -> bool:
246
+ """Internal property used by the EEC."""
247
+
248
+ return False
249
+
250
+ @property
251
+ def task_id(self) -> str:
252
+ """Internal property used by the EEC."""
253
+
254
+ return self._task_id
255
+
256
+ @property
257
+ def monitoring_config_id(self) -> str:
258
+ """Internal property used by the EEC.
259
+
260
+ Represents a unique identifier of the monitoring configuration.
261
+ that is assigned to this particular extension instance.
262
+ """
263
+
264
+ return self._monitoring_config_id
265
+
266
+ def run(self):
267
+ """Launch the extension instance.
268
+
269
+ Calling this method starts the main loop of the extension.
270
+
271
+ This method must be invoked once to start the extension,
272
+
273
+ if `--fastcheck` is set, the extension will run in fastcheck mode,
274
+ otherwise the main loop is started, which periodically runs:
275
+
276
+ * The scheduled callbacks
277
+ * The heartbeat method
278
+ * The metrics publisher method
279
+ """
280
+
281
+ self._setup_signal_handlers()
282
+ if self._is_fastcheck:
283
+ return self._run_fastcheck()
284
+ self._start_extension_loop()
285
+
286
+ def _setup_signal_handlers(self):
287
+ if sys.platform == "win32":
288
+ signal.signal(signal.SIGBREAK, self._shutdown_signal_handler)
289
+ signal.signal(signal.SIGINT, self._shutdown_signal_handler)
290
+
291
+ def _shutdown_signal_handler(self, sig, frame): # noqa: ARG002
292
+ api_logger.info(f"{signal.Signals(sig).name} captured. Flushing metrics and exiting...")
293
+ self.on_shutdown()
294
+ self._send_metrics()
295
+ self._send_sfm_metrics()
296
+ sys.exit(0)
297
+
298
+ def on_shutdown(self):
299
+ """Callback method to be invoked when the extension is shutting down.
300
+
301
+ Called when extension exits after it has received shutdown signal from EEC
302
+ This is executed before metrics are flushed to EEC
303
+ """
304
+ pass
305
+
306
+ def _schedule_callback(self, callback: WrappedCallback):
307
+ if callback.activation_type is not None and callback.activation_type != self.activation_config.type:
308
+ api_logger.info(
309
+ f"Skipping {callback} with activation type {callback.activation_type} because it is not {self.activation_config.type}"
310
+ )
311
+ return
312
+
313
+ api_logger.debug(f"Scheduling callback {callback}")
314
+
315
+ # These properties are updated after the extension starts
316
+ # TODO - These should be part of an ext singleton object instead
317
+ callback.cluster_time_diff = self._cluster_time_diff
318
+ callback.running_in_sim = self._running_in_sim
319
+ self._scheduled_callbacks.append(callback)
320
+ self._scheduler.enter(callback.initial_wait_time(), 1, self._callback_iteration, (callback,))
321
+
322
+ def schedule(
323
+ self,
324
+ callback: Callable,
325
+ interval: Union[timedelta, int],
326
+ args: Optional[tuple] = None,
327
+ activation_type: Optional[ActivationType] = None,
328
+ ) -> None:
329
+ """Schedule a method to be executed periodically.
330
+
331
+ The callback method will be periodically invoked in a separate thread.
332
+ The callback method is always immediately scheduled for execution.
333
+
334
+ Args:
335
+ callback: The callback method to be invoked
336
+ interval: The time interval between invocations, can be a timedelta object,
337
+ or an int representing the number of seconds
338
+ args: Arguments to the callback, if any
339
+ activation_type: Optional activation type when this callback should run,
340
+ can be 'ActivationType.LOCAL' or 'ActivationType.REMOTE'
341
+ """
342
+
343
+ if isinstance(interval, int):
344
+ interval = timedelta(seconds=interval)
345
+
346
+ callback = WrappedCallback(interval, callback, api_logger, args, activation_type=activation_type)
347
+ if self._is_fastcheck:
348
+ self._scheduled_callbacks_before_run.append(callback)
349
+ else:
350
+ self._schedule_callback(callback)
351
+
352
+ def query(self):
353
+ """Callback to be executed every minute by default.
354
+
355
+ Optional method that can be implemented by subclasses.
356
+ The query method is always scheduled to run every minute.
357
+ """
358
+ pass
359
+
360
+ def initialize(self):
361
+ """Callback to be executed when the extension starts.
362
+
363
+ Called once after the extension starts and the processes arguments are parsed.
364
+ Sometimes there are tasks the user needs to do that must happen before runtime,
365
+ but after the activation config has been received, example: Setting the schedule frequency
366
+ based on the user input on the monitoring configuration, this can be done on this method
367
+ """
368
+ pass
369
+
370
+ def fastcheck(self) -> Status:
371
+ """Callback executed when extension is launched.
372
+
373
+ Called if the extension is run in the `fastcheck` mode. Only invoked for remote
374
+ extensions.
375
+ This method is not called if fastcheck callback was already registered with
376
+ Extension.register_fastcheck().
377
+
378
+ Returns:
379
+ Status with optional message whether the fastcheck succeed or failed.
380
+ """
381
+ return Status(StatusValue.OK)
382
+
383
+ def register_fastcheck(self, fast_check_callback: Callable[[ActivationConfig, str], Status]):
384
+ """Registers fastcheck callback that is executed in the `fastcheck` mode.
385
+
386
+ Extension.fastcheck() is not called if fastcheck callback is registered with this method
387
+
388
+ Args:
389
+ fast_check_callback: callable called with ActivationConfig and
390
+ extension_config arguments. Must return the Status with optional message
391
+ whether the fastcheck succeed or failed.
392
+ """
393
+ if self._fast_check_callback:
394
+ api_logger.error("More than one function assigned to fastcheck, last registered one was kept.")
395
+
396
+ self._fast_check_callback = fast_check_callback
397
+
398
+ def _register_count_metrics(self, *count_metric_entries: CountMetricRegistrationEntry) -> None:
399
+ """Send a count metric registration request to EEC.
400
+
401
+ Args:
402
+ count_metric_entries: CountMetricRegistrationEntry objects for each count metric to register
403
+ """
404
+ json_pattern = {
405
+ metric_entry.metric_key: metric_entry.registration_items_dict() for metric_entry in count_metric_entries
406
+ }
407
+ self._client.register_count_metrics(json_pattern)
408
+
409
+ def _send_count_delta_signal(self, metric_keys: set[str], force: bool = True) -> None:
410
+ """Send calculate-delta signal to EEC monotonic converter.
411
+
412
+ Args:
413
+ metric_keys: List with metrics for which we want to calculate deltas
414
+ force: If true, it forces the metrics from cache to be pushed into EEC and then delta signal request is
415
+ sent. Otherwise, it puts delta signal request in cache and request is sent after nearest (in time) sending
416
+ metrics to EEC event
417
+ """
418
+
419
+ with self._metrics_lock:
420
+ if not force:
421
+ for key in metric_keys:
422
+ self._delta_signal_buffer.add(key)
423
+ return
424
+
425
+ self._send_metrics()
426
+ self._client.send_count_delta_signal(metric_keys)
427
+ self._delta_signal_buffer = {
428
+ metric_key for metric_key in self._delta_signal_buffer if metric_key not in metric_keys
429
+ }
430
+
431
+ def report_metric(
432
+ self,
433
+ key: str,
434
+ value: Union[float, str, int, SummaryStat],
435
+ dimensions: Optional[Dict[str, str]] = None,
436
+ techrule: Optional[str] = None,
437
+ timestamp: Optional[datetime] = None,
438
+ metric_type: MetricType = MetricType.GAUGE,
439
+ ) -> None:
440
+ """Report a metric.
441
+
442
+ Metric is sent to EEC using an HTTP request and MINT protocol. EEC then
443
+ sends the metrics to the tenant.
444
+
445
+ By default, it reports a gauge metric.
446
+
447
+ Args:
448
+ key: The metric key, must follow the MINT specification
449
+ value: The metric value, can be a simple value or a SummaryStat
450
+ dimensions: A dictionary of dimensions
451
+ techrule: The technology rule string set by self.techrule setter.
452
+ timestamp: The timestamp of the metric, defaults to the current time
453
+ metric_type: The type of the metric, defaults to MetricType.GAUGE
454
+ """
455
+
456
+ if techrule:
457
+ if not dimensions:
458
+ dimensions = {}
459
+ if "dt.techrule.id" not in dimensions:
460
+ dimensions["dt.techrule.id"] = techrule
461
+
462
+ if metric_type == MetricType.COUNT and timestamp is None:
463
+ # We must report a timestamp for count metrics
464
+ timestamp = datetime.now()
465
+
466
+ metric = Metric(key=key, value=value, dimensions=dimensions, metric_type=metric_type, timestamp=timestamp)
467
+ self._add_metric(metric)
468
+
469
+ def report_mint_lines(self, lines: List[str]) -> None:
470
+ """Report mint lines using the MINT protocol
471
+
472
+ Examples:
473
+ Metric lines must comply with the MINT format.
474
+
475
+ >>> self.report_mint_lines(["my_metric 1", "my_other_metric 2"])
476
+
477
+ Args:
478
+ lines: A list of mint lines
479
+ """
480
+ self._add_mint_lines(lines)
481
+
482
+ def report_event(
483
+ self,
484
+ title: str,
485
+ description: str,
486
+ properties: Optional[dict] = None,
487
+ timestamp: Optional[datetime] = None,
488
+ severity: Union[Severity, str] = Severity.INFO,
489
+ ) -> None:
490
+ """Report an event using log ingest.
491
+
492
+ Args:
493
+ title: The title of the event
494
+ description: The description of the event
495
+ properties: A dictionary of extra event properties
496
+ timestamp: The timestamp of the event, defaults to the current time
497
+ severity: The severity of the event, defaults to Severity.INFO
498
+ """
499
+ if timestamp is None:
500
+ timestamp = datetime.now(tz=timezone.utc)
501
+
502
+ if properties is None:
503
+ properties = {}
504
+
505
+ event = {
506
+ "content": f"{title}\n{description}",
507
+ "title": title,
508
+ "description": description,
509
+ "timestamp": timestamp.strftime(RFC_3339_FORMAT),
510
+ "severity": severity.value if isinstance(severity, Severity) else severity,
511
+ **self._metadata,
512
+ **properties,
513
+ }
514
+ self._send_events(event)
515
+
516
+ def report_dt_event(
517
+ self,
518
+ event_type: DtEventType,
519
+ title: str,
520
+ start_time: Optional[int] = None,
521
+ end_time: Optional[int] = None,
522
+ timeout: Optional[int] = None,
523
+ entity_selector: Optional[str] = None,
524
+ properties: Optional[dict[str, str]] = None,
525
+ ) -> None:
526
+ """
527
+ Reports an event using the v2 event ingest API.
528
+
529
+ Unlike ``report_event``, this directly raises an event or even a problem
530
+ based on the specified ``event_type``.
531
+
532
+ Note:
533
+ For reference see: https://www.dynatrace.com/support/help/dynatrace-api/environment-api/events-v2/post-event
534
+
535
+ Args:
536
+ event_type: The event type chosen from type Enum (required)
537
+ title: The title of the event (required)
538
+ start_time: The start time of event in UTC ms, if not set, current timestamp (optional)
539
+ end_time: The end time of event in UTC ms, if not set, current timestamp + timeout (optional)
540
+ timeout: The timeout of event in minutes, if not set, 15 (optional)
541
+ entity_selector: The entity selector, if not set, the event is associated with environment entity (optional)
542
+ properties: A map of event properties (optional)
543
+ """
544
+ event: Dict[str, Any] = {"eventType": event_type, "title": title}
545
+ if start_time:
546
+ event["startTime"] = start_time
547
+ if end_time:
548
+ event["endTime"] = end_time
549
+ if timeout:
550
+ event["timeout"] = timeout
551
+ if entity_selector:
552
+ event["entitySelector"] = entity_selector
553
+ if properties:
554
+ event["properties"] = properties
555
+
556
+ self._send_dt_event(event)
557
+
558
+ def report_dt_event_dict(self, event: dict):
559
+ """Report an event using event ingest API with provided dictionary.
560
+
561
+ Note:
562
+ For reference see: https://www.dynatrace.com/support/help/dynatrace-api/environment-api/events-v2/post-event
563
+
564
+ Format of the event dictionary::
565
+
566
+ {
567
+ "type": "object",
568
+ "required": ["eventType", "title"],
569
+ "properties": {
570
+ "eventType": {
571
+ "type": "string",
572
+ "enum": [
573
+ "CUSTOM_INFO",
574
+ "CUSTOM_ANNOTATION",
575
+ "CUSTOM_CONFIGURATION",
576
+ "CUSTOM_DEPLOYMENT",
577
+ "MARKED_FOR_TERMINATION",
578
+ "ERROR_EVENT",
579
+ "AVAILABILITY_EVENT",
580
+ "PERFORMANCE_EVENT",
581
+ "RESOURCE_CONTENTION_EVENT",
582
+ "CUSTOM_ALERT"
583
+ ]
584
+ },
585
+ "title": {
586
+ "type": "string",
587
+ "minLength": 1
588
+ },
589
+ "startTime": {"type": "integer"},
590
+ "endTime": {"type": "integer"},
591
+ "timeout": {"type": "integer"},
592
+ "entitySelector": {"type": "string"},
593
+ "properties": {
594
+ "type": "object",
595
+ "patternProperties": {
596
+ "^.*$": {"type": "string"}
597
+ }
598
+ }
599
+ }
600
+ }
601
+ """
602
+
603
+ if "eventType" not in event or "title" not in event:
604
+ raise ValueError('"eventType" not present' if "eventType" not in event else '"title" not present in event')
605
+ for key, value in event.items():
606
+ if DT_EVENT_SCHEMA[key] is None:
607
+ msg = f'invalid member: "{key}"'
608
+ raise ValueError(msg)
609
+ if key == "eventType" and value not in list(DtEventType):
610
+ msg = f"Event type must be a DtEventType enum value, got: {value}"
611
+ raise ValueError(msg)
612
+ if key == "properties":
613
+ for prop_key, prop_val in event[key].items():
614
+ if not isinstance(prop_key, str) or not isinstance(prop_val, str):
615
+ msg = f'invalid "properties" member: {prop_key}: {prop_val}, required: "str": str'
616
+ raise ValueError(msg)
617
+ self._send_dt_event(event)
618
+
619
+ def report_log_event(self, log_event: dict):
620
+ """Report a custom log event using log ingest.
621
+
622
+ Note:
623
+ See reference: https://www.dynatrace.com/support/help/shortlink/log-monitoring-log-data-ingestion
624
+
625
+ Args:
626
+ log_event: The log event dictionary.
627
+ """
628
+ self._send_events(log_event)
629
+
630
+ def report_log_events(self, log_events: List[dict]):
631
+ """Report a list of custom log events using log ingest.
632
+
633
+ Args:
634
+ log_events: The list of log events
635
+ """
636
+ self._send_events(log_events)
637
+
638
+ def report_log_lines(self, log_lines: List[Union[str, bytes]]):
639
+ """Report a list of log lines using log ingest
640
+
641
+ Args:
642
+ log_lines: The list of log lines
643
+ """
644
+ events = [{"content": line} for line in log_lines]
645
+ self._send_events(events)
646
+
647
+ @property
648
+ def enabled_feature_sets(self) -> dict[str, list[str]]:
649
+ """Map of enabled feautre sets and corresponding metrics.
650
+
651
+ Returns:
652
+ Dictionary containing enabled feature sets with corresponding
653
+ metrics defined in ``extension.yaml``.
654
+ """
655
+ return {
656
+ feature_set_name: metric_keys
657
+ for feature_set_name, metric_keys in self._feature_sets.items()
658
+ if feature_set_name in self.activation_config.feature_sets or feature_set_name == "default"
659
+ }
660
+
661
+ @property
662
+ def enabled_feature_sets_names(self) -> list[str]:
663
+ """Names of enabled feature sets.
664
+
665
+ Returns:
666
+ List containing names of enabled feature sets.
667
+ """
668
+ return list(self.enabled_feature_sets.keys())
669
+
670
+ @property
671
+ def enabled_feature_sets_metrics(self) -> list[str]:
672
+ """Enabled metrics.
673
+
674
+ Returns:
675
+ List of all metric keys from enabled feature sets
676
+ """
677
+ return list(chain(*self.enabled_feature_sets.values()))
678
+
679
+ def _parse_args(self):
680
+ parser = ArgumentParser(description="Python extension parameters")
681
+
682
+ # Production parameters, these are passed by the EEC
683
+ parser.add_argument("--dsid", required=False, default=None)
684
+ parser.add_argument("--url", required=False)
685
+ parser.add_argument("--idtoken", required=False)
686
+ parser.add_argument(
687
+ "--loglevel",
688
+ help="Set extension log level. Info is default.",
689
+ type=str,
690
+ choices=["debug", "info"],
691
+ default="info",
692
+ )
693
+ parser.add_argument("--fastcheck", action="store_true", default=False)
694
+ parser.add_argument("--monitoring_config_id", required=False, default=None)
695
+ parser.add_argument("--local-ingest", action="store_true", default=False)
696
+ parser.add_argument("--local-ingest-port", required=False, default=14499)
697
+
698
+ # Debug parameters, these are used when running the extension locally
699
+ parser.add_argument("--extensionconfig", required=False, default=None)
700
+ parser.add_argument("--activationconfig", required=False, default="activation.json")
701
+
702
+ args, unknown = parser.parse_known_args()
703
+ self._is_fastcheck = args.fastcheck
704
+ if args.dsid is None:
705
+ # DEV mode
706
+ self._running_in_sim = True
707
+ self._client = DebugClient(
708
+ args.activationconfig, args.extensionconfig, api_logger, args.local_ingest, args.local_ingest_port
709
+ )
710
+ RuntimeProperties.set_default_log_level(args.loglevel)
711
+ else:
712
+ # EEC mode
713
+ self._client = HttpClient(args.url, args.dsid, args.idtoken, api_logger)
714
+ self._task_id = args.dsid
715
+ self._monitoring_config_id = args.monitoring_config_id
716
+ api_logger.info(f"DSID = {self.task_id}, monitoring config id = {self._monitoring_config_id}")
717
+
718
+ self.activation_config = ActivationConfig(self._client.get_activation_config())
719
+ self.extension_config = self._client.get_extension_config()
720
+ self._feature_sets = self._client.get_feature_sets()
721
+
722
+ self.monitoring_config_name = self.activation_config.description
723
+ self.extension_version = self.activation_config.version
724
+
725
+ if not self._is_fastcheck:
726
+ try:
727
+ self.initialize()
728
+ if not self.is_helper:
729
+ self.schedule(self.query, timedelta(minutes=1))
730
+ except Exception as e:
731
+ msg = f"Error running self.initialize {self}: {e!r}"
732
+ api_logger.exception(msg)
733
+ self._client.send_status(Status(StatusValue.GENERIC_ERROR, msg))
734
+ self._initialization_error = msg
735
+ raise e
736
+
737
+ @property
738
+ def _metadata(self) -> dict:
739
+ return {
740
+ "dt.extension.config.id": self._runtime_properties.extconfig,
741
+ "dt.extension.ds": DATASOURCE_TYPE,
742
+ "dt.extension.version": self.extension_version,
743
+ "dt.extension.name": self.extension_name,
744
+ "monitoring.configuration": self.monitoring_config_name,
745
+ }
746
+
747
+ def _run_fastcheck(self):
748
+ api_logger.info(f"Running fastcheck for monitoring configuration '{self.monitoring_config_name}'")
749
+ try:
750
+ if self._fast_check_callback:
751
+ status = self._fast_check_callback(self.activation_config, self.extension_config)
752
+ api_logger.info(f"Sending fastcheck status: {status}")
753
+ self._client.send_status(status)
754
+ return
755
+
756
+ status = self.fastcheck()
757
+ api_logger.info(f"Sending fastcheck status: {status}")
758
+ self._client.send_status(status)
759
+ except Exception as e:
760
+ status = Status(StatusValue.GENERIC_ERROR, f"Python datasource fastcheck error: {e!r}")
761
+ api_logger.error(f"Error running fastcheck {self}: {e!r}")
762
+ self._client.send_status(status)
763
+ raise
764
+
765
+ def _run_callback(self, callback: WrappedCallback):
766
+ if not callback.running:
767
+ # Add the callback to the list of running callbacks
768
+ with self._running_callbacks_lock:
769
+ current_thread_id = threading.get_ident()
770
+ self._running_callbacks[current_thread_id] = callback
771
+
772
+ callback(self.activation_config, self.extension_config)
773
+
774
+ with self._sfm_metrics_lock:
775
+ self._callbackSfmReport[callback.name()] = callback
776
+ # Remove the callback from the list of running callbacks
777
+ with self._running_callbacks_lock:
778
+ self._running_callbacks.pop(current_thread_id, None)
779
+
780
+ def _callback_iteration(self, callback: WrappedCallback):
781
+ self._callbacks_executor.submit(self._run_callback, callback)
782
+ self._scheduler.enter(callback.interval.total_seconds(), 1, self._callback_iteration, (callback,))
783
+
784
+ def _start_extension_loop(self):
785
+ api_logger.debug(f"Starting main loop for monitoring configuration: '{self.monitoring_config_name}'")
786
+
787
+ # These were scheduled before the extension started, schedule them now
788
+ for callback in self._scheduled_callbacks_before_run:
789
+ self._schedule_callback(callback)
790
+ self._heartbeat_iteration()
791
+ self._metrics_iteration()
792
+ self._sfm_metrics_iteration()
793
+ self._timediff_iteration()
794
+ self._scheduler.run()
795
+
796
+ def _timediff_iteration(self):
797
+ self._internal_executor.submit(self._update_cluster_time_diff)
798
+ self._scheduler.enter(TIME_DIFF_INTERVAL.total_seconds(), 1, self._timediff_iteration)
799
+
800
+ def _heartbeat_iteration(self):
801
+ self._internal_executor.submit(self._heartbeat)
802
+ self._scheduler.enter(HEARTBEAT_INTERVAL.total_seconds(), 1, self._heartbeat_iteration)
803
+
804
+ def _metrics_iteration(self):
805
+ self._internal_executor.submit(self._send_metrics)
806
+ self._scheduler.enter(METRIC_SENDING_INTERVAL.total_seconds(), 1, self._metrics_iteration)
807
+
808
+ def _sfm_metrics_iteration(self):
809
+ self._internal_executor.submit(self._send_sfm_metrics)
810
+ self._scheduler.enter(SFM_METRIC_SENDING_INTERVAL.total_seconds(), 1, self._sfm_metrics_iteration)
811
+
812
+ def _send_metrics(self):
813
+ # TODO - we might need to check size and number of lines before sending
814
+ # Maybe break it down into multiple packets
815
+ with self._metrics_lock and self._internal_callbacks_results_lock:
816
+ if self._metrics:
817
+ number_of_metrics = len(self._metrics)
818
+ responses = self._client.send_metrics(self._metrics)
819
+
820
+ self._internal_callbacks_results[self._send_metrics.__name__] = Status(StatusValue.OK)
821
+ lines_invalid = sum(response.lines_invalid for response in responses)
822
+ if lines_invalid > 0:
823
+ message = f"{lines_invalid} invalid metric lines found"
824
+ self._internal_callbacks_results[self._send_metrics.__name__] = Status(
825
+ StatusValue.GENERIC_ERROR, message
826
+ )
827
+
828
+ api_logger.info(f"Sent {number_of_metrics} metric lines to EEC: {responses}")
829
+ self._metrics = []
830
+
831
+ def _prepare_sfm_metrics(self) -> List[str]:
832
+ """Prepare self monitoring metrics.
833
+
834
+ Builds the list of mint metric lines to send as self monitoring metrics.
835
+ """
836
+
837
+ sfm_metrics: List[Metric] = []
838
+ sfm_dimensions = {"dt.extension.config.id": self.monitoring_config_id}
839
+ _add_sfm_metric(
840
+ SfmMetric("threads", active_count(), sfm_dimensions, client_facing=True, metric_type=MetricType.DELTA),
841
+ sfm_metrics,
842
+ )
843
+
844
+ for name, callback in self._callbackSfmReport.items():
845
+ sfm_dimensions = {"callback": name, "dt.extension.config.id": self.monitoring_config_id}
846
+ _add_sfm_metric(
847
+ SfmMetric(
848
+ "execution.time",
849
+ f"{callback.duration_interval_total:.4f}",
850
+ sfm_dimensions,
851
+ client_facing=True,
852
+ metric_type=MetricType.GAUGE,
853
+ ),
854
+ sfm_metrics,
855
+ )
856
+ _add_sfm_metric(
857
+ SfmMetric(
858
+ "execution.total.count",
859
+ callback.executions_total,
860
+ sfm_dimensions,
861
+ client_facing=True,
862
+ metric_type=MetricType.DELTA,
863
+ ),
864
+ sfm_metrics,
865
+ )
866
+ _add_sfm_metric(
867
+ SfmMetric(
868
+ "execution.count",
869
+ callback.executions_per_interval,
870
+ sfm_dimensions,
871
+ client_facing=True,
872
+ metric_type=MetricType.DELTA,
873
+ ),
874
+ sfm_metrics,
875
+ )
876
+ _add_sfm_metric(
877
+ SfmMetric(
878
+ "execution.ok.count",
879
+ callback.ok_count,
880
+ sfm_dimensions,
881
+ client_facing=True,
882
+ metric_type=MetricType.DELTA,
883
+ ),
884
+ sfm_metrics,
885
+ )
886
+ _add_sfm_metric(
887
+ SfmMetric(
888
+ "execution.timeout.count",
889
+ callback.timeouts_count,
890
+ sfm_dimensions,
891
+ client_facing=True,
892
+ metric_type=MetricType.DELTA,
893
+ ),
894
+ sfm_metrics,
895
+ )
896
+ _add_sfm_metric(
897
+ SfmMetric(
898
+ "execution.exception.count",
899
+ callback.exception_count,
900
+ sfm_dimensions,
901
+ client_facing=True,
902
+ metric_type=MetricType.DELTA,
903
+ ),
904
+ sfm_metrics,
905
+ )
906
+ callback.clear_sfm_metrics()
907
+ return [metric.to_mint_line() for metric in sfm_metrics]
908
+
909
+ def _send_sfm_metrics(self):
910
+ with self._sfm_metrics_lock:
911
+ lines = self._prepare_sfm_metrics()
912
+ # Flushes the cache of metrics, maybe we should only flush if they were successfully sent
913
+ self._callbackSfmReport.clear()
914
+ response = self._client.send_sfm_metrics(lines)
915
+
916
+ with self._internal_callbacks_results_lock:
917
+ self._internal_callbacks_results[self._send_sfm_metrics.__name__] = Status(StatusValue.OK)
918
+ if response.lines_invalid > 0:
919
+ message = f"{response.lines_invalid} invalid metric lines found"
920
+ self._internal_callbacks_results[self._send_sfm_metrics.__name__] = Status(
921
+ StatusValue.GENERIC_ERROR, message
922
+ )
923
+
924
+ def _build_current_status(self):
925
+ overall_status = Status(StatusValue.OK)
926
+
927
+ if self._initialization_error:
928
+ overall_status.status = StatusValue.GENERIC_ERROR
929
+ overall_status.message = self._initialization_error
930
+ return overall_status
931
+
932
+ internal_callback_error = False
933
+ messages = []
934
+ with self._internal_callbacks_results_lock:
935
+ for callback, result in self._internal_callbacks_results.items():
936
+ if result.is_error():
937
+ internal_callback_error = True
938
+ overall_status.status = result.status
939
+ messages.append(f"{callback}: {result.message}")
940
+ if internal_callback_error:
941
+ overall_status.message = "\n".join(messages)
942
+ return overall_status
943
+
944
+ for callback in self._scheduled_callbacks:
945
+ overall_status.timestamp = int(callback.get_adjusted_metric_timestamp().timestamp() * 1000)
946
+ if callback.status.is_error():
947
+ overall_status.status = callback.status.status
948
+ messages.append(f"{callback}: {callback.status.message}")
949
+
950
+ overall_status.message = "\n".join(messages)
951
+ return overall_status
952
+
953
+ def _update_cluster_time_diff(self):
954
+ self._cluster_time_diff = self._client.get_cluster_time_diff()
955
+ for callback in self._scheduled_callbacks:
956
+ callback.cluster_time_diff = self._cluster_time_diff
957
+
958
+ def _heartbeat(self):
959
+ response = bytes("not set", "utf-8")
960
+ try:
961
+ overall_status = self._build_current_status()
962
+ response = self._client.send_status(overall_status)
963
+ self._runtime_properties = RuntimeProperties(response)
964
+ except Exception as e:
965
+ api_logger.error(f"Heartbeat failed because {e}, response {response}", exc_info=True)
966
+
967
+ def __del__(self):
968
+ self._callbacks_executor.shutdown()
969
+ self._internal_executor.shutdown()
970
+
971
+ def _add_metric(self, metric: Metric):
972
+ metric.validate()
973
+
974
+ with self._running_callbacks_lock:
975
+ current_thread_id = threading.get_ident()
976
+ current_callback = self._running_callbacks.get(current_thread_id)
977
+
978
+ if current_callback is not None and metric.timestamp is None:
979
+ # Adjust the metric timestamp according to the callback start time
980
+ # If the user manually set a metric timestamp, don't adjust it
981
+ metric.timestamp = current_callback.get_adjusted_metric_timestamp()
982
+ elif current_callback is None and metric.timestamp is None:
983
+ api_logger.debug(
984
+ f"Metric {metric} was added by unknown thread {current_thread_id}, cannot adjust the timestamp"
985
+ )
986
+
987
+ with self._metrics_lock:
988
+ self._metrics.append(metric.to_mint_line())
989
+
990
+ def _add_mint_lines(self, lines: List[str]):
991
+ with self._metrics_lock:
992
+ self._metrics.extend(lines)
993
+
994
+ def _send_events_internal(self, events: Union[dict, List[dict]]):
995
+ response = self._client.send_events(events, self.log_event_enrichment)
996
+ with self._internal_callbacks_results_lock:
997
+ self._internal_callbacks_results[self._send_events.__name__] = Status(StatusValue.OK)
998
+ if not response or "error" not in response or "message" not in response["error"]:
999
+ return
1000
+ self._internal_callbacks_results[self._send_events.__name__] = Status(
1001
+ StatusValue.GENERIC_ERROR, response["error"]["message"]
1002
+ )
1003
+
1004
+ def _send_events(self, events: Union[dict, List[dict]]):
1005
+ self._internal_executor.submit(self._send_events_internal, events)
1006
+
1007
+ def _send_dt_event(self, event: dict[str, str | int | dict[str, str]]):
1008
+ self._client.send_dt_event(event)
1009
+
1010
+ def get_version(self) -> str:
1011
+ """Return the version of extensions sdk library."""
1012
+
1013
+ return __version__
1014
+
1015
+ @property
1016
+ def techrule(self) -> str:
1017
+ """Internal property used by the EEC."""
1018
+
1019
+ return self._techrule
1020
+
1021
+ @techrule.setter
1022
+ def techrule(self, value):
1023
+ self._techrule = value
1024
+
1025
+ def get_activation_config(self) -> ActivationConfig:
1026
+ """Retrieve the activation config.
1027
+
1028
+ Represents activation configuration assigned to this particular
1029
+ extension instance.
1030
+
1031
+ Returns:
1032
+ ActivationConfig object.
1033
+ """
1034
+ return self.activation_config