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