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