Merge "Cleanup root pom "name"."
[controller.git] / opendaylight / networkconfiguration / neutron / northbound / 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.DefaultValue;
19 import javax.ws.rs.GET;
20 import javax.ws.rs.POST;
21 import javax.ws.rs.PUT;
22 import javax.ws.rs.Path;
23 import javax.ws.rs.PathParam;
24 import javax.ws.rs.Produces;
25 import javax.ws.rs.QueryParam;
26 import javax.ws.rs.core.Context;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Response;
29 import javax.ws.rs.core.UriInfo;
30
31 import org.codehaus.enunciate.jaxrs.ResponseCode;
32 import org.codehaus.enunciate.jaxrs.StatusCodes;
33 import org.codehaus.enunciate.jaxrs.TypeHint;
34 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkAware;
35 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
36 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
37 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
38
39 /**
40  * Neutron Northbound REST APIs for Network.<br>
41  * This class provides REST APIs for managing neutron 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     @Context
61     UriInfo uriInfo;
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             // linkTitle
91             @QueryParam("limit") Integer limit,
92             @QueryParam("marker") String marker,
93             @DefaultValue("false") @QueryParam("page_reverse") Boolean 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
134         if (limit != null && ans.size() > 1) {
135             // Return a paginated request
136             NeutronNetworkRequest request = (NeutronNetworkRequest) PaginatedRequestFactory.createRequest(limit,
137                     marker, pageReverse, uriInfo, ans, NeutronNetwork.class);
138             return Response.status(200).entity(request).build();
139         }
140
141     return Response.status(200).entity(new NeutronNetworkRequest(ans)).build();
142
143     }
144
145     /**
146      * Returns a specific Network */
147
148     @Path("{netUUID}")
149     @GET
150     @Produces({ MediaType.APPLICATION_JSON })
151     //@TypeHint(OpenStackNetworks.class)
152     @StatusCodes({
153         @ResponseCode(code = 200, condition = "Operation successful"),
154         @ResponseCode(code = 401, condition = "Unauthorized"),
155         @ResponseCode(code = 404, condition = "Not Found") })
156     public Response showNetwork(
157             @PathParam("netUUID") String netUUID,
158             // return fields
159             @QueryParam("fields") List<String> fields
160             ) {
161         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
162         if (networkInterface == null) {
163             throw new ServiceUnavailableException("Network CRUD Interface "
164                     + RestMessages.SERVICEUNAVAILABLE.toString());
165         }
166         if (!networkInterface.networkExists(netUUID)) {
167             throw new ResourceNotFoundException("network UUID does not exist.");
168         }
169         if (fields.size() > 0) {
170             NeutronNetwork ans = networkInterface.getNetwork(netUUID);
171             return Response.status(200).entity(
172                     new NeutronNetworkRequest(extractFields(ans, fields))).build();
173         } else {
174             return Response.status(200).entity(
175                     new NeutronNetworkRequest(networkInterface.getNetwork(netUUID))).build();
176         }
177     }
178
179     /**
180      * Creates new Networks */
181     @POST
182     @Produces({ MediaType.APPLICATION_JSON })
183     @Consumes({ MediaType.APPLICATION_JSON })
184     @TypeHint(NeutronNetwork.class)
185     @StatusCodes({
186         @ResponseCode(code = 201, condition = "Created"),
187         @ResponseCode(code = 400, condition = "Bad Request"),
188         @ResponseCode(code = 401, condition = "Unauthorized") })
189     public Response createNetworks(final NeutronNetworkRequest input) {
190         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
191         if (networkInterface == null) {
192             throw new ServiceUnavailableException("Network CRUD Interface "
193                     + RestMessages.SERVICEUNAVAILABLE.toString());
194         }
195         if (input.isSingleton()) {
196             NeutronNetwork singleton = input.getSingleton();
197
198             /*
199              * network ID can't already exist
200              */
201             if (networkInterface.networkExists(singleton.getID())) {
202                 throw new BadRequestException("network UUID already exists");
203             }
204
205             Object[] instances = NeutronUtil.getInstances(INeutronNetworkAware.class, this);
206             if (instances != null) {
207                 if (instances.length > 0) {
208                     for (Object instance : instances) {
209                         INeutronNetworkAware service = (INeutronNetworkAware) instance;
210                         int status = service.canCreateNetwork(singleton);
211                         if (status < 200 || status > 299) {
212                             return Response.status(status).build();
213                         }
214                     }
215                 } else {
216                     throw new ServiceUnavailableException("No providers registered.  Please try again later");
217                 }
218             } else {
219                 throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
220             }
221
222             // add network to cache
223             singleton.initDefaults();
224             networkInterface.addNetwork(singleton);
225             if (instances != null) {
226                 for (Object instance : instances) {
227                     INeutronNetworkAware service = (INeutronNetworkAware) instance;
228                     service.neutronNetworkCreated(singleton);
229                 }
230             }
231
232         } else {
233             List<NeutronNetwork> bulk = input.getBulk();
234             Iterator<NeutronNetwork> i = bulk.iterator();
235             HashMap<String, NeutronNetwork> testMap = new HashMap<String, NeutronNetwork>();
236             Object[] instances = NeutronUtil.getInstances(INeutronNetworkAware.class, this);
237             while (i.hasNext()) {
238                 NeutronNetwork test = i.next();
239
240                 /*
241                  * network ID can't already exist, nor can there be an entry for this UUID
242                  * already in this bulk request
243                  */
244                 if (networkInterface.networkExists(test.getID())) {
245                     throw new BadRequestException("network UUID already exists");
246                 }
247                 if (testMap.containsKey(test.getID())) {
248                     throw new BadRequestException("network UUID already exists");
249                 }
250                 if (instances != null) {
251                     if (instances.length > 0) {
252                         for (Object instance: instances) {
253                             INeutronNetworkAware service = (INeutronNetworkAware) instance;
254                             int status = service.canCreateNetwork(test);
255                             if (status < 200 || status > 299) {
256                                 return Response.status(status).build();
257                             }
258                         }
259                     } else {
260                         throw new ServiceUnavailableException("No providers registered.  Please try again later");
261                     }
262                 } else {
263                     throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
264                 }
265                 testMap.put(test.getID(),test);
266             }
267
268             // now that everything passed, add items to the cache
269             i = bulk.iterator();
270             while (i.hasNext()) {
271                 NeutronNetwork test = i.next();
272                 test.initDefaults();
273                 networkInterface.addNetwork(test);
274                 if (instances != null) {
275                     for (Object instance: instances) {
276                         INeutronNetworkAware service = (INeutronNetworkAware) instance;
277                         service.neutronNetworkCreated(test);
278                     }
279                 }
280             }
281         }
282         return Response.status(201).entity(input).build();
283     }
284
285     /**
286      * Updates a Network */
287     @Path("{netUUID}")
288     @PUT
289     @Produces({ MediaType.APPLICATION_JSON })
290     @Consumes({ MediaType.APPLICATION_JSON })
291     //@TypeHint(OpenStackNetworks.class)
292     @StatusCodes({
293         @ResponseCode(code = 200, condition = "Operation successful"),
294         @ResponseCode(code = 400, condition = "Bad Request"),
295         @ResponseCode(code = 403, condition = "Forbidden"),
296         @ResponseCode(code = 404, condition = "Not Found"), })
297     public Response updateNetwork(
298             @PathParam("netUUID") String netUUID, final NeutronNetworkRequest input
299             ) {
300         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
301         if (networkInterface == null) {
302             throw new ServiceUnavailableException("Network CRUD Interface "
303                     + RestMessages.SERVICEUNAVAILABLE.toString());
304         }
305
306         /*
307          * network has to exist and only a single delta is supported
308          */
309         if (!networkInterface.networkExists(netUUID)) {
310             throw new ResourceNotFoundException("network UUID does not exist.");
311         }
312         if (!input.isSingleton()) {
313             throw new BadRequestException("only singleton edits supported");
314         }
315         NeutronNetwork delta = input.getSingleton();
316
317         /*
318          * transitions forbidden by Neutron
319          */
320         if (delta.getID() != null || delta.getTenantID() != null ||
321                 delta.getStatus() != null) {
322             throw new BadRequestException("attribute edit blocked by Neutron");
323         }
324
325         Object[] instances = NeutronUtil.getInstances(INeutronNetworkAware.class, this);
326         if (instances != null) {
327             if (instances.length > 0) {
328                 for (Object instance : instances) {
329                     INeutronNetworkAware service = (INeutronNetworkAware) instance;
330                     NeutronNetwork original = networkInterface.getNetwork(netUUID);
331                     int status = service.canUpdateNetwork(delta, original);
332                     if (status < 200 || status > 299) {
333                         return Response.status(status).build();
334                     }
335                 }
336             } else {
337                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
338             }
339         } else {
340             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
341         }
342
343         // update network object and return the modified object
344                 networkInterface.updateNetwork(netUUID, delta);
345                 NeutronNetwork updatedSingleton = networkInterface.getNetwork(netUUID);
346                 if (instances != null) {
347                     for (Object instance : instances) {
348                         INeutronNetworkAware service = (INeutronNetworkAware) instance;
349                         service.neutronNetworkUpdated(updatedSingleton);
350                     }
351                 }
352                 return Response.status(200).entity(
353                         new NeutronNetworkRequest(networkInterface.getNetwork(netUUID))).build();
354     }
355
356     /**
357      * Deletes a Network */
358
359     @Path("{netUUID}")
360     @DELETE
361     @StatusCodes({
362         @ResponseCode(code = 204, condition = "No Content"),
363         @ResponseCode(code = 401, condition = "Unauthorized"),
364         @ResponseCode(code = 404, condition = "Not Found"),
365         @ResponseCode(code = 409, condition = "Network In Use") })
366     public Response deleteNetwork(
367             @PathParam("netUUID") String netUUID) {
368         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
369         if (networkInterface == null) {
370             throw new ServiceUnavailableException("Network CRUD Interface "
371                     + RestMessages.SERVICEUNAVAILABLE.toString());
372         }
373
374         /*
375          * network has to exist and not be in use before it can be removed
376          */
377         if (!networkInterface.networkExists(netUUID)) {
378             throw new ResourceNotFoundException("network UUID does not exist.");
379         }
380         if (networkInterface.networkInUse(netUUID)) {
381             throw new ResourceConflictException("Network ID in use");
382         }
383
384         NeutronNetwork singleton = networkInterface.getNetwork(netUUID);
385         Object[] instances = NeutronUtil.getInstances(INeutronNetworkAware.class, this);
386         if (instances != null) {
387             if (instances.length > 0) {
388                 for (Object instance : instances) {
389                     INeutronNetworkAware service = (INeutronNetworkAware) instance;
390                     int status = service.canDeleteNetwork(singleton);
391                     if (status < 200 || status > 299) {
392                         return Response.status(status).build();
393                     }
394                 }
395             } else {
396                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
397             }
398         } else {
399             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
400         }
401
402         networkInterface.removeNetwork(netUUID);
403         if (instances != null) {
404             for (Object instance : instances) {
405                 INeutronNetworkAware service = (INeutronNetworkAware) instance;
406                 service.neutronNetworkDeleted(singleton);
407             }
408         }
409         return Response.status(204).build();
410     }
411 }