Merge "Add Holmes to the Backend"
[clamp.git] / src / main / java / org / onap / clamp / clds / client / PolicyClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.client;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Date;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.UUID;
38
39 import javax.ws.rs.BadRequestException;
40
41 import org.onap.clamp.clds.model.prop.ModelProperties;
42 import org.onap.clamp.clds.model.refprop.RefProp;
43 import org.onap.clamp.clds.util.LoggingUtils;
44 import org.onap.policy.api.AttributeType;
45 import org.onap.policy.api.ConfigRequestParameters;
46 import org.onap.policy.api.DeletePolicyCondition;
47 import org.onap.policy.api.DeletePolicyParameters;
48 import org.onap.policy.api.PolicyChangeResponse;
49 import org.onap.policy.api.PolicyConfig;
50 import org.onap.policy.api.PolicyConfigType;
51 import org.onap.policy.api.PolicyEngine;
52 import org.onap.policy.api.PolicyEngineException;
53 import org.onap.policy.api.PolicyParameters;
54 import org.onap.policy.api.PolicyType;
55 import org.onap.policy.api.PushPolicyParameters;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.beans.factory.annotation.Value;
58 import org.springframework.context.ApplicationContext;
59
60 /**
61  * Policy utility methods - specifically, send the policy.
62  */
63 public class PolicyClient {
64
65     protected static final String     POLICY_PREFIX_BASE         = "Config_";
66     protected static final String     POLICY_PREFIX_BRMS_PARAM   = "Config_BRMS_Param_";
67     protected static final String     POLICY_PREFIX_MICROSERVICE = "Config_MS_";
68
69     protected static final String     LOG_POLICY_PREFIX = "Response is ";
70
71     protected static final EELFLogger logger                     = EELFManager.getInstance()
72             .getLogger(PolicyClient.class);
73     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
74
75     @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}")
76     protected String                  cldsPolicyConfigFile;
77
78     @Autowired
79     protected ApplicationContext      appContext;
80
81     @Autowired
82     protected RefProp                 refProp;
83
84     /**
85      * Perform BRMS policy type.
86      *
87      * @param attributes
88      *            A map of attributes
89      * @param prop
90      *            The ModelProperties
91      * @param policyRequestUuid
92      *            PolicyRequest UUID
93      * @return The response message of policy
94      * @throws IOException
95      *             In case of issues with the Stream
96      * @throws PolicyEngineException
97      *             In case of issues with the PolicyEngine class
98      * 
99      */
100     public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
101             String policyRequestUuid) throws PolicyEngineException, IOException {
102
103         PolicyParameters policyParameters = new PolicyParameters();
104
105         // Set Policy Type(Mandatory)
106         policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
107
108         // Set Policy Name(Mandatory)
109         policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
110
111         // documentation says this is options, but when tested, got the
112         // following failure: java.lang.Exception: Policy send failed: PE300 -
113         // Data Issue: No policyDescription given.
114         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
115
116         policyParameters.setAttributes(attributes);
117
118         // Set a random UUID(Mandatory)
119         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
120         String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
121         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
122
123         String policyType = refProp.getStringValue("policy.op.type");
124         push(policyType, prop);
125
126         return rtnMsg;
127     }
128
129     /**
130      * Perform send of microservice policy in JSON.
131      *
132      * @param policyJson
133      *            The policy JSON
134      * @param prop
135      *            The ModelProperties
136      * @param policyRequestUuid
137      *            The policy Request UUID
138      * @return The response message of policy
139      * @throws PolicyEngineException
140      *             In case of issues with the policy engine class creation
141      * @throws IOException
142      *             In case of issue with the Stream
143      */
144     public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid)
145             throws IOException, PolicyEngineException {
146
147         PolicyParameters policyParameters = new PolicyParameters();
148
149         // Set Policy Type
150         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
151         policyParameters.setEcompName(refProp.getStringValue("policy.ecomp.name"));
152         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
153
154         policyParameters.setConfigBody(policyJson);
155         policyParameters.setConfigBodyType(PolicyType.JSON);
156
157         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
158         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
159
160         // Adding this line to clear the policy id from policy name while
161         // pushing to policy engine
162         prop.setPolicyUniqueId("");
163
164         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
165         String policyType = refProp.getStringValue("policy.ms.type");
166         push(policyType, prop);
167
168         return rtnMsg;
169     }
170
171     /**
172      * Perform send of base policy in OTHER type.
173      * 
174      * @param configBody
175      *            The config policy string body
176      * @param prop
177      *            The ModelProperties
178      * @param policyRequestUuid
179      *            The policy request UUID
180      * @return
181      * @throws IOException
182      *             In case of issues with the policy engine class creation
183      * @throws PolicyEngineException
184      *             In case of issue with the Stream
185      */
186     public String sendBasePolicyInOther(String configBody, ModelProperties prop, String policyRequestUuid)
187             throws IOException, PolicyEngineException {
188
189         PolicyParameters policyParameters = new PolicyParameters();
190
191         // Set Policy Type
192         policyParameters.setPolicyConfigType(PolicyConfigType.Base);
193         policyParameters.setEcompName(refProp.getStringValue("policy.ecomp.name"));
194         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
195
196         policyParameters.setConfigBody(configBody);
197         policyParameters.setConfigBodyType(PolicyType.OTHER);
198         policyParameters.setConfigName("HolmesPolicy");
199
200         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
201
202         // Adding this line to clear the policy id from policy name while
203         // pushing to policy engine
204         prop.setPolicyUniqueId("");
205
206         String rtnMsg = send(policyParameters, prop, POLICY_PREFIX_BASE);
207         push(PolicyConfigType.Base.toString(), prop);
208
209         return rtnMsg;
210     }
211
212     /**
213      * Perform send of policy.
214      *
215      * @param policyParameters
216      *            The PolicyParameters
217      * @param prop
218      *            The ModelProperties
219      * @return THe response message of Policy
220      * @throws IOException
221      *             In case of issues with the Stream
222      * @throws PolicyEngineException
223      *             In case of issue when creating PolicyEngine class
224      */
225     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix)
226             throws IOException, PolicyEngineException {
227         // Verify whether it is triggered by Validation Test button from UI
228         if (prop.isTest()) {
229             return "send not executed for test action";
230         }
231
232         PolicyEngine policyEngine = new PolicyEngine(
233                 appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
234
235         // API method to create or update Policy.
236         PolicyChangeResponse response = null;
237         String responseMessage = "";
238         Date startTime = new Date();
239         try {
240             List<Integer> versions = getVersions(policyNamePrefix, prop);
241             if (versions.isEmpty()) {
242                 LoggingUtils.setTargetContext("Policy", "createPolicy");
243                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
244                 response = policyEngine.createPolicy(policyParameters);
245                 responseMessage = response.getResponseMessage();
246             } else {
247                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
248                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
249                 response = policyEngine.updatePolicy(policyParameters);
250                 responseMessage = response.getResponseMessage();
251             }
252         } catch (Exception e) {
253             logger.error("Exception occurred during policy communication", e);
254         }
255         logger.info(LOG_POLICY_PREFIX + responseMessage);
256
257         LoggingUtils.setTimeContext(startTime, new Date());
258
259         if (response != null && response.getResponseCode() == 200) {
260             logger.info("Policy send successful");
261             metricsLogger.info("Policy send success");
262         } else {
263             logger.warn("Policy send failed: " + responseMessage);
264             metricsLogger.info("Policy send failure");
265             throw new BadRequestException("Policy send failed: " + responseMessage);
266         }
267
268         return responseMessage;
269     }
270
271     /**
272      * Format and send push of policy.
273      *
274      * @param policyType
275      *            The policy Type
276      * @param prop
277      *            The ModelProperties
278      * @return The response message of policy
279      * @throws IOException
280      *             In case of issues with the stream
281      * @throws PolicyEngineException
282      *             In case of issues with the PolicyEngine creation
283      */
284     protected String push(String policyType, ModelProperties prop) throws PolicyEngineException, IOException {
285         // Verify whether it is triggered by Validation Test button from UI
286         if (prop.isTest()) {
287             return "push not executed for test action";
288         }
289
290         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
291
292         // Parameter arguments
293         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
294             pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
295         } else {
296             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
297         }
298         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
299
300         pushPolicyParameters.setPolicyType(policyType);
301         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
302         pushPolicyParameters.setRequestID(null);
303
304         PolicyEngine policyEngine = new PolicyEngine(
305                 appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
306
307         // API method to create or update Policy.
308         PolicyChangeResponse response = null;
309         String responseMessage = "";
310         try {
311             logger.info("Attempting to push policy...");
312             response = policyEngine.pushPolicy(pushPolicyParameters);
313             responseMessage = response.getResponseMessage();
314         } catch (Exception e) {
315             logger.error("Exception occurred during policy communication", e);
316         }
317         logger.info(LOG_POLICY_PREFIX + responseMessage);
318
319         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
320             logger.info("Policy push successful");
321         } else {
322             logger.warn("Policy push failed: " + responseMessage);
323             throw new BadRequestException("Policy push failed: " + responseMessage);
324         }
325
326         return responseMessage;
327     }
328
329     /**
330      * Use Get Config Policy API to retrieve the versions for a policy. Return
331      * versions in sorted order. Return empty list if none found.
332      *
333      * @param policyNamePrefix
334      *            The Policy Name Prefix
335      * @param prop
336      *            The ModelProperties
337      * @return The response message from policy
338      * @throws IOException
339      *             In case of issues with the stream
340      * @throws PolicyEngineException
341      *             In case of issues with the PolicyEngine creation
342      */
343     protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop)
344             throws PolicyEngineException, IOException {
345
346         ArrayList<Integer> versions = new ArrayList<>();
347         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
348         String policyName = "";
349
350         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
351             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
352         } else {
353             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
354         }
355
356         logger.info("policyName=" + policyName);
357         configRequestParameters.setPolicyName(policyName);
358
359         PolicyEngine policyEngine = new PolicyEngine(
360                 appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
361
362         try {
363             Collection<PolicyConfig> response = policyEngine.getConfig(configRequestParameters);
364             Iterator<PolicyConfig> itrResp = response.iterator();
365
366             while (itrResp.hasNext()) {
367                 PolicyConfig policyConfig = itrResp.next();
368                 try {
369                     Integer version = new Integer(policyConfig.getPolicyVersion());
370                     versions.add(version);
371                 } catch (Exception e) {
372                     // just print warning - if n;o policies, version may be null
373                     logger.warn("Failed to parse due to an exception policyConfig.getPolicyVersion()="
374                             + policyConfig.getPolicyVersion(), e);
375                 }
376             }
377             Collections.sort(versions);
378             logger.info("Policy versions.size()=" + versions.size());
379         } catch (Exception e) {
380             // just print warning - if no policy version found
381             logger.warn("warning: policy not found...policy name - " + policyName, e);
382         }
383
384         return versions;
385     }
386
387     /**
388      * Format and send delete Micro Service requests to Policy.
389      *
390      * @param prop
391      *            The ModelProperties
392      * @return The response message from Policy
393      * @throws IOException
394      *             In case of issues with the stream
395      * @throws PolicyEngineException
396      *             In case of issues with the PolicyEngine creation
397      */
398     public String deleteMicrosService(ModelProperties prop) throws PolicyEngineException, IOException {
399         String policyType = refProp.getStringValue("policy.ms.type");
400         return deletePolicy(prop, policyType);
401     }
402
403     /**
404      * This method delete the Base policy.
405      *
406      * @param prop The model Properties
407      * @return A string with the answer from policy
408      * @throws PolicyEngineException In case of issues with the policy engine
409      * @throws IOException In case of issues with the stream
410      */
411     public String deleteBasePolicy(ModelProperties prop) throws PolicyEngineException, IOException {
412         return deletePolicy(prop, PolicyConfigType.Base.toString());
413     }
414
415     /**
416      * Format and send delete BRMS requests to Policy.
417      *
418      * @param prop
419      *            The ModelProperties
420      * @return The response message from policy
421      * @throws IOException
422      *             In case of issues with the stream
423      * @throws PolicyEngineException
424      *             In case of issues with the PolicyEngine creation
425      */
426     public String deleteBrms(ModelProperties prop) throws PolicyEngineException, IOException {
427         String policyType = refProp.getStringValue("policy.op.type");
428         return deletePolicy(prop, policyType);
429     }
430
431     /**
432      * Format and send delete PAP and PDP requests to Policy.
433      *
434      * @param prop
435      *            The ModelProperties
436      *
437      * @return The response message from policy
438      * @throws IOException
439      *             in case of issues with the Stream
440      * @throws PolicyEngineException
441      *             In case of issues with the PolicyEngine class creation
442      */
443     protected String deletePolicy(ModelProperties prop, String policyType) throws PolicyEngineException, IOException {
444         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
445
446         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
447             deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
448         } else {
449             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
450         }
451         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
452         deletePolicyParameters.setPolicyComponent("PDP");
453         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
454         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
455         deletePolicyParameters.setPolicyType(policyType);
456         // send delete request
457         String responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
458
459         logger.info("Deleting policy from PAP...");
460         deletePolicyParameters.setPolicyComponent("PAP");
461         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
462
463         // send delete request
464         responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
465
466         return responseMessage;
467     }
468
469     /**
470      * Send delete request to Policy.
471      *
472      * @param deletePolicyParameters
473      *            The DeletePolicyParameters
474      * @param prop
475      *            The ModelProperties
476      * @return The response message from policy
477      * @throws IOException
478      *             In case of issues with the stream
479      * @throws PolicyEngineException
480      *             In case of issues with PolicyEngine class creation
481      */
482     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop)
483             throws PolicyEngineException, IOException {
484         // Verify whether it is triggered by Validation Test button from UI
485         if (prop.isTest()) {
486             return "delete not executed for test action";
487         }
488         PolicyEngine policyEngine = new PolicyEngine(
489                 appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
490
491         // API method to create or update Policy.
492         PolicyChangeResponse response = null;
493         String responseMessage = "";
494         try {
495             logger.info("Attempting to delete policy...");
496             response = policyEngine.deletePolicy(deletePolicyParameters);
497             responseMessage = response.getResponseMessage();
498         } catch (Exception e) {
499             logger.error("Exception occurred during policy communnication", e);
500         }
501         logger.info(LOG_POLICY_PREFIX + responseMessage);
502
503         if (response != null && response.getResponseCode() == 200) {
504             logger.info("Policy delete successful");
505         } else {
506             logger.warn("Policy delete failed: " + responseMessage);
507             throw new BadRequestException("Policy delete failed: " + responseMessage);
508         }
509
510         return responseMessage;
511     }
512 }