Merge changes I7c36c88e,I7c5d97c7
[controller.git] / opendaylight / northbound / networkconfiguration / neutron / src / main / java / org / opendaylight / controller / networkconfig / neutron / northbound / NeutronSecurityRulesNorthbound.java
1 /*
2  * Copyright (C) 2014 Red Hat, Inc.
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
10 package org.opendaylight.controller.networkconfig.neutron.northbound;
11
12
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.List;
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.controller.networkconfig.neutron.INeutronSecurityGroupCRUD;
32 import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityRuleAware;
33 import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityRuleCRUD;
34 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
35 import org.opendaylight.controller.networkconfig.neutron.NeutronSecurityRule;
36 import org.opendaylight.controller.northbound.commons.RestMessages;
37 import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
38 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
39 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
40 import org.opendaylight.controller.sal.utils.ServiceHelper;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Neutron Northbound REST APIs for Security Rule.<br>
46  * This class provides REST APIs for managing neutron Security Rule
47  * <p/>
48  * <br>
49  * <br>
50  * Authentication scheme : <b>HTTP Basic</b><br>
51  * Authentication realm : <b>opendaylight</b><br>
52  * Transport : <b>HTTP and HTTPS</b><br>
53  * <br>
54  * HTTPS Authentication is disabled by default. Administrator can enable it in
55  * tomcat-server.xml after adding a proper keystore / SSL certificate from a
56  * trusted authority.<br>
57  * More info :
58  * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
59  */
60
61 @Path ("/security-group-rules")
62 public class NeutronSecurityRulesNorthbound {
63     static final Logger logger = LoggerFactory.getLogger(NeutronSecurityRulesNorthbound.class);
64
65     private NeutronSecurityRule extractFields(NeutronSecurityRule o, List<String> fields) {
66         return o.extractFields(fields);
67     }
68
69     /**
70      * Returns a list of all Security Rules
71      */
72     @GET
73     @Produces ({MediaType.APPLICATION_JSON})
74     @StatusCodes ({
75             @ResponseCode (code = 200, condition = "Operation successful"),
76             @ResponseCode (code = 401, condition = "Unauthorized"),
77             @ResponseCode (code = 501, condition = "Not Implemented")})
78     public Response listRules(
79             // return fields
80             @QueryParam ("fields") List<String> fields,
81             // OpenStack security rule attributes
82             @QueryParam ("id") String querySecurityRuleUUID,
83             @QueryParam ("direction") String querySecurityRuleDirection,
84             @QueryParam ("protocol") String querySecurityRuleProtocol,
85             @QueryParam ("port_range_min") Integer querySecurityRulePortMin,
86             @QueryParam ("port_range_max") Integer querySecurityRulePortMax,
87             @QueryParam ("ethertype") String querySecurityRuleEthertype,
88             @QueryParam ("remote_ip_prefix") String querySecurityRuleIpPrefix,
89             @QueryParam ("remote_group_id") String querySecurityRemoteGroupID,
90             @QueryParam ("security_group_id") String querySecurityRuleGroupID,
91             @QueryParam ("tenant_id") String querySecurityRuleTenantID,
92             @QueryParam ("limit") String limit,
93             @QueryParam ("marker") String marker,
94             @QueryParam ("page_reverse") String pageReverse
95     ) {
96         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
97         if (securityRuleInterface == null) {
98             throw new ServiceUnavailableException("Security Rule CRUD Interface "
99                     + RestMessages.SERVICEUNAVAILABLE.toString());
100         }
101         List<NeutronSecurityRule> allSecurityRules = securityRuleInterface.getAllNeutronSecurityRules();
102         List<NeutronSecurityRule> ans = new ArrayList<NeutronSecurityRule>();
103         Iterator<NeutronSecurityRule> i = allSecurityRules.iterator();
104         while (i.hasNext()) {
105             NeutronSecurityRule nsr = i.next();
106             if ((querySecurityRuleUUID == null ||
107                     querySecurityRuleUUID.equals(nsr.getSecurityRuleUUID())) &&
108                     (querySecurityRuleDirection == null ||
109                             querySecurityRuleDirection.equals(nsr.getSecurityRuleDirection())) &&
110                     (querySecurityRuleProtocol == null ||
111                             querySecurityRuleProtocol.equals(nsr.getSecurityRuleProtocol())) &&
112                     (querySecurityRulePortMin == null ||
113                             querySecurityRulePortMin.equals(nsr.getSecurityRulePortMin())) &&
114                     (querySecurityRulePortMax == null ||
115                             querySecurityRulePortMax.equals(nsr.getSecurityRulePortMax())) &&
116                     (querySecurityRuleEthertype == null ||
117                             querySecurityRuleEthertype.equals(nsr.getSecurityRuleEthertype())) &&
118                     (querySecurityRuleIpPrefix == null ||
119                             querySecurityRuleIpPrefix.equals(nsr.getSecurityRuleRemoteIpPrefix())) &&
120                     (querySecurityRuleGroupID == null ||
121                             querySecurityRuleGroupID.equals(nsr.getSecurityRuleGroupID())) &&
122                     (querySecurityRemoteGroupID == null ||
123                             querySecurityRemoteGroupID.equals(nsr.getSecurityRemoteGroupID())) &&
124                     (querySecurityRuleTenantID == null ||
125                             querySecurityRuleTenantID.equals(nsr.getSecurityRuleTenantID()))) {
126                 if (fields.size() > 0) {
127                     ans.add(extractFields(nsr, fields));
128                 } else {
129                     ans.add(nsr);
130                 }
131             }
132         }
133         return Response.status(200).entity(
134                 new NeutronSecurityRuleRequest(ans)).build();
135     }
136
137     /**
138      * Returns a specific Security Rule
139      */
140
141     @Path ("{securityRuleUUID}")
142     @GET
143     @Produces ({MediaType.APPLICATION_JSON})
144     @StatusCodes ({
145             @ResponseCode (code = 200, condition = "Operation successful"),
146             @ResponseCode (code = 401, condition = "Unauthorized"),
147             @ResponseCode (code = 404, condition = "Not Found"),
148             @ResponseCode (code = 501, condition = "Not Implemented")})
149     public Response showSecurityRule(@PathParam ("securityRuleUUID") String securityRuleUUID,
150                                      // return fields
151                                      @QueryParam ("fields") List<String> fields) {
152         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
153         if (securityRuleInterface == null) {
154             throw new ServiceUnavailableException("Security Rule CRUD Interface "
155                     + RestMessages.SERVICEUNAVAILABLE.toString());
156         }
157         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
158             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
159         }
160         if (!fields.isEmpty()) {
161             NeutronSecurityRule ans = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
162             return Response.status(200).entity(
163                     new NeutronSecurityRuleRequest(extractFields(ans, fields))).build();
164         } else {
165             return Response.status(200).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
166         }
167     }
168
169     /**
170      * Creates new Security Rule
171      */
172
173     @POST
174     @Produces ({MediaType.APPLICATION_JSON})
175     @Consumes ({MediaType.APPLICATION_JSON})
176     @StatusCodes ({
177             @ResponseCode (code = 201, condition = "Created"),
178             @ResponseCode (code = 400, condition = "Bad Request"),
179             @ResponseCode (code = 401, condition = "Unauthorized"),
180             @ResponseCode (code = 403, condition = "Forbidden"),
181             @ResponseCode (code = 404, condition = "Not Found"),
182             @ResponseCode (code = 409, condition = "Conflict"),
183             @ResponseCode (code = 501, condition = "Not Implemented")})
184     public Response createSecurityRules(final NeutronSecurityRuleRequest input) {
185         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
186         if (securityRuleInterface == null) {
187             throw new ServiceUnavailableException("Security Rule CRUD Interface "
188                     + RestMessages.SERVICEUNAVAILABLE.toString());
189         }
190         INeutronSecurityGroupCRUD securityGroupInterface = NeutronCRUDInterfaces.getINeutronSecurityGroupCRUD(this);
191         if (securityGroupInterface == null) {
192             throw new ServiceUnavailableException("Security Group CRUD Interface "
193                     + RestMessages.SERVICEUNAVAILABLE.toString());
194         }
195
196         /*
197          * Existing entry checks
198         */
199
200         if (input.isSingleton()) {
201             NeutronSecurityRule singleton = input.getSingleton();
202
203             if (securityRuleInterface.neutronSecurityRuleExists(singleton.getSecurityRuleUUID())) {
204                 throw new BadRequestException("Security Rule UUID already exists");
205             }
206             Object[] instances = ServiceHelper.getGlobalInstances(INeutronSecurityRuleAware.class, this, null);
207             if (instances != null) {
208                 for (Object instance : instances) {
209                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
210                     int status = service.canCreateNeutronSecurityRule(singleton);
211                     if ((status < 200) || (status > 299)) {
212                         return Response.status(status).build();
213                     }
214                 }
215             }
216
217             // add rule to cache
218             singleton.initDefaults();
219             securityRuleInterface.addNeutronSecurityRule(singleton);
220             if (instances != null) {
221                 for (Object instance : instances) {
222                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
223                     service.neutronSecurityRuleCreated(singleton);
224                 }
225             }
226
227             securityRuleInterface.addNeutronSecurityRule(singleton);
228             if (instances != null) {
229                 for (Object instance : instances) {
230                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
231                     service.neutronSecurityRuleCreated(singleton);
232                 }
233             }
234         } else {
235             List<NeutronSecurityRule> bulk = input.getBulk();
236             Iterator<NeutronSecurityRule> i = bulk.iterator();
237             HashMap<String, NeutronSecurityRule> testMap = new HashMap<String, NeutronSecurityRule>();
238             Object[] instances = ServiceHelper.getGlobalInstances(INeutronSecurityRuleAware.class, this, null);
239             while (i.hasNext()) {
240                 NeutronSecurityRule test = i.next();
241
242                 /*
243                  *  Verify that the security rule doesn't already exist
244                  */
245
246                 if (securityRuleInterface.neutronSecurityRuleExists(test.getSecurityRuleUUID())) {
247                     throw new BadRequestException("Security Rule UUID already exists");
248                 }
249                 if (testMap.containsKey(test.getSecurityRuleUUID())) {
250                     throw new BadRequestException("Security Rule UUID already exists");
251                 }
252                 if (instances != null) {
253                     for (Object instance : instances) {
254                         INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
255                         int status = service.canCreateNeutronSecurityRule(test);
256                         if ((status < 200) || (status > 299)) {
257                             return Response.status(status).build();
258                         }
259                     }
260                 }
261             }
262
263             /*
264              * now, each element of the bulk request can be added to the cache
265              */
266             i = bulk.iterator();
267             while (i.hasNext()) {
268                 NeutronSecurityRule test = i.next();
269                 securityRuleInterface.addNeutronSecurityRule(test);
270                 if (instances != null) {
271                     for (Object instance : instances) {
272                         INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
273                         service.neutronSecurityRuleCreated(test);
274                     }
275                 }
276             }
277         }
278         return Response.status(201).entity(input).build();
279     }
280
281     /**
282      * Updates a Security Rule
283      */
284
285     @Path ("{securityRuleUUID}")
286     @PUT
287     @Produces ({MediaType.APPLICATION_JSON})
288     @Consumes ({MediaType.APPLICATION_JSON})
289     @StatusCodes ({
290             @ResponseCode (code = 200, condition = "Operation successful"),
291             @ResponseCode (code = 400, condition = "Bad Request"),
292             @ResponseCode (code = 401, condition = "Unauthorized"),
293             @ResponseCode (code = 403, condition = "Forbidden"),
294             @ResponseCode (code = 404, condition = "Not Found"),
295             @ResponseCode (code = 501, condition = "Not Implemented")})
296     public Response updateSecurityRule(
297             @PathParam ("securityRuleUUID") String securityRuleUUID, final NeutronSecurityRuleRequest input) {
298         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
299         if (securityRuleInterface == null) {
300             throw new ServiceUnavailableException("Security Rule CRUD Interface "
301                     + RestMessages.SERVICEUNAVAILABLE.toString());
302         }
303
304         /*
305          * verify the Security Rule exists and there is only one delta provided
306          */
307         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
308             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
309         }
310         if (!input.isSingleton()) {
311             throw new BadRequestException("Only singleton edit supported");
312         }
313         NeutronSecurityRule delta = input.getSingleton();
314         NeutronSecurityRule original = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
315
316         /*
317          * updates restricted by Neutron
318          *
319          */
320         if (delta.getSecurityRuleUUID() != null ||
321                 delta.getSecurityRuleDirection() != null ||
322                 delta.getSecurityRuleProtocol() != null ||
323                 delta.getSecurityRulePortMin() != null ||
324                 delta.getSecurityRulePortMax() != null ||
325                 delta.getSecurityRuleEthertype() != null ||
326                 delta.getSecurityRuleRemoteIpPrefix() != null ||
327                 delta.getSecurityRuleGroupID() != null ||
328                 delta.getSecurityRemoteGroupID() != null ||
329                 delta.getSecurityRuleTenantID() != null) {
330             throw new BadRequestException("Attribute edit blocked by Neutron");
331         }
332
333         Object[] instances = ServiceHelper.getGlobalInstances(INeutronSecurityRuleAware.class, this, null);
334         if (instances != null) {
335             for (Object instance : instances) {
336                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
337                 int status = service.canUpdateNeutronSecurityRule(delta, original);
338                 if (status < 200 || status > 299) {
339                     return Response.status(status).build();
340                 }
341             }
342         }
343
344         /*
345          * update the object and return it
346          */
347         securityRuleInterface.updateNeutronSecurityRule(securityRuleUUID, delta);
348         NeutronSecurityRule updatedSecurityRule = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
349         if (instances != null) {
350             for (Object instance : instances) {
351                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
352                 service.neutronSecurityRuleUpdated(updatedSecurityRule);
353             }
354         }
355         return Response.status(200).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
356     }
357
358     /**
359      * Deletes a Security Rule
360      */
361
362     @Path ("{securityRuleUUID}")
363     @DELETE
364     @StatusCodes ({
365             @ResponseCode (code = 204, condition = "No Content"),
366             @ResponseCode (code = 401, condition = "Unauthorized"),
367             @ResponseCode (code = 404, condition = "Not Found"),
368             @ResponseCode (code = 409, condition = "Conflict"),
369             @ResponseCode (code = 501, condition = "Not Implemented")})
370     public Response deleteSecurityRule(
371             @PathParam ("securityRuleUUID") String securityRuleUUID) {
372         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
373         if (securityRuleInterface == null) {
374             throw new ServiceUnavailableException("Security Rule CRUD Interface "
375                     + RestMessages.SERVICEUNAVAILABLE.toString());
376         }
377
378         /*
379          * verify the Security Rule exists and it isn't currently in use
380          */
381         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
382             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
383         }
384         if (securityRuleInterface.neutronSecurityRuleInUse(securityRuleUUID)) {
385             return Response.status(409).build();
386         }
387         NeutronSecurityRule singleton = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
388         Object[] instances = ServiceHelper.getGlobalInstances(INeutronSecurityRuleAware.class, this, null);
389         if (instances != null) {
390             for (Object instance : instances) {
391                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
392                 int status = service.canDeleteNeutronSecurityRule(singleton);
393                 if (status < 200 || status > 299) {
394                     return Response.status(status).build();
395                 }
396             }
397         }
398
399         /*
400          * remove it and return 204 status
401          */
402         securityRuleInterface.removeNeutronSecurityRule(securityRuleUUID);
403         if (instances != null) {
404             for (Object instance : instances) {
405                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
406                 service.neutronSecurityRuleDeleted(singleton);
407             }
408         }
409         return Response.status(204).build();
410     }
411 }