Skip to content

Commit 4e1dec1

Browse files
authored
Merge pull request teamhephy#34 from jianxiaoguo/dev
test(controller): add command unittest
2 parents b6118e4 + 180563a commit 4e1dec1

13 files changed

+181
-146
lines changed

rootfs/api/management/commands/measure_app.py

+12-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import uuid
22
import time
3+
import logging
34
from contextlib import closing
45
from django.utils import timezone
56
from django.core.management.base import BaseCommand
@@ -8,9 +9,11 @@
89
from api.models import App
910
from api.utils import get_influxdb_client
1011

12+
logger = logging.getLogger(__name__)
13+
1114

1215
class Command(BaseCommand):
13-
"""Management command for push data to influxdb"""
16+
"""Management command for push data to manager"""
1417

1518
def _build_query_networks_flux(self, app_map, timestamp):
1619
timestamp = int(timestamp)
@@ -60,10 +63,10 @@ def _measure_networks(self, app_map, timestamp):
6063
) as records:
6164
for record in records:
6265
app_id = record["namespace"]
63-
user_id = app_map[app_id].user_id
66+
owner_id = app_map[app_id].owner_id
6467
networks.append({
6568
"app_id": app_id,
66-
"user_id": user_id,
69+
"owner_id": owner_id,
6770
"pod_name": record["pod_name"],
6871
"rx_bytes": record["rx_bytes"],
6972
"tx_bytes": record["tx_bytes"],
@@ -80,11 +83,11 @@ def _measure_instances(self, app_map, timestamp):
8083
) as records:
8184
for record in records:
8285
app_id = record["namespace"]
83-
user_id = app_map[app_id].user_id
86+
owner_id = app_map[app_id].owner_id
8487
container_type = record["container_name"].replace(f"-{app_id}", "", 1)
8588
instances.append({
8689
"app_id": app_id,
87-
"user_id": user_id,
90+
"owner_id": owner_id,
8891
"container_type": container_type,
8992
"container_count": record["_value"],
9093
"timestamp": timestamp
@@ -95,15 +98,16 @@ def handle(self, *args, **options):
9598
if settings.WORKFLOW_MANAGER_URL is not None:
9699
timestamp = time.time()
97100
task_id = uuid.uuid4().hex
98-
print(f"pushing {task_id} networks to workflow_manager when {timezone.now()}")
101+
logger.info(f"pushing {task_id} networks to workflow_manager when {timezone.now()}")
99102
app_map = {}
100103
for app in App.objects.all():
101-
app_map[app.pk] = app
104+
app_map[app.id] = app
102105
if len(app_map) % 1000 == 0:
103106
self._measure_networks(app_map, timestamp)
104107
self._measure_instances(app_map, timestamp)
105108
app_map = {}
106109
if len(app_map) > 0:
107110
self._measure_networks(app_map, timestamp)
108111
self._measure_instances(app_map, timestamp)
109-
print(f"pushed {task_id} networks to workflow_manager when {timezone.now()}")
112+
logger.info(f"pushed {task_id} networks to workflow_manager when {timezone.now()}")
113+
self.stdout.write("done")
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
import uuid
22
import time
3+
import logging
34
from django.utils import timezone
45
from django.core.management.base import BaseCommand
56
from django.conf import settings
67
from api.models import Config
78
from api.tasks import measure_config
89

10+
logger = logging.getLogger(__name__)
11+
912

1013
class Command(BaseCommand):
11-
"""Management command for push data to influxdb"""
14+
"""Management command for push data to manager"""
1215

1316
def handle(self, *args, **options):
1417
if settings.WORKFLOW_MANAGER_URL is not None:
1518
timestamp = time.time()
1619
task_id = uuid.uuid4().hex
17-
print(f"pushing {task_id} limits to workflow_manager when {timezone.now()}")
20+
logger.info(f"pushing {task_id} limits to workflow_manager when {timezone.now()}")
1821
config_list = []
1922
for config in Config.objects.all():
2023
config_list.extend(config.to_measurements(timestamp))
2124
if len(config_list) % 1000 == 0:
2225
measure_config.delay(config_list)
2326
config_list = []
2427
if len(config_list) > 0:
25-
measure_config.delay(*config_list)
26-
print(f"pushed {task_id} limits to workflow_manager when {timezone.now()}")
28+
measure_config.delay(config_list)
29+
logger.info(f"pushed {task_id} limits to workflow_manager when {timezone.now()}")
30+
self.stdout.write("done")
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
import uuid
22
import time
3+
import logging
34
from django.utils import timezone
45
from django.core.management.base import BaseCommand
56
from django.conf import settings
67
from api.models import Resource
78
from api.tasks import measure_resources
89

10+
logger = logging.getLogger(__name__)
11+
912

1013
class Command(BaseCommand):
11-
"""Management command for push data to influxdb"""
14+
"""Management command for push data to manager"""
1215

1316
def handle(self, *args, **options):
1417
if settings.WORKFLOW_MANAGER_URL is not None:
1518
timestamp = time.time()
1619
task_id = uuid.uuid4().hex
17-
print(f"pushing {task_id} resources to workflow_manager when {timezone.now()}")
20+
logger.info(f"pushing {task_id} resources to workflow_manager when {timezone.now()}")
1821
resource_list = []
1922
for resource in Resource.objects.all():
20-
resource_list.extend(resource.to_to_measurements(timestamp))
23+
resource_list.extend(resource.to_measurements(timestamp))
2124
if len(resource_list) % 1000 == 0:
2225
measure_resources.delay(resource_list)
2326
resource_list = []
2427
if len(resource_list) > 0:
25-
measure_resources.delay(*resource_list)
26-
print(f"pushed {task_id} resources to workflow_manager when {timezone.now()}")
28+
measure_resources.delay(resource_list)
29+
logger.info(f"pushed {task_id} resources to workflow_manager when {timezone.now()}")
30+
self.stdout.write("done")
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
import uuid
22
import time
3+
import logging
34
from django.utils import timezone
45
from django.core.management.base import BaseCommand
56
from django.conf import settings
67
from api.models import Volume
78
from api.tasks import measure_volumes
89

10+
logger = logging.getLogger(__name__)
11+
912

1013
class Command(BaseCommand):
11-
"""Management command for push data to influxdb"""
14+
"""Management command for push data to manager"""
1215

1316
def handle(self, *args, **options):
1417
if settings.WORKFLOW_MANAGER_URL is not None:
1518
timestamp = time.time()
1619
task_id = uuid.uuid4().hex
17-
print(f"pushing {task_id} volumes to workflow_manager when {timezone.now()}")
20+
logger.info(f"pushing {task_id} volumes to workflow_manager when {timezone.now()}")
1821
volume_list = []
1922
for volume in Volume.objects.all():
2023
volume_list.extend(volume.to_measurements(timestamp))
2124
if len(volume_list) % 1000 == 0:
2225
measure_volumes.delay(volume_list)
2326
volume_list = []
2427
if len(volume_list) > 0:
25-
measure_volumes.delay(*volume_list)
26-
print(f"pushed {task_id} volumes to workflow_manager when {timezone.now()}")
28+
measure_volumes.delay(volume_list)
29+
logger.info(f"pushed {task_id} volumes to workflow_manager when {timezone.now()}")
30+
self.stdout.write("done")

rootfs/api/models/__init__.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
Data models for the Drycc API.
55
"""
6+
import time
67
import hashlib
78
import hmac
89
import importlib
@@ -265,14 +266,16 @@ def config_changed_handle(sender, instance=None, created=False, update_fields=No
265266
created or (
266267
update_fields is not None and (
267268
"cpu" in update_fields or "memory" in update_fields))):
268-
measure_config.delay(instance.to_measurements())
269+
timestamp = time.time()
270+
measure_config.delay(instance.to_measurements(timestamp))
269271

270272

271273
@receiver(post_save, sender=Volume)
272274
def volume_changed_handle(sender, instance=None, created=False, update_fields=None, **kwargs):
273275
# measure volumes to workflow manager
274276
if settings.WORKFLOW_MANAGER_URL is not None and created:
275-
measure_volumes.delay(instance.to_measurements())
277+
timestamp = time.time()
278+
measure_volumes.delay(instance.to_measurements(timestamp))
276279

277280

278281
@receiver(post_save, sender=Resource)
@@ -290,4 +293,5 @@ def resource_changed_handle(sender, instance=None, created=False, update_fields=
290293
update_fields is not None and (
291294
"plan" in update_fields
292295
))):
293-
measure_resources.delay(instance.to_measurements())
296+
timestamp = time.time()
297+
measure_resources.delay(instance.to_measurements(timestamp))

rootfs/api/models/config.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -198,8 +198,8 @@ def save(self, **kwargs):
198198
def to_measurements(self, timestamp: float):
199199
assert len(set(self.memory.keys()).difference(self.cpu.keys())) == 0
200200
return [{
201-
"app_id": self.app_id,
202-
"user_id": self.user_id,
201+
"app_id": str(self.app_id),
202+
"owner_id": str(self.owner_id),
203203
"container_type": container_type,
204204
"cpu": unit_to_millicpu(self.cpu.get(container_type)),
205205
"memory": unit_to_bytes(self.memory.get(container_type)),

rootfs/api/models/resource.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,8 @@ def detach_resource(self, *args, **kwargs):
201201
def to_measurements(self, timestamp: float):
202202
return [{
203203
"name": self.name,
204-
"app_id": self.app_id,
205-
"user_id": self.user_id,
204+
"app_id": str(self.app_id),
205+
"owner_id": str(self.owner_id),
206206
"plan": self.plan,
207207
"timestamp": "%f" % timestamp
208208
}]

rootfs/api/models/volume.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ def log(self, message, level=logging.INFO):
9595
def to_measurements(self, timestamp: float):
9696
return [{
9797
"name": self.name,
98-
"app_id": self.app_id,
99-
"user_id": self.user_id,
98+
"app_id": str(self.app_id),
99+
"owner_id": str(self.owner_id),
100100
"size": unit_to_bytes(self.size),
101101
"timestamp": "%f" % timestamp
102102
}]

rootfs/api/tasks.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def retrieve_resource(resource):
3333
else:
3434
resource.detach_resource()
3535
except Resource.DoesNotExist:
36-
logger.info("retrieve task not found resource: {}".format(resource.id)) # noqa
36+
logger.exception("retrieve task not found resource: {}".format(resource.id)) # noqa
3737
finally:
3838
signals.request_finished.send(sender=task_id)
3939

@@ -44,7 +44,7 @@ def measure_config(config: List[Dict[str, str]]):
4444
[
4545
{
4646
"app_id": "test",
47-
"user_id": "test",
47+
"owner_id": "test",
4848
"container_type": web,
4949
"cpu": "1",
5050
"memory": "2G",
@@ -64,7 +64,7 @@ def measure_config(config: List[Dict[str, str]]):
6464
data=json.dumps(config)
6565
)
6666
except Exception as e:
67-
logger.info("write influxdb point fail: {}".format(e))
67+
logger.exception("write influxdb point fail: {}".format(e))
6868
finally:
6969
signals.request_finished.send(sender=task_id)
7070

@@ -76,7 +76,7 @@ def measure_volumes(volumes: List[Dict[str, str]]):
7676
{
7777
"name": "disk",
7878
"app_id": "test",
79-
"user_id": "test",
79+
"owner_id": "test",
8080
"size": "100G",
8181
"timestamp": "1609231998.9103732"
8282
}
@@ -94,7 +94,7 @@ def measure_volumes(volumes: List[Dict[str, str]]):
9494
data=json.dumps(volumes)
9595
)
9696
except Exception as e:
97-
logger.info("write influxdb point fail: {}".format(e))
97+
logger.exception("write influxdb point fail: {}".format(e))
9898
finally:
9999
signals.request_finished.send(sender=task_id)
100100

@@ -105,7 +105,7 @@ def measure_networks(networks: List[Dict[str, str]]):
105105
[
106106
{
107107
"app_id": "test",
108-
"user_id": "test",
108+
"owner_id": "test",
109109
"pod_name": "django2test-web-xxxxxx",
110110
"rx_bytes": "10000",
111111
"tx_bytes": "200000",
@@ -125,7 +125,7 @@ def measure_networks(networks: List[Dict[str, str]]):
125125
data=json.dumps(networks)
126126
)
127127
except Exception as e:
128-
logger.info("write influxdb point fail: {}".format(e))
128+
logger.exception("write influxdb point fail: {}".format(e))
129129
finally:
130130
signals.request_finished.send(sender=task_id)
131131

@@ -136,7 +136,7 @@ def measure_instances(instances: List[Dict[str, str]]):
136136
[
137137
{
138138
"app_id": "test",
139-
"user_id": "test",
139+
"owner_id": "test",
140140
"container_type": "web",
141141
"container_count": 1,
142142
"timestamp": "1609231998.9103732"
@@ -155,7 +155,7 @@ def measure_instances(instances: List[Dict[str, str]]):
155155
data=json.dumps(instances)
156156
)
157157
except Exception as e:
158-
logger.info("write influxdb point fail: {}".format(e))
158+
logger.exception("write influxdb point fail: {}".format(e))
159159
finally:
160160
signals.request_finished.send(sender=task_id)
161161

@@ -167,7 +167,7 @@ def measure_resources(resources: List[Dict[str, str]]):
167167
{
168168
"name": "test1",
169169
"app_id": "redis",
170-
"user_id": "test",
170+
"owener_id": "test",
171171
"plan": "redis:small",
172172
"timestamp": "1609231998.9103732"
173173
}
@@ -185,6 +185,6 @@ def measure_resources(resources: List[Dict[str, str]]):
185185
data=json.dumps(resources)
186186
)
187187
except Exception as e:
188-
logger.info("write influxdb point fail: {}".format(e))
188+
logger.exception("write influxdb point fail: {}".format(e))
189189
finally:
190190
signals.request_finished.send(sender=task_id)

rootfs/api/tests/test_config.py

+22
Original file line numberDiff line numberDiff line change
@@ -405,3 +405,25 @@ def test_config_failures(self, mock_requests):
405405
self.assertEqual(app.release_set.latest().version, 5)
406406
self.assertEqual(app.release_set.latest().config, success_config)
407407
self.assertEqual(app.config_set.count(), 3)
408+
409+
def call_command(self, *args, **kwargs):
410+
from io import StringIO
411+
from django.core.management import call_command
412+
out = StringIO()
413+
call_command(
414+
"measure_config",
415+
*args,
416+
stdout=out,
417+
stderr=StringIO(),
418+
**kwargs,
419+
)
420+
return out.getvalue()
421+
422+
def test_measure_config(self, *args, **kwargs):
423+
# create
424+
app_id = self.create_app()
425+
url = "/v2/apps/{app_id}/config".format(**locals())
426+
body = {'values': json.dumps({'PORT': 5000}), 'cpu': json.dumps({'web': '1000m'})}
427+
response = self.client.post(url, body)
428+
out = self.call_command()
429+
self.assertIn(out, "done\n")

0 commit comments

Comments
 (0)