argus-api-client 0.6.0__tar.gz → 0.8.0__tar.gz

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 (29) hide show
  1. argus_api_client-0.8.0/PKG-INFO +312 -0
  2. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/README.md +141 -16
  3. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/pyproject.toml +19 -10
  4. argus_api_client-0.8.0/src/argus_api_client.egg-info/PKG-INFO +312 -0
  5. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/src/argus_api_client.egg-info/SOURCES.txt +10 -1
  6. argus_api_client-0.8.0/src/argus_api_client.egg-info/requires.txt +2 -0
  7. argus_api_client-0.8.0/src/pyargus/__init__.py +7 -0
  8. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/src/pyargus/api.py +13 -0
  9. argus_api_client-0.8.0/src/pyargus/async_api.py +64 -0
  10. argus_api_client-0.8.0/src/pyargus/async_client.py +235 -0
  11. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/src/pyargus/client.py +74 -11
  12. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/src/pyargus/models.py +18 -9
  13. argus_api_client-0.8.0/src/pyargus/multivaluedict.py +251 -0
  14. argus_api_client-0.8.0/src/pyargus/time.py +10 -0
  15. argus_api_client-0.8.0/tests/test_api.py +28 -0
  16. argus_api_client-0.8.0/tests/test_async_api.py +23 -0
  17. argus_api_client-0.8.0/tests/test_async_client.py +110 -0
  18. argus_api_client-0.8.0/tests/test_client.py +99 -0
  19. argus_api_client-0.8.0/tests/test_models.py +62 -0
  20. argus_api_client-0.8.0/tests/test_multivaluedict.py +413 -0
  21. argus_api_client-0.6.0/PKG-INFO +0 -387
  22. argus_api_client-0.6.0/src/argus_api_client.egg-info/PKG-INFO +0 -387
  23. argus_api_client-0.6.0/src/argus_api_client.egg-info/requires.txt +0 -13
  24. argus_api_client-0.6.0/src/pyargus/__init__.py +0 -3
  25. argus_api_client-0.6.0/tests/test_api.py +0 -13
  26. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/LICENSE +0 -0
  27. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/setup.cfg +0 -0
  28. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/src/argus_api_client.egg-info/dependency_links.txt +0 -0
  29. {argus_api_client-0.6.0 → argus_api_client-0.8.0}/src/argus_api_client.egg-info/top_level.txt +0 -0
@@ -0,0 +1,312 @@
1
+ Metadata-Version: 2.4
2
+ Name: argus-api-client
3
+ Version: 0.8.0
4
+ Summary: A Python API client library for the Argus alert aggregator server
5
+ Author-email: Sikt - Kunnskapssektorens Tjenesteleverandør <kontakt@sikt.no>
6
+ License-Expression: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.9
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: simple_rest_client
17
+ Requires-Dist: iso8601
18
+ Dynamic: license-file
19
+
20
+ # Argus API Client
21
+ [![test badge](https://img.shields.io/github/actions/workflow/status/Uninett/pyargus/tox.yml?branch=master)](https://github.com/Uninett/pyargus/actions)
22
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
23
+
24
+ This is the official Python client library for the
25
+ [Argus](https://github.com/Uninett/Argus) API server.
26
+
27
+ The Argus server is an incident registry, capable of aggregating alerts from
28
+ multiple source systems. Argus also can send event notifications (via e-mail,
29
+ SMS, etc.) when incidents are created or resolved.
30
+
31
+ ## Usage examples
32
+
33
+ The pyargus library models [the official API endoints of
34
+ Argus](https://argus-server.readthedocs.io/en/latest/api.html) as methods on an
35
+ API client object.
36
+
37
+ At the moment, only the methods and models needed to interact with
38
+ incident-related endpoints are supported.
39
+
40
+ The `Client` class is found in `pyargus.client`, and the various supported data
41
+ models, such as `Incident`, `Event`, `Acknowledgement` and `SourceSystem`, are
42
+ implemented in `pyargus.models`.
43
+
44
+ **Note:** Always pass timezone-aware `datetime` objects (e.g. `datetime.now(tz=timezone.utc)`) to the client. pyargus serializes datetimes verbatim, so a naive value reaches Argus without a UTC offset and gets recorded at the wrong time.
45
+
46
+ ### Listing open incidents that have not been acknowledged
47
+
48
+ ```pycon
49
+ >>> from pyargus.client import Client
50
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
51
+ >>> for incident in c.get_incidents(open=True, acked=False):
52
+ ... print(incident)
53
+ ...
54
+ Incident(pk=4, start_time=datetime.datetime(2021, 4, 4, 16, 37, 43, 293726, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='202430', details_url='http://localhost/search/event/202430', description='uninett-gsw2 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags=MultiValueDict([('location', 'Teknobyen Innovasjonssenter'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'bgpState'), ('alert_type', 'bgpDown'), ('room', '100'), ('organization', 'uninett.srv'), ('host', 'uninett-gsw2.uninett.no')]), stateful=True, open=True, acked=False)
55
+ Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='202429', details_url='http://localhost/search/event/202429', description='uninett-gsw1 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags=MultiValueDict([('location', 'Teknobyen Innovasjonssenter'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'bgpState'), ('alert_type', 'bgpDown'), ('host', 'uninett-gsw1.uninett.no'), ('room', '100'), ('organization', 'uninett.srv')]), stateful=True, open=True, acked=False)
56
+ Incident(pk=2, start_time=datetime.datetime(2017, 8, 31, 14, 58, 31, 118794, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='184296', details_url='http://localhost/search/event/184296', description='Link DOWN on Gi0/3 at oldsmobile.lab (Simple is better than complex)', level=5, ticket_url='', tags=MultiValueDict([('room', '113'), ('location', 'Teknobyen Innovasjonssenter'), ('organization', 'uninett.testlab'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'linkState'), ('alert_type', 'linkDown'), ('host', 'oldsmobile.lab.uninett.no'), ('interface', 'Gi0/3')]), stateful=True, open=True, acked=False)
57
+ ```
58
+
59
+ As you can see, the arguments given to `get_incidents()` are translated
60
+ verbatim into the arguments supported by the `/incidents` endpoint in the API.
61
+
62
+ ### List only "my" incidents
63
+
64
+ The incidents API also has an `/incidents/mine` endpoint, which works just like
65
+ the `/incidents` endpoint, but searches only the incidents that were posted
66
+ by the connecting user. This is useful for glue services, when they need to
67
+ compare the list of open Argus incidents it has produced with the current list
68
+ of active alerts in its source system.
69
+
70
+ Example:
71
+
72
+ ```pycon
73
+ >>> from pyargus.client import Client
74
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
75
+ >>> for incident in c.get_my_incidents(open=True, acked=False):
76
+ ... print(incident)
77
+ ...
78
+ Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=3, name='foobar, type='nav', user=4, base_url='http://localhost/'), source_incident_id='2716057', details_url='http://localhost/search/event/2716057', description='uninett-gsw1 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags=MultiValueDict([('location', 'Teknobyen Innovasjonssenter'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'bgpState'), ('alert_type', 'bgpDown'), ('host', 'uninett-gsw1.uninett.no'), ('room', '100'), ('organization', 'uninett.srv')]), stateful=True, open=True, acked=False)
79
+ ```
80
+
81
+ ### Post a new incident
82
+
83
+ ```pycon
84
+ >>> from pyargus.client import Client
85
+ >>> from pyargus.models import Incident
86
+ >>> from pyargus.time import now as utcnow
87
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
88
+ >>> i = Incident(
89
+ ... description="The earth was demolished to make way for a hyperspace bypass",
90
+ ... start_time=utcnow(),
91
+ ... tags={
92
+ ... "host": "earth.example.org",
93
+ ... }
94
+ ... )
95
+ >>> c.post_incident(i)
96
+ Incident(pk=8, start_time=datetime.datetime(2021, 4, 22, 11, 41, 53, 580947, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=None, source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='', details_url='', description='The earth was demolished to make way for a hyperspace bypass', level=5, ticket_url='', tags=MultiValueDict([('host', 'earth.example.org')]), stateful=False, open=False, acked=False)
97
+ ```
98
+
99
+ The `post_incident()` method returns the full `Incident` record, as stored in
100
+ Argus. If you need it, you can get the incident ID from the the primary key
101
+ attribute `pk`, in case you need to address it directly later.
102
+
103
+ ### Close an existing incident
104
+
105
+ Incidents are closed by posting a *END* type event to an incident's event
106
+ log, with an optional timestamp. The `Client` class provides the follow
107
+ convenience method for this operation:
108
+
109
+ ```pycon
110
+ >>> from pyargus.client import Client
111
+ >>> from pyargus.time import now as utcnow
112
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
113
+ >>> c.resolve_incident(incident=8, description="The demolition was cancelled", timestamp=utcnow())
114
+ Event(pk=10, actor='testnav', description='The demolition was cancelled', incident=8, received=datetime.datetime(2021, 4, 22, 11, 47, 11, 978438, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), timestamp=datetime.datetime(2021, 4, 22, 11, 47, 11, 946076, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), type='END')
115
+ ```
116
+
117
+ ### Restart an existing incident
118
+
119
+ Incidents are restarted by posting a *RES* type event to an incident's event
120
+ log, with an optional timestamp. The `Client` class provides the follow
121
+ convenience method for this operation:
122
+
123
+ ```pycon
124
+ >>> from pyargus.client import Client
125
+ >>> from pyargus.time import now as utcnow
126
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
127
+ >>> c.restart_incident(incident=8, description="The demolition was restarted", timestamp=utcnow())
128
+ Event(pk=10, actor='testnav', description='The demolition was restarted', incident=8, received=datetime.datetime(2021, 4, 22, 11, 47, 11, 978438, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), timestamp=datetime.datetime(2021, 4, 22, 11, 47, 11, 946076, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), type='RES')
129
+ ```
130
+
131
+ ### Modify an existing incident
132
+
133
+ Argus does not allow modification of most incident attributes, but things
134
+ like the tag list can be changed. Modifications are made by constructing an
135
+ `Incident` object with the `pk` attribute set to the id of the incident you
136
+ wish you modify, and then adding values to the attributes you wish to modify:
137
+
138
+ ```pycon
139
+ >>> from pyargus.client import Client
140
+ >>> from pyargus.models import Incident
141
+ >>> from datetime import datetime
142
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
143
+ >>> i = Incident(
144
+ ... pk=8,
145
+ ... tags={
146
+ ... "host": "earth.example.org",
147
+ ... "location": "Milky way",
148
+ ... }
149
+ ... )
150
+ >>> c.update_incident(i)
151
+ Incident(pk=8, start_time=datetime.datetime(2021, 4, 22, 11, 41, 53, 580947, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=None, source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='', details_url='', description='The earth was demolished to make way for a hyperspace bypass', level=None, ticket_url='', tags=MultiValueDict([('host', 'earth.example.org'), ('location', 'Milky way')]), stateful=False, open=False, acked=False)
152
+
153
+ ```
154
+
155
+ ### Working with multi-valued tags
156
+
157
+ Argus allows an incident to carry the same tag key more than once (for example
158
+ two different `host` values). The `tags` attribute is therefore a
159
+ `MultiValueDict` — a `dict` subclass that keeps every value while still behaving
160
+ like an ordinary dictionary for code that expects a single value per key.
161
+
162
+ Construct it from a sequence of `(key, value)` pairs (unlike a plain `dict`,
163
+ repeated keys are kept), or build it up with `add()`:
164
+
165
+ ```pycon
166
+ >>> from pyargus.models import Incident
167
+ >>> from pyargus.multivaluedict import MultiValueDict
168
+ >>> tags = MultiValueDict([("host", "a.example.org"), ("host", "b.example.org")])
169
+ >>> tags.add("location", "Milky way")
170
+ >>> i = Incident(description="Two hosts affected", tags=tags)
171
+ ```
172
+
173
+ Reading a multi-valued key through the ordinary `[]`/`get()` interface returns
174
+ only the *last* value and emits a `DeprecationWarning`, because the other values
175
+ are dropped silently. Use `getlist()` to retrieve them all:
176
+
177
+ ```pycon
178
+ >>> tags.getlist("host") # every value for the key
179
+ ['a.example.org', 'b.example.org']
180
+ >>> tags["host"] # last value only; warns that values are dropped
181
+ 'b.example.org'
182
+ >>> tags["location"] # single-valued keys read normally, no warning
183
+ 'Milky way'
184
+ >>> tags.lists() # all keys with all of their values
185
+ [('host', ['a.example.org', 'b.example.org']), ('location', ['Milky way'])]
186
+ >>> tags.allitems() # every (key, value) pair, including repeats
187
+ [('host', 'a.example.org'), ('host', 'b.example.org'), ('location', 'Milky way')]
188
+ ```
189
+
190
+ Passing a plain `dict` as `tags` still works exactly as before, so existing code
191
+ needs no changes.
192
+
193
+ ### Stateless incidents
194
+
195
+ Argus supports a concept of "stateless" incidents. Stateless incidents
196
+ represent single points in time, and do not have an end time. To explicitly
197
+ create stateless incidents, set the `end_time` attribute to the STATELESS
198
+ sentinel, like so:
199
+
200
+ ```pycon
201
+ from pyargus.models import Incident, STATELESS
202
+ from pyargus.time import now as utcnow
203
+
204
+ stateless_incident = Incident(
205
+ description="Something happened",
206
+ start_time=utcnow(),
207
+ end_time=STATELESS
208
+ )
209
+ ```
210
+
211
+
212
+ ### Get a new authentication token
213
+
214
+ If your argus server is running version 1.29.0 or newer you can request to get
215
+ a new token (with a new expiration date) via API version 2. The token you are
216
+ using to access the server with must still be valid.
217
+
218
+ ```python
219
+ tokenobj = c.refresh_token()
220
+ c = Client(api_root_url="https://argus.example.org/api/v2", token=tokenobj.token)
221
+ # save the contents of tokenobj in an environment variable, config file or
222
+ # secrets file so that it is not lost on program exit
223
+ ```
224
+
225
+ ### Send a heartbeat
226
+
227
+ A source system with no incidents to report looks exactly like one that has
228
+ crashed. Every glue service should therefore send a *heartbeat* on a regular
229
+ schedule to prove it is still alive. A heartbeat updates the source system's
230
+ `last_seen` timestamp on the server without posting an incident, so Argus can
231
+ tell a healthy-but-quiet source apart from a dead one.
232
+
233
+ ```python
234
+ c.send_heartbeat()
235
+ ```
236
+
237
+ The method returns `None` on success. On failure it raises an exception from
238
+ `simple_rest_client`, the HTTP client library that pyargus is built on; these
239
+ exceptions are defined in its `simple_rest_client.exceptions` module (for
240
+ example, `AuthError` for a `401` or `403` response).
241
+
242
+ #### Detecting whether the server supports heartbeats
243
+
244
+ The heartbeat endpoint requires an Argus server new enough to provide it.
245
+ Older servers don't fail cleanly on a `POST` — they reject it with a `403` that
246
+ is indistinguishable from an authentication error — so don't infer support from
247
+ the `send_heartbeat()` outcome. Instead, probe up front with
248
+ `supports_heartbeat()`, which issues a `GET` and returns whether the endpoint is
249
+ present:
250
+
251
+ ```python
252
+ if c.supports_heartbeat():
253
+ c.send_heartbeat()
254
+ ```
255
+
256
+ A long-running glue service can check once at startup and decide whether to
257
+ bother sending heartbeats at all:
258
+
259
+ ```python
260
+ c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
261
+ heartbeats_enabled = c.supports_heartbeat()
262
+ while running:
263
+ do_work()
264
+ if heartbeats_enabled:
265
+ c.send_heartbeat()
266
+ sleep(interval)
267
+ ```
268
+
269
+ ## Async usage
270
+
271
+ An `AsyncClient` is available for use in asyncio-based applications. It mirrors
272
+ the `Client` interface, but all methods are coroutines. Use `python -m asyncio`
273
+ to try these examples interactively:
274
+
275
+ ```pycon
276
+ >>> from pyargus.async_client import AsyncClient
277
+ >>> from pyargus.models import Incident
278
+ >>> from pyargus.time import now as utcnow
279
+ >>> c = AsyncClient(api_root_url="https://argus.example.org/api/v2", token="foobar")
280
+ >>> async for incident in c.get_incidents(open=True, acked=False):
281
+ ... print(incident)
282
+ ...
283
+ Incident(pk=4, ...)
284
+ >>> i = Incident(
285
+ ... description="The earth was demolished to make way for a hyperspace bypass",
286
+ ... start_time=utcnow(),
287
+ ... tags={"host": "earth.example.org"},
288
+ ... )
289
+ >>> await c.post_incident(i)
290
+ Incident(pk=8, ...)
291
+ >>> if await c.supports_heartbeat():
292
+ ... await c.send_heartbeat()
293
+ ...
294
+ ```
295
+
296
+ ## BUGS
297
+
298
+ * Doesn't provide high-level error handling yet.
299
+
300
+ ## Development
301
+
302
+ ### Code style
303
+
304
+ Pyargus uses *ruff* as a source code formatter. Ruff is part of the optional dev dependencies listed in
305
+ [pyproject.toml](./pyproject.toml)
306
+
307
+ A pre-commit hook will format new code automatically before committing.
308
+ To enable this pre-commit hook, run
309
+
310
+ ```console
311
+ $ pre-commit install
312
+ ```
@@ -2,10 +2,10 @@
2
2
  [![test badge](https://img.shields.io/github/actions/workflow/status/Uninett/pyargus/tox.yml?branch=master)](https://github.com/Uninett/pyargus/actions)
3
3
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
4
4
 
5
- This is the official Python client library for the
5
+ This is the official Python client library for the
6
6
  [Argus](https://github.com/Uninett/Argus) API server.
7
7
 
8
- The Argus server is an incident registry, capable of aggregating alerts from
8
+ The Argus server is an incident registry, capable of aggregating alerts from
9
9
  multiple source systems. Argus also can send event notifications (via e-mail,
10
10
  SMS, etc.) when incidents are created or resolved.
11
11
 
@@ -22,6 +22,8 @@ The `Client` class is found in `pyargus.client`, and the various supported data
22
22
  models, such as `Incident`, `Event`, `Acknowledgement` and `SourceSystem`, are
23
23
  implemented in `pyargus.models`.
24
24
 
25
+ **Note:** Always pass timezone-aware `datetime` objects (e.g. `datetime.now(tz=timezone.utc)`) to the client. pyargus serializes datetimes verbatim, so a naive value reaches Argus without a UTC offset and gets recorded at the wrong time.
26
+
25
27
  ### Listing open incidents that have not been acknowledged
26
28
 
27
29
  ```pycon
@@ -30,9 +32,9 @@ implemented in `pyargus.models`.
30
32
  >>> for incident in c.get_incidents(open=True, acked=False):
31
33
  ... print(incident)
32
34
  ...
33
- Incident(pk=4, start_time=datetime.datetime(2021, 4, 4, 16, 37, 43, 293726, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='202430', details_url='http://localhost/search/event/202430', description='uninett-gsw2 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags={'location': 'Teknobyen Innovasjonssenter', 'kundetjeneste': 'Nett_CNaaS', 'kunde': 'example.org', 'event_type': 'bgpState', 'alert_type': 'bgpDown', 'room': '100', 'organization': 'uninett.srv', 'host': 'uninett-gsw2.uninett.no'}, stateful=True, open=True, acked=False)
34
- Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='202429', details_url='http://localhost/search/event/202429', description='uninett-gsw1 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags={'location': 'Teknobyen Innovasjonssenter', 'kundetjeneste': 'Nett_CNaaS', 'kunde': 'example.org', 'event_type': 'bgpState', 'alert_type': 'bgpDown', 'host': 'uninett-gsw1.uninett.no', 'room': '100', 'organization': 'uninett.srv'}, stateful=True, open=True, acked=False)
35
- Incident(pk=2, start_time=datetime.datetime(2017, 8, 31, 14, 58, 31, 118794, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='184296', details_url='http://localhost/search/event/184296', description='Link DOWN on Gi0/3 at oldsmobile.lab (Simple is better than complex)', level=5, ticket_url='', tags={'room': '113', 'location': 'Teknobyen Innovasjonssenter', 'organization': 'uninett.testlab', 'kundetjeneste': 'Nett_CNaaS', 'kunde': 'example.org', 'event_type': 'linkState', 'alert_type': 'linkDown', 'host': 'oldsmobile.lab.uninett.no', 'interface': 'Gi0/3'}, stateful=True, open=True, acked=False)
35
+ Incident(pk=4, start_time=datetime.datetime(2021, 4, 4, 16, 37, 43, 293726, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='202430', details_url='http://localhost/search/event/202430', description='uninett-gsw2 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags=MultiValueDict([('location', 'Teknobyen Innovasjonssenter'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'bgpState'), ('alert_type', 'bgpDown'), ('room', '100'), ('organization', 'uninett.srv'), ('host', 'uninett-gsw2.uninett.no')]), stateful=True, open=True, acked=False)
36
+ Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='202429', details_url='http://localhost/search/event/202429', description='uninett-gsw1 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags=MultiValueDict([('location', 'Teknobyen Innovasjonssenter'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'bgpState'), ('alert_type', 'bgpDown'), ('host', 'uninett-gsw1.uninett.no'), ('room', '100'), ('organization', 'uninett.srv')]), stateful=True, open=True, acked=False)
37
+ Incident(pk=2, start_time=datetime.datetime(2017, 8, 31, 14, 58, 31, 118794, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='184296', details_url='http://localhost/search/event/184296', description='Link DOWN on Gi0/3 at oldsmobile.lab (Simple is better than complex)', level=5, ticket_url='', tags=MultiValueDict([('room', '113'), ('location', 'Teknobyen Innovasjonssenter'), ('organization', 'uninett.testlab'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'linkState'), ('alert_type', 'linkDown'), ('host', 'oldsmobile.lab.uninett.no'), ('interface', 'Gi0/3')]), stateful=True, open=True, acked=False)
36
38
  ```
37
39
 
38
40
  As you can see, the arguments given to `get_incidents()` are translated
@@ -54,7 +56,7 @@ Example:
54
56
  >>> for incident in c.get_my_incidents(open=True, acked=False):
55
57
  ... print(incident)
56
58
  ...
57
- Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=3, name='foobar, type='nav', user=4, base_url='http://localhost/'), source_incident_id='2716057', details_url='http://localhost/search/event/2716057', description='uninett-gsw1 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags={'location': 'Teknobyen Innovasjonssenter', 'kundetjeneste': 'Nett_CNaaS', 'kunde': 'example.org', 'event_type': 'bgpState', 'alert_type': 'bgpDown', 'host': 'uninett-gsw1.uninett.no', 'room': '100', 'organization': 'uninett.srv'}, stateful=True, open=True, acked=False)
59
+ Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=datetime.datetime(9999, 12, 31, 23, 59, 59, 999999), source=SourceSystem(pk=3, name='foobar, type='nav', user=4, base_url='http://localhost/'), source_incident_id='2716057', details_url='http://localhost/search/event/2716057', description='uninett-gsw1 BGP session with 158.38.3.112 is DOWN', level=5, ticket_url='', tags=MultiValueDict([('location', 'Teknobyen Innovasjonssenter'), ('kundetjeneste', 'Nett_CNaaS'), ('kunde', 'example.org'), ('event_type', 'bgpState'), ('alert_type', 'bgpDown'), ('host', 'uninett-gsw1.uninett.no'), ('room', '100'), ('organization', 'uninett.srv')]), stateful=True, open=True, acked=False)
58
60
  ```
59
61
 
60
62
  ### Post a new incident
@@ -62,17 +64,17 @@ Incident(pk=3, start_time=datetime.datetime(2021, 4, 4, 16, 32, 53, 128780, tzin
62
64
  ```pycon
63
65
  >>> from pyargus.client import Client
64
66
  >>> from pyargus.models import Incident
65
- >>> from datetime import datetime
67
+ >>> from pyargus.time import now as utcnow
66
68
  >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
67
69
  >>> i = Incident(
68
- ... description="The earth was demolished to make way for a hyperspace bypass",
69
- ... start_time=datetime.now(),
70
+ ... description="The earth was demolished to make way for a hyperspace bypass",
71
+ ... start_time=utcnow(),
70
72
  ... tags={
71
73
  ... "host": "earth.example.org",
72
74
  ... }
73
75
  ... )
74
76
  >>> c.post_incident(i)
75
- Incident(pk=8, start_time=datetime.datetime(2021, 4, 22, 11, 41, 53, 580947, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=None, source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='', details_url='', description='The earth was demolished to make way for a hyperspace bypass', level=5, ticket_url='', tags={'host': 'earth.example.org'}, stateful=False, open=False, acked=False)
77
+ Incident(pk=8, start_time=datetime.datetime(2021, 4, 22, 11, 41, 53, 580947, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=None, source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='', details_url='', description='The earth was demolished to make way for a hyperspace bypass', level=5, ticket_url='', tags=MultiValueDict([('host', 'earth.example.org')]), stateful=False, open=False, acked=False)
76
78
  ```
77
79
 
78
80
  The `post_incident()` method returns the full `Incident` record, as stored in
@@ -87,12 +89,26 @@ convenience method for this operation:
87
89
 
88
90
  ```pycon
89
91
  >>> from pyargus.client import Client
90
- >>> from datetime import datetime
92
+ >>> from pyargus.time import now as utcnow
91
93
  >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
92
- >>> c.resolve_incident(incident=8, description="The demolition was cancelled", timestamp=datetime.now())
94
+ >>> c.resolve_incident(incident=8, description="The demolition was cancelled", timestamp=utcnow())
93
95
  Event(pk=10, actor='testnav', description='The demolition was cancelled', incident=8, received=datetime.datetime(2021, 4, 22, 11, 47, 11, 978438, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), timestamp=datetime.datetime(2021, 4, 22, 11, 47, 11, 946076, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), type='END')
94
96
  ```
95
97
 
98
+ ### Restart an existing incident
99
+
100
+ Incidents are restarted by posting a *RES* type event to an incident's event
101
+ log, with an optional timestamp. The `Client` class provides the follow
102
+ convenience method for this operation:
103
+
104
+ ```pycon
105
+ >>> from pyargus.client import Client
106
+ >>> from pyargus.time import now as utcnow
107
+ >>> c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
108
+ >>> c.restart_incident(incident=8, description="The demolition was restarted", timestamp=utcnow())
109
+ Event(pk=10, actor='testnav', description='The demolition was restarted', incident=8, received=datetime.datetime(2021, 4, 22, 11, 47, 11, 978438, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), timestamp=datetime.datetime(2021, 4, 22, 11, 47, 11, 946076, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), type='RES')
110
+ ```
111
+
96
112
  ### Modify an existing incident
97
113
 
98
114
  Argus does not allow modification of most incident attributes, but things
@@ -113,10 +129,48 @@ wish you modify, and then adding values to the attributes you wish to modify:
113
129
  ... }
114
130
  ... )
115
131
  >>> c.update_incident(i)
116
- Incident(pk=8, start_time=datetime.datetime(2021, 4, 22, 11, 41, 53, 580947, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=None, source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='', details_url='', description='The earth was demolished to make way for a hyperspace bypass', level=None, ticket_url='', tags={'host': 'earth.example.org', 'location': 'Milky way'}, stateful=False, open=False, acked=False)
132
+ Incident(pk=8, start_time=datetime.datetime(2021, 4, 22, 11, 41, 53, 580947, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), '+02:00')), end_time=None, source=SourceSystem(pk=2, name='testnav', type='nav', user=3, base_url='http://localhost/'), source_incident_id='', details_url='', description='The earth was demolished to make way for a hyperspace bypass', level=None, ticket_url='', tags=MultiValueDict([('host', 'earth.example.org'), ('location', 'Milky way')]), stateful=False, open=False, acked=False)
133
+
134
+ ```
135
+
136
+ ### Working with multi-valued tags
137
+
138
+ Argus allows an incident to carry the same tag key more than once (for example
139
+ two different `host` values). The `tags` attribute is therefore a
140
+ `MultiValueDict` — a `dict` subclass that keeps every value while still behaving
141
+ like an ordinary dictionary for code that expects a single value per key.
142
+
143
+ Construct it from a sequence of `(key, value)` pairs (unlike a plain `dict`,
144
+ repeated keys are kept), or build it up with `add()`:
117
145
 
146
+ ```pycon
147
+ >>> from pyargus.models import Incident
148
+ >>> from pyargus.multivaluedict import MultiValueDict
149
+ >>> tags = MultiValueDict([("host", "a.example.org"), ("host", "b.example.org")])
150
+ >>> tags.add("location", "Milky way")
151
+ >>> i = Incident(description="Two hosts affected", tags=tags)
118
152
  ```
119
153
 
154
+ Reading a multi-valued key through the ordinary `[]`/`get()` interface returns
155
+ only the *last* value and emits a `DeprecationWarning`, because the other values
156
+ are dropped silently. Use `getlist()` to retrieve them all:
157
+
158
+ ```pycon
159
+ >>> tags.getlist("host") # every value for the key
160
+ ['a.example.org', 'b.example.org']
161
+ >>> tags["host"] # last value only; warns that values are dropped
162
+ 'b.example.org'
163
+ >>> tags["location"] # single-valued keys read normally, no warning
164
+ 'Milky way'
165
+ >>> tags.lists() # all keys with all of their values
166
+ [('host', ['a.example.org', 'b.example.org']), ('location', ['Milky way'])]
167
+ >>> tags.allitems() # every (key, value) pair, including repeats
168
+ [('host', 'a.example.org'), ('host', 'b.example.org'), ('location', 'Milky way')]
169
+ ```
170
+
171
+ Passing a plain `dict` as `tags` still works exactly as before, so existing code
172
+ needs no changes.
173
+
120
174
  ### Stateless incidents
121
175
 
122
176
  Argus supports a concept of "stateless" incidents. Stateless incidents
@@ -124,13 +178,13 @@ represent single points in time, and do not have an end time. To explicitly
124
178
  create stateless incidents, set the `end_time` attribute to the STATELESS
125
179
  sentinel, like so:
126
180
 
127
- ```python
128
- from datetime import datetime
181
+ ```pycon
129
182
  from pyargus.models import Incident, STATELESS
183
+ from pyargus.time import now as utcnow
130
184
 
131
185
  stateless_incident = Incident(
132
186
  description="Something happened",
133
- start_time=datetime.now(),
187
+ start_time=utcnow(),
134
188
  end_time=STATELESS
135
189
  )
136
190
  ```
@@ -149,6 +203,77 @@ c = Client(api_root_url="https://argus.example.org/api/v2", token=tokenobj.token
149
203
  # secrets file so that it is not lost on program exit
150
204
  ```
151
205
 
206
+ ### Send a heartbeat
207
+
208
+ A source system with no incidents to report looks exactly like one that has
209
+ crashed. Every glue service should therefore send a *heartbeat* on a regular
210
+ schedule to prove it is still alive. A heartbeat updates the source system's
211
+ `last_seen` timestamp on the server without posting an incident, so Argus can
212
+ tell a healthy-but-quiet source apart from a dead one.
213
+
214
+ ```python
215
+ c.send_heartbeat()
216
+ ```
217
+
218
+ The method returns `None` on success. On failure it raises an exception from
219
+ `simple_rest_client`, the HTTP client library that pyargus is built on; these
220
+ exceptions are defined in its `simple_rest_client.exceptions` module (for
221
+ example, `AuthError` for a `401` or `403` response).
222
+
223
+ #### Detecting whether the server supports heartbeats
224
+
225
+ The heartbeat endpoint requires an Argus server new enough to provide it.
226
+ Older servers don't fail cleanly on a `POST` — they reject it with a `403` that
227
+ is indistinguishable from an authentication error — so don't infer support from
228
+ the `send_heartbeat()` outcome. Instead, probe up front with
229
+ `supports_heartbeat()`, which issues a `GET` and returns whether the endpoint is
230
+ present:
231
+
232
+ ```python
233
+ if c.supports_heartbeat():
234
+ c.send_heartbeat()
235
+ ```
236
+
237
+ A long-running glue service can check once at startup and decide whether to
238
+ bother sending heartbeats at all:
239
+
240
+ ```python
241
+ c = Client(api_root_url="https://argus.example.org/api/v2", token="foobar")
242
+ heartbeats_enabled = c.supports_heartbeat()
243
+ while running:
244
+ do_work()
245
+ if heartbeats_enabled:
246
+ c.send_heartbeat()
247
+ sleep(interval)
248
+ ```
249
+
250
+ ## Async usage
251
+
252
+ An `AsyncClient` is available for use in asyncio-based applications. It mirrors
253
+ the `Client` interface, but all methods are coroutines. Use `python -m asyncio`
254
+ to try these examples interactively:
255
+
256
+ ```pycon
257
+ >>> from pyargus.async_client import AsyncClient
258
+ >>> from pyargus.models import Incident
259
+ >>> from pyargus.time import now as utcnow
260
+ >>> c = AsyncClient(api_root_url="https://argus.example.org/api/v2", token="foobar")
261
+ >>> async for incident in c.get_incidents(open=True, acked=False):
262
+ ... print(incident)
263
+ ...
264
+ Incident(pk=4, ...)
265
+ >>> i = Incident(
266
+ ... description="The earth was demolished to make way for a hyperspace bypass",
267
+ ... start_time=utcnow(),
268
+ ... tags={"host": "earth.example.org"},
269
+ ... )
270
+ >>> await c.post_incident(i)
271
+ Incident(pk=8, ...)
272
+ >>> if await c.supports_heartbeat():
273
+ ... await c.send_heartbeat()
274
+ ...
275
+ ```
276
+
152
277
  ## BUGS
153
278
 
154
279
  * Doesn't provide high-level error handling yet.
@@ -1,35 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
1
5
  [project]
2
6
  name = "argus-api-client"
3
7
  dynamic = ["version"]
4
8
  description = "A Python API client library for the Argus alert aggregator server"
5
9
  readme = "README.md"
6
10
  authors = [{name="Sikt - Kunnskapssektorens Tjenesteleverandør", email="kontakt@sikt.no"}]
7
- requires-python = ">=3.8"
8
- license = {file = "LICENSE"}
11
+ requires-python = ">=3.9"
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
9
14
  classifiers = [
10
- "License :: OSI Approved :: Apache Software License",
11
15
  "Programming Language :: Python :: 3",
12
- "Programming Language :: Python :: 3.8",
13
16
  "Programming Language :: Python :: 3.9",
14
17
  "Programming Language :: Python :: 3.10",
15
18
  "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
16
21
  ]
17
22
  dependencies = [
18
23
  "simple_rest_client",
19
24
  "iso8601",
20
25
  ]
21
26
 
22
- [project.optional-dependencies]
27
+ [dependency-groups]
28
+ test = [
29
+ "pytest",
30
+ "pytest-asyncio",
31
+ "pytest-cov",
32
+ "pytest-argus-server>=0.2.0",
33
+ ]
23
34
  dev = [
24
35
  "build",
25
36
  "coverage",
26
37
  "ipython",
27
- "isort",
28
38
  "pre-commit",
29
- "pytest",
30
39
  "ruff",
31
40
  "tox",
32
41
  "twine",
42
+ {include-group = "test"},
33
43
  ]
34
44
 
35
45
  [tool.setuptools.dynamic]
@@ -44,8 +54,7 @@ line-length = 88
44
54
  extend-exclude = [
45
55
  ".egg-info",
46
56
  ]
47
- output-format = "full"
48
57
 
49
58
  [tool.ruff.lint]
50
- select = ["E4", "E7", "E9", "F4", "F5", "F6", "F7", "F8", "F9"]
51
- ignore = ["F403", "F405"]
59
+ select = ["E4", "E7", "E9", "F", "I"]
60
+ fixable = ["I"]