Ensure timely termination of all flask servers
[osm/vim-emu.git] / src / emuvim / api / rest / rest_api_endpoint.py
1 # Copyright (c) 2015 SONATA-NFV and Paderborn University
2 # ALL RIGHTS RESERVED.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 # Neither the name of the SONATA-NFV, Paderborn University
17 # nor the names of its contributors may be used to endorse or promote
18 # products derived from this software without specific prior written
19 # permission.
20 #
21 # This work has been performed in the framework of the SONATA project,
22 # funded by the European Commission under Grant number 671517 through
23 # the Horizon 2020 and 5G-PPP programmes. The authors would like to
24 # acknowledge the contributions of their colleagues of the SONATA
25 # partner consortium (www.sonata-nfv.eu).
26
27 import logging
28 import threading
29 from flask import Flask
30 from flask_restful import Api
31 from gevent import monkey
32 from gevent.pywsgi import WSGIServer
33
34 # need to import total module to set its global variable dcs
35 import compute
36 from compute import ComputeList, Compute, ComputeResources, DatacenterList, DatacenterStatus
37
38 # need to import total module to set its global variable net
39 import network
40 from network import NetworkAction, DrawD3jsgraph
41
42 import monitor
43 from monitor import MonitorInterfaceAction, MonitorFlowAction, MonitorLinkAction, MonitorSkewAction, MonitorTerminal
44
45 import pkg_resources
46 from os import path
47
48 monkey.patch_all()
49
50 logging.basicConfig()
51
52
53 class RestApiEndpoint(object):
54 """
55 Simple API endpoint that offers a REST
56 interface. This interface will be used by the
57 default command line client.
58 """
59
60 def __init__(self, listenip, port, DCnetwork=None):
61 self.ip = listenip
62 self.port = port
63
64 # connect this DC network to the rest api endpoint (needed for the
65 # networking and monitoring api)
66 self.connectDCNetwork(DCnetwork)
67
68 # setup Flask
69 # find directory of dashboard files
70 dashboard_file = pkg_resources.resource_filename(
71 'emuvim.dashboard', "index.html")
72 dashboard_dir = path.dirname(dashboard_file)
73 logging.info("Started emu dashboard: {0}".format(dashboard_dir))
74
75 self.app = Flask(__name__, static_folder=dashboard_dir,
76 static_url_path='/dashboard')
77 self.api = Api(self.app)
78
79 # setup endpoints
80
81 # compute related actions (start/stop VNFs, get info)
82 self.api.add_resource(
83 Compute, "/restapi/compute/<dc_label>/<compute_name>")
84 self.api.add_resource(ComputeList,
85 "/restapi/compute",
86 "/restapi/compute/<dc_label>")
87 self.api.add_resource(
88 ComputeResources, "/restapi/compute/resources/<dc_label>/<compute_name>")
89
90 self.api.add_resource(
91 DatacenterStatus, "/restapi/datacenter/<dc_label>")
92 self.api.add_resource(DatacenterList, "/restapi/datacenter")
93
94 # network related actions (setup chaining between VNFs)
95 self.api.add_resource(NetworkAction,
96 "/restapi/network")
97 self.api.add_resource(DrawD3jsgraph,
98 "/restapi/network/d3jsgraph")
99
100 # monitoring related actions
101 # export a network interface traffic rate counter
102 self.api.add_resource(MonitorInterfaceAction,
103 "/restapi/monitor/interface")
104 # export flow traffic counter, of a manually pre-installed flow entry,
105 # specified by its cookie
106 self.api.add_resource(MonitorFlowAction,
107 "/restapi/monitor/flow")
108 # install monitoring of a specific flow on a pre-existing link in the service.
109 # the traffic counters of the newly installed monitor flow are exported
110 self.api.add_resource(MonitorLinkAction,
111 "/restapi/monitor/link")
112 # install skewness monitor of resource usage disribution
113 # the skewness metric is exported
114 self.api.add_resource(MonitorSkewAction,
115 "/restapi/monitor/skewness")
116 # start a terminal window for the specified vnfs
117 self.api.add_resource(MonitorTerminal,
118 "/restapi/monitor/term")
119
120 logging.debug("Created API endpoint %s(%s:%d)" %
121 (self.__class__.__name__, self.ip, self.port))
122
123 def connectDatacenter(self, dc):
124 compute.dcs[dc.label] = dc
125 logging.info(
126 "Connected DC(%s) to API endpoint %s(%s:%d)" % (dc.label, self.__class__.__name__, self.ip, self.port))
127
128 def connectDCNetwork(self, DCnetwork):
129 network.net = DCnetwork
130 monitor.net = DCnetwork
131
132 logging.info("Connected DCNetwork to API endpoint %s(%s:%d)" % (
133 self.__class__.__name__, self.ip, self.port))
134
135 def start(self):
136 self.thread = threading.Thread(target=self._start_flask, args=())
137 self.thread.daemon = True
138 self.thread.start()
139 logging.info("Started API endpoint @ http://%s:%d" %
140 (self.ip, self.port))
141
142 def stop(self):
143 if self.http_server:
144 self.http_server.close()
145
146 def _start_flask(self):
147 # self.app.run(self.ip, self.port, debug=False, use_reloader=False)
148 # this should be a more production-fit http-server
149 # self.app.logger.setLevel(logging.ERROR)
150 self.http_server = WSGIServer((self.ip, self.port),
151 self.app,
152 # This disables HTTP request logs to not
153 # mess up the CLI when e.g. the
154 # auto-updated dashboard is used
155 log=open("/dev/null", "w")
156 )
157 self.http_server.serve_forever()