Merge "Bug 4043 - remote ip prefix of security group is type of ietf ip-prefix"
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / NeutronSecurityRulesNorthbound.java
1 /*
2  * Copyright (c) 2014, 2015 Red Hat, Inc. 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.INeutronSecurityRuleAware;
32 import org.opendaylight.neutron.spi.INeutronSecurityRuleCRUD;
33 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
34 import org.opendaylight.neutron.spi.NeutronSecurityRule;
35
36 /**
37  * Neutron Northbound REST APIs for Security Rule.<br>
38  * This class provides REST APIs for managing neutron Security Rule
39  * <p>
40  * <br>
41  * <br>
42  * Authentication scheme : <b>HTTP Basic</b><br>
43  * Authentication realm : <b>opendaylight</b><br>
44  * Transport : <b>HTTP and HTTPS</b><br>
45  * <br>
46  * HTTPS Authentication is disabled by default. Administrator can enable it in
47  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
48  * trusted authority.<br>
49  * More info :
50  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
51  */
52
53 @Path ("/security-group-rules")
54 public class NeutronSecurityRulesNorthbound extends AbstractNeutronNorthbound {
55     private static final String RESOURCE_NAME = "Security Rule";
56
57     private NeutronSecurityRule extractFields(NeutronSecurityRule o, List<String> fields) {
58         return o.extractFields(fields);
59     }
60
61     private NeutronCRUDInterfaces getNeutronInterfaces() {
62         NeutronCRUDInterfaces answer = new NeutronCRUDInterfaces().fetchINeutronSecurityRuleCRUD(this);
63         if (answer.getSecurityRuleInterface() == null) {
64             throw new ServiceUnavailableException(serviceUnavailable(RESOURCE_NAME));
65         }
66         return answer;
67     }
68
69     /**
70      * Returns a list of all Security Rules
71      */
72     @GET
73     @Produces ({MediaType.APPLICATION_JSON})
74     @StatusCodes ({
75             @ResponseCode (code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
76             @ResponseCode (code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
77             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
78             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
79     public Response listRules(
80             // return fields
81             @QueryParam ("fields") List<String> fields,
82             // OpenStack security rule attributes
83             @QueryParam ("id") String querySecurityRuleUUID,
84             @QueryParam ("direction") String querySecurityRuleDirection,
85             @QueryParam ("protocol") String querySecurityRuleProtocol,
86             @QueryParam ("port_range_min") Integer querySecurityRulePortMin,
87             @QueryParam ("port_range_max") Integer querySecurityRulePortMax,
88             @QueryParam ("ethertype") String querySecurityRuleEthertype,
89             @QueryParam ("remote_ip_prefix") String querySecurityRuleIpPrefix,
90             @QueryParam ("remote_group_id") String querySecurityRemoteGroupID,
91             @QueryParam ("security_group_id") String querySecurityRuleGroupID,
92             @QueryParam ("tenant_id") String querySecurityRuleTenantID,
93             @QueryParam ("limit") String limit,
94             @QueryParam ("marker") String marker,
95             @QueryParam ("page_reverse") String pageReverse
96     ) {
97         INeutronSecurityRuleCRUD securityRuleInterface = getNeutronInterfaces().getSecurityRuleInterface();
98         List<NeutronSecurityRule> allSecurityRules = securityRuleInterface.getAllNeutronSecurityRules();
99         List<NeutronSecurityRule> ans = new ArrayList<NeutronSecurityRule>();
100         Iterator<NeutronSecurityRule> i = allSecurityRules.iterator();
101         while (i.hasNext()) {
102             NeutronSecurityRule nsr = i.next();
103             if ((querySecurityRuleUUID == null ||
104                     querySecurityRuleUUID.equals(nsr.getID())) &&
105                     (querySecurityRuleDirection == null ||
106                             querySecurityRuleDirection.equals(nsr.getSecurityRuleDirection())) &&
107                     (querySecurityRuleProtocol == null ||
108                             querySecurityRuleProtocol.equals(nsr.getSecurityRuleProtocol())) &&
109                     (querySecurityRulePortMin == null ||
110                             querySecurityRulePortMin.equals(nsr.getSecurityRulePortMin())) &&
111                     (querySecurityRulePortMax == null ||
112                             querySecurityRulePortMax.equals(nsr.getSecurityRulePortMax())) &&
113                     (querySecurityRuleEthertype == null ||
114                             querySecurityRuleEthertype.equals(nsr.getSecurityRuleEthertype())) &&
115                     (querySecurityRuleIpPrefix == null ||
116                             querySecurityRuleIpPrefix.equals(nsr.getSecurityRuleRemoteIpPrefix())) &&
117                     (querySecurityRuleGroupID == null ||
118                             querySecurityRuleGroupID.equals(nsr.getSecurityRuleGroupID())) &&
119                     (querySecurityRemoteGroupID == null ||
120                             querySecurityRemoteGroupID.equals(nsr.getSecurityRemoteGroupID())) &&
121                     (querySecurityRuleTenantID == null ||
122                             querySecurityRuleTenantID.equals(nsr.getTenantID()))) {
123                 if (fields.size() > 0) {
124                     ans.add(extractFields(nsr, fields));
125                 } else {
126                     ans.add(nsr);
127                 }
128             }
129         }
130         return Response.status(HttpURLConnection.HTTP_OK).entity(
131                 new NeutronSecurityRuleRequest(ans)).build();
132     }
133
134     /**
135      * Returns a specific Security Rule
136      */
137
138     @Path ("{securityRuleUUID}")
139     @GET
140     @Produces ({MediaType.APPLICATION_JSON})
141     @StatusCodes ({
142             @ResponseCode (code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
143             @ResponseCode (code = HttpURLConnection.HTTP_UNAUTHORIZED, condition = "Unauthorized"),
144             @ResponseCode (code = HttpURLConnection.HTTP_NOT_FOUND, condition = "Not Found"),
145             @ResponseCode(code = HttpURLConnection.HTTP_NOT_IMPLEMENTED, condition = "Not Implemented"),
146             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
147     public Response showSecurityRule(@PathParam ("securityRuleUUID") String securityRuleUUID,
148                                      // return fields
149                                      @QueryParam ("fields") List<String> fields) {
150         INeutronSecurityRuleCRUD securityRuleInterface = getNeutronInterfaces().getSecurityRuleInterface();
151         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
152             throw new ResourceNotFoundException(uuidNoExist(RESOURCE_NAME));
153         }
154         if (!fields.isEmpty()) {
155             NeutronSecurityRule ans = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
156             return Response.status(HttpURLConnection.HTTP_OK).entity(
157                     new NeutronSecurityRuleRequest(extractFields(ans, fields))).build();
158         } else {
159             return Response.status(HttpURLConnection.HTTP_OK).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
160         }
161     }
162
163     /**
164      * Creates new Security Rule
165      */
166
167     @POST
168     @Produces ({MediaType.APPLICATION_JSON})
169     @Consumes ({MediaType.APPLICATION_JSON})
170     @StatusCodes ({
171             @ResponseCode (code = HttpURLConnection.HTTP_CREATED, condition = "Created"),
172             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
173     public Response createSecurityRules(final NeutronSecurityRuleRequest input) {
174         INeutronSecurityRuleCRUD securityRuleInterface = getNeutronInterfaces().getSecurityRuleInterface();
175
176         if (input.isSingleton()) {
177             NeutronSecurityRule singleton = input.getSingleton();
178             Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
179             if (instances != null) {
180                 if (instances.length > 0) {
181                     for (Object instance : instances) {
182                         INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
183                         int status = service.canCreateNeutronSecurityRule(singleton);
184                         if ((status < HTTP_OK_BOTTOM) || (status > HTTP_OK_TOP)) {
185                             return Response.status(status).build();
186                         }
187                     }
188                 } else {
189                     throw new ServiceUnavailableException(NO_PROVIDERS);
190                 }
191             } else {
192                 throw new ServiceUnavailableException(NO_PROVIDER_LIST);
193             }
194
195             // add rule to cache
196             singleton.initDefaults();
197             securityRuleInterface.addNeutronSecurityRule(singleton);
198             if (instances != null) {
199                 for (Object instance : instances) {
200                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
201                     service.neutronSecurityRuleCreated(singleton);
202                 }
203             }
204         } else {
205             Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
206             for (NeutronSecurityRule test : input.getBulk()) {
207                 if (instances != null) {
208                     if (instances.length > 0) {
209                         for (Object instance : instances) {
210                             INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
211                             int status = service.canCreateNeutronSecurityRule(test);
212                             if ((status < HTTP_OK_BOTTOM) || (status > HTTP_OK_TOP)) {
213                                 return Response.status(status).build();
214                             }
215                         }
216                     } else {
217                         throw new ServiceUnavailableException(NO_PROVIDERS);
218                     }
219                 } else {
220                     throw new ServiceUnavailableException(NO_PROVIDER_LIST);
221                 }
222             }
223
224             /*
225              * now, each element of the bulk request can be added to the cache
226              */
227             for (NeutronSecurityRule test : input.getBulk()) {
228                 securityRuleInterface.addNeutronSecurityRule(test);
229                 if (instances != null) {
230                     for (Object instance : instances) {
231                         INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
232                         service.neutronSecurityRuleCreated(test);
233                     }
234                 }
235             }
236         }
237         return Response.status(HttpURLConnection.HTTP_CREATED).entity(input).build();
238     }
239
240     /**
241      * Updates a Security Rule
242      */
243
244     @Path ("{securityRuleUUID}")
245     @PUT
246     @Produces ({MediaType.APPLICATION_JSON})
247     @Consumes ({MediaType.APPLICATION_JSON})
248     @StatusCodes ({
249             @ResponseCode (code = HttpURLConnection.HTTP_OK, condition = "Operation successful"),
250             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
251     public Response updateSecurityRule(
252             @PathParam ("securityRuleUUID") String securityRuleUUID, final NeutronSecurityRuleRequest input) {
253         INeutronSecurityRuleCRUD securityRuleInterface = getNeutronInterfaces().getSecurityRuleInterface();
254
255         NeutronSecurityRule delta = input.getSingleton();
256         NeutronSecurityRule original = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
257
258         Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
259         if (instances != null) {
260             if (instances.length > 0) {
261                 for (Object instance : instances) {
262                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
263                     int status = service.canUpdateNeutronSecurityRule(delta, original);
264                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
265                         return Response.status(status).build();
266                     }
267                 }
268             } else {
269                 throw new ServiceUnavailableException(NO_PROVIDERS);
270             }
271         } else {
272             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
273         }
274
275         /*
276          * update the object and return it
277          */
278         securityRuleInterface.updateNeutronSecurityRule(securityRuleUUID, delta);
279         NeutronSecurityRule updatedSecurityRule = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
280         if (instances != null) {
281             for (Object instance : instances) {
282                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
283                 service.neutronSecurityRuleUpdated(updatedSecurityRule);
284             }
285         }
286         return Response.status(HttpURLConnection.HTTP_OK).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
287     }
288
289     /**
290      * Deletes a Security Rule
291      */
292
293     @Path ("{securityRuleUUID}")
294     @DELETE
295     @StatusCodes ({
296             @ResponseCode (code = HttpURLConnection.HTTP_NO_CONTENT, condition = "No Content"),
297             @ResponseCode(code = HttpURLConnection.HTTP_UNAVAILABLE, condition = "No providers available") })
298     public Response deleteSecurityRule(
299             @PathParam ("securityRuleUUID") String securityRuleUUID) {
300         final INeutronSecurityRuleCRUD securityRuleInterface = getNeutronInterfaces().getSecurityRuleInterface();
301
302         NeutronSecurityRule singleton = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
303         Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
304         if (instances != null) {
305             if (instances.length > 0) {
306                 for (Object instance : instances) {
307                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
308                     int status = service.canDeleteNeutronSecurityRule(singleton);
309                     if (status < HTTP_OK_BOTTOM || status > HTTP_OK_TOP) {
310                         return Response.status(status).build();
311                     }
312                 }
313             } else {
314                 throw new ServiceUnavailableException(NO_PROVIDERS);
315             }
316         } else {
317             throw new ServiceUnavailableException(NO_PROVIDER_LIST);
318         }
319
320
321         /*
322          * remove it and return 204 status
323          */
324         deleteUuid(RESOURCE_NAME, securityRuleUUID,
325                    new Remover() {
326                        public boolean remove(String uuid) {
327                            return securityRuleInterface.removeNeutronSecurityRule(uuid);
328                        }
329                    });
330         if (instances != null) {
331             for (Object instance : instances) {
332                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
333                 service.neutronSecurityRuleDeleted(singleton);
334             }
335         }
336         return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
337     }
338 }