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