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