6f6d3dc958d901b71d1942a6d8ff8cd2522606f6
2 Copyright (c) 2017 SONATA-NFV and Paderborn University
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
9 http://www.apache.org/licenses/LICENSE-2.0
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.
17 Neither the name of the SONATA-NFV, Paderborn University
18 nor the names of its contributors may be used to endorse or promote
19 products derived from this software without specific prior written
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).
28 from flask_restful
import Resource
29 from flask
import request
, Response
30 from emuvim
.api
.openstack
.openstack_dummies
.base_openstack_dummy
import BaseOpenstackDummy
31 from emuvim
.api
.openstack
.helper
import get_host
32 from datetime
import datetime
33 import neutron_sfc_dummy_api
as SFC
39 LOG
= logging
.getLogger("api.openstack.neutron")
42 class NeutronDummyApi(BaseOpenstackDummy
):
43 def __init__(self
, ip
, port
, compute
):
44 super(NeutronDummyApi
, self
).__init
__(ip
, port
)
45 self
.compute
= compute
47 # create default networks (OSM usually assumes to have these pre-configured)
48 self
.compute
.create_network("mgmt")
49 self
.compute
.create_network("mgmtnet")
51 self
.api
.add_resource(NeutronListAPIVersions
, "/")
52 self
.api
.add_resource(NeutronShowAPIv2Details
, "/v2.0")
53 self
.api
.add_resource(NeutronListNetworks
, "/v2.0/networks.json", "/v2.0/networks",
54 resource_class_kwargs
={'api': self
})
55 self
.api
.add_resource(NeutronShowNetwork
, "/v2.0/networks/<network_id>.json", "/v2.0/networks/<network_id>",
56 resource_class_kwargs
={'api': self
})
57 self
.api
.add_resource(NeutronCreateNetwork
, "/v2.0/networks.json", "/v2.0/networks",
58 resource_class_kwargs
={'api': self
})
59 self
.api
.add_resource(NeutronUpdateNetwork
, "/v2.0/networks/<network_id>.json", "/v2.0/networks/<network_id>",
60 resource_class_kwargs
={'api': self
})
61 self
.api
.add_resource(NeutronDeleteNetwork
, "/v2.0/networks/<network_id>.json", "/v2.0/networks/<network_id>",
62 resource_class_kwargs
={'api': self
})
63 self
.api
.add_resource(NeutronListSubnets
, "/v2.0/subnets.json", "/v2.0/subnets",
64 resource_class_kwargs
={'api': self
})
65 self
.api
.add_resource(NeutronShowSubnet
, "/v2.0/subnets/<subnet_id>.json", "/v2.0/subnets/<subnet_id>",
66 resource_class_kwargs
={'api': self
})
67 self
.api
.add_resource(NeutronCreateSubnet
, "/v2.0/subnets.json", "/v2.0/subnets",
68 resource_class_kwargs
={'api': self
})
69 self
.api
.add_resource(NeutronUpdateSubnet
, "/v2.0/subnets/<subnet_id>.json", "/v2.0/subnets/<subnet_id>",
70 resource_class_kwargs
={'api': self
})
71 self
.api
.add_resource(NeutronDeleteSubnet
, "/v2.0/subnets/<subnet_id>.json", "/v2.0/subnets/<subnet_id>",
72 resource_class_kwargs
={'api': self
})
73 self
.api
.add_resource(NeutronListPorts
, "/v2.0/ports.json", "/v2.0/ports",
74 resource_class_kwargs
={'api': self
})
75 self
.api
.add_resource(NeutronShowPort
, "/v2.0/ports/<port_id>.json", "/v2.0/ports/<port_id>",
76 resource_class_kwargs
={'api': self
})
77 self
.api
.add_resource(NeutronCreatePort
, "/v2.0/ports.json", "/v2.0/ports",
78 resource_class_kwargs
={'api': self
})
79 self
.api
.add_resource(NeutronUpdatePort
, "/v2.0/ports/<port_id>.json", "/v2.0/ports/<port_id>",
80 resource_class_kwargs
={'api': self
})
81 self
.api
.add_resource(NeutronDeletePort
, "/v2.0/ports/<port_id>.json", "/v2.0/ports/<port_id>",
82 resource_class_kwargs
={'api': self
})
83 self
.api
.add_resource(NeutronAddFloatingIp
, "/v2.0/floatingips.json", "/v2.0/floatingips",
84 resource_class_kwargs
={'api': self
})
86 # Service Function Chaining (SFC) API
87 self
.api
.add_resource(SFC
.PortPairsCreate
, "/v2.0/sfc/port_pairs.json", "/v2.0/sfc/port_pairs",
88 resource_class_kwargs
={'api': self
})
89 self
.api
.add_resource(SFC
.PortPairsUpdate
, "/v2.0/sfc/port_pairs/<pair_id>.json",
90 "/v2.0/sfc/port_pairs/<pair_id>",
91 resource_class_kwargs
={'api': self
})
92 self
.api
.add_resource(SFC
.PortPairsDelete
, "/v2.0/sfc/port_pairs/<pair_id>.json",
93 "/v2.0/sfc/port_pairs/<pair_id>",
94 resource_class_kwargs
={'api': self
})
95 self
.api
.add_resource(SFC
.PortPairsList
, "/v2.0/sfc/port_pairs.json", "/v2.0/sfc/port_pairs",
96 resource_class_kwargs
={'api': self
})
97 self
.api
.add_resource(SFC
.PortPairsShow
, "/v2.0/sfc/port_pairs/<pair_id>.json",
98 "/v2.0/sfc/port_pairs/<pair_id>",
99 resource_class_kwargs
={'api': self
})
101 self
.api
.add_resource(SFC
.PortPairGroupCreate
, "/v2.0/sfc/port_pair_groups.json", "/v2.0/sfc/port_pair_groups",
102 resource_class_kwargs
={'api': self
})
103 self
.api
.add_resource(SFC
.PortPairGroupUpdate
, "/v2.0/sfc/port_pair_groups/<group_id>.json",
104 "/v2.0/sfc/port_pair_groups/<group_id>",
105 resource_class_kwargs
={'api': self
})
106 self
.api
.add_resource(SFC
.PortPairGroupDelete
, "/v2.0/sfc/port_pair_groups/<group_id>.json",
107 "/v2.0/sfc/port_pair_groups/<group_id>",
108 resource_class_kwargs
={'api': self
})
109 self
.api
.add_resource(SFC
.PortPairGroupList
, "/v2.0/sfc/port_pair_groups.json", "/v2.0/sfc/port_pair_groups",
110 resource_class_kwargs
={'api': self
})
111 self
.api
.add_resource(SFC
.PortPairGroupShow
, "/v2.0/sfc/port_pair_groups/<group_id>.json",
112 "/v2.0/sfc/port_pair_groups/<group_id>",
113 resource_class_kwargs
={'api': self
})
115 self
.api
.add_resource(SFC
.FlowClassifierCreate
, "/v2.0/sfc/flow_classifiers.json", "/v2.0/sfc/flow_classifiers",
116 resource_class_kwargs
={'api': self
})
117 self
.api
.add_resource(SFC
.FlowClassifierUpdate
, "/v2.0/sfc/flow_classifiers/<flow_classifier_id>.json",
118 "/v2.0/sfc/flow_classifiers/<flow_classifier_id>",
119 resource_class_kwargs
={'api': self
})
120 self
.api
.add_resource(SFC
.FlowClassifierDelete
, "/v2.0/sfc/flow_classifiers/<flow_classifier_id>.json",
121 "/v2.0/sfc/flow_classifiers/<flow_classifier_id>",
122 resource_class_kwargs
={'api': self
})
123 self
.api
.add_resource(SFC
.FlowClassifierList
, "/v2.0/sfc/flow_classifiers.json", "/v2.0/sfc/flow_classifiers",
124 resource_class_kwargs
={'api': self
})
125 self
.api
.add_resource(SFC
.FlowClassifierShow
, "/v2.0/sfc/flow_classifiers/<flow_classifier_id>.json",
126 "/v2.0/sfc/flow_classifiers/<flow_classifier_id>",
127 resource_class_kwargs
={'api': self
})
129 self
.api
.add_resource(SFC
.PortChainCreate
, "/v2.0/sfc/port_chains.json", "/v2.0/sfc/port_chains",
130 resource_class_kwargs
={'api': self
})
131 self
.api
.add_resource(SFC
.PortChainUpdate
, "/v2.0/sfc/port_chains/<chain_id>.json",
132 "/v2.0/sfc/port_chains/<chain_id>",
133 resource_class_kwargs
={'api': self
})
134 self
.api
.add_resource(SFC
.PortChainDelete
, "/v2.0/sfc/port_chains/<chain_id>.json",
135 "/v2.0/sfc/port_chains/<chain_id>",
136 resource_class_kwargs
={'api': self
})
137 self
.api
.add_resource(SFC
.PortChainList
, "/v2.0/sfc/port_chains.json", "/v2.0/sfc/port_chains",
138 resource_class_kwargs
={'api': self
})
139 self
.api
.add_resource(SFC
.PortChainShow
, "/v2.0/sfc/port_chains/<chain_id>.json",
140 "/v2.0/sfc/port_chains/<chain_id>",
141 resource_class_kwargs
={'api': self
})
144 class NeutronListAPIVersions(Resource
):
149 :return: Returns a json with API versions.
150 :rtype: :class:`flask.response`
152 LOG
.debug("API CALL: Neutron - List API Versions")
154 resp
['versions'] = dict()
161 "href": request
.url_root
+ '/v2.0',
166 resp
['versions'] = versions
168 return Response(json
.dumps(resp
), status
=200, mimetype
='application/json')
171 class NeutronShowAPIv2Details(Resource
):
176 :return: Returns a json with API details.
177 :rtype: :class:`flask.response`
179 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
182 resp
['resources'] = dict()
183 resp
['resources'] = [{
186 "href": request
.url_root
+ 'v2.0/subnets',
191 "collection": "subnets"
196 "href": request
.url_root
+ 'v2.0/networks',
201 "collection": "networks"
206 "href": request
.url_root
+ 'v2.0/ports',
211 "collection": "ports"
215 return Response(json
.dumps(resp
), status
=200, mimetype
='application/json')
218 class NeutronListNetworks(Resource
):
219 def __init__(self
, api
):
224 Lists all networks, used in son-emu. If a 'name' or one or more 'id's are specified, it will only list the
225 network with the name, or the networks specified via id.
227 :return: Returns a json response, starting with 'networks' as root node.
228 :rtype: :class:`flask.response`
230 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
231 # LOG.debug("ARGS: {}".format(request.args))
233 if request
.args
.get('name'):
234 tmp_network
= NeutronShowNetwork(self
.api
)
235 response
= tmp_network
.get_network(request
.args
.get('name'), True)
236 LOG
.debug("{} RESPONSE (1): {}".format(self
.__class
__.__name
__, response
))
238 id_list
= request
.args
.getlist('id')
239 if len(id_list
) == 1:
240 tmp_network
= NeutronShowNetwork(self
.api
)
241 response
= tmp_network
.get_network(request
.args
.get('id'), True)
242 LOG
.debug("{} RESPONSE (2): {}".format(self
.__class
__.__name
__, response
))
245 network_list
= list()
246 network_dict
= dict()
248 if len(id_list
) == 0:
249 for net
in self
.api
.compute
.nets
.values():
250 tmp_network_dict
= net
.create_network_dict()
251 if tmp_network_dict
not in network_list
:
252 network_list
.append(tmp_network_dict
)
254 for net
in self
.api
.compute
.nets
.values():
255 if net
.id in id_list
:
256 tmp_network_dict
= net
.create_network_dict()
257 if tmp_network_dict
not in network_list
:
258 network_list
.append(tmp_network_dict
)
260 network_dict
["networks"] = network_list
261 LOG
.debug("{} RESPONSE (3): {}".format(self
.__class
__.__name
__, network_dict
))
262 return Response(json
.dumps(network_dict
), status
=200, mimetype
='application/json')
264 except Exception as ex
:
265 LOG
.exception("Neutron: List networks exception.")
266 return Response(ex
.message
, status
=500, mimetype
='application/json')
269 class NeutronShowNetwork(Resource
):
270 def __init__(self
, api
):
273 def get(self
, network_id
):
275 Returns the network, specified via 'network_id'.
277 :param network_id: The unique ID string of the network.
278 :type network_id: ``str``
279 :return: Returns a json response, starting with 'network' as root node and one network description.
280 :rtype: :class:`flask.response`
282 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
283 return self
.get_network(network_id
, False)
285 def get_network(self
, network_name_or_id
, as_list
):
287 Returns one network description of the network, specified via 'network_name_or_id'.
289 :param network_name_or_id: The indicator string, which specifies the requested network.
290 :type network_name_or_id: ``str``
291 :param as_list: Determines if the network description should start with the root node 'network' or 'networks'.
292 :type as_list: ``bool``
293 :return: Returns a json response, with one network description.
294 :rtype: :class:`flask.response`
297 net
= self
.api
.compute
.find_network_by_name_or_id(network_name_or_id
)
299 return Response(u
'Network not found.\n', status
=404, mimetype
='application/json')
301 tmp_network_dict
= net
.create_network_dict()
304 tmp_dict
["networks"] = [tmp_network_dict
]
306 tmp_dict
["network"] = tmp_network_dict
308 return Response(json
.dumps(tmp_dict
), status
=200, mimetype
='application/json')
311 except Exception as ex
:
312 logging
.exception("Neutron: Show network exception.")
313 return Response(ex
.message
, status
=500, mimetype
='application/json')
316 class NeutronCreateNetwork(Resource
):
317 def __init__(self
, api
):
322 Creates a network with the name, specified within the request under ['network']['name'].
324 :return: * 400, if the network already exists.
325 * 500, if any exception occurred while creation.
326 * 201, if everything worked out.
327 :rtype: :class:`flask.response`
329 LOG
.debug("API CALL: %s POST" % str(self
.__class
__.__name
__))
331 network_dict
= json
.loads(request
.data
)
332 name
= network_dict
['network']['name']
333 net
= self
.api
.compute
.find_network_by_name_or_id(name
)
335 return Response('Network already exists.\n', status
=400, mimetype
='application/json')
337 net
= self
.api
.compute
.create_network(name
)
338 return Response(json
.dumps({"network": net
.create_network_dict()}), status
=201, mimetype
='application/json')
339 except Exception as ex
:
340 LOG
.exception("Neutron: Create network excepiton.")
341 return Response(ex
.message
, status
=500, mimetype
='application/json')
344 class NeutronUpdateNetwork(Resource
):
345 def __init__(self
, api
):
348 def put(self
, network_id
): # TODO currently only the name will be changed
350 Updates the existing network with the given parameters.
352 :param network_id: The indicator string, which specifies the requested network.
353 :type network_id: ``str``
354 :return: * 404, if the network could not be found.
355 * 500, if any exception occurred while updating the network.
356 * 200, if everything worked out.
357 :rtype: :class:`flask.response`
359 LOG
.debug("API CALL: %s PUT" % str(self
.__class
__.__name
__))
361 if network_id
in self
.api
.compute
.nets
:
362 net
= self
.api
.compute
.nets
[network_id
]
363 network_dict
= json
.loads(request
.data
)
364 old_net
= copy
.copy(net
)
366 if "status" in network_dict
["network"]:
367 net
.status
= network_dict
["network"]["status"]
368 if "subnets" in network_dict
["network"]:
369 pass # tmp_network_dict["subnets"] = None
370 if "name" in network_dict
["network"] and net
.name
!= network_dict
["network"]["name"]:
371 net
.name
= network_dict
["network"]["name"]
372 if "admin_state_up" in network_dict
["network"]:
373 pass # tmp_network_dict["admin_state_up"] = True
374 if "tenant_id" in network_dict
["network"]:
375 pass # tmp_network_dict["tenant_id"] = "c1210485b2424d48804aad5d39c61b8f"
376 if "shared" in network_dict
["network"]:
377 pass # tmp_network_dict["shared"] = False
379 return Response(json
.dumps(network_dict
), status
=200, mimetype
='application/json')
381 return Response('Network not found.\n', status
=404, mimetype
='application/json')
383 except Exception as ex
:
384 LOG
.exception("Neutron: Show networks exception.")
385 return Response(ex
.message
, status
=500, mimetype
='application/json')
388 class NeutronDeleteNetwork(Resource
):
389 def __init__(self
, api
):
392 def delete(self
, network_id
):
394 Deletes the specified network and all its subnets.
396 :param network_id: The indicator string, which specifies the requested network.
397 :type network_id: ``str``
398 :return: * 404, if the network or the subnet could not be removed.
399 * 500, if any exception occurred while deletion.
400 * 204, if everything worked out.
401 :rtype: :class:`flask.response`
403 LOG
.debug("API CALL: %s DELETE" % str(self
.__class
__.__name
__))
405 if network_id
not in self
.api
.compute
.nets
:
406 return Response('Could not find network. (' + network_id
+ ')\n',
407 status
=404, mimetype
='application/json')
409 net
= self
.api
.compute
.nets
[network_id
]
410 delete_subnet
= NeutronDeleteSubnet(self
.api
)
411 resp
= delete_subnet
.delete(net
.subnet_id
)
413 if not '204' in resp
.status
and not '404' in resp
.status
:
416 self
.api
.compute
.delete_network(network_id
)
418 return Response('', status
=204, mimetype
='application/json')
419 except Exception as ex
:
420 LOG
.exception("Neutron: Delete network exception.")
421 return Response(ex
.message
, status
=500, mimetype
='application/json')
424 class NeutronListSubnets(Resource
):
425 def __init__(self
, api
):
430 Lists all subnets, used in son-emu. If a 'name' or one or more 'id's are specified, it will only list the
431 subnet with the name, or the subnets specified via id.
433 :return: Returns a json response, starting with 'subnets' as root node.
434 :rtype: :class:`flask.response`
436 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
438 if request
.args
.get('name'):
439 show_subnet
= NeutronShowSubnet(self
.api
)
440 return show_subnet
.get_subnet(request
.args
.get('name'), True)
441 id_list
= request
.args
.getlist('id')
442 if len(id_list
) == 1:
443 show_subnet
= NeutronShowSubnet(self
.api
)
444 return show_subnet
.get_subnet(id_list
[0], True)
449 if len(id_list
) == 0:
450 for net
in self
.api
.compute
.nets
.values():
451 if net
.subnet_id
is not None:
452 tmp_subnet_dict
= net
.create_subnet_dict()
453 subnet_list
.append(tmp_subnet_dict
)
455 for net
in self
.api
.compute
.nets
.values():
456 if net
.subnet_id
in id_list
:
457 tmp_subnet_dict
= net
.create_subnet_dict()
458 subnet_list
.append(tmp_subnet_dict
)
460 subnet_dict
["subnets"] = subnet_list
462 return Response(json
.dumps(subnet_dict
), status
=200, mimetype
='application/json')
464 except Exception as ex
:
465 LOG
.exception("Neutron: List subnets exception.")
466 return Response(ex
.message
, status
=500, mimetype
='application/json')
469 class NeutronShowSubnet(Resource
):
470 def __init__(self
, api
):
473 def get(self
, subnet_id
):
475 Returns the subnet, specified via 'subnet_id'.
477 :param subnet_id: The unique ID string of the subnet.
478 :type subnet_id: ``str``
479 :return: Returns a json response, starting with 'subnet' as root node and one subnet description.
480 :rtype: :class:`flask.response`
482 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
483 return self
.get_subnet(subnet_id
, False)
485 def get_subnet(self
, subnet_name_or_id
, as_list
):
487 Returns one subnet description of the subnet, specified via 'subnet_name_or_id'.
489 :param subnet_name_or_id: The indicator string, which specifies the requested subnet.
490 :type subnet_name_or_id: ``str``
491 :param as_list: Determines if the subnet description should start with the root node 'subnet' or 'subnets'.
492 :type as_list: ``bool``
493 :return: Returns a json response, with one subnet description.
494 :rtype: :class:`flask.response`
497 for net
in self
.api
.compute
.nets
.values():
498 if net
.subnet_id
== subnet_name_or_id
or net
.subnet_name
== subnet_name_or_id
:
499 tmp_subnet_dict
= net
.create_subnet_dict()
502 tmp_dict
["subnets"] = [tmp_subnet_dict
]
504 tmp_dict
["subnet"] = tmp_subnet_dict
505 return Response(json
.dumps(tmp_dict
), status
=200, mimetype
='application/json')
507 return Response('Subnet not found. (' + subnet_name_or_id
+ ')\n', status
=404, mimetype
='application/json')
509 except Exception as ex
:
510 LOG
.exception("Neutron: Show subnet exception.")
511 return Response(ex
.message
, status
=500, mimetype
='application/json')
514 class NeutronCreateSubnet(Resource
):
515 def __init__(self
, api
):
520 Creates a subnet with the name, specified within the request under ['subnet']['name'].
522 :return: * 400, if the 'CIDR' format is wrong or it does not exist.
523 * 404, if the network was not found.
524 * 409, if the corresponding network already has one subnet.
525 * 500, if any exception occurred while creation and
526 * 201, if everything worked out.
527 :rtype: :class:`flask.response`
529 LOG
.debug("API CALL: %s POST" % str(self
.__class
__.__name
__))
531 subnet_dict
= json
.loads(request
.data
)
532 net
= self
.api
.compute
.find_network_by_name_or_id(subnet_dict
['subnet']['network_id'])
535 return Response('Could not find network.\n', status
=404, mimetype
='application/json')
537 net
.subnet_name
= subnet_dict
["subnet"].get('name', str(net
.name
) + '-sub')
538 if net
.subnet_id
is not None:
539 LOG
.error("Only one subnet per network is supported: {}".format(net
.subnet_id
))
540 return Response('Only one subnet per network is supported\n', status
=409, mimetype
='application/json')
542 if "id" in subnet_dict
["subnet"]:
543 net
.subnet_id
= subnet_dict
["subnet"]["id"]
545 net
.subnet_id
= str(uuid
.uuid4())
546 import emuvim
.api
.openstack
.ip_handler
as IP
547 net
.set_cidr(IP
.get_new_cidr(net
.subnet_id
))
549 if "tenant_id" in subnet_dict
["subnet"]:
551 if "allocation_pools" in subnet_dict
["subnet"]:
553 if "gateway_ip" in subnet_dict
["subnet"]:
554 net
.gateway_ip
= subnet_dict
["subnet"]["gateway_ip"]
555 if "ip_version" in subnet_dict
["subnet"]:
557 if "enable_dhcp" in subnet_dict
["subnet"]:
560 return Response(json
.dumps({'subnet': net
.create_subnet_dict()}), status
=201, mimetype
='application/json')
562 except Exception as ex
:
563 LOG
.exception("Neutron: Create network excepiton.")
564 return Response(ex
.message
, status
=500, mimetype
='application/json')
567 class NeutronUpdateSubnet(Resource
):
568 def __init__(self
, api
):
571 def put(self
, subnet_id
):
573 Updates the existing subnet with the given parameters.
575 :param subnet_id: The indicator string, which specifies the requested subnet.
576 :type subnet_id: ``str``
577 :return: * 404, if the network could not be found.
578 * 500, if any exception occurred while updating the network.
579 * 200, if everything worked out.
580 :rtype: :class:`flask.response`
582 LOG
.debug("API CALL: %s PUT" % str(self
.__class
__.__name
__))
584 for net
in self
.api
.compute
.nets
.values():
585 if net
.subnet_id
== subnet_id
:
586 subnet_dict
= json
.loads(request
.data
)
588 if "name" in subnet_dict
["subnet"]:
589 net
.subnet_name
= subnet_dict
["subnet"]["name"]
590 if "network_id" in subnet_dict
["subnet"]:
591 net
.id = subnet_dict
["subnet"]["network_id"]
592 if "tenant_id" in subnet_dict
["subnet"]:
594 if "allocation_pools" in subnet_dict
["subnet"]:
596 if "gateway_ip" in subnet_dict
["subnet"]:
597 net
.gateway_ip
= subnet_dict
["subnet"]["gateway_ip"]
598 if "ip_version" in subnet_dict
["subnet"]:
600 if "cidr" in subnet_dict
["subnet"]:
601 net
.set_cidr(subnet_dict
["subnet"]["cidr"])
602 if "id" in subnet_dict
["subnet"]:
603 net
.subnet_id
= subnet_dict
["subnet"]["id"]
604 if "enable_dhcp" in subnet_dict
["subnet"]:
607 net
.subnet_update_time
= str(datetime
.now())
608 tmp_dict
= {'subnet': net
.create_subnet_dict()}
609 return Response(json
.dumps(tmp_dict
), status
=200, mimetype
='application/json')
611 return Response('Network not found.\n', status
=404, mimetype
='application/json')
613 except Exception as ex
:
614 LOG
.exception("Neutron: Show networks exception.")
615 return Response(ex
.message
, status
=500, mimetype
='application/json')
618 class NeutronDeleteSubnet(Resource
):
619 def __init__(self
, api
):
622 def delete(self
, subnet_id
):
624 Deletes the specified subnet.
626 :param subnet_id: The indicator string, which specifies the requested subnet.
627 :type subnet_id: ``str``
628 :return: * 404, if the subnet could not be removed.
629 * 500, if any exception occurred while deletion.
630 * 204, if everything worked out.
631 :rtype: :class:`flask.response`
633 LOG
.debug("API CALL: %s DELETE" % str(self
.__class
__.__name
__))
635 for net
in self
.api
.compute
.nets
.values():
636 if net
.subnet_id
== subnet_id
:
637 for server
in self
.api
.compute
.computeUnits
.values():
638 for port_name
in server
.port_names
:
639 port
= self
.api
.compute
.find_port_by_name_or_id(port_name
)
641 LOG
.warning("Port search for {} returned None.".format(port_name
))
643 if port
.net_name
== net
.name
:
644 port
.ip_address
= None
645 self
.api
.compute
.dc
.net
.removeLink(
647 node1
=self
.api
.compute
.dc
.containers
[server
.name
],
648 node2
=self
.api
.compute
.dc
.switch
)
653 return Response('', status
=204, mimetype
='application/json')
655 return Response('Could not find subnet.', status
=404, mimetype
='application/json')
656 except Exception as ex
:
657 LOG
.exception("Neutron: Delete subnet exception.")
658 return Response(ex
.message
, status
=500, mimetype
='application/json')
661 class NeutronListPorts(Resource
):
662 def __init__(self
, api
):
667 Lists all ports, used in son-emu. If a 'name' or one or more 'id's are specified, it will only list the
668 port with the name, or the ports specified via id.
670 :return: Returns a json response, starting with 'ports' as root node.
671 :rtype: :class:`flask.response`
673 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
675 if request
.args
.get('name'):
676 show_port
= NeutronShowPort(self
.api
)
677 return show_port
.get_port(request
.args
.get('name'), True)
678 id_list
= request
.args
.getlist('id')
679 if len(id_list
) == 1:
680 show_port
= NeutronShowPort(self
.api
)
681 return show_port
.get_port(request
.args
.get('id'), True)
686 if len(id_list
) == 0:
687 for port
in self
.api
.compute
.ports
.values():
688 tmp_port_dict
= port
.create_port_dict(self
.api
.compute
)
689 port_list
.append(tmp_port_dict
)
691 for port
in self
.api
.compute
.ports
.values():
692 if port
.id in id_list
:
693 tmp_port_dict
= port
.create_port_dict(self
.api
.compute
)
694 port_list
.append(tmp_port_dict
)
696 port_dict
["ports"] = port_list
698 return Response(json
.dumps(port_dict
), status
=200, mimetype
='application/json')
700 except Exception as ex
:
701 LOG
.exception("Neutron: List ports exception.")
702 return Response(ex
.message
, status
=500, mimetype
='application/json')
705 class NeutronShowPort(Resource
):
706 def __init__(self
, api
):
709 def get(self
, port_id
):
711 Returns the port, specified via 'port_id'.
713 :param port_id: The unique ID string of the network.
714 :type port_id: ``str``
715 :return: Returns a json response, starting with 'port' as root node and one network description.
716 :rtype: :class:`flask.response`
718 LOG
.debug("API CALL: %s GET" % str(self
.__class
__.__name
__))
719 return self
.get_port(port_id
, False)
721 def get_port(self
, port_name_or_id
, as_list
):
723 Returns one network description of the port, specified via 'port_name_or_id'.
725 :param port_name_or_id: The indicator string, which specifies the requested port.
726 :type port_name_or_id: ``str``
727 :param as_list: Determines if the port description should start with the root node 'port' or 'ports'.
728 :type as_list: ``bool``
729 :return: Returns a json response, with one port description.
730 :rtype: :class:`flask.response`
733 port
= self
.api
.compute
.find_port_by_name_or_id(port_name_or_id
)
735 return Response('Port not found. (' + port_name_or_id
+ ')\n', status
=404, mimetype
='application/json')
736 tmp_port_dict
= port
.create_port_dict(self
.api
.compute
)
739 tmp_dict
["ports"] = [tmp_port_dict
]
741 tmp_dict
["port"] = tmp_port_dict
742 return Response(json
.dumps(tmp_dict
), status
=200, mimetype
='application/json')
743 except Exception as ex
:
744 LOG
.exception("Neutron: Show port exception.")
745 return Response(ex
.message
, status
=500, mimetype
='application/json')
748 class NeutronCreatePort(Resource
):
749 def __init__(self
, api
):
754 Creates a port with the name, specified within the request under ['port']['name'].
756 :return: * 404, if the network could not be found.
757 * 500, if any exception occurred while creation and
758 * 201, if everything worked out.
759 :rtype: :class:`flask.response`
761 LOG
.debug("API CALL: %s POST" % str(self
.__class
__.__name
__))
763 port_dict
= json
.loads(request
.data
)
764 net_id
= port_dict
['port']['network_id']
766 if net_id
not in self
.api
.compute
.nets
:
767 return Response('Could not find network.\n', status
=404, mimetype
='application/json')
769 net
= self
.api
.compute
.nets
[net_id
]
770 if 'name' in port_dict
['port']:
771 name
= port_dict
['port']['name']
773 num_ports
= len(self
.api
.compute
.ports
)
774 name
= "port:cp%s:man:%s" % (num_ports
, str(uuid
.uuid4()))
776 if self
.api
.compute
.find_port_by_name_or_id(name
):
777 return Response("Port with name %s already exists.\n" % name
, status
=500, mimetype
='application/json')
779 port
= self
.api
.compute
.create_port(name
)
781 port
.net_name
= net
.name
782 port
.ip_address
= net
.get_new_ip_address(name
)
784 if "admin_state_up" in port_dict
["port"]:
786 if "device_id" in port_dict
["port"]:
788 if "device_owner" in port_dict
["port"]:
790 if "fixed_ips" in port_dict
["port"]:
792 if "mac_address" in port_dict
["port"]:
793 port
.mac_address
= port_dict
["port"]["mac_address"]
794 if "status" in port_dict
["port"]:
796 if "tenant_id" in port_dict
["port"]:
799 # add the port to a stack if the specified network is a stack network
800 for stack
in self
.api
.compute
.stacks
.values():
801 for net
in stack
.nets
.values():
803 stack
.ports
[name
] = port
805 return Response(json
.dumps({'port': port
.create_port_dict(self
.api
.compute
)}), status
=201,
806 mimetype
='application/json')
807 except Exception as ex
:
808 LOG
.exception("Neutron: Show port exception.")
809 return Response(ex
.message
, status
=500, mimetype
='application/json')
812 class NeutronUpdatePort(Resource
):
813 def __init__(self
, api
):
816 def put(self
, port_id
):
818 Updates the existing port with the given parameters.
820 :param network_id: The indicator string, which specifies the requested port.
821 :type network_id: ``str``
822 :return: * 404, if the network could not be found.
823 * 500, if any exception occurred while updating the network.
824 * 200, if everything worked out.
825 :rtype: :class:`flask.response`
827 LOG
.debug("API CALL: %s PUT" % str(self
.__class
__.__name
__))
829 port_dict
= json
.loads(request
.data
)
830 port
= self
.api
.compute
.find_port_by_name_or_id(port_id
)
832 return Response("Port with id %s does not exists.\n" % port_id
, status
=404, mimetype
='application/json')
833 old_port
= copy
.copy(port
)
836 for s
in self
.api
.compute
.stacks
.values():
837 for port
in s
.ports
.values():
838 if port
.id == port_id
:
840 if "admin_state_up" in port_dict
["port"]:
842 if "device_id" in port_dict
["port"]:
844 if "device_owner" in port_dict
["port"]:
846 if "fixed_ips" in port_dict
["port"]:
848 if "id" in port_dict
["port"]:
849 port
.id = port_dict
["port"]["id"]
850 if "mac_address" in port_dict
["port"]:
851 port
.mac_address
= port_dict
["port"]["mac_address"]
852 if "name" in port_dict
["port"] and port_dict
["port"]["name"] != port
.name
:
853 port
.set_name(port_dict
["port"]["name"])
854 if stack
is not None:
855 if port
.net_name
in stack
.nets
:
856 stack
.nets
[port
.net_name
].update_port_name_for_ip_address(port
.ip_address
, port
.name
)
857 stack
.ports
[port
.name
] = stack
.ports
[old_port
.name
]
858 del stack
.ports
[old_port
.name
]
859 if "network_id" in port_dict
["port"]:
861 if "status" in port_dict
["port"]:
863 if "tenant_id" in port_dict
["port"]:
866 return Response(json
.dumps({'port': port
.create_port_dict(self
.api
.compute
)}), status
=200,
867 mimetype
='application/json')
868 except Exception as ex
:
869 LOG
.exception("Neutron: Update port exception.")
870 return Response(ex
.message
, status
=500, mimetype
='application/json')
873 class NeutronDeletePort(Resource
):
874 def __init__(self
, api
):
877 def delete(self
, port_id
):
879 Deletes the specified port.
881 :param port_id: The indicator string, which specifies the requested port.
882 :type port_id: ``str``
883 :return: * 404, if the port could not be found.
884 * 500, if any exception occurred while deletion.
885 * 204, if everything worked out.
886 :rtype: :class:`flask.response`
888 LOG
.debug("API CALL: %s DELETE" % str(self
.__class
__.__name
__))
890 port
= self
.api
.compute
.find_port_by_name_or_id(port_id
)
892 return Response("Port with id %s does not exists.\n" % port_id
, status
=404)
894 for s
in self
.api
.compute
.stacks
.values():
895 for p
in s
.ports
.values():
898 if stack
is not None:
899 if port
.net_name
in stack
.nets
:
900 stack
.nets
[port
.net_name
].withdraw_ip_address(port
.ip_address
)
901 for server
in stack
.servers
.values():
903 server
.port_names
.remove(port
.name
)
908 self
.api
.compute
.delete_port(port
.id)
910 return Response('', status
=204, mimetype
='application/json')
912 except Exception as ex
:
913 LOG
.exception("Neutron: Delete port exception.")
914 return Response(ex
.message
, status
=500, mimetype
='application/json')
917 class NeutronAddFloatingIp(Resource
):
918 def __init__(self
, api
):
923 Added a quick and dirty fake for the OSM integration. Returns a list of
924 floating IPs. Has nothing to do with the setup inside the emulator.
925 But its enough to make the OSM driver happy.
926 @PG Sandman: Feel free to improve this and let it do something meaningful.
929 resp
["floatingips"] = list()
930 # create a list of floting IP definitions and return it
931 for i
in range(100, 110):
933 ip
["router_id"] = "router_id"
934 ip
["description"] = "hardcoded in api"
935 ip
["created_at"] = "router_id"
936 ip
["updated_at"] = "router_id"
937 ip
["revision_number"] = 1
938 ip
["tenant_id"] = "tenant_id"
939 ip
["project_id"] = "project_id"
940 ip
["floating_network_id"] = str(i
)
941 ip
["status"] = "ACTIVE"
943 ip
["port_id"] = "port_id"
944 ip
["floating_ip_address"] = "172.0.0.%d" % i
945 ip
["fixed_ip_address"] = "10.0.0.%d" % i
946 resp
["floatingips"].append(ip
)
947 return Response(json
.dumps(resp
), status
=200, mimetype
='application/json')
951 Adds a floating IP to neutron.
953 :return: Returns a floating network description.
954 :rtype: :class:`flask.response`
956 LOG
.debug("API CALL: %s POST" % str(self
.__class
__.__name
__))
958 # Fiddle with floating_network !
959 req
= json
.loads(request
.data
)
961 network_id
= req
["floatingip"]["floating_network_id"]
962 net
= self
.api
.compute
.find_network_by_name_or_id(network_id
)
963 if net
!= self
.api
.manage
.floating_network
:
964 return Response("You have to specify the existing floating network\n",
965 status
=400, mimetype
='application/json')
967 port_id
= req
["floatingip"].get("port_id", None)
968 port
= self
.api
.compute
.find_port_by_name_or_id(port_id
)
970 if port
.net_name
!= self
.api
.manage
.floating_network
.name
:
971 return Response("You have to specify a port in the floating network\n",
972 status
=400, mimetype
='application/json')
974 if port
.floating_ip
is not None:
975 return Response("We allow only one floating ip per port\n", status
=400, mimetype
='application/json')
977 num_ports
= len(self
.api
.compute
.ports
)
978 name
= "port:cp%s:fl:%s" % (num_ports
, str(uuid
.uuid4()))
979 port
= self
.api
.compute
.create_port(name
)
980 port
.net_name
= net
.name
981 port
.ip_address
= net
.get_new_ip_address(name
)
983 port
.floating_ip
= port
.ip_address
986 resp
= response
["floatingip"] = dict()
988 resp
["floating_network_id"] = net
.id
989 resp
["status"] = "ACTIVE"
991 resp
["port_id"] = port
.id
992 resp
["floating_ip_address"] = port
.floating_ip
993 resp
["fixed_ip_address"] = port
.floating_ip
995 return Response(json
.dumps(response
), status
=200, mimetype
='application/json')
996 except Exception as ex
:
997 LOG
.exception("Neutron: Create FloatingIP exception %s.", ex
)
998 return Response(ex
.message
, status
=500, mimetype
='application/json')