Exemplo n.º 1
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))
Exemplo n.º 2
0
    def get_auth_token(self, username, password, tenant_id, **kwargs):
        """
        Init the variables related to authorization, needed to execute tests
        :return: The auth token retrieved
        """
        if self.auth_token is None:

            cred_kwargs = {
                'auth_url': self.identity_url,
                'username': username,
                'password': password
            }

            # Currently, both v2 and v3 Identity API versions are supported
            if self.api_version == AUTH_API_V2:
                cred_kwargs['tenant_name'] = kwargs.get('tenant_name')
            elif self.api_version == AUTH_API_V3:
                cred_kwargs['user_domain_name'] = kwargs.get(
                    'user_domain_name')

            # Instantiate a Password object
            try:
                identity_package = 'keystoneclient.auth.identity.%s' % self.api_version.replace(
                    '.0', '')
                identity_module = __import__(identity_package,
                                             fromlist=['Password'])
                password_class = getattr(identity_module, 'Password')
                logger.debug("Authentication with %s", password_class)
                credentials = password_class(**cred_kwargs)
            except (ImportError, AttributeError) as e:
                raise e
            # Get auth token
            logger.debug("Getting auth token for tenant %s...", tenant_id)
            try:
                auth_sess = self.session.Session(
                    auth=credentials, timeout=DEFAULT_REQUEST_TIMEOUT)
                self.auth_token = auth_sess.get_token()
                logger.debug("Admin token generated: %s", self.auth_token)

            except Exception as e:
                logger.error("No auth token (%s)", e.message)
                raise (e)

        return self.auth_token
Exemplo n.º 3
0
    def get_auth_token(self, username, password, tenant_id, auth_api, url, **kwargs):
        """
        Init the variables related to authorization, needed to execute tests
        :return: The auth token retrieved
        """

        cred_kwargs = {
            'auth_url': url,
            'username': username,
            'password': password
        }

        # Currently, both v2 and v3 Identity API versions are supported
        if auth_api == AUTH_API_V2:
            cred_kwargs['tenant_name'] = kwargs.get('tenant_name')
        elif auth_api == AUTH_API_V3:
            cred_kwargs['user_domain_name'] = kwargs.get('user_domain_name')

        # Instantiate a Password object
        try:
            identity_package = 'keystoneclient.auth.identity.%s' % auth_api.replace('.0', '')
            identity_module = __import__(identity_package, fromlist=['Password'])
            password_class = getattr(identity_module, 'Password')
            logger.debug("Authentication with %s", password_class)
            credentials = password_class(**cred_kwargs)
        except (ImportError, AttributeError) as e:
                raise e
        # Get auth token
        logger.debug("Getting auth token for tenant %s...", tenant_id)
        try:
            auth_sess = self.session.Session(auth=credentials, timeout=DEFAULT_REQUEST_TIMEOUT)
            auth_token = auth_sess.get_token()
            logger.debug("Admin token generated:" + auth_token)

        except (KeystoneClientException, KeystoneConnectionRefused) as e:
            logger.error("No auth token (%s)", e.message)
            raise(e)

        return auth_token
Exemplo n.º 4
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"]
Exemplo n.º 5
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"]
Exemplo n.º 6
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))
Exemplo n.º 7
0
    def get_auth_token(self, username, password, tenant_id, **kwargs):
        """
        Init the variables related to authorization, needed to execute tests
        :return: The auth token retrieved
        """
        if self.auth_token is None:

            cred_kwargs = {"auth_url": self.identity_url, "username": username, "password": password}

            # Currently, both v2 and v3 Identity API versions are supported
            if self.api_version == AUTH_API_V2:
                cred_kwargs["tenant_name"] = kwargs.get("tenant_name")
            elif self.api_version == AUTH_API_V3:
                cred_kwargs["user_domain_name"] = kwargs.get("user_domain_name")

            # Instantiate a Password object
            try:
                identity_package = "keystoneclient.auth.identity.%s" % self.api_version.replace(".0", "")
                identity_module = __import__(identity_package, fromlist=["Password"])
                password_class = getattr(identity_module, "Password")
                logger.debug("Authentication with %s", password_class)
                credentials = password_class(**cred_kwargs)
            except (ImportError, AttributeError) as e:
                raise e
            # Get auth token
            logger.debug("Getting auth token for tenant %s...", tenant_id)
            try:
                auth_sess = self.session.Session(auth=credentials, timeout=DEFAULT_REQUEST_TIMEOUT)
                self.auth_token = auth_sess.get_token()
                logger.debug("Admin token generated: %s", self.auth_token)

            except Exception as e:
                logger.error("No auth token (%s)", e.message)
                raise (e)

        return self.auth_token
Exemplo n.º 8
0
 def checkToken(self, admin_token, token, tenant_id, url, auth_api):
     """checks if a token is valid against a url using an admin token."""
     logger.debug("Starting Authentication of token %s ", token)
     try:
         if not token:
             raise Unauthorized("Token is empty")
         auth_result = self.get_info_token(url, admin_token, token, auth_api)
         if auth_result:
             if tenant_id == auth_result.tenant["id"]:
                 logger.debug('The token is valid')
             else:
                 logger.error("TenantId %s ", tenant_id)
                 logger.error("Token TenantId %s ", auth_result.tenant["id"])
                 raise Unauthorized("Token is not valid for specified tenant %s" % tenant_id)
     except Unauthorized as unauth:
         logger.error(unauth)
         raise unauth
     except InternalServerError as internalError:
         raise AuthorizationFailure("Token could not have enough permissions to access tenant: %s" % tenant_id)
     except Exception as ex:
         raise ex
Exemplo n.º 9
0
    def checkToken(self, admin_token, token, tenant_id):
        """checks if a token is valid against a url using an admin token."""

        token_db = None
        try:
            if not token:
                raise Unauthorized("Token is empty")
            logger.debug("Starting Authentication of token %s ", token)

            try:
                token_db = self.get_token_from_memory(token)
                if self.api_version == AUTH_API_V2:
                    time_to_review = token_db['createdAt'] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V2[
                            settings.SECURITY_LEVEL]))
                elif self.api_version == AUTH_API_V3:
                    time_to_review = token_db['createdAt'] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V3[
                            settings.SECURITY_LEVEL]))

                logger.debug(
                    "Token {0} is present in memory, should be checked at {1}".
                    format(token, time_to_review))
                expires = dateparse.parse_datetime(token_db['expires'])
                if timezone.now() > expires or timezone.now(
                ) > time_to_review or tenant_id is not token_db["tenant"]:
                    logger.debug(
                        "Token %s should be checked against keystone.", token)
                else:
                    return token
            except KeyError:

                logger.debug("Token %s is not present in DB", token)
                pass

            auth_result = self.get_info_token(admin_token, token)
            if auth_result:
                if tenant_id == auth_result.tenant["id"]:
                    # STORE TOKEN IN MEMORY
                    createdAt = timezone.now()
                    token_db = self.user_tokens.setdefault(
                        token, {
                            'id': auth_result.id,
                            'expires': auth_result.expires,
                            'username': auth_result.username,
                            'tenant': auth_result.tenant["id"],
                            'createdAt': createdAt
                        })

                    self.user_tokens[token] = token_db
                    return token

                else:
                    logger.error("TenantId %s ", tenant_id)
                    logger.error("Token TenantId %s ",
                                 auth_result.tenant["id"])
                    raise Unauthorized(
                        "Token is not valid for specified tenant %s" %
                        tenant_id)

        except AuthorizationFailure as ex:
            if re.search(self.auth_token, ex.message) or re.search(
                    AUTH_TOKEN_ERROR_MESSAGE, ex.message):
                self.auth_token = None
                logger.debug(
                    "Admin token has expired, setting global to None.")
            elif re.search(token, ex.message) and token_db:
                self.user_tokens.pop(token)
            raise ex
        except Unauthorized as unauth:
            logger.debug(unauth)
            raise unauth
        except InternalServerError as internalError:
            raise AuthorizationFailure(
                "Token could not have enough permissions to access tenant: %s"
                % tenant_id)
        except Exception as ex:
            raise ex
Exemplo n.º 10
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")
Exemplo n.º 11
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")
Exemplo n.º 12
0
    def checkToken(self, admin_token, token, tenant_id):
        """checks if a token is valid against a url using an admin token."""

        token_db = None
        try:
            if not token:
                raise Unauthorized("Token is empty")
            logger.debug("Starting Authentication of token %s ", token)

            try:
                token_db = self.get_token_from_memory(token)
                if self.api_version == AUTH_API_V2:
                    time_to_review = token_db["createdAt"] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V2[settings.SECURITY_LEVEL])
                    )
                elif self.api_version == AUTH_API_V3:
                    time_to_review = token_db["createdAt"] + timezone.timedelta(
                        seconds=int(settings.SECURITY_LEVEL_SECONDS_V3[settings.SECURITY_LEVEL])
                    )

                logger.debug("Token {0} is present in memory, should be checked at {1}".format(token, time_to_review))
                expires = dateparse.parse_datetime(token_db["expires"])
                if timezone.now() > expires or timezone.now() > time_to_review or tenant_id is not token_db["tenant"]:
                    logger.debug("Token %s should be checked against keystone.", token)
                else:
                    return token
            except KeyError:

                logger.debug("Token %s is not present in DB", token)
                pass

            auth_result = self.get_info_token(admin_token, token)
            if auth_result:
                if tenant_id == auth_result.tenant["id"]:
                    # STORE TOKEN IN MEMORY
                    createdAt = timezone.now()
                    token_db = self.user_tokens.setdefault(
                        token,
                        {
                            "id": auth_result.id,
                            "expires": auth_result.expires,
                            "username": auth_result.username,
                            "tenant": auth_result.tenant["id"],
                            "createdAt": createdAt,
                        },
                    )

                    self.user_tokens[token] = token_db
                    return token

                else:
                    logger.error("TenantId %s ", tenant_id)
                    logger.error("Token TenantId %s ", auth_result.tenant["id"])
                    raise Unauthorized("Token is not valid for specified tenant %s" % tenant_id)

        except AuthorizationFailure as ex:
            if re.search(self.auth_token, ex.message) or re.search(AUTH_TOKEN_ERROR_MESSAGE, ex.message):
                self.auth_token = None
                logger.debug("Admin token has expired, setting global to None.")
            elif re.search(token, ex.message) and token_db:
                self.user_tokens.pop(token)
            raise ex
        except Unauthorized as unauth:
            logger.debug(unauth)
            raise unauth
        except InternalServerError as internalError:
            raise AuthorizationFailure("Token could not have enough permissions to access tenant: %s" % tenant_id)
        except Exception as ex:
            raise ex