-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathresource.py
More file actions
207 lines (189 loc) · 8.42 KB
/
resource.py
File metadata and controls
207 lines (189 loc) · 8.42 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
import logging
from django.conf import settings
from django.db import models, transaction
from api.exceptions import DryccException, AlreadyExists, ServiceUnavailable
from api.models import UuidAuditedModel, validate_label
from scheduler import KubeException
logger = logging.getLogger(__name__)
class Resource(UuidAuditedModel):
owner = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.PROTECT)
app = models.ForeignKey('App', on_delete=models.CASCADE)
name = models.CharField(max_length=63, validators=[validate_label])
plan = models.CharField(max_length=128)
data = models.JSONField(default=dict, blank=True)
status = models.TextField(blank=True, null=True)
binding = models.TextField(blank=True, null=True)
options = models.JSONField(default=dict, blank=True)
class Meta:
get_latest_by = 'created'
unique_together = (('app', 'name'),)
ordering = ['-created']
def __str__(self):
return self.name
@transaction.atomic
def save(self, *args, **kwargs):
# Attach ServiceInstance, updates k8s
if self.created == self.updated:
self.attach(*args, **kwargs)
# Save to DB
return super(Resource, self).save(*args, **kwargs)
def attach(self, *args, **kwargs):
try:
self._scheduler.svcat.get_instance(self.app.id, self.name)
err = "Resource {} already exists in this namespace".format(self.name) # noqa
self.log(err, logging.INFO)
raise AlreadyExists(err)
except KubeException as e:
logger.info(e)
try:
instance = self.plan.split(":")
kwargs = {
"instance_class": instance[0],
"instance_plan": ":".join(instance[1:]),
"parameters": self.options,
}
self._scheduler.svcat.create_instance(
self.app.id, self.name, **kwargs
)
except KubeException as e:
msg = 'There was a problem creating the resource ' \
'{} for {}'.format(self.name, self.app_id)
raise ServiceUnavailable(msg) from e
@transaction.atomic
def delete(self, *args, **kwargs):
if self.binding == "Ready":
raise DryccException("the plan is still binding")
# Deatch ServiceInstance, updates k8s
self.detach(*args, **kwargs)
# Delete from DB
return super(Resource, self).delete(*args, **kwargs)
def detach(self, *args, **kwargs):
try:
# We raise an exception when a resource doesn't exist
self._scheduler.svcat.get_instance(self.app.id, self.name)
self._scheduler.svcat.delete_instance(self.app.id, self.name)
except KubeException as e:
raise ServiceUnavailable("Could not delete resource {} for application {}".format(self.name, self.app_id)) from e # noqa
def log(self, message, level=logging.INFO):
"""Logs a message in the context of this service.
This prefixes log messages with an application "tag" that the customized
drycc-logspout will be on the lookout for. 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(self.uuid, message))
def bind(self, *args, **kwargs):
if self.status != "Ready":
raise DryccException("the resource is not ready")
if self.binding == "Ready":
raise DryccException("the resource is binding")
self.binding = "Binding"
self.save()
try:
self._scheduler.svcat.get_binding(self.app.id, self.name)
err = "Resource {} is binding".format(self.name)
self.log(err, logging.INFO)
raise AlreadyExists(err)
except KubeException as e:
logger.info(e)
try:
self._scheduler.svcat.create_binding(
self.app.id, self.name, **kwargs)
except KubeException as e:
msg = 'There was a problem binding the resource ' \
'{} for {}'.format(self.name, self.app_id)
raise ServiceUnavailable(msg) from e
def unbind(self, *args, **kwargs):
if not self.binding:
raise DryccException("the resource is not binding")
try:
# We raise an exception when a resource doesn't exist
self._scheduler.svcat.get_binding(self.app.id, self.name)
self._scheduler.svcat.delete_binding(self.app.id, self.name)
self.binding = None
self.data = {}
self.save()
except KubeException as e:
raise ServiceUnavailable("Could not unbind resource {} for application {}".format(self.name, self.app_id)) from e # noqa
def attach_update(self, *args, **kwargs):
try:
data = self._scheduler.svcat.get_instance(
self.app.id, self.name).json()
except KubeException as e:
logger.debug(e)
self.DryccException("resource {} does not exist".format(self.name))
try:
version = data["metadata"]["resourceVersion"]
instance = self.plan.split(":")
kwargs = {
"instance_class": instance[0],
"instance_plan": ":".join(instance[1:]),
"parameters": self.options,
"external_id": data["spec"]["externalID"]
}
self._scheduler.svcat.put_instance(
self.app.id, self.name, version, **kwargs
)
except KubeException as e:
msg = 'There was a problem update the resource ' \
'{} for {}'.format(self.name, self.app_id)
raise ServiceUnavailable(msg) from e
def retrieve(self, *args, **kwargs):
update_flag = False
if self.status != "Ready":
try:
resp_i = self._scheduler.svcat.get_instance(
self.app.id, self.name).json()
self.status = resp_i.get('status', {}).\
get('lastConditionState')
self.options = resp_i.get('spec', {}).get('parameters', {})
update_flag = True
except KubeException as e:
logger.info("retrieve instance info error: {}".format(e))
if self.binding != "Ready":
try:
# We raise an exception when a resource doesn't exist
resp_b = self._scheduler.svcat.get_binding(
self.app.id, self.name).json()
self.binding = resp_b.get('status', {}).\
get('lastConditionState')
update_flag = True
secret_name = resp_b.get('spec', {}).get('secretName')
if secret_name:
resp_s = self._scheduler.secret.get(
self.app.id, secret_name).json()
self.data = resp_s.get('data', {})
update_flag = True
except KubeException as e:
logger.info("retrieve binding info error: {}".format(e))
if update_flag is True:
self.save()
if self.status == "Ready" and self.binding == "Ready":
return True
else:
return False
def detach_resource(self, *args, **kwargs):
if self.binding != "Ready":
try:
resp_b = self._scheduler.svcat.get_binding(
self.app.id, self.name).json()
secret_name = resp_b.get('spec', {}).get('secretName')
if secret_name:
self._scheduler.secret.delete(self.app.id, secret_name)
self._scheduler.svcat.delete_binding(
self.app.id, self.name)
except KubeException as e:
logger.info("delete binding info error: {}".format(e))
self.binding = None
if (self.status != "Ready") or (not self.binding):
self.delete()
def to_measurements(self, timestamp: float):
return [{
"name": self.name,
"app_id": str(self.app_id),
"owner_id": str(self.owner_id),
"plan": self.plan,
"timestamp": "%f" % timestamp
}]