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