Merge "Initial implementation of the ClusteredDataStore"
[controller.git] / opendaylight / northbound / networkconfiguration / neutron / src / main / java / org / opendaylight / controller / networkconfig / neutron / northbound / NeutronNetworksNorthbound.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 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.Iterator;
14 import java.util.List;
15 import javax.ws.rs.Consumes;
16 import javax.ws.rs.DELETE;
17 import javax.ws.rs.GET;
18 import javax.ws.rs.POST;
19 import javax.ws.rs.PUT;
20 import javax.ws.rs.Path;
21 import javax.ws.rs.PathParam;
22 import javax.ws.rs.Produces;
23 import javax.ws.rs.QueryParam;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.Response;
26
27 import org.codehaus.enunciate.jaxrs.ResponseCode;
28 import org.codehaus.enunciate.jaxrs.StatusCodes;
29 import org.codehaus.enunciate.jaxrs.TypeHint;
30 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkAware;
31 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
32 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
33 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
34 import org.opendaylight.controller.northbound.commons.RestMessages;
35 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
36 import org.opendaylight.controller.sal.utils.ServiceHelper;
37
38 /**
39  * Open DOVE Northbound REST APIs for Network.<br>
40  * This class provides REST APIs for managing open DOVE internals related to Networks
41  *
42  * <br>
43  * <br>
44  * Authentication scheme : <b>HTTP Basic</b><br>
45  * Authentication realm : <b>opendaylight</b><br>
46  * Transport : <b>HTTP and HTTPS</b><br>
47  * <br>
48  * HTTPS Authentication is disabled by default. Administrator can enable it in
49  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
50  * trusted authority.<br>
51  * More info :
52  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
53  *
54  */
55
56 @Path("/networks")
57 public class NeutronNetworksNorthbound {
58
59     private NeutronNetwork extractFields(NeutronNetwork o, List<String> fields) {
60         return o.extractFields(fields);
61     }
62
63     /**
64      * Returns a list of all Networks */
65
66     @GET
67     @Produces({ MediaType.APPLICATION_JSON })
68     //@TypeHint(OpenStackNetworks.class)
69     @StatusCodes({
70             @ResponseCode(code = 200, condition = "Operation successful"),
71             @ResponseCode(code = 401, condition = "Unauthorized") })
72     public Response listNetworks(
73             // return fields
74             @QueryParam("fields") List<String> fields,
75             // note: openstack isn't clear about filtering on lists, so we aren't handling them
76             @QueryParam("id") String queryID,
77             @QueryParam("name") String queryName,
78             @QueryParam("admin_state_up") String queryAdminStateUp,
79             @QueryParam("status") String queryStatus,
80             @QueryParam("shared") String queryShared,
81             @QueryParam("tenant_id") String queryTenantID,
82             @QueryParam("router_external") String queryRouterExternal,
83             @QueryParam("provider_network_type") String queryProviderNetworkType,
84             @QueryParam("provider_physical_network") String queryProviderPhysicalNetwork,
85             @QueryParam("provider_segmentation_id") String queryProviderSegmentationID,
86             // pagination
87             @QueryParam("limit") String limit,
88             @QueryParam("marker") String marker,
89             @QueryParam("page_reverse") String pageReverse
90             // sorting not supported
91         ) {
92         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
93         if (networkInterface == null) {
94             throw new ServiceUnavailableException("Network CRUD Interface "
95                     + RestMessages.SERVICEUNAVAILABLE.toString());
96         }
97         List<NeutronNetwork> allNetworks = networkInterface.getAllNetworks();
98         List<NeutronNetwork> ans = new ArrayList<NeutronNetwork>();
99         Iterator<NeutronNetwork> i = allNetworks.iterator();
100         while (i.hasNext()) {
101             NeutronNetwork oSN = i.next();
102             //match filters: TODO provider extension
103             Boolean bAdminStateUp = null;
104             Boolean bShared = null;
105             Boolean bRouterExternal = null;
106             if (queryAdminStateUp != null)
107                 bAdminStateUp = Boolean.valueOf(queryAdminStateUp);
108             if (queryShared != null)
109                 bShared = Boolean.valueOf(queryShared);
110             if (queryRouterExternal != null)
111                 bRouterExternal = Boolean.valueOf(queryRouterExternal);
112             if ((queryID == null || queryID.equals(oSN.getID())) &&
113                     (queryName == null || queryName.equals(oSN.getNetworkName())) &&
114                     (bAdminStateUp == null || bAdminStateUp.booleanValue() == oSN.isAdminStateUp()) &&
115                     (queryStatus == null || queryStatus.equals(oSN.getStatus())) &&
116                     (bShared == null || bShared.booleanValue() == oSN.isShared()) &&
117                     (bRouterExternal == null || bRouterExternal.booleanValue() == oSN.isRouterExternal()) &&
118                     (queryTenantID == null || queryTenantID.equals(oSN.getTenantID()))) {
119                 if (fields.size() > 0)
120                     ans.add(extractFields(oSN,fields));
121                 else
122                     ans.add(oSN);
123             }
124         }
125         //TODO: apply pagination to results
126         return Response.status(200).entity(
127                 new NeutronNetworkRequest(ans)).build();
128     }
129
130     /**
131      * Returns a specific Network */
132
133     @Path("{netUUID}")
134     @GET
135     @Produces({ MediaType.APPLICATION_JSON })
136     //@TypeHint(OpenStackNetworks.class)
137     @StatusCodes({
138             @ResponseCode(code = 200, condition = "Operation successful"),
139             @ResponseCode(code = 401, condition = "Unauthorized"),
140             @ResponseCode(code = 404, condition = "Not Found") })
141     public Response showNetwork(
142             @PathParam("netUUID") String netUUID,
143             // return fields
144             @QueryParam("fields") List<String> fields
145             ) {
146         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
147         if (networkInterface == null) {
148             throw new ServiceUnavailableException("Network CRUD Interface "
149                     + RestMessages.SERVICEUNAVAILABLE.toString());
150         }
151         if (!networkInterface.networkExists(netUUID))
152             return Response.status(404).build();
153         if (fields.size() > 0) {
154             NeutronNetwork ans = networkInterface.getNetwork(netUUID);
155             return Response.status(200).entity(
156                     new NeutronNetworkRequest(extractFields(ans, fields))).build();
157         } else
158             return Response.status(200).entity(
159                     new NeutronNetworkRequest(networkInterface.getNetwork(netUUID))).build();
160     }
161
162     /**
163      * Creates new Networks */
164     @POST
165     @Produces({ MediaType.APPLICATION_JSON })
166     @Consumes({ MediaType.APPLICATION_JSON })
167     @TypeHint(NeutronNetwork.class)
168     @StatusCodes({
169             @ResponseCode(code = 201, condition = "Created"),
170             @ResponseCode(code = 400, condition = "Bad Request"),
171             @ResponseCode(code = 401, condition = "Unauthorized") })
172     public Response createNetworks(final NeutronNetworkRequest input) {
173         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
174         if (networkInterface == null) {
175             throw new ServiceUnavailableException("Network CRUD Interface "
176                     + RestMessages.SERVICEUNAVAILABLE.toString());
177         }
178         if (input.isSingleton()) {
179             NeutronNetwork singleton = input.getSingleton();
180
181             /*
182              * network ID can't already exist
183              */
184             if (networkInterface.networkExists(singleton.getID()))
185                 return Response.status(400).build();
186
187             Object[] instances = ServiceHelper.getGlobalInstances(INeutronNetworkAware.class, this, null);
188             if (instances != null) {
189                 for (Object instance : instances) {
190                     INeutronNetworkAware service = (INeutronNetworkAware) instance;
191                     int status = service.canCreateNetwork(singleton);
192                     if (status < 200 || status > 299)
193                         return Response.status(status).build();
194                 }
195             }
196
197             // add network to cache
198             networkInterface.addNetwork(singleton);
199             if (instances != null) {
200                 for (Object instance : instances) {
201                     INeutronNetworkAware service = (INeutronNetworkAware) instance;
202                     service.neutronNetworkCreated(singleton);
203                 }
204             }
205
206         } else {
207             List<NeutronNetwork> bulk = input.getBulk();
208             Iterator<NeutronNetwork> i = bulk.iterator();
209             HashMap<String, NeutronNetwork> testMap = new HashMap<String, NeutronNetwork>();
210             Object[] instances = ServiceHelper.getGlobalInstances(INeutronNetworkAware.class, this, null);
211             while (i.hasNext()) {
212                 NeutronNetwork test = i.next();
213
214                 /*
215                  * network ID can't already exist, nor can there be an entry for this UUID
216                  * already in this bulk request
217                  */
218                 if (networkInterface.networkExists(test.getID()))
219                     return Response.status(400).build();
220                 if (testMap.containsKey(test.getID()))
221                     return Response.status(400).build();
222                 if (instances != null) {
223                     for (Object instance: instances) {
224                         INeutronNetworkAware service = (INeutronNetworkAware) instance;
225                         int status = service.canCreateNetwork(test);
226                         if (status < 200 || status > 299)
227                             return Response.status(status).build();
228                     }
229                 }
230                 testMap.put(test.getID(),test);
231             }
232
233             // now that everything passed, add items to the cache
234             i = bulk.iterator();
235             while (i.hasNext()) {
236                 NeutronNetwork test = i.next();
237                 test.initDefaults();
238                 networkInterface.addNetwork(test);
239                 if (instances != null) {
240                     for (Object instance: instances) {
241                         INeutronNetworkAware service = (INeutronNetworkAware) instance;
242                         service.neutronNetworkCreated(test);
243                     }
244                 }
245             }
246         }
247         return Response.status(201).entity(input).build();
248     }
249
250     /**
251      * Updates a Network */
252     @Path("{netUUID}")
253     @PUT
254     @Produces({ MediaType.APPLICATION_JSON })
255     @Consumes({ MediaType.APPLICATION_JSON })
256     //@TypeHint(OpenStackNetworks.class)
257     @StatusCodes({
258             @ResponseCode(code = 200, condition = "Operation successful"),
259             @ResponseCode(code = 400, condition = "Bad Request"),
260             @ResponseCode(code = 403, condition = "Forbidden"),
261             @ResponseCode(code = 404, condition = "Not Found"), })
262     public Response updateNetwork(
263             @PathParam("netUUID") String netUUID, final NeutronNetworkRequest input
264             ) {
265         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
266         if (networkInterface == null) {
267             throw new ServiceUnavailableException("Network CRUD Interface "
268                     + RestMessages.SERVICEUNAVAILABLE.toString());
269         }
270
271         /*
272          * network has to exist and only a single delta is supported
273          */
274         if (!networkInterface.networkExists(netUUID))
275             return Response.status(404).build();
276         if (!input.isSingleton())
277             return Response.status(400).build();
278         NeutronNetwork delta = input.getSingleton();
279
280         /*
281          * transitions forbidden by Neutron
282          */
283         if (delta.getID() != null || delta.getTenantID() != null ||
284                 delta.getStatus() != null)
285             return Response.status(400).build();
286
287         Object[] instances = ServiceHelper.getGlobalInstances(INeutronNetworkAware.class, this, null);
288         if (instances != null) {
289             for (Object instance : instances) {
290                 INeutronNetworkAware service = (INeutronNetworkAware) instance;
291                 NeutronNetwork original = networkInterface.getNetwork(netUUID);
292                 int status = service.canUpdateNetwork(delta, original);
293                 if (status < 200 || status > 299)
294                     return Response.status(status).build();
295             }
296         }
297
298         // update network object and return the modified object
299         networkInterface.updateNetwork(netUUID, delta);
300         NeutronNetwork updatedSingleton = networkInterface.getNetwork(netUUID);
301         if (instances != null) {
302             for (Object instance : instances) {
303                 INeutronNetworkAware service = (INeutronNetworkAware) instance;
304                 service.neutronNetworkUpdated(updatedSingleton);
305             }
306         }
307         return Response.status(200).entity(
308                 new NeutronNetworkRequest(networkInterface.getNetwork(netUUID))).build();
309     }
310
311     /**
312      * Deletes a Network */
313
314     @Path("{netUUID}")
315     @DELETE
316     @StatusCodes({
317             @ResponseCode(code = 204, condition = "No Content"),
318             @ResponseCode(code = 401, condition = "Unauthorized"),
319             @ResponseCode(code = 404, condition = "Not Found"),
320             @ResponseCode(code = 409, condition = "Network In Use") })
321     public Response deleteNetwork(
322             @PathParam("netUUID") String netUUID) {
323         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
324         if (networkInterface == null) {
325             throw new ServiceUnavailableException("Network CRUD Interface "
326                     + RestMessages.SERVICEUNAVAILABLE.toString());
327         }
328
329         /*
330          * network has to exist and not be in use before it can be removed
331          */
332         if (!networkInterface.networkExists(netUUID))
333             return Response.status(404).build();
334         if (networkInterface.networkInUse(netUUID))
335             return Response.status(409).build();
336
337         NeutronNetwork singleton = networkInterface.getNetwork(netUUID);
338         Object[] instances = ServiceHelper.getGlobalInstances(INeutronNetworkAware.class, this, null);
339         if (instances != null) {
340             for (Object instance : instances) {
341                 INeutronNetworkAware service = (INeutronNetworkAware) instance;
342                 int status = service.canDeleteNetwork(singleton);
343                 if (status < 200 || status > 299)
344                     return Response.status(status).build();
345             }
346         }
347         networkInterface.removeNetwork(netUUID);
348         if (instances != null) {
349             for (Object instance : instances) {
350                 INeutronNetworkAware service = (INeutronNetworkAware) instance;
351                 service.neutronNetworkDeleted(singleton);
352             }
353         }
354         return Response.status(204).build();
355     }
356 }