-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path__init__.py
More file actions
1136 lines (959 loc) · 37.4 KB
/
__init__.py
File metadata and controls
1136 lines (959 loc) · 37.4 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
import json
import logging
import os
import string
import time
from urllib.parse import urljoin
import base64
from django.conf import settings
from docker import Client
from .states import JobState
from .abstract import AbstractSchedulerClient
import requests
from .utils import dict_merge
logger = logging.getLogger(__name__)
# Used for one off command runs on pods
POD_BTEMPLATE = """\
{
"kind": "Pod",
"apiVersion": "$version",
"metadata": {
"name": "$id"
},
"spec": {
"containers": [
{
"name": "$id",
"image": "quay.io/deisci/slugrunner:v2-beta",
"env": [
{
"name":"PORT",
"value":"5000"
},
{
"name":"SLUG_URL",
"value":"$image"
},
{
"name": "DOCKERIMAGE",
"value":"1"
}
],
"volumeMounts":[
{
"name":"minio-user",
"mountPath":"/var/run/secrets/object/store",
"readOnly":true
}
]
}
],
"volumes":[
{
"name":"minio-user",
"secret":{
"secretName":"minio-user"
}
}
],
"restartPolicy": "Never"
}
}
"""
POD_TEMPLATE = """\
{
"kind": "Pod",
"apiVersion": "$version",
"metadata": {
"name": "$id"
},
"spec": {
"containers": [
{
"name": "$id",
"image": "$image"
}
],
"restartPolicy": "Never"
}
}
"""
RCD_TEMPLATE = """\
{
"kind": "ReplicationController",
"apiVersion": "$version",
"metadata": {
"name": "$name",
"labels": {
"app": "$id",
"heritage": "deis"
}
},
"spec": {
"replicas": $num,
"selector": {
"app": "$id",
"version": "$appversion",
"type": "$type",
"heritage": "deis"
},
"template": {
"metadata": {
"labels": {
"app": "$id",
"version": "$appversion",
"type": "$type",
"heritage": "deis"
}
},
"spec": {
"containers": [
{
"name": "$containername",
"image": "$image",
"env": [
{
"name":"DEIS_APP",
"value":"$id"
},
{
"name":"DEIS_RELEASE",
"value":"$appversion"
}
]
}
],
"nodeSelector": {}
}
}
}
}
"""
RCB_TEMPLATE = """\
{
"kind": "ReplicationController",
"apiVersion": "$version",
"metadata": {
"name": "$name",
"labels": {
"app": "$id",
"heritage": "deis"
}
},
"spec": {
"replicas": $num,
"selector": {
"app": "$id",
"version": "$appversion",
"type": "$type",
"heritage": "deis"
},
"template": {
"metadata": {
"labels": {
"app": "$id",
"version": "$appversion",
"type": "$type",
"heritage": "deis"
}
},
"spec": {
"containers": [
{
"name": "$containername",
"image": "quay.io/deisci/slugrunner:v2-beta",
"imagePullPolicy": "Always",
"env": [
{
"name":"PORT",
"value":"5000"
},
{
"name":"SLUG_URL",
"value":"$image"
},
{
"name":"DEIS_APP",
"value":"$id"
},
{
"name":"DEIS_RELEASE",
"value":"$appversion"
},
{
"name": "DOCKERIMAGE",
"value":"1"
}
],
"volumeMounts":[
{
"name":"minio-user",
"mountPath":"/var/run/secrets/object/store",
"readOnly":true
}
]
}
],
"nodeSelector": {},
"volumes":[
{
"name":"minio-user",
"secret":{
"secretName":"minio-user"
}
}
]
}
}
}
}
"""
# Ports and app type will be overwritten as required
SERVICE_TEMPLATE = """\
{
"kind": "Service",
"apiVersion": "$version",
"metadata": {
"name": "$name",
"labels": {
"app": "$name"
},
"annotations": {}
},
"spec": {
"ports": [
{
"name": "http",
"port": 80,
"targetPort": 8080,
"protocol": "TCP"
}
],
"selector": {
"app": "$name",
"type": "web",
"heritage": "deis"
}
}
}
"""
SECRET_TEMPLATE = """\
{
"kind": "Secret",
"apiVersion": "$version",
"metadata": {
"name": "$name",
"namespace": "$id"
},
"type": "Opaque",
"data": {}
}
"""
class KubeException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class KubeHTTPException(KubeException):
def __init__(self, *args, **kwargs):
self.response = kwargs.pop('response', object)
KubeException.__init__(self, *args, **kwargs)
def error(response, errmsg, *args):
errmsg = errmsg.format(*args)
errmsg = "failed to {}: {} {}\n{}".format(
errmsg,
response.status_code,
response.reason,
response.json()
)
raise KubeHTTPException(errmsg, response=response)
def unhealthy(status_code):
if not 200 <= status_code <= 299:
return True
return False
class KubeHTTPClient(AbstractSchedulerClient):
def __init__(self, target):
super(KubeHTTPClient, self).__init__(target)
self.url = settings.SCHEDULER_URL
self.registry = settings.REGISTRY_URL
self.apiversion = "v1"
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',
}
# TODO: accessing the k8s api server by IP address rather than hostname avoids
# intermittent DNS errors, but at the price of disabling cert verification.
# session.verify = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'
session.verify = False
self.session = session
def deploy(self, namespace, name, image, command, **kwargs):
logger.debug('deploy {}, img {}, params {}, cmd "{}"'.format(name, image, kwargs, command))
app_type = kwargs.get('app_type')
# Fetch service
service = self._get_service(namespace, namespace).json()
old_service = service.copy() # in case anything fails for rollback
# Update service information
# Make sure the router knows what to do with this
# TODO this should potentially be higher up in the flow
if app_type in ['web', 'cmd']:
# see http://docs.deis.io/en/latest/using_deis/process-types/#web-vs-cmd-process-types
service['metadata']['labels']['router.deis.io/routable'] = 'true'
# Set app type
if (
'type' not in service['spec']['selector'] or
app_type != service['spec']['selector']['type']
):
service['spec']['selector']['type'] = app_type
# Find if target port exists already, which it also may not
port = self._get_port(image)
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'] = port
self._update_service(namespace, namespace, data=service)
# Fetch old RC and create the new one for a release
old_rc = self._get_old_rc(namespace, app_type)
new_rc = self._create_rc(namespace, name, image, command, **kwargs)
# Get the desired number to scale to
desired = 1
if old_rc:
desired = int(old_rc["spec"]["replicas"])
try:
count = 1
while desired >= count:
logger.debug('scaling release {} to {} out of final {}'.format(
new_rc["metadata"]["name"], count, desired
))
self._scale_rc(namespace, new_rc["metadata"]["name"], count)
logger.debug('scaled up pod number {} for {}'.format(
count, new_rc["metadata"]["name"]
))
if old_rc:
logger.debug('scaling old release {} from original {} to {}'.format(
old_rc["metadata"]["name"], desired, (desired-count))
)
self._scale_rc(namespace, old_rc["metadata"]["name"], (desired-count))
logger.debug('scaled down pod number {} for {}'.format(
count, old_rc["metadata"]["name"]
))
count += 1
except Exception as e:
logger.error('Could not scale {} to {}. Deleting and going back to old release'.format(
new_rc["metadata"]["name"], desired)
)
# Fix service to old port and app type
self._update_service(namespace, namespace, data=old_service)
# Remove old release
self._scale_rc(namespace, new_rc["metadata"]["name"], 0)
self._delete_rc(namespace, new_rc["metadata"]["name"])
# Bring back old release if available
if old_rc:
self._scale_rc(namespace, old_rc["metadata"]["name"], desired)
raise RuntimeError('{} (deploy): {}'.format(name, e))
if old_rc:
self._delete_rc(namespace, old_rc["metadata"]["name"])
def scale(self, namespace, name, image, command, **kwargs):
logger.debug('scale {}, img {}, params {}, cmd "{}"'.format(name, image, kwargs, command))
if unhealthy(self._get_rc_status(namespace, name)):
# add RC if it is missing for the namespace
try:
self._create_rc(namespace, name, image, command, **kwargs)
except KubeException as e:
logger.debug("Creating RC failed because of: {}".format(str(e)))
raise RuntimeError('{} (RC): {}'.format(name, e))
try:
self._scale_rc(namespace, name, kwargs.get('num'))
except KubeException as e:
logger.debug("Scaling failed because of: {}".format(str(e)))
old = self._get_rc(namespace, name).json()
self._scale_rc(namespace, name, old['spec']['replicas'])
raise RuntimeError('{} (Scale): {}'.format(name, e))
def create(self, namespace, **kwargs):
"""Create a basic structure for an application in k8s"""
logger.debug('create {}'.format(namespace))
try:
# Create essential resources
try:
self._get_namespace(namespace)
except KubeException:
self._create_namespace(namespace)
try:
self._get_secret(namespace, 'minio-user')
except KubeException:
self._create_minio_secret(namespace)
try:
self._get_service(namespace, namespace)
except KubeException:
self._create_service(namespace, namespace)
except KubeException as e:
# Blow it all away only if something horrible happens
logger.debug(e)
self._delete_namespace(namespace)
raise
def start(self, name):
"""Start a container."""
pass
def stop(self, name):
"""Stop a container."""
pass
def destroy(self, namespace):
"""Destroy a application by deleting its namespace."""
logger.debug("destroy {}".format(namespace))
self._delete_namespace(namespace)
# wait 30 seconds for termination
for _ in range(30):
try:
self._get_namespace(namespace).json()
except KubeException:
break
def run(self, name, image, entrypoint, command, **kwargs):
"""Run a one-off command."""
logger.debug('run {}, img {}, entrypoint {}, cmd "{}"'.format(
name, image, entrypoint, command))
appname = name.split('_')[0]
name = name.replace('.', '-').replace('_', '-')
imgurl = self.registry + '/' + image
POD = POD_TEMPLATE
if image.startswith('http://') or image.startswith('https://'):
POD = POD_BTEMPLATE
imgurl = image
l = {
'id': name,
'version': self.apiversion,
'image': imgurl,
}
template = string.Template(POD).substitute(l)
if command.startswith('-c '):
args = command.split(' ', 1)
args[1] = args[1][1:-1]
else:
args = [command[1:-1]]
js_template = json.loads(template)
containers = js_template['spec']['containers'][0]
containers['command'] = [entrypoint]
containers['args'] = args
self._set_environment(containers, **kwargs)
url = self._api("/namespaces/{}/pods", appname)
resp = self.session.post(url, json=js_template)
if unhealthy(resp.status_code):
error(resp, 'create Pod in Namespace "{}"', appname)
data = ''
duration = 30
iteration = 1
while(iteration < duration):
try:
response = self._get_pod(appname, name)
data = response.text
pod = response.json()
if pod['status']['phase'] == 'Succeeded':
response = self._pod_log(appname, name)
response.encoding = 'utf-8' # defaults to "ISO-8859-1" otherwise...
log = response.text
self._delete_pod(appname, name)
return 0, log
if pod['status']['phase'] == 'Running':
if iteration > 28:
duration = duration + 1
except:
break
iteration = iteration + 1
time.sleep(1)
if iteration >= duration:
error(resp, 'Pod start took more than 30 seconds', appname)
return 0, data
if pod['status']['phase'] == 'Failed':
pod_state = pod['status']['containerStatuses'][0]['state']
err_code = pod_state['terminated']['exitCode']
self._delete_pod(appname, name)
return err_code, data
return 0, data
def _set_environment(self, json_data, **kwargs):
app_type = kwargs.get('app_type')
mem = kwargs.get('memory', {}).get(app_type)
cpu = kwargs.get('cpu', {}).get(app_type)
env = kwargs.get('envs', {})
if env:
for key, value in env.items():
json_data["env"].append({
"name": key,
"value": str(value)
})
# Inject debugging if workflow is in debug mode
if os.environ.get("DEBUG", False):
json_data["env"].append({
"name": "DEBUG",
"value": "1"
})
if mem or cpu:
json_data["resources"] = {"limits": {}}
if mem:
if mem[-2:-1].isalpha() and mem[-1].isalpha():
mem = mem[:-1]
mem = mem + "i"
json_data["resources"]["limits"]["memory"] = mem
if cpu:
json_data["resources"]["limits"]["cpu"] = cpu
def state(self, name):
"""Display the state of a container."""
try:
appname = name.split('_')[0]
name = name.split('.')
name = name[0] + '-' + name[1]
name = name.replace('_', '-')
# FIXME fetch a singular pod instead of *all* pods
pods = self._get_pods(appname)
parsed_json = pods.json()
for pod in parsed_json["items"]:
if pod["metadata"]["generateName"] == name + "-":
return self.resolve_state(pod)
return JobState.destroyed
except Exception as err:
logger.warn(err)
return JobState.error
def resolve_state(self, pod):
if pod is None:
return JobState.destroyed
# See "Pod Phase" at http://kubernetes.io/v1.1/docs/user-guide/pod-states.html
states = {
'Pending': JobState.initialized,
'Starting': JobState.starting,
'Running': JobState.up,
'Terminating': JobState.terminating,
'Succeeded': JobState.down,
'Failed': JobState.crashed,
'Unknown': JobState.error,
}
# being in a running state can mean a pod is starting, actually running or terminating
if pod['status']['phase'] == 'Running':
# is the readiness probe passing?
container_status = self._pod_readiness_status(pod)
if container_status in ['Starting', 'Terminating']:
return states[container_status]
elif container_status == 'Running' and self._pod_liveness_status(pod):
# is the pod ready to serve requests?
return states[container_status]
return states[pod['status']['phase']]
def _get_port(self, image):
try:
image = self.registry + '/' + image
repo = image.split(":")
# image already includes the tag, so we split it out here
docker_cli = Client(version="auto")
docker_cli.pull(repo[0]+":"+repo[1], tag=repo[2], insecure_registry=True)
image_info = docker_cli.inspect_image(image)
port = int(list(image_info['Config']['ExposedPorts'].keys())[0].split("/")[0])
except Exception:
logger.debug("Failed to find port for Docker image {}, defaulting to 5000".format(image)) # noqa
port = 5000
return port
def _api(self, tmpl, *args):
"""Return a fully-qualified Kubernetes API URL from a string template with args."""
url = "/api/{}".format(self.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:
# http://kubernetes.io/v1.1/docs/user-guide/labels.html#list-and-watch-filtering
labels = ['{}={}'.format(key, value) for key, value in labels.items()]
query['labelSelector'] = ','.join(labels)
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):
error(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):
error(response, 'get Namespace "{}"', namespace)
return response
def _create_namespace(self, namespace):
url = self._api("/namespaces")
data = {
"kind": "Namespace",
"apiVersion": self.apiversion,
"metadata": {
"name": namespace
}
}
response = self.session.post(url, json=data)
if not response.status_code == 201:
error(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:
error(response, 'delete Namespace "{}"', namespace)
return response
# REPLICATION CONTROLLER #
def _get_old_rc(self, namespace, app_type):
url = self._api("/namespaces/{}/replicationcontrollers", namespace)
resp = self.session.get(url)
if unhealthy(resp.status_code):
error(resp, 'get ReplicationControllers in Namespace "{}"', namespace)
exists = False
prev_rc = []
for rc in resp.json()['items']:
if (
'app' in rc['spec']['selector'] and
namespace == rc['metadata']['labels']['app'] and
'type' in rc['spec']['selector'] and
app_type == rc['spec']['selector']['type']
):
exists = True
prev_rc = rc
break
if exists:
return prev_rc
return 0
def _get_rc_status(self, namespace, name):
url = self._api("/namespaces/{}/replicationcontrollers/{}", namespace, name)
resp = self.session.get(url)
return resp.status_code
def _get_rc(self, namespace, name):
url = self._api("/namespaces/{}/replicationcontrollers/{}", namespace, name)
response = self.session.get(url)
if unhealthy(response.status_code):
error(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):
error(response, 'get ReplicationControllers in Namespace "{}"', namespace)
return response
def _wait_until_pods_terminate(self, namespace, labels, current, desired):
delta = current - desired
logger.debug("waiting for {} pods in {} namespace to be terminated (120s timeout)".format(delta, namespace)) # noqa
for waited in range(120):
pods = self._get_pods(namespace, labels=labels).json()
count = len(pods['items'])
# stop when all pods are terminated as expected
if count == desired:
break
if waited > 0 and (waited % 10) == 0:
logger.debug("waited {}s and {} pods out of {} are fully terminated".format(waited, (delta - count), delta)) # noqa
time.sleep(1)
logger.debug("{} pods in namespace {} are terminated".format(delta, namespace)) # noqa
def _get_pod_ready_status(self, namespace, labels, desired):
# If desired is 0 then there is no ready state to check on
if desired == 0:
return
# Ensure the minimum desired number of pods are available
logger.debug("waiting for {} pods in {} namespace to be in services (120s timeout)".format(desired, namespace)) # noqa
for waited in range(120):
count = 0
pods = self._get_pods(namespace, labels=labels).json()
for pod in pods['items']:
# now that state is running time to see if probes are passing
if (
pod['status']['phase'] == 'Running' and
# is the readiness probe passing?
self._pod_readiness_status(pod) == 'Running' and
# is the pod ready to serve requests?
self._pod_liveness_status(pod)
):
count += 1
if count == desired:
break
if waited > 0 and (waited % 10) == 0:
logger.debug("waited {}s and {} pods are in service".format(waited, count))
time.sleep(1)
logger.debug("{} out of {} pods in namespace {} are in service".format(count, desired, namespace)) # noqa
def _scale_rc(self, namespace, name, desired):
rc = self._get_rc(namespace, name).json()
# get the current replica count by querying for pods instead of introspecting RC
labels = {
'app': rc['spec']['selector']['app'],
'type': rc['spec']['selector']['type'],
'version': rc['spec']['selector']['version']
}
current = len(self._get_pods(namespace, labels=labels).json()['items'])
# Set the new desired replica count
rc['spec']['replicas'] = desired
logger.debug("scaling RC {} in namespace {} from {} to {} replicas".format(name, namespace, current, desired)) # noqa
url = self._api("/namespaces/{}/replicationcontrollers/{}", namespace, name)
resp = self.session.put(url, json=rc)
if unhealthy(resp.status_code):
error(resp, 'scale ReplicationController "{}"', name)
resource_ver = rc['metadata']['resourceVersion']
logger.debug("waiting for RC {} to get a newer resource version than {} (30s timeout)".format(name, resource_ver)) # noqa
for waited in range(30):
js_template = self._get_rc(namespace, name).json()
if js_template["metadata"]["resourceVersion"] != resource_ver:
break
if waited > 0 and (waited % 10) == 0:
logger.debug("waited {}s so far for a new resource version".format(waited))
time.sleep(1)
logger.debug("RC {} has a new resource version {}".format(name, js_template["metadata"]["resourceVersion"])) # noqa
# Double check enough pods are in the required state to service the application
self._get_pod_ready_status(namespace, labels, desired)
# if it was a scale down operation, wait until terminating pods are done
if int(desired) < int(current):
self._wait_until_pods_terminate(namespace, labels, current, desired)
def _create_rc(self, namespace, name, image, command, **kwargs): # noqa
app_type = kwargs.get('app_type')
container_name = namespace + '-' + app_type
args = command.split()
imgurl = self.registry + "/" + image
TEMPLATE = RCD_TEMPLATE
# Check if it is a slug builder image.
if kwargs.get('build_type') == "buildpack":
imgurl = image
TEMPLATE = RCB_TEMPLATE
l = {
"name": name,
"id": namespace,
"appversion": kwargs.get("version", {}),
"version": self.apiversion,
"image": imgurl,
"num": kwargs.get("num", {}),
"containername": container_name,
"type": app_type,
}
template = json.loads(string.Template(TEMPLATE).substitute(l))
# apply tags as needed
tags = kwargs.get('tags', {})
template["spec"]["template"]["spec"]["nodeSelector"] = tags
# Deal with container information
containers = template["spec"]["template"]["spec"]["containers"]
containers[0]['args'] = args
self._set_environment(containers[0], **kwargs)
# add in healtchecks
if kwargs.get('healthcheck'):
template = self._healthcheck(template, **kwargs['healthcheck'])
url = self._api("/namespaces/{}/replicationcontrollers", namespace)
resp = self.session.post(url, json=template)
if unhealthy(resp.status_code):
error(resp, 'create ReplicationController "{}" in Namespace "{}"', name, namespace)
logger.debug('template used: {}'.format(json.dumps(template, indent=4)))
create = False
for _ in range(30):
if not create and self._get_rc_status(namespace, name) == 404:
time.sleep(1)
continue
create = True
rc = self._get_rc(namespace, name).json()
if (
"observedGeneration" in rc["status"] and
rc["metadata"]["generation"] == rc["status"]["observedGeneration"]
):
break
time.sleep(1)
return resp.json()
def _update_rc(self, namespace, name, data):
url = self._api("/namespaces/{}/replicationcontrollers/{}", namespace, name)
return self.session.put(url, json=data)
def _delete_rc(self, namespace, name):
url = self._api("/namespaces/{}/replicationcontrollers/{}", namespace, name)
resp = self.session.delete(url)
if unhealthy(resp.status_code):
error(resp, 'delete ReplicationController "{}" in Namespace "{}"',
name, namespace)
def _healthcheck(self, controller, path='/', port=8080, delay=30, timeout=1):
# FIXME this logic ideally should live higher up
if controller['spec']['selector']['type'] not in ['web', 'cmd']:
return controller
namespace = controller['spec']['selector']['app']
# Inspect if a PORT env is already defined, make sure that's the port used
try:
service = self._get_service(namespace, namespace).json()
port = service['spec']['ports'][0]['targetPort']
except:
pass
# Only support HTTP checks for now
# http://kubernetes.io/v1.1/docs/user-guide/pod-states.html#container-probes
healthcheck = {
# defines the health checking
'livenessProbe': {
# an http probe
'httpGet': {
'path': path,
'port': port
},
# length of time to wait for a pod to initialize
# after pod startup, before applying health checking
'initialDelaySeconds': delay,
'timeoutSeconds': timeout
},
'readinessProbe': {
# an http probe
'httpGet': {
'path': path,
'port': port
},
# length of time to wait for a pod to initialize
# after pod startup, before applying health checking
'initialDelaySeconds': delay,
'timeoutSeconds': timeout
},
}
# Because it comes from a JSON template, need to hit the first key
controller['spec']['template']['spec']['containers'][0].update(healthcheck)
return controller
# SECRETS #
# http://kubernetes.io/v1.1/docs/api-reference/v1/definitions.html#_v1_secret
def _create_minio_secret(self, namespace):
with open("/var/run/secrets/deis/minio/user/access-key-id", "rb") as the_file:
secretId = the_file.read()
with open("/var/run/secrets/deis/minio/user/access-secret-key", "rb") as the_file:
secretKey = the_file.read()
data = {
'access-key-id': secretId,
'access-secret-key': secretKey
}
self._create_secret(namespace, 'minio-user', data)
def _get_secret(self, namespace, name):
url = self._api("/namespaces/{}/secrets/{}", namespace, name)
response = self.session.get(url)
if unhealthy(response.status_code):
error(response, 'get Secret "{}" in Namespace "{}"', name, namespace)
return response
def _get_secrets(self, namespace, **kwargs):
url = self._api('/namespaces/{}/secrets', namespace)
response = self.session.get(url, params=self._selectors(**kwargs))
if unhealthy(response.status_code):
error(response, 'get Secrets in Namespace "{}"', namespace)
return response
def _create_secret(self, namespace, name, data):
template = json.loads(string.Template(SECRET_TEMPLATE).substitute({
"version": self.apiversion,
"id": namespace,
"name": name
}))
for key, value in data.items():
value = value if isinstance(value, bytes) else bytes(value, 'UTF-8')
item = base64.b64encode(value).decode()
template["data"].update({key: item})
url = self._api("/namespaces/{}/secrets", namespace)
response = self.session.post(url, json=template)
if unhealthy(response.status_code):
error(response, 'failed to create secret "{}" in Namespace "{}"', name, namespace)
return response
def _delete_secret(self, namespace, name):