def create_specific_rule(self, tenantId, serverId, rule): """Creates a new specific rule for a server :param str tenantId: The id of the tenant :param str serverId: The id of the server :param str rule: The rule description in json format """ try: entity = Entity.objects.get(serverId__exact=serverId) except Entity.DoesNotExist as err: entity = Entity(serverId=serverId, tenantId=tenantId) entity.save() try: condition = self.getContition(rule) action = self.getAction(rule) name = self.getName(rule) except Exception as err: raise ValueError(str(err) + " is missing") self.checkRule(name, condition, action) #Its necesary modify action to get subscriptionId modifiedAction = self.pimp_rule_action(action, name, serverId) modifiedCondition = self.pimp_rule_condition(condition, name, serverId) createdAt = datetime.datetime.now(tz=timezone.get_default_timezone()) ruleId = uuid.uuid1() rule = SpecificRule(specificRule_Id=ruleId, tenantId=tenantId, name=name, condition=condition, action=action, clips_condition=modifiedCondition, clips_action=modifiedAction, createdAt=createdAt) """try: rule = SpecificRule.objects.get(serverId__exact=serverId, ) raise ValueError("rule name already exists") except Entity.DoesNotExist as err: entity = Entity(serverId=serverId, tenantId=tenantId)""" rule.save() entity.specificrules.add(rule) rule.save() ruleResult = RuleModel() ruleResult.ruleId = str(ruleId) logger.info("RuleId %s was created for server %s" % (str(ruleId), serverId)) return ruleResult
def subscribe_to_rule(self, tenantId, serverId, subscription): """Creates a server subscription to a rule. :param str tenantId: The id of the tenant :param str serverId: The id of the server :param str subscription: The subscription description in json format """ context_broker_subscription = False try: entity = Entity.objects.get(serverId__exact=serverId) except Entity.DoesNotExist as err: entity = Entity(serverId=serverId, tenantId=tenantId) entity.save() ruleId = json.loads(subscription)['ruleId'] SpecificRule.objects.get(specificRule_Id__exact=ruleId, entity__exact=serverId) url = json.loads(subscription)['url'] #Verify that there is no more subscriptions to the rule for that server it = entity.subscription.iterator() for sub in it: if sub.serverId == serverId: context_broker_subscription = sub.cbSubscriptionId if sub.ruleId == ruleId: raise Conflict("Subscription already exists") self.verify_url(url) if not context_broker_subscription: cbSubscriptionId = self.orionClient.contextBrokerSubscription(tenantId, serverId) else: cbSubscriptionId = context_broker_subscription subscription_Id = uuid.uuid1() subscr = Subscription(subscription_Id=subscription_Id, ruleId=ruleId, url=url, serverId=serverId, cbSubscriptionId=cbSubscriptionId) subscr.save() entity.subscription.add(subscr) entity.save() logger.info("Server %s was subscribed to rule %s: cbSubscriptionId is %s and internal subscription %s" % (serverId, ruleId, cbSubscriptionId, str(subscription_Id))) return subscription_Id
def subscribe_to_rule(self, tenantId, serverId, subscription): """Creates a server subscription to a rule. :param str tenantId: The id of the tenant :param str serverId: The id of the server :param str subscription: The subscription description in json format """ context_broker_subscription = False try: entity = Entity.objects.get(serverId__exact=serverId) except Entity.DoesNotExist as err: entity = Entity(serverId=serverId, tenantId=tenantId) entity.save() ruleId = json.loads(subscription)['ruleId'] SpecificRule.objects.get(specificRule_Id__exact=ruleId, entity__exact=serverId) url = json.loads(subscription)['url'] #Verify that there is no more subscriptions to the rule for that server it = entity.subscription.iterator() for sub in it: if sub.serverId == serverId: context_broker_subscription = sub.cbSubscriptionId if sub.ruleId == ruleId: raise Conflict("Subscription already exists") self.verify_url(url) if not context_broker_subscription: cbSubscriptionId = self.orionClient.contextBrokerSubscription( tenantId, serverId) else: cbSubscriptionId = context_broker_subscription subscription_Id = uuid.uuid1() subscr = Subscription(subscription_Id=subscription_Id, ruleId=ruleId, url=url, serverId=serverId, cbSubscriptionId=cbSubscriptionId) subscr.save() entity.subscription.add(subscr) entity.save() logger.info( "Server %s was subscribed to rule %s: cbSubscriptionId is %s and internal subscription %s" % (serverId, ruleId, cbSubscriptionId, str(subscription_Id))) return subscription_Id
def setUp(self): self.rule = '{\"name\": \"test Name\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"hdd\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"net\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.ruleUpdated = '{\"name\": \"test Name2\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"hdd\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"net\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": {\"actionName\": \"notify-email\", \"body\": \"test body\",' \ ' \"email\": \"[email protected]\"}}' self.ruleFake1 = '{\"name\": \"te\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.ruleFake2 = '{\"name\": \"test Name\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": \"\"}' self.ruleFake3 = '{\"name\": \"test Name\", \"condition\": \"\",' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.ruleFake4 = '{\"name\": \"test Name\",' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.tenantId = "tenantId" self.serverId = "serverId" self.newServerId = "ServerIdThatNoExists" entity = Entity(serverId=self.serverId, tenantId=self.tenantId) entity.save() CONTEXT_BROKER_URL_FAIL = "http://130.206.82.0:1026/NGSI10" self.ruleManager = RuleManager.RuleManager() self.mockedClient = mock() self.OrionClientError = mock() response = Response() responseFailure = Response() self.subscription_failure = "{Invalid subscription body}" responseFailure.status_code = 400 response.status_code = 200 self.expected_cbSubscriptionId = "51c04a21d714fb3b37d7d5a7" response._content = "{\"subscribeResponse\": {" \ "\"duration\": \"P1M\"," \ "\"subscriptionId\": \"%s\"" \ "}" \ "}" % self.expected_cbSubscriptionId headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } #data to subscription data = '{"entities": [' \ '{"type": "Server",'\ '"isPattern": "false",' \ '"id": "' + self.newServerId + '"' \ '}],' \ '"attributes": [' \ '"cpu",' \ '"mem"],' \ '"reference": "' + settings.NOTIFICATION_URL + '/' + self.tenantId + 'servers/' + \ self.newServerId + '",' \ '"duration": "P1M",' \ '"notifyConditions": [' \ '{"type": "' + settings.NOTIFICATION_TYPE + '",' \ '"condValues": ["' + settings.NOTIFICATION_TIME + '"]}]}' #data2 for unsubscription data2 = json.dumps("{\"subscriptionId\": \"%s\"}" % self.expected_cbSubscriptionId) when(self.mockedClient).post(settings.CONTEXT_BROKER_URL + "/subscribeContext", data, headers=headers)\ .thenReturn(response) when(self.mockedClient).post(settings.CONTEXT_BROKER_URL + "/unsubscribeContext", data2, headers=headers)\ .thenReturn(response) when(self.OrionClientError).post(settings.CONTEXT_BROKER_URL + "/subscribeContext", data, headers=headers)\ .thenReturn(responseFailure) when(self.OrionClientError).post(settings.CONTEXT_BROKER_URL + "/unsubscribeContext", data2, headers=headers)\ .thenReturn(responseFailure) self.ruleManager.orionClient.client = self.mockedClient rule = RuleManager.RuleManager().create_specific_rule( self.tenantId, self.serverId, self.rule)
def setUp(self): self.rule = '{\"name\": \"test Name\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"hdd\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"net\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.ruleUpdated = '{\"name\": \"test Name2\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"hdd\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"net\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": {\"actionName\": \"notify-email\", \"body\": \"test body\",' \ ' \"email\": \"[email protected]\"}}' self.ruleFake1 = '{\"name\": \"te\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.ruleFake2 = '{\"name\": \"test Name\", \"condition\": ' \ '{\"cpu\": {\"value\": 98, \"operand\": \"greater\"},' \ ' \"mem\": {\"value\": 95, \"operand\": \"greater equal\"}},' \ '\"action\": \"\"}' self.ruleFake3 = '{\"name\": \"test Name\", \"condition\": \"\",' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.ruleFake4 = '{\"name\": \"test Name\",' \ '\"action\": {\"actionName\": \"notify-scale\", \"operation\": \"scaleUp\"}}' self.tenantId = "tenantId" self.serverId = "serverId" self.newServerId = "ServerIdThatNoExists" entity = Entity(serverId=self.serverId, tenantId=self.tenantId) entity.save() CONTEXT_BROKER_URL_FAIL = "http://130.206.82.0:1026/NGSI10" self.ruleManager = RuleManager.RuleManager() self.mockedClient = mock() self.OrionClientError = mock() response = Response() responseFailure = Response() self.subscription_failure = "{Invalid subscription body}" responseFailure.status_code = 400 response.status_code = 200 self.expected_cbSubscriptionId = "51c04a21d714fb3b37d7d5a7" response._content = "{\"subscribeResponse\": {" \ "\"duration\": \"P1M\"," \ "\"subscriptionId\": \"%s\"" \ "}" \ "}" % self.expected_cbSubscriptionId headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} #data to subscription data = '{"entities": [' \ '{"type": "Server",'\ '"isPattern": "false",' \ '"id": "' + self.newServerId + '"' \ '}],' \ '"attributes": [' \ '"cpu",' \ '"mem"],' \ '"reference": "' + settings.NOTIFICATION_URL + '/' + self.tenantId + 'servers/' + \ self.newServerId + '",' \ '"duration": "P1M",' \ '"notifyConditions": [' \ '{"type": "' + settings.NOTIFICATION_TYPE + '",' \ '"condValues": ["' + settings.NOTIFICATION_TIME + '"]}]}' #data2 for unsubscription data2 = json.dumps("{\"subscriptionId\": \"%s\"}" % self.expected_cbSubscriptionId) when(self.mockedClient).post(settings.CONTEXT_BROKER_URL + "/subscribeContext", data, headers=headers)\ .thenReturn(response) when(self.mockedClient).post(settings.CONTEXT_BROKER_URL + "/unsubscribeContext", data2, headers=headers)\ .thenReturn(response) when(self.OrionClientError).post(settings.CONTEXT_BROKER_URL + "/subscribeContext", data, headers=headers)\ .thenReturn(responseFailure) when(self.OrionClientError).post(settings.CONTEXT_BROKER_URL + "/unsubscribeContext", data2, headers=headers)\ .thenReturn(responseFailure) self.ruleManager.orionClient.client = self.mockedClient rule = RuleManager.RuleManager().create_specific_rule(self.tenantId, self.serverId, self.rule)