-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path__init__.py
More file actions
1850 lines (1536 loc) · 72.8 KB
/
__init__.py
File metadata and controls
1850 lines (1536 loc) · 72.8 KB
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import OrderedDict
from datetime import datetime, timedelta
import json
import logging
import operator
import os
import string
import time
from urllib.parse import urljoin
import base64
from django.conf import settings
from docker.auth import auth as docker_auth
from .states import PodState
import ruamel.yaml
import requests
from requests_toolbelt import user_agent
from .utils import dict_merge
from deis import __version__ as deis_version
logger = logging.getLogger(__name__)
# Ports and app type will be overwritten as required
SERVICE_TEMPLATE = """\
kind: Service
apiVersion: v1
metadata:
name: $name
labels:
app: $name
heritage: deis
annotations: {}
spec:
ports:
- name: http
port: 80
targetPort: 5000
protocol: TCP
selector:
app: $name
heritage: deis
"""
class KubeException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class KubeHTTPException(KubeException):
def __init__(self, response, errmsg, *args, **kwargs):
self.response = response
msg = errmsg.format(*args)
msg = "failed to {}: {} {}\n{}".format(
msg,
response.status_code,
response.reason,
response.json()
)
KubeException.__init__(self, msg, *args, **kwargs)
def unhealthy(status_code):
if not 200 <= status_code <= 299:
return True
return False
session = None
def get_session():
global session
if session is None:
with open('/var/run/secrets/kubernetes.io/serviceaccount/token') as token_file:
token = token_file.read()
session = requests.Session()
session.headers = {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
'User-Agent': user_agent('Deis Controller', deis_version)
}
session.verify = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'
return session
class KubeHTTPClient(object):
# used as the basis to check if a pod is ready
deploy_timeout = 120
apiversion = "v1"
def __init__(self):
self.url = settings.SCHEDULER_URL
self.session = get_session()
def log(self, namespace, message, level=logging.INFO):
"""Logs a message in the context of this application.
This prefixes log messages with a namespace "tag".
When it's seen, the message-- usually an application event of some
sort like releasing or scaling, will be considered as "belonging" to the application
instead of the controller and will be handled accordingly.
"""
logger.log(level, "[{}]: {}".format(namespace, message))
def deploy(self, namespace, name, image, entrypoint, command, **kwargs): # noqa
"""Scale RC or Deployment depending on what's requested"""
self.deploy_timeout = kwargs.get('deploy_timeout')
if kwargs.get('deployments', False):
self.deploy_deployment(namespace, name, image, entrypoint, command, **kwargs)
else:
self.deploy_rc(namespace, name, image, entrypoint, command, **kwargs)
def deploy_deployment(self, namespace, name, image, entrypoint, command, **kwargs): # noqa
app_type = kwargs.get('app_type')
routable = kwargs.get('routable', False)
envs = kwargs.get('envs', {})
port = envs.get('PORT', None)
# create a deployment if missing, otherwise update to trigger a release
try:
deployment = self.get_deployment(namespace, name).json()
# labels that represent the pod(s)
version = kwargs.get('version')
labels = {
'app': namespace,
'version': version,
'type': app_type,
'heritage': 'deis',
}
# this depends on the deployment object having the latest information
if deployment['spec']['template']['metadata']['labels'] == labels:
self.log(namespace, 'Deployment {} with release {} already exists. Stopping deploy'.format(name, version)) # noqa
return
except KubeException:
# create the initial deployment object (and the first revision)
self.create_deployment(namespace,
name,
image,
entrypoint,
command,
**kwargs)
else:
try:
# kick off a new revision of the deployment
self.update_deployment(namespace,
name,
image,
entrypoint,
command,
**kwargs)
except KubeException as e:
# rollback to the previous Deployment
kwargs['rollback'] = True
self.update_deployment(namespace,
name,
image,
entrypoint,
command,
**kwargs)
raise KubeException(
'There was a problem while deploying {} of {}-{}. '
'Going back to the previous release'.format(version, namespace, app_type)
) from e
# Make sure the application is routable and uses the correct port
# Done after the fact to let initial deploy settle before routing
# traffic to the application
self._update_application_service(namespace, name, app_type, port, routable)
def deploy_rc(self, namespace, name, image, entrypoint, command, **kwargs): # noqa
app_type = kwargs.get('app_type')
routable = kwargs.get('routable', False)
envs = kwargs.get('envs', {})
port = envs.get('PORT', None)
timeout = kwargs.get('deploy_timeout')
# Fetch old RC and create the new one for a release
old_rc = self.get_old_rc(namespace, app_type)
# If an RC already exists then stop processing of the deploy
try:
self.get_rc(namespace, name)
self.log(namespace, 'RC {} already exists. Stopping deploy'.format(name)) # noqa
return
except KubeHTTPException:
# make replicas 0 so scaling handles the work
replicas = kwargs.pop('replicas')
new_rc = self.create_rc(
namespace,
name,
image,
entrypoint,
command,
replicas=0,
**kwargs).json()
kwargs['replicas'] = replicas
# Get the desired number to scale to
if old_rc:
desired = int(old_rc["spec"]["replicas"])
else:
desired = kwargs['replicas']
self.log(namespace, 'No prior RC could be found for {}'.format(app_type))
# see if application or global deploy batches are defined
batches = kwargs.get('deploy_batches', None)
tags = kwargs.get('tags', {})
steps = self._get_deploy_steps(batches, tags)
batches = self._get_deploy_batches(steps, desired)
try:
count = 0
new_name = new_rc["metadata"]["name"]
for batch in batches:
count += batch
self.log(namespace, 'scaling release {} to {} out of final {}'.format(
new_name, count, desired
))
self._scale_rc(namespace, new_name, count, timeout)
if old_rc:
old_name = old_rc["metadata"]["name"]
self.log(namespace, 'scaling old release {} from original {} to {}'.format(
old_name, desired, (desired-count))
)
self._scale_rc(namespace, old_name, (desired-count), timeout)
except Exception as e:
# New release is broken. Clean up
# Remove new release of the RC
self.cleanup_release(namespace, new_rc, timeout)
# If there was a previous release then bring that back
if old_rc:
self._scale_rc(namespace, old_rc["metadata"]["name"], desired, timeout)
raise KubeException(
'Could not scale {} to {}. '
'Deleting and going back to old release'.format(
new_rc["metadata"]["name"], desired
)
) from e
# New release is live and kicking. Clean up old release
if old_rc:
self.cleanup_release(namespace, old_rc, timeout)
# Make sure the application is routable and uses the correct port
# Done after the fact to let initial deploy settle before routing
# traffic to the application
self._update_application_service(namespace, name, app_type, port, routable)
def cleanup_release(self, namespace, controller, timeout):
"""
Cleans up resources related to an application deployment
"""
# Deployment takes care of this in the API, RC does not
# Have the RC scale down pods and delete itself
self._scale_rc(namespace, controller['metadata']['name'], 0, timeout)
self.delete_rc(namespace, controller['metadata']['name'])
# Remove stray pods that the scale down will have missed (this can occassionally happen)
pods = self.get_pods(namespace, labels=controller['metadata']['labels']).json()
for pod in pods['items']:
if self.pod_deleted(pod):
continue
self.delete_pod(namespace, pod['metadata']['name'])
def _get_deploy_steps(self, batches, tags):
# if there is no batch information available default to available nodes for app
if not batches:
# figure out how many nodes the application can go on
steps = len(self.get_nodes(labels=tags).json()['items'])
else:
steps = int(batches)
return steps
def _get_deploy_batches(self, steps, desired):
# figure out what kind of batches the deploy is done in - 1 in, 1 out or higher
if desired < steps:
# do it all in one go
batches = [desired]
else:
# figure out the stepped deploy count and then see if there is a leftover
batches = [steps for n in set(range(1, (desired + 1))) if n % steps == 0]
if desired - sum(batches) > 0:
batches.append(desired - sum(batches))
return batches
def _update_application_service(self, namespace, name, app_type, port, routable=False):
"""Update application service with all the various required information"""
service = self.get_service(namespace, namespace).json()
old_service = service.copy() # in case anything fails for rollback
try:
# Update service information
if routable:
service['metadata']['labels']['router.deis.io/routable'] = 'true'
# Set app type if there is not one available
if 'type' not in service['spec']['selector']:
service['spec']['selector']['type'] = app_type
# Find if target port exists already, update / create as required
if routable:
for pos, item in enumerate(service['spec']['ports']):
if item['port'] == 80 and port != item['targetPort']:
# port 80 is the only one we care about right now
service['spec']['ports'][pos]['targetPort'] = int(port)
self.update_service(namespace, namespace, data=service)
except Exception as e:
# Fix service to old port and app type
self.update_service(namespace, namespace, data=old_service)
raise KubeException(str(e)) from e
def scale(self, namespace, name, image, entrypoint, command, **kwargs):
"""Scale RC or Deployment depending on what's requested"""
self.deploy_timeout = kwargs.get('deploy_timeout')
if kwargs.get('deployments', False):
self.scale_deployment(namespace, name, image, entrypoint, command, **kwargs)
else:
self.scale_rc(namespace, name, image, entrypoint, command, **kwargs)
def scale_deployment(self, namespace, name, image, entrypoint, command, **kwargs):
try:
self.get_deployment(namespace, name)
except KubeHTTPException as e:
if e.response.status_code == 404:
# create missing deployment - deleted if it fails
try:
self.create_deployment(namespace, name, image, entrypoint, command, **kwargs)
except KubeException:
self.delete_deployment(namespace, name)
raise
# let the scale failure bubble up
self._scale_deployment(namespace, name, image, entrypoint, command, **kwargs)
def scale_rc(self, namespace, name, image, entrypoint, command, **kwargs):
replicas = kwargs.pop('replicas')
try:
self.get_rc(namespace, name)
except KubeHTTPException as e:
if e.response.status_code == 404:
# add RC if it is missing for the namespace
try:
# Create RC with scale as 0 and then scale to get pod monitoring
kwargs['replicas'] = 0
self.create_rc(namespace, name, image, entrypoint, command, **kwargs)
except KubeException:
logger.exception("Creating RC {} failed".format(name))
raise
# let the scale failure bubble up
self._scale_rc(namespace, name, replicas, kwargs.get('deploy_timeout'))
def _build_pod_manifest(self, namespace, name, image, **kwargs):
app_type = kwargs.get('app_type')
build_type = kwargs.get('build_type')
# labels that represent the pod(s)
labels = {
'app': namespace,
'version': kwargs.get('version'),
'type': app_type,
'heritage': 'deis',
}
# create base pod structure
manifest = {
'kind': 'Pod',
'apiVersion': 'v1',
'metadata': {
'name': name,
'labels': labels
},
'spec': {}
}
# pod manifest spec
spec = manifest['spec']
# what should the pod do if it exits
spec['restartPolicy'] = kwargs.get('restartPolicy', 'Always')
# apply tags as needed to restrict pod to particular node(s)
spec['nodeSelector'] = kwargs.get('tags', {})
# How long until a pod is forcefully terminated
spec['terminationGracePeriodSeconds'] = settings.KUBERNETES_POD_TERMINATION_GRACE_PERIOD_SECONDS # noqa
# set the image pull policy that is associated with the application container
kwargs['image_pull_policy'] = settings.DOCKER_BUILDER_IMAGE_PULL_POLICY
# mix in default environment information deis may require
default_env = {
'DEIS_APP': namespace,
'WORKFLOW_RELEASE': kwargs.get("version")
}
# Check if it is a slug builder image.
if build_type == "buildpack":
# only buildpack apps need access to object storage
try:
self.get_secret(namespace, 'objectstorage-keyfile')
except KubeException:
secret = self.get_secret('deis', 'objectstorage-keyfile').json()
self.create_secret(namespace, 'objectstorage-keyfile', secret['data'])
# add the required volume to the top level pod spec
spec['volumes'] = [{
'name': 'objectstorage-keyfile',
'secret': {
'secretName': 'objectstorage-keyfile'
}
}]
# added to kwargs to send to the container function
kwargs['volumeMounts'] = [{
'name': 'objectstorage-keyfile',
'mountPath': '/var/run/secrets/deis/objectstore/creds',
'readOnly': True
}]
default_env['SLUG_URL'] = image
default_env['BUILDER_STORAGE'] = os.getenv("APP_STORAGE")
default_env['DEIS_MINIO_SERVICE_HOST'] = os.getenv("DEIS_MINIO_SERVICE_HOST")
default_env['DEIS_MINIO_SERVICE_PORT'] = os.getenv("DEIS_MINIO_SERVICE_PORT")
# overwrite image so slugrunner image is used in the container
image = settings.SLUGRUNNER_IMAGE
# slugrunner pull policy
kwargs['image_pull_policy'] = settings.SLUG_BUILDER_IMAGE_PULL_POLICY
envs = kwargs.get('envs', {})
default_env.update(envs)
kwargs['envs'] = default_env
# create the base container
container = {}
# process to call
if kwargs.get('command', []):
container['command'] = kwargs.get('command')
if kwargs.get('args', []):
container['args'] = kwargs.get('args')
# set information to the application container
kwargs['image'] = image
container_name = namespace + '-' + app_type
self._set_container(namespace, container_name, container, **kwargs)
# add image to the mix
self._set_image_secret(spec, namespace, **kwargs)
spec['containers'] = [container]
return manifest
def run(self, namespace, name, image, entrypoint, command, **kwargs):
"""Run a one-off command."""
self.log(namespace, 'run {}, img {}, entrypoint {}, cmd "{}"'.format(
name, image, entrypoint, command)
)
# force the app_type
kwargs['app_type'] = 'run'
# run pods never restart
kwargs['restartPolicy'] = 'Never'
kwargs['command'] = entrypoint
kwargs['args'] = command
manifest = self._build_pod_manifest(namespace, name, image, **kwargs)
url = self._api("/namespaces/{}/pods", namespace)
response = self.session.post(url, json=manifest)
if unhealthy(response.status_code):
raise KubeHTTPException(response, 'create Pod in Namespace "{}"', namespace)
# wait for run pod to start - use the same function as scale
labels = manifest['metadata']['labels']
containers = manifest['spec']['containers']
self._wait_until_pods_are_ready(
namespace,
containers,
labels,
desired=1,
timeout=kwargs.get('deploy_timeout')
)
try:
# give pod 20 minutes to execute (after it got into ready state)
# this is a fairly arbitrary limit but the gunicorn worker / LBs
# will make this timeout around 20 anyway.
# TODO: Revisit in the future so it can run longer
state = 'up' # pod is still running
waited = 0
timeout = 1200 # 20 minutes
while (state == 'up' and waited < timeout):
response = self.get_pod(namespace, name)
pod = response.json()
state = str(self.pod_state(pod))
# default data
exit_code = 0
waited += 1
time.sleep(1)
if state == 'down': # run finished successfully
exit_code = 0 # successful run
elif state == 'crashed': # run failed
pod_state = pod['status']['containerStatuses'][0]['state']
exit_code = pod_state['terminated']['exitCode']
# timed out!
if waited == timeout:
raise KubeException('Timed out (20 mins) while running')
# grab log information
log = self._pod_log(namespace, name)
log.encoding = 'utf-8' # defaults to "ISO-8859-1" otherwise...
return exit_code, log.text
finally:
# cleanup
self.delete_pod(namespace, name)
def _set_container(self, namespace, container_name, data, **kwargs): # noqa
"""Set app container information (env, healthcheck, etc) on a Pod"""
app_type = kwargs.get('app_type')
mem = kwargs.get('memory', {}).get(app_type)
cpu = kwargs.get('cpu', {}).get(app_type)
env = kwargs.get('envs', {})
# container name
data['name'] = container_name
# set the image to use
data['image'] = kwargs.get('image')
# set the image pull policy for the above image
data['imagePullPolicy'] = kwargs.get('image_pull_policy')
# add in any volumes that need to be mounted into the container
data['volumeMounts'] = kwargs.get('volumeMounts', [])
# create env list if missing
if 'env' not in data:
data['env'] = []
if env:
# env vars are stored in secrets and mapped to env in k8s
try:
labels = {
'version': kwargs.get('version'),
'type': 'env'
}
# secrets use dns labels for keys, map those properly here
secrets_env = {}
for key, value in env.items():
secrets_env[key.lower().replace('_', '-')] = str(value)
# dictionary sorted by key
secrets_env = OrderedDict(sorted(secrets_env.items(), key=lambda t: t[0]))
secret_name = "{}-{}-env".format(namespace, kwargs.get('version'))
self.get_secret(namespace, secret_name)
except KubeHTTPException:
self.create_secret(namespace, secret_name, secrets_env, labels=labels)
else:
self.update_secret(namespace, secret_name, secrets_env, labels=labels)
for key in env.keys():
item = {
"name": key,
"valueFrom": {
"secretKeyRef": {
"name": secret_name,
# k8s doesn't allow _ so translate to -, see above
"key": key.lower().replace('_', '-')
}
}
}
# add value to env hash. Overwrite hardcoded values if need be
match = next((k for k, e in enumerate(data["env"]) if e['name'] == key), None)
if match is not None:
data["env"][match] = item
else:
data["env"].append(item)
# Inject debugging if workflow is in debug mode
if os.environ.get("DEIS_DEBUG", False):
data["env"].append({
"name": "DEIS_DEBUG",
"value": "1"
})
# list sorted by dict key name
data['env'].sort(key=operator.itemgetter('name'))
if mem or cpu:
data["resources"] = {"limits": {}}
if mem:
if mem[-2:-1].isalpha() and mem[-1].isalpha():
mem = mem[:-1]
mem = mem + "i"
data["resources"]["limits"]["memory"] = mem
if cpu:
data["resources"]["limits"]["cpu"] = cpu
# add in healthchecks
healthchecks = kwargs.get('healthcheck', None)
if healthchecks and kwargs.get('routable', False):
# check if a port is present. if not, auto-populate it
# TODO: rip this out when we stop supporting deis config:set HEALTHCHECK_URL
if (
healthchecks.get('livenessProbe') is not None and
healthchecks['livenessProbe'].get('httpGet') is not None and
healthchecks['livenessProbe']['httpGet'].get('port') is None
):
healthchecks['livenessProbe']['httpGet']['port'] = env['PORT']
data.update(healthchecks)
else:
self._default_readiness_probe(data, kwargs.get('build_type'), env.get('PORT', None))
def _set_image_secret(self, data, namespace, **kwargs):
"""
Take registry information and set as an imagePullSecret for an RC / Deployment
http://kubernetes.io/docs/user-guide/images/#specifying-imagepullsecrets-on-a-pod
"""
registry = kwargs.get('registry', {})
if not registry:
return
# try to get the hostname information
hostname = registry.get('hostname', None)
if not hostname:
hostname, _ = docker_auth.split_repo_name(kwargs.get('image'))
# create / update private registry secret
auth = bytes('{}:{}'.format(registry.get('username'), registry.get('password')), 'UTF-8')
# value has to be a base64 encoded JSON
docker_config = json.dumps({
"auths": {
hostname: {
"auth": base64.b64encode(auth).decode(encoding='UTF-8'),
"email": 'not@valid.id'
}
}
})
secret_data = {'.dockerconfigjson': docker_config}
secret_name = 'private-registry'
try:
self.get_secret(namespace, secret_name)
except KubeHTTPException:
self.create_secret(
namespace,
secret_name,
secret_data,
secret_type='kubernetes.io/dockerconfigjson'
)
else:
self.update_secret(
namespace,
secret_name,
secret_data,
secret_type='kubernetes.io/dockerconfigjson'
)
# apply image pull secret to a Pod spec
data['imagePullSecrets'] = [{'name': secret_name}]
def pod_state(self, pod):
# See "Pod Phase" at http://kubernetes.io/docs/user-guide/pod-states/
if pod is None:
return PodState.destroyed
states = {
'Pending': PodState.initializing,
'ContainerCreating': PodState.creating,
'Starting': PodState.starting,
'Running': PodState.up,
'Terminating': PodState.terminating,
'Succeeded': PodState.down,
'Failed': PodState.crashed,
'Unknown': PodState.error,
}
# being in a Pending state can mean different things, introspecting app container first
if pod['status']['phase'] == 'Pending':
pod_state, _ = self._pod_pending_status(pod)
# being in a running state can mean a pod is starting, actually running or terminating
elif pod['status']['phase'] == 'Running':
# is the readiness probe passing?
pod_state = self._pod_readiness_status(pod)
if pod_state in ['Starting', 'Terminating']:
return states[pod_state]
elif pod_state == 'Running' and self._pod_liveness_status(pod):
# is the pod ready to serve requests?
return states[pod_state]
else:
# if no match was found for deis mapping then passthrough the real state
pod_state = pod['status']['phase']
return states.get(pod_state, pod_state)
def _api(self, tmpl, *args):
"""Return a fully-qualified Kubernetes API URL from a string template with args."""
# FIXME better way of determining API version based on requested component
# extensions use apis and not api
# TODO this needs to be aware that deployments / rs could be top level in future releases
# https://github.com/deis/controller/issues/875
prefix = 'api'
apiversion = 'v1'
components = tmpl.strip('/').split('/')
if len(components) > 2:
component = components[2]
if component in ['deployments', 'replicasets']:
prefix = 'apis'
apiversion = 'extensions/v1beta1'
url = "/{}/{}".format(prefix, apiversion) + tmpl.format(*args)
return urljoin(self.url, url)
def _selectors(self, **kwargs):
query = {}
# labels and fields are encoded slightly differently than python-requests can do
labels = kwargs.get('labels', {})
if labels:
selectors = []
for key, value in labels.items():
# http://kubernetes.io/docs/user-guide/labels/#set-based-requirement
if '__notin' in key:
key = key.replace('__notin', '')
selectors.append('{} notin({})'.format(key, ','.join(value)))
# list is automagically a in()
elif '__in' in key or isinstance(value, list):
key = key.replace('__in', '')
selectors.append('{} in({})'.format(key, ','.join(value)))
elif value is None:
# allowing a check if a label exists (or not) without caring about value
selectors.append(key)
# http://kubernetes.io/docs/user-guide/labels/#equality-based-requirement
elif isinstance(value, str):
selectors.append('{}={}'.format(key, value))
query['labelSelector'] = ','.join(selectors)
fields = kwargs.get('fields', {})
if fields:
fields = ['{}={}'.format(key, value) for key, value in fields.items()]
query['fieldSelector'] = ','.join(fields)
# Which resource version to start from. Otherwise starts from the beginning
resource_version = kwargs.get('resourceVersion', None)
if resource_version:
query['resourceVersion'] = resource_version
# If output should pretty print, only True / False allowed
pretty = bool(kwargs.get('pretty', False))
if pretty:
query['pretty'] = pretty
return query
# NAMESPACE #
def get_namespace_events(self, namespace, **kwargs):
url = self._api("/namespaces/{}/events", namespace)
response = self.session.get(url, params=self._selectors(**kwargs))
if unhealthy(response.status_code):
raise KubeHTTPException(response, "get Events in Namespace {}", namespace)
return response
def get_namespace(self, namespace):
url = self._api("/namespaces/{}/", namespace)
response = self.session.get(url)
if unhealthy(response.status_code):
raise KubeHTTPException(response, 'get Namespace "{}"', namespace)
return response
def get_namespaces(self, **kwargs):
url = self._api("/namespaces")
response = self.session.get(url, params=self._selectors(**kwargs))
if unhealthy(response.status_code):
raise KubeHTTPException(response, 'get Namespaces')
return response
def create_namespace(self, namespace):
url = self._api("/namespaces")
data = {
"kind": "Namespace",
"apiVersion": "v1",
"metadata": {
"name": namespace
}
}
response = self.session.post(url, json=data)
if not response.status_code == 201:
raise KubeHTTPException(response, "create Namespace {}".format(namespace))
return response
def delete_namespace(self, namespace):
url = self._api("/namespaces/{}", namespace)
response = self.session.delete(url)
if response.status_code == 404:
logger.warn('delete Namespace "{}": not found'.format(namespace))
elif response.status_code != 200:
raise KubeHTTPException(response, 'delete Namespace "{}"', namespace)
return response
# REPLICATION CONTROLLER #
def get_old_rc(self, namespace, app_type):
labels = {
'app': namespace,
'type': app_type
}
controllers = self.get_rcs(namespace, labels=labels).json()
if len(controllers['items']) == 0:
return False
return controllers['items'][0]
def get_rc(self, namespace, name):
url = self._api("/namespaces/{}/replicationcontrollers/{}", namespace, name)
response = self.session.get(url)
if unhealthy(response.status_code):
raise KubeHTTPException(
response,
'get ReplicationController "{}" in Namespace "{}"', name, namespace
)
return response
def get_rcs(self, namespace, **kwargs):
url = self._api("/namespaces/{}/replicationcontrollers", namespace)
response = self.session.get(url, params=self._selectors(**kwargs))
if unhealthy(response.status_code):
raise KubeHTTPException(
response,
'get ReplicationControllers in Namespace "{}"', namespace
)
return response
def _wait_until_pods_terminate(self, namespace, labels, current, desired):
"""Wait until all the desired pods are terminated"""
# http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_podspec
# https://github.com/kubernetes/kubernetes/blob/release-1.2/docs/devel/api-conventions.md#metadata
# http://kubernetes.io/docs/user-guide/pods/#termination-of-pods
timeout = settings.KUBERNETES_POD_TERMINATION_GRACE_PERIOD_SECONDS
delta = current - desired
self.log(namespace, "waiting for {} pods to be terminated ({}s timeout)".format(delta, timeout)) # noqa
for waited in range(timeout):
pods = self.get_pods(namespace, labels=labels).json()
count = len(pods['items'])
# see if any pods are past their terminationGracePeriodsSeconds (as in stuck)
# seems to be a problem in k8s around that:
# https://github.com/kubernetes/kubernetes/search?q=terminating&type=Issues
# these will be eventually GC'ed by k8s, ignoring them for now
for pod in pods['items']:
# remove pod if it is passed the graceful termination period
if self.pod_deleted(pod):
count -= 1
# stop when all pods are terminated as expected
if count == desired:
break
if waited > 0 and (waited % 10) == 0:
self.log(namespace, "waited {}s and {} pods out of {} are fully terminated".format(waited, (delta - count), delta)) # noqa
time.sleep(1)
self.log(namespace, "{} pods are terminated".format(delta))
def _deploy_probe_timeout(self, timeout, namespace, labels, containers):
"""
Added in additional timeouts based on readiness and liveness probe
Uses the max of the two instead of combining them as the checks are stacked.
"""
container_name = '{}-{}'.format(labels['app'], labels['type'])
container = self._find_container(container_name, containers)
# get health info from container
added_timeout = []
if 'readinessProbe' in container:
# If there is initial delay on the readiness check then timeout needs to be higher
# this is to account for kubernetes having readiness check report as failure until
# the initial delay period is up
added_timeout.append(int(container['readinessProbe'].get('initialDelaySeconds', 50)))
if 'livenessProbe' in container:
# If there is initial delay on the readiness check then timeout needs to be higher
# this is to account for kubernetes having liveness check report as failure until
# the initial delay period is up
added_timeout.append(int(container['livenessProbe'].get('initialDelaySeconds', 50)))
if added_timeout:
delay = max(added_timeout)
self.log(namespace, "adding {}s on to the original {}s timeout to account for the initial delay specified in the liveness / readiness probe".format(delay, timeout)) # noqa
timeout += delay
return timeout
def _wait_until_pods_are_ready(self, namespace, containers, labels, desired, timeout): # noqa
# If desired is 0 then there is no ready state to check on
if desired == 0:
return
timeout = self._deploy_probe_timeout(timeout, namespace, labels, containers)
self.log(namespace, "waiting for {} pods in {} namespace to be in services ({}s timeout)".format(desired, namespace, timeout)) # noqa
# Ensure the minimum desired number of pods are available
waited = 0
while waited < timeout:
count = 0 # ready pods
pods = self.get_pods(namespace, labels=labels).json()
for pod in pods['items']:
# Get more information on why a pod is pending
if pod['status']['phase'] == 'Pending':
reason, message = self._pod_pending_status(pod)
# If pulling an image is taking long then increase the timeout
timeout += self._handle_pod_long_image_pulling(pod, reason)
# handle errors and bubble up if need be
self._handle_pod_image_errors(pod, reason, message)
# now that state is running time to see if probes are passing
if self._pod_ready(pod):
count += 1
# Find out if any pod goes beyond the Running (up) state
# Allow that to happen to account for very fast `deis run` as
# an example. Code using this function will account for it
state = self.pod_state(pod)
if isinstance(state, PodState) and state > PodState.up:
count += 1
if count == desired:
break
if waited > 0 and (waited % 10) == 0:
self.log(namespace, "waited {}s and {} pods are in service".format(waited, count))
# increase wait time without dealing with jitters from above code
waited += 1
time.sleep(1)
# timed out
if waited > timeout:
self.log(namespace, 'timed out ({}s) waiting for pods to come up in namespace {}'.format(timeout, namespace)) # noqa
self.log(namespace, "{} out of {} pods are in service".format(count, desired)) # noqa
def _scale_rc(self, namespace, name, desired, timeout):
rc = self.get_rc(namespace, name).json()
current = int(rc['spec']['replicas'])
if desired == current:
self.log(namespace, "Not scaling RC {} to {} replicas. Already at desired replicas".format(name, desired)) # noqa
return
elif desired != rc['spec']['replicas']: # RC needs new replica count
# Set the new desired replica count
rc['spec']['replicas'] = desired
self.log(namespace, "scaling RC {} from {} to {} replicas".format(name, current, desired)) # noqa
self.update_rc(namespace, name, rc)
self._wait_until_rc_is_updated(namespace, name)
# Double check enough pods are in the required state to service the application
labels = rc['metadata']['labels']
containers = rc['spec']['template']['spec']['containers']
self._wait_until_pods_are_ready(namespace, containers, labels, desired, timeout)