22e0451e302010d0ed5a8f918ef0a709343319dc
[policy/drools-applications.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.drools.server.restful;
22
23 import io.swagger.annotations.Api;
24 import io.swagger.annotations.ApiOperation;
25 import io.swagger.annotations.ApiParam;
26 import io.swagger.annotations.ApiResponse;
27 import io.swagger.annotations.ApiResponses;
28 import java.io.UnsupportedEncodingException;
29 import java.net.URLDecoder;
30 import java.net.URLEncoder;
31 import java.util.List;
32 import java.util.UUID;
33 import java.util.stream.Collectors;
34 import javax.ws.rs.Consumes;
35 import javax.ws.rs.GET;
36 import javax.ws.rs.PUT;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.PathParam;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.Status;
43 import org.onap.policy.aai.AaiManager;
44 import org.onap.policy.aai.util.AaiException;
45 import org.onap.policy.controlloop.ControlLoopException;
46 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
47 import org.onap.policy.controlloop.params.ControlLoopParams;
48 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
49 import org.onap.policy.drools.apps.controlloop.feature.management.ControlLoopManagementFeature;
50 import org.onap.policy.drools.controller.DroolsController;
51 import org.onap.policy.drools.system.PolicyController;
52 import org.onap.policy.drools.system.PolicyEngine;
53 import org.onap.policy.rest.RestManager;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * Telemetry Extensions for Control Loops in the PDP-D.
59  */
60
61 @Path("/policy/pdp")
62 @Produces(MediaType.APPLICATION_JSON)
63 @Consumes(MediaType.APPLICATION_JSON)
64 @Api
65 public class RestControlLoopManager {
66     private static final Logger logger = LoggerFactory.getLogger(RestControlLoopManager.class);
67
68     /**
69      * GET control loops.
70      *
71      * @param controllerName controller name.
72      * @param sessionName session name.
73      * @return list of controller names.
74      */
75     @GET
76     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops")
77     @ApiOperation(value = "Control Loops", notes = "Compact list", responseContainer = "List")
78     @ApiResponses(value = {@ApiResponse(code = 404, message = "Control Loops cannot be found")})
79     public Response controlLoops(
80         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
81         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName) {
82
83         try {
84             List<String> controlLoopNames =
85                 ControlLoopManagementFeature.controlLoops(controllerName, sessionName)
86                     .map(ControlLoopParams::getClosedLoopControlName)
87                     .collect(Collectors.toList());
88
89             return Response.status(Response.Status.OK).entity(controlLoopNames).build();
90         } catch (IllegalArgumentException e) {
91             logger.error("{}", e);
92             return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
93         }
94     }
95
96     /**
97      * GET control loop.
98      *
99      * @param controllerName controller name.
100      * @param sessionName session name.
101      * @param controlLoopName control loop name.
102      * @return control loop.
103      */
104     @GET
105     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops/{controlLoopName}")
106     @ApiOperation( value = "Control Loop", notes = "Control Loop Parameters", responseContainer = "List")
107     @ApiResponses(value = {@ApiResponse(code = 404, message = "The Control Loop cannot be found")})
108     public Response controlLoop(
109         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
110         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName,
111         @ApiParam(value = "Control Loop Name", required = true) @PathParam("controlLoopName") String controlLoopName) {
112
113         try {
114             List<ControlLoopParams> controlLoopParams =
115                 ControlLoopManagementFeature.controlLoops(controllerName, sessionName)
116                     .filter(c -> c.getClosedLoopControlName().equals(controlLoopName))
117                     .collect(Collectors.toList());
118
119             return Response.status(Response.Status.OK).entity(controlLoopParams).build();
120         } catch (IllegalArgumentException e) {
121             logger.error("{}", e);
122             return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
123         }
124     }
125
126     /**
127      * GET operational policy.
128      *
129      * @param controllerName controller name.
130      * @param sessionName session name.
131      * @param controlLoopName control loop name.
132      * @return operational policy.
133      */
134     @GET
135     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops/{controlLoopName}/policy")
136     @Produces(MediaType.TEXT_PLAIN)
137     @ApiOperation( value = "Operational Policy", notes = "The policy is in yaml format")
138     @ApiResponses(value = {@ApiResponse(code = 404, message = "The Control Loop cannot be found"),
139         @ApiResponse(code = 500, message = "The Control Loop has invalid data")})
140     public Response policy(
141         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
142         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName,
143         @ApiParam(value = "Control Loop Name", required = true) @PathParam("controlLoopName") String controlLoopName) {
144
145         try {
146             ControlLoopParams controlLoopParams =
147                 ControlLoopManagementFeature.controlLoops(controllerName, sessionName)
148                     .filter(c -> c.getClosedLoopControlName().equals(controlLoopName))
149                     .findFirst()
150                     .orElse(null);
151
152             if (controlLoopParams == null || controlLoopParams.getControlLoopYaml() == null) {
153                 return Response.status(Response.Status.NOT_FOUND).entity("Policy not found").build();
154             }
155
156             return Response.status(Status.OK)
157                 .entity(URLDecoder.decode(controlLoopParams.getControlLoopYaml(), "UTF-8")).build();
158         } catch (IllegalArgumentException e) {
159             logger.error("{}", e);
160             return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
161         } catch (UnsupportedEncodingException e) {
162             logger.error("{}", e);
163             return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Unreadable Policy").build();
164         }
165     }
166
167     /**
168      * PUT an Operational Policy.
169      *
170      * @param controllerName controller name.
171      * @param sessionName session name.
172      * @param controlLoopName control loop name.
173      * @param policy operational policy.
174      *
175      * @return operational policy.
176      */
177
178     @PUT
179     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops/{controlLoopName}/policy")
180     @Consumes(MediaType.TEXT_PLAIN)
181     @ApiOperation( value = "Add Operational Policy", notes = "The Operational Policy should be syntactically correct")
182     @ApiResponses(value = {@ApiResponse(code = 404, message = "The Control Loop cannot be found"),
183         @ApiResponse(code = 409, message = "The Control Loop exists"),
184         @ApiResponse(code = 412, message = "The Control Loop Name must be matched in the URL"),
185         @ApiResponse(code = 406, message = "The Operational Policy is invalid")})
186     public Response opOffer(
187         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
188         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName,
189         @ApiParam(value = "Control Loop Name", required = true) @PathParam("controlLoopName") String controlLoopName,
190         @ApiParam(value = "Operational Policy", required = true) String policy) {
191
192         try {
193             ControlLoopParams controlLoop =
194                 ControlLoopManagementFeature.controlLoop(controllerName, sessionName, controlLoopName);
195
196             if (controlLoop != null) {
197                 return Response.status(Status.CONFLICT).entity(controlLoop).build();
198             }
199
200             /* validation */
201
202             ControlLoopProcessor controlLoopProcessor = new ControlLoopProcessor(policy);
203
204             if (!controlLoopName.equals(controlLoopProcessor.getControlLoop().getControlLoopName())) {
205                 return Response.status(Status.PRECONDITION_FAILED)
206                     .entity("Control Loop Name in URL does not match the Operational Policy")
207                     .build();
208             }
209
210             DroolsController controller = PolicyController.factory.get(controllerName).getDrools();
211
212             controlLoop = new ControlLoopParams();
213             controlLoop.setPolicyScope(controller.getGroupId());
214             controlLoop.setPolicyName(controller.getArtifactId());
215             controlLoop.setPolicyVersion(controller.getVersion());
216             controlLoop.setClosedLoopControlName(controlLoopName);
217             controlLoop.setControlLoopYaml(URLEncoder.encode(policy, "UTF-8"));
218
219             controller.getContainer().insertAll(controlLoop);
220             return Response.status(Status.OK).entity(controlLoop).build();
221
222         } catch (IllegalArgumentException i) {
223             logger.error("{}", i);
224             return Response.status(Response.Status.NOT_FOUND).entity(i).build();
225         } catch (ControlLoopException | UnsupportedEncodingException e) {
226             logger.error("{}", e);
227             return Response.status(Status.NOT_ACCEPTABLE).entity(e).build();
228         }
229     }
230
231     /**
232      * AAI Custom Query.
233      *
234      * @param vserverId vServer identifier.
235      * @return query results.
236      */
237     @GET
238     @Path("engine/tools/controlloops/aai/customQuery/{vserverId}")
239     @ApiOperation(value = "AAI Custom Query")
240     public Response aaiCustomQuery(@ApiParam(value = "vserver Identifier") String vserverId) {
241         return Response
242             .status(Status.OK)
243             .entity(new AaiManager(new RestManager())
244                 .getCustomQueryResponse(PolicyEngine.manager.getEnvironmentProperty(ControlLoopEventManager.AAI_URL),
245                     PolicyEngine.manager.getEnvironmentProperty(ControlLoopEventManager.AAI_USERNAME_PROPERTY),
246                     PolicyEngine.manager.getEnvironmentProperty(ControlLoopEventManager.AAI_PASS_PROPERTY),
247                     UUID.randomUUID(),
248                     vserverId))
249             .build();
250     }
251
252     /**
253      * AAI Named Query.
254      *
255      * @param vserverId vServer identifier.
256      * @return query results.
257      */
258     @GET
259     @Path("engine/tools/controlloops/aai/namedQuery/{vserverId}")
260     @ApiOperation(value = "AAI Custom Query")
261     public Response aaiNamedQuery(@ApiParam(value = "vserver Identifier") String vserverId) {
262         return Response
263             .status(Status.OK)
264             .entity(new AaiManager(new RestManager())
265                 .postQuery(PolicyEngine.manager.getEnvironmentProperty(ControlLoopEventManager.AAI_URL),
266                     PolicyEngine.manager.getEnvironmentProperty(ControlLoopEventManager.AAI_USERNAME_PROPERTY),
267                     PolicyEngine.manager.getEnvironmentProperty(ControlLoopEventManager.AAI_PASS_PROPERTY),
268                     ControlLoopEventManager.getAaiNqRequest(vserverId),
269                     UUID.randomUUID()))
270             .build();
271     }
272 }