aboutsummaryrefslogtreecommitdiffstats
path: root/moon_wrapper/moon_wrapper/http_server.py
blob: dfbaed9f59827c9295d8ef0ee68bfd90df11e630 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# 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 flask
from flask import Flask, jsonify
from flask_restful import Resource, Api
import logging
from moon_wrapper import __version__
from moon_wrapper.api.generic import Status, Logs, API
from moon_wrapper.api.oslowrapper import OsloWrapper
from python_moonutilities.cache import Cache
from python_moonutilities import configuration, exceptions

logger = logging.getLogger("moon.wrapper.http_server")


CACHE = Cache()

__API__ = (
    Status, Logs, API
 )


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()


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/orchestrator")
        _hostname = conf["components/orchestrator"].get("hostname",
                                                        "orchestrator")
        _port = conf["components/orchestrator"].get("port", 80)
        _protocol = conf["components/orchestrator"].get("protocol", "http")
        self.orchestrator_url = "{}://{}:{}".format(
            _protocol, _hostname, _port)
        # Todo : specify only few urls instead of *
        # CORS(self.app)
        self.api = Api(self.app)
        self.__set_route()
        self.__hook_errors()

    def __hook_errors(self):

        def get_404_json(e):
            return flask.make_response("False")

        self.app.register_error_handler(404, get_404_json)

        def get_400_json(e):
            return flask.make_response("False")

        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(OsloWrapper, *OsloWrapper.__urls__,
                              resource_class_kwargs={
                                  "orchestrator_url": self.orchestrator_url,
                                  "cache": CACHE,
                              }
                              )

    def run(self):
        self.app.run(host=self._host, port=self._port, threaded=True)  # nosec