Make neutron a simple osgi app
[controller.git] / opendaylight / networkconfiguration / neutron / northbound / src / main / java / org / opendaylight / controller / networkconfig / neutron / northbound / NeutronPortsNorthbound.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.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
34 import org.opendaylight.controller.networkconfig.neutron.INeutronPortAware;
35 import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
36 import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
37 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
38 import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
39 import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
40 import org.opendaylight.controller.networkconfig.neutron.Neutron_IPs;
41
42 /**
43  * Neutron Northbound REST APIs.<br>
44  * This class provides REST APIs for managing neutron port objects
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("/ports")
61 public class NeutronPortsNorthbound {
62
63     final String mac_regex="^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
64
65     private NeutronPort extractFields(NeutronPort o, List<String> fields) {
66         return o.extractFields(fields);
67     }
68
69     @Context
70     UriInfo uriInfo;
71
72     /**
73      * Returns a list of all Ports */
74
75     @GET
76     @Produces({ MediaType.APPLICATION_JSON })
77     //@TypeHint(OpenStackPorts.class)
78     @StatusCodes({
79         @ResponseCode(code = 200, condition = "Operation successful"),
80         @ResponseCode(code = 401, condition = "Unauthorized"),
81         @ResponseCode(code = 501, condition = "Not Implemented") })
82     public Response listPorts(
83             // return fields
84             @QueryParam("fields") List<String> fields,
85             // note: openstack isn't clear about filtering on lists, so we aren't handling them
86             @QueryParam("id") String queryID,
87             @QueryParam("network_id") String queryNetworkID,
88             @QueryParam("name") String queryName,
89             @QueryParam("admin_state_up") String queryAdminStateUp,
90             @QueryParam("status") String queryStatus,
91             @QueryParam("mac_address") String queryMACAddress,
92             @QueryParam("device_id") String queryDeviceID,
93             @QueryParam("device_owner") String queryDeviceOwner,
94             @QueryParam("tenant_id") String queryTenantID,
95             // linkTitle
96             @QueryParam("limit") Integer limit,
97             @QueryParam("marker") String marker,
98             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
99             // sorting not supported
100             ) {
101         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
102         if (portInterface == null) {
103             throw new ServiceUnavailableException("Port CRUD Interface "
104                     + RestMessages.SERVICEUNAVAILABLE.toString());
105         }
106         List<NeutronPort> allPorts = portInterface.getAllPorts();
107         List<NeutronPort> ans = new ArrayList<NeutronPort>();
108         Iterator<NeutronPort> i = allPorts.iterator();
109         while (i.hasNext()) {
110             NeutronPort oSS = i.next();
111             if ((queryID == null || queryID.equals(oSS.getID())) &&
112                     (queryNetworkID == null || queryNetworkID.equals(oSS.getNetworkUUID())) &&
113                     (queryName == null || queryName.equals(oSS.getName())) &&
114                     (queryAdminStateUp == null || queryAdminStateUp.equals(oSS.getAdminStateUp())) &&
115                     (queryStatus == null || queryStatus.equals(oSS.getStatus())) &&
116                     (queryMACAddress == null || queryMACAddress.equals(oSS.getMacAddress())) &&
117                     (queryDeviceID == null || queryDeviceID.equals(oSS.getDeviceID())) &&
118                     (queryDeviceOwner == null || queryDeviceOwner.equals(oSS.getDeviceOwner())) &&
119                     (queryTenantID == null || queryTenantID.equals(oSS.getTenantID()))) {
120                 if (fields.size() > 0) {
121                     ans.add(extractFields(oSS,fields));
122                 } else {
123                     ans.add(oSS);
124                 }
125             }
126         }
127
128         if (limit != null && ans.size() > 1) {
129             // Return a paginated request
130             NeutronPortRequest request = (NeutronPortRequest) PaginatedRequestFactory.createRequest(limit,
131                     marker, pageReverse, uriInfo, ans, NeutronPort.class);
132             return Response.status(200).entity(request).build();
133         }
134
135         return Response.status(200).entity(
136                 new NeutronPortRequest(ans)).build();
137     }
138
139     /**
140      * Returns a specific Port */
141
142     @Path("{portUUID}")
143     @GET
144     @Produces({ MediaType.APPLICATION_JSON })
145     //@TypeHint(OpenStackPorts.class)
146     @StatusCodes({
147         @ResponseCode(code = 200, condition = "Operation successful"),
148         @ResponseCode(code = 401, condition = "Unauthorized"),
149         @ResponseCode(code = 404, condition = "Not Found"),
150         @ResponseCode(code = 501, condition = "Not Implemented") })
151     public Response showPort(
152             @PathParam("portUUID") String portUUID,
153             // return fields
154             @QueryParam("fields") List<String> fields ) {
155         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
156         if (portInterface == null) {
157             throw new ServiceUnavailableException("Port CRUD Interface "
158                     + RestMessages.SERVICEUNAVAILABLE.toString());
159         }
160         if (!portInterface.portExists(portUUID)) {
161             throw new ResourceNotFoundException("port UUID does not exist.");
162         }
163         if (fields.size() > 0) {
164             NeutronPort ans = portInterface.getPort(portUUID);
165             return Response.status(200).entity(
166                     new NeutronPortRequest(extractFields(ans, fields))).build();
167         } else {
168             return Response.status(200).entity(
169                     new NeutronPortRequest(portInterface.getPort(portUUID))).build();
170         }
171     }
172
173     /**
174      * Creates new Ports */
175
176     @POST
177     @Produces({ MediaType.APPLICATION_JSON })
178     @Consumes({ MediaType.APPLICATION_JSON })
179     //@TypeHint(OpenStackPorts.class)
180     @StatusCodes({
181         @ResponseCode(code = 201, condition = "Created"),
182         @ResponseCode(code = 400, condition = "Bad Request"),
183         @ResponseCode(code = 401, condition = "Unauthorized"),
184         @ResponseCode(code = 403, condition = "Forbidden"),
185         @ResponseCode(code = 404, condition = "Not Found"),
186         @ResponseCode(code = 409, condition = "Conflict"),
187         @ResponseCode(code = 501, condition = "Not Implemented"),
188         @ResponseCode(code = 503, condition = "MAC generation failure") })
189     public Response createPorts(final NeutronPortRequest input) {
190         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
191         if (portInterface == null) {
192             throw new ServiceUnavailableException("Port CRUD Interface "
193                     + RestMessages.SERVICEUNAVAILABLE.toString());
194         }
195         INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
196         if (networkInterface == null) {
197             throw new ServiceUnavailableException("Network CRUD Interface "
198                     + RestMessages.SERVICEUNAVAILABLE.toString());
199         }
200         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
201         if (subnetInterface == null) {
202             throw new ServiceUnavailableException("Subnet CRUD Interface "
203                     + RestMessages.SERVICEUNAVAILABLE.toString());
204         }
205         if (input.isSingleton()) {
206             NeutronPort singleton = input.getSingleton();
207
208             /*
209              * the port must be part of an existing network, must not already exist,
210              * have a valid MAC and the MAC not be in use
211              */
212             if (singleton.getNetworkUUID() == null) {
213                 throw new BadRequestException("network UUID musy be specified");
214             }
215             if (portInterface.portExists(singleton.getID())) {
216                 throw new BadRequestException("port UUID already exists");
217             }
218             if (!networkInterface.networkExists(singleton.getNetworkUUID())) {
219                 throw new ResourceNotFoundException("network UUID does not exist.");
220             }
221             if (singleton.getMacAddress() == null ||
222                     !singleton.getMacAddress().matches(mac_regex)) {
223                 throw new BadRequestException("MAC address not properly formatted");
224             }
225             if (portInterface.macInUse(singleton.getMacAddress())) {
226                 throw new ResourceConflictException("MAC Address is in use.");
227             }
228             /*
229              * if fixed IPs are specified, each one has to have an existing subnet ID
230              * that is in the same scoping network as the port.  In addition, if an IP
231              * address is specified it has to be a valid address for the subnet and not
232              * already in use
233              */
234             List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
235             if (fixedIPs != null && fixedIPs.size() > 0) {
236                 Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
237                 while (fixedIPIterator.hasNext()) {
238                     Neutron_IPs ip = fixedIPIterator.next();
239                     if (ip.getSubnetUUID() == null) {
240                         throw new BadRequestException("subnet UUID not specified");
241                     }
242                     if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
243                         throw new BadRequestException("subnet UUID must exists");
244                     }
245                     NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
246                     if (!singleton.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
247                         throw new BadRequestException("network UUID must match that of subnet");
248                     }
249                     if (ip.getIpAddress() != null) {
250                         if (!subnet.isValidIP(ip.getIpAddress())) {
251                             throw new BadRequestException("IP address is not valid");
252                         }
253                         if (subnet.isIPInUse(ip.getIpAddress())) {
254                             throw new ResourceConflictException("IP address is in use.");
255                         }
256                     }
257                 }
258             }
259
260             Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
261             if (instances != null) {
262                 for (Object instance : instances) {
263                     INeutronPortAware service = (INeutronPortAware) instance;
264                     int status = service.canCreatePort(singleton);
265                     if (status < 200 || status > 299) {
266                         return Response.status(status).build();
267                     }
268                 }
269             }
270
271
272             // add the port to the cache
273             portInterface.addPort(singleton);
274             if (instances != null) {
275                 for (Object instance : instances) {
276                     INeutronPortAware service = (INeutronPortAware) instance;
277                     service.neutronPortCreated(singleton);
278                 }
279             }
280         } else {
281             List<NeutronPort> bulk = input.getBulk();
282             Iterator<NeutronPort> i = bulk.iterator();
283             HashMap<String, NeutronPort> testMap = new HashMap<String, NeutronPort>();
284             Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
285             while (i.hasNext()) {
286                 NeutronPort test = i.next();
287
288                 /*
289                  * the port must be part of an existing network, must not already exist,
290                  * have a valid MAC and the MAC not be in use.  Further the bulk request
291                  * can't already contain a new port with the same UUID
292                  */
293                 if (portInterface.portExists(test.getID())) {
294                     throw new BadRequestException("port UUID already exists");
295                 }
296                 if (testMap.containsKey(test.getID())) {
297                     throw new BadRequestException("port UUID already exists");
298                 }
299                 for (NeutronPort check : testMap.values()) {
300                     if (test.getMacAddress().equalsIgnoreCase(check.getMacAddress())) {
301                         throw new ResourceConflictException("MAC address already allocated");
302                     }
303                     for (Neutron_IPs test_fixedIP : test.getFixedIPs()) {
304                         for (Neutron_IPs check_fixedIP : check.getFixedIPs()) {
305                             if (test_fixedIP.getIpAddress().equals(check_fixedIP.getIpAddress())) {
306                                 throw new ResourceConflictException("IP address already allocated");
307                             }
308                         }
309                     }
310                 }
311                 testMap.put(test.getID(), test);
312                 if (!networkInterface.networkExists(test.getNetworkUUID())) {
313                     throw new ResourceNotFoundException("network UUID does not exist.");
314                 }
315                 if (!test.getMacAddress().matches(mac_regex)) {
316                     throw new BadRequestException("MAC address not properly formatted");
317                 }
318                 if (portInterface.macInUse(test.getMacAddress())) {
319                     throw new ResourceConflictException("MAC address in use");
320                 }
321
322                 /*
323                  * if fixed IPs are specified, each one has to have an existing subnet ID
324                  * that is in the same scoping network as the port.  In addition, if an IP
325                  * address is specified it has to be a valid address for the subnet and not
326                  * already in use (or be the gateway IP address of the subnet)
327                  */
328                 List<Neutron_IPs> fixedIPs = test.getFixedIPs();
329                 if (fixedIPs != null && fixedIPs.size() > 0) {
330                     Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
331                     while (fixedIPIterator.hasNext()) {
332                         Neutron_IPs ip = fixedIPIterator.next();
333                         if (ip.getSubnetUUID() == null) {
334                             throw new BadRequestException("subnet UUID must be specified");
335                         }
336                         if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
337                             throw new BadRequestException("subnet UUID doesn't exists");
338                         }
339                         NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
340                         if (!test.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
341                             throw new BadRequestException("network UUID must match that of subnet");
342                         }
343                         if (ip.getIpAddress() != null) {
344                             if (!subnet.isValidIP(ip.getIpAddress())) {
345                                 throw new BadRequestException("ip address not valid");
346                             }
347                             //TODO: need to add consideration for a fixed IP being assigned the same address as a allocated IP in the
348                             //same bulk create
349                             if (subnet.isIPInUse(ip.getIpAddress())) {
350                                 throw new ResourceConflictException("IP address in use");
351                             }
352                         }
353                     }
354                 }
355                 if (instances != null) {
356                     for (Object instance : instances) {
357                         INeutronPortAware service = (INeutronPortAware) instance;
358                         int status = service.canCreatePort(test);
359                         if (status < 200 || status > 299) {
360                             return Response.status(status).build();
361                         }
362                     }
363                 }
364             }
365
366             //once everything has passed, then we can add to the cache
367             i = bulk.iterator();
368             while (i.hasNext()) {
369                 NeutronPort test = i.next();
370                 portInterface.addPort(test);
371                 if (instances != null) {
372                     for (Object instance : instances) {
373                         INeutronPortAware service = (INeutronPortAware) instance;
374                         service.neutronPortCreated(test);
375                     }
376                 }
377             }
378         }
379         return Response.status(201).entity(input).build();
380     }
381
382     /**
383      * Updates a Port */
384
385     @Path("{portUUID}")
386     @PUT
387     @Produces({ MediaType.APPLICATION_JSON })
388     @Consumes({ MediaType.APPLICATION_JSON })
389     //@TypeHint(OpenStackPorts.class)
390     @StatusCodes({
391         @ResponseCode(code = 200, condition = "Operation successful"),
392         @ResponseCode(code = 400, condition = "Bad Request"),
393         @ResponseCode(code = 401, condition = "Unauthorized"),
394         @ResponseCode(code = 403, condition = "Forbidden"),
395         @ResponseCode(code = 404, condition = "Not Found"),
396         @ResponseCode(code = 409, condition = "Conflict"),
397         @ResponseCode(code = 501, condition = "Not Implemented") })
398     public Response updatePort(
399             @PathParam("portUUID") String portUUID,
400             NeutronPortRequest input
401             ) {
402         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
403         if (portInterface == null) {
404             throw new ServiceUnavailableException("Port CRUD Interface "
405                     + RestMessages.SERVICEUNAVAILABLE.toString());
406         }
407         INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
408         if (subnetInterface == null) {
409             throw new ServiceUnavailableException("Subnet CRUD Interface "
410                     + RestMessages.SERVICEUNAVAILABLE.toString());
411         }
412
413         // port has to exist and only a single delta is supported
414         if (!portInterface.portExists(portUUID)) {
415             throw new ResourceNotFoundException("port UUID does not exist.");
416         }
417         NeutronPort target = portInterface.getPort(portUUID);
418         if (!input.isSingleton()) {
419             throw new BadRequestException("only singleton edit suported");
420         }
421         NeutronPort singleton = input.getSingleton();
422         NeutronPort original = portInterface.getPort(portUUID);
423
424         // deltas restricted by Neutron
425         if (singleton.getID() != null || singleton.getTenantID() != null ||
426                 singleton.getStatus() != null) {
427             throw new BadRequestException("attribute change blocked by Neutron");
428         }
429
430         Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
431         if (instances != null) {
432             for (Object instance : instances) {
433                 INeutronPortAware service = (INeutronPortAware) instance;
434                 int status = service.canUpdatePort(singleton, original);
435                 if (status < 200 || status > 299) {
436                     return Response.status(status).build();
437                 }
438             }
439         }
440
441         // Verify the new fixed ips are valid
442         List<Neutron_IPs> fixedIPs = singleton.getFixedIPs();
443         if (fixedIPs != null && fixedIPs.size() > 0) {
444             Iterator<Neutron_IPs> fixedIPIterator = fixedIPs.iterator();
445             while (fixedIPIterator.hasNext()) {
446                 Neutron_IPs ip = fixedIPIterator.next();
447                 if (ip.getSubnetUUID() == null) {
448                     throw new BadRequestException("subnet UUID must be specified");
449                 }
450                 if (!subnetInterface.subnetExists(ip.getSubnetUUID())) {
451                     throw new BadRequestException("subnet UUID doesn't exist.");
452                 }
453                 NeutronSubnet subnet = subnetInterface.getSubnet(ip.getSubnetUUID());
454                 if (!target.getNetworkUUID().equalsIgnoreCase(subnet.getNetworkUUID())) {
455                     throw new BadRequestException("network UUID must match that of subnet");
456                 }
457                 if (ip.getIpAddress() != null) {
458                     if (!subnet.isValidIP(ip.getIpAddress())) {
459                         throw new BadRequestException("invalid IP address");
460                     }
461                     if (subnet.isIPInUse(ip.getIpAddress())) {
462                         throw new ResourceConflictException("IP address in use");
463                     }
464                 }
465             }
466         }
467
468         //        TODO: Support change of security groups
469         // update the port and return the modified object
470         portInterface.updatePort(portUUID, singleton);
471         NeutronPort updatedPort = portInterface.getPort(portUUID);
472         if (instances != null) {
473             for (Object instance : instances) {
474                 INeutronPortAware service = (INeutronPortAware) instance;
475                 service.neutronPortUpdated(updatedPort);
476             }
477         }
478         return Response.status(200).entity(
479                 new NeutronPortRequest(updatedPort)).build();
480
481     }
482
483     /**
484      * Deletes a Port */
485
486     @Path("{portUUID}")
487     @DELETE
488     @StatusCodes({
489         @ResponseCode(code = 204, condition = "No Content"),
490         @ResponseCode(code = 401, condition = "Unauthorized"),
491         @ResponseCode(code = 403, condition = "Forbidden"),
492         @ResponseCode(code = 404, condition = "Not Found"),
493         @ResponseCode(code = 501, condition = "Not Implemented") })
494     public Response deletePort(
495             @PathParam("portUUID") String portUUID) {
496         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
497         if (portInterface == null) {
498             throw new ServiceUnavailableException("Port CRUD Interface "
499                     + RestMessages.SERVICEUNAVAILABLE.toString());
500         }
501
502         // port has to exist and not be owned by anyone.  then it can be removed from the cache
503         if (!portInterface.portExists(portUUID)) {
504             throw new ResourceNotFoundException("port UUID does not exist.");
505         }
506         NeutronPort port = portInterface.getPort(portUUID);
507         if (port.getDeviceID() != null ||
508                 port.getDeviceOwner() != null) {
509             Response.status(403).build();
510         }
511         NeutronPort singleton = portInterface.getPort(portUUID);
512         Object[] instances = NeutronUtil.getInstances(INeutronPortAware.class, this);
513         if (instances != null) {
514             for (Object instance : instances) {
515                 INeutronPortAware service = (INeutronPortAware) instance;
516                 int status = service.canDeletePort(singleton);
517                 if (status < 200 || status > 299) {
518                     return Response.status(status).build();
519                 }
520             }
521         }
522         portInterface.removePort(portUUID);
523         if (instances != null) {
524             for (Object instance : instances) {
525                 INeutronPortAware service = (INeutronPortAware) instance;
526                 service.neutronPortDeleted(singleton);
527             }
528         }
529         return Response.status(204).build();
530     }
531 }