|
| 1 | +import logging |
| 2 | +import time |
| 3 | + |
1 | 4 | from django.contrib.contenttypes.models import ContentType |
2 | 5 | from django.core.exceptions import ValidationError |
3 | 6 | from swapper import load_model |
4 | 7 |
|
| 8 | +logger = logging.getLogger(__name__) |
| 9 | + |
5 | 10 | Check = load_model('check', 'Check') |
6 | 11 | Metric = load_model('monitoring', 'Metric') |
7 | 12 | Device = load_model('config', 'Device') |
@@ -55,6 +60,57 @@ def may_execute(cls): |
55 | 60 | def check(self, store=True): |
56 | 61 | raise NotImplementedError |
57 | 62 |
|
| 63 | + def store(self, *args, **kwargs): |
| 64 | + raise NotImplementedError |
| 65 | + |
| 66 | + def timed_check(self, store=True): |
| 67 | + """ |
| 68 | + Executes the check method and measures its execution time. |
| 69 | +
|
| 70 | + Optionally stores the result and logs the time taken for the check execution |
| 71 | + and the time spent storing the result in the database(if available). |
| 72 | +
|
| 73 | + Args: |
| 74 | + store (bool, optional): Whether to store the result of the check. Defaults to True. |
| 75 | +
|
| 76 | + Returns: |
| 77 | + The result of the check method. |
| 78 | +
|
| 79 | + Logs: |
| 80 | + The time taken to execute the check and store the result. |
| 81 | + """ |
| 82 | + start_time = time.time() |
| 83 | + result = self.check(store=store) |
| 84 | + elapsed_time = time.time() - start_time |
| 85 | + if hasattr(self, '_store_result_elapsed_time'): |
| 86 | + elapsed_time -= self._store_result_elapsed_time |
| 87 | + logger.info( |
| 88 | + 'Check "%s" executed in %.2fs, writing took %.2fs' |
| 89 | + % ( |
| 90 | + self.check_instance, |
| 91 | + elapsed_time, |
| 92 | + getattr(self, '_store_result_elapsed_time', 0.0), |
| 93 | + ), |
| 94 | + ) |
| 95 | + return result |
| 96 | + |
| 97 | + def timed_store(self, *args, **kwargs): |
| 98 | + """ |
| 99 | + Calls the `store` method with the provided arguments and measures the time taken to execute it. |
| 100 | +
|
| 101 | + The elapsed time (in seconds) is stored in the `timed_store` attribute of the instance. |
| 102 | +
|
| 103 | + Args: |
| 104 | + *args: Variable length argument list to pass to the `store` method. |
| 105 | + **kwargs: Arbitrary keyword arguments to pass to the `store` method. |
| 106 | +
|
| 107 | + Side Effects: |
| 108 | + Sets the `timed_store` attribute to the duration (in seconds) of the `store` method execution. |
| 109 | + """ |
| 110 | + start_time = time.time() |
| 111 | + self.store(*args, **kwargs) |
| 112 | + self._store_result_elapsed_time = time.time() - start_time |
| 113 | + |
58 | 114 | def _get_or_create_metric(self, configuration=None): |
59 | 115 | """Gets or creates metric.""" |
60 | 116 | check = self.check_instance |
|
0 commit comments