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