This repository has been archived by the owner on Feb 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
__init__.py
287 lines (251 loc) · 9.57 KB
/
__init__.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
# Copyright (C) 2016 Red Hat, Inc
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The kubernetes container manager package.
"""
import json
import requests
from urllib.parse import urljoin, urlparse
from commissaire.containermgr import ContainerManagerBase
from commissaire.util.config import ConfigurationError
class KubeContainerManager(ContainerManagerBase):
"""
Kubernetes container manager implementation.
"""
def __init__(self, config):
"""
Creates an instance of the Kubernetes Container Manager.
:param config: Configuration details
:type config: dict
"""
ContainerManagerBase.__init__(self, config)
self.__class__.check_config(config)
self.con = requests.Session()
token = config.get('token', None)
if token:
self.con.headers['Authorization'] = 'Bearer {}'.format(token)
self.logger.info('Using bearer token')
self.logger.debug('Bearer token: {}'.format(token))
certificate_path = config.get('certificate_path')
certificate_key_path = config.get('certificate_key_path')
if certificate_path and certificate_key_path:
self.con.cert = (certificate_path, certificate_key_path)
self.logger.info(
'Using client side certificate. Certificate path: {} '
'Certificate Key Path: {}'.format(
certificate_path, certificate_key_path))
# TODO: Verify TLS!!!
self.con.verify = False
self.base_uri = urljoin(config['server_url'], '/api/v1')
self.logger.info('Kubernetes Container Manager created: {}'.format(
self.base_uri))
self.logger.debug(
'Kubernetes Container Manager: {}'.format(self.__dict__))
@classmethod
def check_config(cls, config):
"""
Examines the configuration parameters for an ContainerManager
and throws a ConfigurationError if any parameters are invalid.
:param cls: ContainerManager class.
:type cls: class
:param config: Configuration dictionary to check.
:type config: dict
:returns: True if configuration is valid
:rtype: bool
:raises: commissaire.util.config.ConfigurationError
"""
try:
url = urlparse(config['server_url'])
except KeyError:
raise ConfigurationError(
'server_url is a required configuration item')
if (bool(config.get('certificate_path')) ^
bool(config.get('certificate_key_path'))):
raise ConfigurationError(
'Both "certificate_path" and "certificate_key_path" '
'must be provided to use a client side certificate')
if config.get('certificate_path'):
if url.scheme != 'https':
raise ConfigurationError(
'Server URL scheme must be "https" when using client '
'side certificates (got "{}")'.format(url.scheme))
def _fix_part(self, part):
"""
Fixes part if it doesn't start with a slash.
:param part: The URI part. EG: /nodes
:type part: str
:returns: The part in the proper format.
:rtype: str
"""
if not part.startswith('/'):
self.logger.debug(
'Part given without starting slash. Adding...')
part = '/{}'.format(part)
return part
def _get(self, part, *args, **kwargs):
"""
Get information from the Kubernetes apiserver.
:param part: The URI part. EG: /nodes
:type part: sdtr
:param args: All other non-keyword arguments.
:type args: tuple
:param kwargs: All other keyword arguments.
:type kwargs: dict
:returns: requests.Response
"""
part = self._fix_part(part)
self.logger.debug('Executing GET for {}'.format(part))
resp = self.con.get(
'{}{}'.format(self.base_uri, part), *args, **kwargs)
self.logger.debug('Response for {}. Status: {}'.format(
part, resp.status_code))
return resp
def _delete(self, part, *args, **kwargs):
"""
Delete data from the Kubernetes apiserver.
:param part: The URI part. EG: /nodes
:type part: str
::param payload: Data to send with the DELETE.
:type payload: dict
:param args: All other non-keyword arguments.
:type args: tuple
:param kwargs: All other keyword arguments.
:type kwargs: dict
:returns: requests.Response
"""
part = self._fix_part(part)
self.logger.debug('Executing DELETE for {}.'.format(part))
resp = self.con.delete(
'{}{}'.format(self.base_uri, part), *args, **kwargs)
self.logger.debug('Response for {}. Status: {}'.format(
part, resp.status_code))
return resp
def _put(self, part, payload, *args, **kwargs):
"""
Put data to the Kubernetes apiserver.
:param part: The URI part. EG: /nodes
:type part: str
::param payload: Data to send with the PUT.
:type payload: dict
:param args: All other non-keyword arguments.
:type args: tuple
:param kwargs: All other keyword arguments.
:type kwargs: dict
:returns: requests.Response
"""
part = self._fix_part(part)
payload = json.dumps(payload)
self.logger.debug('Executing PUT for {}. Payload={}'.format(
part, payload))
resp = self.con.put(
'{}{}'.format(self.base_uri, part), data=payload, *args, **kwargs)
self.logger.debug('Response for {}. Status: {}'.format(
part, resp.status_code))
return resp
def _post(self, part, payload, *args, **kwargs):
"""
Post data to the Kubernetes apiserver.
:param part: The URI part. EG: /nodes
:type part: str
::param payload: Data to send with the POST.
:type payload: dict
:param args: All other non-keyword arguments.
:type args: tuple
:param kwargs: All other keyword arguments.
:type kwargs: dict
:returns: requests.Response
"""
part = self._fix_part(part)
payload = json.dumps(payload)
self.logger.debug('Executing POST for {}. Payload={}'.format(
part, payload))
resp = self.con.post(
'{}{}'.format(self.base_uri, part), data=payload, *args, **kwargs)
self.logger.debug('Response for {}. Status: {}'.format(
part, resp.status_code))
return resp
def register_node(self, name):
"""
Registers a node to the Kubernetes Container Manager.
:param name: The name of the node.
:type name: str
:returns: True if registered, otherwise False
:rtype: bool
"""
part = '/nodes'
payload = {
"kind": "Node",
"apiVersion": "v1",
"metadata": {
"name": name,
}
}
resp = self._post(part, payload)
if resp.status_code == 201:
return True
self.logger.error(
'Non-created response when trying to register the node {}.'
'Status: {}, Data: {}'.format(name, resp.status_code, resp.text))
return False
def remove_node(self, name):
"""
Removes a node from the Kubernetes Container Manager.
:param name: The name of the node.
:type name: str
:returns: True if removed, otherwise False
:rtype: bool
"""
part = '/nodes/{}'.format(name)
resp = self._delete(part)
if resp.status_code == 200:
return True
self.logger.error(
'Unexpected response when trying to remove the node {}.'
'Status: {}, Data: {}'.format(name, resp.status_code, resp.text))
return False
def node_registered(self, name):
"""
Checks is a node was registered.
:param name: The name of the node.
:type name: str
:returns: True if registered, otherwise False
:rtype: bool
"""
part = '/nodes/{0}'.format(name)
resp = self._get(part)
# TODO: Stronger checking would be better
if resp.status_code == 200:
return True
return False
def get_node_status(self, address, raw=False):
"""
Returns the node status.
:param address: The address of the host to check.
:type address: str
:param raw: If the result should be limited to its own status.
:type raw: bool
:returns: The response back from kubernetes.
:rtype: requests.Response
"""
part = '/nodes/{}'.format(address)
resp = self._get(part)
if resp.status_code == 200:
data = resp.json()
if raw:
data = data['status']
return data
return False
#: Common name for the class
ContainerHandler = KubeContainerManager