Code cleanup: use collection interfaces in declarations
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / NeutronSubnetsNorthbound.java
1 /*
2  * Copyright IBM Corporation and others, 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 java.net.HttpURLConnection;
12
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Map;
18
19 import javax.ws.rs.Consumes;
20 import javax.ws.rs.DELETE;
21 import javax.ws.rs.DefaultValue;
22 import javax.ws.rs.GET;
23 import javax.ws.rs.POST;
24 import javax.ws.rs.PUT;
25 import javax.ws.rs.Path;
26 import javax.ws.rs.PathParam;
27 import javax.ws.rs.Produces;
28 import javax.ws.rs.QueryParam;
29 import javax.ws.rs.core.Context;
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.UriInfo;
33
34 import org.codehaus.enunciate.jaxrs.ResponseCode;
35 import org.codehaus.enunciate.jaxrs.StatusCodes;
36 import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
37 import org.opendaylight.neutron.spi.INeutronSubnetAware;
38 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
39 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
40 import org.opendaylight.neutron.spi.NeutronSubnet;
41
42 /**
43  * Neutron Northbound REST APIs for Subnets.<br>
44  * This class provides REST APIs for managing neutron Subnets
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("/subnets")
61 public class NeutronSubnetsNorthbound {
62     private static final int HTTP_OK_BOTTOM = 200;
63     private static final int HTTP_OK_TOP = 299;
64     private static final String INTERFACE_NAME = "Subnet CRUD Interface";
65     private static final String UUID_NO_EXIST = "Subnet UUID does not exist.";
66     private static final String UUID_EXISTS = "Subnet UUID already exists.";
67     private static final String NO_PROVIDERS = "No providers registered.  Please try again later";
68     private static final String NO_PROVIDER_LIST = "Couldn't get providers list.  Please try again later";
69
70     private NeutronSubnet extractFields(NeutronSubnet o, List<String> fields) {
71         return o.extractFields(fields);
72     }
73
74     private NeutronCRUDInterfaces getNeutronInterfaces(boolean needNetwork) {
75         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronSubnetCRUD(this);
76         if (answer.getSubnetInterface() == null) {
77             throw new ServiceUnavailableException(INTERFACE_NAME
78                 + RestMessages.SERVICEUNAVAILABLE.toString());
79         }
80         if (needNetwork) {
81             answer = answer.fetchINeutronNetworkCRUD(this);
82             if (answer.getNetworkInterface() == null) {
83                 throw new ServiceUnavailableException("Network CRUD Interface "
84                     + RestMessages.SERVICEUNAVAILABLE.toString());
85             }
86         }
87         return answer;
88     }
89
90     @Context
91     UriInfo uriInfo;
92
93     /**
94      * Returns a list of all Subnets */
95     @GET
96     @Produces({ MediaType.APPLICATION_JSON })
97     //@TypeHint(OpenStackSubnets.class)
98     @StatusCodes({
99             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
100             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
101             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
102             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
103     public Response listSubnets(
104             // return fields
105             @QueryParam("fields") List<String> fields,
106             // note: openstack isn't clear about filtering on lists, so we aren't handling them
107             @QueryParam("id") String queryID,
108             @QueryParam("network_id") String queryNetworkID,
109             @QueryParam("name") String queryName,
110             @QueryParam("ip_version") String queryIPVersion,
111             @QueryParam("cidr") String queryCIDR,
112             @QueryParam("gateway_ip") String queryGatewayIP,
113             @QueryParam("enable_dhcp") String queryEnableDHCP,
114             @QueryParam("tenant_id") String queryTenantID,
115             @QueryParam("ipv6_address_mode") String queryIpV6AddressMode,
116             @QueryParam("ipv6_ra_mode") String queryIpV6RaMode,
117             // linkTitle
118             @QueryParam("limit") Integer limit,
119             @QueryParam("marker") String marker,
120             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
121             // sorting not supported
122             ) {
123         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
124         List<NeutronSubnet> allNetworks = subnetInterface.getAllSubnets();
125         List<NeutronSubnet> ans = new ArrayList<NeutronSubnet>();
126         Iterator<NeutronSubnet> i = allNetworks.iterator();
127         while (i.hasNext()) {
128             NeutronSubnet oSS = i.next();
129             if ((queryID == null || queryID.equals(oSS.getID())) &&
130                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
131                     (queryName == null || queryName.equals(oSS.getName())) &&
132                     (queryIPVersion == null || queryIPVersion.equals(oSS.getIpVersion())) &&
133                     (queryCIDR == null || queryCIDR.equals(oSS.getCidr())) &&
134                     (queryGatewayIP == null || queryGatewayIP.equals(oSS.getGatewayIP())) &&
135                     (queryEnableDHCP == null || queryEnableDHCP.equals(oSS.getEnableDHCP())) &&
136                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID())) &&
137                     (queryIpV6AddressMode == null || queryIpV6AddressMode.equals(oSS.getIpV6AddressMode())) &&
138                     (queryIpV6RaMode == null || queryIpV6RaMode.equals(oSS.getIpV6RaMode()))){
139                 if (fields.size() > 0) {
140                     ans.add(extractFields(oSS,fields));
141                 } else {
142                     ans.add(oSS);
143                 }
144             }
145         }
146
147         if (limit != null && ans.size() > 1) {
148             // Return a paginated request
149             NeutronSubnetRequest request = (NeutronSubnetRequest) PaginatedRequestFactory.createRequest(limit,
150                     marker, pageReverse, uriInfo, ans, NeutronSubnet.class);
151             return Response.status(HttpURLConnection.HTTP_OK).entity(request).build();
152         }
153
154         return Response.status(HttpURLConnection.HTTP_OK).entity(
155                 new NeutronSubnetRequest(ans)).build();
156     }
157
158     /**
159      * Returns a specific Subnet */
160
161     @Path("{subnetUUID}")
162     @GET
163     @Produces({ MediaType.APPLICATION_JSON })
164     //@TypeHint(OpenStackSubnets.class)
165     @StatusCodes({
166             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
167             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
168             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
169             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
170             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
171     public Response showSubnet(
172             @PathParam("subnetUUID") String subnetUUID,
173             // return fields
174             @QueryParam("fields") List<String> fields) {
175         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
176         if (!subnetInterface.subnetExists(subnetUUID)) {
177             throw new ResourceNotFoundException(UUID_NO_EXIST);
178         }
179         if (fields.size() > 0) {
180             NeutronSubnet ans = subnetInterface.getSubnet(subnetUUID);
181             return Response.status(HttpURLConnection.HTTP_OK).entity(
182                     new NeutronSubnetRequest(extractFields(ans, fields))).build();
183         } else {
184             return Response.status(HttpURLConnection.HTTP_OK).entity(
185                     new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
186         }
187     }
188
189     /**
190      * Creates new Subnets */
191
192     @POST
193     @Produces({ MediaType.APPLICATION_JSON })
194     @Consumes({ MediaType.APPLICATION_JSON })
195     //@TypeHint(OpenStackSubnets.class)
196     @StatusCodes({
197             @ResponseCode(code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
198             @ResponseCode(code = HttpURLConnection.HTTP_BAD_REQUEST, condition = "Bad Request"),
199             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
200             @ResponseCode(code = HttpURLConnection.HTTP_FORBIDDEN, condition = "Forbidden"),
201             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
202             @ResponseCode(code = HttpURLConnection.HTTP_CONFLICT, condition = "Conflict"),
203             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
204             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
205     public Response createSubnets(final NeutronSubnetRequest input) {
206         NeutronCRUDInterfaces interfaces = getNeutronInterfaces(true);
207         INeutronSubnetCRUD subnetInterface = interfaces.getSubnetInterface();
208         INeutronNetworkCRUD networkInterface = interfaces.getNetworkInterface();
209         if (input.isSingleton()) {
210             NeutronSubnet singleton = input.getSingleton();
211
212             /*
213              *  Verify that the subnet doesn't already exist (Issue: is a deeper check necessary?)
214              *  the specified network exists, the subnet has a valid network address,
215              *  and that the gateway IP doesn't overlap with the allocation pools
216              *  *then* add the subnet to the cache
217              */
218             if (subnetInterface.subnetExists(singleton.getID())) {
219                 throw new BadRequestException(UUID_EXISTS);
220             }
221             if (!networkInterface.networkExists(singleton.getNetworkUUID())) {
222                 throw new ResourceNotFoundException("network UUID does not exist.");
223             }
224             if (!singleton.isValidCIDR()) {
225                 throw new BadRequestException("invaild CIDR");
226             }
227             if (!singleton.initDefaults()) {
228                 throw new InternalServerErrorException("subnet object could not be initialized properly");
229             }
230             if (singleton.gatewayIP_Pool_overlap()) {
231                 throw new ResourceConflictException("IP pool overlaps with gateway");
232             }
233             Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
234             if (instances != null) {
235                 if (instances.length > 0) {
236                     for (Object instance : instances) {
237                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
238                         int status = service.canCreateSubnet(singleton);
239                         if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
240                             return Response.status(status).build();
241                         }
242                     }
243                 } else {
244                     throw new ServiceUnavailableException(NO_PROVIDERS);
245                 }
246             } else {
247                 throw new ServiceUnavailableException(NO_PROVIDER_LIST);
248             }
249             subnetInterface.addSubnet(singleton);
250             if (instances != null) {
251                 for (Object instance : instances) {
252                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
253                     service.neutronSubnetCreated(singleton);
254                 }
255             }
256         } else {
257             List<NeutronSubnet> bulk = input.getBulk();
258             Iterator<NeutronSubnet> i = bulk.iterator();
259             Map<String, NeutronSubnet> testMap = new HashMap<String, NeutronSubnet>();
260             Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
261             while (i.hasNext()) {
262                 NeutronSubnet test = i.next();
263
264                 /*
265                  *  Verify that the subnet doesn't already exist (Issue: is a deeper check necessary?)
266                  *  the specified network exists, the subnet has a valid network address,
267                  *  and that the gateway IP doesn't overlap with the allocation pools,
268                  *  and that the bulk request doesn't already contain a subnet with this id
269                  */
270
271                 if (!test.initDefaults()) {
272                     throw new InternalServerErrorException("subnet object could not be initialized properly");
273                 }
274                 if (subnetInterface.subnetExists(test.getID())) {
275                     throw new BadRequestException(UUID_EXISTS);
276                 }
277                 if (testMap.containsKey(test.getID())) {
278                     throw new BadRequestException(UUID_EXISTS);
279                 }
280                 testMap.put(test.getID(), test);
281                 if (!networkInterface.networkExists(test.getNetworkUUID())) {
282                     throw new ResourceNotFoundException("network UUID does not exist.");
283                 }
284                 if (!test.isValidCIDR()) {
285                     throw new BadRequestException("Invalid CIDR");
286                 }
287                 if (test.gatewayIP_Pool_overlap()) {
288                     throw new ResourceConflictException("IP pool overlaps with gateway");
289                 }
290                 if (instances != null) {
291                     if (instances.length > 0) {
292                         for (Object instance : instances) {
293                             INeutronSubnetAware service = (INeutronSubnetAware) instance;
294                             int status = service.canCreateSubnet(test);
295                             if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
296                                 return Response.status(status).build();
297                             }
298                         }
299                     } else {
300                         throw new ServiceUnavailableException(NO_PROVIDERS);
301                     }
302                 } else {
303                     throw new ServiceUnavailableException(NO_PROVIDER_LIST);
304                 }
305             }
306
307             /*
308              * now, each element of the bulk request can be added to the cache
309              */
310             i = bulk.iterator();
311             while (i.hasNext()) {
312                 NeutronSubnet test = i.next();
313                 subnetInterface.addSubnet(test);
314                 if (instances != null) {
315                     for (Object instance : instances) {
316                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
317                         service.neutronSubnetCreated(test);
318                     }
319                 }
320             }
321         }
322         return Response.status(HttpURLConnection.HTTP_CREATED).entity(input).build();
323     }
324
325     /**
326      * Updates a Subnet */
327
328     @Path("{subnetUUID}")
329     @PUT
330     @Produces({ MediaType.APPLICATION_JSON })
331     @Consumes({ MediaType.APPLICATION_JSON })
332     //@TypeHint(OpenStackSubnets.class)
333     @StatusCodes({
334             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
335             @ResponseCode(code = HttpURLConnection.HTTP_BAD_REQUEST, condition = "Bad Request"),
336             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
337             @ResponseCode(code = HttpURLConnection.HTTP_FORBIDDEN, condition = "Forbidden"),
338             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
339             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
340             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
341     public Response updateSubnet(
342             @PathParam("subnetUUID") String subnetUUID, final NeutronSubnetRequest input
343             ) {
344         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
345
346         /*
347          * verify the subnet exists and there is only one delta provided
348          */
349         if (!subnetInterface.subnetExists(subnetUUID)) {
350             throw new ResourceNotFoundException(UUID_NO_EXIST);
351         }
352         if (!input.isSingleton()) {
353             throw new BadRequestException("Only singleton edit supported");
354         }
355         NeutronSubnet delta = input.getSingleton();
356         NeutronSubnet original = subnetInterface.getSubnet(subnetUUID);
357
358         /*
359          * updates restricted by Neutron
360          */
361         if (delta.getID() != null || delta.getTenantID() != null ||
362                 delta.getIpVersion() != null || delta.getCidr() != null ||
363                 delta.getAllocationPools() != null) {
364             throw new BadRequestException("Attribute edit blocked by Neutron");
365         }
366
367         Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
368         if (instances != null) {
369             if (instances.length > 0) {
370                 for (Object instance : instances) {
371                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
372                     int status = service.canUpdateSubnet(delta, original);
373                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
374                         return Response.status(status).build();
375                     }
376                 }
377             } else {
378                 throw new ServiceUnavailableException(NO_PROVIDERS);
379             }
380         } else {
381             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
382         }
383
384         /*
385          * update the object and return it
386          */
387         subnetInterface.updateSubnet(subnetUUID, delta);
388         NeutronSubnet updatedSubnet = subnetInterface.getSubnet(subnetUUID);
389         if (instances != null) {
390             for (Object instance : instances) {
391                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
392                 service.neutronSubnetUpdated(updatedSubnet);
393             }
394         }
395         return Response.status(HttpURLConnection.HTTP_OK).entity(
396                 new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
397     }
398
399     /**
400      * Deletes a Subnet */
401
402     @Path("{subnetUUID}")
403     @DELETE
404     @StatusCodes({
405             @ResponseCode(code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
406             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
407             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
408             @ResponseCode(code = HttpURLConnection.HTTP_CONFLICT, condition = "Conflict"),
409             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
410             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
411     public Response deleteSubnet(
412             @PathParam("subnetUUID") String subnetUUID) {
413         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
414
415         /*
416          * verify the subnet exists and it isn't currently in use
417          */
418         if (!subnetInterface.subnetExists(subnetUUID)) {
419             throw new ResourceNotFoundException(UUID_NO_EXIST);
420         }
421         if (subnetInterface.subnetInUse(subnetUUID)) {
422             return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
423         }
424         NeutronSubnet singleton = subnetInterface.getSubnet(subnetUUID);
425         Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
426         if (instances != null) {
427             if (instances.length > 0) {
428                 for (Object instance : instances) {
429                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
430                     int status = service.canDeleteSubnet(singleton);
431                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
432                         return Response.status(status).build();
433                     }
434                 }
435             } else {
436                 throw new ServiceUnavailableException(NO_PROVIDERS);
437             }
438         } else {
439             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
440         }
441
442         /*
443          * remove it and return 204 status
444          */
445         subnetInterface.removeSubnet(subnetUUID);
446         if (instances != null) {
447             for (Object instance : instances) {
448                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
449                 service.neutronSubnetDeleted(singleton);
450             }
451         }
452         return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
453     }
454 }