Added LeaderElectionScenariosTest class
[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                 for (Object instance : instances) {
223                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
224                     int status = service.canCreateSubnet(singleton);
225                     if (status < 200 || status > 299) {
226                         return Response.status(status).build();
227                     }
228                 }
229             }
230             subnetInterface.addSubnet(singleton);
231             if (instances != null) {
232                 for (Object instance : instances) {
233                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
234                     service.neutronSubnetCreated(singleton);
235                 }
236             }
237         } else {
238             List<NeutronSubnet> bulk = input.getBulk();
239             Iterator<NeutronSubnet> i = bulk.iterator();
240             HashMap<String, NeutronSubnet> testMap = new HashMap<String, NeutronSubnet>();
241             Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
242             while (i.hasNext()) {
243                 NeutronSubnet test = i.next();
244
245                 /*
246                  *  Verify that the subnet doesn't already exist (Issue: is a deeper check necessary?)
247                  *  the specified network exists, the subnet has a valid network address,
248                  *  and that the gateway IP doesn't overlap with the allocation pools,
249                  *  and that the bulk request doesn't already contain a subnet with this id
250                  */
251
252                 if (!test.initDefaults()) {
253                     throw new InternalServerErrorException("subnet object could not be initialized properly");
254                 }
255                 if (subnetInterface.subnetExists(test.getID())) {
256                     throw new BadRequestException("subnet UUID already exists");
257                 }
258                 if (testMap.containsKey(test.getID())) {
259                     throw new BadRequestException("subnet UUID already exists");
260                 }
261                 testMap.put(test.getID(), test);
262                 if (!networkInterface.networkExists(test.getNetworkUUID())) {
263                     throw new ResourceNotFoundException("network UUID does not exist.");
264                 }
265                 if (!test.isValidCIDR()) {
266                     throw new BadRequestException("Invalid CIDR");
267                 }
268                 if (test.gatewayIP_Pool_overlap()) {
269                     throw new ResourceConflictException("IP pool overlaps with gateway");
270                 }
271                 if (instances != null) {
272                     for (Object instance : instances) {
273                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
274                         int status = service.canCreateSubnet(test);
275                         if (status < 200 || status > 299) {
276                             return Response.status(status).build();
277                         }
278                     }
279                 }
280             }
281
282             /*
283              * now, each element of the bulk request can be added to the cache
284              */
285             i = bulk.iterator();
286             while (i.hasNext()) {
287                 NeutronSubnet test = i.next();
288                 subnetInterface.addSubnet(test);
289                 if (instances != null) {
290                     for (Object instance : instances) {
291                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
292                         service.neutronSubnetCreated(test);
293                     }
294                 }
295             }
296         }
297         return Response.status(201).entity(input).build();
298     }
299
300     /**
301      * Updates a Subnet */
302
303     @Path("{subnetUUID}")
304     @PUT
305     @Produces({ MediaType.APPLICATION_JSON })
306     @Consumes({ MediaType.APPLICATION_JSON })
307     //@TypeHint(OpenStackSubnets.class)
308     @StatusCodes({
309             @ResponseCode(code = 200, condition = "Operation successful"),
310             @ResponseCode(code = 400, condition = "Bad Request"),
311             @ResponseCode(code = 401, condition = "Unauthorized"),
312             @ResponseCode(code = 403, condition = "Forbidden"),
313             @ResponseCode(code = 404, condition = "Not Found"),
314             @ResponseCode(code = 501, condition = "Not Implemented") })
315     public Response updateSubnet(
316             @PathParam("subnetUUID") String subnetUUID, final NeutronSubnetRequest input
317             ) {
318         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
319         if (subnetInterface == null) {
320             throw new ServiceUnavailableException("Subnet CRUD Interface "
321                     + RestMessages.SERVICEUNAVAILABLE.toString());
322         }
323
324         /*
325          * verify the subnet exists and there is only one delta provided
326          */
327         if (!subnetInterface.subnetExists(subnetUUID)) {
328             throw new ResourceNotFoundException("subnet UUID does not exist.");
329         }
330         if (!input.isSingleton()) {
331             throw new BadRequestException("Only singleton edit supported");
332         }
333         NeutronSubnet delta = input.getSingleton();
334         NeutronSubnet original = subnetInterface.getSubnet(subnetUUID);
335
336         /*
337          * updates restricted by Neutron
338          */
339         if (delta.getID() != null || delta.getTenantID() != null ||
340                 delta.getIpVersion() != null || delta.getCidr() != null ||
341                 delta.getAllocationPools() != null) {
342             throw new BadRequestException("Attribute edit blocked by Neutron");
343         }
344
345         Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
346         if (instances != null) {
347             for (Object instance : instances) {
348                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
349                 int status = service.canUpdateSubnet(delta, original);
350                 if (status < 200 || status > 299) {
351                     return Response.status(status).build();
352                 }
353             }
354         }
355
356         /*
357          * update the object and return it
358          */
359         subnetInterface.updateSubnet(subnetUUID, delta);
360         NeutronSubnet updatedSubnet = subnetInterface.getSubnet(subnetUUID);
361         if (instances != null) {
362             for (Object instance : instances) {
363                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
364                 service.neutronSubnetUpdated(updatedSubnet);
365             }
366         }
367         return Response.status(200).entity(
368                 new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
369     }
370
371     /**
372      * Deletes a Subnet */
373
374     @Path("{subnetUUID}")
375     @DELETE
376     @StatusCodes({
377             @ResponseCode(code = 204, condition = "No Content"),
378             @ResponseCode(code = 401, condition = "Unauthorized"),
379             @ResponseCode(code = 404, condition = "Not Found"),
380             @ResponseCode(code = 409, condition = "Conflict"),
381             @ResponseCode(code = 501, condition = "Not Implemented") })
382     public Response deleteSubnet(
383             @PathParam("subnetUUID") String subnetUUID) {
384         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
385         if (subnetInterface == null) {
386             throw new ServiceUnavailableException("Network CRUD Interface "
387                     + RestMessages.SERVICEUNAVAILABLE.toString());
388         }
389
390         /*
391          * verify the subnet exists and it isn't currently in use
392          */
393         if (!subnetInterface.subnetExists(subnetUUID)) {
394             throw new ResourceNotFoundException("subnet UUID does not exist.");
395         }
396         if (subnetInterface.subnetInUse(subnetUUID)) {
397             return Response.status(409).build();
398         }
399         NeutronSubnet singleton = subnetInterface.getSubnet(subnetUUID);
400         Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
401         if (instances != null) {
402             for (Object instance : instances) {
403                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
404                 int status = service.canDeleteSubnet(singleton);
405                 if (status < 200 || status > 299) {
406                     return Response.status(status).build();
407                 }
408             }
409         }
410
411         /*
412          * remove it and return 204 status
413          */
414         subnetInterface.removeSubnet(subnetUUID);
415         if (instances != null) {
416             for (Object instance : instances) {
417                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
418                 service.neutronSubnetDeleted(singleton);
419             }
420         }
421         return Response.status(204).build();
422     }
423 }