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