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