Skip to content

Commit abdd796

Browse files
committed
chore(controller): remove start/stop api
1 parent 9613a1f commit abdd796

5 files changed

Lines changed: 11 additions & 145 deletions

File tree

rootfs/api/models/app.py

Lines changed: 4 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -491,78 +491,6 @@ def scale(self, user, structure): # noqa
491491

492492
return False
493493

494-
def stop(self, user, types): # noqa
495-
"""scale containers which types contained down """
496-
rs_zero = []
497-
for _ in types:
498-
if not self.structure.get(_, 0):
499-
rs_zero.append(_)
500-
if rs_zero:
501-
raise DryccException("process {} replicas is zero".format(",".join(rs_zero))) # noqa
502-
503-
if self.release_set.filter(failed=False).latest().build is None:
504-
raise DryccException('No build associated with this release')
505-
506-
release = self.release_set.filter(failed=False).latest()
507-
structure = {_: 0 for _ in types}
508-
509-
# test for available process types
510-
available_process_types = release.build.procfile or {}
511-
for container_type in types:
512-
if container_type == 'cmd':
513-
continue # allow docker cmd types in case we don't have the image source
514-
515-
if container_type not in available_process_types:
516-
raise NotFound(
517-
'Container type {} does not exist in application'.format(container_type))
518-
519-
# merge current structure and the new items together
520-
old_structure = self.structure
521-
new_structure = old_structure.copy()
522-
new_structure.update(structure)
523-
524-
if new_structure != self.structure:
525-
try:
526-
self._scale_pods(structure)
527-
except ServiceUnavailable:
528-
# scaling failed, go back to old scaling numbers
529-
self._scale_pods(old_structure)
530-
raise
531-
532-
msg = '{} stopped pods '.format(user.username) + ' '.join(types)
533-
self.log(msg)
534-
535-
return True
536-
537-
return False
538-
539-
def start(self, user, types): # noqa
540-
"""scale containers which types contained up."""
541-
# use create to make sure minimum resources are created
542-
self.create()
543-
if self.release_set.filter(failed=False).latest().build is None:
544-
raise DryccException('No build associated with this release')
545-
546-
rs_zero = []
547-
for _ in types:
548-
if not self.structure.get(_, 0):
549-
rs_zero.append(_)
550-
if rs_zero:
551-
raise DryccException("process {} replicas is zero".format(",".join(rs_zero))) # noqa
552-
553-
structure = {}
554-
for k, v in self.structure.items():
555-
if k in types:
556-
structure[k] = v
557-
try:
558-
self._scale_pods(structure)
559-
except ServiceUnavailable:
560-
# scaling failed, go back to old scaling numbers
561-
raise
562-
msg = '{} stopped pods '.format(user.username) + ' '.join(types)
563-
self.log(msg)
564-
return True
565-
566494
def _scale_pods(self, scale_types):
567495
release = self.release_set.filter(failed=False).latest()
568496
app_settings = self.appsettings_set.latest()
@@ -910,7 +838,6 @@ def pod_name(size=5, chars=string.ascii_lowercase + string.digits):
910838

911839
def list_pods(self, *args, **kwargs):
912840
"""Used to list basic information about pods running for a given application"""
913-
autoscale = self.appsettings_set.latest().autoscale
914841
try:
915842
labels = self._scheduler_filter(**kwargs)
916843

@@ -947,18 +874,16 @@ def list_pods(self, *args, **kwargs):
947874
if 'startTime' in p['status']:
948875
started = p['status']['startTime']
949876
else:
950-
started = str(datetime.utcnow().strftime(settings.DRYCC_DATETIME_FORMAT))
877+
started = str(datetime.utcnow().strftime(settings.DEIS_DATETIME_FORMAT))
951878
item['started'] = started
952-
replicas = str(autoscale[labels['type']]['min']) + '-' + str(autoscale[labels['type']]['max']) \
953-
if autoscale.get(labels['type']) is not None else self.structure.get(labels['type']) # noqa
954-
item['replicas'] = str(replicas)
879+
955880
data.append(item)
956881

957882
# sorting so latest start date is first
958883
data.sort(key=lambda x: x['started'], reverse=True)
959884
return data
960-
except KubeHTTPException as e:
961-
logger.debug(e)
885+
except KubeHTTPException:
886+
pass
962887
except Exception as e:
963888
err = '(list pods): {}'.format(e)
964889
self.log(err, logging.ERROR)

rootfs/api/serializers.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,6 @@ class PodSerializer(serializers.BaseSerializer):
599599
type = serializers.CharField()
600600
release = serializers.CharField(required=False)
601601
started = serializers.DateTimeField(required=False)
602-
replicas = serializers.CharField(required=False)
603602

604603
def to_representation(self, obj):
605604
return obj

rootfs/api/tests/test_pods.py

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -100,20 +100,6 @@ def test_container_api_heroku(self, mock_requests):
100100
response = self.client.post(url, body)
101101
self.assertEqual(response.status_code, 204, response.data)
102102

103-
# stop
104-
url = "/v2/apps/{app_id}/stop".format(**locals())
105-
# test setting one proc type at a time
106-
body = {"types": ['web']}
107-
response = self.client.post(url, body)
108-
self.assertEqual(response.status_code, 204, response.data)
109-
110-
# start
111-
url = "/v2/apps/{app_id}/start".format(**locals())
112-
# test setting one proc type at a time
113-
body = {"types": ['web']}
114-
response = self.client.post(url, body)
115-
self.assertEqual(response.status_code, 204, response.data)
116-
117103
url = "/v2/apps/{app_id}/pods".format(**locals())
118104
response = self.client.get(url)
119105
self.assertEqual(response.status_code, 200, response.data)
@@ -135,7 +121,7 @@ def test_container_api_heroku(self, mock_requests):
135121
url = "/v2/apps/{app_id}/pods".format(**locals())
136122
response = self.client.get(url)
137123
self.assertEqual(response.status_code, 200, response.data)
138-
self.assertEqual(len(response.data['results']), 2)
124+
self.assertEqual(len(response.data['results']), 0)
139125

140126
url = "/v2/apps/{app_id}".format(**locals())
141127
response = self.client.get(url)
@@ -205,7 +191,7 @@ def test_container_api_docker(self, mock_requests):
205191
url = "/v2/apps/{app_id}/pods".format(**locals())
206192
response = self.client.get(url)
207193
self.assertEqual(response.status_code, 200, response.data)
208-
self.assertEqual(len(response.data['results']), 1)
194+
self.assertEqual(len(response.data['results']), 0)
209195

210196
url = "/v2/apps/{app_id}".format(**locals())
211197
response = self.client.get(url)
@@ -243,7 +229,7 @@ def test_release(self, mock_requests):
243229
url = "/v2/apps/{app_id}/pods".format(**locals())
244230
response = self.client.get(url)
245231
self.assertEqual(response.status_code, 200, response.data)
246-
self.assertEqual(len(response.data['results']), 2)
232+
self.assertEqual(len(response.data['results']), 1)
247233
self.assertEqual(response.data['results'][0]['release'], 'v2')
248234

249235
# post a new build
@@ -370,7 +356,7 @@ def test_pod_command_format(self, mock_requests):
370356

371357
# verify that the app._get_command property got formatted
372358
self.assertEqual(response.status_code, 200, response.data)
373-
self.assertEqual(len(response.data['results']), 2)
359+
self.assertEqual(len(response.data['results']), 1)
374360

375361
pod = response.data['results'][0]
376362
self.assertEqual(pod['type'], 'web')

rootfs/api/urls.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,6 @@
6262
# application actions
6363
url(r"^apps/(?P<id>{})/scale/?$".format(settings.APP_URL_REGEX),
6464
views.AppViewSet.as_view({'post': 'scale'})),
65-
url(r"^apps/(?P<id>{})/stop/?$".format(settings.APP_URL_REGEX),
66-
views.AppViewSet.as_view({'post': 'stop'})),
67-
url(r"^apps/(?P<id>{})/start/?$".format(settings.APP_URL_REGEX),
68-
views.AppViewSet.as_view({'post': 'start'})),
6965
url(r"^apps/(?P<id>{})/logs/?$".format(settings.APP_URL_REGEX),
7066
views.AppViewSet.as_view({'get': 'logs'})),
7167
url(r"^apps/(?P<id>{})/run/?$".format(settings.APP_URL_REGEX),

rootfs/api/views.py

Lines changed: 3 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -187,20 +187,6 @@ def scale(self, request, **kwargs):
187187
scale_app.delay(self.get_object(), request.user, request.data)
188188
return Response(status=status.HTTP_204_NO_CONTENT)
189189

190-
def stop(self, request, **kwargs):
191-
types = request.data.get("types")
192-
if not types:
193-
raise DryccException("types is a required field")
194-
self.get_object().stop(request.user, types)
195-
return Response(status=status.HTTP_204_NO_CONTENT)
196-
197-
def start(self, request, **kwargs):
198-
types = request.data.get("types")
199-
if not types:
200-
raise DryccException("types is a required field")
201-
self.get_object().start(request.user, types)
202-
return Response(status=status.HTTP_204_NO_CONTENT)
203-
204190
def logs(self, request, **kwargs):
205191
app = self.get_object()
206192
try:
@@ -289,34 +275,7 @@ class PodViewSet(AppResourceViewSet):
289275
def list(self, *args, **kwargs):
290276
pods = self.get_app().list_pods(*args, **kwargs)
291277
data = self.get_serializer(pods, many=True).data
292-
293-
if not kwargs.get("type"):
294-
autoscale = self.get_app().appsettings_set.latest().autoscale
295-
exist_pod_type = list(set([_["type"] for _ in data if _["type"]]))
296-
structure = self.get_app().structure
297-
procfile_structure = self.get_app().procfile_structure
298-
# remove prev release container type
299-
if procfile_structure:
300-
condition_procfile_structure = list(procfile_structure.keys())
301-
else:
302-
condition_procfile_structure = ['cmd', 'web']
303-
structure = {k: v for k, v in structure.items() if (v != 0 or k in condition_procfile_structure)} # noqa
304-
for _ in structure.keys():
305-
if _ not in exist_pod_type:
306-
replicas = str(autoscale[_]['min']) + '-' + str(autoscale[_]['max']) \
307-
if (autoscale.get(_) is not None and structure[_] !=0) else structure[_] # noqa
308-
exist_pod_type.append(_)
309-
data.append({"type": _,
310-
"replicas": str(replicas),
311-
"state": "stopped"})
312-
313-
for _ in procfile_structure:
314-
if _ not in exist_pod_type:
315-
data.append({"type": _,
316-
"replicas": str(0),
317-
"state": "started"})
318-
319-
# # fake out pagination for now
278+
# fake out pagination for now
320279
pagination = {'results': data, 'count': len(data)}
321280
return Response(pagination, status=status.HTTP_200_OK)
322281

@@ -953,12 +912,13 @@ class AdmissionWebhook(GenericViewSet):
953912

954913
def scale(self, request, **kwargs):
955914
token = kwargs['token']
915+
print(request.body.decode("utf8"))
956916
data = json.loads(request.body.decode("utf8"))["request"]
957917
if settings.DRYCC_ADMISSION_WEBHOOK_TOKEN == token:
958918
allowed = True
959919
app_id = data["object"]["metadata"]["namespace"]
960920
app = models.App.objects.filter(id=app_id).first()
961-
replicas = data["object"]["spec"]["replicas"]
921+
replicas = data["object"]["spec"].get("replicas", 0)
962922
container_type = data["object"]["metadata"]["name"].replace(f"{app_id}-", "", 1)
963923
if app and app.structure.get(container_type) != replicas: # sync replicas
964924
app.structure[container_type] = replicas

0 commit comments

Comments
 (0)