Merge "Bug 4354 - neutron tenant_id doens't contain '-'(dash)"
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / NeutronPortsNorthbound.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.DefaultValue;
20 import javax.ws.rs.GET;
21 import javax.ws.rs.POST;
22 import javax.ws.rs.PUT;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.PathParam;
25 import javax.ws.rs.Produces;
26 import javax.ws.rs.QueryParam;
27 import javax.ws.rs.core.Context;
28 import javax.ws.rs.core.MediaType;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.UriInfo;
31
32 import org.codehaus.enunciate.jaxrs.ResponseCode;
33 import org.codehaus.enunciate.jaxrs.StatusCodes;
34 import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
35 import org.opendaylight.neutron.spi.INeutronPortAware;
36 import org.opendaylight.neutron.spi.INeutronPortCRUD;
37 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
38 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
39 import org.opendaylight.neutron.spi.NeutronPort;
40
41 /**
42  * Neutron Northbound REST APIs.<br>
43  * This class provides REST APIs for managing neutron port objects
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("/ports")
60 public class NeutronPortsNorthbound extends AbstractNeutronNorthbound {
61
62     private static final String RESOURCE_NAME = "Port";
63
64     private NeutronPort extractFields(NeutronPort o, List<String> fields) {
65         return o.extractFields(fields);
66     }
67
68     private NeutronCRUDInterfaces getNeutronInterfaces(boolean needNetworks, boolean needSubnets) {
69         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronPortCRUD(this);
70         if (answer.getPortInterface() == null) {
71             throw new ServiceUnavailableException(serviceUnavailable(RESOURCE_NAME));
72         }
73         if (needNetworks) {
74             answer = answer.fetchINeutronNetworkCRUD( this);
75             if (answer.getNetworkInterface() == null) {
76                 throw new ServiceUnavailableException("Network CRUD Interface "
77                         + RestMessages.SERVICEUNAVAILABLE.toString());
78             }
79         }
80         if (needSubnets) {
81             answer = answer.fetchINeutronSubnetCRUD( this);
82             if (answer.getSubnetInterface() == null) {
83                 throw new ServiceUnavailableException("Subnet CRUD Interface "
84                         + RestMessages.SERVICEUNAVAILABLE.toString());
85             }
86         }
87         return answer;
88     }
89
90     @Context
91     UriInfo uriInfo;
92
93     /**
94      * Returns a list of all Ports */
95
96     @GET
97     @Produces({ MediaType.APPLICATION_JSON })
98     //@TypeHint(OpenStackPorts.class)
99     @StatusCodes({
100         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
101         @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
102         @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
103         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
104     public Response listPorts(
105             // return fields
106             @QueryParam("fields") List<String> fields,
107             // note: openstack isn't clear about filtering on lists, so we aren't handling them
108             @QueryParam("id") String queryID,
109             @QueryParam("network_id") String queryNetworkID,
110             @QueryParam("name") String queryName,
111             @QueryParam("admin_state_up") String queryAdminStateUp,
112             @QueryParam("status") String queryStatus,
113             @QueryParam("mac_address") String queryMACAddress,
114             @QueryParam("device_id") String queryDeviceID,
115             @QueryParam("device_owner") String queryDeviceOwner,
116             @QueryParam("tenant_id") String queryTenantID,
117             // linkTitle
118             @QueryParam("limit") Integer limit,
119             @QueryParam("marker") String marker,
120             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
121             // sorting not supported
122             ) {
123         INeutronPortCRUD portInterface = getNeutronInterfaces(false, false).getPortInterface();
124         List<NeutronPort> allPorts = portInterface.getAllPorts();
125         List<NeutronPort> ans = new ArrayList<NeutronPort>();
126         Iterator<NeutronPort> i = allPorts.iterator();
127         while (i.hasNext()) {
128             NeutronPort oSS = i.next();
129             if ((queryID == null || queryID.equals(oSS.getID())) &&
130                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
131                     (queryName == null || queryName.equals(oSS.getName())) &&
132                     (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
133                     (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
134                     (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&
135                     (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&
136                     (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&
137                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {
138                 if (fields.size() > 0) {
139                     ans.add(extractFields(oSS,fields));
140                 } else {
141                     ans.add(oSS);
142                 }
143             }
144         }
145
146         if (limit != null && ans.size() > 1) {
147             // Return a paginated request
148             NeutronPortRequest request = (NeutronPortRequest) PaginatedRequestFactory.createRequest(limit,
149                     marker, pageReverse, uriInfo, ans, NeutronPort.class);
150             return Response.status(HttpURLConnection.HTTP_OK).entity(request).build();
151         }
152
153         return Response.status(HttpURLConnection.HTTP_OK).entity(
154                 new NeutronPortRequest(ans)).build();
155     }
156
157     /**
158      * Returns a specific Port */
159
160     @Path("{portUUID}")
161     @GET
162     @Produces({ MediaType.APPLICATION_JSON })
163     //@TypeHint(OpenStackPorts.class)
164     @StatusCodes({
165         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
166         @ResponseCode(code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
167         @ResponseCode(code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
168         @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
169         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
170     public Response showPort(
171             @PathParam("portUUID") String portUUID,
172             // return fields
173             @QueryParam("fields") List<String> fields ) {
174         INeutronPortCRUD portInterface = getNeutronInterfaces(false, false).getPortInterface();
175         if (!portInterface.portExists(portUUID)) {
176             throw new ResourceNotFoundException(uuidNoExist(RESOURCE_NAME));
177         }
178         if (fields.size() > 0) {
179             NeutronPort ans = portInterface.getPort(portUUID);
180             return Response.status(HttpURLConnection.HTTP_OK).entity(
181                     new NeutronPortRequest(extractFields(ans, fields))).build();
182         } else {
183             return Response.status(HttpURLConnection.HTTP_OK).entity(
184                     new NeutronPortRequest(portInterface.getPort(portUUID))).build();
185         }
186     }
187
188     /**
189      * Creates new Ports */
190
191     @POST
192     @Produces({ MediaType.APPLICATION_JSON })
193     @Consumes({ MediaType.APPLICATION_JSON })
194     //@TypeHint(OpenStackPorts.class)
195     @StatusCodes({
196         @ResponseCode(code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
197         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
198     public Response createPorts(final NeutronPortRequest input) {
199         NeutronCRUDInterfaces interfaces = getNeutronInterfaces(true, true);
200         INeutronPortCRUD portInterface = interfaces.getPortInterface();
201         if (input.isSingleton()) {
202             NeutronPort singleton = input.getSingleton();
203
204             Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
205             if (instances != null) {
206                 if (instances.length > 0) {
207                     for (Object instance : instances) {
208                         INeutronPortAware service = (INeutronPortAware) instance;
209                         int status = service.canCreatePort(singleton);
210                         if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
211                             return Response.status(status).build();
212                         }
213                     }
214                 } else {
215                     throw new ServiceUnavailableException(NO_PROVIDERS);
216                 }
217             } else {
218                 throw new ServiceUnavailableException(NO_PROVIDER_LIST);
219             }
220
221             // add the port to the cache
222             portInterface.addPort(singleton);
223             if (instances != null) {
224                 for (Object instance : instances) {
225                     INeutronPortAware service = (INeutronPortAware) instance;
226                     service.neutronPortCreated(singleton);
227                 }
228             }
229         } else {
230             Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
231             for (NeutronPort test : input.getBulk()) {
232
233                 if (instances != null) {
234                     if (instances.length > 0) {
235                         for (Object instance : instances) {
236                             INeutronPortAware service = (INeutronPortAware) instance;
237                             int status = service.canCreatePort(test);
238                             if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
239                                 return Response.status(status).build();
240                             }
241                         }
242                     } else {
243                         throw new ServiceUnavailableException(NO_PROVIDERS);
244                     }
245                 } else {
246                     throw new ServiceUnavailableException(NO_PROVIDER_LIST);
247                 }
248             }
249
250             //once everything has passed, then we can add to the cache
251             for (NeutronPort test : input.getBulk()) {
252                 portInterface.addPort(test);
253                 if (instances != null) {
254                     for (Object instance : instances) {
255                         INeutronPortAware service = (INeutronPortAware) instance;
256                         service.neutronPortCreated(test);
257                     }
258                 }
259             }
260         }
261         return Response.status(HttpURLConnection.HTTP_CREATED).entity(input).build();
262     }
263
264     /**
265      * Updates a Port */
266
267     @Path("{portUUID}")
268     @PUT
269     @Produces({ MediaType.APPLICATION_JSON })
270     @Consumes({ MediaType.APPLICATION_JSON })
271     //@TypeHint(OpenStackPorts.class)
272     @StatusCodes({
273         @ResponseCode(code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
274         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
275     public Response updatePort(
276             @PathParam("portUUID") String portUUID,
277             NeutronPortRequest input
278             ) {
279         NeutronCRUDInterfaces interfaces = getNeutronInterfaces(false, true);
280         INeutronPortCRUD portInterface = interfaces.getPortInterface();
281         NeutronPort original = portInterface.getPort(portUUID);
282
283         /*
284          * note: what we would like to get is the complete object as it
285          * is known by neutron.  Until then, patch what we *do* get
286          * so that we don't lose already known information
287          */
288
289         NeutronPort updatedObject = input.getSingleton();
290         if (updatedObject.getID() == null) {
291             updatedObject.setID(portUUID);
292         }
293         if (updatedObject.getTenantID() == null) {
294             updatedObject.setTenantID(original.getTenantID());
295         }
296         if (updatedObject.getNetworkUUID() == null) {
297             updatedObject.setNetworkUUID(original.getNetworkUUID());
298         }
299         if (updatedObject.getMacAddress() == null) {
300             updatedObject.setMacAddress(original.getMacAddress());
301         }
302         if (updatedObject.getFixedIPs() == null) {
303             updatedObject.setFixedIPs(original.getFixedIPs());
304         }
305
306         Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
307         if (instances != null) {
308             if (instances.length > 0) {
309                 for (Object instance : instances) {
310                     INeutronPortAware service = (INeutronPortAware) instance;
311                     int status = service.canUpdatePort(updatedObject, original);
312                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
313                         return Response.status(status).build();
314                     }
315                 }
316             } else {
317                 throw new ServiceUnavailableException(NO_PROVIDERS);
318             }
319         } else {
320             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
321         }
322
323         //        TODO: Support change of security groups
324         // update the port and return the modified object
325         portInterface.updatePort(portUUID, updatedObject);
326         if (instances != null) {
327             for (Object instance : instances) {
328                 INeutronPortAware service = (INeutronPortAware) instance;
329                 service.neutronPortUpdated(updatedObject);
330             }
331         }
332         return Response.status(HttpURLConnection.HTTP_OK).entity(
333                 new NeutronPortRequest(updatedObject)).build();
334
335     }
336
337     /**
338      * Deletes a Port */
339
340     @Path("{portUUID}")
341     @DELETE
342     @StatusCodes({
343         @ResponseCode(code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
344         @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
345     public Response deletePort(
346             @PathParam("portUUID") String portUUID) {
347         final INeutronPortCRUD portInterface = getNeutronInterfaces(false, false).getPortInterface();
348
349         NeutronPort singleton = portInterface.getPort(portUUID);
350         Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
351         if (instances != null) {
352             if (instances.length > 0) {
353                 for (Object instance : instances) {
354                     INeutronPortAware service = (INeutronPortAware) instance;
355                     int status = service.canDeletePort(singleton);
356                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
357                         return Response.status(status).build();
358                     }
359                 }
360             } else {
361                 throw new ServiceUnavailableException(NO_PROVIDERS);
362             }
363         } else {
364             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
365         }
366         deleteUuid(RESOURCE_NAME, portUUID,
367                    new Remover() {
368                        public boolean remove(String uuid) {
369                            return portInterface.removePort(uuid);
370                        }
371                    });
372         if (instances != null) {
373             for (Object instance : instances) {
374                 INeutronPortAware service = (INeutronPortAware) instance;
375                 service.neutronPortDeleted(singleton);
376             }
377         }
378         return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
379     }
380 }