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