-
Notifications
You must be signed in to change notification settings - Fork 6
/
_network.py
370 lines (282 loc) · 10.8 KB
/
_network.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
A Kubernetes client which uses Twisted to interact with Kubernetes
via HTTP.
"""
from os.path import expanduser
from json import loads, dumps
from zope.interface import implementer
import attr
from attr import validators
from pem import parse
from twisted.python.reflect import namedAny
from twisted.python.failure import Failure
from twisted.python.url import URL
from twisted.python.filepath import FilePath
from twisted.internet.defer import succeed
from twisted.web.iweb import IBodyProducer, IAgent
from twisted.web.http import OK, CREATED
from twisted.web.client import Agent, readBody
from eliot import Message, start_action
from eliot.twisted import DeferredContext
from pykube import KubeConfig
from . import (
IObject, IKubernetes, IKubernetesClient, KubernetesError,
iobject_from_raw, iobject_to_raw,
authenticate_with_certificate,
)
def network_kubernetes(**kw):
"""
Create a new ``IKubernetes`` provider which can be used to create clients.
:param twisted.python.url.URL base_url: The root of the Kubernetes HTTPS
API to interact with.
:param twisted.web.iweb.IAgent agent: An HTTP agent to use to issue
requests. Defaults to a new ``twisted.web.client.Agent`` instance.
See ``txkube.authenticate_with_serviceaccount`` and
``txkube.authenticate_with_certificate`` for helpers for creating
agents that interact well with Kubernetes servers.
:return IKubernetes: The Kubernetes service.
"""
return _NetworkKubernetes(**kw)
def network_kubernetes_from_context(reactor, context, path=None):
"""
Create a new ``IKubernetes`` provider based on a kube config file.
:param reactor: A Twisted reactor which will be used for I/O and
scheduling.
:param unicode context: The name of the kube config context from which to
load configuration details.
:param FilePath path: The location of the kube config file to use.
:return IKubernetes: The Kubernetes service described by the named
context.
"""
if path is None:
path = FilePath(expanduser(u"~/.kube/config"))
config = KubeConfig.from_file(path.path)
context = config.contexts[context]
cluster = config.clusters[context[u"cluster"]]
user = config.users[context[u"user"]]
base_url = URL.fromText(cluster[u"server"].decode("ascii"))
[ca_cert] = parse(cluster[u"certificate-authority"].bytes())
[client_cert] = parse(user[u"client-certificate"].bytes())
[client_key] = parse(user[u"client-key"].bytes())
agent = authenticate_with_certificate(
reactor, base_url, client_cert, client_key, ca_cert,
)
return network_kubernetes(
base_url=base_url,
agent=agent,
)
# It would be simpler to use FileBodyProducer(BytesIO(...)) but:
#
# - https://twistedmatrix.com/trac/ticket/9003
# - https://github.com/twisted/treq/issues/161
@implementer(IBodyProducer)
@attr.s(frozen=True)
class _BytesProducer(object):
_data = attr.ib(validator=validators.instance_of(bytes), repr=False)
@property
def length(self):
return len(self._data)
def startProducing(self, consumer):
consumer.write(self._data)
return succeed(None)
def stopProducing(self):
pass
def pauseProducing(self):
pass
def resumeProducing(self):
pass
@implementer(IKubernetesClient)
@attr.s(frozen=True)
class _NetworkClient(object):
_apiVersion = u"v1"
kubernetes = attr.ib(validator=validators.provides(IKubernetes))
agent = attr.ib(validator=validators.provides(IAgent))
def _request(self, method, url, headers=None, bodyProducer=None):
action = start_action(
action_type=u"network-client:request",
method=method,
url=url.asText(),
)
with action.context():
d = self.agent.request(
method, url.asText().encode("ascii"), headers, bodyProducer,
)
return DeferredContext(d).addActionFinish()
def _get(self, url):
return self._request(b"GET", url)
def _delete(self, url, options):
bodyProducer = None
if options is not None:
bodyProducer = _BytesProducer(dumps(iobject_to_raw(options)))
return self._request(b"DELETE", url, bodyProducer=bodyProducer)
def _post(self, url, obj):
return self._request(
b"POST", url, bodyProducer=_BytesProducer(dumps(obj)),
)
def _put(self, url, obj):
return self._request(
b"PUT", url, bodyProducer=_BytesProducer(dumps(obj)),
)
def create(self, obj):
"""
Issue a I{POST} to create the given object.
"""
action = start_action(
action_type=u"network-client:create",
)
with action.context():
url = self.kubernetes.base_url.child(*collection_location(obj))
document = iobject_to_raw(obj)
Message.log(submitted_object=document)
d = DeferredContext(self._post(url, document))
d.addCallback(check_status, (CREATED,))
d.addCallback(readBody)
d.addCallback(loads)
d.addCallback(log_response_object, action)
d.addCallback(iobject_from_raw)
return d.addActionFinish()
def replace(self, obj):
"""
Issue a I{PUT} to replace an existing object with a new one.
"""
action = start_action(
action_type=u"network-client:replace",
)
with action.context():
url = self.kubernetes.base_url.child(*object_location(obj))
document = iobject_to_raw(obj)
Message.log(submitted_object=document)
d = DeferredContext(self._put(url, document))
d.addCallback(check_status, (OK,))
d.addCallback(readBody)
d.addCallback(loads)
d.addCallback(log_response_object, action)
d.addCallback(iobject_from_raw)
return d.addActionFinish()
def get(self, obj):
"""
Issue a I{GET} to retrieve the given object.
The object must have identifying metadata such as a namespace and a
name but other fields are ignored.
"""
action = start_action(
action_type=u"network-client:get",
kind=obj.kind,
name=obj.metadata.name,
namespace=getattr(obj.metadata, "namespace", None),
)
with action.context():
url = self.kubernetes.base_url.child(*object_location(obj))
d = DeferredContext(self._get(url))
d.addCallback(check_status, (OK,))
d.addCallback(readBody)
d.addCallback(loads)
d.addCallback(log_response_object, action)
d.addCallback(iobject_from_raw)
return d.addActionFinish()
def delete(self, obj, options=None):
"""
Issue a I{DELETE} to delete the given object.
:param v1.DeleteOptions options: Optional details to control some
consequences of the deletion.
"""
action = start_action(
action_type=u"network-client:delete",
kind=obj.kind,
name=obj.metadata.name,
namespace=getattr(obj.metadata, "namespace", None),
)
with action.context():
url = self.kubernetes.base_url.child(*object_location(obj))
d = DeferredContext(self._delete(url, options))
d.addCallback(check_status, (OK,))
d.addCallback(readBody)
d.addCallback(lambda raw: None)
return d.addActionFinish()
def list(self, kind):
"""
Issue a I{GET} to retrieve objects of a given kind.
"""
action = start_action(
action_type=u"network-client:list",
kind=kind.kind,
apiVersion=kind.apiVersion,
)
with action.context():
url = self.kubernetes.base_url.child(*collection_location(kind))
d = DeferredContext(self._get(url))
d.addCallback(check_status, (OK,))
d.addCallback(readBody)
d.addCallback(lambda body: iobject_from_raw(loads(body)))
return d.addActionFinish()
def object_location(obj):
"""
Get the URL for a specific object.
:param IObject obj: The object the URL for which to get.
:return tuple[unicode]: Some path segments to stick on to a base URL top
construct the location for the given object.
"""
return collection_location(obj) + (obj.metadata.name,)
version_to_segments = {
u"v1": (u"api", u"v1"),
u"v1beta1": (u"apis", u"extensions", u"v1beta1"),
}
def collection_location(obj):
"""
Get the URL for the collection of objects like ``obj``.
:param obj: Either a type representing a Kubernetes object kind or an
instance of such a type.
:return tuple[unicode]: Some path segments to stick on to a base URL to
construct the location of the collection of objects like the one
given.
"""
# TODO kind is not part of IObjectLoader and we should really be loading
# apiVersion off of this object too.
kind = obj.kind
apiVersion = obj.apiVersion
prefix = version_to_segments[apiVersion]
collection = kind.lower() + u"s"
if IObject.providedBy(obj):
# Actual objects *could* have a namespace...
namespace = obj.metadata.namespace
else:
# Types representing a kind couldn't possible.
namespace = None
if namespace is None:
# If there's no namespace, look in the un-namespaced area.
return prefix + (collection,)
# If there is, great, look there.
return prefix + (u"namespaces", namespace, collection)
@implementer(IKubernetes)
@attr.s(frozen=True)
class _NetworkKubernetes(object):
"""
``_NetworkKubernetes`` knows the location of a particular
Kubernetes deployment and gives out clients which speak to that
deployment.
"""
base_url = attr.ib(validator=validators.instance_of(URL))
_agent = attr.ib(
default=attr.Factory(lambda: Agent(namedAny("twisted.internet.reactor"))),
)
def client(self):
return _NetworkClient(self, self._agent)
def log_response_object(document, action):
"""
Emit an Eliot log event belonging to the given action describing the given
response.
:param document: Anything Eliot loggable (but presumably a parsed
Kubernetes response document).
:param action: The Eliot action to which to attach the event.
:return: ``document``
"""
action.add_success_fields(response_object=document)
return document
def check_status(response, expected):
if response.code not in expected:
d = KubernetesError.from_response(response)
d.addCallback(Failure)
return d
return response