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