Example #1
0
    BaseVim,
    KubernetesVimSchema,
    OpenStackVimSchema,
    VimType,
)
from vim_adaptor.terraform import TERRAFORM_WORKDIR
from vim_adaptor.util import create_completed_response, create_error_response

logging.basicConfig(level=logging.INFO)
logging.getLogger("manobase:plugin").setLevel(logging.INFO)
logging.getLogger("amqpstorm.channel").setLevel(logging.ERROR)

LOG = logging.getLogger("plugin:vim-adaptor")
LOG.setLevel(logging.DEBUG)

config = get_config(__name__)


class VimAdaptor(ManoBasePlugin):
    """
    Vim Adaptor main class. Instantiate this class to run the Vim Adaptor.
    """
    def __init__(self, *args, **kwargs):
        # Connect to MongoDB
        LOG.debug("Connecting to MongoDB at %s", config["mongo"])
        connect(host=config["mongo"])
        LOG.info("Connected to MongoDB")

        super().__init__(*args, version="0.1.0", **kwargs)

    def declare_subscriptions(self):
Example #2
0
from contextlib import contextmanager

import pytest
from appcfg import get_config
from mongoengine.connection import connect

from manobase.messaging import AsyncioBrokerConnection, Message
from manobase.messaging.util import async_endpoint
from slm.slm import ServiceLifecycleManager

config = get_config("slm")


@pytest.fixture(scope="module")
def slm_plugin():
    """
    A running SLM plugin instance that uses a loopback broker connection
    """
    adaptor = ServiceLifecycleManager(use_loopback_connection=True,
                                      fake_registration=True)
    yield adaptor
    adaptor.conn.close()


@pytest.fixture(scope="function"
                )  # to reset subscriptions after each test case
def connection():
    """
    A loopback broker connection
    """
    connection = AsyncioBrokerConnection("test-connection", is_loopback=True)
Example #3
0
import pytest
from appcfg import get_config
from mongoengine.errors import DoesNotExist

from vim_adaptor.managers.base import (
    FunctionInstanceManager,
    FunctionInstanceManagerFactory,
    ServiceInstanceHandler,
    ServiceInstanceHandlerFactory,
)
from vim_adaptor.managers.terraform import TerraformFunctionInstanceManager
from vim_adaptor.models.service import ServiceInstance
from vim_adaptor.models.vims import BaseVim, VimType

config = get_config("vim_adaptor")


def uuid_string():
    return str(uuid4())


@pytest.fixture
def vim(mongo_connection):
    vim = BaseVim(name="MyVIM", country="country", city="city", type="aws")
    vim.save()
    yield vim
    vim.delete()


def test_manager_factory(mongo_connection, mocker, vim):
Example #4
0
import importlib

import mongomock
import pymongo
import pytest
from appcfg import get_config
from pytest_voluptuous import S
from voluptuous.validators import All, Contains
from werkzeug.test import Client

config = get_config("repository")

RESOURCES = {
    "entries": {
        "type": "object",
        "required": ["a"],
        "properties": {
            "a": {
                "type": "string"
            },
            "b": {
                "type": "object",
                "required": ["c"],
                "properties": {
                    "c": {
                        "type": "number"
                    }
                },
            },
        },
    }
Example #5
0
import appcfg
import connexion
import redis
from amqpstorm import AMQPConnectionError
from flask_jwt_extended import JWTManager
from flask_mongoengine import MongoEngine
from flask_redis import FlaskRedis

from gatekeeper.models.users import User
from gatekeeper.util.flask import MongoEngineJSONEncoder
from gatekeeper.util.messaging import ConnexionBrokerConnection

logger = logging.getLogger(__name__)

config = appcfg.get_config(__name__)

# Create the application instance
app = connexion.FlaskApp(
    __name__,
    specification_dir="../",
    options=config["connexion"]["options"],
)

# Set flask environment, if ENV variable is set
if appcfg.get_env() is not None:
    app.app.config["ENV"] = appcfg.get_env()

    if appcfg.get_env() == "test":
        app.app.config["TESTING"] = True
Example #6
0
from appcfg import get_config
from pytest_voluptuous import S

config = get_config("gatekeeper")


def testUsers(api):
    adminUserData = dict(config["initialUserData"])
    adminUserData.pop("password")

    # GET /users
    def getUsers():
        return api.get("/api/v3/users").get_json()

    # Only the admin user should be present
    users = getUsers()
    assert 1 == len(users)
    adminUser = users[0]
    assert (S({
        **adminUserData, "id": str,
        "createdAt": str,
        "updatedAt": str
    }) == adminUser)

    # GET /current-user should return the admin user
    assert adminUser == api.get("/api/v3/current-user").get_json()

    # Let's change the username of the admin user via PUT /current-user
    newAdminUserData = {**adminUserData, "username": "******", "password": ""}
    reply = api.put("/api/v3/current-user", json=newAdminUserData)
    assert 200 == reply.status_code
Example #7
0
import json
import logging
from collections import defaultdict
from copy import deepcopy
from queue import Queue
from threading import Event, Lock, Thread
from typing import Any, Callable, Dict, Set
from uuid import uuid4

import amqpstorm
import yaml
from amqpstorm.exception import AMQPConnectionError
from appcfg import get_config

amqp_config = get_config(__name__)["amqp"]

logging.getLogger("amqpstorm.channel").setLevel(logging.ERROR)
LOG = logging.getLogger(__name__)

# For connections with is_loopback=True:

# Map topics to tags of local queues
_loopback_queue_tags_by_topic: Dict[str, Set[str]] = defaultdict(set)

# Map queue tags to local queues
_loopback_queue_by_tag: Dict[str, "Queue[Message]"] = defaultdict(Queue)

# Map queue tags to topics
_loopback_topic_by_tag: Dict[str, str] = {}
Example #8
0
"""
Helper functions to access the repository microservice
"""

from typing import List, Union

import requests
from appcfg import get_config

repository_url = get_config(__name__)["repository_url"]

TIMEOUT = 5  # seconds

Resource = Union[dict, List[dict]]


def post(endpoint: str, data: Resource) -> Resource:
    """
    Sends a POST request to the given repository endpoint with the provided data and
    raises a `requests.RequestException` on error.

    Args:
        endpoint: The endpoint URL relative to the repository root URL, without a leading slash
        data: The data to be sent to the repository
    """
    response = requests.post(repository_url + endpoint,
                             json=data,
                             timeout=TIMEOUT)
    response.raise_for_status()
    return response.json()