Debian Codegraph @

consul/base.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import abc
4 import collections
5 import logging
6 import os
7 import urllib
8 from typing import TYPE_CHECKING, Any, Optional
9
10 from consul.api.acl import ACL
11 from consul.api.agent import Agent
12 from consul.api.catalog import Catalog
13 from consul.api.connect import Connect
14 from consul.api.coordinates import Coordinate
15 from consul.api.event import Event
16 from consul.api.health import Health
17 from consul.api.kv import KV
18 from consul.api.operator import Operator
19 from consul.api.query import Query
20 from consul.api.session import Session
21 from consul.api.status import Status
22 from consul.api.txn import Txn
23 from consul.exceptions import ConsulException
24
25 if TYPE_CHECKING:
26 from types import TracebackType
27
28 log = logging.getLogger(__name__)
29
30
31 #
32 # Convenience to define checks
33
34
35 Response = collections.namedtuple("Response", ["code", "headers", "body"])
36
37
38 class HTTPClient(metaclass=abc.ABCMeta):
39 def __init__(
40 self, host: str = "127.0.0.1", port: int = 8500, scheme: str = "http", verify: bool = True, cert=None
41 ) -> None:
42 self.host = host
43 self.port = port
44 self.scheme = scheme
45 self.verify = verify
46 self.base_uri = f"{self.scheme}://{self.host}:{self.port}"
47 self.cert = cert
48
49 def uri(self, path: str, params: list[tuple[str, Any]] | None = None):
50 uri = self.base_uri + urllib.parse.quote(path, safe="/:")
51 if params:
52 uri = f"{uri}?{urllib.parse.urlencode(params)}"
53 return uri
54
55 @abc.abstractmethod
56 def get(self, callback, path, params=None, headers: Optional[dict[str, str]] = None):
57 raise NotImplementedError
58
59 @abc.abstractmethod
60 def put(self, callback, path, params=None, data: str = "", headers: Optional[dict[str, str]] = None):
61 raise NotImplementedError
62
63 @abc.abstractmethod
64 def delete(self, callback, path, params=None, headers: Optional[dict[str, str]] = None):
65 raise NotImplementedError
66
67 @abc.abstractmethod
68 def post(self, callback, path, params=None, data: str = "", headers: Optional[dict[str, str]] = None):
69 raise NotImplementedError
70
71 @abc.abstractmethod
72 def close(self):
73 raise NotImplementedError
74
75
76 class Consul:
77 def __init__(
78 self,
79 host: str | None = None,
80 port: int | None = None,
81 token: str | None = None,
82 scheme: str | None = None,
83 consistency: str = "default",
84 dc=None,
85 verify: bool | None = None,
86 cert=None,
87 ) -> None:
88 """
89 *token* is an optional `ACL token`_. If supplied it will be used by
90 default for all requests made with this client session. It's still
91 possible to override this token by passing a token explicitly for a
92 request.
93
94 *consistency* sets the consistency mode to use by default for all reads
95 that support the consistency option. It's still possible to override
96 this by passing explicitly for a given request. *consistency* can be
97 either 'default', 'consistent' or 'stale'.
98
99 *dc* is the datacenter that this agent will communicate with.
100 By default the datacenter of the host is used.
101
102 *verify* is whether to verify the SSL certificate for HTTPS requests
103
104 *cert* client side certificates for HTTPS requests
105 """
106
107 # TODO: Status
108
109 if os.getenv("CONSUL_HTTP_ADDR") and not (host or port):
110 try:
111 host, port = os.getenv("CONSUL_HTTP_ADDR").split(":") # type: ignore
112 except ValueError as err:
113 raise ConsulException(
114 f"CONSUL_HTTP_ADDR ({os.getenv('CONSUL_HTTP_ADDR')}) invalid, does not match <host>:<port>"
115 ) from err
116 if not host:
117 host = "127.0.0.1"
118 if not port:
119 port = 8500
120
121 if scheme is None:
122 use_ssl = os.getenv("CONSUL_HTTP_SSL")
123 scheme = ("https" if use_ssl.lower() == "true" else "http") if use_ssl else "http"
124
125 if verify is None:
126 ssl_verify = os.getenv("CONSUL_HTTP_SSL_VERIFY")
127 verify = ssl_verify.lower() == "true" if ssl_verify else True
128
129 self.http = self.http_connect(host, port, scheme, verify, cert)
130 self.token = os.getenv("CONSUL_HTTP_TOKEN", token)
131 self.scheme = scheme
132 self.dc = dc
133 assert consistency in (
134 "default",
135 "consistent",
136 "stale",
137 ), "consistency must be either default, consistent or state"
138 self.consistency = consistency
139
140 self.event = Event(self)
141 self.kv = KV(self)
142 self.txn = Txn(self)
143 self.agent = Agent(self)
144 self.catalog = Catalog(self)
145 self.health = Health(self)
146 self.session = Session(self)
147 self.acl = ACL(self)
148 self.status = Status(self)
149 self.query = Query(self)
150 self.coordinate = Coordinate(self)
151 self.operator = Operator(self)
152 self.connect = Connect(self)
153
154 def __enter__(self):
155 return self
156
157 async def __aenter__(self):
158 return self
159
160 def __exit__(
161 self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
162 ) -> None:
163 self.http.close()
164
165 async def __aexit__(
166 self, exc_type: Optional[type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]
167 ) -> None:
168 await self.http.close()
169
170 @abc.abstractmethod
171 def http_connect(self, host: str, port: int, scheme, verify: bool = True, cert=None):
172 pass
173
174 def prepare_headers(self, token: Optional[str] = None) -> dict[str, str]:
175 headers = {}
176 if token or self.token:
177 headers["X-Consul-Token"] = token or self.token
178 return headers # type: ignore