Merge "creating a default subnet"
[controller.git] / opendaylight / northbound / networkconfiguration / neutron / src / main / java / org / opendaylight / controller / networkconfig / neutron / northbound / NeutronPortsNorthbound.java
1 /*
2  * Copyright IBM Corporation, 2013.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.networkconfig.neutron.northbound;
10
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.List;
15 import javax.ws.rs.Consumes;
16 import javax.ws.rs.DELETE;
17 import javax.ws.rs.GET;
18 import javax.ws.rs.POST;
19 import javax.ws.rs.PUT;
20 import javax.ws.rs.Path;
21 import javax.ws.rs.PathParam;
22 import javax.ws.rs.Produces;
23 import javax.ws.rs.QueryParam;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.Response;
26
27 import org.codehaus.enunciate.jaxrs.ResponseCode;
28 import org.codehaus.enunciate.jaxrs.StatusCodes;
29 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
30 import org.opendaylight.controller.networkconfig.neutron.INeutronPortAware;
31 import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
32 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetAware;
33 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
34 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
35 import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
36 import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
37 import org.opendaylight.controller.networkconfig.neutron.Neutron_IPs;
38 import org.opendaylight.controller.northbound.commons.RestMessages;
39 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
40 import org.opendaylight.controller.sal.utils.ServiceHelper;
41
42 /**
43  * Open DOVE Northbound REST APIs.<br>
44  * This class provides REST APIs for managing the open DOVE
45  *
46  * <br>
47  * <br>
48  * Authentication scheme : <b>HTTP Basic</b><br>
49  * Authentication realm : <b>opendaylight</b><br>
50  * Transport : <b>HTTP and HTTPS</b><br>
51  * <br>
52  * HTTPS Authentication is disabled by default. Administrator can enable it in
53  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
54  * trusted authority.<br>
55  * More info :
56  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
57  *
58  */
59
60 @Path("/ports")
61 public class NeutronPortsNorthbound {
62
63     private NeutronPort extractFields(NeutronPort o, List<String> fields) {
64         return o.extractFields(fields);
65     }
66
67     /**
68      * Returns a list of all Ports */
69
70     @GET
71     @Produces({ MediaType.APPLICATION_JSON })
72     //@TypeHint(OpenStackPorts.class)
73     @StatusCodes({
74             @ResponseCode(code = 200, condition = "Operation successful"),
75             @ResponseCode(code = 401, condition = "Unauthorized"),
76             @ResponseCode(code = 501, condition = "Not Implemented") })
77     public Response listPorts(
78             // return fields
79             @QueryParam("fields") List<String> fields,
80             // note: openstack isn't clear about filtering on lists, so we aren't handling them
81             @QueryParam("id") String queryID,
82             @QueryParam("network_id") String queryNetworkID,
83             @QueryParam("name") String queryName,
84             @QueryParam("admin_state_up") String queryAdminStateUp,
85             @QueryParam("status") String queryStatus,
86             @QueryParam("mac_address") String queryMACAddress,
87             @QueryParam("device_id") String queryDeviceID,
88             @QueryParam("device_owner") String queryDeviceOwner,
89             @QueryParam("tenant_id") String queryTenantID,
90             // pagination
91             @QueryParam("limit") String limit,
92             @QueryParam("marker") String marker,
93             @QueryParam("page_reverse") String pageReverse
94             // sorting not supported
95             ) {
96         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
97         if (portInterface == null) {
98             throw new ServiceUnavailableException("Port CRUD Interface "
99                     + RestMessages.SERVICEUNAVAILABLE.toString());
100         }
101         List<NeutronPort> allPorts = portInterface.getAllPorts();
102         List<NeutronPort> ans = new ArrayList<NeutronPort>();
103         Iterator<NeutronPort> i = allPorts.iterator();
104         while (i.hasNext()) {
105             NeutronPort oSS = i.next();
106             if ((queryID == null || queryID.equals(oSS.getID())) &&
107                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
108                     (queryName == null || queryName.equals(oSS.getName())) &&
109                     (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
110                     (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
111                     (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&
112                     (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&
113                     (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&
114                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {
115                 if (fields.size() > 0)
116                     ans.add(extractFields(oSS,fields));
117                 else
118                     ans.add(oSS);
119             }
120         }
121         //TODO: apply pagination to results
122         return Response.status(200).entity(
123                 new NeutronPortRequest(ans)).build();
124     }
125
126     /**
127      * Returns a specific Port */
128
129     @Path("{portUUID}")
130     @GET
131     @Produces({ MediaType.APPLICATION_JSON })
132     //@TypeHint(OpenStackPorts.class)
133     @StatusCodes({
134             @ResponseCode(code = 200, condition = "Operation successful"),
135             @ResponseCode(code = 401, condition = "Unauthorized"),
136             @ResponseCode(code = 404, condition = "Not Found"),
137             @ResponseCode(code = 501, condition = "Not Implemented") })
138     public Response showPort(
139             @PathParam("portUUID") String portUUID,
140             // return fields
141             @QueryParam("fields") List<String> fields ) {
142         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
143         if (portInterface == null) {
144             throw new ServiceUnavailableException("Port CRUD Interface "
145                     + RestMessages.SERVICEUNAVAILABLE.toString());
146         }
147         if (!portInterface.portExists(portUUID))
148             return Response.status(404).build();
149         if (fields.size() > 0) {
150             NeutronPort ans = portInterface.getPort(portUUID);
151             return Response.status(200).entity(
152                     new NeutronPortRequest(extractFields(ans, fields))).build();
153         } else
154             return Response.status(200).entity(
155                     new NeutronPortRequest(portInterface.getPort(portUUID))).build();
156     }
157
158     /**
159      * Creates new Ports */
160
161     @POST
162     @Produces({ MediaType.APPLICATION_JSON })
163     @Consumes({ MediaType.APPLICATION_JSON })
164     //@TypeHint(OpenStackPorts.class)
165     @StatusCodes({
166             @ResponseCode(code = 201, condition = "Created"),
167             @ResponseCode(code = 400, condition = "Bad Request"),
168             @ResponseCode(code = 401, condition = "Unauthorized"),
169             @ResponseCode(code = 403, condition = "Forbidden"),
170             @ResponseCode(code = 404, condition = "Not Found"),
171             @ResponseCode(code = 409, condition = "Conflict"),
172             @ResponseCode(code = 501, condition = "Not Implemented"),
173             @ResponseCode(code = 503, condition = "MAC generation failure") })
174     public Response createPorts(final NeutronPortRequest input) {
175         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
176         if (portInterface == null) {
177             throw new ServiceUnavailableException("Port CRUD Interface "
178                     + RestMessages.SERVICEUNAVAILABLE.toString());
179         }
180         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
181         if (networkInterface == null) {
182             throw new ServiceUnavailableException("Network CRUD Interface "
183                     + RestMessages.SERVICEUNAVAILABLE.toString());
184         }
185         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
186         if (subnetInterface == null) {
187             throw new ServiceUnavailableException("Subnet CRUD Interface "
188                     + RestMessages.SERVICEUNAVAILABLE.toString());
189         }
190         if (input.isSingleton()) {
191             NeutronPort singleton = input.getSingleton();
192
193             /*
194              * the port must be part of an existing network, must not already exist,
195              * have a valid MAC and the MAC not be in use
196              */
197             if (singleton.getNetworkUUID() == null)
198                 return Response.status(400).build();
199             if (portInterface.portExists(singleton.getID()))
200                 return Response.status(400).build();
201             if (!networkInterface.networkExists(singleton.getNetworkUUID()))
202                 return Response.status(404).build();
203             if (singleton.getMacAddress() == null ||
204                     !singleton.getMacAddress().matches("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$"))
205                 return Response.status(400).build();
206             if (portInterface.macInUse(singleton.getMacAddress()))
207                 return Response.status(409).build();
208             Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
209             if (instances != null) {
210                 for (Object instance : instances) {
211                     INeutronPortAware service = (INeutronPortAware) instance;
212                     int status = service.canCreatePort(singleton);
213                     if (status < 200 || status > 299)
214                         return Response.status(status).build();
215                 }
216             }
217             /*
218              * if fixed IPs are specified, each one has to have an existing subnet ID
219              * that is in the same scoping network as the port.  In addition, if an IP
220              * address is specified it has to be a valid address for the subnet and not
221              * already in use
222              */
223             List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
224             if (fixedIPs != null && fixedIPs.size() > 0) {
225                 Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
226                 while (fixedIPIterator.hasNext()) {
227                     Neutron_IPs ip = fixedIPIterator.next();
228                     if (ip.getSubnetUUID() == null)
229                         return Response.status(400).build();
230                     if (!subnetInterface.subnetExists(ip.getSubnetUUID()))
231                         return Response.status(400).build();
232                     NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
233                     if (!singleton.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID()))
234                         return Response.status(400).build();
235                     if (ip.getIpAddress() != null) {
236                         if (!subnet.isValidIP(ip.getIpAddress()))
237                             return Response.status(400).build();
238                         if (subnet.isIPInUse(ip.getIpAddress()))
239                             return Response.status(409).build();
240                     }
241                 }
242             }
243
244             // add the port to the cache
245             portInterface.addPort(singleton);
246             if (instances != null) {
247                 for (Object instance : instances) {
248                     INeutronPortAware service = (INeutronPortAware) instance;
249                     service.neutronPortCreated(singleton);
250                 }
251             }
252         } else {
253             List<NeutronPort> bulk = input.getBulk();
254             Iterator<NeutronPort> i = bulk.iterator();
255             HashMap<String, NeutronPort> testMap = new HashMap<String, NeutronPort>();
256             Object[] instances = ServiceHelper.getGlobalInstances(INeutronSubnetAware.class, this, null);
257             while (i.hasNext()) {
258                 NeutronPort test = i.next();
259
260                 /*
261                  * the port must be part of an existing network, must not already exist,
262                  * have a valid MAC and the MAC not be in use.  Further the bulk request
263                  * can't already contain a new port with the same UUID
264                  */
265                 if (portInterface.portExists(test.getID()))
266                     return Response.status(400).build();
267                 if (testMap.containsKey(test.getID()))
268                     return Response.status(400).build();
269                 for (NeutronPort check : testMap.values()) {
270                     if (test.getMacAddress().equalsIgnoreCase(check.getMacAddress()))
271                         return Response.status(409).build();
272                     for (Neutron_IPs test_fixedIP : test.getFixedIPs()) {
273                         for (Neutron_IPs check_fixedIP : check.getFixedIPs()) {
274                             if (test_fixedIP.getIpAddress().equals(check_fixedIP.getIpAddress()))
275                                 return Response.status(409).build();
276                         }
277                     }
278                 }
279                 testMap.put(test.getID(), test);
280                 if (!networkInterface.networkExists(test.getNetworkUUID()))
281                     return Response.status(404).build();
282                 if (!test.getMacAddress().matches("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$"))
283                     return Response.status(400).build();
284                 if (portInterface.macInUse(test.getMacAddress()))
285                     return Response.status(409).build();
286                 if (instances != null) {
287                     for (Object instance : instances) {
288                         INeutronPortAware service = (INeutronPortAware) instance;
289                         int status = service.canCreatePort(test);
290                         if (status < 200 || status > 299)
291                             return Response.status(status).build();
292                     }
293                 }
294                 /*
295                  * if fixed IPs are specified, each one has to have an existing subnet ID
296                  * that is in the same scoping network as the port.  In addition, if an IP
297                  * address is specified it has to be a valid address for the subnet and not
298                  * already in use (or be the gateway IP address of the subnet)
299                  */
300                 List<Neutron_IPs> fixedIPs = test.getFixedIPs();
301                 if (fixedIPs != null && fixedIPs.size() > 0) {
302                     Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
303                     while (fixedIPIterator.hasNext()) {
304                         Neutron_IPs ip = fixedIPIterator.next();
305                         if (ip.getSubnetUUID() == null)
306                             return Response.status(400).build();
307                         if (!subnetInterface.subnetExists(ip.getSubnetUUID()))
308                             return Response.status(400).build();
309                         NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
310                         if (!test.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID()))
311                             return Response.status(400).build();
312                         if (ip.getIpAddress() != null) {
313                             if (!subnet.isValidIP(ip.getIpAddress()))
314                                 return Response.status(400).build();
315                             //TODO: need to add consideration for a fixed IP being assigned the same address as a allocated IP in the
316                             //same bulk create
317                             if (subnet.isIPInUse(ip.getIpAddress()))
318                                 return Response.status(409).build();
319                         }
320                     }
321                 }
322             }
323
324             //once everything has passed, then we can add to the cache
325             i = bulk.iterator();
326             while (i.hasNext()) {
327                 NeutronPort test = i.next();
328                 portInterface.addPort(test);
329                 if (instances != null) {
330                     for (Object instance : instances) {
331                         INeutronPortAware service = (INeutronPortAware) instance;
332                         service.neutronPortCreated(test);
333                     }
334                 }
335             }
336         }
337         return Response.status(201).entity(input).build();
338     }
339
340     /**
341      * Updates a Port */
342
343     @Path("{portUUID}")
344     @PUT
345     @Produces({ MediaType.APPLICATION_JSON })
346     @Consumes({ MediaType.APPLICATION_JSON })
347     //@TypeHint(OpenStackPorts.class)
348     @StatusCodes({
349             @ResponseCode(code = 200, condition = "Operation successful"),
350             @ResponseCode(code = 400, condition = "Bad Request"),
351             @ResponseCode(code = 401, condition = "Unauthorized"),
352             @ResponseCode(code = 403, condition = "Forbidden"),
353             @ResponseCode(code = 404, condition = "Not Found"),
354             @ResponseCode(code = 409, condition = "Conflict"),
355             @ResponseCode(code = 501, condition = "Not Implemented") })
356     public Response updatePort(
357             @PathParam("portUUID") String portUUID,
358             NeutronPortRequest input
359             ) {
360         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
361         if (portInterface == null) {
362             throw new ServiceUnavailableException("Port CRUD Interface "
363                     + RestMessages.SERVICEUNAVAILABLE.toString());
364         }
365         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
366         if (subnetInterface == null) {
367             throw new ServiceUnavailableException("Subnet CRUD Interface "
368                     + RestMessages.SERVICEUNAVAILABLE.toString());
369         }
370
371         // port has to exist and only a single delta is supported
372         if (!portInterface.portExists(portUUID))
373             return Response.status(404).build();
374         NeutronPort target = portInterface.getPort(portUUID);
375         if (!input.isSingleton())
376             return Response.status(400).build();
377         NeutronPort singleton = input.getSingleton();
378         NeutronPort original = portInterface.getPort(portUUID);
379
380         // deltas restricted by Neutron
381         if (singleton.getID() != null || singleton.getTenantID() != null ||
382                 singleton.getStatus() != null)
383             return Response.status(400).build();
384
385         Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
386         if (instances != null) {
387             for (Object instance : instances) {
388                 INeutronPortAware service = (INeutronPortAware) instance;
389                 int status = service.canUpdatePort(singleton, original);
390                 if (status < 200 || status > 299)
391                     return Response.status(status).build();
392             }
393         }
394
395         // Verify the new fixed ips are valid
396         List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
397         if (fixedIPs != null && fixedIPs.size() > 0) {
398             Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
399             while (fixedIPIterator.hasNext()) {
400                 Neutron_IPs ip = fixedIPIterator.next();
401                 if (ip.getSubnetUUID() == null)
402                     return Response.status(400).build();
403                 if (!subnetInterface.subnetExists(ip.getSubnetUUID()))
404                     return Response.status(400).build();
405                 NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
406                 if (!target.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID()))
407                     return Response.status(400).build();
408                 if (ip.getIpAddress() != null) {
409                     if (!subnet.isValidIP(ip.getIpAddress()))
410                         return Response.status(400).build();
411                     if (subnet.isIPInUse(ip.getIpAddress()))
412                         return Response.status(409).build();
413                 }
414             }
415         }
416
417 //        TODO: Support change of security groups
418         // update the port and return the modified object
419         portInterface.updatePort(portUUID, singleton);
420         NeutronPort updatedPort = portInterface.getPort(portUUID);
421         if (instances != null) {
422             for (Object instance : instances) {
423                 INeutronPortAware service = (INeutronPortAware) instance;
424                 service.neutronPortUpdated(updatedPort);
425             }
426         }
427         return Response.status(200).entity(
428                 new NeutronPortRequest(updatedPort)).build();
429
430     }
431
432     /**
433      * Deletes a Port */
434
435     @Path("{portUUID}")
436     @DELETE
437     @StatusCodes({
438         @ResponseCode(code = 204, condition = "No Content"),
439         @ResponseCode(code = 401, condition = "Unauthorized"),
440         @ResponseCode(code = 403, condition = "Forbidden"),
441         @ResponseCode(code = 404, condition = "Not Found"),
442         @ResponseCode(code = 501, condition = "Not Implemented") })
443     public Response deletePort(
444             @PathParam("portUUID") String portUUID) {
445         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
446         if (portInterface == null) {
447             throw new ServiceUnavailableException("Port CRUD Interface "
448                     + RestMessages.SERVICEUNAVAILABLE.toString());
449         }
450
451         // port has to exist and not be owned by anyone.  then it can be removed from the cache
452         if (!portInterface.portExists(portUUID))
453             return Response.status(404).build();
454         NeutronPort port = portInterface.getPort(portUUID);
455         if (port.getDeviceID() != null ||
456                 port.getDeviceOwner() != null)
457             Response.status(403).build();
458         NeutronPort singleton = portInterface.getPort(portUUID);
459         Object[] instances = ServiceHelper.getGlobalInstances(INeutronPortAware.class, this, null);
460         if (instances != null) {
461             for (Object instance : instances) {
462                 INeutronPortAware service = (INeutronPortAware) instance;
463                 int status = service.canDeletePort(singleton);
464                 if (status < 200 || status > 299)
465                     return Response.status(status).build();
466             }
467         }
468         portInterface.removePort(portUUID);
469         if (instances != null) {
470             for (Object instance : instances) {
471                 INeutronPortAware service = (INeutronPortAware) instance;
472                 service.neutronPortDeleted(singleton);
473             }
474         }
475         return Response.status(204).build();
476     }
477 }