-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconfig.py
More file actions
131 lines (108 loc) · 5.13 KB
/
config.py
File metadata and controls
131 lines (108 loc) · 5.13 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
from django.conf import settings
from django.db import models
from jsonfield import JSONField
from api.models import UuidAuditedModel, DeisException
class Config(UuidAuditedModel):
"""
Set of configuration values applied as environment variables
during runtime execution of the Application.
"""
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
app = models.ForeignKey('App')
values = JSONField(default={}, blank=True)
memory = JSONField(default={}, blank=True)
cpu = JSONField(default={}, blank=True)
tags = JSONField(default={}, blank=True)
registry = JSONField(default={}, blank=True)
class Meta:
get_latest_by = 'created'
ordering = ['-created']
unique_together = (('app', 'uuid'),)
def __str__(self):
return "{}-{}".format(self.app.id, str(self.uuid)[:7])
def healthcheck(self):
"""
Get all healthchecks options together for use in scheduler
"""
# return empty dict if no healthcheck is found
if 'HEALTHCHECK_URL' not in self.values.keys():
return {}
path = self.values.get('HEALTHCHECK_URL', '/')
timeout = int(self.values.get('HEALTHCHECK_TIMEOUT', 50))
delay = int(self.values.get('HEALTHCHECK_INITIAL_DELAY', 50))
port = int(self.values.get('HEALTHCHECK_PORT', 5000))
period_seconds = int(self.values.get('HEALTHCHECK_PERIOD_SECONDS', 10))
success_threshold = int(self.values.get('HEALTHCHECK_SUCCESS_THRESHOLD', 1))
failure_threshold = int(self.values.get('HEALTHCHECK_FAILURE_THRESHOLD', 3))
return {
'path': path,
'timeout': timeout,
'delay': delay,
'port': port,
'period_seconds': period_seconds,
'success_threshold': success_threshold,
'failure_threshold': failure_threshold,
}
def set_healthchecks(self):
"""Defines default values for HTTP healthchecks"""
if not {k: v for k, v in self.values.items() if k.startswith('HEALTHCHECK_')}:
return
# fetch set health values and any defaults
# this approach allows new health items to be added without issues
health = self.healthcheck()
if not health:
return
# HTTP GET related
self.values['HEALTHCHECK_URL'] = health['path']
self.values['HEALTHCHECK_PORT'] = health['port']
# Number of seconds after which the probe times out.
# More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes
self.values['HEALTHCHECK_TIMEOUT'] = health['timeout']
# Number of seconds after the container has started before liveness probes are initiated.
# More info: http://releases.k8s.io/HEAD/docs/user-guide/pod-states.md#container-probes
self.values['HEALTHCHECK_INITIAL_DELAY'] = health['delay']
# How often (in seconds) to perform the probe.
self.values['HEALTHCHECK_PERIOD_SECONDS'] = health['period_seconds']
# Minimum consecutive successes for the probe to be considered successful
# after having failed.
self.values['HEALTHCHECK_SUCCESS_THRESHOLD'] = health['success_threshold']
# Minimum consecutive failures for the probe to be considered failed after
# having succeeded.
self.values['HEALTHCHECK_FAILURE_THRESHOLD'] = health['failure_threshold']
def set_registry(self):
# lower case all registry options for consistency
self.registry = {key.lower(): value for key, value in self.registry.copy().items()}
def set_tags(self, previous_config):
"""verify the tags exist on any nodes as labels"""
if not self.tags:
return
# Get all nodes with label selectors
nodes = self._scheduler._get_nodes(labels=self.tags).json()
if nodes['items']:
return
labels = ['{}={}'.format(key, value) for key, value in self.tags.items()]
message = 'No nodes matched the provided labels: {}'.format(', '.join(labels))
# Find out if there are any other tags around
old_tags = getattr(previous_config, 'tags')
if old_tags:
old = ['{}={}'.format(key, value) for key, value in old_tags.items()]
new = set(labels) - set(old)
message += ' - Addition of {} is the cause'.format(', '.join(new))
raise DeisException(message)
def save(self, **kwargs):
"""merge the old config with the new"""
try:
previous_config = self.app.config_set.latest()
for attr in ['cpu', 'memory', 'tags', 'registry', 'values']:
data = getattr(previous_config, attr, {}).copy()
new_data = getattr(self, attr, {}).copy()
data.update(new_data)
# remove config keys if we provided a null value
[data.pop(k) for k, v in new_data.items() if v is None]
setattr(self, attr, data)
self.set_healthchecks()
self.set_registry()
self.set_tags(previous_config)
except Config.DoesNotExist:
pass
return super(Config, self).save(**kwargs)