@add_metaclass(ABCMeta)
class NodeHistoryBaseView(APIView):
TENDENCY_INTERVAL_TIME = {
'hour': '30s',
'day': '12m',
'week': '1h24m',
'month': '6h12m'
}
def get(self, request, pk, category):
hostname = Node.objects.get(id=pk).hostname
sql_history = self.get_history_sql(request, category, hostname)
logger.info("sql: %s" % (sql_history,))
try:
history = cache.get(sql_history, epoch='s')
except InfluxDBServerError or InfluxDBClientError:
raise InfluxDBException
history = self.handle_query_data(history)
sql_current = self.get_current_sql(category, hostname)
logger.info("sql: %s" % (sql_current,))
current = self.get_current_data(sql_current)
return self.return_success(history, current)
@abstractmethod #父类制定了是抽象方法,子类不能实例化此方法
def get_db_table(self):
pass
@property
def get_scale_data(self):
''' sql: select [sql value] **
handle_key: handle_query_data use handle_key'''
return {'sql': 'last(value) as value', 'handle_key': ['value']}
def get_history_sql(self, request, *args, **kwargs):
category = args[0]
hostname = args[1]
sql = "select {field_sql} from \"{categ}\".{table} where \
host=\'{host}\'".format(
field_sql=self.get_scale_data['sql'],
categ=category,
table=self.get_db_table(),
host=hostname)
sql += " and time > now() - %s" % (CATEGORY_MAPPING[category],)
sql += " group by time(%s)" % (self.TENDENCY_INTERVAL_TIME[category],)
return sql
def get_current_sql(self, category, hostname):
sql = "select last(value) from \"{categ}\".{table} where " \
"host=\'{host}\'".format(categ=category,
table=self.get_db_table(),
host=hostname
)
return sql
def get_current_data(self, sql):
ret = cache.get(sql)
current = 0
for p in ret.get_points():
current = p.get('last', 0)
return current
def handle_query_data(self, data):
return list(data.get_points())
def return_success(self, history, current):
return_data = {"history": history if history else [],
'current': current}
return Response(return_data, status=HTTP_200_OK)