Make NN more transparent, part I
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / 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.neutron.northbound.api;
10
11 import java.net.HttpURLConnection;
12
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Map;
18
19 import javax.ws.rs.Consumes;
20 import javax.ws.rs.DELETE;
21 import javax.ws.rs.DefaultValue;
22 import javax.ws.rs.GET;
23 import javax.ws.rs.POST;
24 import javax.ws.rs.PUT;
25 import javax.ws.rs.Path;
26 import javax.ws.rs.PathParam;
27 import javax.ws.rs.Produces;
28 import javax.ws.rs.QueryParam;
29 import javax.ws.rs.core.Context;
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.UriInfo;
33
34 import org.codehaus.enunciate.jaxrs.ResponseCode;
35 import org.codehaus.enunciate.jaxrs.StatusCodes;
36 import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
37 import org.opendaylight.neutron.spi.INeutronSubnetAware;
38 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
39 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
40 import org.opendaylight.neutron.spi.NeutronSubnet;
41
42 /**
43  * Neutron Northbound REST APIs for Subnets.<br>
44  * This class provides REST APIs for managing neutron Subnets
45  *
46  * <br>
47  * <br>
48  * Authentication scheme : <b>HTTP Basic</b><br>
49  * Authentication realm : <b>opendaylight</b><br>
50  * Transport : <b>HTTP and HTTPS</b><br>
51  * <br>
52  * HTTPS Authentication is disabled by default. Administrator can enable it in
53  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
54  * trusted authority.<br>
55  * More info :
56  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
57  *
58  */
59
60 @Path("/subnets")
61 public class NeutronSubnetsNorthbound {
62     private static final int HTTP_OK_BOTTOM = 200;
63     private static final int HTTP_OK_TOP = 299;
64     private static final String INTERFACE_NAME = "Subnet CRUD Interface";
65     private static final String UUID_NO_EXIST = "Subnet UUID does not exist.";
66     private static final String UUID_EXISTS = "Subnet UUID already exists.";
67     private static final String NO_PROVIDERS = "No providers registered.  Please try again later";
68     private static final String NO_PROVIDER_LIST = "Couldn't get providers list.  Please try again later";
69
70     private NeutronSubnet extractFields(NeutronSubnet o, List<String> fields) {
71         return o.extractFields(fields);
72     }
73
74     private NeutronCRUDInterfaces getNeutronInterfaces(boolean needNetwork) {
75         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronSubnetCRUD(this);
76         if (answer.getSubnetInterface() == null) {
77             throw new ServiceUnavailableException(INTERFACE_NAME
78                 + RestMessages.SERVICEUNAVAILABLE.toString());
79         }
80         if (needNetwork) {
81             answer = answer.fetchINeutronNetworkCRUD(this);
82             if (answer.getNetworkInterface() == null) {
83                 throw new ServiceUnavailableException("Network CRUD Interface "
84                     + RestMessages.SERVICEUNAVAILABLE.toString());
85             }
86         }
87         return answer;
88     }
89
90     @Context
91     UriInfo uriInfo;
92
93     /**
94      * Returns a list of all Subnets */
95     @GET
96     @Produces({ MediaType.APPLICATION_JSON })
97     //@TypeHint(OpenStackSubnets.class)
98     @StatusCodes({
99             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
100             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
101             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
102             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
103     public Response listSubnets(
104             // return fields
105             @QueryParam("fields") List<String> fields,
106             // note: openstack isn't clear about filtering on lists, so we aren't handling them
107             @QueryParam("id") String queryID,
108             @QueryParam("network_id") String queryNetworkID,
109             @QueryParam("name") String queryName,
110             @QueryParam("ip_version") String queryIPVersion,
111             @QueryParam("cidr") String queryCIDR,
112             @QueryParam("gateway_ip") String queryGatewayIP,
113             @QueryParam("enable_dhcp") String queryEnableDHCP,
114             @QueryParam("tenant_id") String queryTenantID,
115             @QueryParam("ipv6_address_mode") String queryIpV6AddressMode,
116             @QueryParam("ipv6_ra_mode") String queryIpV6RaMode,
117             // linkTitle
118             @QueryParam("limit") Integer limit,
119             @QueryParam("marker") String marker,
120             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
121             // sorting not supported
122             ) {
123         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
124         List<NeutronSubnet> allNetworks = subnetInterface.getAllSubnets();
125         List<NeutronSubnet> ans = new ArrayList<NeutronSubnet>();
126         Iterator<NeutronSubnet> i = allNetworks.iterator();
127         while (i.hasNext()) {
128             NeutronSubnet oSS = i.next();
129             if ((queryID == null || queryID.equals(oSS.getID())) &&
130                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
131                     (queryName == null || queryName.equals(oSS.getName())) &&
132                     (queryIPVersion == null || queryIPVersion.equals(oSS.getIpVersion())) &&
133                     (queryCIDR == null || queryCIDR.equals(oSS.getCidr())) &&
134                     (queryGatewayIP == null || queryGatewayIP.equals(oSS.getGatewayIP())) &&
135                     (queryEnableDHCP == null || queryEnableDHCP.equals(oSS.getEnableDHCP())) &&
136                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID())) &&
137                     (queryIpV6AddressMode == null || queryIpV6AddressMode.equals(oSS.getIpV6AddressMode())) &&
138                     (queryIpV6RaMode == null || queryIpV6RaMode.equals(oSS.getIpV6RaMode()))){
139                 if (fields.size() > 0) {
140                     ans.add(extractFields(oSS,fields));
141                 } else {
142                     ans.add(oSS);
143                 }
144             }
145         }
146
147         if (limit != null && ans.size() > 1) {
148             // Return a paginated request
149             NeutronSubnetRequest request = (NeutronSubnetRequest) PaginatedRequestFactory.createRequest(limit,
150                     marker, pageReverse, uriInfo, ans, NeutronSubnet.class);
151             return Response.status(HttpURLConnection.HTTP_OK).entity(request).build();
152         }
153
154         return Response.status(HttpURLConnection.HTTP_OK).entity(
155                 new NeutronSubnetRequest(ans)).build();
156     }
157
158     /**
159      * Returns a specific Subnet */
160
161     @Path("{subnetUUID}")
162     @GET
163     @Produces({ MediaType.APPLICATION_JSON })
164     //@TypeHint(OpenStackSubnets.class)
165     @StatusCodes({
166             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
167             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
168             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
169             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
170             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
171     public Response showSubnet(
172             @PathParam("subnetUUID") String subnetUUID,
173             // return fields
174             @QueryParam("fields") List<String> fields) {
175         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
176         if (!subnetInterface.subnetExists(subnetUUID)) {
177             throw new ResourceNotFoundException(UUID_NO_EXIST);
178         }
179         if (fields.size() > 0) {
180             NeutronSubnet ans = subnetInterface.getSubnet(subnetUUID);
181             return Response.status(HttpURLConnection.HTTP_OK).entity(
182                     new NeutronSubnetRequest(extractFields(ans, fields))).build();
183         } else {
184             return Response.status(HttpURLConnection.HTTP_OK).entity(
185                     new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
186         }
187     }
188
189     /**
190      * Creates new Subnets */
191
192     @POST
193     @Produces({ MediaType.APPLICATION_JSON })
194     @Consumes({ MediaType.APPLICATION_JSON })
195     //@TypeHint(OpenStackSubnets.class)
196     @StatusCodes({
197             @ResponseCode(code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
198             @ResponseCode(code = HttpURLConnection.HTTP_BAD_REQUEST, condition = "Bad Request"),
199             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
200             @ResponseCode(code = HttpURLConnection.HTTP_FORBIDDEN, condition = "Forbidden"),
201             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
202             @ResponseCode(code = HttpURLConnection.HTTP_CONFLICT, condition = "Conflict"),
203             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
204             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
205     public Response createSubnets(final NeutronSubnetRequest input) {
206         NeutronCRUDInterfaces interfaces = getNeutronInterfaces(true);
207         INeutronSubnetCRUD subnetInterface = interfaces.getSubnetInterface();
208         INeutronNetworkCRUD networkInterface = interfaces.getNetworkInterface();
209         if (input.isSingleton()) {
210             NeutronSubnet singleton = input.getSingleton();
211
212             Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
213             if (instances != null) {
214                 if (instances.length > 0) {
215                     for (Object instance : instances) {
216                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
217                         int status = service.canCreateSubnet(singleton);
218                         if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
219                             return Response.status(status).build();
220                         }
221                     }
222                 } else {
223                     throw new ServiceUnavailableException(NO_PROVIDERS);
224                 }
225             } else {
226                 throw new ServiceUnavailableException(NO_PROVIDER_LIST);
227             }
228             subnetInterface.addSubnet(singleton);
229             if (instances != null) {
230                 for (Object instance : instances) {
231                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
232                     service.neutronSubnetCreated(singleton);
233                 }
234             }
235         } else {
236             Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
237             for (NeutronSubnet test : input.getBulk()) {
238                 if (instances != null) {
239                     if (instances.length > 0) {
240                         for (Object instance : instances) {
241                             INeutronSubnetAware service = (INeutronSubnetAware) instance;
242                             int status = service.canCreateSubnet(test);
243                             if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
244                                 return Response.status(status).build();
245                             }
246                         }
247                     } else {
248                         throw new ServiceUnavailableException(NO_PROVIDERS);
249                     }
250                 } else {
251                     throw new ServiceUnavailableException(NO_PROVIDER_LIST);
252                 }
253             }
254
255             /*
256              * now, each element of the bulk request can be added to the cache
257              */
258             for (NeutronSubnet test : input.getBulk()) {
259                 subnetInterface.addSubnet(test);
260                 if (instances != null) {
261                     for (Object instance : instances) {
262                         INeutronSubnetAware service = (INeutronSubnetAware) instance;
263                         service.neutronSubnetCreated(test);
264                     }
265                 }
266             }
267         }
268         return Response.status(HttpURLConnection.HTTP_CREATED).entity(input).build();
269     }
270
271     /**
272      * Updates a Subnet */
273
274     @Path("{subnetUUID}")
275     @PUT
276     @Produces({ MediaType.APPLICATION_JSON })
277     @Consumes({ MediaType.APPLICATION_JSON })
278     //@TypeHint(OpenStackSubnets.class)
279     @StatusCodes({
280             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
281             @ResponseCode(code = HttpURLConnection.HTTP_BAD_REQUEST, condition = "Bad Request"),
282             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
283             @ResponseCode(code = HttpURLConnection.HTTP_FORBIDDEN, condition = "Forbidden"),
284             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
285             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
286             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
287     public Response updateSubnet(
288             @PathParam("subnetUUID") String subnetUUID, final NeutronSubnetRequest input
289             ) {
290         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
291
292         /*
293          * note: what we get appears to not be a delta, but rather a
294          * complete updated object.  So, that needs to be sent down to
295          * folks to check 
296          */
297
298         NeutronSubnet updatedObject = input.getSingleton();
299
300         Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
301         if (instances != null) {
302             if (instances.length > 0) {
303                 for (Object instance : instances) {
304                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
305                     NeutronSubnet original = subnetInterface.getSubnet(subnetUUID);
306                     int status = service.canUpdateSubnet(updatedObject, original);
307                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
308                         return Response.status(status).build();
309                     }
310                 }
311             } else {
312                 throw new ServiceUnavailableException(NO_PROVIDERS);
313             }
314         } else {
315             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
316         }
317
318         /*
319          * update the object and return it
320          */
321         subnetInterface.updateSubnet(subnetUUID, updatedObject);
322         if (instances != null) {
323             for (Object instance : instances) {
324                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
325                 service.neutronSubnetUpdated(updatedObject);
326             }
327         }
328         return Response.status(HttpURLConnection.HTTP_OK).entity(
329                 new NeutronSubnetRequest(subnetInterface.getSubnet(subnetUUID))).build();
330     }
331
332     /**
333      * Deletes a Subnet */
334
335     @Path("{subnetUUID}")
336     @DELETE
337     @StatusCodes({
338             @ResponseCode(code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
339             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
340             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
341             @ResponseCode(code = HttpURLConnection.HTTP_CONFLICT, condition = "Conflict"),
342             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
343             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
344     public Response deleteSubnet(
345             @PathParam("subnetUUID") String subnetUUID) {
346         INeutronSubnetCRUD subnetInterface = getNeutronInterfaces(false).getSubnetInterface();
347
348         NeutronSubnet singleton = subnetInterface.getSubnet(subnetUUID);
349         Object[] instances = NeutronUtil.getInstances(INeutronSubnetAware.class, this);
350         if (instances != null) {
351             if (instances.length > 0) {
352                 for (Object instance : instances) {
353                     INeutronSubnetAware service = (INeutronSubnetAware) instance;
354                     int status = service.canDeleteSubnet(singleton);
355                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
356                         return Response.status(status).build();
357                     }
358                 }
359             } else {
360                 throw new ServiceUnavailableException(NO_PROVIDERS);
361             }
362         } else {
363             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
364         }
365
366         /*
367          * remove it and return 204 status
368          */
369         subnetInterface.removeSubnet(subnetUUID);
370         if (instances != null) {
371             for (Object instance : instances) {
372                 INeutronSubnetAware service = (INeutronSubnetAware) instance;
373                 service.neutronSubnetDeleted(singleton);
374             }
375         }
376         return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
377     }
378 }