Skip to content

Commit 3df0dd9

Browse files
committed
Implements #1353
1 parent 6d18ac9 commit 3df0dd9

12 files changed

+71
-25
lines changed

IM/InfrastructureManager.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1733,20 +1733,21 @@ def ChangeInfrastructureAuth(inf_id, new_auth, overwrite, auth):
17331733
return ""
17341734

17351735
@staticmethod
1736-
def GetStats(date, auth):
1736+
def GetStats(init_date, end_date, auth):
17371737
"""
17381738
Get the statistics from the IM DB.
17391739
17401740
Args:
17411741
17421742
- init_date(str): Only will be returned infrastructure created afther this date.
1743+
- end_date(str): Only will be returned infrastructure created before this date.
17431744
- auth(Authentication): parsed authentication tokens.
17441745
17451746
Return: a list of dict with the stats.
17461747
"""
17471748
# First check the auth data
17481749
auth = InfrastructureManager.check_auth_data(auth)
1749-
stats = Stats.get_stats(date, auth)
1750+
stats = Stats.get_stats(init_date, end_date, auth)
17501751
if stats is None:
17511752
raise Exception("ERROR connecting with the database!.")
17521753
else:

IM/REST.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -1066,6 +1066,7 @@ def RESTGetStats():
10661066
return return_error(401, "No authentication data provided")
10671067

10681068
try:
1069+
init_date = None
10691070
if "init_date" in bottle.request.params.keys():
10701071
init_date = bottle.request.params.get("init_date").lower()
10711072
init_date = init_date.replace("/", "-")
@@ -1080,7 +1081,20 @@ def RESTGetStats():
10801081
else:
10811082
init_date = "1970-01-01"
10821083

1083-
stats = InfrastructureManager.GetStats(init_date, auth)
1084+
end_date = None
1085+
if "end_date" in bottle.request.params.keys():
1086+
end_date = bottle.request.params.get("end_date").lower()
1087+
end_date = end_date.replace("/", "-")
1088+
parts = end_date.split("-")
1089+
try:
1090+
year = int(parts[0])
1091+
month = int(parts[1])
1092+
day = int(parts[2])
1093+
datetime.date(year, month, day)
1094+
except Exception:
1095+
return return_error(400, "Incorrect format in end_date parameter: YYYY/MM/dd")
1096+
1097+
stats = InfrastructureManager.GetStats(init_date, end_date, auth)
10841098
bottle.response.content_type = "application/json"
10851099
return format_output(stats, default_type="application/json", field_name="stats")
10861100
except Exception as ex:

IM/ServiceRequests.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -457,5 +457,5 @@ class Request_GetStats(IMBaseRequest):
457457

458458
def _call_function(self):
459459
self._error_mesage = "Error getting stats"
460-
(init_date, auth_data) = self.arguments
461-
return IM.InfrastructureManager.InfrastructureManager.GetStats(init_date, Authentication(auth_data))
460+
(init_date, end_date, auth_data) = self.arguments
461+
return IM.InfrastructureManager.InfrastructureManager.GetStats(init_date, end_date, Authentication(auth_data))

IM/Stats.py

+13-2
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,14 @@ def _get_data(str_data, auth=None):
8080
return resp
8181

8282
@staticmethod
83-
def get_stats(init_date="1970-01-01", auth=None):
83+
def get_stats(init_date="1970-01-01", end_date=None, auth=None):
8484
"""
8585
Get the statistics from the IM DB.
8686
8787
Args:
8888
8989
- init_date(str): Only will be returned infrastructure created afther this date.
90+
- end_date(str): Only will be returned infrastructure created afther this date.
9091
- auth(Authentication): parsed authentication tokens.
9192
9293
Return: a list of dict with the stats with the following format:
@@ -105,7 +106,17 @@ def get_stats(init_date="1970-01-01", auth=None):
105106
stats = []
106107
db = DataBase(Config.DATA_DB)
107108
if db.connect():
108-
res = db.select("SELECT data, date, id FROM inf_list WHERE date > '%s' order by rowid desc;" % init_date)
109+
where = "creation_date > '%s'" % init_date
110+
if end_date:
111+
where += " and creation_date < %s" % end_date
112+
if auth:
113+
where += " and ("
114+
for num, elem in enumerate(auth.getAuthInfo("InfrastructureManager")):
115+
if num > 0:
116+
where += " or "
117+
where += "auth == '%s:%s'" % (elem["username"], elem["password"])
118+
where += ")"
119+
res = db.select("SELECT data, date, id FROM inf_list WHERE %s order by rowid desc;" % where)
109120
for elem in res:
110121
data = elem[0]
111122
date = elem[1]

doc/source/REST.rst

+1
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@ GET ``http://imserver.com/stats``
459459
:Response Content-type: application/json
460460
:ok response: 200 OK
461461
:input fields: ``init_date`` (optional)
462+
:input fields: ``end_date`` (optional)
462463
:fail response: 401, 400
463464

464465
Return the stats of the current user in the IM service.

doc/source/xmlrpc.rst

+4-3
Original file line numberDiff line numberDiff line change
@@ -417,13 +417,14 @@ This is the list of method names:
417417

418418
``GetStat``
419419
:parameter 0: ``init_date``: string
420-
:parameter 1: ``auth``: array of structs
420+
:parameter 1: ``end_date``: string
421+
:parameter 2: ``auth``: array of structs
421422
:ok response: [true, list of dicts]
422423
:fail response: [false, ``error``: string]
423424

424425
Return the stats of the current user in the IM service.
425-
Return all the infrastructures since ``init_date`` deployed by the user showing some
426-
aggregated information. In JSON format::
426+
Return all the infrastructures in the interval ``init_date``-``end-date`` deployed by the user
427+
showing some aggregated information. In JSON format::
427428
428429
[
429430
{"creation_date": "2022-03-07 13:16:14",

doc/swagger_api.yaml

+19-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ openapi: 3.0.0
22

33
info:
44
description: Infrastructure Manager (IM) REST API.
5-
version: 1.11.0
5+
version: 1.12.0
66
title: Infrastructure Manager (IM) REST API
77
contact:
88
@@ -47,9 +47,26 @@ paths:
4747
summary: Get IM server stats.
4848
description: >-
4949
Return the stats of the current user in the IM service.
50-
Return all the infrastructures since the init_date parameter deployed
50+
Return all the infrastructures in the interval init_date-end_date parameters deployed
5151
by the user showing some aggregated information.
5252
operationId: GetStats
53+
parameters:
54+
- name: init_date
55+
in: query
56+
description: >-
57+
The init_date parameter is optional and it is a date with format
58+
YYYY/MM/dd. Only will be returned infrastructure created afther this date.
59+
required: false
60+
schema:
61+
type: string
62+
- name: end_date
63+
in: query
64+
description: >-
65+
The end_date parameter is optional and it is a date with format
66+
YYYY/MM/dd. Only will be returned infrastructure created before this date.
67+
required: false
68+
schema:
69+
type: string
5370
responses:
5471
'200':
5572
description: successful operation

im_service.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -220,9 +220,9 @@ def ChangeInfrastructureAuth(inf_id, new_auth_data, overwrite, auth_data):
220220
return WaitRequest(request)
221221

222222

223-
def GetStats(init_date, auth_data):
223+
def GetStats(init_date, end_date, auth_data):
224224
request = IMBaseRequest.create_request(
225-
IMBaseRequest.GET_STATS, (init_date, auth_data))
225+
IMBaseRequest.GET_STATS, (init_date, end_date, auth_data))
226226
return WaitRequest(request)
227227

228228

scripts/db_1_10_to_1_12.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,10 @@ def load_data(db_url):
4545
sys.exit(-1)
4646

4747
@staticmethod
48-
def rename_old_data(db_url):
48+
def rename_old_data(db_url, now):
4949
db = DataBase(db_url)
5050
if db.connect():
5151
if db.table_exists("inf_list"):
52-
now = str(int(time.time() * 100))
5352
if db.db_type == DataBase.SQLITE:
5453
db.execute('ALTER TABLE inf_list RENAME TO inf_list_%s;' % now)
5554
db.close()
@@ -82,8 +81,9 @@ def rename_old_data(db_url):
8281
sys.stdout.write("Loading Data...\n")
8382
inf_list = DB110to112.load_data(db_url)
8483
if inf_list:
85-
sys.stdout.write("Previous table inf_list will be renamed to inf_list_XXXXXX.\n")
86-
DB110to112.rename_old_data(db_url)
84+
now = str(int(time.time() * 100))
85+
sys.stdout.write("Previous table inf_list will be renamed to inf_list_%s.\n" % now)
86+
DB110to112.rename_old_data(db_url, now)
8787
# To create the new table
8888
sys.stdout.write("Saving Data...\n")
8989
DB110to112.save_data(db_url, inf_list)

test/unit/REST.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -758,7 +758,7 @@ def test_RebootVM(self, bottle_request, StopVM):
758758
self.assertEqual(res, "Error rebooting VM: Invalid VM ID")
759759

760760
def test_GeVersion(self):
761-
res = RESTGeVersion()
761+
res = RESTGetVersion()
762762
self.assertEqual(res, version)
763763

764764
@patch("IM.InfrastructureManager.InfrastructureManager.CreateDiskSnapshot")
@@ -1081,12 +1081,13 @@ def test_GetStats(self, GetStats, bottle_request):
10811081
"""Test REST GetStats."""
10821082
bottle_request.return_value = MagicMock()
10831083
bottle_request.headers = {"AUTHORIZATION": "type = InfrastructureManager; username = user; password = pass"}
1084-
GetStats.return_value = [{"stats"}]
1085-
bottle_request.params = {'init_date': '2010-01-01'}
1084+
GetStats.return_value = [{"key": 1}]
1085+
bottle_request.params = {'init_date': '2010-01-01', 'end_date': '2022-01-01'}
10861086
res = RESTGetStats()
1087-
self.assertEqual(res, [{"stats"}])
1087+
self.assertEqual(json.loads(res), {"stats": [{"key": 1}]})
10881088
self.assertEqual(GetStats.call_args_list[0][0][0], '2010-01-01')
1089-
self.assertEqual(GetStats.call_args_list[0][0][1].auth_list, [{"type": "InfrastructureManager",
1089+
self.assertEqual(GetStats.call_args_list[0][0][1], '2022-01-01')
1090+
self.assertEqual(GetStats.call_args_list[0][0][2].auth_list, [{"type": "InfrastructureManager",
10901091
"username": "user",
10911092
"password": "pass"}])
10921093

test/unit/ServiceRequests.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ def test_change_auth(self, inflist):
204204
def test_get_stats(self, inflist):
205205
import IM.ServiceRequests
206206
req = IM.ServiceRequests.IMBaseRequest.create_request(
207-
IM.ServiceRequests.IMBaseRequest.GET_STATS, ("", ""))
207+
IM.ServiceRequests.IMBaseRequest.GET_STATS, ("", "", ""))
208208
req._call_function()
209209

210210

test/unit/test_im_logic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1418,7 +1418,7 @@ def test_get_stats(self, check_auth_data, DataBase):
14181418
db.select.return_value = [(json.dumps(inf_data), '2022-03-23', '1')]
14191419
DataBase.return_value = db
14201420

1421-
stats = IM.GetStats('2001-01-01', auth)
1421+
stats = IM.GetStats('2001-01-01', '2122-01-01', auth)
14221422
expected_res = [{'creation_date': '2022-03-07 13:16:14',
14231423
'tosca_name': 'kubernetes',
14241424
'vm_count': 2,

0 commit comments

Comments
 (0)