|
| 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 |
0 commit comments