Merge "Add md-transcribing for Port."
[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         } else {
232             List<NeutronSecurityRule> bulk = input.getBulk();
233             Iterator<NeutronSecurityRule> i = bulk.iterator();
234             HashMap<String, NeutronSecurityRule> testMap = new HashMap<String, NeutronSecurityRule>();
235             Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
236             while (i.hasNext()) {
237                 NeutronSecurityRule test = i.next();
238
239                 /*
240                  *  Verify that the security rule doesn't already exist
241                  */
242
243                 if (securityRuleInterface.neutronSecurityRuleExists(test.getSecurityRuleUUID())) {
244                     throw new BadRequestException("Security Rule UUID already exists");
245                 }
246                 if (testMap.containsKey(test.getSecurityRuleUUID())) {
247                     throw new BadRequestException("Security Rule UUID already exists");
248                 }
249                 if (instances != null) {
250                     if (instances.length > 0) {
251                         for (Object instance : instances) {
252                             INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
253                             int status = service.canCreateNeutronSecurityRule(test);
254                             if ((status < 200) || (status > 299)) {
255                                 return Response.status(status).build();
256                             }
257                         }
258                     } else {
259                         throw new ServiceUnavailableException("No providers registered.  Please try again later");
260                     }
261                 } else {
262                     throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
263                 }
264             }
265
266             /*
267              * now, each element of the bulk request can be added to the cache
268              */
269             i = bulk.iterator();
270             while (i.hasNext()) {
271                 NeutronSecurityRule test = i.next();
272                 securityRuleInterface.addNeutronSecurityRule(test);
273                 if (instances != null) {
274                     for (Object instance : instances) {
275                         INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
276                         service.neutronSecurityRuleCreated(test);
277                     }
278                 }
279             }
280         }
281         return Response.status(201).entity(input).build();
282     }
283
284     /**
285      * Updates a Security Rule
286      */
287
288     @Path ("{securityRuleUUID}")
289     @PUT
290     @Produces ({MediaType.APPLICATION_JSON})
291     @Consumes ({MediaType.APPLICATION_JSON})
292     @StatusCodes ({
293             @ResponseCode (code = 200, condition = "Operation successful"),
294             @ResponseCode (code = 400, condition = "Bad Request"),
295             @ResponseCode (code = 401, condition = "Unauthorized"),
296             @ResponseCode (code = 403, condition = "Forbidden"),
297             @ResponseCode (code = 404, condition = "Not Found"),
298             @ResponseCode(code = 501, condition = "Not Implemented"),
299             @ResponseCode(code = 503, condition = "No providers available") })
300     public Response updateSecurityRule(
301             @PathParam ("securityRuleUUID") String securityRuleUUID, final NeutronSecurityRuleRequest input) {
302         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
303         if (securityRuleInterface == null) {
304             throw new ServiceUnavailableException("Security Rule CRUD Interface "
305                     + RestMessages.SERVICEUNAVAILABLE.toString());
306         }
307
308         /*
309          * verify the Security Rule exists and there is only one delta provided
310          */
311         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
312             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
313         }
314         if (!input.isSingleton()) {
315             throw new BadRequestException("Only singleton edit supported");
316         }
317         NeutronSecurityRule delta = input.getSingleton();
318         NeutronSecurityRule original = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
319
320         /*
321          * updates restricted by Neutron
322          *
323          */
324         if (delta.getSecurityRuleUUID() != null ||
325                 delta.getSecurityRuleDirection() != null ||
326                 delta.getSecurityRuleProtocol() != null ||
327                 delta.getSecurityRulePortMin() != null ||
328                 delta.getSecurityRulePortMax() != null ||
329                 delta.getSecurityRuleEthertype() != null ||
330                 delta.getSecurityRuleRemoteIpPrefix() != null ||
331                 delta.getSecurityRuleGroupID() != null ||
332                 delta.getSecurityRemoteGroupID() != null ||
333                 delta.getSecurityRuleTenantID() != null) {
334             throw new BadRequestException("Attribute edit blocked by Neutron");
335         }
336
337         Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
338         if (instances != null) {
339             if (instances.length > 0) {
340                 for (Object instance : instances) {
341                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
342                     int status = service.canUpdateNeutronSecurityRule(delta, original);
343                     if (status < 200 || status > 299) {
344                         return Response.status(status).build();
345                     }
346                 }
347             } else {
348                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
349             }
350         } else {
351             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
352         }
353
354         /*
355          * update the object and return it
356          */
357         securityRuleInterface.updateNeutronSecurityRule(securityRuleUUID, delta);
358         NeutronSecurityRule updatedSecurityRule = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
359         if (instances != null) {
360             for (Object instance : instances) {
361                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
362                 service.neutronSecurityRuleUpdated(updatedSecurityRule);
363             }
364         }
365         return Response.status(200).entity(new NeutronSecurityRuleRequest(securityRuleInterface.getNeutronSecurityRule(securityRuleUUID))).build();
366     }
367
368     /**
369      * Deletes a Security Rule
370      */
371
372     @Path ("{securityRuleUUID}")
373     @DELETE
374     @StatusCodes ({
375             @ResponseCode (code = 204, condition = "No Content"),
376             @ResponseCode (code = 401, condition = "Unauthorized"),
377             @ResponseCode (code = 404, condition = "Not Found"),
378             @ResponseCode (code = 409, condition = "Conflict"),
379             @ResponseCode(code = 501, condition = "Not Implemented"),
380             @ResponseCode(code = 503, condition = "No providers available") })
381     public Response deleteSecurityRule(
382             @PathParam ("securityRuleUUID") String securityRuleUUID) {
383         INeutronSecurityRuleCRUD securityRuleInterface = NeutronCRUDInterfaces.getINeutronSecurityRuleCRUD(this);
384         if (securityRuleInterface == null) {
385             throw new ServiceUnavailableException("Security Rule CRUD Interface "
386                     + RestMessages.SERVICEUNAVAILABLE.toString());
387         }
388
389         /*
390          * verify the Security Rule exists and it isn't currently in use
391          */
392         if (!securityRuleInterface.neutronSecurityRuleExists(securityRuleUUID)) {
393             throw new ResourceNotFoundException("Security Rule UUID does not exist.");
394         }
395         if (securityRuleInterface.neutronSecurityRuleInUse(securityRuleUUID)) {
396             return Response.status(409).build();
397         }
398         NeutronSecurityRule singleton = securityRuleInterface.getNeutronSecurityRule(securityRuleUUID);
399         Object[] instances = NeutronUtil.getInstances(INeutronSecurityRuleAware.class, this);
400         if (instances != null) {
401             if (instances.length > 0) {
402                 for (Object instance : instances) {
403                     INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
404                     int status = service.canDeleteNeutronSecurityRule(singleton);
405                     if (status < 200 || status > 299) {
406                         return Response.status(status).build();
407                     }
408                 }
409             } else {
410                 throw new ServiceUnavailableException("No providers registered.  Please try again later");
411             }
412         } else {
413             throw new ServiceUnavailableException("Couldn't get providers list.  Please try again later");
414         }
415
416
417         /*
418          * remove it and return 204 status
419          */
420         securityRuleInterface.removeNeutronSecurityRule(securityRuleUUID);
421         if (instances != null) {
422             for (Object instance : instances) {
423                 INeutronSecurityRuleAware service = (INeutronSecurityRuleAware) instance;
424                 service.neutronSecurityRuleDeleted(singleton);
425             }
426         }
427         return Response.status(204).build();
428     }
429 }