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