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