Esempio n. 1
0
    def update_specific_rule(self, tenantId, serverId, ruleId, rule):
        """Updates a specific rule

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        :param str rule:        The rule description in json format
        """

        rule_db = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId, entity__exact=serverId)
        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)

        rule_db.action = action
        rule_db.name = name
        rule_db.condition = condition
        modifiedAction = self.pimp_rule_action(action, name, serverId)
        modifiedCondition = self.pimp_rule_condition(condition, name, serverId)
        rule_db.clips_action = modifiedAction
        rule_db.clips_condition = modifiedCondition
        rule_db.save()
        ruleResult = RuleModel()
        ruleResult.ruleId = str(ruleId)
        ruleResult.name = name
        ruleResult.condition = condition
        ruleResult.action = action
        logger.info("RuleId %s was updated" % str(ruleId))
        return ruleResult
Esempio n. 2
0
    def updateWindowSize(self, tenantId, newSize):
        """Updates windowsize of a specified tenant."""
        self.checkSize(newSize)
        t = self.tenantInfo.objects.get(tenantId__exact=tenantId)
        t.windowsize = newSize
        t.save()
        message = tenantId + " " + str(newSize)
        logger.info("%s", message)

        self.publish_message(message)

        logger.info("%s windowsize updated to %d", tenantId, newSize)
        return t
Esempio n. 3
0
    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
Esempio n. 4
0
    def delete_specific_rule(self, tenantId, serverId, ruleId):
        """Deletes a specific rule.

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        """
        r_query = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId, entity__exact=serverId)
        r_query.delete()

        #Deleting subscriptions to that rule
        subscriptions = Subscription.objects.filter(ruleId__exact=ruleId)
        subscriptions.delete()
        logger.info("RuleId %s from server %s was deleted" % (ruleId, serverId))
        return True
Esempio n. 5
0
    def contextBrokerUnSubscription(self, cbSubscriptionId, serverId):
        """Unsubscribes server from Context Broker """
        headers = {"Content-Type": "application/json", "Accept": "application/json"}
        data = json.dumps('{"subscriptionId": "%s"}' % cbSubscriptionId)

        r = self.client.post(settings.CONTEXT_BROKER_URL + "/unsubscribeContext", data, headers=headers)
        if r.status_code == 200:
            logger.info(
                "Server %s was unsubscribed from Context Broker.--- HTTP Response: %d" % (serverId, r.status_code)
            )
        else:
            logger.error(
                "ERROR, Server %s was not unsubscribed from Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code)
            )
            raise SystemError("ERROR, Server %s was not unsubscribed.--- HTTP Response: %d" % (serverId, r.status_code))
Esempio n. 6
0
    def unsubscribe_to_rule(self, serverId, subscriptionId):
        """Unsuscribe a server from a rule.

        :param str tenantId:        The id of the tenant
        :param str serverId:        The id of the server
        :param str subscriptionId:  The id of the subscription
        """

        r_query = Subscription.objects.get(subscription_Id__exact=subscriptionId, serverId__exact=serverId)
        if Subscription.objects.filter(serverId__exact=serverId).count() == 1:
            self.orionClient.contextBrokerUnSubscription(r_query.cbSubscriptionId, r_query.serverId)
            r_query.delete()
        else:
            r_query.delete()
        logger.info("Server %s was unsubscribed to this subscription: %s"
                        % (serverId, subscriptionId))
        return True
Esempio n. 7
0
    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
Esempio n. 8
0
    def delete_specific_rule(self, tenantId, serverId, ruleId):
        """Deletes a specific rule.

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        """
        r_query = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId,
                                           entity__exact=serverId)
        r_query.delete()

        #Deleting subscriptions to that rule
        subscriptions = Subscription.objects.filter(ruleId__exact=ruleId)
        subscriptions.delete()
        logger.info("RuleId %s from server %s was deleted" %
                    (ruleId, serverId))
        return True
Esempio n. 9
0
    def unsubscribe_to_rule(self, serverId, subscriptionId):
        """Unsuscribe a server from a rule.

        :param str tenantId:        The id of the tenant
        :param str serverId:        The id of the server
        :param str subscriptionId:  The id of the subscription
        """

        r_query = Subscription.objects.get(
            subscription_Id__exact=subscriptionId, serverId__exact=serverId)
        if Subscription.objects.filter(serverId__exact=serverId).count() == 1:
            self.orionClient.contextBrokerUnSubscription(
                r_query.cbSubscriptionId, r_query.serverId)
            r_query.delete()
        else:
            r_query.delete()
        logger.info("Server %s was unsubscribed to this subscription: %s" %
                    (serverId, subscriptionId))
        return True
Esempio n. 10
0
    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
Esempio n. 11
0
    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
Esempio n. 12
0
    def contextBrokerSubscription(self, tenantId, serverId):
        """Subscribes server to Context Broker to get information about cpu and memory monitoring"""

        headers = {CONTENT_HEADER: JSON_TYPE, ACCEPT_HEADER: JSON_TYPE}

        data = '{"entities": [' \
               '{"type": "Server",'\
               '"isPattern": "false",' \
                          '"id": "' + serverId + '"' \
                          '}],' \
                '"attributes": [' \
                            '"cpu",' \
                            '"mem"],' \
                            '"reference": "' + settings.NOTIFICATION_URL + '/' + \
                            tenantId + 'servers/' + serverId + '",' \
                            '"duration": "P1M",' \
                            '"notifyConditions": [' \
                            '{"type": "' + settings.NOTIFICATION_TYPE + '",' \
                            '"condValues": ["' + settings.NOTIFICATION_TIME + '"]}]}'

        r = self.client.post(settings.CONTEXT_BROKER_URL + "/subscribeContext",
                             data,
                             headers=headers)

        if r.status_code == 200:
            decoded = json.loads(r.text.decode())
            logger.info(
                "Server %s was subscribed to Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code))

        else:
            logger.error(
                "ERROR, Server %s was not subscribed to Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code))
            raise SystemError(
                "ERROR, Server %s was not subscribed to Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code))

        return decoded["subscribeResponse"]["subscriptionId"]
Esempio n. 13
0
    def contextBrokerSubscription(self, tenantId, serverId):
        """Subscribes server to Context Broker to get information about cpu and memory monitoring"""

        headers = {CONTENT_HEADER: JSON_TYPE, ACCEPT_HEADER: JSON_TYPE}

        data = (
            '{"entities": ['
            '{"type": "Server",'
            '"isPattern": "false",'
            '"id": "' + serverId + '"'
            "}],"
            '"attributes": ['
            '"cpu",'
            '"mem"],'
            '"reference": "' + settings.NOTIFICATION_URL + "/" + tenantId + "servers/" + serverId + '",'
            '"duration": "P1M",'
            '"notifyConditions": ['
            '{"type": "' + settings.NOTIFICATION_TYPE + '",'
            '"condValues": ["' + settings.NOTIFICATION_TIME + '"]}]}'
        )

        r = self.client.post(settings.CONTEXT_BROKER_URL + "/subscribeContext", data, headers=headers)

        if r.status_code == 200:
            decoded = json.loads(r.text.decode())
            logger.info("Server %s was subscribed to Context Broker.--- HTTP Response: %d" % (serverId, r.status_code))

        else:
            logger.error(
                "ERROR, Server %s was not subscribed to Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code)
            )
            raise SystemError(
                "ERROR, Server %s was not subscribed to Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code)
            )

        return decoded["subscribeResponse"]["subscriptionId"]
Esempio n. 14
0
    def contextBrokerUnSubscription(self, cbSubscriptionId, serverId):
        """Unsubscribes server from Context Broker """
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        data = json.dumps("{\"subscriptionId\": \"%s\"}" % cbSubscriptionId)

        r = self.client.post(settings.CONTEXT_BROKER_URL +
                             "/unsubscribeContext",
                             data,
                             headers=headers)
        if r.status_code == 200:
            logger.info(
                "Server %s was unsubscribed from Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code))
        else:
            logger.error(
                "ERROR, Server %s was not unsubscribed from Context Broker.--- HTTP Response: %d"
                % (serverId, r.status_code))
            raise SystemError(
                "ERROR, Server %s was not unsubscribed.--- HTTP Response: %d" %
                (serverId, r.status_code))
Esempio n. 15
0
    def update_specific_rule(self, tenantId, serverId, ruleId, rule):
        """Updates a specific rule

        :param str tenantId:    The id of the tenant
        :param str serverId:    The id of the server
        :param str ruleId:      The id of the rule
        :param str rule:        The rule description in json format
        """

        rule_db = SpecificRule.objects.get(specificRule_Id__exact=ruleId,
                                           tenantId__exact=tenantId,
                                           entity__exact=serverId)
        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)

        rule_db.action = action
        rule_db.name = name
        rule_db.condition = condition
        modifiedAction = self.pimp_rule_action(action, name, serverId)
        modifiedCondition = self.pimp_rule_condition(condition, name, serverId)
        rule_db.clips_action = modifiedAction
        rule_db.clips_condition = modifiedCondition
        rule_db.save()
        ruleResult = RuleModel()
        ruleResult.ruleId = str(ruleId)
        ruleResult.name = name
        ruleResult.condition = condition
        ruleResult.action = action
        logger.info("RuleId %s was updated" % str(ruleId))
        return ruleResult
Esempio n. 16
0
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from fiware_cloto.environments import environment_controller
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

import datetime

from django.utils import timezone
from fiware_cloto.cloto.models import ServerInfo
from django.conf import settings
from fiware_cloto.cloto.utils.log import logger

runningfrom = datetime.datetime.now(tz=timezone.get_default_timezone())
# Creating initial data
s = ServerInfo(id=1, owner=settings.OWNER, version=settings.VERSION,
               runningfrom=runningfrom, doc=settings.API_INFO_URL)
try:
    s.save()
except Exception as ex:
    logger.error("Error saving initial server data into DB while server was starting: %s", ex)

# Starting environments Controller
controller = environment_controller.environment_controller()
if not controller.is_started():
    controller.start_manager()

logger.info("SERVER STARTED")
Esempio n. 17
0
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

import datetime

from django.utils import timezone
from fiware_cloto.cloto.models import ServerInfo
from django.conf import settings
from fiware_cloto.cloto.utils.log import logger

runningfrom = datetime.datetime.now(tz=timezone.get_default_timezone())
# Creating initial data
s = ServerInfo(id=1,
               owner=settings.OWNER,
               version=settings.VERSION,
               runningfrom=runningfrom,
               doc=settings.API_INFO_URL)
try:
    s.save()
except Exception as ex:
    logger.error(
        "Error saving initial server data into DB while server was starting: %s",
        ex)

# Starting environments Controller
controller = environment_controller.environment_controller()
if not controller.is_started():
    controller.start_manager()

logger.info("SERVER STARTED")