kubex 0.1.0a1__py3-none-any.whl
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.
- kubex/__init__.py +4 -0
- kubex/__version__.py +1 -0
- kubex/client/__init__.py +5 -0
- kubex/client/api/__init__.py +3 -0
- kubex/client/api/_logs.py +64 -0
- kubex/client/api/_metadata.py +65 -0
- kubex/client/api/_protocol.py +14 -0
- kubex/client/api/_subressource.py +105 -0
- kubex/client/api/api.py +187 -0
- kubex/client/client.py +157 -0
- kubex/client/configuration.py +252 -0
- kubex/client/file_config.py +95 -0
- kubex/client/incluster_config.py +39 -0
- kubex/core/__init__.py +3 -0
- kubex/core/exceptions.py +73 -0
- kubex/core/params.py +273 -0
- kubex/core/patch.py +93 -0
- kubex/core/request.py +20 -0
- kubex/core/request_builder/__init__.py +0 -0
- kubex/core/request_builder/builder.py +120 -0
- kubex/core/request_builder/constants.py +7 -0
- kubex/core/request_builder/logs.py +27 -0
- kubex/core/request_builder/metadata.py +68 -0
- kubex/core/request_builder/subresource.py +53 -0
- kubex/core/response.py +18 -0
- kubex/core/subresource.py +15 -0
- kubex/models/__init__.py +0 -0
- kubex/models/base.py +8 -0
- kubex/models/base_entity.py +15 -0
- kubex/models/interfaces.py +19 -0
- kubex/models/list_entity.py +14 -0
- kubex/models/metadata.py +45 -0
- kubex/models/namespace.py +26 -0
- kubex/models/partial_object_meta.py +14 -0
- kubex/models/pod.py +31 -0
- kubex/models/resource_config.py +156 -0
- kubex/models/scale.py +22 -0
- kubex/models/status.py +60 -0
- kubex/models/typing.py +9 -0
- kubex/models/watch_event.py +36 -0
- kubex/py.typed +0 -0
- kubex-0.1.0a1.dist-info/METADATA +53 -0
- kubex-0.1.0a1.dist-info/RECORD +44 -0
- kubex-0.1.0a1.dist-info/WHEEL +4 -0
kubex/__init__.py
ADDED
kubex/__version__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
VERSION = "0.1.0-alpha.1"
|
kubex/client/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
from typing import AsyncGenerator
|
|
2
|
+
|
|
3
|
+
from kubex.core.params import LogOptions
|
|
4
|
+
from kubex.models.interfaces import HasLogs
|
|
5
|
+
from kubex.models.typing import ResourceType
|
|
6
|
+
|
|
7
|
+
from ._protocol import ApiProtocol
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LogsMixin(ApiProtocol[ResourceType]):
|
|
11
|
+
def _check_implemented(self) -> None:
|
|
12
|
+
if not issubclass(self._resource, HasLogs):
|
|
13
|
+
raise NotImplementedError("Logs are only supported for Pods")
|
|
14
|
+
|
|
15
|
+
# TODO: Investigate how to force mypy to complain on logs calling with non-Pod resources
|
|
16
|
+
# @overload
|
|
17
|
+
# def logs(
|
|
18
|
+
# self: Type[ApiProtocol[Any]],
|
|
19
|
+
# name: str,
|
|
20
|
+
# options: LogOptions | None = None,
|
|
21
|
+
# ) -> NoReturn: ...
|
|
22
|
+
|
|
23
|
+
# @overload
|
|
24
|
+
# def logs(
|
|
25
|
+
# self: Type[ApiProtocol[PodProtocol]],
|
|
26
|
+
# name: str,
|
|
27
|
+
# options: LogOptions | None = None,
|
|
28
|
+
# ) -> Awaitable[str]: ...
|
|
29
|
+
|
|
30
|
+
async def logs(self, name: str, options: LogOptions | None = None) -> str:
|
|
31
|
+
self._check_implemented()
|
|
32
|
+
self._check_namespace()
|
|
33
|
+
request = self._request_builder.logs(
|
|
34
|
+
name, options=options or LogOptions.default()
|
|
35
|
+
)
|
|
36
|
+
response = await self._client.request(request)
|
|
37
|
+
return response.text
|
|
38
|
+
|
|
39
|
+
# TODO: Investigate how to force mypy to complain on stream_logs calling with non-Pod resources
|
|
40
|
+
# @overload
|
|
41
|
+
# def stream_logs(
|
|
42
|
+
# self: Type[ApiProtocol[ResourceType]],
|
|
43
|
+
# name: str,
|
|
44
|
+
# options: LogOptions | None = None,
|
|
45
|
+
# ) -> NoReturn: ...
|
|
46
|
+
|
|
47
|
+
# @overload
|
|
48
|
+
# def stream_logs(
|
|
49
|
+
# self: Type[ApiProtocol[PodProtocol]],
|
|
50
|
+
# name: str,
|
|
51
|
+
# options: LogOptions | None = None,
|
|
52
|
+
# ) -> AsyncGenerator[str, None]: ...
|
|
53
|
+
|
|
54
|
+
async def stream_logs(
|
|
55
|
+
self, name: str, options: LogOptions | None = None
|
|
56
|
+
) -> AsyncGenerator[str, None]:
|
|
57
|
+
self._check_implemented()
|
|
58
|
+
self._check_namespace()
|
|
59
|
+
request = self._request_builder.stream_logs(
|
|
60
|
+
name, options=options or LogOptions.default()
|
|
61
|
+
)
|
|
62
|
+
# TODO: ReadTimeout
|
|
63
|
+
async for line in self._client.stream_lines(request):
|
|
64
|
+
yield line
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import AsyncGenerator
|
|
5
|
+
|
|
6
|
+
from kubex.client.api._protocol import ApiProtocol
|
|
7
|
+
from kubex.core.params import GetOptions, ListOptions, PatchOptions, WatchOptions
|
|
8
|
+
from kubex.core.patch import (
|
|
9
|
+
ApplyPatch,
|
|
10
|
+
JsonPatch,
|
|
11
|
+
MergePatch,
|
|
12
|
+
StrategicMergePatch,
|
|
13
|
+
)
|
|
14
|
+
from kubex.models.list_entity import ListEntity
|
|
15
|
+
from kubex.models.partial_object_meta import PartialObjectMetadata
|
|
16
|
+
from kubex.models.typing import (
|
|
17
|
+
ResourceType,
|
|
18
|
+
)
|
|
19
|
+
from kubex.models.watch_event import WatchEvent
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MetadataMixin(ApiProtocol[ResourceType]):
|
|
23
|
+
async def get_metadata(
|
|
24
|
+
self, name: str, options: GetOptions | None = None
|
|
25
|
+
) -> PartialObjectMetadata:
|
|
26
|
+
self._check_namespace()
|
|
27
|
+
request = self._request_builder.get_metadata(
|
|
28
|
+
name, options=options or GetOptions.default()
|
|
29
|
+
)
|
|
30
|
+
response = await self._client.request(request)
|
|
31
|
+
return PartialObjectMetadata.model_validate_json(response.content)
|
|
32
|
+
|
|
33
|
+
async def list_metadata(
|
|
34
|
+
self, options: ListOptions | None = None
|
|
35
|
+
) -> ListEntity[PartialObjectMetadata]:
|
|
36
|
+
request = self._request_builder.list_metadata(options or ListOptions.default())
|
|
37
|
+
response = await self._client.request(request)
|
|
38
|
+
model = PartialObjectMetadata.__RESOURCE_CONFIG__.list_model
|
|
39
|
+
return model.model_validate_json(response.content)
|
|
40
|
+
|
|
41
|
+
async def patch_metadata(
|
|
42
|
+
self,
|
|
43
|
+
name: str,
|
|
44
|
+
patch: ApplyPatch[ResourceType]
|
|
45
|
+
| MergePatch[ResourceType]
|
|
46
|
+
| StrategicMergePatch[ResourceType]
|
|
47
|
+
| JsonPatch,
|
|
48
|
+
options: PatchOptions,
|
|
49
|
+
) -> PartialObjectMetadata:
|
|
50
|
+
self._check_namespace()
|
|
51
|
+
request = self._request_builder.patch_metadata(name, options, patch)
|
|
52
|
+
response = await self._client.request(request)
|
|
53
|
+
return PartialObjectMetadata.model_validate_json(response.content)
|
|
54
|
+
|
|
55
|
+
async def watch_metadata(
|
|
56
|
+
self, options: WatchOptions | None = None, resource_version: str | None = None
|
|
57
|
+
) -> AsyncGenerator[
|
|
58
|
+
WatchEvent[PartialObjectMetadata],
|
|
59
|
+
None,
|
|
60
|
+
]:
|
|
61
|
+
request = self._request_builder.watch_metadata(
|
|
62
|
+
options or WatchOptions.default(), resource_version=resource_version
|
|
63
|
+
)
|
|
64
|
+
async for line in self._client.stream_lines(request):
|
|
65
|
+
yield WatchEvent(PartialObjectMetadata, json.loads(line))
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from typing import Protocol, Type
|
|
2
|
+
|
|
3
|
+
from kubex.client.client import Client
|
|
4
|
+
from kubex.core.request_builder.builder import RequestBuilder
|
|
5
|
+
from kubex.models.typing import ResourceType
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ApiProtocol(Protocol[ResourceType]):
|
|
9
|
+
_resource: Type[ResourceType]
|
|
10
|
+
_client: Client
|
|
11
|
+
_request_builder: RequestBuilder
|
|
12
|
+
_namespace: str | None
|
|
13
|
+
|
|
14
|
+
def _check_namespace(self) -> None: ...
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
from kubex.core.params import PatchOptions, PostOptions
|
|
2
|
+
from kubex.core.patch import (
|
|
3
|
+
Patch,
|
|
4
|
+
)
|
|
5
|
+
from kubex.models.interfaces import HasScaleSubresource
|
|
6
|
+
from kubex.models.scale import Scale
|
|
7
|
+
from kubex.models.typing import ResourceType
|
|
8
|
+
|
|
9
|
+
from ._protocol import ApiProtocol
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ScaleMixin(ApiProtocol[ResourceType]):
|
|
13
|
+
def _check_implemented(self) -> None:
|
|
14
|
+
if not issubclass(self._resource, HasScaleSubresource):
|
|
15
|
+
raise NotImplementedError(
|
|
16
|
+
"Scale is only supported for resources with replicas"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
async def get_scale(self, name: str) -> Scale:
|
|
20
|
+
self._check_implemented()
|
|
21
|
+
self._check_namespace()
|
|
22
|
+
request = self._request_builder.get_subresource("scale", name)
|
|
23
|
+
response = await self._client.request(request)
|
|
24
|
+
return Scale.model_validate_json(response.content)
|
|
25
|
+
|
|
26
|
+
async def replace_scale(
|
|
27
|
+
self, name: str, scale: Scale, options: PostOptions | None = None
|
|
28
|
+
) -> Scale:
|
|
29
|
+
self._check_implemented()
|
|
30
|
+
self._check_namespace()
|
|
31
|
+
request = self._request_builder.replace_subresource(
|
|
32
|
+
"scale",
|
|
33
|
+
name,
|
|
34
|
+
data=scale.model_dump_json(
|
|
35
|
+
by_alias=True, exclude_unset=True, exclude_none=True
|
|
36
|
+
),
|
|
37
|
+
options=options or PostOptions.default(),
|
|
38
|
+
)
|
|
39
|
+
response = await self._client.request(request)
|
|
40
|
+
return Scale.model_validate_json(response.content)
|
|
41
|
+
|
|
42
|
+
async def patch_scale(
|
|
43
|
+
self,
|
|
44
|
+
name: str,
|
|
45
|
+
patch: Patch,
|
|
46
|
+
options: PatchOptions | None = None,
|
|
47
|
+
) -> Scale:
|
|
48
|
+
self._check_implemented()
|
|
49
|
+
self._check_namespace()
|
|
50
|
+
request = self._request_builder.patch_subresource(
|
|
51
|
+
"scale",
|
|
52
|
+
name,
|
|
53
|
+
options=options or PatchOptions.default(),
|
|
54
|
+
patch=patch,
|
|
55
|
+
)
|
|
56
|
+
response = await self._client.request(request)
|
|
57
|
+
return Scale.model_validate_json(response.content)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# class _SubresourceMixin(ApiProtocol[ResourceType]):
|
|
61
|
+
# def _check_subresource(self, surecesource: Subresource) -> None:
|
|
62
|
+
# parent_required = surecesource.value
|
|
63
|
+
# if not issubclass(self._resource, parent_required):
|
|
64
|
+
# raise NotImplementedError(
|
|
65
|
+
# f"{self._resource.__RESOURCE_CONFIG__.kind} from {self._resource.__RESOURCE_CONFIG__.api_version} has no {surecesource.name.lower()} subresource"
|
|
66
|
+
# )
|
|
67
|
+
|
|
68
|
+
# async def get_subresource(
|
|
69
|
+
# self, name: str, subresource: Subresource
|
|
70
|
+
# ) -> ResourceType:
|
|
71
|
+
# self._check_subresource(subresource)
|
|
72
|
+
# self._check_namespace()
|
|
73
|
+
# request = self._request_builder.get_subresource(name, subresource)
|
|
74
|
+
# async with self._client.get_client() as client:
|
|
75
|
+
# response = await client.get(request.url, params=request.query_params)
|
|
76
|
+
# response.raise_for_status()
|
|
77
|
+
# return self._resource.model_validate_json(response.content)
|
|
78
|
+
|
|
79
|
+
# async def patch_subresource(
|
|
80
|
+
# self, name: str, subresource: str, patch: dict[str, str]
|
|
81
|
+
# ) -> ResourceType:
|
|
82
|
+
# self._check_namespace()
|
|
83
|
+
# request = self._request_builder.patch_subresource(name, subresource, patch)
|
|
84
|
+
# async with self._client.get_client() as client:
|
|
85
|
+
# response = await client.patch(
|
|
86
|
+
# request.url,
|
|
87
|
+
# data=patch,
|
|
88
|
+
# headers={"Content-Type": "application/merge-patch+json"},
|
|
89
|
+
# )
|
|
90
|
+
# response.raise_for_status()
|
|
91
|
+
# return self._resource.model_validate_json(response.content)
|
|
92
|
+
|
|
93
|
+
# async def replace_subresource(
|
|
94
|
+
# self, name: str, subresource: str, body: ResourceType
|
|
95
|
+
# ) -> ResourceType:
|
|
96
|
+
# self._check_namespace()
|
|
97
|
+
# request = self._request_builder.replace_subresource(name, subresource, body)
|
|
98
|
+
# async with self._client.get_client() as client:
|
|
99
|
+
# response = await client.put(
|
|
100
|
+
# request.url,
|
|
101
|
+
# data=body.json(),
|
|
102
|
+
# headers={"Content-Type": "application/json"},
|
|
103
|
+
# )
|
|
104
|
+
# response.raise_for_status()
|
|
105
|
+
# return self._resource.model_validate_json(response.content)
|
kubex/client/api/api.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import (
|
|
5
|
+
AsyncGenerator,
|
|
6
|
+
Generic,
|
|
7
|
+
Type,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
|
|
12
|
+
from kubex.client.client import Client
|
|
13
|
+
from kubex.core.params import (
|
|
14
|
+
DeleteOptions,
|
|
15
|
+
GetOptions,
|
|
16
|
+
ListOptions,
|
|
17
|
+
PatchOptions,
|
|
18
|
+
PostOptions,
|
|
19
|
+
VersionMatch,
|
|
20
|
+
WatchOptions,
|
|
21
|
+
)
|
|
22
|
+
from kubex.core.patch import (
|
|
23
|
+
ApplyPatch,
|
|
24
|
+
JsonPatch,
|
|
25
|
+
MergePatch,
|
|
26
|
+
StrategicMergePatch,
|
|
27
|
+
)
|
|
28
|
+
from kubex.core.request_builder.builder import RequestBuilder
|
|
29
|
+
from kubex.models.list_entity import ListEntity
|
|
30
|
+
from kubex.models.resource_config import Scope
|
|
31
|
+
from kubex.models.status import Status
|
|
32
|
+
from kubex.models.typing import (
|
|
33
|
+
ResourceType,
|
|
34
|
+
)
|
|
35
|
+
from kubex.models.watch_event import WatchEvent
|
|
36
|
+
|
|
37
|
+
from ._logs import LogsMixin
|
|
38
|
+
from ._metadata import MetadataMixin
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Api(Generic[ResourceType], MetadataMixin[ResourceType], LogsMixin[ResourceType]):
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
resource_type: Type[ResourceType],
|
|
45
|
+
client: Client,
|
|
46
|
+
*,
|
|
47
|
+
namespace: str | None = None,
|
|
48
|
+
) -> None:
|
|
49
|
+
self._resource = resource_type
|
|
50
|
+
self._client = client
|
|
51
|
+
self._request_builder = RequestBuilder(
|
|
52
|
+
resource_config=resource_type.__RESOURCE_CONFIG__,
|
|
53
|
+
)
|
|
54
|
+
self._request_builder.namespace = namespace
|
|
55
|
+
self._namespace: str | None = namespace
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
async def create_api(
|
|
59
|
+
cls,
|
|
60
|
+
resource_type: Type[ResourceType],
|
|
61
|
+
*,
|
|
62
|
+
client: Client | None = None,
|
|
63
|
+
namespace: str | None = None,
|
|
64
|
+
) -> Api[ResourceType]:
|
|
65
|
+
client = client or await Client.create()
|
|
66
|
+
return cls(resource_type, client=client, namespace=namespace)
|
|
67
|
+
|
|
68
|
+
def _check_namespace(self) -> None:
|
|
69
|
+
if (
|
|
70
|
+
self._namespace is None
|
|
71
|
+
and self._resource.__RESOURCE_CONFIG__.scope == Scope.NAMESPACE
|
|
72
|
+
):
|
|
73
|
+
raise ValueError("Namespace is required")
|
|
74
|
+
|
|
75
|
+
async def get(self, name: str, resource_version: str | None = None) -> ResourceType:
|
|
76
|
+
options = GetOptions(resource_version=resource_version)
|
|
77
|
+
return await self.get_with_options(name, options)
|
|
78
|
+
|
|
79
|
+
async def get_with_options(self, name: str, options: GetOptions) -> ResourceType:
|
|
80
|
+
self._check_namespace()
|
|
81
|
+
request = self._request_builder.get(name, options)
|
|
82
|
+
response = await self._client.request(request)
|
|
83
|
+
return self._resource.model_validate_json(response.content)
|
|
84
|
+
|
|
85
|
+
async def list(
|
|
86
|
+
self,
|
|
87
|
+
label_selector: str | None = None,
|
|
88
|
+
field_selector: str | None = None,
|
|
89
|
+
timeout: int | None = None,
|
|
90
|
+
limit: int | None = None,
|
|
91
|
+
continue_token: str | None = None,
|
|
92
|
+
version_match: VersionMatch | None = None,
|
|
93
|
+
resource_version: str | None = None,
|
|
94
|
+
) -> ListEntity[ResourceType]:
|
|
95
|
+
options = ListOptions(
|
|
96
|
+
label_selector=label_selector,
|
|
97
|
+
field_selector=field_selector,
|
|
98
|
+
timeout=timeout,
|
|
99
|
+
limit=limit,
|
|
100
|
+
continue_token=continue_token,
|
|
101
|
+
version_match=version_match,
|
|
102
|
+
resource_version=resource_version,
|
|
103
|
+
)
|
|
104
|
+
return await self.list_with_options(options)
|
|
105
|
+
|
|
106
|
+
async def list_with_options(self, options: ListOptions) -> ListEntity[ResourceType]:
|
|
107
|
+
request = self._request_builder.list(options)
|
|
108
|
+
response = await self._client.request(request)
|
|
109
|
+
# json_ = response.json()
|
|
110
|
+
list_model = self._resource.__RESOURCE_CONFIG__.list_model
|
|
111
|
+
return list_model.model_validate_json(response.content)
|
|
112
|
+
|
|
113
|
+
async def create(self, data: ResourceType) -> ResourceType:
|
|
114
|
+
options = PostOptions()
|
|
115
|
+
return await self.create_with_options(data, options)
|
|
116
|
+
|
|
117
|
+
async def create_with_options(
|
|
118
|
+
self, data: ResourceType, options: PostOptions
|
|
119
|
+
) -> ResourceType:
|
|
120
|
+
self._check_namespace()
|
|
121
|
+
request = self._request_builder.create(
|
|
122
|
+
options,
|
|
123
|
+
data.model_dump_json(by_alias=True, exclude_unset=True, exclude_none=True),
|
|
124
|
+
)
|
|
125
|
+
response = await self._client.request(request)
|
|
126
|
+
return self._resource.model_validate_json(response.content)
|
|
127
|
+
|
|
128
|
+
async def delete(
|
|
129
|
+
self, name: str, options: DeleteOptions | None = None
|
|
130
|
+
) -> Status | ResourceType:
|
|
131
|
+
self._check_namespace()
|
|
132
|
+
if options is None:
|
|
133
|
+
options = DeleteOptions.default()
|
|
134
|
+
request = self._request_builder.delete(name, options)
|
|
135
|
+
response = await self._client.request(request)
|
|
136
|
+
try:
|
|
137
|
+
return Status.model_validate_json(response.content)
|
|
138
|
+
except ValidationError:
|
|
139
|
+
return self._resource.model_validate_json(response.content)
|
|
140
|
+
|
|
141
|
+
async def delete_collection(
|
|
142
|
+
self, list_options: ListOptions, delete_options: DeleteOptions
|
|
143
|
+
) -> Status | ListEntity[ResourceType]:
|
|
144
|
+
request = self._request_builder.delete_collection(list_options, delete_options)
|
|
145
|
+
response = await self._client.request(request)
|
|
146
|
+
list_model = self._resource.__RESOURCE_CONFIG__.list_model
|
|
147
|
+
try:
|
|
148
|
+
return Status.model_validate_json(response.content)
|
|
149
|
+
except ValidationError:
|
|
150
|
+
return list_model.model_validate_json(response.content)
|
|
151
|
+
|
|
152
|
+
async def patch(
|
|
153
|
+
self,
|
|
154
|
+
name: str,
|
|
155
|
+
patch: ApplyPatch[ResourceType]
|
|
156
|
+
| MergePatch[ResourceType]
|
|
157
|
+
| StrategicMergePatch[ResourceType]
|
|
158
|
+
| JsonPatch,
|
|
159
|
+
options: PatchOptions,
|
|
160
|
+
) -> ResourceType:
|
|
161
|
+
self._check_namespace()
|
|
162
|
+
request = self._request_builder.patch(name, options, patch)
|
|
163
|
+
response = await self._client.request(request)
|
|
164
|
+
return self._resource.model_validate_json(response.content)
|
|
165
|
+
|
|
166
|
+
async def replace(
|
|
167
|
+
self, name: str, data: ResourceType, options: PostOptions
|
|
168
|
+
) -> ResourceType:
|
|
169
|
+
self._check_namespace()
|
|
170
|
+
request = self._request_builder.replace(
|
|
171
|
+
name,
|
|
172
|
+
options,
|
|
173
|
+
data.model_dump_json(by_alias=True, exclude_unset=True, exclude_none=True),
|
|
174
|
+
)
|
|
175
|
+
response = await self._client.request(request)
|
|
176
|
+
return self._resource.model_validate_json(response.content)
|
|
177
|
+
|
|
178
|
+
async def watch(
|
|
179
|
+
self, options: WatchOptions | None = None, resource_version: str | None = None
|
|
180
|
+
) -> AsyncGenerator[WatchEvent[ResourceType], None]:
|
|
181
|
+
if options is None:
|
|
182
|
+
options = WatchOptions.default()
|
|
183
|
+
request = self._request_builder.watch(
|
|
184
|
+
options, resource_version=resource_version
|
|
185
|
+
)
|
|
186
|
+
async for line in self._client.stream_lines(request):
|
|
187
|
+
yield WatchEvent(self._resource, json.loads(line))
|
kubex/client/client.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import warnings
|
|
5
|
+
from http import HTTPStatus
|
|
6
|
+
from types import TracebackType
|
|
7
|
+
from typing import AsyncGenerator, NoReturn, Self
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
|
|
12
|
+
from kubex.client.configuration import ClientConfiguration
|
|
13
|
+
from kubex.core import exceptions
|
|
14
|
+
from kubex.core.request import Request
|
|
15
|
+
from kubex.core.request_builder.constants import (
|
|
16
|
+
APPLICATION_JSON_MIME_TYPE,
|
|
17
|
+
CONTENT_TYPE_HEADER,
|
|
18
|
+
)
|
|
19
|
+
from kubex.core.response import Response
|
|
20
|
+
from kubex.models.status import Status
|
|
21
|
+
|
|
22
|
+
from .file_config import configure_from_kubeconfig
|
|
23
|
+
from .incluster_config import configure_from_pod_env
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("kubex.client")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
async def _try_read_configuration() -> ClientConfiguration:
|
|
29
|
+
try:
|
|
30
|
+
return await configure_from_kubeconfig()
|
|
31
|
+
except Exception as e:
|
|
32
|
+
logger.error("Failed to read configuration from kubeconfig", exc_info=e)
|
|
33
|
+
return await configure_from_pod_env()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Client:
|
|
37
|
+
def __init__(self, configuration: ClientConfiguration) -> None:
|
|
38
|
+
self._configuration = configuration
|
|
39
|
+
self._inner_client = self._create_inner_client()
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
async def create(cls, configuration: ClientConfiguration | None = None) -> Self:
|
|
43
|
+
if configuration is None:
|
|
44
|
+
configuration = await _try_read_configuration()
|
|
45
|
+
self = cls(configuration)
|
|
46
|
+
return self
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def configuration(self) -> ClientConfiguration:
|
|
50
|
+
return self._configuration
|
|
51
|
+
|
|
52
|
+
def _get_headers(self) -> dict[str, str]:
|
|
53
|
+
if self.configuration.token is None:
|
|
54
|
+
return {}
|
|
55
|
+
return {"Authorization": f"Bearer {self.configuration.token}"}
|
|
56
|
+
|
|
57
|
+
def _create_inner_client(self) -> httpx.AsyncClient:
|
|
58
|
+
return httpx.AsyncClient(
|
|
59
|
+
base_url=str(self.configuration.base_url),
|
|
60
|
+
verify=self.configuration.verify,
|
|
61
|
+
cert=self.configuration.client_cert,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
async def __aenter__(self) -> Self:
|
|
65
|
+
await self._inner_client.__aenter__()
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
async def __aexit__(
|
|
69
|
+
self,
|
|
70
|
+
exc_type: type[BaseException] | None = None,
|
|
71
|
+
exc_value: BaseException | None = None,
|
|
72
|
+
traceback: TracebackType | None = None,
|
|
73
|
+
) -> None:
|
|
74
|
+
await self._inner_client.__aexit__(exc_type, exc_value, traceback)
|
|
75
|
+
|
|
76
|
+
def handle_request_error(self, response: Response) -> NoReturn:
|
|
77
|
+
status_code = response.status_code
|
|
78
|
+
content: Status | str
|
|
79
|
+
if CONTENT_TYPE_HEADER in response.headers:
|
|
80
|
+
content_type = response.headers[CONTENT_TYPE_HEADER]
|
|
81
|
+
if content_type == APPLICATION_JSON_MIME_TYPE:
|
|
82
|
+
try:
|
|
83
|
+
content = Status.model_validate_json(response.content)
|
|
84
|
+
except ValidationError:
|
|
85
|
+
content = response.text
|
|
86
|
+
else:
|
|
87
|
+
content = response.text
|
|
88
|
+
match status_code:
|
|
89
|
+
case HTTPStatus.BAD_REQUEST:
|
|
90
|
+
raise exceptions.BadRequest(content=content)
|
|
91
|
+
case HTTPStatus.UNAUTHORIZED:
|
|
92
|
+
raise exceptions.Unauthorized(content=content)
|
|
93
|
+
case HTTPStatus.FORBIDDEN:
|
|
94
|
+
raise exceptions.Forbidden(content=content)
|
|
95
|
+
case HTTPStatus.NOT_FOUND:
|
|
96
|
+
raise exceptions.NotFound(content=content)
|
|
97
|
+
case HTTPStatus.METHOD_NOT_ALLOWED:
|
|
98
|
+
raise exceptions.MethodNotAllowed(content=content)
|
|
99
|
+
case HTTPStatus.CONFLICT:
|
|
100
|
+
raise exceptions.Conflict(content=content)
|
|
101
|
+
case HTTPStatus.GONE:
|
|
102
|
+
raise exceptions.Gone(content=content)
|
|
103
|
+
case HTTPStatus.UNPROCESSABLE_ENTITY:
|
|
104
|
+
raise exceptions.UnprocessableEntity(content=content)
|
|
105
|
+
case status:
|
|
106
|
+
raise exceptions.KubexApiError(
|
|
107
|
+
content=content, status=HTTPStatus(status)
|
|
108
|
+
)
|
|
109
|
+
raise exceptions.KubernetesError(content=content)
|
|
110
|
+
|
|
111
|
+
async def request(self, request: Request) -> Response:
|
|
112
|
+
headers = self._get_headers()
|
|
113
|
+
if request.headers:
|
|
114
|
+
headers.update(request.headers)
|
|
115
|
+
_response = await self._inner_client.request(
|
|
116
|
+
method=request.method,
|
|
117
|
+
url=request.url,
|
|
118
|
+
params=request.query_params,
|
|
119
|
+
content=request.body,
|
|
120
|
+
headers=headers,
|
|
121
|
+
)
|
|
122
|
+
http_status = HTTPStatus(_response.status_code)
|
|
123
|
+
response = Response(
|
|
124
|
+
status_code=http_status,
|
|
125
|
+
headers=_response.headers,
|
|
126
|
+
content=_response.content,
|
|
127
|
+
)
|
|
128
|
+
if self.configuration.log_api_warnings and (
|
|
129
|
+
api_warnings := _response.headers.get("Warning")
|
|
130
|
+
):
|
|
131
|
+
for warning in api_warnings.split(","):
|
|
132
|
+
warnings.warn(f"API Warning: {warning}")
|
|
133
|
+
if http_status.is_client_error or http_status.is_server_error:
|
|
134
|
+
self.handle_request_error(response)
|
|
135
|
+
return response
|
|
136
|
+
|
|
137
|
+
async def stream_lines(self, request: Request) -> AsyncGenerator[str, None]:
|
|
138
|
+
async with self._inner_client.stream(
|
|
139
|
+
method=request.method,
|
|
140
|
+
url=request.url,
|
|
141
|
+
params=request.query_params,
|
|
142
|
+
content=request.body,
|
|
143
|
+
headers=request.headers,
|
|
144
|
+
) as _response:
|
|
145
|
+
http_status = HTTPStatus(_response.status_code)
|
|
146
|
+
if http_status.is_client_error or http_status.is_server_error:
|
|
147
|
+
response = Response(
|
|
148
|
+
status_code=_response.status_code,
|
|
149
|
+
headers=_response.headers,
|
|
150
|
+
content=await _response.aread(),
|
|
151
|
+
)
|
|
152
|
+
self.handle_request_error(response)
|
|
153
|
+
async for line in _response.aiter_lines():
|
|
154
|
+
yield line
|
|
155
|
+
|
|
156
|
+
async def close(self) -> None:
|
|
157
|
+
await self._inner_client.aclose()
|