08b218dd6c4d5f02d4d7c29f6dadcfc71d0320ae
[policy/drools-applications.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2018-2019 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.controlloop.ControlLoopException;
45 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
46 import org.onap.policy.controlloop.params.ControlLoopParams;
47 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
48 import org.onap.policy.drools.apps.controlloop.feature.management.ControlLoopManagementFeature;
49 import org.onap.policy.drools.controller.DroolsController;
50 import org.onap.policy.drools.system.PolicyControllerConstants;
51 import org.onap.policy.drools.system.PolicyEngineConstants;
52 import org.onap.policy.rest.RestManager;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * Telemetry Extensions for Control Loops in the PDP-D.
58  */
59
60 @Path("/policy/pdp")
61 @Produces(MediaType.APPLICATION_JSON)
62 @Consumes(MediaType.APPLICATION_JSON)
63 @Api
64 public class RestControlLoopManager {
65     private static final Logger logger = LoggerFactory.getLogger(RestControlLoopManager.class);
66
67     /**
68      * GET control loops.
69      *
70      * @param controllerName controller name.
71      * @param sessionName session name.
72      * @return list of controller names.
73      */
74     @GET
75     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops")
76     @ApiOperation(value = "Control Loops", notes = "Compact list", responseContainer = "List")
77     @ApiResponses(value = {@ApiResponse(code = 404, message = "Control Loops cannot be found")})
78     public Response controlLoops(
79         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
80         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName) {
81
82         try {
83             List<String> controlLoopNames =
84                 ControlLoopManagementFeature.controlLoops(controllerName, sessionName)
85                     .map(ControlLoopParams::getClosedLoopControlName)
86                     .collect(Collectors.toList());
87
88             return Response.status(Response.Status.OK).entity(controlLoopNames).build();
89         } catch (IllegalArgumentException e) {
90             logger.error("{}", e);
91             return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
92         }
93     }
94
95     /**
96      * GET control loop.
97      *
98      * @param controllerName controller name.
99      * @param sessionName session name.
100      * @param controlLoopName control loop name.
101      * @return control loop.
102      */
103     @GET
104     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops/{controlLoopName}")
105     @ApiOperation( value = "Control Loop", notes = "Control Loop Parameters", responseContainer = "List")
106     @ApiResponses(value = {@ApiResponse(code = 404, message = "The Control Loop cannot be found")})
107     public Response controlLoop(
108         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
109         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName,
110         @ApiParam(value = "Control Loop Name", required = true) @PathParam("controlLoopName") String controlLoopName) {
111
112         try {
113             List<ControlLoopParams> controlLoopParams =
114                 ControlLoopManagementFeature.controlLoops(controllerName, sessionName)
115                     .filter(c -> c.getClosedLoopControlName().equals(controlLoopName))
116                     .collect(Collectors.toList());
117
118             return Response.status(Response.Status.OK).entity(controlLoopParams).build();
119         } catch (IllegalArgumentException e) {
120             logger.error("{}", e);
121             return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
122         }
123     }
124
125     /**
126      * GET operational policy.
127      *
128      * @param controllerName controller name.
129      * @param sessionName session name.
130      * @param controlLoopName control loop name.
131      * @return operational policy.
132      */
133     @GET
134     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops/{controlLoopName}/policy")
135     @Produces(MediaType.TEXT_PLAIN)
136     @ApiOperation( value = "Operational Policy", notes = "The policy is in yaml format")
137     @ApiResponses(value = {@ApiResponse(code = 404, message = "The Control Loop cannot be found"),
138         @ApiResponse(code = 500, message = "The Control Loop has invalid data")})
139     public Response policy(
140         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
141         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName,
142         @ApiParam(value = "Control Loop Name", required = true) @PathParam("controlLoopName") String controlLoopName) {
143
144         try {
145             ControlLoopParams controlLoopParams =
146                 ControlLoopManagementFeature.controlLoops(controllerName, sessionName)
147                     .filter(c -> c.getClosedLoopControlName().equals(controlLoopName))
148                     .findFirst()
149                     .orElse(null);
150
151             if (controlLoopParams == null || controlLoopParams.getControlLoopYaml() == null) {
152                 return Response.status(Response.Status.NOT_FOUND).entity("Policy not found").build();
153             }
154
155             return Response.status(Status.OK)
156                 .entity(URLDecoder.decode(controlLoopParams.getControlLoopYaml(), "UTF-8")).build();
157         } catch (IllegalArgumentException e) {
158             logger.error("{}", e);
159             return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
160         } catch (UnsupportedEncodingException e) {
161             logger.error("{}", e);
162             return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Unreadable Policy").build();
163         }
164     }
165
166     /**
167      * PUT an Operational Policy.
168      *
169      * @param controllerName controller name.
170      * @param sessionName session name.
171      * @param controlLoopName control loop name.
172      * @param policy operational policy.
173      *
174      * @return operational policy.
175      */
176
177     @PUT
178     @Path("engine/controllers/{controller}/drools/facts/{session}/controlloops/{controlLoopName}/policy")
179     @Consumes(MediaType.TEXT_PLAIN)
180     @ApiOperation( value = "Add Operational Policy", notes = "The Operational Policy should be syntactically correct")
181     @ApiResponses(value = {@ApiResponse(code = 404, message = "The Control Loop cannot be found"),
182         @ApiResponse(code = 409, message = "The Control Loop exists"),
183         @ApiResponse(code = 412, message = "The Control Loop Name must be matched in the URL"),
184         @ApiResponse(code = 406, message = "The Operational Policy is invalid")})
185     public Response opOffer(
186         @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName,
187         @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName,
188         @ApiParam(value = "Control Loop Name", required = true) @PathParam("controlLoopName") String controlLoopName,
189         @ApiParam(value = "Operational Policy", required = true) String policy) {
190
191         try {
192             ControlLoopParams controlLoop =
193                 ControlLoopManagementFeature.controlLoop(controllerName, sessionName, controlLoopName);
194
195             if (controlLoop != null) {
196                 return Response.status(Status.CONFLICT).entity(controlLoop).build();
197             }
198
199             /* validation */
200
201             ControlLoopProcessor controlLoopProcessor = new ControlLoopProcessor(policy);
202
203             if (!controlLoopName.equals(controlLoopProcessor.getControlLoop().getControlLoopName())) {
204                 return Response.status(Status.PRECONDITION_FAILED)
205                     .entity("Control Loop Name in URL does not match the Operational Policy")
206                     .build();
207             }
208
209             DroolsController controller = PolicyControllerConstants.getFactory().get(controllerName).getDrools();
210
211             controlLoop = new ControlLoopParams();
212             controlLoop.setPolicyScope(controller.getGroupId());
213             controlLoop.setPolicyName(controller.getArtifactId());
214             controlLoop.setPolicyVersion(controller.getVersion());
215             controlLoop.setClosedLoopControlName(controlLoopName);
216             controlLoop.setControlLoopYaml(URLEncoder.encode(policy, "UTF-8"));
217
218             controller.getContainer().insertAll(controlLoop);
219             return Response.status(Status.OK).entity(controlLoop).build();
220
221         } catch (IllegalArgumentException i) {
222             logger.error("{}", i);
223             return Response.status(Response.Status.NOT_FOUND).entity(i).build();
224         } catch (ControlLoopException | UnsupportedEncodingException e) {
225             logger.error("{}", e);
226             return Response.status(Status.NOT_ACCEPTABLE).entity(e).build();
227         }
228     }
229
230     /**
231      * AAI Custom Query.
232      *
233      * @param vserverId vServer identifier.
234      * @return query results.
235      */
236     @GET
237     @Path("engine/tools/controlloops/aai/customQuery/{vserverId}")
238     @ApiOperation(value = "AAI Custom Query")
239     public Response aaiCustomQuery(@ApiParam(value = "vserver Identifier") String vserverId) {
240         return Response
241             .status(Status.OK)
242             .entity(new AaiManager(new RestManager())
243                 .getCustomQueryResponse(
244                     PolicyEngineConstants.getManager()
245                                     .getEnvironmentProperty(ControlLoopEventManager.AAI_URL),
246                     PolicyEngineConstants.getManager().getEnvironmentProperty(
247                                     ControlLoopEventManager.AAI_USERNAME_PROPERTY),
248                     PolicyEngineConstants.getManager().getEnvironmentProperty(
249                                     ControlLoopEventManager.AAI_PASS_PROPERTY),
250                     UUID.randomUUID(),
251                     vserverId))
252             .build();
253     }
254
255     /**
256      * AAI Named Query.
257      *
258      * @param vserverId vServer identifier.
259      * @return query results.
260      */
261     @GET
262     @Path("engine/tools/controlloops/aai/namedQuery/{vserverId}")
263     @ApiOperation(value = "AAI Custom Query")
264     public Response aaiNamedQuery(@ApiParam(value = "vserver Identifier") String vserverId) {
265         return Response
266             .status(Status.OK)
267             .entity(new AaiManager(new RestManager())
268                 .postQuery(
269                     PolicyEngineConstants.getManager()
270                                     .getEnvironmentProperty(ControlLoopEventManager.AAI_URL),
271                     PolicyEngineConstants.getManager().getEnvironmentProperty(
272                                     ControlLoopEventManager.AAI_USERNAME_PROPERTY),
273                     PolicyEngineConstants.getManager().getEnvironmentProperty(
274                                     ControlLoopEventManager.AAI_PASS_PROPERTY),
275                     ControlLoopEventManager.getAaiNqRequest(vserverId),
276                     UUID.randomUUID()))
277             .build();
278     }
279 }