Debian Codegraph @

consul/api/agent.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import json
4 from typing import Any, Optional
5
6 from consul import Check
7 from consul.callback import CB
8
9
10 class Agent:
11 """
12 The Agent endpoints are used to interact with a local Consul agent.
13 Usually, services and checks are registered with an agent, which then
14 takes on the burden of registering with the Catalog and performing
15 anti-entropy to recover from outages.
16 """
17
18 def __init__(self, agent) -> None:
19 self.agent = agent
20 self.service = Agent.Service(agent)
21 self.check = Agent.Check(agent)
22 self.connect = Agent.Connect(agent)
23
24 def self(self):
25 """
26 Returns configuration of the local agent and member information.
27 """
28 return self.agent.http.get(CB.json(), "/v1/agent/self")
29
30 def services(self) -> Any:
31 """
32 Returns all the services that are registered with the local agent.
33 These services were either provided through configuration files, or
34 added dynamically using the HTTP API. It is important to note that
35 the services known by the agent may be different than those
36 reported by the Catalog. This is usually due to changes being made
37 while there is no leader elected. The agent performs active
38 anti-entropy, so in most situations everything will be in sync
39 within a few seconds.
40 """
41 return self.agent.http.get(CB.json(), "/v1/agent/services")
42
43 def service_definition(self, service_id):
44 """
45 Returns a service definition for a single instance that is registered
46 with the local agent.
47 """
48 return self.agent.http.get(CB.json(), f"/v1/agent/service/{service_id}")
49
50 def checks(self) -> Any:
51 """
52 Returns all the checks that are registered with the local agent.
53 These checks were either provided through configuration files, or
54 added dynamically using the HTTP API. Similar to services,
55 the checks known by the agent may be different than those
56 reported by the Catalog. This is usually due to changes being made
57 while there is no leader elected. The agent performs active
58 anti-entropy, so in most situations everything will be in sync
59 within a few seconds.
60 """
61 return self.agent.http.get(CB.json(), "/v1/agent/checks")
62
63 def members(self, wan: bool = False):
64 """
65 Returns all the members that this agent currently sees. This may
66 vary by agent, use the nodes api of Catalog to retrieve a cluster
67 wide consistent view of members.
68
69 For agents running in server mode, setting *wan* to *True* returns
70 the list of WAN members instead of the LAN members which is
71 default.
72 """
73 params = []
74 if wan:
75 params.append(("wan", 1))
76 return self.agent.http.get(CB.json(), "/v1/agent/members", params=params)
77
78 def maintenance(self, enable: bool, reason: Optional[str] = None, token: str | None = None):
79 """
80 The node maintenance endpoint can place the agent into
81 "maintenance mode".
82
83 *enable* is either 'true' or 'false'. 'true' enables maintenance
84 mode, 'false' disables maintenance mode.
85
86 *reason* is an optional string. This is simply to aid human
87 operators.
88 """
89
90 params: list[tuple[str, Any]] = []
91
92 params.append(("enable", enable))
93 if reason:
94 params.append(("reason", reason))
95
96 headers = self.agent.prepare_headers(token)
97 return self.agent.http.put(CB.boolean(), "/v1/agent/maintenance", params=params, headers=headers)
98
99 def join(self, address: str, wan: bool = False, token: str | None = None):
100 """
101 This endpoint instructs the agent to attempt to connect to a
102 given address.
103
104 *address* is the ip to connect to.
105
106 *wan* is either 'true' or 'false'. For agents running in server
107 mode, 'true' causes the agent to attempt to join using the WAN
108 pool. Default is 'false'.
109 """
110
111 params = []
112
113 if wan:
114 params.append(("wan", 1))
115 headers = self.agent.prepare_headers(token)
116 return self.agent.http.put(CB.boolean(), f"/v1/agent/join/{address}", params=params, headers=headers)
117
118 def force_leave(self, node: str, token: str | None = None):
119 """
120 This endpoint instructs the agent to force a node into the left
121 state. If a node fails unexpectedly, then it will be in a failed
122 state. Once in the failed state, Consul will attempt to reconnect,
123 and the services and checks belonging to that node will not be
124 cleaned up. Forcing a node into the left state allows its old
125 entries to be removed.
126
127 *node* is the node to change state for.
128 """
129
130 headers = self.agent.prepare_headers(token)
131 return self.agent.http.put(CB.boolean(), f"/v1/agent/force-leave/{node}", headers=headers)
132
133 class Service:
134 def __init__(self, agent) -> None:
135 self.agent = agent
136
137 def register(
138 self,
139 name: str,
140 service_id=None,
141 address=None,
142 port: Optional[int] = None,
143 tags=None,
144 check=None,
145 token: str | None = None,
146 meta=None,
147 weights=None,
148 # *deprecated* use check parameter
149 script=None,
150 interval=None,
151 ttl: Optional[int] = None,
152 http=None,
153 timeout=None,
154 enable_tag_override: bool = False,
155 extra_checks=None,
156 replace_existing_checks=False,
157 ):
158 """
159 Add a new service to the local agent. There is more
160 documentation on services
161 `here <http://www.consul.io/docs/agent/services.html>`_.
162
163 *name* is the name of the service.
164
165 If the optional *service_id* is not provided it is set to
166 *name*. You cannot have duplicate *service_id* entries per
167 agent, so it may be necessary to provide one.
168
169 *address* will default to the address of the agent if not
170 provided.
171
172 An optional health *check* can be created for this service is
173 one of `Check.script`_, `Check.http`_, `Check.tcp`_,
174 `Check.ttl`_ or `Check.docker`_.
175
176 *token* is an optional `ACL token`_ to apply to this request.
177 Note this call will return successful even if the token doesn't
178 have permissions to register this service.
179
180 *meta* specifies arbitrary KV metadata linked to the service
181 formatted as {k1:v1, k2:v2}.
182
183 *weights* specifies weights for the service; default to
184 {"Passing": 1, "Warning": 1}.
185
186 *script*, *interval*, *ttl*, *http*, and *timeout* arguments
187 are deprecated. use *check* instead.
188
189 *replace_existing_checks* Missing health checks from the request will
190 be deleted from the agent.
191 Using this parameter allows to idempotently register a service and its
192 checks without having to manually deregister checks.
193
194 *enable_tag_override* is an optional bool that enable you
195 to modify a service tags from servers(consul agent role server)
196 Default is set to False.
197 This option is only for >=v0.6.0 version on both agent and
198 servers.
199 for more information
200 https://www.consul.io/docs/agent/services.html
201 """
202
203 if extra_checks is None:
204 extra_checks = []
205 payload: dict[str, Any] = {}
206
207 payload["name"] = name
208 if enable_tag_override:
209 payload["enabletagoverride"] = enable_tag_override
210 if service_id:
211 payload["id"] = service_id
212 if address:
213 payload["address"] = address
214 if port:
215 payload["port"] = port
216 if tags:
217 payload["tags"] = tags
218 if meta:
219 payload["meta"] = meta
220 if check:
221 payload["checks"] = [check] + extra_checks
222 if weights:
223 payload["weights"] = weights
224 else:
225 payload.update(
226 Check._compat( # pylint: disable=protected-access
227 script=script, interval=interval, ttl=ttl, http=http, timeout=timeout
228 )
229 )
230 params = []
231 if replace_existing_checks:
232 params.append(("replace-existing-checks", "true"))
233 headers = self.agent.prepare_headers(token)
234 return self.agent.http.put(
235 CB.boolean(), "/v1/agent/service/register", params=params, headers=headers, data=json.dumps(payload)
236 )
237
238 def deregister(self, service_id: str, token: str | None = None):
239 """
240 Used to remove a service from the local agent. The agent will
241 take care of deregistering the service with the Catalog. If
242 there is an associated check, that is also deregistered.
243 """
244 headers = self.agent.prepare_headers(token)
245
246 return self.agent.http.put(CB.boolean(), f"/v1/agent/service/deregister/{service_id}", headers=headers)
247
248 def maintenance(self, service_id: str, enable: bool, reason: Optional[str] = None, token: str | None = None):
249 """
250 The service maintenance endpoint allows placing a given service
251 into "maintenance mode".
252
253 *service_id* is the id of the service that is to be targeted
254 for maintenance.
255
256 *enable* is either 'true' or 'false'. 'true' enables
257 maintenance mode, 'false' disables maintenance mode.
258
259 *reason* is an optional string. This is simply to aid human
260 operators.
261 """
262
263 params: list[tuple[str, Any]] = []
264
265 params.append(("enable", enable))
266 if reason:
267 params.append(("reason", reason))
268
269 headers = self.agent.prepare_headers(token)
270
271 return self.agent.http.put(
272 CB.boolean(), f"/v1/agent/service/maintenance/{service_id}", params=params, headers=headers
273 )
274
275 class Check:
276 def __init__(self, agent) -> None:
277 self.agent = agent
278
279 def register(
280 self,
281 name: str,
282 check=None,
283 check_id=None,
284 notes=None,
285 service_id=None,
286 token: str | None = None,
287 # *deprecated* use check parameter
288 script=None,
289 interval=None,
290 ttl: Optional[int] = None,
291 http=None,
292 timeout=None,
293 ):
294 """
295 Register a new check with the local agent. More documentation
296 on checks can be found `here
297 <http://www.consul.io/docs/agent/checks.html>`_.
298
299 *name* is the name of the check.
300
301 *check* is one of `Check.script`_, `Check.http`_, `Check.tcp`_
302 `Check.ttl`_ or `Check.docker`_ and is required.
303
304 If the optional *check_id* is not provided it is set to *name*.
305 *check_id* must be unique for this agent.
306
307 *notes* is not used by Consul, and is meant to be human
308 readable.
309
310 Optionally, a *service_id* can be specified to associate a
311 registered check with an existing service.
312
313 *token* is an optional `ACL token`_ to apply to this request.
314 Note this call will return successful even if the token doesn't
315 have permissions to register this check.
316
317 *script*, *interval*, *ttl*, *http*, and *timeout* arguments
318 are deprecated. use *check* instead.
319
320 Returns *True* on success.
321 """
322 payload = {"name": name}
323
324 assert check or script or ttl or http, "check is required"
325
326 if check:
327 payload.update(check)
328
329 else:
330 payload.update(
331 Check._compat(script=script, interval=interval, ttl=ttl, http=http, timeout=timeout)["check"]
332 )
333
334 if check_id:
335 payload["id"] = check_id
336 if notes:
337 payload["notes"] = notes
338 if service_id:
339 payload["serviceid"] = service_id
340
341 headers = self.agent.prepare_headers(token)
342 return self.agent.http.put(
343 CB.boolean(), "/v1/agent/check/register", headers=headers, data=json.dumps(payload)
344 )
345
346 def deregister(self, check_id: str, token: str | None = None):
347 """
348 Remove a check from the local agent.
349 """
350 headers = self.agent.prepare_headers(token)
351
352 return self.agent.http.put(CB.boolean(), f"/v1/agent/check/deregister/{check_id}", headers=headers)
353
354 def ttl_pass(self, check_id: str, notes=None, token: str | None = None):
355 """
356 Mark a ttl based check as passing. Optional notes can be
357 attached to describe the status of the check.
358 """
359 params = []
360 if notes:
361 params.append(("note", notes))
362 headers = self.agent.prepare_headers(token)
363
364 return self.agent.http.put(CB.boolean(), f"/v1/agent/check/pass/{check_id}", params=params, headers=headers)
365
366 def ttl_fail(self, check_id: str, notes=None, token: str | None = None):
367 """
368 Mark a ttl based check as failing. Optional notes can be
369 attached to describe why check is failing. The status of the
370 check will be set to critical and the ttl clock will be reset.
371 """
372 params = []
373 if notes:
374 params.append(("note", notes))
375 headers = self.agent.prepare_headers(token)
376
377 return self.agent.http.put(CB.boolean(), f"/v1/agent/check/fail/{check_id}", params=params, headers=headers)
378
379 def ttl_warn(self, check_id: str, notes=None, token: str | None = None):
380 """
381 Mark a ttl based check with warning. Optional notes can be
382 attached to describe the warning. The status of the
383 check will be set to warn and the ttl clock will be reset.
384 """
385 params = []
386 if notes:
387 params.append(("note", notes))
388 headers = self.agent.prepare_headers(token)
389
390 return self.agent.http.put(CB.boolean(), f"/v1/agent/check/warn/{check_id}", params=params, headers=headers)
391
392 class Connect:
393 def __init__(self, agent) -> None:
394 self.agent = agent
395 self.ca = Agent.Connect.CA(agent)
396
397 def authorize(self, target, client_cert_uri, client_cert_serial, token: str | None = None):
398 """
399 Tests whether a connection attempt is authorized between
400 two services.
401 More information is available
402 `here <https://www.consul.io/api-docs/agent/connect>`_.
403
404 *target* is the name of the service that is being requested.
405
406 *client_cert_uri* The unique identifier for the requesting
407 client.
408
409 *client_cert_serial* The colon-hex-encoded serial number for
410 the requesting client cert.
411 """
412
413 payload = {"Target": target, "ClientCertURI": client_cert_uri, "ClientCertSerial": client_cert_serial}
414
415 headers = self.agent.prepare_headers(token)
416
417 return self.agent.http.put(
418 CB.json(), "/v1/agent/connect/authorize", headers=headers, data=json.dumps(payload)
419 )
420
421 class CA:
422 def __init__(self, agent) -> None:
423 self.agent = agent
424
425 def roots(self):
426 return self.agent.http.get(CB.json(), "/v1/agent/connect/ca/roots")
427
428 def leaf(self, service, token: str | None = None):
429 headers = self.agent.prepare_headers(token)
430
431 return self.agent.http.get(CB.json(), f"/v1/agent/connect/ca/leaf/{service}", headers=headers)