Bug 5478 - northbound: improve 404 check on update/delete
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / NeutronRoutersNorthbound.java
1 /*
2  * Copyright (c) 2013, 2015 IBM Corporation and others.  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.Iterator;
15 import java.util.List;
16
17 import javax.ws.rs.Consumes;
18 import javax.ws.rs.DELETE;
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.MediaType;
27 import javax.ws.rs.core.Response;
28
29 import org.codehaus.enunciate.jaxrs.ResponseCode;
30 import org.codehaus.enunciate.jaxrs.StatusCodes;
31 import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
32 import org.opendaylight.neutron.spi.INeutronPortCRUD;
33 import org.opendaylight.neutron.spi.INeutronRouterAware;
34 import org.opendaylight.neutron.spi.INeutronRouterCRUD;
35 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
36 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
37 import org.opendaylight.neutron.spi.NeutronRouter;
38 import org.opendaylight.neutron.spi.NeutronRouter_Interface;
39
40
41 /**
42  * Neutron Northbound REST APIs.<br>
43  * This class provides REST APIs for managing neutron routers
44  *
45  * <br>
46  * <br>
47  * Authentication scheme : <b>HTTP Basic</b><br>
48  * Authentication realm : <b>opendaylight</b><br>
49  * Transport : <b>HTTP and HTTPS</b><br>
50  * <br>
51  * HTTPS Authentication is disabled by default. Administrator can enable it in
52  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
53  * trusted authority.<br>
54  * More info :
55  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
56  *
57  */
58
59 @Path("/routers")
60 public class NeutronRoutersNorthbound
61     extends AbstractNeutronNorthboundIAware<NeutronRouter, NeutronRouterRequest, INeutronRouterCRUD, INeutronRouterAware> {
62     static final String ROUTER_INTERFACE_STR = "network:router_interface";
63     static final String ROUTER_GATEWAY_STR = "network:router_gateway";
64     private static final String RESOURCE_NAME = "Router";
65
66     @Override
67     protected String getResourceName() {
68         return RESOURCE_NAME;
69     }
70
71     @Override
72     protected NeutronRouter extractFields(NeutronRouter o, List<String> fields) {
73         return o.extractFields(fields);
74     }
75
76     private NeutronCRUDInterfaces getNeutronInterfaces(boolean flag) {
77         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronRouterCRUD(this);
78         if (answer.getRouterInterface() == null) {
79             throw new ServiceUnavailableException(serviceUnavailable());
80         }
81         if (flag) {
82             answer = answer.fetchINeutronNetworkCRUD(this);
83             if (answer.getNetworkInterface() == null) {
84                 throw new ServiceUnavailableException("Network CRUD Interface "
85                     + RestMessages.SERVICEUNAVAILABLE.toString());
86             }
87         }
88         return answer;
89     }
90
91     @Override
92     protected INeutronRouterCRUD getNeutronCRUD() {
93         return getNeutronInterfaces(false).getRouterInterface();
94     }
95
96     private NeutronCRUDInterfaces getAttachInterfaces() {
97         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronRouterCRUD(this);
98         if (answer.getRouterInterface() == null) {
99             throw new ServiceUnavailableException(serviceUnavailable());
100         }
101         answer = answer.fetchINeutronPortCRUD(this).fetchINeutronSubnetCRUD(this);
102         if (answer.getPortInterface() == null) {
103             throw new ServiceUnavailableException("Port CRUD Interface "
104                     + RestMessages.SERVICEUNAVAILABLE.toString());
105         }
106         if (answer.getSubnetInterface() == null) {
107             throw new ServiceUnavailableException("Subnet CRUD Interface "
108                     + RestMessages.SERVICEUNAVAILABLE.toString());
109         }
110         return answer;
111     }
112
113     @Override
114     protected NeutronRouterRequest newNeutronRequest(NeutronRouter o) {
115         return new NeutronRouterRequest(o);
116     }
117
118     @Override
119     protected Object[] getInstances() {
120         return NeutronUtil.getInstances(INeutronRouterAware.class, this);
121     }
122
123     @Override
124     protected int canCreate(Object instance, NeutronRouter singleton) {
125         INeutronRouterAware service = (INeutronRouterAware) instance;
126         return service.canCreateRouter(singleton);
127     }
128
129     @Override
130     protected void created(Object instance, NeutronRouter singleton) {
131         INeutronRouterAware service = (INeutronRouterAware) instance;
132         service.neutronRouterCreated(singleton);
133     }
134
135     @Override
136     protected int canUpdate(Object instance, NeutronRouter delta, NeutronRouter original) {
137         INeutronRouterAware service = (INeutronRouterAware) instance;
138         return service.canUpdateRouter(delta, original);
139     }
140
141     @Override
142     protected void updated(Object instance, NeutronRouter updated) {
143         INeutronRouterAware service = (INeutronRouterAware) instance;
144         service.neutronRouterUpdated(updated);
145     }
146
147     @Override
148     protected int canDelete(Object instance, NeutronRouter singleton) {
149         INeutronRouterAware service = (INeutronRouterAware) instance;
150         return service.canDeleteRouter(singleton);
151     }
152
153     @Override
154     protected void deleted(Object instance, NeutronRouter singleton) {
155         INeutronRouterAware service = (INeutronRouterAware) instance;
156         service.neutronRouterDeleted(singleton);
157     }
158
159     /**
160      * Returns a list of all Routers */
161
162     @GET
163     @Produces({ MediaType.APPLICATION_JSON })
164     //@TypeHint(OpenStackRouters.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_IMPLEMENTED, condition = "Not Implemented"),
169             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
170     public Response listRouters(
171             // return fields
172             @QueryParam("fields") List<String> fields,
173             // note: openstack isn't clear about filtering on lists, so we aren't handling them
174             @QueryParam("id") String queryID,
175             @QueryParam("name") String queryName,
176             @QueryParam("admin_state_up") Boolean queryAdminStateUp,
177             @QueryParam("status") String queryStatus,
178             @QueryParam("tenant_id") String queryTenantID,
179             @QueryParam("external_gateway_info") String queryExternalGatewayInfo,
180             // pagination
181             @QueryParam("limit") String limit,
182             @QueryParam("marker") String marker,
183             @QueryParam("page_reverse") String pageReverse
184             // sorting not supported
185             ) {
186         INeutronRouterCRUD routerInterface = getNeutronInterfaces(false).getRouterInterface();
187         if (routerInterface == null) {
188             throw new ServiceUnavailableException(serviceUnavailable());
189         }
190         List<NeutronRouter> allRouters = routerInterface.getAllRouters();
191         List<NeutronRouter> ans = new ArrayList<NeutronRouter>();
192         Iterator<NeutronRouter> i = allRouters.iterator();
193         while (i.hasNext()) {
194             NeutronRouter oSS = i.next();
195             if ((queryID == null || queryID.equals(oSS.getID())) &&
196                     (queryName == null || queryName.equals(oSS.getName())) &&
197                     (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
198                     (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
199                     (queryExternalGatewayInfo == null || queryExternalGatewayInfo.equals(oSS.getExternalGatewayInfo())) &&
200                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {
201                 if (fields.size() > 0) {
202                     ans.add(extractFields(oSS,fields));
203                 } else {
204                     ans.add(oSS);
205                 }
206             }
207         }
208         //TODO: apply pagination to results
209         return Response.status(HttpURLConnection.HTTP_OK).entity(
210                 new NeutronRouterRequest(ans)).build();
211     }
212
213     /**
214      * Returns a specific Router */
215
216     @Path("{routerUUID}")
217     @GET
218     @Produces({ MediaType.APPLICATION_JSON })
219     //@TypeHint(OpenStackRouters.class)
220     @StatusCodes({
221             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
222             @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
223             @ResponseCode(code = HttpURLConnection.HTTP_FORBIDDEN, condition = "Forbidden"),
224             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
225             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
226             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
227     public Response showRouter(
228             @PathParam("routerUUID") String routerUUID,
229             // return fields
230             @QueryParam("fields") List<String> fields) {
231         return show(routerUUID, fields);
232     }
233
234     /**
235      * Creates new Routers */
236
237     @POST
238     @Produces({ MediaType.APPLICATION_JSON })
239     @Consumes({ MediaType.APPLICATION_JSON })
240     //@TypeHint(OpenStackRouters.class)
241     @StatusCodes({
242             @ResponseCode(code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
243             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
244     public Response createRouters(final NeutronRouterRequest input) {
245         getNeutronInterfaces(true); // ensure that network service is loaded
246         return create(input);
247     }
248
249     @Override
250     protected void updateDelta(String uuid, NeutronRouter delta, NeutronRouter original) {
251         delta.setID(uuid);
252         delta.setTenantID(original.getTenantID());
253     }
254
255     /**
256      * Updates a Router */
257
258     @Path("{routerUUID}")
259     @PUT
260     @Produces({ MediaType.APPLICATION_JSON })
261     @Consumes({ MediaType.APPLICATION_JSON })
262     //@TypeHint(OpenStackRouters.class)
263     @StatusCodes({
264             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
265             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
266             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
267     public Response updateRouter(
268             @PathParam("routerUUID") String routerUUID,
269             NeutronRouterRequest input
270             ) {
271         getNeutronInterfaces(true); // ensure that network service is loaded
272         return update(routerUUID, input);
273     }
274
275     /**
276      * Deletes a Router */
277
278     @Path("{routerUUID}")
279     @DELETE
280     @StatusCodes({
281             @ResponseCode(code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
282             @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
283             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
284     public Response deleteRouter(
285             @PathParam("routerUUID") String routerUUID) {
286         return delete(routerUUID);
287     }
288
289     /**
290      * Adds an interface to a router */
291
292     @Path("{routerUUID}/add_router_interface")
293     @PUT
294     @Produces({ MediaType.APPLICATION_JSON })
295     @Consumes({ MediaType.APPLICATION_JSON })
296     //@TypeHint(OpenStackRouterInterfaces.class)
297     @StatusCodes({
298             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
299             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
300     public Response addRouterInterface(
301             @PathParam("routerUUID") String routerUUID,
302             NeutronRouter_Interface input
303             ) {
304         NeutronCRUDInterfaces interfaces = getAttachInterfaces();
305         INeutronRouterCRUD routerInterface = interfaces.getRouterInterface();
306
307         NeutronRouter target = routerInterface.getRouter(routerUUID);
308         Object[] instances = getInstances();
309         if (instances != null) {
310             for (Object instance : instances) {
311                 INeutronRouterAware service = (INeutronRouterAware) instance;
312                 int status = service.canAttachInterface(target, input);
313                 if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
314                     return Response.status(status).build();
315                 }
316             }
317         }
318
319         target.addInterface(input.getPortUUID(), input);
320         if (instances != null) {
321             for (Object instance : instances) {
322                 INeutronRouterAware service = (INeutronRouterAware) instance;
323                 service.neutronRouterInterfaceAttached(target, input);
324             }
325         }
326
327         return Response.status(HttpURLConnection.HTTP_OK).entity(input).build();
328     }
329
330
331     private int checkDownstreamDetach(NeutronRouter target, NeutronRouter_Interface input) {
332         Object[] instances = getInstances();
333         if (instances != null) {
334             for (Object instance : instances) {
335                 INeutronRouterAware service = (INeutronRouterAware) instance;
336                 int status = service.canDetachInterface(target, input);
337                 if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
338                     return status;
339                 }
340             }
341         }
342         return HTTP_OK_BOTTOM;
343     }
344
345     /**
346      * Removes an interface to a router */
347
348     @Path("{routerUUID}/remove_router_interface")
349     @PUT
350     @Produces({ MediaType.APPLICATION_JSON })
351     @Consumes({ MediaType.APPLICATION_JSON })
352     //@TypeHint(OpenStackRouterInterfaces.class)
353     @StatusCodes({
354             @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
355             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
356     public Response removeRouterInterface(
357             @PathParam("routerUUID") String routerUUID,
358             NeutronRouter_Interface input
359             ) {
360         NeutronCRUDInterfaces interfaces = getAttachInterfaces();
361         INeutronRouterCRUD routerInterface = interfaces.getRouterInterface();
362         Object[] instances = getInstances();
363
364         NeutronRouter target = routerInterface.getRouter(routerUUID);
365         input.setID(target.getID());
366         input.setTenantID(target.getTenantID());
367         int status = checkDownstreamDetach(target, input);
368         if (status != HTTP_OK_BOTTOM) {
369             return Response.status(status).build();
370         }
371         target.removeInterface(input.getPortUUID());
372         if (instances != null) {
373             for (Object instance : instances) {
374                 INeutronRouterAware service = (INeutronRouterAware) instance;
375                 service.neutronRouterInterfaceDetached(target, input);
376             }
377         }
378         return Response.status(HttpURLConnection.HTTP_OK).entity(input).build();
379     }
380 }