keyrequest_monitor/SLO.py

151 lines
4.5 KiB
Python

try:
# Python 3
from collections.abc import MutableSequence
except ImportError:
# Python 2.7
from collections import MutableSequence
class KeyRequestGroup(MutableSequence):
"""A container for manipulating lists of hosts"""
def __init__(self, data=None):
"""Initialize the class"""
super(KeyRequestGroup, self).__init__()
if (data is not None):
self._list = list(data)
else:
self._list = list()
def __repr__(self):
return "<{0} {1}>".format(self.__class__.__name__, self._list)
def __len__(self):
"""List length"""
return len(self._list)
def __getitem__(self, ii):
"""Get a list item"""
if isinstance(ii, slice):
return self.__class__(self._list[ii])
else:
return self._list[ii]
def __delitem__(self, ii):
"""Delete an item"""
del self._list[ii]
def __setitem__(self, ii, val):
# optional: self._acl_check(val)
self._list[ii] = val
def __str__(self):
return str(self._list)
def createExistsQuery(self, val):
query="type(service_method)"
val['services'] = list(map(lambda x: x.replace("~","") , val['services']))
val['methods'] = list(map(lambda x: x.replace("~","") , val['methods']))
#case Service Names exists
if len(val["services"]) > 0:
if val["services"][0].startswith("SERVICE-"):
query+=",fromRelationship.isServiceMethodOfService(type(\"SERVICE\"),entityId(\""+'","'.join(val["services"])+"\"))"
else:
query+=",fromRelationship.isServiceMethodOfService(type(\"SERVICE\"),entityName.in(\""+'","'.join(val["services"])+"\"))"
if val["methods"][0].startswith("SERVICE_METHOD-"):
query+=",entityId(\""+'","'.join(val["methods"])+"\")"
else:
query+=",entityName.in(\""+'","'.join(val["methods"])+"\")"
val["existsQuery"]= query
def insert(self, ii, val):
self.createExistsQuery(val)
self._list.insert(ii, val)
def append(self, val):
if len(self._list) == 0:
#self._list.insert(ii, val)
self.insert(len(self._list), val)
return
for group in self._list:
if len(set(group["services"]) - set(val["services"])) > 0 or len(set(group["methods"]) - set(val["methods"])) > 0:
self.insert(len(self._list), val)
from helper import get_request,contains
class SLO:
def getNotExistingKeyRequests(self):
return [k for k in self.keyRequests if k['exists']==False]
def hasNotExistingKeyRequests(self):
for k in self.keyRequests:
if k['exists']==False:
return True
return False
def checkKeyRequetsExists(self, DTAPIURL, DTAPIToken):
DTAPIURL = DTAPIURL + "/api/v2/entities"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Api-Token ' + DTAPIToken
}
for group in self.keyRequestGroup:
params={"entitySelector": group["existsQuery"]}
response = get_request(DTAPIURL, headers, params)
entities = (response.json())['entities']
for method in group["methods"]:
comparer=None
if method.startswith('SERVICE_METHOD-'):
comparer="entityId"
else:
comparer="displayName"
found = [x for x in entities if x[comparer] == method]
if len(found) > 0:
#Keyrequest exists
tmp=found[0]
tmp["exists"]=True
else:
#Keyrequest not exists
tmp={"displayName":method,"type": "SERVICE_METHOD", "entityId":method, "exists":False}
self.keyRequests.append(tmp)
def checkKeyRequestsHasData(self):
pass
def __init__(self,
sloName,
env,
metricExpression,
filter,
keyRequests_groups: KeyRequestGroup = None):
self.sloName=sloName
self.env=env
self.metricExpression=metricExpression
self.filter=filter
if keyRequests_groups == None:
self.keyRequestGroup = KeyRequestGroup()
else:
self.keyRequestGroup = keyRequests_groups
self.keyRequests=[]