Fixed package directory issues.
[neutron.git] / northbound-api / src / main / java / org / opendaylight / neutron / northbound / api / 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.neutron.northbound.api;
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.neutron.spi.INeutronSecurityGroupCRUD;
33 import org.opendaylight.neutron.spi.INeutronSecurityRuleAware;
34 import org.opendaylight.neutron.spi.INeutronSecurityRuleCRUD;
35 import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
36 import org.opendaylight.neutron.spi.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             @ResponseCode(code = 503, condition = "No providers available") })
75     public Response listRules(
76             // return fields
77             @QueryParam ("fields") List<String> fields,
78             // OpenStack security rule attributes
79             @QueryParam ("id") String querySecurityRuleUUID,
80             @QueryParam ("direction") String querySecurityRuleDirection,
81             @QueryParam ("protocol") String querySecurityRuleProtocol,
82             @QueryParam ("port_range_min") Integer querySecurityRulePortMin,
83             @QueryParam ("port_range_max") Integer querySecurityRulePortMax,
84             @QueryParam ("ethertype") String querySecurityRuleEthertype,
85             @QueryParam ("remote_ip_prefix") String querySecurityRuleIpPrefix,
86             @QueryParam ("remote_group_id") String querySecurityRemoteGroupID,
87             @QueryParam ("security_group_id") String querySecurityRuleGroupID,
88             @QueryParam ("tenant_id") String querySecurityRuleTenantID,
89             @QueryParam ("limit") String limit,
90             @QueryParam ("marker") String marker,
91             @QueryParam ("page_reverse") String pageReverse
92     ) {
93         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
94         if (securityRuleInterface == null) {
95             throw new ServiceUnavailableException("Security Rule CRUD Interface "
96                     + RestMessages.SERVICEUNAVAILABLE.toString());
97         }
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.getSecurityRuleUUID())) &&
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.getSecurityRuleTenantID()))) {
123                 if (fields.size() > 0) {
124                     ans.add(extractFields(nsr, fields));
125                 } else {
126                     ans.add(nsr);
127                 }
128             }
129         }
130         return Response.status(200).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 = 200, condition = "Operation successful"),
143             @ResponseCode (code = 401, condition = "Unauthorized"),
144             @ResponseCode (code = 404, condition = "Not Found"),
145             @ResponseCode(code = 501, condition = "Not Implemented"),
146             @ResponseCode(code = 503, condition = "No providers available") })
147     public Response showSecurityRule(@PathParam ("securityRuleUUID") String securityRuleUUID,
148                                      // return fields
149                                      @QueryParam ("fields") List<String> fields) {
150         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
151         if (securityRuleInterface == null) {
152             throw new ServiceUnavailableException("Security Rule CRUD Interface "
153                     + RestMessages.SERVICEUNAVAILABLE.toString());
154         }
155         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
156             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
157         }
158         if (!fields.isEmpty()) {
159             NeutronSecurityRule ans = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
160             return Response.status(200).entity(
161                     new NeutronSecurityRuleRequest(extractFields(ans, fields))).build();
162         } else {
163             return Response.status(200).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
164         }
165     }
166
167     /**
168      * Creates new Security Rule
169      */
170
171     @POST
172     @Produces ({MediaType.APPLICATION_JSON})
173     @Consumes ({MediaType.APPLICATION_JSON})
174     @StatusCodes ({
175             @ResponseCode (code = 201, condition = "Created"),
176             @ResponseCode (code = 400, condition = "Bad Request"),
177             @ResponseCode (code = 401, condition = "Unauthorized"),
178             @ResponseCode (code = 403, condition = "Forbidden"),
179             @ResponseCode (code = 404, condition = "Not Found"),
180             @ResponseCode (code = 409, condition = "Conflict"),
181             @ResponseCode(code = 501, condition = "Not Implemented"),
182             @ResponseCode(code = 503, condition = "No providers available") })
183     public Response createSecurityRules(final NeutronSecurityRuleRequest input) {
184         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
185         if (securityRuleInterface == null) {
186             throw new ServiceUnavailableException("Security Rule CRUD Interface "
187                     + RestMessages.SERVICEUNAVAILABLE.toString());
188         }
189         INeutronSecurityGroupCRUD securityGroupInterface = NeutronCRUDInterfaces.getINeutronSecurityGroupCRUD(this);
190         if (securityGroupInterface == null) {
191             throw new ServiceUnavailableException("Security Group CRUD Interface "
192                     + RestMessages.SERVICEUNAVAILABLE.toString());
193         }
194
195         /*
196          * Existing entry checks
197         */
198
199         if (input.isSingleton()) {
200             NeutronSecurityRule singleton = input.getSingleton();
201
202             if (securityRuleInterface.neutronSecurityRuleExists(singleton.getSecurityRuleUUID())) {
203                 throw new BadRequestException("Security Rule UUID already exists");
204             }
205             Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
206             if (instances != null) {
207                 if (instances.length > 0) {
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                 } else {
216                     throw new ServiceUnavailableException("No providers registered.  Please try again later");
217                 }
218             } else {
219                 throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
220             }
221
222             // add rule to cache
223             singleton.initDefaults();
224             securityRuleInterface.addNeutronSecurityRule(singleton);
225             if (instances != null) {
226                 for (Object instance : instances) {
227                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
228                     service.neutronSecurityRuleCreated(singleton);
229                 }
230             }
231
232             securityRuleInterface.addNeutronSecurityRule(singleton);
233             if (instances != null) {
234                 for (Object instance : instances) {
235                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
236                     service.neutronSecurityRuleCreated(singleton);
237                 }
238             }
239         } else {
240             List<NeutronSecurityRule> bulk = input.getBulk();
241             Iterator<NeutronSecurityRule> i = bulk.iterator();
242             HashMap<String, NeutronSecurityRule> testMap = new HashMap<String, NeutronSecurityRule>();
243             Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
244             while (i.hasNext()) {
245                 NeutronSecurityRule test = i.next();
246
247                 /*
248                  *  Verify that the security rule doesn't already exist
249                  */
250
251                 if (securityRuleInterface.neutronSecurityRuleExists(test.getSecurityRuleUUID())) {
252                     throw new BadRequestException("Security Rule UUID already exists");
253                 }
254                 if (testMap.containsKey(test.getSecurityRuleUUID())) {
255                     throw new BadRequestException("Security Rule UUID already exists");
256                 }
257                 if (instances != null) {
258                     if (instances.length > 0) {
259                         for (Object instance : instances) {
260                             INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
261                             int status = service.canCreateNeutronSecurityRule(test);
262                             if ((status < 200) || (status > 299)) {
263                                 return Response.status(status).build();
264                             }
265                         }
266                     } else {
267                         throw new ServiceUnavailableException("No providers registered.  Please try again later");
268                     }
269                 } else {
270                     throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
271                 }
272             }
273
274             /*
275              * now, each element of the bulk request can be added to the cache
276              */
277             i = bulk.iterator();
278             while (i.hasNext()) {
279                 NeutronSecurityRule test = i.next();
280                 securityRuleInterface.addNeutronSecurityRule(test);
281                 if (instances != null) {
282                     for (Object instance : instances) {
283                         INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
284                         service.neutronSecurityRuleCreated(test);
285                     }
286                 }
287             }
288         }
289         return Response.status(201).entity(input).build();
290     }
291
292     /**
293      * Updates a Security Rule
294      */
295
296     @Path ("{securityRuleUUID}")
297     @PUT
298     @Produces ({MediaType.APPLICATION_JSON})
299     @Consumes ({MediaType.APPLICATION_JSON})
300     @StatusCodes ({
301             @ResponseCode (code = 200, condition = "Operation successful"),
302             @ResponseCode (code = 400, condition = "Bad Request"),
303             @ResponseCode (code = 401, condition = "Unauthorized"),
304             @ResponseCode (code = 403, condition = "Forbidden"),
305             @ResponseCode (code = 404, condition = "Not Found"),
306             @ResponseCode(code = 501, condition = "Not Implemented"),
307             @ResponseCode(code = 503, condition = "No providers available") })
308     public Response updateSecurityRule(
309             @PathParam ("securityRuleUUID") String securityRuleUUID, final NeutronSecurityRuleRequest input) {
310         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
311         if (securityRuleInterface == null) {
312             throw new ServiceUnavailableException("Security Rule CRUD Interface "
313                     + RestMessages.SERVICEUNAVAILABLE.toString());
314         }
315
316         /*
317          * verify the Security Rule exists and there is only one delta provided
318          */
319         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
320             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
321         }
322         if (!input.isSingleton()) {
323             throw new BadRequestException("Only singleton edit supported");
324         }
325         NeutronSecurityRule delta = input.getSingleton();
326         NeutronSecurityRule original = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
327
328         /*
329          * updates restricted by Neutron
330          *
331          */
332         if (delta.getSecurityRuleUUID() != null ||
333                 delta.getSecurityRuleDirection() != null ||
334                 delta.getSecurityRuleProtocol() != null ||
335                 delta.getSecurityRulePortMin() != null ||
336                 delta.getSecurityRulePortMax() != null ||
337                 delta.getSecurityRuleEthertype() != null ||
338                 delta.getSecurityRuleRemoteIpPrefix() != null ||
339                 delta.getSecurityRuleGroupID() != null ||
340                 delta.getSecurityRemoteGroupID() != null ||
341                 delta.getSecurityRuleTenantID() != null) {
342             throw new BadRequestException("Attribute edit blocked by Neutron");
343         }
344
345         Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
346         if (instances != null) {
347             if (instances.length > 0) {
348                 for (Object instance : instances) {
349                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
350                     int status = service.canUpdateNeutronSecurityRule(delta, original);
351                     if (status < 200 || status > 299) {
352                         return Response.status(status).build();
353                     }
354                 }
355             } else {
356                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
357             }
358         } else {
359             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
360         }
361
362         /*
363          * update the object and return it
364          */
365         securityRuleInterface.updateNeutronSecurityRule(securityRuleUUID, delta);
366         NeutronSecurityRule updatedSecurityRule = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
367         if (instances != null) {
368             for (Object instance : instances) {
369                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
370                 service.neutronSecurityRuleUpdated(updatedSecurityRule);
371             }
372         }
373         return Response.status(200).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
374     }
375
376     /**
377      * Deletes a Security Rule
378      */
379
380     @Path ("{securityRuleUUID}")
381     @DELETE
382     @StatusCodes ({
383             @ResponseCode (code = 204, condition = "No Content"),
384             @ResponseCode (code = 401, condition = "Unauthorized"),
385             @ResponseCode (code = 404, condition = "Not Found"),
386             @ResponseCode (code = 409, condition = "Conflict"),
387             @ResponseCode(code = 501, condition = "Not Implemented"),
388             @ResponseCode(code = 503, condition = "No providers available") })
389     public Response deleteSecurityRule(
390             @PathParam ("securityRuleUUID") String securityRuleUUID) {
391         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
392         if (securityRuleInterface == null) {
393             throw new ServiceUnavailableException("Security Rule CRUD Interface "
394                     + RestMessages.SERVICEUNAVAILABLE.toString());
395         }
396
397         /*
398          * verify the Security Rule exists and it isn't currently in use
399          */
400         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
401             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
402         }
403         if (securityRuleInterface.neutronSecurityRuleInUse(securityRuleUUID)) {
404             return Response.status(409).build();
405         }
406         NeutronSecurityRule singleton = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
407         Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
408         if (instances != null) {
409             if (instances.length > 0) {
410                 for (Object instance : instances) {
411                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
412                     int status = service.canDeleteNeutronSecurityRule(singleton);
413                     if (status < 200 || status > 299) {
414                         return Response.status(status).build();
415                     }
416                 }
417             } else {
418                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
419             }
420         } else {
421             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
422         }
423
424
425         /*
426          * remove it and return 204 status
427          */
428         securityRuleInterface.removeNeutronSecurityRule(securityRuleUUID);
429         if (instances != null) {
430             for (Object instance : instances) {
431                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
432                 service.neutronSecurityRuleDeleted(singleton);
433             }
434         }
435         return Response.status(204).build();
436     }
437 }