Skip to content

Commit 4bac32d

Browse files
authored
Merge pull request #1622 from grycap/stats
Implements: #1353
2 parents fe9b11b + d3d3750 commit 4bac32d

12 files changed

+412
-7
lines changed

IM/InfrastructureList.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ def _save_data_to_db(db_url, inf_list, inf_id=None):
250250
return None
251251

252252
@staticmethod
253-
def _gen_where_from_auth(auth):
253+
def _gen_where_from_auth(auth, deleted=0):
254254
like = ""
255255
if auth:
256256
for elem in auth.getAuthInfo('InfrastructureManager'):
@@ -260,12 +260,12 @@ def _gen_where_from_auth(auth):
260260
like += "auth like '%%\"" + elem.get("username") + "\"%%'"
261261

262262
if like:
263-
return "where deleted = 0 and (" + like + ")"
263+
return "where deleted = %d and (%s)" % (deleted, like)
264264
else:
265-
return "where deleted = 0"
265+
return "where deleted = %d" % deleted
266266

267267
@staticmethod
268-
def _gen_filter_from_auth(auth):
268+
def _gen_filter_from_auth(auth, deleted=0):
269269
like = ""
270270
if auth:
271271
for elem in auth.getAuthInfo('InfrastructureManager'):
@@ -275,9 +275,9 @@ def _gen_filter_from_auth(auth):
275275
like += '"%s"' % elem.get("username")
276276

277277
if like:
278-
return {"deleted": 0, "auth": {"$regex": like}}
278+
return {"deleted": deleted, "auth": {"$regex": like}}
279279
else:
280-
return {"deleted": 0}
280+
return {"deleted": deleted}
281281

282282
@staticmethod
283283
def _get_inf_ids_from_db(auth=None):

IM/InfrastructureManager.py

+19
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
from IM.openid.JWT import JWT
4343
from IM.openid.OpenIDClient import OpenIDClient
4444
from IM.vault import VaultCredentials
45+
from IM.Stats import Stats
4546

4647

4748
if Config.MAX_SIMULTANEOUS_LAUNCHES > 1:
@@ -2036,3 +2037,21 @@ def EstimateResouces(radl_data, auth):
20362037
cont += 1
20372038

20382039
return res
2040+
2041+
@staticmethod
2042+
def GetStats(init_date, end_date, auth):
2043+
"""
2044+
Get the statistics from the IM DB.
2045+
Args:
2046+
- init_date(str): Only will be returned infrastructure created afther this date.
2047+
- end_date(str): Only will be returned infrastructure created before this date.
2048+
- auth(Authentication): parsed authentication tokens.
2049+
Return: a list of dict with the stats.
2050+
"""
2051+
# First check the auth data
2052+
auth = InfrastructureManager.check_auth_data(auth)
2053+
stats = Stats.get_stats(init_date, end_date, auth)
2054+
if not stats:
2055+
raise Exception("ERROR connecting with the database!.")
2056+
else:
2057+
return stats

IM/REST.py

+44
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import flask
2222
import os
2323
import yaml
24+
import datetime
2425

2526
from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
2627
from cheroot.ssl.builtin import BuiltinSSLAdapter
@@ -1077,6 +1078,49 @@ def RESTChangeInfrastructureAuth(infid=None):
10771078
return return_error(400, "Error modifying infrastructure owner: %s" % get_ex_error(ex))
10781079

10791080

1081+
@app.route('/stats', methods=['GET'])
1082+
def RESTGetStats():
1083+
try:
1084+
auth = get_auth_header()
1085+
except Exception:
1086+
return return_error(401, "No authentication data provided")
1087+
1088+
try:
1089+
init_date = None
1090+
if "init_date" in flask.request.args.keys():
1091+
init_date = flask.request.args.get("init_date").lower()
1092+
init_date = init_date.replace("/", "-")
1093+
parts = init_date.split("-")
1094+
try:
1095+
year = int(parts[0])
1096+
month = int(parts[1])
1097+
day = int(parts[2])
1098+
datetime.date(year, month, day)
1099+
except Exception:
1100+
return return_error(400, "Incorrect format in init_date parameter: YYYY/MM/dd")
1101+
else:
1102+
init_date = "1970-01-01"
1103+
1104+
end_date = None
1105+
if "end_date" in flask.request.args.keys():
1106+
end_date = flask.request.args.get("end_date").lower()
1107+
end_date = end_date.replace("/", "-")
1108+
parts = end_date.split("-")
1109+
try:
1110+
year = int(parts[0])
1111+
month = int(parts[1])
1112+
day = int(parts[2])
1113+
datetime.date(year, month, day)
1114+
except Exception:
1115+
return return_error(400, "Incorrect format in end_date parameter: YYYY/MM/dd")
1116+
1117+
stats = InfrastructureManager.GetStats(init_date, end_date, auth)
1118+
return format_output(stats, default_type="application/json", field_name="stats")
1119+
except Exception as ex:
1120+
logger.exception("Error getting stats")
1121+
return return_error(400, "Error getting stats: %s" % get_ex_error(ex))
1122+
1123+
10801124
@app.errorhandler(403)
10811125
def error_mesage_403(error):
10821126
return return_error(403, error.description)

IM/ServiceRequests.py

+14
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ class IMBaseRequest(AsyncRequest):
6060
CHANGE_INFRASTRUCTURE_AUTH = "ChangeInfrastructureAuth"
6161
GET_INFRASTRUCTURE_OWNERS = "GetInfrastructureOwners"
6262
ESTIMATE_RESOURCES = "EstimateResouces"
63+
GET_STATS = "GetStats"
6364

6465
@staticmethod
6566
def create_request(function, arguments=()):
@@ -119,6 +120,8 @@ def create_request(function, arguments=()):
119120
return Request_GetInfrastructureOwners(arguments)
120121
elif function == IMBaseRequest.ESTIMATE_RESOURCES:
121122
return Request_EstimateResouces(arguments)
123+
elif function == IMBaseRequest.GET_STATS:
124+
return Request_GetStats(arguments)
122125
else:
123126
raise NotImplementedError("Function not Implemented")
124127

@@ -473,3 +476,14 @@ def _call_function(self):
473476
self._error_mesage = "Error getting the resources estimation"
474477
(radl_data, auth_data) = self.arguments
475478
return IM.InfrastructureManager.InfrastructureManager.EstimateResouces(radl_data, Authentication(auth_data))
479+
480+
481+
class Request_GetStats(IMBaseRequest):
482+
"""
483+
Request class for the GetStats function
484+
"""
485+
486+
def _call_function(self):
487+
self._error_mesage = "Error getting stats"
488+
(init_date, end_date, auth_data) = self.arguments
489+
return IM.InfrastructureManager.InfrastructureManager.GetStats(init_date, end_date, Authentication(auth_data))

IM/Stats.py

+148
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# IM - Infrastructure Manager
2+
# Copyright (C) 2011 - GRyCAP - Universitat Politecnica de Valencia
3+
#
4+
# This program is free software: you can redistribute it and/or modify
5+
# it under the terms of the GNU General Public License as published by
6+
# the Free Software Foundation, either version 3 of the License, or
7+
# (at your option) any later version.
8+
#
9+
# This program is distributed in the hope that it will be useful,
10+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
# GNU General Public License for more details.
13+
#
14+
# You should have received a copy of the GNU General Public License
15+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
16+
17+
import os.path
18+
import datetime
19+
import json
20+
import yaml
21+
import logging
22+
23+
from IM.db import DataBase
24+
from IM.auth import Authentication
25+
from IM.config import Config
26+
from IM.InfrastructureList import InfrastructureList
27+
from radl.radl_parse import parse_radl
28+
29+
30+
class Stats():
31+
32+
logger = logging.getLogger('InfrastructureManager')
33+
"""Logger object."""
34+
35+
@staticmethod
36+
def _get_data(str_data, init_date=None, end_date=None):
37+
dic = json.loads(str_data)
38+
resp = {'creation_date': None}
39+
if 'creation_date' in dic and dic['creation_date']:
40+
creation_date = datetime.datetime.fromtimestamp(float(dic['creation_date']))
41+
resp['creation_date'] = str(creation_date)
42+
if init_date and creation_date < init_date:
43+
return None
44+
if end_date and creation_date > end_date:
45+
return None
46+
47+
resp['tosca_name'] = None
48+
if 'extra_info' in dic and dic['extra_info'] and "TOSCA" in dic['extra_info']:
49+
try:
50+
tosca = yaml.safe_load(dic['extra_info']['TOSCA'])
51+
icon = tosca.get("metadata", {}).get("icon", "")
52+
resp['tosca_name'] = os.path.basename(icon)[:-4]
53+
except Exception:
54+
Stats.logger.exception("Error loading TOSCA.")
55+
56+
resp['vm_count'] = 0
57+
resp['cpu_count'] = 0
58+
resp['memory_size'] = 0
59+
resp['cloud_type'] = None
60+
resp['cloud_host'] = None
61+
resp['hybrid'] = False
62+
resp['deleted'] = True if 'deleted' in dic and dic['deleted'] else False
63+
for str_vm_data in dic['vm_list']:
64+
vm_data = json.loads(str_vm_data)
65+
cloud_data = json.loads(vm_data["cloud"])
66+
67+
# only get the cloud of the first VM
68+
if not resp['cloud_type']:
69+
resp['cloud_type'] = cloud_data["type"]
70+
if not resp['cloud_host']:
71+
resp['cloud_host'] = cloud_data["server"]
72+
elif resp['cloud_host'] != cloud_data["server"]:
73+
resp['hybrid'] = True
74+
75+
vm_sys = parse_radl(vm_data['info']).systems[0]
76+
if vm_sys.getValue('cpu.count'):
77+
resp['cpu_count'] += vm_sys.getValue('cpu.count')
78+
if vm_sys.getValue('memory.size'):
79+
resp['memory_size'] += vm_sys.getFeature('memory.size').getValue('M')
80+
resp['vm_count'] += 1
81+
82+
inf_auth = Authentication.deserialize(dic['auth']).getAuthInfo('InfrastructureManager')[0]
83+
resp['im_user'] = inf_auth.get('username')
84+
return resp
85+
86+
@staticmethod
87+
def get_stats(init_date="1970-01-01", end_date=None, auth=None):
88+
"""
89+
Get the statistics from the IM DB.
90+
91+
Args:
92+
93+
- init_date(str): Only will be returned infrastructure created afther this date.
94+
- end_date(str): Only will be returned infrastructure created afther this date.
95+
- auth(Authentication): parsed authentication tokens.
96+
97+
Return: a list of dict with the stats with the following format:
98+
{'creation_date': '2022-03-07 13:16:14',
99+
'tosca_name': 'kubernetes',
100+
'vm_count': 2,
101+
'cpu_count': 4,
102+
'memory_size': 1024,
103+
'cloud_type': 'OSCAR',
104+
'cloud_host': 'sharp-elbakyan5.im.grycap.net',
105+
'hybrid': False,
106+
'im_user': '__OPENID__mcaballer',
107+
'inf_id': '1',
108+
'deleted': False,
109+
'last_date': '2022-03-23'}
110+
"""
111+
stats = []
112+
db = DataBase(Config.DATA_DB)
113+
if db.connect():
114+
if db.db_type == DataBase.MONGO:
115+
filt = InfrastructureList._gen_filter_from_auth(auth, 1)
116+
if end_date:
117+
filt["date"] = {"$lte": end_date}
118+
res = db.find("inf_list", filt, {"id": True, "data": True, "date": True}, [('id', -1)])
119+
else:
120+
where = InfrastructureList._gen_where_from_auth(auth, 1)
121+
if end_date:
122+
where += " and date <= '%s'" % end_date
123+
res = db.select("select data, date, id from inf_list %s order by rowid desc" % where)
124+
125+
for elem in res:
126+
if db.db_type == DataBase.MONGO:
127+
data = elem["data"]
128+
date = elem["date"]
129+
inf_id = elem["id"]
130+
else:
131+
data = elem[0]
132+
date = elem[1]
133+
inf_id = elem[2]
134+
try:
135+
init = datetime.datetime.strptime(init_date, "%Y-%m-%d")
136+
end = datetime.datetime.strptime(end_date, "%Y-%m-%d") if end_date else None
137+
res = Stats._get_data(data, init, end)
138+
if res:
139+
res['inf_id'] = inf_id
140+
res['last_date'] = str(date)
141+
stats.append(res)
142+
except Exception:
143+
Stats.logger.exception("ERROR reading infrastructure info from Inf ID: %s" % inf_id)
144+
db.close()
145+
return stats
146+
else:
147+
Stats.logger.error("ERROR connecting with the database!.")
148+
return None

IM/im_service.py

+7
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,12 @@ def EstimateResources(radl_data, auth_data):
229229
return WaitRequest(request)
230230

231231

232+
def GetStats(init_date, end_date, auth_data):
233+
request = IMBaseRequest.create_request(
234+
IMBaseRequest.GET_STATS, (init_date, end_date, auth_data))
235+
return WaitRequest(request)
236+
237+
232238
def launch_daemon():
233239
"""
234240
Launch the IM daemon
@@ -290,6 +296,7 @@ def launch_daemon():
290296
server.register_function(ChangeInfrastructureAuth)
291297
server.register_function(GetInfrastructureOwners)
292298
server.register_function(EstimateResources)
299+
server.register_function(GetStats)
293300

294301
# Launch the API XMLRPC thread
295302
server.serve_forever_in_thread()

0 commit comments

Comments
 (0)