| 1 | from __future__ import annotations |
| 2 | |
| 3 | import json |
| 4 | |
| 5 | from consul.callback import CB |
| 6 | |
| 7 | |
| 8 | class Catalog: |
| 9 | def __init__(self, agent) -> None: |
| 10 | self.agent = agent |
| 11 | |
| 12 | def register(self, node, address, service=None, check=None, dc=None, token: str | None = None, node_meta=None): |
| 13 | """ |
| 14 | A low level mechanism for directly registering or updating entries |
| 15 | in the catalog. It is usually recommended to use |
| 16 | agent.service.register and agent.check.register, as they are |
| 17 | simpler and perform anti-entropy. |
| 18 | |
| 19 | *node* is the name of the node to register. |
| 20 | |
| 21 | *address* is the ip of the node. |
| 22 | |
| 23 | *service* is an optional service to register. if supplied this is a |
| 24 | dict:: |
| 25 | |
| 26 | { |
| 27 | "Service": "redis", |
| 28 | "ID": "redis1", |
| 29 | "Tags": [ |
| 30 | "master", |
| 31 | "v1" |
| 32 | ], |
| 33 | "Port": 8000 |
| 34 | } |
| 35 | |
| 36 | where |
| 37 | |
| 38 | *Service* is required and is the name of the service |
| 39 | |
| 40 | *ID* is optional, and will be set to *Service* if not provided. |
| 41 | Note *ID* must be unique for the given *node*. |
| 42 | |
| 43 | *Tags* and *Port* are optional. |
| 44 | |
| 45 | *check* is an optional check to register. if supplied this is a |
| 46 | dict:: |
| 47 | |
| 48 | { |
| 49 | "Node": "foobar", |
| 50 | "CheckID": "service:redis1", |
| 51 | "Name": "Redis health check", |
| 52 | "Notes": "Script based health check", |
| 53 | "Status": "passing", |
| 54 | "ServiceID": "redis1" |
| 55 | } |
| 56 | |
| 57 | *dc* is the datacenter of the node and defaults to this agents |
| 58 | datacenter. |
| 59 | |
| 60 | *token* is an optional `ACL token`_ to apply to this request. |
| 61 | |
| 62 | *node_meta* is an optional meta data used for filtering, a |
| 63 | dictionary formatted as {k1:v1, k2:v2}. |
| 64 | |
| 65 | This manipulates the health check entry, but does not setup a |
| 66 | script or TTL to actually update the status. The full documentation |
| 67 | is `here <https://consul.io/docs/agent/http.html#catalog>`_. |
| 68 | |
| 69 | Returns *True* on success. |
| 70 | """ |
| 71 | data = {"node": node, "address": address} |
| 72 | params = [] |
| 73 | dc = dc or self.agent.dc |
| 74 | if dc: |
| 75 | data["datacenter"] = dc |
| 76 | if service: |
| 77 | data["service"] = service |
| 78 | if check: |
| 79 | data["check"] = check |
| 80 | token = token or self.agent.token |
| 81 | if token: |
| 82 | data["WriteRequest"] = {"Token": token} |
| 83 | params.append(("token", token)) |
| 84 | if node_meta: |
| 85 | for nodemeta_name, nodemeta_value in node_meta.items(): |
| 86 | params.append(("node-meta", f"{nodemeta_name}:{nodemeta_value}")) |
| 87 | |
| 88 | headers = self.agent.prepare_headers(token) |
| 89 | return self.agent.http.put( |
| 90 | CB.boolean(), "/v1/catalog/register", data=json.dumps(data), params=params, headers=headers |
| 91 | ) |
| 92 | |
| 93 | def deregister(self, node, service_id=None, check_id=None, dc=None, token: str | None = None): |
| 94 | """ |
| 95 | A low level mechanism for directly removing entries in the catalog. |
| 96 | It is usually recommended to use the agent APIs, as they are |
| 97 | simpler and perform anti-entropy. |
| 98 | |
| 99 | *node* and *dc* specify which node on which datacenter to remove. |
| 100 | If *service_id* and *check_id* are not provided, all associated |
| 101 | services and checks are deleted. Otherwise only one of *service_id* |
| 102 | and *check_id* should be provided and only that service or check |
| 103 | will be removed. |
| 104 | |
| 105 | *token* is an optional `ACL token`_ to apply to this request. |
| 106 | |
| 107 | Returns *True* on success. |
| 108 | """ |
| 109 | assert not (service_id and check_id) |
| 110 | data = {"node": node} |
| 111 | dc = dc or self.agent.dc |
| 112 | if dc: |
| 113 | data["datacenter"] = dc |
| 114 | if service_id: |
| 115 | data["serviceid"] = service_id |
| 116 | if check_id: |
| 117 | data["checkid"] = check_id |
| 118 | token = token or self.agent.token |
| 119 | if token: |
| 120 | data["WriteRequest"] = {"Token": token} |
| 121 | headers = self.agent.prepare_headers(token) |
| 122 | return self.agent.http.put(CB.boolean(), "/v1/catalog/deregister", headers=headers, data=json.dumps(data)) |
| 123 | |
| 124 | def datacenters(self): |
| 125 | """ |
| 126 | Returns all the datacenters that are known by the Consul server. |
| 127 | """ |
| 128 | return self.agent.http.get(CB.json(), "/v1/catalog/datacenters") |
| 129 | |
| 130 | def nodes( |
| 131 | self, index=None, wait=None, consistency=None, dc=None, near=None, token: str | None = None, node_meta=None |
| 132 | ): |
| 133 | """ |
| 134 | Returns a tuple of (*index*, *nodes*) of all nodes known |
| 135 | about in the *dc* datacenter. *dc* defaults to the current |
| 136 | datacenter of this agent. |
| 137 | |
| 138 | *index* is the current Consul index, suitable for making subsequent |
| 139 | calls to wait for changes since this query was last run. |
| 140 | |
| 141 | *wait* the maximum duration to wait (e.g. '10s') to retrieve |
| 142 | a given index. this parameter is only applied if *index* is also |
| 143 | specified. the wait time by default is 5 minutes. |
| 144 | |
| 145 | *near* is a node name to sort the resulting list in ascending |
| 146 | order based on the estimated round trip time from that node |
| 147 | |
| 148 | *consistency* can be either 'default', 'consistent' or 'stale'. if |
| 149 | not specified *consistency* will the consistency level this client |
| 150 | was configured with. |
| 151 | |
| 152 | *token* is an optional `ACL token`_ to apply to this request. |
| 153 | |
| 154 | *node_meta* is an optional meta data used for filtering, a |
| 155 | dictionary formatted as {k1:v1, k2:v2}. |
| 156 | |
| 157 | The response looks like this:: |
| 158 | |
| 159 | (index, [ |
| 160 | { |
| 161 | "Node": "baz", |
| 162 | "Address": "10.1.10.11" |
| 163 | }, |
| 164 | { |
| 165 | "Node": "foobar", |
| 166 | "Address": "10.1.10.12" |
| 167 | } |
| 168 | ]) |
| 169 | """ |
| 170 | params = [] |
| 171 | dc = dc or self.agent.dc |
| 172 | if dc: |
| 173 | params.append(("dc", dc)) |
| 174 | if index: |
| 175 | params.append(("index", index)) |
| 176 | if wait: |
| 177 | params.append(("wait", wait)) |
| 178 | if near: |
| 179 | params.append(("near", near)) |
| 180 | |
| 181 | consistency = consistency or self.agent.consistency |
| 182 | if consistency in ("consistent", "stale"): |
| 183 | params.append((consistency, "1")) |
| 184 | if node_meta: |
| 185 | for nodemeta_name, nodemeta_value in node_meta.items(): |
| 186 | params.append(("node-meta", f"{nodemeta_name}:{nodemeta_value}")) |
| 187 | headers = self.agent.prepare_headers(token) |
| 188 | return self.agent.http.get(CB.json(index=True), "/v1/catalog/nodes", params=params, headers=headers) |
| 189 | |
| 190 | def services(self, index=None, wait=None, consistency=None, dc=None, token: str | None = None, node_meta=None): |
| 191 | """ |
| 192 | Returns a tuple of (*index*, *services*) of all services known |
| 193 | about in the *dc* datacenter. *dc* defaults to the current |
| 194 | datacenter of this agent. |
| 195 | |
| 196 | *index* is the current Consul index, suitable for making subsequent |
| 197 | calls to wait for changes since this query was last run. |
| 198 | |
| 199 | *wait* the maximum duration to wait (e.g. '10s') to retrieve |
| 200 | a given index. this parameter is only applied if *index* is also |
| 201 | specified. the wait time by default is 5 minutes. |
| 202 | |
| 203 | *consistency* can be either 'default', 'consistent' or 'stale'. if |
| 204 | not specified *consistency* will the consistency level this client |
| 205 | was configured with. |
| 206 | |
| 207 | *token* is an optional `ACL token`_ to apply to this request. |
| 208 | |
| 209 | *node_meta* is an optional meta data used for filtering, a |
| 210 | dictionary formatted as {k1:v1, k2:v2}. |
| 211 | |
| 212 | The response looks like this:: |
| 213 | |
| 214 | (index, { |
| 215 | "consul": [], |
| 216 | "redis": [], |
| 217 | "postgresql": [ |
| 218 | "master", |
| 219 | "slave" |
| 220 | ] |
| 221 | }) |
| 222 | |
| 223 | The main keys are the service names and the list provides all the |
| 224 | known tags for a given service. |
| 225 | """ |
| 226 | params = [] |
| 227 | dc = dc or self.agent.dc |
| 228 | if dc: |
| 229 | params.append(("dc", dc)) |
| 230 | if index: |
| 231 | params.append(("index", index)) |
| 232 | if wait: |
| 233 | params.append(("wait", wait)) |
| 234 | consistency = consistency or self.agent.consistency |
| 235 | if consistency in ("consistent", "stale"): |
| 236 | params.append((consistency, "1")) |
| 237 | if node_meta: |
| 238 | for nodemeta_name, nodemeta_value in node_meta.items(): |
| 239 | params.append(("node-meta", f"{nodemeta_name}:{nodemeta_value}")) |
| 240 | headers = self.agent.prepare_headers(token) |
| 241 | return self.agent.http.get(CB.json(index=True), "/v1/catalog/services", params=params, headers=headers) |
| 242 | |
| 243 | def node(self, node, index=None, wait=None, consistency=None, dc=None, token: str | None = None): |
| 244 | """ |
| 245 | Returns a tuple of (*index*, *services*) of all services provided |
| 246 | by *node*. |
| 247 | |
| 248 | *index* is the current Consul index, suitable for making subsequent |
| 249 | calls to wait for changes since this query was last run. |
| 250 | |
| 251 | *wait* the maximum duration to wait (e.g. '10s') to retrieve |
| 252 | a given index. this parameter is only applied if *index* is also |
| 253 | specified. the wait time by default is 5 minutes. |
| 254 | |
| 255 | *consistency* can be either 'default', 'consistent' or 'stale'. if |
| 256 | not specified *consistency* will the consistency level this client |
| 257 | was configured with. |
| 258 | |
| 259 | *dc* is the datacenter of the node and defaults to this agents |
| 260 | datacenter. |
| 261 | |
| 262 | *token* is an optional `ACL token`_ to apply to this request. |
| 263 | |
| 264 | The response looks like this:: |
| 265 | |
| 266 | (index, { |
| 267 | "Node": { |
| 268 | "Node": "foobar", |
| 269 | "Address": "10.1.10.12" |
| 270 | }, |
| 271 | "Services": { |
| 272 | "consul": { |
| 273 | "ID": "consul", |
| 274 | "Service": "consul", |
| 275 | "Tags": null, |
| 276 | "Port": 8300 |
| 277 | }, |
| 278 | "redis": { |
| 279 | "ID": "redis", |
| 280 | "Service": "redis", |
| 281 | "Tags": [ |
| 282 | "v1" |
| 283 | ], |
| 284 | "Port": 8000 |
| 285 | } |
| 286 | } |
| 287 | }) |
| 288 | """ |
| 289 | params = [] |
| 290 | dc = dc or self.agent.dc |
| 291 | if dc: |
| 292 | params.append(("dc", dc)) |
| 293 | if index: |
| 294 | params.append(("index", index)) |
| 295 | if wait: |
| 296 | params.append(("wait", wait)) |
| 297 | consistency = consistency or self.agent.consistency |
| 298 | if consistency in ("consistent", "stale"): |
| 299 | params.append((consistency, "1")) |
| 300 | headers = self.agent.prepare_headers(token) |
| 301 | return self.agent.http.get(CB.json(index=True), f"/v1/catalog/node/{node}", params=params, headers=headers) |
| 302 | |
| 303 | def _service( |
| 304 | self, |
| 305 | internal_uri, |
| 306 | index=None, |
| 307 | wait=None, |
| 308 | tag=None, |
| 309 | consistency=None, |
| 310 | dc=None, |
| 311 | near=None, |
| 312 | token: str | None = None, |
| 313 | node_meta=None, |
| 314 | ): |
| 315 | params = [] |
| 316 | dc = dc or self.agent.dc |
| 317 | if dc: |
| 318 | params.append(("dc", dc)) |
| 319 | if tag: |
| 320 | params.append(("tag", tag)) |
| 321 | if index: |
| 322 | params.append(("index", index)) |
| 323 | if wait: |
| 324 | params.append(("wait", wait)) |
| 325 | if near: |
| 326 | params.append(("near", near)) |
| 327 | consistency = consistency or self.agent.consistency |
| 328 | if consistency in ("consistent", "stale"): |
| 329 | params.append((consistency, "1")) |
| 330 | if node_meta: |
| 331 | for nodemeta_name, nodemeta_value in node_meta.items(): |
| 332 | params.append(("node-meta", f"{nodemeta_name}:{nodemeta_value}")) |
| 333 | headers = self.agent.prepare_headers(token) |
| 334 | return self.agent.http.get(CB.json(index=True), internal_uri, params=params, headers=headers) |
| 335 | |
| 336 | def service(self, service: str, **kwargs): |
| 337 | """ |
| 338 | Returns a tuple of (*index*, *nodes*) of the nodes providing |
| 339 | *service* in the *dc* datacenter. *dc* defaults to the current |
| 340 | datacenter of this agent. |
| 341 | |
| 342 | *index* is the current Consul index, suitable for making subsequent |
| 343 | calls to wait for changes since this query was last run. |
| 344 | |
| 345 | *wait* the maximum duration to wait (e.g. '10s') to retrieve |
| 346 | a given index. this parameter is only applied if *index* is also |
| 347 | specified. the wait time by default is 5 minutes. |
| 348 | |
| 349 | If *tag* is provided, the list of nodes returned will be filtered |
| 350 | by that tag. |
| 351 | |
| 352 | *near* is a node name to sort the resulting list in ascending |
| 353 | order based on the estimated round trip time from that node |
| 354 | |
| 355 | *consistency* can be either 'default', 'consistent' or 'stale'. if |
| 356 | not specified *consistency* will the consistency level this client |
| 357 | was configured with. |
| 358 | |
| 359 | *token* is an optional `ACL token`_ to apply to this request. |
| 360 | |
| 361 | *node_meta* is an optional meta data used for filtering, a |
| 362 | dictionary formatted as {k1:v1, k2:v2}. |
| 363 | |
| 364 | The response looks like this:: |
| 365 | |
| 366 | (index, [ |
| 367 | { |
| 368 | "Node": "foobar", |
| 369 | "Address": "10.1.10.12", |
| 370 | "ServiceID": "redis", |
| 371 | "ServiceName": "redis", |
| 372 | "ServiceTags": null, |
| 373 | "ServicePort": 8000 |
| 374 | } |
| 375 | ]) |
| 376 | """ |
| 377 | internal_uri = f"/v1/catalog/service/{service}" |
| 378 | return self._service(internal_uri=internal_uri, **kwargs) |
| 379 | |
| 380 | def connect(self, service: str, **kwargs): |
| 381 | """ |
| 382 | Returns a tuple of (*index*, *nodes*) of the nodes providing |
| 383 | connect-capable *service* in the *dc* datacenter. *dc* defaults |
| 384 | to the current datacenter of this agent. |
| 385 | |
| 386 | Request arguments and response format are the same as catalog.service |
| 387 | """ |
| 388 | internal_uri = f"/v1/catalog/connect/{service}" |
| 389 | return self._service(internal_uri=internal_uri, **kwargs) |