Fixed package directory issues.
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / 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.neutron.northbound.api;
10
11 import org.codehaus.enunciate.jaxrs.ResponseCode;
12 import org.codehaus.enunciate.jaxrs.StatusCodes;
13 import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
14 import org.opendaylight.neutron.spi.INeutronPortAware;
15 import org.opendaylight.neutron.spi.INeutronPortCRUD;
16 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
17 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
18 import org.opendaylight.neutron.spi.NeutronPort;
19 import org.opendaylight.neutron.spi.NeutronSubnet;
20 import org.opendaylight.neutron.spi.Neutron_IPs;
21
22 import javax.ws.rs.Consumes;
23 import javax.ws.rs.DELETE;
24 import javax.ws.rs.DefaultValue;
25 import javax.ws.rs.GET;
26 import javax.ws.rs.POST;
27 import javax.ws.rs.PUT;
28 import javax.ws.rs.Path;
29 import javax.ws.rs.PathParam;
30 import javax.ws.rs.Produces;
31 import javax.ws.rs.QueryParam;
32 import javax.ws.rs.core.Context;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.UriInfo;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40
41 /**
42  * Neutron Northbound REST APIs.<br>
43  * This class provides REST APIs for managing neutron port objects
44  *
45  * <br>
46  * <br>
47  * Authentication scheme : <b>HTTP Basic</b><br>
48  * Authentication realm : <b>opendaylight</b><br>
49  * Transport : <b>HTTP and HTTPS</b><br>
50  * <br>
51  * HTTPS Authentication is disabled by default. Administrator can enable it in
52  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
53  * trusted authority.<br>
54  * More info :
55  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
56  *
57  */
58
59 @Path("/ports")
60 public class NeutronPortsNorthbound {
61
62     final String mac_regex="^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
63
64     private NeutronPort extractFields(NeutronPort o, List<String> fields) {
65         return o.extractFields(fields);
66     }
67
68     @Context
69     UriInfo uriInfo;
70
71     /**
72      * Returns a list of all Ports */
73
74     @GET
75     @Produces({ MediaType.APPLICATION_JSON })
76     //@TypeHint(OpenStackPorts.class)
77     @StatusCodes({
78         @ResponseCode(code = 200, condition = "Operation successful"),
79         @ResponseCode(code = 401, condition = "Unauthorized"),
80         @ResponseCode(code = 501, condition = "Not Implemented"),
81         @ResponseCode(code = 503, condition = "No providers available") })
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         @ResponseCode(code = 503, condition = "No providers available") })
152     public Response showPort(
153             @PathParam("portUUID") String portUUID,
154             // return fields
155             @QueryParam("fields") List<String> fields ) {
156         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
157         if (portInterface == null) {
158             throw new ServiceUnavailableException("Port CRUD Interface "
159                     + RestMessages.SERVICEUNAVAILABLE.toString());
160         }
161         if (!portInterface.portExists(portUUID)) {
162             throw new ResourceNotFoundException("port UUID does not exist.");
163         }
164         if (fields.size() > 0) {
165             NeutronPort ans = portInterface.getPort(portUUID);
166             return Response.status(200).entity(
167                     new NeutronPortRequest(extractFields(ans, fields))).build();
168         } else {
169             return Response.status(200).entity(
170                     new NeutronPortRequest(portInterface.getPort(portUUID))).build();
171         }
172     }
173
174     /**
175      * Creates new Ports */
176
177     @POST
178     @Produces({ MediaType.APPLICATION_JSON })
179     @Consumes({ MediaType.APPLICATION_JSON })
180     //@TypeHint(OpenStackPorts.class)
181     @StatusCodes({
182         @ResponseCode(code = 201, condition = "Created"),
183         @ResponseCode(code = 400, condition = "Bad Request"),
184         @ResponseCode(code = 401, condition = "Unauthorized"),
185         @ResponseCode(code = 403, condition = "Forbidden"),
186         @ResponseCode(code = 404, condition = "Not Found"),
187         @ResponseCode(code = 409, condition = "Conflict"),
188         @ResponseCode(code = 501, condition = "Not Implemented"),
189         @ResponseCode(code = 503, condition = "MAC generation failure"),
190         @ResponseCode(code = 503, condition = "No providers available") })
191     public Response createPorts(final NeutronPortRequest input) {
192         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
193         if (portInterface == null) {
194             throw new ServiceUnavailableException("Port CRUD Interface "
195                     + RestMessages.SERVICEUNAVAILABLE.toString());
196         }
197         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
198         if (networkInterface == null) {
199             throw new ServiceUnavailableException("Network CRUD Interface "
200                     + RestMessages.SERVICEUNAVAILABLE.toString());
201         }
202         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
203         if (subnetInterface == null) {
204             throw new ServiceUnavailableException("Subnet CRUD Interface "
205                     + RestMessages.SERVICEUNAVAILABLE.toString());
206         }
207         if (input.isSingleton()) {
208             NeutronPort singleton = input.getSingleton();
209
210             /*
211              * the port must be part of an existing network, must not already exist,
212              * have a valid MAC and the MAC not be in use
213              */
214             if (singleton.getNetworkUUID() == null) {
215                 throw new BadRequestException("network UUID musy be specified");
216             }
217             if (portInterface.portExists(singleton.getID())) {
218                 throw new BadRequestException("port UUID already exists");
219             }
220             if (!networkInterface.networkExists(singleton.getNetworkUUID())) {
221                 throw new ResourceNotFoundException("network UUID does not exist.");
222             }
223             if (singleton.getMacAddress() == null ||
224                     !singleton.getMacAddress().matches(mac_regex)) {
225                 throw new BadRequestException("MAC address not properly formatted");
226             }
227             if (portInterface.macInUse(singleton.getMacAddress())) {
228                 throw new ResourceConflictException("MAC Address is in use.");
229             }
230             /*
231              * if fixed IPs are specified, each one has to have an existing subnet ID
232              * that is in the same scoping network as the port.  In addition, if an IP
233              * address is specified it has to be a valid address for the subnet and not
234              * already in use
235              */
236             List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
237             if (fixedIPs != null && fixedIPs.size() > 0) {
238                 Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
239                 while (fixedIPIterator.hasNext()) {
240                     Neutron_IPs ip = fixedIPIterator.next();
241                     if (ip.getSubnetUUID() == null) {
242                         throw new BadRequestException("subnet UUID not specified");
243                     }
244                     if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
245                         throw new BadRequestException("subnet UUID must exists");
246                     }
247                     NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
248                     if (!singleton.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
249                         throw new BadRequestException("network UUID must match that of subnet");
250                     }
251                     if (ip.getIpAddress() != null) {
252                         if (!subnet.isValidIP(ip.getIpAddress())) {
253                             throw new BadRequestException("IP address is not valid");
254                         }
255                         if (subnet.isIPInUse(ip.getIpAddress())) {
256                             throw new ResourceConflictException("IP address is in use.");
257                         }
258                     }
259                 }
260             }
261
262             Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
263             if (instances != null) {
264                 if (instances.length > 0) {
265                     for (Object instance : instances) {
266                         INeutronPortAware service = (INeutronPortAware) instance;
267                         int status = service.canCreatePort(singleton);
268                         if (status < 200 || status > 299) {
269                             return Response.status(status).build();
270                         }
271                     }
272                 } else {
273                     throw new ServiceUnavailableException("No providers registered.  Please try again later");
274                 }
275             } else {
276                 throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
277             }
278
279             // add the port to the cache
280             portInterface.addPort(singleton);
281             if (instances != null) {
282                 for (Object instance : instances) {
283                     INeutronPortAware service = (INeutronPortAware) instance;
284                     service.neutronPortCreated(singleton);
285                 }
286             }
287         } else {
288             List<NeutronPort> bulk = input.getBulk();
289             Iterator<NeutronPort> i = bulk.iterator();
290             HashMap<String, NeutronPort> testMap = new HashMap<String, NeutronPort>();
291             Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
292             while (i.hasNext()) {
293                 NeutronPort test = i.next();
294
295                 /*
296                  * the port must be part of an existing network, must not already exist,
297                  * have a valid MAC and the MAC not be in use.  Further the bulk request
298                  * can't already contain a new port with the same UUID
299                  */
300                 if (portInterface.portExists(test.getID())) {
301                     throw new BadRequestException("port UUID already exists");
302                 }
303                 if (testMap.containsKey(test.getID())) {
304                     throw new BadRequestException("port UUID already exists");
305                 }
306                 for (NeutronPort check : testMap.values()) {
307                     if (test.getMacAddress().equalsIgnoreCase(check.getMacAddress())) {
308                         throw new ResourceConflictException("MAC address already allocated");
309                     }
310                     for (Neutron_IPs test_fixedIP : test.getFixedIPs()) {
311                         for (Neutron_IPs check_fixedIP : check.getFixedIPs()) {
312                             if (test_fixedIP.getSubnetUUID().equals(check_fixedIP.getSubnetUUID())) {
313                                 if (test_fixedIP.getIpAddress().equals(check_fixedIP.getIpAddress())) {
314                                     throw new ResourceConflictException("IP address already allocated");
315                                 }
316                             }
317                         }
318                     }
319                 }
320                 testMap.put(test.getID(), test);
321                 if (!networkInterface.networkExists(test.getNetworkUUID())) {
322                     throw new ResourceNotFoundException("network UUID does not exist.");
323                 }
324                 if (!test.getMacAddress().matches(mac_regex)) {
325                     throw new BadRequestException("MAC address not properly formatted");
326                 }
327                 if (portInterface.macInUse(test.getMacAddress())) {
328                     throw new ResourceConflictException("MAC address in use");
329                 }
330
331                 /*
332                  * if fixed IPs are specified, each one has to have an existing subnet ID
333                  * that is in the same scoping network as the port.  In addition, if an IP
334                  * address is specified it has to be a valid address for the subnet and not
335                  * already in use (or be the gateway IP address of the subnet)
336                  */
337                 List<Neutron_IPs> fixedIPs = test.getFixedIPs();
338                 if (fixedIPs != null && fixedIPs.size() > 0) {
339                     Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
340                     while (fixedIPIterator.hasNext()) {
341                         Neutron_IPs ip = fixedIPIterator.next();
342                         if (ip.getSubnetUUID() == null) {
343                             throw new BadRequestException("subnet UUID must be specified");
344                         }
345                         if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
346                             throw new BadRequestException("subnet UUID doesn't exists");
347                         }
348                         NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
349                         if (!test.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
350                             throw new BadRequestException("network UUID must match that of subnet");
351                         }
352                         if (ip.getIpAddress() != null) {
353                             if (!subnet.isValidIP(ip.getIpAddress())) {
354                                 throw new BadRequestException("ip address not valid");
355                             }
356                             //TODO: need to add consideration for a fixed IP being assigned the same address as a allocated IP in the
357                             //same bulk create
358                             if (subnet.isIPInUse(ip.getIpAddress())) {
359                                 throw new ResourceConflictException("IP address in use");
360                             }
361                         }
362                     }
363                 }
364                 if (instances != null) {
365                     if (instances.length > 0) {
366                         for (Object instance : instances) {
367                             INeutronPortAware service = (INeutronPortAware) instance;
368                             int status = service.canCreatePort(test);
369                             if (status < 200 || status > 299) {
370                                 return Response.status(status).build();
371                             }
372                         }
373                     } else {
374                         throw new ServiceUnavailableException("No providers registered.  Please try again later");
375                     }
376                 } else {
377                     throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
378                 }
379             }
380
381             //once everything has passed, then we can add to the cache
382             i = bulk.iterator();
383             while (i.hasNext()) {
384                 NeutronPort test = i.next();
385                 portInterface.addPort(test);
386                 if (instances != null) {
387                     for (Object instance : instances) {
388                         INeutronPortAware service = (INeutronPortAware) instance;
389                         service.neutronPortCreated(test);
390                     }
391                 }
392             }
393         }
394         return Response.status(201).entity(input).build();
395     }
396
397     /**
398      * Updates a Port */
399
400     @Path("{portUUID}")
401     @PUT
402     @Produces({ MediaType.APPLICATION_JSON })
403     @Consumes({ MediaType.APPLICATION_JSON })
404     //@TypeHint(OpenStackPorts.class)
405     @StatusCodes({
406         @ResponseCode(code = 200, condition = "Operation successful"),
407         @ResponseCode(code = 400, condition = "Bad Request"),
408         @ResponseCode(code = 401, condition = "Unauthorized"),
409         @ResponseCode(code = 403, condition = "Forbidden"),
410         @ResponseCode(code = 404, condition = "Not Found"),
411         @ResponseCode(code = 409, condition = "Conflict"),
412         @ResponseCode(code = 501, condition = "Not Implemented"),
413         @ResponseCode(code = 503, condition = "No providers available") })
414     public Response updatePort(
415             @PathParam("portUUID") String portUUID,
416             NeutronPortRequest input
417             ) {
418         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
419         if (portInterface == null) {
420             throw new ServiceUnavailableException("Port CRUD Interface "
421                     + RestMessages.SERVICEUNAVAILABLE.toString());
422         }
423         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
424         if (subnetInterface == null) {
425             throw new ServiceUnavailableException("Subnet CRUD Interface "
426                     + RestMessages.SERVICEUNAVAILABLE.toString());
427         }
428
429         // port has to exist and only a single delta is supported
430         if (!portInterface.portExists(portUUID)) {
431             throw new ResourceNotFoundException("port UUID does not exist.");
432         }
433         NeutronPort target = portInterface.getPort(portUUID);
434         if (!input.isSingleton()) {
435             throw new BadRequestException("only singleton edit suported");
436         }
437         NeutronPort singleton = input.getSingleton();
438         NeutronPort original = portInterface.getPort(portUUID);
439
440         // deltas restricted by Neutron
441         if (singleton.getID() != null || singleton.getTenantID() != null ||
442                 singleton.getStatus() != null) {
443             throw new BadRequestException("attribute change blocked by Neutron");
444         }
445
446         Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
447         if (instances != null) {
448             if (instances.length > 0) {
449                 for (Object instance : instances) {
450                     INeutronPortAware service = (INeutronPortAware) instance;
451                     int status = service.canUpdatePort(singleton, original);
452                     if (status < 200 || status > 299) {
453                         return Response.status(status).build();
454                     }
455                 }
456             } else {
457                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
458             }
459         } else {
460             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
461         }
462
463         // Verify the new fixed ips are valid
464         List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
465         if (fixedIPs != null && fixedIPs.size() > 0) {
466             Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
467             while (fixedIPIterator.hasNext()) {
468                 Neutron_IPs ip = fixedIPIterator.next();
469                 if (ip.getSubnetUUID() == null) {
470                     throw new BadRequestException("subnet UUID must be specified");
471                 }
472                 if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
473                     throw new BadRequestException("subnet UUID doesn't exist.");
474                 }
475                 NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
476                 if (!target.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
477                     throw new BadRequestException("network UUID must match that of subnet");
478                 }
479                 if (ip.getIpAddress() != null) {
480                     if (!subnet.isValidIP(ip.getIpAddress())) {
481                         throw new BadRequestException("invalid IP address");
482                     }
483                     if (subnet.isIPInUse(ip.getIpAddress())) {
484                         throw new ResourceConflictException("IP address in use");
485                     }
486                 }
487             }
488         }
489
490         //        TODO: Support change of security groups
491         // update the port and return the modified object
492         portInterface.updatePort(portUUID, singleton);
493         NeutronPort updatedPort = portInterface.getPort(portUUID);
494         if (instances != null) {
495             for (Object instance : instances) {
496                 INeutronPortAware service = (INeutronPortAware) instance;
497                 service.neutronPortUpdated(updatedPort);
498             }
499         }
500         return Response.status(200).entity(
501                 new NeutronPortRequest(updatedPort)).build();
502
503     }
504
505     /**
506      * Deletes a Port */
507
508     @Path("{portUUID}")
509     @DELETE
510     @StatusCodes({
511         @ResponseCode(code = 204, condition = "No Content"),
512         @ResponseCode(code = 401, condition = "Unauthorized"),
513         @ResponseCode(code = 403, condition = "Forbidden"),
514         @ResponseCode(code = 404, condition = "Not Found"),
515         @ResponseCode(code = 501, condition = "Not Implemented"),
516         @ResponseCode(code = 503, condition = "No providers available") })
517     public Response deletePort(
518             @PathParam("portUUID") String portUUID) {
519         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
520         if (portInterface == null) {
521             throw new ServiceUnavailableException("Port CRUD Interface "
522                     + RestMessages.SERVICEUNAVAILABLE.toString());
523         }
524
525         // port has to exist and not be owned by anyone.  then it can be removed from the cache
526         if (!portInterface.portExists(portUUID)) {
527             throw new ResourceNotFoundException("port UUID does not exist.");
528         }
529         NeutronPort port = portInterface.getPort(portUUID);
530         if (port.getDeviceID() != null ||
531                 port.getDeviceOwner() != null) {
532             Response.status(403).build();
533         }
534         NeutronPort singleton = portInterface.getPort(portUUID);
535         Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
536         if (instances != null) {
537             if (instances.length > 0) {
538                 for (Object instance : instances) {
539                     INeutronPortAware service = (INeutronPortAware) instance;
540                     int status = service.canDeletePort(singleton);
541                     if (status < 200 || status > 299) {
542                         return Response.status(status).build();
543                     }
544                 }
545             } else {
546                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
547             }
548         } else {
549             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
550         }
551         portInterface.removePort(portUUID);
552         if (instances != null) {
553             for (Object instance : instances) {
554                 INeutronPortAware service = (INeutronPortAware) instance;
555                 service.neutronPortDeleted(singleton);
556             }
557         }
558         return Response.status(204).build();
559     }
560 }