/
kubernetes_common.py
526 lines (430 loc) · 18.5 KB
/
kubernetes_common.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#!/usr/bin/env python
# Copyright 2015 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import re
import os
import subprocess
import hashlib
import json
import traceback
from pathlib import Path
from subprocess import check_output, check_call
from socket import gethostname, getfqdn
from shlex import split
from subprocess import CalledProcessError
from charmhelpers.core import hookenv, unitdata
from charmhelpers.core import host
from charms.reactive import endpoint_from_flag, is_state
from time import sleep
db = unitdata.kv()
kubeclientconfig_path = '/root/.kube/config'
gcp_creds_env_key = 'GOOGLE_APPLICATION_CREDENTIALS'
kubeproxyconfig_path = '/root/cdk/kubeproxyconfig'
certs_dir = Path('/root/cdk')
ca_crt_path = certs_dir / 'ca.crt'
server_crt_path = certs_dir / 'server.crt'
server_key_path = certs_dir / 'server.key'
client_crt_path = certs_dir / 'client.crt'
client_key_path = certs_dir / 'client.key'
def get_version(bin_name):
"""Get the version of an installed Kubernetes binary.
:param str bin_name: Name of binary
:return: 3-tuple version (maj, min, patch)
Example::
>>> `get_version('kubelet')
(1, 6, 0)
"""
cmd = '{} --version'.format(bin_name).split()
version_string = subprocess.check_output(cmd).decode('utf-8')
return tuple(int(q) for q in re.findall("[0-9]+", version_string)[:3])
def retry(times, delay_secs):
""" Decorator for retrying a method call.
Args:
times: How many times should we retry before giving up
delay_secs: Delay in secs
Returns: A callable that would return the last call outcome
"""
def retry_decorator(func):
""" Decorator to wrap the function provided.
Args:
func: Provided function should return either True od False
Returns: A callable that would return the last call outcome
"""
def _wrapped(*args, **kwargs):
res = func(*args, **kwargs)
attempt = 0
while not res and attempt < times:
sleep(delay_secs)
res = func(*args, **kwargs)
if res:
break
attempt += 1
return res
return _wrapped
return retry_decorator
def calculate_resource_checksum(resource):
''' Calculate a checksum for a resource '''
md5 = hashlib.md5()
path = hookenv.resource_get(resource)
if path:
with open(path, 'rb') as f:
data = f.read()
md5.update(data)
return md5.hexdigest()
def get_resource_checksum_db_key(checksum_prefix, resource):
''' Convert a resource name to a resource checksum database key. '''
return checksum_prefix + resource
def migrate_resource_checksums(checksum_prefix, snap_resources):
''' Migrate resource checksums from the old schema to the new one '''
for resource in snap_resources:
new_key = get_resource_checksum_db_key(checksum_prefix, resource)
if not db.get(new_key):
path = hookenv.resource_get(resource)
if path:
# old key from charms.reactive.helpers.any_file_changed
old_key = 'reactive.files_changed.' + path
old_checksum = db.get(old_key)
db.set(new_key, old_checksum)
else:
# No resource is attached. Previously, this meant no checksum
# would be calculated and stored. But now we calculate it as if
# it is a 0-byte resource, so let's go ahead and do that.
zero_checksum = hashlib.md5().hexdigest()
db.set(new_key, zero_checksum)
def check_resources_for_upgrade_needed(checksum_prefix, snap_resources):
hookenv.status_set('maintenance', 'Checking resources')
for resource in snap_resources:
key = get_resource_checksum_db_key(checksum_prefix, resource)
old_checksum = db.get(key)
new_checksum = calculate_resource_checksum(resource)
if new_checksum != old_checksum:
return True
return False
def calculate_and_store_resource_checksums(checksum_prefix, snap_resources):
for resource in snap_resources:
key = get_resource_checksum_db_key(checksum_prefix, resource)
checksum = calculate_resource_checksum(resource)
db.set(key, checksum)
def get_ingress_address(endpoint_name):
try:
network_info = hookenv.network_get(endpoint_name)
except NotImplementedError:
network_info = {}
if not network_info or 'ingress-addresses' not in network_info:
# if they don't have ingress-addresses they are running a juju that
# doesn't support spaces, so just return the private address
return hookenv.unit_get('private-address')
addresses = network_info['ingress-addresses']
# Need to prefer non-fan IP addresses due to various issues, e.g.
# https://bugs.launchpad.net/charm-gcp-integrator/+bug/1822997
# Fan typically likes to use IPs in the 240.0.0.0/4 block, so we'll
# prioritize those last. Not technically correct, but good enough.
try:
sort_key = lambda a: int(a.partition('.')[0]) >= 240
addresses = sorted(addresses, key=sort_key)
except Exception:
hookenv.log(traceback.format_exc())
return addresses[0]
def service_restart(service_name):
hookenv.status_set('maintenance', 'Restarting {0} service'.format(
service_name))
host.service_restart(service_name)
def service_start(service_name):
hookenv.log('Starting {0} service.'.format(service_name))
host.service_stop(service_name)
def service_stop(service_name):
hookenv.log('Stopping {0} service.'.format(service_name))
host.service_stop(service_name)
def arch():
'''Return the package architecture as a string. Raise an exception if the
architecture is not supported by kubernetes.'''
# Get the package architecture for this system.
architecture = check_output(['dpkg', '--print-architecture']).rstrip()
# Convert the binary result into a string.
architecture = architecture.decode('utf-8')
return architecture
def get_service_ip(service, namespace="kube-system", errors_fatal=True):
cmd = "kubectl get service --namespace {} {} --output json".format(
namespace, service)
if errors_fatal:
output = check_output(cmd, shell=True).decode()
else:
try:
output = check_output(cmd, shell=True).decode()
except CalledProcessError:
return None
svc = json.loads(output)
return svc['spec']['clusterIP']
def kubectl(*args):
''' Run a kubectl cli command with a config file. Returns stdout and throws
an error if the command fails. '''
command = ['kubectl', '--kubeconfig=' + kubeclientconfig_path] + list(args)
hookenv.log('Executing {}'.format(command))
return check_output(command)
def kubectl_success(*args):
''' Runs kubectl with the given args. Returns True if successful, False if
not. '''
try:
kubectl(*args)
return True
except CalledProcessError:
return False
def kubectl_manifest(operation, manifest):
''' Wrap the kubectl creation command when using filepath resources
:param operation - one of get, create, delete, replace
:param manifest - filepath to the manifest
'''
# Deletions are a special case
if operation == 'delete':
# Ensure we immediately remove requested resources with --now
return kubectl_success(operation, '-f', manifest, '--now')
else:
# Guard against an error re-creating the same manifest multiple times
if operation == 'create':
# If we already have the definition, its probably safe to assume
# creation was true.
if kubectl_success('get', '-f', manifest):
hookenv.log('Skipping definition for {}'.format(manifest))
return True
# Execute the requested command that did not match any of the special
# cases above
return kubectl_success(operation, '-f', manifest)
def get_node_name():
kubelet_extra_args = parse_extra_args('kubelet-extra-args')
cloud_provider = kubelet_extra_args.get('cloud-provider', '')
if is_state('endpoint.aws.ready'):
cloud_provider = 'aws'
elif is_state('endpoint.gcp.ready'):
cloud_provider = 'gce'
elif is_state('endpoint.openstack.ready'):
cloud_provider = 'openstack'
elif is_state('endpoint.vsphere.ready'):
cloud_provider = 'vsphere'
elif is_state('endpoint.azure.ready'):
cloud_provider = 'azure'
if cloud_provider == 'aws':
return getfqdn().lower()
else:
return gethostname().lower()
def create_kubeconfig(kubeconfig, server, ca, key=None, certificate=None,
user='ubuntu', context='juju-context',
cluster='juju-cluster', password=None, token=None,
keystone=False):
'''Create a configuration for Kubernetes based on path using the supplied
arguments for values of the Kubernetes server, CA, key, certificate, user
context and cluster.'''
if not key and not certificate and not password and not token:
raise ValueError('Missing authentication mechanism.')
# token and password are mutually exclusive. Error early if both are
# present. The developer has requested an impossible situation.
# see: kubectl config set-credentials --help
if token and password:
raise ValueError('Token and Password are mutually exclusive.')
# Create the config file with the address of the master server.
cmd = 'kubectl config --kubeconfig={0} set-cluster {1} ' \
'--server={2} --certificate-authority={3} --embed-certs=true'
check_call(split(cmd.format(kubeconfig, cluster, server, ca)))
# Delete old users
cmd = 'kubectl config --kubeconfig={0} unset users'
check_call(split(cmd.format(kubeconfig)))
# Create the credentials using the client flags.
cmd = 'kubectl config --kubeconfig={0} ' \
'set-credentials {1} '.format(kubeconfig, user)
if key and certificate:
cmd = '{0} --client-key={1} --client-certificate={2} '\
'--embed-certs=true'.format(cmd, key, certificate)
if password:
cmd = "{0} --username={1} --password={2}".format(cmd, user, password)
# This is mutually exclusive from password. They will not work together.
if token:
cmd = "{0} --token={1}".format(cmd, token)
check_call(split(cmd))
# Create a default context with the cluster.
cmd = 'kubectl config --kubeconfig={0} set-context {1} ' \
'--cluster={2} --user={3}'
check_call(split(cmd.format(kubeconfig, context, cluster, user)))
# Make the config use this new context.
cmd = 'kubectl config --kubeconfig={0} use-context {1}'
check_call(split(cmd.format(kubeconfig, context)))
if keystone:
# create keystone user
cmd = 'kubectl config --kubeconfig={0} ' \
'set-credentials keystone-user'.format(kubeconfig)
check_call(split(cmd))
# create keystone context
cmd = 'kubectl config --kubeconfig={0} ' \
'set-context --cluster={1} ' \
'--user=keystone-user keystone'.format(kubeconfig, cluster)
check_call(split(cmd))
# use keystone context
cmd = 'kubectl config --kubeconfig={0} ' \
'use-context keystone'.format(kubeconfig)
check_call(split(cmd))
# manually add exec command until kubectl can do it for us
with open(kubeconfig, "r") as f:
content = f.read()
content = content.replace("""- name: keystone-user
user: {}""", """- name: keystone-user
user:
exec:
command: "/snap/bin/client-keystone-auth"
apiVersion: "client.authentication.k8s.io/v1beta1"
""")
with open(kubeconfig, "w") as f:
f.write(content)
def parse_extra_args(config_key):
elements = hookenv.config().get(config_key, '').split()
args = {}
for element in elements:
if '=' in element:
key, _, value = element.partition('=')
args[key] = value
else:
args[element] = 'true'
return args
def configure_kubernetes_service(key, service, base_args, extra_args_key):
db = unitdata.kv()
prev_args_key = key + service
prev_args = db.get(prev_args_key) or {}
extra_args = parse_extra_args(extra_args_key)
args = {}
for arg in prev_args:
# remove previous args by setting to null
args[arg] = 'null'
for k, v in base_args.items():
args[k] = v
for k, v in extra_args.items():
args[k] = v
cmd = ['snap', 'set', service] + ['%s=%s' % item for item in args.items()]
check_call(cmd)
db.set(prev_args_key, args)
def _snap_common_path(component):
return Path('/var/snap/{}/common'.format(component))
def cloud_config_path(component):
return _snap_common_path(component) / 'cloud-config.conf'
def _gcp_creds_path(component):
return _snap_common_path(component) / 'gcp-creds.json'
def _daemon_env_path(component):
return _snap_common_path(component) / 'environment'
def _cloud_endpoint_ca_path(component):
return _snap_common_path(component) / 'cloud-endpoint-ca.crt'
def encryption_config_path():
apiserver_snap_common_path = _snap_common_path('kube-apiserver')
encryption_conf_dir = apiserver_snap_common_path / 'encryption'
return encryption_conf_dir / 'encryption_config.yaml'
def write_gcp_snap_config(component):
# gcp requires additional credentials setup
gcp = endpoint_from_flag('endpoint.gcp.ready')
creds_path = _gcp_creds_path(component)
with creds_path.open('w') as fp:
os.fchmod(fp.fileno(), 0o600)
fp.write(gcp.credentials)
# create a cloud-config file that sets token-url to nil to make the
# services use the creds env var instead of the metadata server, as
# well as making the cluster multizone
comp_cloud_config_path = cloud_config_path(component)
comp_cloud_config_path.write_text('[Global]\n'
'token-url = nil\n'
'multizone = true\n')
daemon_env_path = _daemon_env_path(component)
if daemon_env_path.exists():
daemon_env = daemon_env_path.read_text()
if not daemon_env.endswith('\n'):
daemon_env += '\n'
else:
daemon_env = ''
if gcp_creds_env_key not in daemon_env:
daemon_env += '{}={}\n'.format(gcp_creds_env_key, creds_path)
daemon_env_path.parent.mkdir(parents=True, exist_ok=True)
daemon_env_path.write_text(daemon_env)
def write_openstack_snap_config(component):
# openstack requires additional credentials setup
openstack = endpoint_from_flag('endpoint.openstack.ready')
lines = [
'[Global]',
'auth-url = {}'.format(openstack.auth_url),
'region = {}'.format(openstack.region),
'username = {}'.format(openstack.username),
'password = {}'.format(openstack.password),
'tenant-name = {}'.format(openstack.project_name),
'domain-name = {}'.format(openstack.user_domain_name),
]
if openstack.endpoint_tls_ca:
cloud_endpoint_ca_path = _cloud_endpoint_ca_path(component)
cloud_endpoint_ca_path.write_text(base64.b64decode(
openstack.endpoint_tls_ca
).decode('utf-8'))
lines.append('ca-file = {}'.format(str(cloud_endpoint_ca_path)))
if any([openstack.subnet_id,
openstack.floating_network_id,
openstack.lb_method,
openstack.manage_security_groups]):
lines.append('')
lines.append('[LoadBalancer]')
if openstack.subnet_id:
lines.append('subnet-id = {}'.format(openstack.subnet_id))
if openstack.floating_network_id:
lines.append('floating-network-id = {}'.format(
openstack.floating_network_id))
if openstack.lb_method:
lines.append('lb-method = {}'.format(
openstack.lb_method))
if openstack.manage_security_groups:
lines.append('manage-security-groups = {}'.format(
openstack.manage_security_groups))
if any([openstack.bs_version,
openstack.trust_device_path,
openstack.ignore_volume_az]):
lines.append('')
lines.append('[BlockStorage]')
if openstack.bs_version is not None:
lines.append('bs-version = {}'.format(openstack.bs_version))
if openstack.trust_device_path is not None:
lines.append('trust-device-path = {}'.format(
openstack.trust_device_path))
if openstack.ignore_volume_az is not None:
lines.append('ignore-volume-az = {}'.format(
openstack.ignore_volume_az))
comp_cloud_config_path = cloud_config_path(component)
comp_cloud_config_path.write_text(''.join('{}\n'.format(l) for l in lines))
def write_azure_snap_config(component):
azure = endpoint_from_flag('endpoint.azure.ready')
comp_cloud_config_path = cloud_config_path(component)
comp_cloud_config_path.write_text(json.dumps({
'useInstanceMetadata': True,
'useManagedIdentityExtension': True,
'subscriptionId': azure.subscription_id,
'resourceGroup': azure.resource_group,
'location': azure.resource_group_location,
'vnetName': azure.vnet_name,
'vnetResourceGroup': azure.vnet_resource_group,
'subnetName': azure.subnet_name,
'securityGroupName': azure.security_group_name,
}))
def configure_kube_proxy(configure_prefix, api_servers, cluster_cidr):
kube_proxy_opts = {}
kube_proxy_opts['cluster-cidr'] = cluster_cidr
kube_proxy_opts['kubeconfig'] = kubeproxyconfig_path
kube_proxy_opts['logtostderr'] = 'true'
kube_proxy_opts['v'] = '0'
num_apis = len(api_servers)
kube_proxy_opts['master'] = api_servers[get_unit_number() % num_apis]
kube_proxy_opts['hostname-override'] = get_node_name()
if host.is_container():
kube_proxy_opts['conntrack-max-per-core'] = '0'
configure_kubernetes_service(configure_prefix, 'kube-proxy',
kube_proxy_opts, 'proxy-extra-args')
def get_unit_number():
return int(hookenv.local_unit().split('/')[1])