aboutsummaryrefslogtreecommitdiffstats
path: root/moon_interface/moon_interface
diff options
context:
space:
mode:
authorWuKong <rebirthmonkey@gmail.com>2017-12-23 21:49:35 +0100
committerWuKong <rebirthmonkey@gmail.com>2017-12-23 21:49:58 +0100
commit1100c66ce03a059ebe7ece9734e799b49b3a5a9e (patch)
treea057e7e7511f6675a9327b79e6919f07c5f89f07 /moon_interface/moon_interface
parent7a4dfdde6314476ae2a1a1c881ff1e3c430f790e (diff)
moonv4 cleanup
Change-Id: Icef927f3236d985ac13ff7376f6ce6314b2b39b0 Signed-off-by: WuKong <rebirthmonkey@gmail.com>
Diffstat (limited to 'moon_interface/moon_interface')
-rw-r--r--moon_interface/moon_interface/__init__.py6
-rw-r--r--moon_interface/moon_interface/__main__.py4
-rw-r--r--moon_interface/moon_interface/api/__init__.py0
-rw-r--r--moon_interface/moon_interface/api/authz.py193
-rw-r--r--moon_interface/moon_interface/api/generic.py131
-rw-r--r--moon_interface/moon_interface/authz_requests.py159
-rw-r--r--moon_interface/moon_interface/containers.py102
-rw-r--r--moon_interface/moon_interface/http_server.py136
-rw-r--r--moon_interface/moon_interface/server.py34
9 files changed, 765 insertions, 0 deletions
diff --git a/moon_interface/moon_interface/__init__.py b/moon_interface/moon_interface/__init__.py
new file mode 100644
index 00000000..903c6518
--- /dev/null
+++ b/moon_interface/moon_interface/__init__.py
@@ -0,0 +1,6 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+
+__version__ = "0.1.0"
diff --git a/moon_interface/moon_interface/__main__.py b/moon_interface/moon_interface/__main__.py
new file mode 100644
index 00000000..517fdd60
--- /dev/null
+++ b/moon_interface/moon_interface/__main__.py
@@ -0,0 +1,4 @@
+from moon_interface.server import main
+
+server = main()
+server.run()
diff --git a/moon_interface/moon_interface/api/__init__.py b/moon_interface/moon_interface/api/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_interface/moon_interface/api/__init__.py
diff --git a/moon_interface/moon_interface/api/authz.py b/moon_interface/moon_interface/api/authz.py
new file mode 100644
index 00000000..c9f4697f
--- /dev/null
+++ b/moon_interface/moon_interface/api/authz.py
@@ -0,0 +1,193 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Authz is the endpoint to get authorization response
+"""
+
+from flask import request
+from flask_restful import Resource
+import logging
+import pickle
+import requests
+import time
+from uuid import uuid4
+
+from moon_interface.authz_requests import AuthzRequest
+
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.interface.api." + __name__)
+
+
+def pdp_in_cache(cache, uuid):
+ """Check if a PDP exist with this Keystone Project ID in the cache of this component
+
+ :param cache: Cache to use
+ :param uuid: Keystone Project ID
+ :return: True or False
+ """
+ for item_uuid, item_value in cache.pdp.items():
+ if uuid == item_value['keystone_project_id']:
+ return item_uuid, item_value
+ return None, None
+
+
+def pdp_in_manager(cache, uuid):
+ """Check if a PDP exist with this Keystone Project ID in the Manager component
+
+ :param cache: Cache to use
+ :param uuid: Keystone Project ID
+ :return: True or False
+ """
+ cache.update()
+ return pdp_in_cache(cache, uuid)
+
+
+def container_exist(cache, uuid):
+ """Check if a PDP exist with this Keystone Project ID in the Manager component
+
+ :param cache: Cache to use
+ :param uuid: Keystone Project ID
+ :return: True or False
+ """
+ for key, value in cache.containers.items():
+ if "keystone_project_id" not in value:
+ continue
+ if value["keystone_project_id"] == uuid:
+ try:
+ req = requests.head("http://{}:{}/".format(
+ value.get("hostname"),
+ value.get("port")[0].get("PublicPort")))
+ LOG.info("container_exist {}".format(req.status_code))
+ if req.status_code in (200, 201):
+ return value
+ return
+ except requests.exceptions.ConnectionError:
+ pass
+ # maybe hostname is not working so trying with IP address
+ try:
+ req = requests.head("http://{}:{}/".format(
+ value.get("ip"),
+ value.get("port")[0].get("PublicPort")))
+ if req.status_code in (200, 201):
+ return value
+ return
+ except requests.exceptions.ConnectionError:
+ return
+
+
+def create_authz_request(cache, interface_name, manager_url, uuid, subject_name, object_name, action_name):
+ """Create the authorization request and make the first call to the Authz function
+
+ :param cache: Cache to use
+ :param interface_name: hostname of the interface
+ :param manager_url: URL of the manager
+ :param uuid: Keystone Project ID
+ :param subject_name: name of the subject
+ :param object_name: name of the object
+ :param action_name: name of the action
+ :return: Authorisation request
+ """
+ req_id = uuid4().hex
+ ctx = {
+ "project_id": uuid,
+ "subject_name": subject_name,
+ "object_name": object_name,
+ "action_name": action_name,
+ "request_id": req_id,
+ "interface_name": interface_name,
+ "manager_url": manager_url,
+ "cookie": uuid4().hex
+ }
+ cache.authz_requests[req_id] = AuthzRequest(ctx)
+ return cache.authz_requests[req_id]
+
+
+class Authz(Resource):
+ """
+ Endpoint for authz requests
+ """
+
+ __urls__ = (
+ "/authz/<string:uuid>",
+ "/authz/<string:uuid>/<string:subject_name>/<string:object_name>/<string:action_name>",
+ )
+
+ def __init__(self, **kwargs):
+ self.CACHE = kwargs.get("cache")
+ self.INTERFACE_NAME = kwargs.get("interface_name", "interface")
+ self.MANAGER_URL = kwargs.get("manager_url", "http://manager:8080")
+ self.TIMEOUT = 5
+
+ def get(self, uuid=None, subject_name=None, object_name=None, action_name=None):
+ """Get a response on an authorization request
+
+ :param uuid: uuid of a tenant or an intra_extension
+ :param subject_name: name of the subject or the request
+ :param object_name: name of the object
+ :param action_name: name of the action
+ :return: {
+ "args": {},
+ "ctx": {
+ "action_name": "4567",
+ "id": "123456",
+ "method": "authz",
+ "object_name": "234567",
+ "subject_name": "123456",
+ "user_id": "admin"
+ },
+ "error": {
+ "code": 500,
+ "description": "",
+ "title": "Moon Error"
+ },
+ "intra_extension_id": "123456",
+ "result": false
+ }
+ :internal_api: authz
+ """
+ pdp_id, pdp_value = pdp_in_cache(self.CACHE, uuid)
+ if not pdp_id:
+ pdp_id, pdp_value = pdp_in_manager(self.CACHE, uuid)
+ if not pdp_id:
+ return {
+ "result": False,
+ "message": "Unknown Project ID or "
+ "Project ID is not bind to a PDP."}, 403
+ authz_request = create_authz_request(
+ cache=self.CACHE,
+ uuid=uuid,
+ interface_name=self.INTERFACE_NAME,
+ manager_url=self.MANAGER_URL,
+ subject_name=subject_name,
+ object_name=object_name,
+ action_name=action_name)
+ cpt = 0
+ while True:
+ if cpt > self.TIMEOUT*10:
+ return {"result": False,
+ "message": "Authz request had timed out."}, 500
+ if authz_request.is_authz():
+ if authz_request.final_result == "Grant":
+ return {"result": True, "message": ""}, 200
+ return {"result": False, "message": ""}, 401
+ cpt += 1
+ time.sleep(0.1)
+
+ def patch(self, uuid=None, subject_name=None, object_name=None, action_name=None):
+ """Get a response on an authorization request
+
+ :param uuid: uuid of the authorization request
+ :param subject_name: not used
+ :param object_name: not used
+ :param action_name: not used
+ :request body: a Context object
+ :return: {}
+ :internal_api: authz
+ """
+ if uuid in self.CACHE.authz_requests:
+ self.CACHE.authz_requests[uuid].set_result(pickle.loads(request.data))
+ return "", 201
+ return {"result": False, "message": "The request ID is unknown"}, 500
diff --git a/moon_interface/moon_interface/api/generic.py b/moon_interface/moon_interface/api/generic.py
new file mode 100644
index 00000000..51de9214
--- /dev/null
+++ b/moon_interface/moon_interface/api/generic.py
@@ -0,0 +1,131 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+"""
+Those API are helping API used to manage the Moon platform.
+"""
+
+from flask_restful import Resource, request
+import logging
+import moon_interface.api
+from python_moonutilities.security_functions import check_auth
+
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.interface.api." + __name__)
+
+
+class Status(Resource):
+ """
+ Endpoint for status requests
+ """
+
+ __urls__ = ("/status", "/status/", "/status/<string:component_id>")
+
+ def get(self, component_id=None):
+ """Retrieve status of all components
+
+ :return: {
+ "orchestrator": {
+ "status": "Running"
+ },
+ "security_router": {
+ "status": "Running"
+ }
+ }
+ """
+ raise NotImplemented
+
+
+class Logs(Resource):
+ """
+ Endpoint for logs requests
+ """
+
+ __urls__ = ("/logs", "/logs/", "/logs/<string:component_id>")
+
+ def get(self, component_id=None):
+ """Get logs from the Moon platform
+
+ :param component_id: the ID of the component your are looking for (optional)
+ :return: [
+ "2015-04-15-13:45:20
+ "2015-04-15-13:45:21
+ "2015-04-15-13:45:22
+ "2015-04-15-13:45:23
+ ]
+ """
+ filter_str = request.args.get('filter', '')
+ from_str = request.args.get('from', '')
+ to_str = request.args.get('to', '')
+ event_number = request.args.get('event_number', '')
+ try:
+ event_number = int(event_number)
+ except ValueError:
+ event_number = None
+ args = dict()
+ args["filter"] = filter_str
+ args["from"] = from_str
+ args["to"] = to_str
+ args["event_number"] = event_number
+
+ raise NotImplemented
+
+
+class API(Resource):
+ """
+ Endpoint for API requests
+ """
+
+ __urls__ = (
+ "/api",
+ "/api/",
+ "/api/<string:group_id>",
+ "/api/<string:group_id>/",
+ "/api/<string:group_id>/<string:endpoint_id>")
+
+ @check_auth
+ def get(self, group_id="", endpoint_id="", user_id=""):
+ """Retrieve all API endpoints or a specific endpoint if endpoint_id is given
+
+ :param group_id: the name of one existing group (ie generic, ...)
+ :param endpoint_id: the name of one existing component (ie Logs, Status, ...)
+ :return: {
+ "group_name": {
+ "endpoint_name": {
+ "description": "a description",
+ "methods": {
+ "get": "description of the HTTP method"
+ },
+ "urls": ('/api', '/api/', '/api/<string:endpoint_id>')
+ }
+ }
+ """
+ __methods = ("get", "post", "put", "delete", "options", "patch")
+ api_list = filter(lambda x: "__" not in x, dir(moon_interface.api))
+ api_desc = dict()
+ for api_name in api_list:
+ api_desc[api_name] = {}
+ group_api_obj = eval("moon_interface.api.{}".format(api_name))
+ api_desc[api_name]["description"] = group_api_obj.__doc__
+ if "__version__" in dir(group_api_obj):
+ api_desc[api_name]["version"] = group_api_obj.__version__
+ object_list = list(filter(lambda x: "__" not in x, dir(group_api_obj)))
+ for obj in map(lambda x: eval("moon_interface.api.{}.{}".format(api_name, x)), object_list):
+ if "__urls__" in dir(obj):
+ api_desc[api_name][obj.__name__] = dict()
+ api_desc[api_name][obj.__name__]["urls"] = obj.__urls__
+ api_desc[api_name][obj.__name__]["methods"] = dict()
+ for _method in filter(lambda x: x in __methods, dir(obj)):
+ docstring = eval("moon_interface.api.{}.{}.{}.__doc__".format(api_name, obj.__name__, _method))
+ api_desc[api_name][obj.__name__]["methods"][_method] = docstring
+ api_desc[api_name][obj.__name__]["description"] = str(obj.__doc__)
+ if group_id in api_desc:
+ if endpoint_id in api_desc[group_id]:
+ return {group_id: {endpoint_id: api_desc[group_id][endpoint_id]}}
+ elif len(endpoint_id) > 0:
+ LOG.error("Unknown endpoint_id {}".format(endpoint_id))
+ return {"error": "Unknown endpoint_id {}".format(endpoint_id)}
+ return {group_id: api_desc[group_id]}
+ return api_desc
diff --git a/moon_interface/moon_interface/authz_requests.py b/moon_interface/moon_interface/authz_requests.py
new file mode 100644
index 00000000..3f99cb93
--- /dev/null
+++ b/moon_interface/moon_interface/authz_requests.py
@@ -0,0 +1,159 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+
+import logging
+import itertools
+import pickle
+import requests
+from python_moonutilities import configuration, exceptions
+from python_moonutilities.security_functions import Context
+from python_moonutilities.cache import Cache
+
+LOG = logging.getLogger("moon.interface.authz_requests")
+
+
+CACHE = Cache()
+CACHE.update()
+
+
+class AuthzRequest:
+
+ result = None
+ final_result = "Deny"
+ req_max_delay = 2
+
+ def __init__(self, ctx, args=None):
+ self.context = Context(ctx, CACHE)
+ self.args = args
+ self.request_id = ctx["request_id"]
+ if ctx['project_id'] not in CACHE.container_chaining:
+ raise exceptions.KeystoneProjectError("Unknown Project ID {}".format(ctx['project_id']))
+ self.container_chaining = CACHE.container_chaining[ctx['project_id']]
+ if len(self.container_chaining) == 0:
+ raise exceptions.MoonError('Void container chaining')
+ self.pdp_container = self.container_chaining[0]["container_id"]
+ self.run()
+
+ def run(self):
+ self.context.delete_cache()
+ req = None
+ try:
+ req = requests.post("http://{}:{}/authz".format(
+ self.container_chaining[0]["hostip"],
+ self.container_chaining[0]["port"],
+ ), data=pickle.dumps(self.context))
+ if req.status_code != 200:
+ raise exceptions.AuthzException(
+ "Receive bad response from Authz function "
+ "(with IP address - {})".format(
+ req.status_code
+ ))
+ except requests.exceptions.ConnectionError:
+ LOG.error("Cannot connect to {}".format(
+ "http://{}:{}/authz".format(
+ self.container_chaining[0]["hostip"],
+ self.container_chaining[0]["port"]
+ )))
+ except ValueError:
+ try:
+ req = requests.post("http://{}:{}/authz".format(
+ self.container_chaining[0]["hostname"],
+ self.container_chaining[0]["port"],
+ ), data=pickle.dumps(self.context))
+ if req.status_code != 200:
+ raise exceptions.AuthzException(
+ "Receive bad response from Authz function "
+ "(with hostname - {})".format(
+ req.status_code
+ ))
+ except requests.exceptions.ConnectionError:
+ LOG.error("Cannot connect to {}".format(
+ "http://{}:{}/authz".format(
+ self.container_chaining[0]["hostname"],
+ self.container_chaining[0]["port"]
+ )))
+ raise exceptions.AuthzException(
+ "Cannot connect to Authz function")
+ self.context.set_cache(CACHE)
+ if req and len(self.container_chaining) == 1:
+ self.result = pickle.loads(req.content)
+
+ # def __exec_next_state(self, rule_found):
+ # index = self.context.index
+ # current_meta_rule = self.context.headers[index]
+ # current_container = self.__get_container_from_meta_rule(current_meta_rule)
+ # current_container_genre = current_container["genre"]
+ # try:
+ # next_meta_rule = self.context.headers[index + 1]
+ # except IndexError:
+ # next_meta_rule = None
+ # if current_container_genre == "authz":
+ # if rule_found:
+ # return True
+ # pass
+ # if next_meta_rule:
+ # # next will be session if current is deny and session is unset
+ # if self.payload["authz_context"]['pdp_set'][next_meta_rule]['effect'] == "unset":
+ # return notify(
+ # request_id=self.payload["authz_context"]["request_id"],
+ # container_id=self.__get_container_from_meta_rule(next_meta_rule)['container_id'],
+ # payload=self.payload)
+ # # next will be delegation if current is deny and session is passed or deny and delegation is unset
+ # else:
+ # LOG.error("Delegation is not developed!")
+ #
+ # else:
+ # # else next will be None and the request is sent to router
+ # return self.__return_to_router()
+ # elif current_container_genre == "session":
+ # pass
+ # # next will be next container in headers if current is passed
+ # if self.payload["authz_context"]['pdp_set'][current_meta_rule]['effect'] == "passed":
+ # return notify(
+ # request_id=self.payload["authz_context"]["request_id"],
+ # container_id=self.__get_container_from_meta_rule(next_meta_rule)['container_id'],
+ # payload=self.payload)
+ # # next will be None if current is grant and the request is sent to router
+ # else:
+ # return self.__return_to_router()
+ # elif current_container_genre == "delegation":
+ # LOG.error("Delegation is not developed!")
+ # # next will be authz if current is deny
+ # # next will be None if current is grant and the request is sent to router
+
+ def set_result(self, result):
+ self.result = result
+
+ def is_authz(self):
+ if not self.result:
+ return False
+ authz_results = []
+ for key in self.result.pdp_set:
+ if "effect" in self.result.pdp_set[key]:
+ if self.result.pdp_set[key]["effect"] == "grant":
+ # the pdp is a authorization PDP and grant the request
+ authz_results.append(True)
+ elif self.result.pdp_set[key]["effect"] == "passed":
+ # the pdp is not a authorization PDP (session or delegation) and had run normally
+ authz_results.append(True)
+ elif self.result.pdp_set[key]["effect"] == "unset":
+ # the pdp is not a authorization PDP (session or delegation) and had not yep run
+ authz_results.append(True)
+ else:
+ # the pdp is (or not) a authorization PDP and had run badly
+ authz_results.append(False)
+ if list(itertools.accumulate(authz_results, lambda x, y: x & y))[-1]:
+ self.result.pdp_set["effect"] = "grant"
+ if self.result:
+ if self.result.pdp_set["effect"] == "grant":
+ self.final_result = "Grant"
+ return True
+ self.final_result = "Deny"
+ return True
+
+ # def notify(self, request_id, container_id, payload):
+ # LOG.info("notify {} {} {}".format(request_id, container_id, payload))
+ # # TODO: send the notification and wait for the result
+ # # req = requests.get()
diff --git a/moon_interface/moon_interface/containers.py b/moon_interface/moon_interface/containers.py
new file mode 100644
index 00000000..4f93d742
--- /dev/null
+++ b/moon_interface/moon_interface/containers.py
@@ -0,0 +1,102 @@
+# Copyright 2017 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+
+import docker
+import logging
+import re
+import requests
+import time
+from python_moonutilities import configuration, exceptions
+
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.interface.container")
+
+
+class DockerManager:
+
+ def __init__(self):
+ docker_conf = configuration.get_configuration("docker")['docker']
+ self.docker = docker.DockerClient(base_url=docker_conf['url'])
+
+ def create_container(self, data):
+ """Create the container through the docker client
+
+ :param data: {
+ "name": "authz",
+ "hostname": "authz123456789",
+ "port": {
+ "PrivatePort": 8090,
+ "Type": "tcp",
+ "IP": "0.0.0.0",
+ "PublicPort": 8090
+ },
+ "keystone_project_id": "keystone_project_id1",
+ "pdp_id": "123456789",
+ "container_name": "wukongsun/moon_authz:v4.1"
+ }
+ :return: container output
+ """
+ output = self.docker.containers.run(
+ image=data.get("container_name"),
+ hostname=data.get("hostname", data.get("name"))[:63],
+ name=data.get("name"),
+ network='moon',
+ ports={'{}/{}'.format(
+ data.get("port").get("PrivatePort"),
+ data.get("port").get("Type")
+ ): int(data.get("port").get("PrivatePort"))},
+ environment={
+ "UUID": data.get("hostname"),
+ "BIND": data.get("port").get("IP"),
+ "TYPE": data.get("plugin_name"),
+ "PORT": data.get("port").get("PrivatePort"),
+ "PDP_ID": data.get("pdp_id"),
+ "META_RULE_ID": data.get("meta_rule_id"),
+ "KEYSTONE_PROJECT_ID": data.get("keystone_project_id"),
+ },
+ detach=True
+ )
+ try:
+ req = requests.head("http://{}:{}/".format(data.get("hostname"), data.get("port").get("PublicPort")))
+ except requests.exceptions.ConnectionError:
+ pass
+ else:
+ if req.status_code != 200:
+ raise exceptions.DockerError("Container {} is not running!".format(data.get("hostname")))
+ output.ip = "0.0.0.0"
+ return output
+
+ # Note: host is not reachable through hostname so trying to find th IP address
+ res = output.exec_run("ip addr")
+ find = re.findall("inet (\d+\.\d+\.\d+\.\d+)", res.decode("utf-8"))
+ ip = "127.0.0.1"
+ for ip in find:
+ if ip.startswith("127"):
+ continue
+ break
+ cpt = 0
+ while True:
+ try:
+ req = requests.head("http://{}:{}/".format(ip, data.get("port").get("PublicPort")))
+ except requests.exceptions.ConnectionError:
+ pass
+ else:
+ if req.status_code not in (200, 201):
+ LOG.error("url={}".format("http://{}:{}/".format(ip, data.get("port").get("PublicPort"))))
+ LOG.error("req={}".format(req))
+ raise exceptions.DockerError("Container {} is not running!".format(data.get("hostname")))
+ output.ip = ip
+ return output
+ finally:
+ cpt += 1
+ time.sleep(0.1)
+ if cpt > 20:
+ break
+ output.ip = ip
+ return output
+
+ def delete_container(self, uuid):
+ raise NotImplementedError
diff --git a/moon_interface/moon_interface/http_server.py b/moon_interface/moon_interface/http_server.py
new file mode 100644
index 00000000..890bb82f
--- /dev/null
+++ b/moon_interface/moon_interface/http_server.py
@@ -0,0 +1,136 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+
+from flask import Flask, jsonify
+from flask_cors import CORS, cross_origin
+from flask_restful import Resource, Api
+import logging
+from moon_interface import __version__
+from moon_interface.api.generic import Status, Logs, API
+from moon_interface.api.authz import Authz
+from moon_interface.authz_requests import CACHE
+from python_moonutilities import configuration, exceptions
+
+logger = logging.getLogger("moon.interface.http")
+
+
+class Server:
+ """Base class for HTTP server"""
+
+ def __init__(self, host="localhost", port=80, api=None, **kwargs):
+ """Run a server
+
+ :param host: hostname of the server
+ :param port: port for the running server
+ :param kwargs: optional parameters
+ :return: a running server
+ """
+ self._host = host
+ self._port = port
+ self._api = api
+ self._extra = kwargs
+
+ @property
+ def host(self):
+ return self._host
+
+ @host.setter
+ def host(self, name):
+ self._host = name
+
+ @host.deleter
+ def host(self):
+ self._host = ""
+
+ @property
+ def port(self):
+ return self._port
+
+ @port.setter
+ def port(self, number):
+ self._port = number
+
+ @port.deleter
+ def port(self):
+ self._port = 80
+
+ def run(self):
+ raise NotImplementedError()
+
+__API__ = (
+ Status, Logs, API
+ )
+
+
+class Root(Resource):
+ """
+ The root of the web service
+ """
+ __urls__ = ("/", )
+ __methods = ("get", "post", "put", "delete", "options")
+
+ def get(self):
+ tree = {"/": {"methods": ("get",), "description": "List all methods for that service."}}
+ for item in __API__:
+ tree[item.__name__] = {"urls": item.__urls__}
+ _methods = []
+ for _method in self.__methods:
+ if _method in dir(item):
+ _methods.append(_method)
+ tree[item.__name__]["methods"] = _methods
+ tree[item.__name__]["description"] = item.__doc__.strip()
+ return {
+ "version": __version__,
+ "tree": tree
+ }
+
+
+class HTTPServer(Server):
+
+ def __init__(self, host="localhost", port=80, **kwargs):
+ super(HTTPServer, self).__init__(host=host, port=port, **kwargs)
+ self.app = Flask(__name__)
+ self.port = port
+ conf = configuration.get_configuration("components/manager")
+ self.manager_hostname = conf["components/manager"].get("hostname", "manager")
+ self.manager_port = conf["components/manager"].get("port", 80)
+ #Todo : specify only few urls instead of *
+ CORS(self.app)
+ self.api = Api(self.app)
+ self.__set_route()
+ self.__hook_errors()
+
+ # @self.app.errorhandler(exceptions.AuthException)
+ # def _auth_exception(error):
+ # return {"error": "Unauthorized"}, 401
+
+ def __hook_errors(self):
+
+ def get_404_json(e):
+ return jsonify({"result": False, "code": 404, "description": str(e)}), 404
+ self.app.register_error_handler(404, get_404_json)
+
+ def get_400_json(e):
+ return jsonify({"result": False, "code": 400, "description": str(e)}), 400
+ self.app.register_error_handler(400, lambda e: get_400_json)
+ self.app.register_error_handler(403, exceptions.AuthException)
+
+ def __set_route(self):
+ self.api.add_resource(Root, '/')
+
+ for api in __API__:
+ self.api.add_resource(api, *api.__urls__)
+ self.api.add_resource(Authz, *Authz.__urls__,
+ resource_class_kwargs={
+ "cache": CACHE,
+ "interface_name": self.host,
+ "manager_url": "http://{}:{}".format(self.manager_hostname, self.manager_port),
+ }
+ )
+
+ def run(self):
+ self.app.run(host=self._host, port=self._port) # nosec
+ # self.app.run(debug=True, host=self._host, port=self._port) # nosec
+
diff --git a/moon_interface/moon_interface/server.py b/moon_interface/moon_interface/server.py
new file mode 100644
index 00000000..e53b4504
--- /dev/null
+++ b/moon_interface/moon_interface/server.py
@@ -0,0 +1,34 @@
+# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors
+# This software is distributed under the terms and conditions of the 'Apache-2.0'
+# license which can be found in the file 'LICENSE' in this package distribution
+# or at 'http://www.apache.org/licenses/LICENSE-2.0'.
+
+import logging
+from python_moonutilities import configuration, exceptions
+from moon_interface.http_server import HTTPServer
+
+LOG = logging.getLogger("moon.interface")
+
+
+def main():
+ configuration.init_logging()
+ try:
+ conf = configuration.get_configuration("components/interface")
+ hostname = conf["components/interface"].get("hostname", "interface")
+ port = conf["components/interface"].get("port", 80)
+ bind = conf["components/interface"].get("bind", "127.0.0.1")
+ except exceptions.ConsulComponentNotFound:
+ hostname = "interface"
+ bind = "127.0.0.1"
+ port = 80
+ configuration.add_component(uuid="interface", name=hostname, port=port, bind=bind)
+ LOG.info("Starting server with IP {} on port {} bind to {}".format(hostname, port, bind))
+ server = HTTPServer(host=bind, port=port)
+ # LOG.info("Starting server")
+ # server = HTTPServer(host="0.0.0.0", port=8081)
+ return server
+
+
+if __name__ == '__main__':
+ server = main()
+ server.run()