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