aboutsummaryrefslogtreecommitdiffstats
path: root/moon_orchestrator/moon_orchestrator
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_orchestrator/moon_orchestrator
parent7a4dfdde6314476ae2a1a1c881ff1e3c430f790e (diff)
moonv4 cleanup
Change-Id: Icef927f3236d985ac13ff7376f6ce6314b2b39b0 Signed-off-by: WuKong <rebirthmonkey@gmail.com>
Diffstat (limited to 'moon_orchestrator/moon_orchestrator')
-rw-r--r--moon_orchestrator/moon_orchestrator/__init__.py6
-rw-r--r--moon_orchestrator/moon_orchestrator/__main__.py4
-rw-r--r--moon_orchestrator/moon_orchestrator/api/__init__.py0
-rw-r--r--moon_orchestrator/moon_orchestrator/api/generic.py131
-rw-r--r--moon_orchestrator/moon_orchestrator/api/pods.py127
-rw-r--r--moon_orchestrator/moon_orchestrator/drivers.py175
-rw-r--r--moon_orchestrator/moon_orchestrator/http_server.py292
-rw-r--r--moon_orchestrator/moon_orchestrator/server.py36
8 files changed, 771 insertions, 0 deletions
diff --git a/moon_orchestrator/moon_orchestrator/__init__.py b/moon_orchestrator/moon_orchestrator/__init__.py
new file mode 100644
index 00000000..2302dea9
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/__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__ = "1.1.0"
diff --git a/moon_orchestrator/moon_orchestrator/__main__.py b/moon_orchestrator/moon_orchestrator/__main__.py
new file mode 100644
index 00000000..9ebc3a7f
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/__main__.py
@@ -0,0 +1,4 @@
+from moon_orchestrator.server import main
+
+server = main()
+server.run()
diff --git a/moon_orchestrator/moon_orchestrator/api/__init__.py b/moon_orchestrator/moon_orchestrator/api/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/api/__init__.py
diff --git a/moon_orchestrator/moon_orchestrator/api/generic.py b/moon_orchestrator/moon_orchestrator/api/generic.py
new file mode 100644
index 00000000..84de4e69
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/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_orchestrator.api
+from python_moonutilities.security_functions import check_auth
+
+__version__ = "0.1.0"
+
+LOG = logging.getLogger("moon.orchestrator.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_orchestrator.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_orchestrator/moon_orchestrator/api/pods.py b/moon_orchestrator/moon_orchestrator/api/pods.py
new file mode 100644
index 00000000..9bca4d93
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/api/pods.py
@@ -0,0 +1,127 @@
+# 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 request
+from flask_restful import Resource
+from python_moonutilities.security_functions import check_auth
+import logging
+
+LOG = logging.getLogger("moon.orchestrator.api.pods")
+
+
+class Pods(Resource):
+ """
+ Endpoint for pdp requests
+ """
+
+ __urls__ = (
+ "/pods",
+ "/pods/",
+ "/pods/<string:uuid>",
+ "/pods/<string:uuid>/",
+ )
+
+ def __init__(self, **kwargs):
+ self.driver = kwargs.get("driver")
+ self.create_security_function = kwargs.get("create_security_function_hook")
+
+ @check_auth
+ def get(self, uuid=None, user_id=None):
+ """Retrieve all pods
+
+ :param uuid: uuid of the pod
+ :param user_id: user ID who do the request
+ :return: {
+ "pod_id1": {
+ "name": "...",
+ "replicas": "...",
+ "description": "...",
+ }
+ }
+ :internal_api: get_pdp
+ """
+ pods = {}
+ # LOG.info("pods={}".format(self.driver.get_pods()))
+ if uuid:
+ return {"pods": self.driver.get_pods(uuid)}
+ for _pod_key, _pod_values in self.driver.get_pods().items():
+ pods[_pod_key] = []
+ for _pod_value in _pod_values:
+ if _pod_value['namespace'] != "moon":
+ continue
+ pods[_pod_key].append(_pod_value)
+ return {"pods": pods}
+
+ @check_auth
+ def post(self, uuid=None, user_id=None):
+ """Create a new pod.
+
+ :param uuid: uuid of the pod (not used here)
+ :param user_id: user ID who do the request
+ :request body: {
+ "name": "...",
+ "description": "...",
+ "type": "plugin_name"
+ }
+ :return: {
+ "pdp_id1": {
+ "name": "...",
+ "replicas": "...",
+ "description": "...",
+ }
+ }
+ """
+ LOG.info("POST param={}".format(request.json))
+ self.create_security_function(
+ request.json.get("keystone_project_id"),
+ request.json.get("pdp_id"),
+ request.json.get("security_pipeline"),
+ manager_data=request.json,
+ active_context=None,
+ active_context_name=None)
+ pods = {}
+ for _pod_key, _pod_values in self.driver.get_pods().items():
+ pods[_pod_key] = []
+ for _pod_value in _pod_values:
+ if _pod_value['namespace'] != "moon":
+ continue
+ pods[_pod_key].append(_pod_value)
+ return {"pods": pods}
+
+ @check_auth
+ def delete(self, uuid=None, user_id=None):
+ """Delete a pod
+
+ :param uuid: uuid of the pod to delete
+ :param user_id: user ID who do the request
+ :return: {
+ "result": "True or False",
+ "message": "optional message"
+ }
+ """
+ return {"result": True}
+
+ @check_auth
+ def patch(self, uuid=None, user_id=None):
+ """Update a pod
+
+ :param uuid: uuid of the pdp to update
+ :param user_id: user ID who do the request
+ :request body: {
+ "name": "...",
+ "replicas": "...",
+ "description": "...",
+ }
+ :return: {
+ "pod_id1": {
+ "name": "...",
+ "replicas": "...",
+ "description": "...",
+ }
+ }
+ :internal_api: update_pdp
+ """
+ return {"pods": None}
+
diff --git a/moon_orchestrator/moon_orchestrator/drivers.py b/moon_orchestrator/moon_orchestrator/drivers.py
new file mode 100644
index 00000000..08c53be3
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/drivers.py
@@ -0,0 +1,175 @@
+# 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 kubernetes import client, config
+import logging
+import urllib3.exceptions
+from python_moonutilities import configuration
+
+LOG = logging.getLogger("moon.orchestrator.drivers")
+
+
+def get_driver():
+ try:
+ return K8S()
+ except urllib3.exceptions.MaxRetryError as e:
+ LOG.exception(e)
+ return Docker()
+
+
+class Driver:
+
+ def __init__(self):
+ self.cache = {}
+ # example of cache:
+ # {
+ # "uuid_of_pod": {
+ # "ip": "",
+ # "hostname": "",
+ # "port": 30001,
+ # "pdp": "",
+ # "keystone_project_id": "",
+ # "plugin_name": "",
+ # "namespace": ""
+ # }
+ # }
+
+ def get_pods(self, namespace=None):
+ raise NotImplementedError
+
+ def load_pod(self, data, api_client=None, ext_client=None):
+ raise NotImplementedError
+
+ def delete_pod(self, uuid=None, name=None):
+ raise NotImplementedError
+
+ def get_slaves(self):
+ raise NotImplementedError
+
+
+class K8S(Driver):
+
+ def __init__(self):
+ super(K8S, self).__init__()
+ config.load_kube_config()
+ self.client = client.CoreV1Api()
+
+ def get_pods(self, name=None):
+ if name:
+ pods = self.client.list_pod_for_all_namespaces(watch=False)
+ for pod in pods.items:
+ LOG.info("get_pods {}".format(pod.metadata.name))
+ if name in pod.metadata.name:
+ return pod
+ else:
+ return None
+ LOG.info("get_pods cache={}".format(self.cache))
+ return self.cache
+
+ @staticmethod
+ def __create_pod(client, data):
+ pod_manifest = {
+ 'apiVersion': 'extensions/v1beta1',
+ 'kind': 'Deployment',
+ 'metadata': {
+ 'name': data[0].get('name')
+ },
+ 'spec': {
+ 'replicas': 1,
+ 'template': {
+ 'metadata': {'labels': {'app': data[0].get('name')}},
+ 'hostname': data[0].get('name'),
+ 'spec': {
+ 'containers': []
+ }
+ },
+ }
+ }
+ for _data in data:
+ pod_manifest['spec']['template']['spec']['containers'].append(
+ {
+ 'image': _data.get('container', "busybox"),
+ 'name': _data.get('name'),
+ 'hostname': _data.get('name'),
+ 'ports': [
+ {"containerPort": _data.get('port', 80)},
+ ],
+ 'env': [
+ {'name': "UUID", "value": _data.get('name', "None")},
+ {'name': "TYPE", "value": _data.get('genre', "None")},
+ {'name': "PORT", "value": str(_data.get('port', 80))},
+ {'name': "PDP_ID", "value": _data.get('pdp_id', "None")},
+ {'name': "META_RULE_ID", "value": _data.get('meta_rule_id', "None")},
+ {'name': "KEYSTONE_PROJECT_ID",
+ "value": _data.get('keystone_project_id', "None")},
+ ]
+ }
+ )
+ resp = client.create_namespaced_deployment(body=pod_manifest,
+ namespace='moon')
+ LOG.info("Pod {} created!".format(data[0].get('name')))
+ # logger.info(yaml.dump(pod_manifest, sys.stdout))
+ # logger.info(resp)
+ return resp
+
+ @staticmethod
+ def __create_service(client, data, expose=False):
+ service_manifest = {
+ 'apiVersion': 'v1',
+ 'kind': 'Service',
+ 'metadata': {
+ 'name': data.get('name'),
+ 'namespace': 'moon'
+ },
+ 'spec': {
+ 'ports': [{
+ 'port': data.get('port', 80),
+ 'targetPort': data.get('port', 80)
+ }],
+ 'selector': {
+ 'app': data.get('name')
+ },
+ # 'type': 'NodePort',
+ 'endpoints': [{
+ 'port': data.get('port', 80),
+ 'protocol': 'TCP',
+ }],
+ }
+ }
+ if expose:
+ service_manifest['spec']['ports'][0]['nodePort'] = \
+ configuration.increment_port()
+ service_manifest['spec']['type'] = "NodePort"
+ resp = client.create_namespaced_service(namespace="moon",
+ body=service_manifest)
+ LOG.info("Service {} created!".format(data.get('name')))
+ return resp
+
+ def load_pod(self, data, api_client=None, ext_client=None, expose=False):
+ _client = api_client if api_client else self.client
+ pod = self.__create_pod(client=ext_client, data=data)
+ service = self.__create_service(client=_client, data=data[0],
+ expose=expose)
+ self.cache[pod.metadata.uid] = data
+
+ def delete_pod(self, uuid=None, name=None):
+ LOG.info("Deleting pod {}".format(uuid))
+ # TODO: delete_namespaced_deployment
+ # https://github.com/kubernetes-incubator/client-python/blob/master/kubernetes/client/apis/extensions_v1beta1_api.py
+
+ def get_slaves(self):
+ contexts, active_context = config.list_kube_config_contexts()
+ return contexts, active_context
+
+
+class Docker(Driver):
+
+ def load_pod(self, data, api_client=None, ext_client=None):
+ LOG.info("Creating pod {}".format(data[0].get('name')))
+ raise NotImplementedError
+
+ def delete_pod(self, uuid=None, name=None):
+ LOG.info("Deleting pod {}".format(uuid))
+ raise NotImplementedError
diff --git a/moon_orchestrator/moon_orchestrator/http_server.py b/moon_orchestrator/moon_orchestrator/http_server.py
new file mode 100644
index 00000000..e6a5ee57
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/http_server.py
@@ -0,0 +1,292 @@
+# 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 kubernetes import client, config
+import random
+import requests
+import time
+from moon_orchestrator import __version__
+from moon_orchestrator.api.pods import Pods
+from moon_orchestrator.api.generic import Logs, Status
+from python_moonutilities import configuration, exceptions
+from python_moonutilities.misc import get_random_name
+from moon_orchestrator.drivers import get_driver
+
+LOG = logging.getLogger("moon.orchestrator.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
+ )
+
+
+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__)
+ conf = configuration.get_configuration("components/orchestrator")
+ self.orchestrator_hostname = conf["components/orchestrator"].get("hostname", "orchestrator")
+ self.orchestrator_port = conf["components/orchestrator"].get("port", 80)
+ 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.driver = get_driver()
+ LOG.info("Driver = {}".format(self.driver.__class__))
+ self.__set_route()
+ self.__hook_errors()
+ pdp = None
+ while True:
+ try:
+ pdp = requests.get(
+ "http://{}:{}/pdp".format(self.manager_hostname,
+ self.manager_port))
+ except requests.exceptions.ConnectionError:
+ LOG.warning("Manager is not ready, standby...")
+ time.sleep(1)
+ except KeyError:
+ LOG.warning("Manager is not ready, standby...")
+ time.sleep(1)
+ else:
+ if "pdps" in pdp.json():
+ break
+ LOG.debug("pdp={}".format(pdp))
+ self.create_wrappers()
+ for _pdp_key, _pdp_value in pdp.json()['pdps'].items():
+ if _pdp_value.get('keystone_project_id'):
+ # TODO: select context to add security function
+ self.create_security_function(
+ keystone_project_id=_pdp_value.get('keystone_project_id'),
+ pdp_id=_pdp_key,
+ policy_ids=_pdp_value.get('security_pipeline', []))
+
+ 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(Pods, *Pods.__urls__,
+ resource_class_kwargs={
+ "driver": self.driver,
+ "create_security_function_hook":
+ self.create_security_function,
+ })
+
+ def run(self):
+ self.app.run(host=self._host, port=self._port) # nosec
+
+ @staticmethod
+ def __filter_str(data):
+ return data.replace("@", "-")
+
+ def create_wrappers(self):
+ contexts, active_context = self.driver.get_slaves()
+ LOG.debug("contexts: {}".format(contexts))
+ LOG.debug("active_context: {}".format(active_context))
+ conf = configuration.get_configuration("components/wrapper")
+ hostname = conf["components/wrapper"].get(
+ "hostname", "wrapper")
+ port = conf["components/wrapper"].get("port", 80)
+ container = conf["components/wrapper"].get(
+ "container",
+ "wukongsun/moon_wrapper:v4.3")
+ for _ctx in contexts:
+ _config = config.new_client_from_config(context=_ctx['name'])
+ LOG.debug("_config={}".format(_config))
+ api_client = client.CoreV1Api(_config)
+ ext_client = client.ExtensionsV1beta1Api(_config)
+ # TODO: get data from consul
+ data = [{
+ "name": hostname + "-" + get_random_name(),
+ "container": container,
+ "port": port,
+ "namespace": "moon"
+ }, ]
+ pod = self.driver.load_pod(data, api_client, ext_client, expose=True)
+ LOG.debug('wrapper pod={}'.format(pod))
+
+ def create_security_function(self, keystone_project_id,
+ pdp_id, policy_ids, manager_data={},
+ active_context=None,
+ active_context_name=None):
+ """ Create security functions
+
+ :param policy_id: the policy ID mapped to this security function
+ :param active_context: if present, add the security function in this
+ context
+ :param active_context_name: if present, add the security function in
+ this context name
+ if active_context_name and active_context are not present, add the
+ security function in all context (ie, in all slaves)
+ :return: None
+ """
+ for key, value in self.driver.get_pods().items():
+ for _pod in value:
+ if _pod.get('keystone_project_id') == keystone_project_id:
+ LOG.warning("A pod for this Keystone project {} "
+ "already exists.".format(keystone_project_id))
+ return
+
+ plugins = configuration.get_plugins()
+ conf = configuration.get_configuration("components/interface")
+ i_hostname = conf["components/interface"].get("hostname", "interface")
+ i_port = conf["components/interface"].get("port", 80)
+ i_container = conf["components/interface"].get(
+ "container",
+ "wukongsun/moon_interface:v4.3")
+ data = [
+ {
+ "name": i_hostname + "-" + get_random_name(),
+ "container": i_container,
+ "port": i_port,
+ 'pdp_id': pdp_id,
+ 'genre': "interface",
+ 'keystone_project_id': keystone_project_id,
+ "namespace": "moon"
+ },
+ ]
+ LOG.info("data={}".format(data))
+ policies = manager_data.get('policies')
+ if not policies:
+ LOG.info("No policy data from Manager, trying to get them")
+ policies = requests.get("http://{}:{}/policies".format(
+ self.manager_hostname, self.manager_port)).json().get(
+ "policies", dict())
+ LOG.info("policies={}".format(policies))
+ models = manager_data.get('models')
+ if not models:
+ LOG.info("No models data from Manager, trying to get them")
+ models = requests.get("http://{}:{}/models".format(
+ self.manager_hostname, self.manager_port)).json().get(
+ "models", dict())
+ LOG.info("models={}".format(models))
+
+ for policy_id in policy_ids:
+ if policy_id in policies:
+ genre = policies[policy_id].get("genre", "authz")
+ if genre in plugins:
+ for meta_rule in models[policies[policy_id]['model_id']]['meta_rules']:
+ data.append({
+ "name": genre + "-" + get_random_name(),
+ "container": plugins[genre]['container'],
+ 'pdp_id': pdp_id,
+ "port": plugins[genre].get('port', 8080),
+ 'genre': genre,
+ 'policy_id': policy_id,
+ 'meta_rule_id': meta_rule,
+ 'keystone_project_id': keystone_project_id,
+ "namespace": "moon"
+ })
+ LOG.info("data={}".format(data))
+ contexts, _active_context = self.driver.get_slaves()
+ LOG.info("active_context_name={}".format(active_context_name))
+ LOG.info("active_context={}".format(active_context))
+ if active_context_name:
+ for _context in contexts:
+ if _context["name"] == active_context_name:
+ active_context = _context
+ break
+ if active_context:
+ active_context = _active_context
+ _config = config.new_client_from_config(
+ context=active_context['name'])
+ LOG.debug("_config={}".format(_config))
+ api_client = client.CoreV1Api(_config)
+ ext_client = client.ExtensionsV1beta1Api(_config)
+ self.driver.load_pod(data, api_client, ext_client, expose=False)
+ return
+ LOG.info("contexts={}".format(contexts))
+ for _ctx in contexts:
+ _config = config.new_client_from_config(context=_ctx['name'])
+ LOG.debug("_config={}".format(_config))
+ api_client = client.CoreV1Api(_config)
+ ext_client = client.ExtensionsV1beta1Api(_config)
+ self.driver.load_pod(data, api_client, ext_client, expose=False)
+
+
diff --git a/moon_orchestrator/moon_orchestrator/server.py b/moon_orchestrator/moon_orchestrator/server.py
new file mode 100644
index 00000000..0cbd535a
--- /dev/null
+++ b/moon_orchestrator/moon_orchestrator/server.py
@@ -0,0 +1,36 @@
+# 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 os
+import logging
+from python_moonutilities import configuration, exceptions
+from moon_orchestrator.http_server import HTTPServer
+
+LOG = logging.getLogger("moon.orchestrator")
+DOMAIN = "moon_orchestrator"
+
+__CWD__ = os.path.dirname(os.path.abspath(__file__))
+
+
+def main():
+ configuration.init_logging()
+ try:
+ conf = configuration.get_configuration("components/orchestrator")
+ hostname = conf["components/orchestrator"].get("hostname", "orchestrator")
+ port = conf["components/orchestrator"].get("port", 80)
+ bind = conf["components/orchestrator"].get("bind", "127.0.0.1")
+ except exceptions.ConsulComponentNotFound:
+ hostname = "orchestrator"
+ bind = "127.0.0.1"
+ port = 80
+ configuration.add_component(uuid="orchestrator", 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)
+ return server
+
+
+if __name__ == '__main__':
+ server = main()
+ server.run()