ops.interface-kube-control 0.2.0__tar.gz → 0.2.3__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.
- ops_interface_kube_control-0.2.3/MANIFEST.in +1 -0
- ops_interface_kube_control-0.2.3/PKG-INFO +50 -0
- ops_interface_kube_control-0.2.3/README.md +29 -0
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops/interface_kube_control/model.py +42 -27
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops/interface_kube_control/provides.py +53 -33
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops/interface_kube_control/requires.py +46 -31
- ops_interface_kube_control-0.2.3/ops.interface_kube_control.egg-info/PKG-INFO +50 -0
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops.interface_kube_control.egg-info/SOURCES.txt +3 -1
- ops_interface_kube_control-0.2.3/ops.interface_kube_control.egg-info/requires.txt +2 -0
- ops_interface_kube_control-0.2.3/ops.interface_kube_control.egg-info/top_level.txt +3 -0
- ops_interface_kube_control-0.2.3/pyproject.toml +80 -0
- ops_interface_kube_control-0.2.3/tox.ini +56 -0
- ops_interface_kube_control-0.2.3/uv.lock +1413 -0
- ops_interface_kube_control-0.2.0/PKG-INFO +0 -27
- ops_interface_kube_control-0.2.0/README.md +0 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/PKG-INFO +0 -27
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/requires.txt +0 -3
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/top_level.txt +0 -1
- ops_interface_kube_control-0.2.0/setup.py +0 -33
- ops_interface_kube_control-0.2.0/tox.ini +0 -35
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops/interface_kube_control/__init__.py +0 -0
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops.interface_kube_control.egg-info/dependency_links.txt +0 -0
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/ops.interface_kube_control.egg-info/zip-safe +0 -0
- {ops_interface_kube_control-0.2.0 → ops_interface_kube_control-0.2.3}/setup.cfg +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
prune tests
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ops.interface_kube_control
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Kube-Control Interface for Charmed Operators
|
|
5
|
+
Author-email: Adam Dyess <adam.dyess@canonical.com>, Mateo Florido <mateo.florido@canonical.com>
|
|
6
|
+
License: Apache
|
|
7
|
+
Project-URL: Repository, https://github.com/charmed-kubernetes/interface-kube-control
|
|
8
|
+
Keywords: juju,charming,kubernetes,ops,framework,interface
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Requires-Python: >=3.8
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
Requires-Dist: ops
|
|
20
|
+
Requires-Dist: pydantic<3,>=2
|
|
21
|
+
|
|
22
|
+
# ops.interface_kube_control
|
|
23
|
+
|
|
24
|
+
## Rationale for this library
|
|
25
|
+
Many project need credentials in a kubernetes cluster to apply their workloads
|
|
26
|
+
using credentials from the kubernetes cluster. Outside the cluster, these charms
|
|
27
|
+
need access to the cluster's API and credentials within that API.
|
|
28
|
+
|
|
29
|
+
This library supports the `kube-control` relation to relate to a kubernetes
|
|
30
|
+
control-plane application, to provide access to that endpoint.
|
|
31
|
+
|
|
32
|
+
## Contributing
|
|
33
|
+
This library provides an interface for `ops` charms to use to connect to this interface.
|
|
34
|
+
|
|
35
|
+
* Make adjustments
|
|
36
|
+
* test the changes by running tox
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
tox
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
* Raise your PR and contact maintainers
|
|
43
|
+
* Once merged, tag with an `ops-X.X.X` to publish a new pypi package
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
git switch main
|
|
47
|
+
git pull
|
|
48
|
+
git tag -a ops-X.X.X
|
|
49
|
+
git push <origin> tag ops-X.X.X
|
|
50
|
+
```
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# ops.interface_kube_control
|
|
2
|
+
|
|
3
|
+
## Rationale for this library
|
|
4
|
+
Many project need credentials in a kubernetes cluster to apply their workloads
|
|
5
|
+
using credentials from the kubernetes cluster. Outside the cluster, these charms
|
|
6
|
+
need access to the cluster's API and credentials within that API.
|
|
7
|
+
|
|
8
|
+
This library supports the `kube-control` relation to relate to a kubernetes
|
|
9
|
+
control-plane application, to provide access to that endpoint.
|
|
10
|
+
|
|
11
|
+
## Contributing
|
|
12
|
+
This library provides an interface for `ops` charms to use to connect to this interface.
|
|
13
|
+
|
|
14
|
+
* Make adjustments
|
|
15
|
+
* test the changes by running tox
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
tox
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
* Raise your PR and contact maintainers
|
|
22
|
+
* Once merged, tag with an `ops-X.X.X` to publish a new pypi package
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
git switch main
|
|
26
|
+
git pull
|
|
27
|
+
git tag -a ops-X.X.X
|
|
28
|
+
git push <origin> tag ops-X.X.X
|
|
29
|
+
```
|
|
@@ -1,30 +1,45 @@
|
|
|
1
|
-
from pydantic import
|
|
1
|
+
from pydantic import (
|
|
2
|
+
ConfigDict,
|
|
3
|
+
Field,
|
|
4
|
+
AnyHttpUrl,
|
|
5
|
+
BaseModel,
|
|
6
|
+
GetCoreSchemaHandler,
|
|
7
|
+
Json,
|
|
8
|
+
)
|
|
9
|
+
|
|
2
10
|
import json
|
|
3
|
-
import ops
|
|
4
|
-
from typing import List, Dict, Optional
|
|
5
11
|
import re
|
|
12
|
+
from typing import Any, ClassVar, List, Dict, Optional, Pattern
|
|
13
|
+
|
|
14
|
+
import ops
|
|
15
|
+
|
|
16
|
+
from pydantic_core import core_schema
|
|
6
17
|
|
|
7
18
|
|
|
8
19
|
class _ValidatedStr:
|
|
9
|
-
|
|
20
|
+
REGEX: ClassVar[Pattern[str]]
|
|
21
|
+
|
|
22
|
+
def __init__(self, value: str, *groups: str) -> None:
|
|
10
23
|
self._str = value
|
|
11
24
|
self.groups = groups
|
|
12
25
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
yield cls.validate
|
|
26
|
+
def __repr__(self) -> str:
|
|
27
|
+
return f"{type(self).__name__}({self._str!r}, groups={self.groups})"
|
|
16
28
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if not isinstance(v, str):
|
|
20
|
-
raise TypeError("string required")
|
|
21
|
-
m = cls.REGEX.match(v)
|
|
22
|
-
if not m:
|
|
23
|
-
raise ValueError("invalid format")
|
|
24
|
-
return cls(v, *m.groups())
|
|
29
|
+
def __str__(self) -> str:
|
|
30
|
+
return self._str
|
|
25
31
|
|
|
26
|
-
|
|
27
|
-
|
|
32
|
+
@classmethod
|
|
33
|
+
def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> Any:
|
|
34
|
+
def validate(value: str) -> "_ValidatedStr":
|
|
35
|
+
if match := cls.REGEX.match(value):
|
|
36
|
+
return cls(value, *match.groups())
|
|
37
|
+
raise ValueError(f"Invalid {cls.__name__} format")
|
|
38
|
+
|
|
39
|
+
return core_schema.no_info_plain_validator_function(
|
|
40
|
+
validate,
|
|
41
|
+
serialization=core_schema.to_string_ser_schema(),
|
|
42
|
+
)
|
|
28
43
|
|
|
29
44
|
@property
|
|
30
45
|
def key(self) -> str:
|
|
@@ -59,13 +74,13 @@ class AuthRequest(BaseModel):
|
|
|
59
74
|
group str: alias for auth_group
|
|
60
75
|
"""
|
|
61
76
|
|
|
62
|
-
kubelet_user: Optional[str]
|
|
63
|
-
auth_group: Optional[str]
|
|
77
|
+
kubelet_user: Optional[str] = None
|
|
78
|
+
auth_group: Optional[str] = None
|
|
64
79
|
schema_vers: Json[List[int]] = Field(default_factory=list)
|
|
65
|
-
unit: Optional[str]
|
|
80
|
+
unit: Optional[str] = None
|
|
66
81
|
|
|
67
|
-
def
|
|
68
|
-
d = super().
|
|
82
|
+
def model_dump(self, **kwargs):
|
|
83
|
+
d = super().model_dump(**kwargs)
|
|
69
84
|
if schema_vers := d.pop("schema_vers", None):
|
|
70
85
|
d["schema_vers"] = json.dumps(schema_vers)
|
|
71
86
|
return d
|
|
@@ -87,6 +102,8 @@ class AuthRequest(BaseModel):
|
|
|
87
102
|
|
|
88
103
|
|
|
89
104
|
class Creds(BaseModel):
|
|
105
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
106
|
+
|
|
90
107
|
client_token: str
|
|
91
108
|
kubelet_token: str
|
|
92
109
|
proxy_token: str
|
|
@@ -115,9 +132,9 @@ class Creds(BaseModel):
|
|
|
115
132
|
|
|
116
133
|
class Data(BaseModel):
|
|
117
134
|
api_endpoints: Json[List[AnyHttpUrl]] = Field(alias="api-endpoints")
|
|
118
|
-
ca_certificate_secret_id: Optional[str] = Field(alias="ca-certificate-secret-id")
|
|
135
|
+
ca_certificate_secret_id: Optional[str] = Field(None, alias="ca-certificate-secret-id")
|
|
119
136
|
cluster_tag: str = Field(alias="cluster-tag")
|
|
120
|
-
cohort_keys: Optional[Json[Dict[str, str]]] = Field(alias="cohort-keys")
|
|
137
|
+
cohort_keys: Optional[Json[Dict[str, str]]] = Field(None, alias="cohort-keys")
|
|
121
138
|
creds: Json[Dict[str, Creds]] = Field(alias="creds")
|
|
122
139
|
default_cni: Json[str] = Field(alias="default-cni")
|
|
123
140
|
domain: str = Field(alias="domain")
|
|
@@ -133,9 +150,7 @@ class Data(BaseModel):
|
|
|
133
150
|
if not self.ca_certificate_secret_id:
|
|
134
151
|
return None
|
|
135
152
|
try:
|
|
136
|
-
secret = model.get_secret(
|
|
137
|
-
id=self.ca_certificate_secret_id, label="ca-certificate"
|
|
138
|
-
)
|
|
153
|
+
secret = model.get_secret(id=self.ca_certificate_secret_id, label="ca-certificate")
|
|
139
154
|
return secret.get_content(refresh=True)["ca-certificate"].encode()
|
|
140
155
|
except ops.SecretNotFoundError:
|
|
141
156
|
return None
|
|
@@ -1,19 +1,26 @@
|
|
|
1
|
+
import ipaddress
|
|
1
2
|
import json
|
|
2
3
|
import logging
|
|
4
|
+
from typing import Generator, List, Tuple
|
|
5
|
+
|
|
6
|
+
import ops
|
|
7
|
+
from pydantic import TypeAdapter
|
|
3
8
|
|
|
4
9
|
from .model import AuthRequest, Creds, Label, Taint
|
|
5
|
-
from ops import CharmBase, Relation, SecretNotFoundError, Unit
|
|
6
|
-
from typing import Generator, List, Tuple
|
|
7
10
|
|
|
8
11
|
log = logging.getLogger("KubeControlProvides")
|
|
9
12
|
|
|
10
13
|
|
|
11
|
-
class KubeControlProvides:
|
|
14
|
+
class KubeControlProvides(ops.Object):
|
|
12
15
|
"""Implements the Provides side of the kube-control interface."""
|
|
13
16
|
|
|
14
|
-
def __init__(self, charm: CharmBase, endpoint: str = "kube-control", schemas="0,1"):
|
|
17
|
+
def __init__(self, charm: ops.CharmBase, endpoint: str = "kube-control", schemas="0,1"):
|
|
18
|
+
super().__init__(charm, f"{endpoint}-provider")
|
|
15
19
|
self.charm = charm
|
|
16
20
|
self.endpoint = endpoint
|
|
21
|
+
self.label_adapter = TypeAdapter(Label)
|
|
22
|
+
self.taint_adapter = TypeAdapter(Taint)
|
|
23
|
+
self.framework.observe(charm.on.secret_remove, self._on_secret_remove)
|
|
17
24
|
|
|
18
25
|
@property
|
|
19
26
|
def auth_requests(self) -> List[AuthRequest]:
|
|
@@ -31,8 +38,7 @@ class KubeControlProvides:
|
|
|
31
38
|
|
|
32
39
|
def clear_creds(self) -> None:
|
|
33
40
|
"""Clear creds from the relation. This is used by non-leader units to
|
|
34
|
-
stop advertising creds so that the leader can assume full control of
|
|
35
|
-
them.
|
|
41
|
+
stop advertising creds so that the leader can assume full control of them.
|
|
36
42
|
"""
|
|
37
43
|
for relation in self.relations:
|
|
38
44
|
relation.data[self.unit]["creds"] = ""
|
|
@@ -40,18 +46,18 @@ class KubeControlProvides:
|
|
|
40
46
|
@property
|
|
41
47
|
def ingress_addresses(self) -> List[str]:
|
|
42
48
|
"""Ingress addresses for this endpoint."""
|
|
49
|
+
binding = self.charm.model.get_binding(self.endpoint)
|
|
43
50
|
return [
|
|
44
51
|
# RFC 5280 section 4.2.1.6: "For IP version 6 ... the octet string
|
|
45
52
|
# MUST contain exactly sixteen octets." We'll use .exploded to be
|
|
46
53
|
# safe.
|
|
47
|
-
|
|
48
|
-
for addr in
|
|
49
|
-
|
|
50
|
-
).network.ingress_addresses
|
|
54
|
+
ip.exploded
|
|
55
|
+
for addr in (binding and binding.network.ingress_addresses or [])
|
|
56
|
+
if (ip := ipaddress.ip_address(addr))
|
|
51
57
|
]
|
|
52
58
|
|
|
53
59
|
@property
|
|
54
|
-
def relations(self) -> List[Relation]:
|
|
60
|
+
def relations(self) -> List[ops.Relation]:
|
|
55
61
|
"""List of relations on this endpoint."""
|
|
56
62
|
return self.charm.model.relations[self.endpoint]
|
|
57
63
|
|
|
@@ -65,10 +71,10 @@ class KubeControlProvides:
|
|
|
65
71
|
"""Send the CA certificate to the remote units.
|
|
66
72
|
|
|
67
73
|
Args:
|
|
68
|
-
ca_certificate str: The CA certificate in PEM format.
|
|
74
|
+
ca_certificate (str): The CA certificate in PEM format.
|
|
69
75
|
"""
|
|
70
76
|
content = {"ca-certificate": ca_certificate}
|
|
71
|
-
secret = self.
|
|
77
|
+
secret = self._refresh_secret_content(
|
|
72
78
|
"ca-certificate", content, "Kubernetes API endpoint CA certificate"
|
|
73
79
|
)
|
|
74
80
|
for relation in self.relations:
|
|
@@ -128,31 +134,43 @@ class KubeControlProvides:
|
|
|
128
134
|
|
|
129
135
|
def set_labels(self, labels) -> None:
|
|
130
136
|
"""Send the Juju config labels of the control-plane."""
|
|
131
|
-
|
|
132
|
-
dedup = sorted(set(
|
|
137
|
+
valid_labels = [str(self.label_adapter.validate_python(label_str)) for label_str in labels]
|
|
138
|
+
dedup = sorted(set(valid_labels))
|
|
133
139
|
value = json.dumps(dedup)
|
|
134
140
|
for relation in self.relations:
|
|
135
141
|
relation.data[self.unit]["labels"] = value
|
|
136
142
|
|
|
137
143
|
def set_taints(self, taints) -> None:
|
|
138
144
|
"""Send the Juju config taints of the control-plane."""
|
|
139
|
-
|
|
140
|
-
dedup = sorted(set(
|
|
145
|
+
valid_taints = [str(self.taint_adapter.validate_python(taint_str)) for taint_str in taints]
|
|
146
|
+
dedup = sorted(set(valid_taints))
|
|
141
147
|
value = json.dumps(dedup)
|
|
142
148
|
for relation in self.relations:
|
|
143
149
|
relation.data[self.unit]["taints"] = value
|
|
144
150
|
|
|
145
|
-
def
|
|
151
|
+
def _on_secret_remove(self, event: ops.SecretRemoveEvent) -> None:
|
|
152
|
+
"""Remove revisions for secrets matching this object's endpoint.
|
|
153
|
+
Args:
|
|
154
|
+
event (ops.SecretRemoveEvent): The secret removal event.
|
|
155
|
+
"""
|
|
156
|
+
try:
|
|
157
|
+
content = event.secret.get_content()
|
|
158
|
+
except ops.SecretNotFoundError:
|
|
159
|
+
return
|
|
160
|
+
if content.get("endpoint") == self.endpoint:
|
|
161
|
+
log.info(f"Removing secret {event.secret.id}")
|
|
162
|
+
event.secret.remove_revision(event.revision)
|
|
163
|
+
|
|
164
|
+
def _refresh_secret_content(self, label, content, description=None):
|
|
146
165
|
"""Refresh the content of a secret."""
|
|
166
|
+
content = {**content, "endpoint": self.endpoint}
|
|
147
167
|
try:
|
|
148
168
|
secret = self.charm.model.get_secret(label=label)
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
secret
|
|
154
|
-
content, label=label, description=description
|
|
155
|
-
)
|
|
169
|
+
except ops.SecretNotFoundError:
|
|
170
|
+
secret = self.charm.app.add_secret(content, label=label, description=description)
|
|
171
|
+
if secret.get_content(refresh=True) != content:
|
|
172
|
+
log.info("Refresh content %s", secret.id)
|
|
173
|
+
secret.set_content(content)
|
|
156
174
|
return secret
|
|
157
175
|
|
|
158
176
|
def closed_auth_creds(self) -> Generator[Tuple[str, Creds], None, None]:
|
|
@@ -171,12 +189,12 @@ class KubeControlProvides:
|
|
|
171
189
|
"""
|
|
172
190
|
creds, unit_names = {}, []
|
|
173
191
|
|
|
174
|
-
# Collect creds from all relations
|
|
192
|
+
# Collect creds from all relations.
|
|
175
193
|
for relation in self.relations:
|
|
176
194
|
creds.update(json.loads(relation.data[self.unit].get("creds", "{}")))
|
|
177
195
|
unit_names += [u.name for u in relation.units]
|
|
178
196
|
|
|
179
|
-
# Revoke creds for units that have been removed
|
|
197
|
+
# Revoke creds for units that have been removed.
|
|
180
198
|
for user, cred in dict(**creds).items():
|
|
181
199
|
data = Creds(**cred)
|
|
182
200
|
if data.scope not in unit_names:
|
|
@@ -187,7 +205,7 @@ class KubeControlProvides:
|
|
|
187
205
|
secret = self.charm.model.get_secret(id=data.secret_id)
|
|
188
206
|
secret.remove_all_revisions()
|
|
189
207
|
|
|
190
|
-
# Publish the updated creds without the revoked units
|
|
208
|
+
# Publish the updated creds without the revoked units.
|
|
191
209
|
value = json.dumps(creds)
|
|
192
210
|
for relation in self.relations:
|
|
193
211
|
relation.data[self.unit]["creds"] = value
|
|
@@ -197,6 +215,8 @@ class KubeControlProvides:
|
|
|
197
215
|
) -> None:
|
|
198
216
|
"""Send authorization tokens to the requesting unit."""
|
|
199
217
|
creds, request_relation = {}, None
|
|
218
|
+
if not request.unit:
|
|
219
|
+
raise ValueError("Request unit is required")
|
|
200
220
|
request_unit = self.charm.model.get_unit(request.unit)
|
|
201
221
|
|
|
202
222
|
for relation in self.relations:
|
|
@@ -212,7 +232,7 @@ class KubeControlProvides:
|
|
|
212
232
|
)
|
|
213
233
|
|
|
214
234
|
if 1 in request.schema_vers and request_relation:
|
|
215
|
-
# Requesting unit can use schema 1, use
|
|
235
|
+
# Requesting unit can use schema 1, use Juju secrets.
|
|
216
236
|
content = {
|
|
217
237
|
"client-token": client_token,
|
|
218
238
|
"kubelet-token": kubelet_token,
|
|
@@ -220,7 +240,7 @@ class KubeControlProvides:
|
|
|
220
240
|
}
|
|
221
241
|
label = f"{request.user}-creds"
|
|
222
242
|
description = f"Credentials for {request.user}"
|
|
223
|
-
secret = self.
|
|
243
|
+
secret = self._refresh_secret_content(label, content, description)
|
|
224
244
|
if secret.id:
|
|
225
245
|
log.info(f"Granting secret {secret.id} to {request_relation.name}")
|
|
226
246
|
secret.grant(request_relation, unit=request_unit)
|
|
@@ -232,15 +252,15 @@ class KubeControlProvides:
|
|
|
232
252
|
tokens.kubelet_token = ""
|
|
233
253
|
tokens.proxy_token = ""
|
|
234
254
|
tokens.secret_id = secret.id
|
|
235
|
-
creds[request.user] = tokens.
|
|
255
|
+
creds[request.user] = tokens.model_dump(by_alias=True, exclude_none=True)
|
|
236
256
|
else:
|
|
237
|
-
creds[request.user] = tokens.
|
|
257
|
+
creds[request.user] = tokens.model_dump(by_alias=True, exclude_none=True)
|
|
238
258
|
|
|
239
259
|
value = json.dumps(creds)
|
|
240
260
|
for relation in self.relations:
|
|
241
261
|
relation.data[self.unit]["creds"] = value
|
|
242
262
|
|
|
243
263
|
@property
|
|
244
|
-
def unit(self) -> Unit:
|
|
264
|
+
def unit(self) -> ops.Unit:
|
|
245
265
|
"""Local unit."""
|
|
246
266
|
return self.charm.unit
|
|
@@ -8,55 +8,73 @@ style rather than the reactive style.
|
|
|
8
8
|
|
|
9
9
|
import base64
|
|
10
10
|
import logging
|
|
11
|
+
from functools import cached_property
|
|
11
12
|
from os import PathLike
|
|
12
13
|
from pathlib import Path
|
|
13
|
-
from typing import Dict,
|
|
14
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
14
15
|
|
|
15
16
|
import yaml
|
|
16
|
-
from backports.cached_property import cached_property
|
|
17
|
-
from .model import AuthRequest, Creds, Data, Taint, Label
|
|
18
17
|
from pydantic import ValidationError
|
|
19
18
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
from
|
|
19
|
+
import ops
|
|
20
|
+
|
|
21
|
+
from .model import AuthRequest, Creds, Data, Label, Taint
|
|
23
22
|
|
|
24
23
|
log = logging.getLogger("KubeControlRequirer")
|
|
25
24
|
JUJU_CLUSTER = "juju-cluster"
|
|
26
25
|
JUJU_CONTEXT = "juju-context"
|
|
27
26
|
|
|
28
27
|
|
|
29
|
-
class
|
|
28
|
+
class RelationNotReady(Exception):
|
|
29
|
+
"""Exception raised when the relation is not ready."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class KubeControlRequirer(ops.Object):
|
|
30
33
|
"""
|
|
31
34
|
Implements the requirer side of the kube-control interface.
|
|
32
35
|
"""
|
|
33
36
|
|
|
34
|
-
def __init__(self, charm: CharmBase, endpoint: str = "kube-control", schemas="0"):
|
|
37
|
+
def __init__(self, charm: ops.CharmBase, endpoint: str = "kube-control", schemas="0"):
|
|
35
38
|
super().__init__(charm, f"relation-{endpoint}")
|
|
39
|
+
self.charm = charm
|
|
36
40
|
self.endpoint = endpoint
|
|
37
41
|
# comma-separated set of schemas to advertise support
|
|
38
42
|
# schema 0 -- same as unschema'd
|
|
39
43
|
# schema 1 -- signals support for credentials in juju secrets
|
|
40
44
|
self.schema_ver = [int(v) for v in schemas.split(",")]
|
|
45
|
+
self.framework.observe(charm.on.secret_changed, self._on_secret_change)
|
|
46
|
+
|
|
47
|
+
def _on_secret_change(self, event):
|
|
48
|
+
"""Handle secret change events by re-emitting as relation changed."""
|
|
49
|
+
try:
|
|
50
|
+
content = event.secret.get_content(refresh=True)
|
|
51
|
+
except ops.SecretNotFoundError:
|
|
52
|
+
return
|
|
53
|
+
relation = self.model.get_relation(self.endpoint)
|
|
54
|
+
if relation and content.get("endpoint") == self.endpoint:
|
|
55
|
+
log.info(
|
|
56
|
+
f"Secret change event {event.secret.id} emits [{self.endpoint}].relation_changed"
|
|
57
|
+
)
|
|
58
|
+
self.charm.on[self.endpoint].relation_changed.emit(relation, relation.app)
|
|
41
59
|
|
|
42
60
|
@cached_property
|
|
43
|
-
def relation(self) -> Optional[Relation]:
|
|
61
|
+
def relation(self) -> Optional[ops.Relation]:
|
|
44
62
|
"""The lone relation endpoint or None."""
|
|
45
63
|
return self.model.get_relation(self.endpoint)
|
|
46
64
|
|
|
47
65
|
@cached_property
|
|
48
|
-
def _data(self) ->
|
|
66
|
+
def _data(self) -> Data:
|
|
49
67
|
if self.relation and self.relation.units:
|
|
50
|
-
rx = {}
|
|
68
|
+
rx: Dict[str, str] = {}
|
|
51
69
|
for unit in self.relation.units:
|
|
52
70
|
rx.update(self.relation.data[unit])
|
|
53
|
-
return Data(
|
|
54
|
-
|
|
71
|
+
return Data.model_validate(rx)
|
|
72
|
+
raise RelationNotReady("No unit data available")
|
|
55
73
|
|
|
56
74
|
def evaluate_relation(self, event) -> Optional[str]:
|
|
57
75
|
"""Determine if relation is ready."""
|
|
58
76
|
no_relation = not self.relation or (
|
|
59
|
-
isinstance(event, RelationBrokenEvent) and event.relation is self.relation
|
|
77
|
+
isinstance(event, ops.RelationBrokenEvent) and event.relation is self.relation
|
|
60
78
|
)
|
|
61
79
|
if not self.is_ready:
|
|
62
80
|
if no_relation:
|
|
@@ -72,14 +90,12 @@ class KubeControlRequirer(Object):
|
|
|
72
90
|
except ValidationError as ve:
|
|
73
91
|
log.error(f"{self.endpoint} relation data not yet valid. ({ve}")
|
|
74
92
|
return False
|
|
75
|
-
|
|
93
|
+
except RelationNotReady:
|
|
76
94
|
log.error(f"{self.endpoint} relation data not yet available.")
|
|
77
95
|
return False
|
|
78
96
|
return True
|
|
79
97
|
|
|
80
|
-
def create_kubeconfig(
|
|
81
|
-
self, ca: PathLike, kubeconfig: PathLike, user: str, k8s_user: str
|
|
82
|
-
):
|
|
98
|
+
def create_kubeconfig(self, ca: PathLike, kubeconfig: PathLike, user: str, k8s_user: str):
|
|
83
99
|
"""Write kubeconfig based on available creds."""
|
|
84
100
|
creds = self.get_auth_credentials(k8s_user)
|
|
85
101
|
endpoints = self.get_api_endpoints()
|
|
@@ -153,7 +169,7 @@ class KubeControlRequirer(Object):
|
|
|
153
169
|
}
|
|
154
170
|
return None
|
|
155
171
|
|
|
156
|
-
def get_dns(self) -> Mapping[str,
|
|
172
|
+
def get_dns(self) -> Mapping[str, Any]:
|
|
157
173
|
"""
|
|
158
174
|
Return DNS info provided by the control-plane.
|
|
159
175
|
"""
|
|
@@ -170,10 +186,7 @@ class KubeControlRequirer(Object):
|
|
|
170
186
|
"""
|
|
171
187
|
keys = ["port", "domain", "sdn-ip", "enable-kube-dns"]
|
|
172
188
|
dns_info = self.get_dns()
|
|
173
|
-
return (
|
|
174
|
-
set(dns_info.keys()) == set(keys)
|
|
175
|
-
and dns_info["enable-kube-dns"] is not None
|
|
176
|
-
)
|
|
189
|
+
return set(dns_info.keys()) == set(keys) and dns_info["enable-kube-dns"] is not None
|
|
177
190
|
|
|
178
191
|
def set_auth_request(self, user, group="system:nodes") -> None:
|
|
179
192
|
"""Notify control-plane that we are requesting auth.
|
|
@@ -187,19 +200,21 @@ class KubeControlRequirer(Object):
|
|
|
187
200
|
cluster via changing to
|
|
188
201
|
system:masters. # wokeignore:rule=master
|
|
189
202
|
"""
|
|
190
|
-
if self.relation:
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
203
|
+
if not self.relation:
|
|
204
|
+
return
|
|
205
|
+
|
|
206
|
+
req = AuthRequest(kubelet_user=user, auth_group=group)
|
|
207
|
+
req.schema_vers = self.schema_ver
|
|
208
|
+
log.info(f"Auth Req for {user} with group {group} on schema {self.schema_ver}")
|
|
209
|
+
self.relation.data[self.model.unit].update(
|
|
210
|
+
req.model_dump(exclude_none=True, by_alias=True)
|
|
211
|
+
)
|
|
197
212
|
|
|
198
213
|
def set_gpu(self, enabled=True):
|
|
199
214
|
"""
|
|
200
215
|
Tell the control-plane that we're gpu-enabled (or not).
|
|
201
216
|
"""
|
|
202
|
-
log("Setting gpu
|
|
217
|
+
log.info("Setting gpu=%s on kube-control relation", enabled)
|
|
203
218
|
for relation in self.model.relations:
|
|
204
219
|
relation.data[self.model.unit].update(dict(gpu=enabled))
|
|
205
220
|
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ops.interface_kube_control
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Kube-Control Interface for Charmed Operators
|
|
5
|
+
Author-email: Adam Dyess <adam.dyess@canonical.com>, Mateo Florido <mateo.florido@canonical.com>
|
|
6
|
+
License: Apache
|
|
7
|
+
Project-URL: Repository, https://github.com/charmed-kubernetes/interface-kube-control
|
|
8
|
+
Keywords: juju,charming,kubernetes,ops,framework,interface
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Requires-Python: >=3.8
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
Requires-Dist: ops
|
|
20
|
+
Requires-Dist: pydantic<3,>=2
|
|
21
|
+
|
|
22
|
+
# ops.interface_kube_control
|
|
23
|
+
|
|
24
|
+
## Rationale for this library
|
|
25
|
+
Many project need credentials in a kubernetes cluster to apply their workloads
|
|
26
|
+
using credentials from the kubernetes cluster. Outside the cluster, these charms
|
|
27
|
+
need access to the cluster's API and credentials within that API.
|
|
28
|
+
|
|
29
|
+
This library supports the `kube-control` relation to relate to a kubernetes
|
|
30
|
+
control-plane application, to provide access to that endpoint.
|
|
31
|
+
|
|
32
|
+
## Contributing
|
|
33
|
+
This library provides an interface for `ops` charms to use to connect to this interface.
|
|
34
|
+
|
|
35
|
+
* Make adjustments
|
|
36
|
+
* test the changes by running tox
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
tox
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
* Raise your PR and contact maintainers
|
|
43
|
+
* Once merged, tag with an `ops-X.X.X` to publish a new pypi package
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
git switch main
|
|
47
|
+
git pull
|
|
48
|
+
git tag -a ops-X.X.X
|
|
49
|
+
git push <origin> tag ops-X.X.X
|
|
50
|
+
```
|