Merge "Fixed potential class pool override in integration tests."
[controller.git] / opendaylight / northbound / networkconfiguration / neutron / src / main / java / org / opendaylight / controller / networkconfig / neutron / northbound / 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.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             @QueryParam("ipv6_address_mode") String queryIpV6AddressMode,
91             @QueryParam("ipv6_ra_mode") String queryIpV6RaMode,
92             // pagination
93             @QueryParam("limit") String limit,
94             @QueryParam("marker") String marker,
95             @QueryParam("page_reverse") String 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         //TODO: apply pagination to results
126         return Response.status(200).entity(
127                 new NeutronSubnetRequest(ans)).build();
128     }
129
130     /**
131      * Returns a specific Subnet */
132
133     @Path("{subnetUUID}")
134     @GET
135     @Produces({ MediaType.APPLICATION_JSON })
136     //@TypeHint(OpenStackSubnets.class)
137     @StatusCodes({
138             @ResponseCode(code = 200, condition = "Operation successful"),
139             @ResponseCode(code = 401, condition = "Unauthorized"),
140             @ResponseCode(code = 404, condition = "Not Found"),
141             @ResponseCode(code = 501, condition = "Not Implemented") })
142     public Response showSubnet(
143             @PathParam("subnetUUID") String subnetUUID,
144             // return fields
145             @QueryParam("fields") List<String> fields) {
146         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
147         if (subnetInterface == null) {
148             throw new ServiceUnavailableException("Subnet CRUD Interface "
149                     + RestMessages.SERVICEUNAVAILABLE.toString());
150         }
151         if (!subnetInterface.subnetExists(subnetUUID)) {
152             throw new ResourceNotFoundException("subnet UUID does not exist.");
153         }
154         if (fields.size() > 0) {
155             NeutronSubnet ans = subnetInterface.getSubnet(subnetUUID);
156             return Response.status(200).entity(
157                     new NeutronSubnetRequest(extractFields(ans, fields))).build();
158         } else {
159             return Response.status(200).entity(
160                     new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
161         }
162     }
163
164     /**
165      * Creates new Subnets */
166
167     @POST
168     @Produces({ MediaType.APPLICATION_JSON })
169     @Consumes({ MediaType.APPLICATION_JSON })
170     //@TypeHint(OpenStackSubnets.class)
171     @StatusCodes({
172             @ResponseCode(code = 201, condition = "Created"),
173             @ResponseCode(code = 400, condition = "Bad Request"),
174             @ResponseCode(code = 401, condition = "Unauthorized"),
175             @ResponseCode(code = 403, condition = "Forbidden"),
176             @ResponseCode(code = 404, condition = "Not Found"),
177             @ResponseCode(code = 409, condition = "Conflict"),
178             @ResponseCode(code = 501, condition = "Not Implemented") })
179     public Response createSubnets(final NeutronSubnetRequest input) {
180         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
181         if (subnetInterface == null) {
182             throw new ServiceUnavailableException("Subnet CRUD Interface "
183                     + RestMessages.SERVICEUNAVAILABLE.toString());
184         }
185         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
186         if (networkInterface == null) {
187             throw new ServiceUnavailableException("Network CRUD Interface "
188                     + RestMessages.SERVICEUNAVAILABLE.toString());
189         }
190         if (input.isSingleton()) {
191             NeutronSubnet singleton = input.getSingleton();
192
193             /*
194              *  Verify that the subnet doesn't already exist (Issue: is a deeper check necessary?)
195              *  the specified network exists, the subnet has a valid network address,
196              *  and that the gateway IP doesn't overlap with the allocation pools
197              *  *then* add the subnet to the cache
198              */
199             if (subnetInterface.subnetExists(singleton.getID())) {
200                 throw new BadRequestException("subnet UUID already exists");
201             }
202             if (!networkInterface.networkExists(singleton.getNetworkUUID())) {
203                 throw new ResourceNotFoundException("network UUID does not exist.");
204             }
205             if (!singleton.isValidCIDR()) {
206                 throw new BadRequestException("invaild CIDR");
207             }
208             if (!singleton.initDefaults()) {
209                 throw new InternalServerErrorException("subnet object could not be initialized properly");
210             }
211             if (singleton.gatewayIP_Pool_overlap()) {
212                 throw new ResourceConflictException("IP pool overlaps with gateway");
213             }
214             Object[] instances = ServiceHelper.getGlobalInstances(INeutronSubnetAware.class, this, null);
215             if (instances != null) {
216                 for (Object instance : instances) {
217                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
218                     int status = service.canCreateSubnet(singleton);
219                     if (status < 200 || status > 299) {
220                         return Response.status(status).build();
221                     }
222                 }
223             }
224             subnetInterface.addSubnet(singleton);
225             if (instances != null) {
226                 for (Object instance : instances) {
227                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
228                     service.neutronSubnetCreated(singleton);
229                 }
230             }
231         } else {
232             List<NeutronSubnet> bulk = input.getBulk();
233             Iterator<NeutronSubnet> i = bulk.iterator();
234             HashMap<String, NeutronSubnet> testMap = new HashMap<String, NeutronSubnet>();
235             Object[] instances = ServiceHelper.getGlobalInstances(INeutronSubnetAware.class, this, null);
236             while (i.hasNext()) {
237                 NeutronSubnet test = i.next();
238
239                 /*
240                  *  Verify that the subnet doesn't already exist (Issue: is a deeper check necessary?)
241                  *  the specified network exists, the subnet has a valid network address,
242                  *  and that the gateway IP doesn't overlap with the allocation pools,
243                  *  and that the bulk request doesn't already contain a subnet with this id
244                  */
245
246                 if (!test.initDefaults()) {
247                     throw new InternalServerErrorException("subnet object could not be initialized properly");
248                 }
249                 if (subnetInterface.subnetExists(test.getID())) {
250                     throw new BadRequestException("subnet UUID already exists");
251                 }
252                 if (testMap.containsKey(test.getID())) {
253                     throw new BadRequestException("subnet UUID already exists");
254                 }
255                 testMap.put(test.getID(), test);
256                 if (!networkInterface.networkExists(test.getNetworkUUID())) {
257                     throw new ResourceNotFoundException("network UUID does not exist.");
258                 }
259                 if (!test.isValidCIDR()) {
260                     throw new BadRequestException("Invalid CIDR");
261                 }
262                 if (test.gatewayIP_Pool_overlap()) {
263                     throw new ResourceConflictException("IP pool overlaps with gateway");
264                 }
265                 if (instances != null) {
266                     for (Object instance : instances) {
267                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
268                         int status = service.canCreateSubnet(test);
269                         if (status < 200 || status > 299) {
270                             return Response.status(status).build();
271                         }
272                     }
273                 }
274             }
275
276             /*
277              * now, each element of the bulk request can be added to the cache
278              */
279             i = bulk.iterator();
280             while (i.hasNext()) {
281                 NeutronSubnet test = i.next();
282                 subnetInterface.addSubnet(test);
283                 if (instances != null) {
284                     for (Object instance : instances) {
285                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
286                         service.neutronSubnetCreated(test);
287                     }
288                 }
289             }
290         }
291         return Response.status(201).entity(input).build();
292     }
293
294     /**
295      * Updates a Subnet */
296
297     @Path("{subnetUUID}")
298     @PUT
299     @Produces({ MediaType.APPLICATION_JSON })
300     @Consumes({ MediaType.APPLICATION_JSON })
301     //@TypeHint(OpenStackSubnets.class)
302     @StatusCodes({
303             @ResponseCode(code = 200, condition = "Operation successful"),
304             @ResponseCode(code = 400, condition = "Bad Request"),
305             @ResponseCode(code = 401, condition = "Unauthorized"),
306             @ResponseCode(code = 403, condition = "Forbidden"),
307             @ResponseCode(code = 404, condition = "Not Found"),
308             @ResponseCode(code = 501, condition = "Not Implemented") })
309     public Response updateSubnet(
310             @PathParam("subnetUUID") String subnetUUID, final NeutronSubnetRequest input
311             ) {
312         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
313         if (subnetInterface == null) {
314             throw new ServiceUnavailableException("Subnet CRUD Interface "
315                     + RestMessages.SERVICEUNAVAILABLE.toString());
316         }
317
318         /*
319          * verify the subnet exists and there is only one delta provided
320          */
321         if (!subnetInterface.subnetExists(subnetUUID)) {
322             throw new ResourceNotFoundException("subnet UUID does not exist.");
323         }
324         if (!input.isSingleton()) {
325             throw new BadRequestException("Only singleton edit supported");
326         }
327         NeutronSubnet delta = input.getSingleton();
328         NeutronSubnet original = subnetInterface.getSubnet(subnetUUID);
329
330         /*
331          * updates restricted by Neutron
332          */
333         if (delta.getID() != null || delta.getTenantID() != null ||
334                 delta.getIpVersion() != null || delta.getCidr() != null ||
335                 delta.getAllocationPools() != null) {
336             throw new BadRequestException("Attribute edit blocked by Neutron");
337         }
338
339         Object[] instances = ServiceHelper.getGlobalInstances(INeutronSubnetAware.class, this, null);
340         if (instances != null) {
341             for (Object instance : instances) {
342                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
343                 int status = service.canUpdateSubnet(delta, original);
344                 if (status < 200 || status > 299) {
345                     return Response.status(status).build();
346                 }
347             }
348         }
349
350         /*
351          * update the object and return it
352          */
353         subnetInterface.updateSubnet(subnetUUID, delta);
354         NeutronSubnet updatedSubnet = subnetInterface.getSubnet(subnetUUID);
355         if (instances != null) {
356             for (Object instance : instances) {
357                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
358                 service.neutronSubnetUpdated(updatedSubnet);
359             }
360         }
361         return Response.status(200).entity(
362                 new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
363     }
364
365     /**
366      * Deletes a Subnet */
367
368     @Path("{subnetUUID}")
369     @DELETE
370     @StatusCodes({
371             @ResponseCode(code = 204, condition = "No Content"),
372             @ResponseCode(code = 401, condition = "Unauthorized"),
373             @ResponseCode(code = 404, condition = "Not Found"),
374             @ResponseCode(code = 409, condition = "Conflict"),
375             @ResponseCode(code = 501, condition = "Not Implemented") })
376     public Response deleteSubnet(
377             @PathParam("subnetUUID") String subnetUUID) {
378         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
379         if (subnetInterface == null) {
380             throw new ServiceUnavailableException("Network CRUD Interface "
381                     + RestMessages.SERVICEUNAVAILABLE.toString());
382         }
383
384         /*
385          * verify the subnet exists and it isn't currently in use
386          */
387         if (!subnetInterface.subnetExists(subnetUUID)) {
388             throw new ResourceNotFoundException("subnet UUID does not exist.");
389         }
390         if (subnetInterface.subnetInUse(subnetUUID)) {
391             return Response.status(409).build();
392         }
393         NeutronSubnet singleton = subnetInterface.getSubnet(subnetUUID);
394         Object[] instances = ServiceHelper.getGlobalInstances(INeutronSubnetAware.class, this, null);
395         if (instances != null) {
396             for (Object instance : instances) {
397                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
398                 int status = service.canDeleteSubnet(singleton);
399                 if (status < 200 || status > 299) {
400                     return Response.status(status).build();
401                 }
402             }
403         }
404
405         /*
406          * remove it and return 204 status
407          */
408         subnetInterface.removeSubnet(subnetUUID);
409         if (instances != null) {
410             for (Object instance : instances) {
411                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
412                 service.neutronSubnetDeleted(singleton);
413             }
414         }
415         return Response.status(204).build();
416     }
417 }