Fix: Added CORS header to REST API to allow cross-domain calls from modern browsers.
[osm/vim-emu.git] / src / emuvim / api / rest / compute.py
1 """
2 Copyright (c) 2015 SONATA-NFV and Paderborn University
3 ALL RIGHTS RESERVED.
4
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16
17 Neither the name of the SONATA-NFV [, ANY ADDITIONAL AFFILIATION]
18 nor the names of its contributors may be used to endorse or promote
19 products derived from this software without specific prior written
20 permission.
21
22 This work has been performed in the framework of the SONATA project,
23 funded by the European Commission under Grant number 671517 through
24 the Horizon 2020 and 5G-PPP programmes. The authors would like to
25 acknowledge the contributions of their colleagues of the SONATA
26 partner consortium (www.sonata-nfv.eu).
27 """
28 import logging
29 from flask_restful import Resource
30 from flask import request
31 import json
32
33 logging.basicConfig(level=logging.INFO)
34
35 CORS_HEADER = {'Access-Control-Allow-Origin': '*'}
36
37 dcs = {}
38
39
40 class Compute(Resource):
41 """
42 Start a new compute instance: A docker container (note: zerorpc does not support keyword arguments)
43 :param dc_label: name of the DC
44 :param compute_name: compute container name
45 :param image: image name
46 :param command: command to execute
47 :param network: list of all interface of the vnf, with their parameters (id=id1,ip=x.x.x.x/x),...
48 example networks list({"id":"input","ip": "10.0.0.254/8"}, {"id":"output","ip": "11.0.0.254/24"})
49 :return: docker inspect dict of deployed docker
50 """
51 global dcs
52
53 def put(self, dc_label, compute_name):
54
55 # check if json data is a dict
56 data = request.json
57 if data is None:
58 data = {}
59 elif type(data) is not dict:
60 data = json.loads(request.json)
61
62 network = data.get("network")
63 nw_list = self._parse_network(network)
64 image = data.get("image")
65 command = data.get("docker_command")
66
67 try:
68 logging.debug("API CALL: compute start")
69 c = dcs.get(dc_label).startCompute(
70 compute_name, image=image, command=command, network=nw_list)
71 # return docker inspect dict
72 return c.getStatus(), 200, CORS_HEADER
73 except Exception as ex:
74 logging.exception("API error.")
75 return ex.message, 500, CORS_HEADER
76
77 def get(self, dc_label, compute_name):
78
79 logging.debug("API CALL: compute status")
80
81 try:
82 return dcs.get(dc_label).containers.get(compute_name).getStatus(), 200, CORS_HEADER
83 except Exception as ex:
84 logging.exception("API error.")
85 return ex.message, 500, CORS_HEADER
86
87 def delete(self, dc_label, compute_name):
88 logging.debug("API CALL: compute stop")
89 try:
90 return dcs.get(dc_label).stopCompute(compute_name), 200, CORS_HEADER
91 except Exception as ex:
92 logging.exception("API error.")
93 return ex.message, 500, CORS_HEADER
94
95 def _parse_network(self, network_str):
96 '''
97 parse the options for all network interfaces of the vnf
98 :param network_str: (id=x,ip=x.x.x.x/x), ...
99 :return: list of dicts [{"id":x,"ip":"x.x.x.x/x"}, ...]
100 '''
101 nw_list = list()
102
103 # TODO make this more robust with regex check
104 if network_str is None:
105 return nw_list
106
107 networks = network_str[1:-1].split('),(')
108 for nw in networks:
109 nw_dict = dict(tuple(e.split('=')) for e in nw.split(','))
110 nw_list.append(nw_dict)
111
112 return nw_list
113
114
115 class ComputeList(Resource):
116 global dcs
117
118 def get(self, dc_label=None):
119 logging.debug("API CALL: compute list")
120 try:
121 if dc_label is None or dc_label == 'None':
122 # return list with all compute nodes in all DCs
123 all_containers = []
124 for dc in dcs.itervalues():
125 all_containers += dc.listCompute()
126 return [(c.name, c.getStatus()) for c in all_containers], 200, CORS_HEADER
127 else:
128 # return list of compute nodes for specified DC
129 return [(c.name, c.getStatus())
130 for c in dcs.get(dc_label).listCompute()], 200, CORS_HEADER
131 except Exception as ex:
132 logging.exception("API error.")
133 return ex.message, 500, CORS_HEADER
134
135
136 class DatacenterList(Resource):
137 global dcs
138
139 def get(self):
140 logging.debug("API CALL: datacenter list")
141 try:
142 return [d.getStatus() for d in dcs.itervalues()], 200, CORS_HEADER
143 except Exception as ex:
144 logging.exception("API error.")
145 return ex.message, 500, CORS_HEADER
146
147
148 class DatacenterStatus(Resource):
149 global dcs
150
151 def get(self, dc_label):
152 logging.debug("API CALL: datacenter status")
153 try:
154 return dcs.get(dc_label).getStatus(), 200, CORS_HEADER
155 except Exception as ex:
156 logging.exception("API error.")
157 return ex.message, 500, CORS_HEADER