ops.interface-kube-control 0.2.0__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.0/PKG-INFO +27 -0
- ops_interface_kube_control-0.2.0/README.md +0 -0
- ops_interface_kube_control-0.2.0/ops/interface_kube_control/__init__.py +4 -0
- ops_interface_kube_control-0.2.0/ops/interface_kube_control/model.py +141 -0
- ops_interface_kube_control-0.2.0/ops/interface_kube_control/provides.py +246 -0
- ops_interface_kube_control-0.2.0/ops/interface_kube_control/requires.py +250 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/PKG-INFO +27 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/SOURCES.txt +13 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/dependency_links.txt +1 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/requires.txt +3 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/top_level.txt +1 -0
- ops_interface_kube_control-0.2.0/ops.interface_kube_control.egg-info/zip-safe +1 -0
- ops_interface_kube_control-0.2.0/setup.cfg +4 -0
- ops_interface_kube_control-0.2.0/setup.py +33 -0
- ops_interface_kube_control-0.2.0/tox.ini +35 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: ops.interface_kube_control
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Kube-Control Interface for Charmed Operators
|
|
5
|
+
Home-page: https://github.com/juju-solutions/interface-kube-control/blob/HEAD/ops
|
|
6
|
+
Author: Adam Dyess
|
|
7
|
+
Author-email: adam.dyess@canonical.com
|
|
8
|
+
License: MIT license
|
|
9
|
+
Keywords: juju,charming,kubernetes,ops,framework,interface
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
Requires-Dist: backports.cached-property
|
|
17
|
+
Requires-Dist: pydantic<2
|
|
18
|
+
Requires-Dist: ops
|
|
19
|
+
Dynamic: author
|
|
20
|
+
Dynamic: author-email
|
|
21
|
+
Dynamic: classifier
|
|
22
|
+
Dynamic: description-content-type
|
|
23
|
+
Dynamic: home-page
|
|
24
|
+
Dynamic: keywords
|
|
25
|
+
Dynamic: license
|
|
26
|
+
Dynamic: requires-dist
|
|
27
|
+
Dynamic: summary
|
|
File without changes
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from pydantic import Field, AnyHttpUrl, BaseModel, Json
|
|
2
|
+
import json
|
|
3
|
+
import ops
|
|
4
|
+
from typing import List, Dict, Optional
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class _ValidatedStr:
|
|
9
|
+
def __init__(self, value, *groups) -> None:
|
|
10
|
+
self._str = value
|
|
11
|
+
self.groups = groups
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def __get_validators__(cls):
|
|
15
|
+
yield cls.validate
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def validate(cls, v):
|
|
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())
|
|
25
|
+
|
|
26
|
+
def __repr__(self) -> str:
|
|
27
|
+
return f"{type(self).__name__}({self._str},*{self.groups})"
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def key(self) -> str:
|
|
31
|
+
return self.groups[0]
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def value(self) -> Optional[str]:
|
|
35
|
+
return self.groups[1]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Label(_ValidatedStr):
|
|
39
|
+
REGEX = re.compile(r"^([\w\d\-\.\/]+)=([\w\d\-\.]*)$")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Taint(_ValidatedStr):
|
|
43
|
+
REGEX = re.compile(r"^([\w\d\-\.\/]+)(?:=([\w\d\-\.]*))?:([\w\d\-\.]+)$")
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def effect(self) -> str:
|
|
47
|
+
return self.groups[2]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AuthRequest(BaseModel):
|
|
51
|
+
"""Models the requests from the requirer side of the relation.
|
|
52
|
+
|
|
53
|
+
Attributes:
|
|
54
|
+
kubelet_user str: name of the user the token is granted for
|
|
55
|
+
auth_group str: kubernetes group associated with the token
|
|
56
|
+
schema_vers list[int]: schemas versions supported by the requester
|
|
57
|
+
unit str: unit name requesting tokens, (only on provider)
|
|
58
|
+
user str: alias for kubelet_user
|
|
59
|
+
group str: alias for auth_group
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
kubelet_user: Optional[str]
|
|
63
|
+
auth_group: Optional[str]
|
|
64
|
+
schema_vers: Json[List[int]] = Field(default_factory=list)
|
|
65
|
+
unit: Optional[str]
|
|
66
|
+
|
|
67
|
+
def dict(self, **kwds):
|
|
68
|
+
d = super().dict(**kwds)
|
|
69
|
+
if schema_vers := d.pop("schema_vers", None):
|
|
70
|
+
d["schema_vers"] = json.dumps(schema_vers)
|
|
71
|
+
return d
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def user(self) -> Optional[str]:
|
|
75
|
+
return self.kubelet_user
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def group(self) -> Optional[str]:
|
|
79
|
+
return self.auth_group
|
|
80
|
+
|
|
81
|
+
def __lt__(self, other):
|
|
82
|
+
return (self.unit, self.kubelet_user, self.auth_group) < (
|
|
83
|
+
other.unit,
|
|
84
|
+
other.kubelet_user,
|
|
85
|
+
other.auth_group,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Creds(BaseModel):
|
|
90
|
+
client_token: str
|
|
91
|
+
kubelet_token: str
|
|
92
|
+
proxy_token: str
|
|
93
|
+
scope: str
|
|
94
|
+
secret_id: Optional[str] = Field(alias="secret-id", default=None)
|
|
95
|
+
|
|
96
|
+
def _get_secret_content(self, model: ops.Model, user: str) -> Dict[str, str]:
|
|
97
|
+
secret = model.get_secret(id=self.secret_id, label=f"{user}-creds")
|
|
98
|
+
return secret.get_content(refresh=True)
|
|
99
|
+
|
|
100
|
+
def load_client_token(self, model: ops.Model, user: str) -> str:
|
|
101
|
+
if self.secret_id:
|
|
102
|
+
return self._get_secret_content(model, user)["client-token"]
|
|
103
|
+
return self.client_token
|
|
104
|
+
|
|
105
|
+
def load_kubelet_token(self, model, user: str) -> str:
|
|
106
|
+
if self.secret_id:
|
|
107
|
+
return self._get_secret_content(model, user)["kubelet-token"]
|
|
108
|
+
return self.kubelet_token
|
|
109
|
+
|
|
110
|
+
def load_proxy_token(self, model, user: str) -> str:
|
|
111
|
+
if self.secret_id:
|
|
112
|
+
return self._get_secret_content(model, user)["proxy-token"]
|
|
113
|
+
return self.proxy_token
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class Data(BaseModel):
|
|
117
|
+
api_endpoints: Json[List[AnyHttpUrl]] = Field(alias="api-endpoints")
|
|
118
|
+
ca_certificate_secret_id: Optional[str] = Field(alias="ca-certificate-secret-id")
|
|
119
|
+
cluster_tag: str = Field(alias="cluster-tag")
|
|
120
|
+
cohort_keys: Optional[Json[Dict[str, str]]] = Field(alias="cohort-keys")
|
|
121
|
+
creds: Json[Dict[str, Creds]] = Field(alias="creds")
|
|
122
|
+
default_cni: Json[str] = Field(alias="default-cni")
|
|
123
|
+
domain: str = Field(alias="domain")
|
|
124
|
+
enable_kube_dns: bool = Field(alias="enable-kube-dns")
|
|
125
|
+
has_xcp: Json[bool] = Field(alias="has-xcp")
|
|
126
|
+
port: Json[int] = Field(alias="port")
|
|
127
|
+
sdn_ip: Optional[str] = Field(default=None, alias="sdn-ip")
|
|
128
|
+
registry_location: str = Field(alias="registry-location")
|
|
129
|
+
taints: Optional[Json[List[Taint]]] = Field(alias="taints", default=None)
|
|
130
|
+
labels: Optional[Json[List[Label]]] = Field(alias="labels", default=None)
|
|
131
|
+
|
|
132
|
+
def get_ca_certificate(self, model: ops.Model) -> Optional[bytes]:
|
|
133
|
+
if not self.ca_certificate_secret_id:
|
|
134
|
+
return None
|
|
135
|
+
try:
|
|
136
|
+
secret = model.get_secret(
|
|
137
|
+
id=self.ca_certificate_secret_id, label="ca-certificate"
|
|
138
|
+
)
|
|
139
|
+
return secret.get_content(refresh=True)["ca-certificate"].encode()
|
|
140
|
+
except ops.SecretNotFoundError:
|
|
141
|
+
return None
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from .model import AuthRequest, Creds, Label, Taint
|
|
5
|
+
from ops import CharmBase, Relation, SecretNotFoundError, Unit
|
|
6
|
+
from typing import Generator, List, Tuple
|
|
7
|
+
|
|
8
|
+
log = logging.getLogger("KubeControlProvides")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class KubeControlProvides:
|
|
12
|
+
"""Implements the Provides side of the kube-control interface."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, charm: CharmBase, endpoint: str = "kube-control", schemas="0,1"):
|
|
15
|
+
self.charm = charm
|
|
16
|
+
self.endpoint = endpoint
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def auth_requests(self) -> List[AuthRequest]:
|
|
20
|
+
"""Return a list of authentication requests from related units."""
|
|
21
|
+
requests = [
|
|
22
|
+
request
|
|
23
|
+
for relation in self.relations
|
|
24
|
+
for unit in relation.units
|
|
25
|
+
if (request := AuthRequest(unit=unit.name, **relation.data[unit]))
|
|
26
|
+
and request.user
|
|
27
|
+
and request.group
|
|
28
|
+
]
|
|
29
|
+
requests.sort()
|
|
30
|
+
return requests
|
|
31
|
+
|
|
32
|
+
def clear_creds(self) -> None:
|
|
33
|
+
"""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.
|
|
36
|
+
"""
|
|
37
|
+
for relation in self.relations:
|
|
38
|
+
relation.data[self.unit]["creds"] = ""
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def ingress_addresses(self) -> List[str]:
|
|
42
|
+
"""Ingress addresses for this endpoint."""
|
|
43
|
+
return [
|
|
44
|
+
# RFC 5280 section 4.2.1.6: "For IP version 6 ... the octet string
|
|
45
|
+
# MUST contain exactly sixteen octets." We'll use .exploded to be
|
|
46
|
+
# safe.
|
|
47
|
+
addr.exploded
|
|
48
|
+
for addr in self.charm.model.get_binding(
|
|
49
|
+
self.endpoint
|
|
50
|
+
).network.ingress_addresses
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def relations(self) -> List[Relation]:
|
|
55
|
+
"""List of relations on this endpoint."""
|
|
56
|
+
return self.charm.model.relations[self.endpoint]
|
|
57
|
+
|
|
58
|
+
def set_api_endpoints(self, endpoints) -> None:
|
|
59
|
+
"""Send the list of API endpoint URLs to which workers should connect."""
|
|
60
|
+
endpoints = json.dumps(endpoints)
|
|
61
|
+
for relation in self.relations:
|
|
62
|
+
relation.data[self.unit]["api-endpoints"] = endpoints
|
|
63
|
+
|
|
64
|
+
def set_ca_certificate(self, ca_certificate: str) -> None:
|
|
65
|
+
"""Send the CA certificate to the remote units.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
ca_certificate str: The CA certificate in PEM format.
|
|
69
|
+
"""
|
|
70
|
+
content = {"ca-certificate": ca_certificate}
|
|
71
|
+
secret = self.refresh_secret_content(
|
|
72
|
+
"ca-certificate", content, "Kubernetes API endpoint CA certificate"
|
|
73
|
+
)
|
|
74
|
+
for relation in self.relations:
|
|
75
|
+
if secret.id:
|
|
76
|
+
secret.grant(relation)
|
|
77
|
+
relation.data[self.unit]["ca-certificate-secret-id"] = secret.id
|
|
78
|
+
|
|
79
|
+
def set_cluster_name(self, cluster_name) -> None:
|
|
80
|
+
"""Send the cluster name to the remote units."""
|
|
81
|
+
for relation in self.relations:
|
|
82
|
+
relation.data[self.unit]["cluster-tag"] = cluster_name
|
|
83
|
+
|
|
84
|
+
def set_default_cni(self, default_cni) -> None:
|
|
85
|
+
"""Send the default CNI. The default_cni value should be a string
|
|
86
|
+
containing the name of a related CNI application to use as the default
|
|
87
|
+
CNI. For example: "flannel" or "calico". If no default has been chosen
|
|
88
|
+
then "" can be sent instead."""
|
|
89
|
+
value = json.dumps(default_cni)
|
|
90
|
+
for relation in self.relations:
|
|
91
|
+
relation.data[self.unit]["default-cni"] = value
|
|
92
|
+
|
|
93
|
+
def set_dns_address(self, address) -> None:
|
|
94
|
+
"""Send DNS address to the remote units for use in Kubelet configuration.
|
|
95
|
+
This will typically be the cluster IP of the kube-dns service belonging
|
|
96
|
+
to CoreDNS."""
|
|
97
|
+
for relation in self.relations:
|
|
98
|
+
relation.data[self.unit]["sdn-ip"] = address
|
|
99
|
+
|
|
100
|
+
def set_dns_domain(self, domain) -> None:
|
|
101
|
+
"""Send DNS domain to the remote units for use in Kubelet configuration."""
|
|
102
|
+
for relation in self.relations:
|
|
103
|
+
relation.data[self.unit]["domain"] = domain
|
|
104
|
+
|
|
105
|
+
def set_dns_enabled(self, enabled) -> None:
|
|
106
|
+
"""Send DNS enabled status. This indicates to remote units if they should
|
|
107
|
+
wait for DNS info or not."""
|
|
108
|
+
value = str(enabled)
|
|
109
|
+
for relation in self.relations:
|
|
110
|
+
relation.data[self.unit]["enable-kube-dns"] = value
|
|
111
|
+
|
|
112
|
+
def set_dns_port(self, port) -> None:
|
|
113
|
+
"""Send DNS port to the remote units for use in Kubelet configuration."""
|
|
114
|
+
value = str(port)
|
|
115
|
+
for relation in self.relations:
|
|
116
|
+
relation.data[self.unit]["port"] = value
|
|
117
|
+
|
|
118
|
+
def set_has_external_cloud_provider(self, has_xcp) -> None:
|
|
119
|
+
"""Send indicator to remote units that an external cloud provider is in use."""
|
|
120
|
+
value = str(has_xcp).lower()
|
|
121
|
+
for relation in self.relations:
|
|
122
|
+
relation.data[self.unit]["has-xcp"] = value
|
|
123
|
+
|
|
124
|
+
def set_image_registry(self, image_registry) -> None:
|
|
125
|
+
"""Send the image registry location to the remote units."""
|
|
126
|
+
for relation in self.relations:
|
|
127
|
+
relation.data[self.unit]["registry-location"] = image_registry
|
|
128
|
+
|
|
129
|
+
def set_labels(self, labels) -> None:
|
|
130
|
+
"""Send the Juju config labels of the control-plane."""
|
|
131
|
+
labels = [str(_) for _ in labels if Label.validate(_)]
|
|
132
|
+
dedup = sorted(set(labels))
|
|
133
|
+
value = json.dumps(dedup)
|
|
134
|
+
for relation in self.relations:
|
|
135
|
+
relation.data[self.unit]["labels"] = value
|
|
136
|
+
|
|
137
|
+
def set_taints(self, taints) -> None:
|
|
138
|
+
"""Send the Juju config taints of the control-plane."""
|
|
139
|
+
taints = [str(_) for _ in taints if Taint.validate(_)]
|
|
140
|
+
dedup = sorted(set(taints))
|
|
141
|
+
value = json.dumps(dedup)
|
|
142
|
+
for relation in self.relations:
|
|
143
|
+
relation.data[self.unit]["taints"] = value
|
|
144
|
+
|
|
145
|
+
def refresh_secret_content(self, label, content, description=None):
|
|
146
|
+
"""Refresh the content of a secret."""
|
|
147
|
+
try:
|
|
148
|
+
secret = self.charm.model.get_secret(label=label)
|
|
149
|
+
if secret.get_content(refresh=True) != content:
|
|
150
|
+
secret.set_content(content)
|
|
151
|
+
secret.set_info(description=description, label=label)
|
|
152
|
+
except SecretNotFoundError:
|
|
153
|
+
secret = self.charm.app.add_secret(
|
|
154
|
+
content, label=label, description=description
|
|
155
|
+
)
|
|
156
|
+
return secret
|
|
157
|
+
|
|
158
|
+
def closed_auth_creds(self) -> Generator[Tuple[str, Creds], None, None]:
|
|
159
|
+
"""Revoke tokens for units removed from the relation.
|
|
160
|
+
|
|
161
|
+
Example:
|
|
162
|
+
```python
|
|
163
|
+
for user, cred in self.kube_control.closed_auth_creds():
|
|
164
|
+
log.info("Revoke auth-token for '%s'", user)
|
|
165
|
+
token = cred.client_token.get_secret_value()
|
|
166
|
+
kubernetes.remove_auth_token(token)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Yields:
|
|
170
|
+
Tuple[str, Creds]: The user and creds to be revoked.
|
|
171
|
+
"""
|
|
172
|
+
creds, unit_names = {}, []
|
|
173
|
+
|
|
174
|
+
# Collect creds from all relations
|
|
175
|
+
for relation in self.relations:
|
|
176
|
+
creds.update(json.loads(relation.data[self.unit].get("creds", "{}")))
|
|
177
|
+
unit_names += [u.name for u in relation.units]
|
|
178
|
+
|
|
179
|
+
# Revoke creds for units that have been removed
|
|
180
|
+
for user, cred in dict(**creds).items():
|
|
181
|
+
data = Creds(**cred)
|
|
182
|
+
if data.scope not in unit_names:
|
|
183
|
+
log.info(f"Revoking creds for {user} on unit {data.scope}")
|
|
184
|
+
creds.pop(user)
|
|
185
|
+
yield user, data
|
|
186
|
+
if data.secret_id:
|
|
187
|
+
secret = self.charm.model.get_secret(id=data.secret_id)
|
|
188
|
+
secret.remove_all_revisions()
|
|
189
|
+
|
|
190
|
+
# Publish the updated creds without the revoked units
|
|
191
|
+
value = json.dumps(creds)
|
|
192
|
+
for relation in self.relations:
|
|
193
|
+
relation.data[self.unit]["creds"] = value
|
|
194
|
+
|
|
195
|
+
def sign_auth_request(
|
|
196
|
+
self, request: AuthRequest, client_token, kubelet_token, proxy_token
|
|
197
|
+
) -> None:
|
|
198
|
+
"""Send authorization tokens to the requesting unit."""
|
|
199
|
+
creds, request_relation = {}, None
|
|
200
|
+
request_unit = self.charm.model.get_unit(request.unit)
|
|
201
|
+
|
|
202
|
+
for relation in self.relations:
|
|
203
|
+
creds.update(json.loads(relation.data[self.unit].get("creds", "{}")))
|
|
204
|
+
if request_unit in relation.units:
|
|
205
|
+
request_relation = relation
|
|
206
|
+
|
|
207
|
+
tokens = Creds(
|
|
208
|
+
client_token=client_token,
|
|
209
|
+
kubelet_token=kubelet_token,
|
|
210
|
+
proxy_token=proxy_token,
|
|
211
|
+
scope=request.unit,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
if 1 in request.schema_vers and request_relation:
|
|
215
|
+
# Requesting unit can use schema 1, use juju secrets
|
|
216
|
+
content = {
|
|
217
|
+
"client-token": client_token,
|
|
218
|
+
"kubelet-token": kubelet_token,
|
|
219
|
+
"proxy-token": proxy_token,
|
|
220
|
+
}
|
|
221
|
+
label = f"{request.user}-creds"
|
|
222
|
+
description = f"Credentials for {request.user}"
|
|
223
|
+
secret = self.refresh_secret_content(label, content, description)
|
|
224
|
+
if secret.id:
|
|
225
|
+
log.info(f"Granting secret {secret.id} to {request_relation.name}")
|
|
226
|
+
secret.grant(request_relation, unit=request_unit)
|
|
227
|
+
# Intentionally set the tokens to empty strings in order to
|
|
228
|
+
# be valid credentials for units still receiving these on schema 0
|
|
229
|
+
# if None, these would be considered missing and the schema 0
|
|
230
|
+
# parser would assume the relation wasn't ready.
|
|
231
|
+
tokens.client_token = ""
|
|
232
|
+
tokens.kubelet_token = ""
|
|
233
|
+
tokens.proxy_token = ""
|
|
234
|
+
tokens.secret_id = secret.id
|
|
235
|
+
creds[request.user] = tokens.dict(by_alias=True, exclude_none=True)
|
|
236
|
+
else:
|
|
237
|
+
creds[request.user] = tokens.dict(by_alias=True, exclude_none=True)
|
|
238
|
+
|
|
239
|
+
value = json.dumps(creds)
|
|
240
|
+
for relation in self.relations:
|
|
241
|
+
relation.data[self.unit]["creds"] = value
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def unit(self) -> Unit:
|
|
245
|
+
"""Local unit."""
|
|
246
|
+
return self.charm.unit
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# Copyright 2022 Canonical Ltd.
|
|
2
|
+
# See LICENSE file for licensing details.
|
|
3
|
+
"""Implementation of kube-control interface (requires)
|
|
4
|
+
|
|
5
|
+
This re-implements the requires side of the interface in ops.framework
|
|
6
|
+
style rather than the reactive style.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import logging
|
|
11
|
+
from os import PathLike
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Dict, Optional, Mapping, List
|
|
14
|
+
|
|
15
|
+
import yaml
|
|
16
|
+
from backports.cached_property import cached_property
|
|
17
|
+
from .model import AuthRequest, Creds, Data, Taint, Label
|
|
18
|
+
from pydantic import ValidationError
|
|
19
|
+
|
|
20
|
+
from ops.charm import CharmBase, RelationBrokenEvent
|
|
21
|
+
from ops.framework import Object
|
|
22
|
+
from ops.model import Relation
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger("KubeControlRequirer")
|
|
25
|
+
JUJU_CLUSTER = "juju-cluster"
|
|
26
|
+
JUJU_CONTEXT = "juju-context"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class KubeControlRequirer(Object):
|
|
30
|
+
"""
|
|
31
|
+
Implements the requirer side of the kube-control interface.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, charm: CharmBase, endpoint: str = "kube-control", schemas="0"):
|
|
35
|
+
super().__init__(charm, f"relation-{endpoint}")
|
|
36
|
+
self.endpoint = endpoint
|
|
37
|
+
# comma-separated set of schemas to advertise support
|
|
38
|
+
# schema 0 -- same as unschema'd
|
|
39
|
+
# schema 1 -- signals support for credentials in juju secrets
|
|
40
|
+
self.schema_ver = [int(v) for v in schemas.split(",")]
|
|
41
|
+
|
|
42
|
+
@cached_property
|
|
43
|
+
def relation(self) -> Optional[Relation]:
|
|
44
|
+
"""The lone relation endpoint or None."""
|
|
45
|
+
return self.model.get_relation(self.endpoint)
|
|
46
|
+
|
|
47
|
+
@cached_property
|
|
48
|
+
def _data(self) -> Optional[Data]:
|
|
49
|
+
if self.relation and self.relation.units:
|
|
50
|
+
rx = {}
|
|
51
|
+
for unit in self.relation.units:
|
|
52
|
+
rx.update(self.relation.data[unit])
|
|
53
|
+
return Data(**rx)
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
def evaluate_relation(self, event) -> Optional[str]:
|
|
57
|
+
"""Determine if relation is ready."""
|
|
58
|
+
no_relation = not self.relation or (
|
|
59
|
+
isinstance(event, RelationBrokenEvent) and event.relation is self.relation
|
|
60
|
+
)
|
|
61
|
+
if not self.is_ready:
|
|
62
|
+
if no_relation:
|
|
63
|
+
return f"Missing required {self.endpoint} relation"
|
|
64
|
+
return f"Waiting for {self.endpoint} relation"
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def is_ready(self):
|
|
69
|
+
"""Whether the request for this instance has been completed."""
|
|
70
|
+
try:
|
|
71
|
+
self._data
|
|
72
|
+
except ValidationError as ve:
|
|
73
|
+
log.error(f"{self.endpoint} relation data not yet valid. ({ve}")
|
|
74
|
+
return False
|
|
75
|
+
if self._data is None:
|
|
76
|
+
log.error(f"{self.endpoint} relation data not yet available.")
|
|
77
|
+
return False
|
|
78
|
+
return True
|
|
79
|
+
|
|
80
|
+
def create_kubeconfig(
|
|
81
|
+
self, ca: PathLike, kubeconfig: PathLike, user: str, k8s_user: str
|
|
82
|
+
):
|
|
83
|
+
"""Write kubeconfig based on available creds."""
|
|
84
|
+
creds = self.get_auth_credentials(k8s_user)
|
|
85
|
+
endpoints = self.get_api_endpoints()
|
|
86
|
+
server = endpoints[0] if endpoints else None
|
|
87
|
+
token = creds["client_token"] if creds else None
|
|
88
|
+
|
|
89
|
+
if ca_content := self.get_ca_certificate():
|
|
90
|
+
ca_b64 = base64.b64encode(ca_content).decode("utf-8")
|
|
91
|
+
elif Path(ca).exists():
|
|
92
|
+
ca_b64 = base64.b64encode(Path(ca).read_bytes()).decode("utf-8")
|
|
93
|
+
else:
|
|
94
|
+
log.error("No CA certificate found")
|
|
95
|
+
raise FileNotFoundError("No CA certificate found")
|
|
96
|
+
|
|
97
|
+
# Create the config file with the address of the control-plane server.
|
|
98
|
+
config_contents = {
|
|
99
|
+
"apiVersion": "v1",
|
|
100
|
+
"kind": "Config",
|
|
101
|
+
"preferences": {},
|
|
102
|
+
"clusters": [
|
|
103
|
+
{
|
|
104
|
+
"cluster": {
|
|
105
|
+
"certificate-authority-data": ca_b64,
|
|
106
|
+
"server": server,
|
|
107
|
+
},
|
|
108
|
+
"name": JUJU_CLUSTER,
|
|
109
|
+
}
|
|
110
|
+
],
|
|
111
|
+
"contexts": [
|
|
112
|
+
{
|
|
113
|
+
"context": {"cluster": JUJU_CLUSTER, "user": user},
|
|
114
|
+
"name": JUJU_CONTEXT,
|
|
115
|
+
}
|
|
116
|
+
],
|
|
117
|
+
"users": [{"name": user, "user": {"token": token}}],
|
|
118
|
+
"current-context": JUJU_CONTEXT,
|
|
119
|
+
}
|
|
120
|
+
old_kubeconfig = Path(kubeconfig)
|
|
121
|
+
new_kubeconfig = Path(f"{kubeconfig}.new")
|
|
122
|
+
new_kubeconfig.parent.mkdir(exist_ok=True, mode=0o750)
|
|
123
|
+
new_kubeconfig.write_text(yaml.safe_dump(config_contents))
|
|
124
|
+
new_kubeconfig.chmod(mode=0o600)
|
|
125
|
+
|
|
126
|
+
if old_kubeconfig.exists():
|
|
127
|
+
changed = new_kubeconfig.read_text() != old_kubeconfig.read_text()
|
|
128
|
+
else:
|
|
129
|
+
changed = True
|
|
130
|
+
if changed:
|
|
131
|
+
new_kubeconfig.rename(old_kubeconfig)
|
|
132
|
+
|
|
133
|
+
def get_ca_certificate(self) -> Optional[bytes]:
|
|
134
|
+
"""Return the CA certificate in pem format."""
|
|
135
|
+
if not self.is_ready:
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
return self._data.get_ca_certificate(self.model)
|
|
139
|
+
|
|
140
|
+
def get_auth_credentials(self, user) -> Optional[Mapping[str, str]]:
|
|
141
|
+
"""Return the authentication credentials."""
|
|
142
|
+
if not self.is_ready:
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
users: Dict[str, Creds] = self._data.creds
|
|
146
|
+
|
|
147
|
+
if creds := users.get(user):
|
|
148
|
+
return {
|
|
149
|
+
"user": user,
|
|
150
|
+
"kubelet_token": creds.load_kubelet_token(self.model, user),
|
|
151
|
+
"proxy_token": creds.load_proxy_token(self.model, user),
|
|
152
|
+
"client_token": creds.load_client_token(self.model, user),
|
|
153
|
+
}
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
def get_dns(self) -> Mapping[str, str]:
|
|
157
|
+
"""
|
|
158
|
+
Return DNS info provided by the control-plane.
|
|
159
|
+
"""
|
|
160
|
+
return {
|
|
161
|
+
"port": self._data.port if self.is_ready else None,
|
|
162
|
+
"domain": self._data.domain if self.is_ready else None,
|
|
163
|
+
"sdn-ip": self._data.sdn_ip if self.is_ready else None,
|
|
164
|
+
"enable-kube-dns": self._data.enable_kube_dns if self.is_ready else None,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
def dns_ready(self) -> bool:
|
|
168
|
+
"""
|
|
169
|
+
Return True if we have all DNS info from the control-plane.
|
|
170
|
+
"""
|
|
171
|
+
keys = ["port", "domain", "sdn-ip", "enable-kube-dns"]
|
|
172
|
+
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
|
+
)
|
|
177
|
+
|
|
178
|
+
def set_auth_request(self, user, group="system:nodes") -> None:
|
|
179
|
+
"""Notify control-plane that we are requesting auth.
|
|
180
|
+
|
|
181
|
+
Also, use this hostname for the kubelet system account.
|
|
182
|
+
|
|
183
|
+
@params user - user requesting authentication
|
|
184
|
+
@params groups - Determines the level of elevated privileges of the
|
|
185
|
+
requested user.
|
|
186
|
+
Can be overridden to request sudo level access on the
|
|
187
|
+
cluster via changing to
|
|
188
|
+
system:masters. # wokeignore:rule=master
|
|
189
|
+
"""
|
|
190
|
+
if self.relation:
|
|
191
|
+
req = AuthRequest(kubelet_user=user, auth_group=group)
|
|
192
|
+
req.schema_vers = self.schema_ver
|
|
193
|
+
log.info(
|
|
194
|
+
f"Auth Req for {user} with group {group} on schema {self.schema_ver}"
|
|
195
|
+
)
|
|
196
|
+
self.relation.data[self.model.unit].update(req.dict(exclude_none=True))
|
|
197
|
+
|
|
198
|
+
def set_gpu(self, enabled=True):
|
|
199
|
+
"""
|
|
200
|
+
Tell the control-plane that we're gpu-enabled (or not).
|
|
201
|
+
"""
|
|
202
|
+
log("Setting gpu={} on kube-control relation".format(enabled))
|
|
203
|
+
for relation in self.model.relations:
|
|
204
|
+
relation.data[self.model.unit].update(dict(gpu=enabled))
|
|
205
|
+
|
|
206
|
+
def get_cluster_tag(self):
|
|
207
|
+
"""
|
|
208
|
+
Tag for identifying resources that are part of the cluster.
|
|
209
|
+
"""
|
|
210
|
+
return self._data.cluster_tag if self.is_ready else None
|
|
211
|
+
|
|
212
|
+
def get_registry_location(self):
|
|
213
|
+
"""
|
|
214
|
+
URL for container image registry.
|
|
215
|
+
"""
|
|
216
|
+
return self._data.registry_location if self.is_ready else None
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def cohort_keys(self):
|
|
220
|
+
"""
|
|
221
|
+
The cohort snapshot keys sent by the control-plane.
|
|
222
|
+
"""
|
|
223
|
+
return self._data.cohort_keys if self.is_ready else None
|
|
224
|
+
|
|
225
|
+
def get_default_cni(self):
|
|
226
|
+
"""
|
|
227
|
+
Default CNI network to use.
|
|
228
|
+
"""
|
|
229
|
+
return self._data.default_cni if self.is_ready else None
|
|
230
|
+
|
|
231
|
+
def get_api_endpoints(self):
|
|
232
|
+
"""
|
|
233
|
+
Returns a list of API endpoint URLs.
|
|
234
|
+
"""
|
|
235
|
+
api_endpoints = (self.is_ready and self._data.api_endpoints) or []
|
|
236
|
+
endpoints = set(map(str, api_endpoints))
|
|
237
|
+
return sorted(endpoints)
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def has_xcp(self):
|
|
241
|
+
"""The has-xcp value."""
|
|
242
|
+
return (self.is_ready and self._data.has_xcp) or False
|
|
243
|
+
|
|
244
|
+
def get_controller_taints(self) -> List[Taint]:
|
|
245
|
+
"""Returns a list of taints configured on the control-plane nodes."""
|
|
246
|
+
return (self.is_ready and self._data.taints) or []
|
|
247
|
+
|
|
248
|
+
def get_controller_labels(self) -> List[Label]:
|
|
249
|
+
"""Returns a list of lables configured on the control-plane nodes."""
|
|
250
|
+
return (self.is_ready and self._data.labels) or []
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: ops.interface_kube_control
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Kube-Control Interface for Charmed Operators
|
|
5
|
+
Home-page: https://github.com/juju-solutions/interface-kube-control/blob/HEAD/ops
|
|
6
|
+
Author: Adam Dyess
|
|
7
|
+
Author-email: adam.dyess@canonical.com
|
|
8
|
+
License: MIT license
|
|
9
|
+
Keywords: juju,charming,kubernetes,ops,framework,interface
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
Requires-Dist: backports.cached-property
|
|
17
|
+
Requires-Dist: pydantic<2
|
|
18
|
+
Requires-Dist: ops
|
|
19
|
+
Dynamic: author
|
|
20
|
+
Dynamic: author-email
|
|
21
|
+
Dynamic: classifier
|
|
22
|
+
Dynamic: description-content-type
|
|
23
|
+
Dynamic: home-page
|
|
24
|
+
Dynamic: keywords
|
|
25
|
+
Dynamic: license
|
|
26
|
+
Dynamic: requires-dist
|
|
27
|
+
Dynamic: summary
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
setup.py
|
|
3
|
+
tox.ini
|
|
4
|
+
ops.interface_kube_control.egg-info/PKG-INFO
|
|
5
|
+
ops.interface_kube_control.egg-info/SOURCES.txt
|
|
6
|
+
ops.interface_kube_control.egg-info/dependency_links.txt
|
|
7
|
+
ops.interface_kube_control.egg-info/requires.txt
|
|
8
|
+
ops.interface_kube_control.egg-info/top_level.txt
|
|
9
|
+
ops.interface_kube_control.egg-info/zip-safe
|
|
10
|
+
ops/interface_kube_control/__init__.py
|
|
11
|
+
ops/interface_kube_control/model.py
|
|
12
|
+
ops/interface_kube_control/provides.py
|
|
13
|
+
ops/interface_kube_control/requires.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ops
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from setuptools import setup, find_namespace_packages
|
|
6
|
+
|
|
7
|
+
setup(
|
|
8
|
+
author="Adam Dyess",
|
|
9
|
+
author_email="adam.dyess@canonical.com",
|
|
10
|
+
description="Kube-Control Interface for Charmed Operators",
|
|
11
|
+
long_description=Path("README.md").read_text(),
|
|
12
|
+
long_description_content_type="text/markdown",
|
|
13
|
+
classifiers=[
|
|
14
|
+
"Programming Language :: Python",
|
|
15
|
+
"Programming Language :: Python :: 3.7",
|
|
16
|
+
"Programming Language :: Python :: 3.8",
|
|
17
|
+
"Programming Language :: Python :: 3.9",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
],
|
|
20
|
+
license="MIT license",
|
|
21
|
+
include_package_data=True,
|
|
22
|
+
keywords=["juju", "charming", "kubernetes", "ops", "framework", "interface"],
|
|
23
|
+
name="ops.interface_kube_control",
|
|
24
|
+
packages=find_namespace_packages(include=["ops.*"]),
|
|
25
|
+
url="https://github.com/juju-solutions/interface-kube-control/blob/HEAD/ops",
|
|
26
|
+
version="0.2.0",
|
|
27
|
+
zip_safe=True,
|
|
28
|
+
install_requires=[
|
|
29
|
+
"backports.cached-property",
|
|
30
|
+
"pydantic<2",
|
|
31
|
+
"ops",
|
|
32
|
+
],
|
|
33
|
+
)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[tox]
|
|
2
|
+
envlist = unit
|
|
3
|
+
|
|
4
|
+
[vars]
|
|
5
|
+
tst_path = {toxinidir}/tests
|
|
6
|
+
|
|
7
|
+
[testenv]
|
|
8
|
+
basepython = python3
|
|
9
|
+
setenv =
|
|
10
|
+
PYTHONPATH = {toxinidir}
|
|
11
|
+
|
|
12
|
+
[testenv:unit]
|
|
13
|
+
deps =
|
|
14
|
+
pytest-cov
|
|
15
|
+
pytest-html
|
|
16
|
+
commands =
|
|
17
|
+
pytest \
|
|
18
|
+
-vv \
|
|
19
|
+
--cov='{envsitepackagesdir}/ops/interface_kube_control' \
|
|
20
|
+
--cov-report=term-missing \
|
|
21
|
+
--tb=native \
|
|
22
|
+
{posargs:{[vars]tst_path}/unit}
|
|
23
|
+
|
|
24
|
+
[testenv:build]
|
|
25
|
+
skip_install = True
|
|
26
|
+
skipsdist = True
|
|
27
|
+
allowlist_externals = rm
|
|
28
|
+
deps =
|
|
29
|
+
build
|
|
30
|
+
twine
|
|
31
|
+
commands=
|
|
32
|
+
rm -rf build/ *.egg-info/ dist/
|
|
33
|
+
python -m build
|
|
34
|
+
twine check {toxinidir}/dist/*
|
|
35
|
+
twine upload {posargs} {toxinidir}/dist/*
|