Improve logs in Policy methods.
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / policy / PolicyClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.req.policy;
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.List;
35 import java.util.Map;
36 import java.util.UUID;
37
38 import javax.ws.rs.BadRequestException;
39
40 import org.onap.clamp.clds.exception.policy.PolicyClientException;
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.PolicyConfigException;
51 import org.onap.policy.api.PolicyConfigType;
52 import org.onap.policy.api.PolicyEngine;
53 import org.onap.policy.api.PolicyEngineException;
54 import org.onap.policy.api.PolicyParameters;
55 import org.onap.policy.api.PolicyType;
56 import org.onap.policy.api.PushPolicyParameters;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.beans.factory.annotation.Value;
59 import org.springframework.context.ApplicationContext;
60
61 /**
62  * Policy utility methods - specifically, send the policy.
63  */
64 public class PolicyClient {
65     protected static final String     POLICY_PREFIX_BASE            = "Config_";
66     protected static final String     LOG_POLICY_PREFIX             = "Response is ";
67     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
68     protected static final EELFLogger metricsLogger                 = EELFManager.getInstance().getMetricsLogger();
69     protected static final String     POLICY_MSTYPE_PROPERTY_NAME   = "policy.ms.type";
70     protected static final String     POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
71     @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}")
72     protected String                  cldsPolicyConfigFile;
73     @Autowired
74     protected ApplicationContext      appContext;
75     @Autowired
76     protected RefProp                 refProp;
77
78     /**
79      * Perform BRMS policy type.
80      *
81      * @param attributes
82      *            A map of attributes
83      * @param prop
84      *            The ModelProperties
85      * @param policyRequestUuid
86      *            PolicyRequest UUID
87      * @return The response message of policy
88      */
89     public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
90             String policyRequestUuid) {
91         PolicyParameters policyParameters = new PolicyParameters();
92         // Set Policy Type(Mandatory)
93         policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
94         // Set Policy Name(Mandatory)
95         policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
96         // documentation says this is options, but when tested, got the
97         // following failure: java.lang.Exception: Policy send failed: PE300 -
98         // Data Issue: No policyDescription given.
99         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
100         policyParameters.setAttributes(attributes);
101         // Set a random UUID(Mandatory)
102         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
103         String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
104         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
105         String policyType = refProp.getStringValue("policy.op.type");
106         push(policyType, prop);
107         return rtnMsg;
108     }
109
110     /**
111      * Perform send of microservice policy in JSON.
112      *
113      * @param policyJson
114      *            The policy JSON
115      * @param prop
116      *            The ModelProperties
117      * @param policyRequestUuid
118      *            The policy Request UUID
119      * @return The response message of policy
120      */
121     public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
122         PolicyParameters policyParameters = new PolicyParameters();
123         // Set Policy Type
124         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
125         policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
126         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
127         policyParameters.setConfigBody(policyJson);
128         policyParameters.setConfigBodyType(PolicyType.JSON);
129         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
130         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
131         // Adding this line to clear the policy id from policy name while
132         // pushing to policy engine
133         prop.setPolicyUniqueId("");
134         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
135         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
136         push(policyType, prop);
137         return rtnMsg;
138     }
139
140     /**
141      * Perform send of base policy in OTHER type.
142      *
143      * @param configBody
144      *            The config policy string body
145      * @param configPolicyName
146      *            The config policy name of the component that has been
147      *            pre-deployed in DCAE
148      * @param prop
149      *            The ModelProperties
150      * @param policyRequestUuid
151      *            The policy request UUID
152      * @return The answer from policy call
153      */
154     public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
155             String policyRequestUuid) {
156         PolicyParameters policyParameters = new PolicyParameters();
157         // Set Policy Type
158         policyParameters.setPolicyConfigType(PolicyConfigType.Base);
159         policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
160         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
161         policyParameters.setConfigBody(configBody);
162         policyParameters.setConfigBodyType(PolicyType.OTHER);
163         policyParameters.setConfigName("HolmesPolicy");
164         policyParameters.setPolicyName(configPolicyName);
165         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
166         // Adding this line to clear the policy id from policy name while
167         // pushing to policy engine
168         prop.setPolicyUniqueId("");
169         String rtnMsg = send(policyParameters, prop, POLICY_PREFIX_BASE);
170         push(PolicyConfigType.Base.toString(), prop);
171         return rtnMsg;
172     }
173
174     /**
175      * Perform send of Microservice policy in OTHER type.
176      * 
177      * @param configBody
178      *            The config policy string body
179      * @param prop
180      *            The ModelProperties
181      * @return The answer from policy call
182      */
183     public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
184         PolicyParameters policyParameters = new PolicyParameters();
185         // Set Policy Type
186         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
187         policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
188         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
189         policyParameters.setConfigBody(configBody);
190         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
191         // Adding this line to clear the policy id from policy name while
192         // pushing to policy engine
193         prop.setPolicyUniqueId("");
194         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
195         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
196         push(policyType, prop);
197         return rtnMsg;
198     }
199
200     /**
201      * Perform send of policy.
202      *
203      * @param policyParameters
204      *            The PolicyParameters
205      * @param prop
206      *            The ModelProperties
207      * @return The response message of Policy
208      */
209     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
210         // Verify whether it is triggered by Validation Test button from UI
211         if (prop.isTestOnly()) {
212             return "send not executed for test action";
213         }
214         // API method to create or update Policy.
215         PolicyChangeResponse response = null;
216         String responseMessage = "";
217         Date startTime = new Date();
218         try {
219             List<Integer> versions = getVersions(policyNamePrefix, prop);
220             if (versions.isEmpty()) {
221                 LoggingUtils.setTargetContext("Policy", "createPolicy");
222                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
223                 response = getPolicyEngine().createPolicy(policyParameters);
224                 responseMessage = response.getResponseMessage();
225             } else {
226                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
227                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
228                 response = getPolicyEngine().updatePolicy(policyParameters);
229                 responseMessage = response.getResponseMessage();
230             }
231         } catch (Exception e) {
232                 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
233                 LoggingUtils.setErrorContext("900", "Policy send error");
234             logger.error("Exception occurred during policy communication", e);
235             throw new PolicyClientException("Exception while communicating with Policy", e);
236         }
237         logger.info(LOG_POLICY_PREFIX + responseMessage);
238         LoggingUtils.setTimeContext(startTime, new Date());
239         if (response.getResponseCode() == 200) {
240                 LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
241             logger.info("Policy send successful");
242             metricsLogger.info("Policy send success");
243         } else {
244                 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
245             logger.warn("Policy send failed: " + responseMessage);
246             metricsLogger.info("Policy send failure");
247             throw new BadRequestException("Policy send failed: " + responseMessage);
248         }
249         return responseMessage;
250     }
251
252     /**
253      * Format and send push of policy.
254      *
255      * @param policyType
256      *            The policy Type
257      * @param prop
258      *            The ModelProperties
259      * @return The response message of policy
260      */
261     protected String push(String policyType, ModelProperties prop) {
262         // Verify whether it is triggered by Validation Test button from UI
263         if (prop.isTestOnly()) {
264             return "push not executed for test action";
265         }
266         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
267         // Parameter arguments
268         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
269             pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
270         } else {
271             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
272         }
273         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
274         pushPolicyParameters.setPolicyType(policyType);
275         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
276         pushPolicyParameters.setRequestID(null);
277         // API method to create or update Policy.
278         PolicyChangeResponse response;
279         String responseMessage = "";
280         try {
281                 LoggingUtils.setTargetContext("Policy", "pushPolicy");
282             logger.info("Attempting to push policy...");
283             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
284             if (response != null) {
285                 responseMessage = response.getResponseMessage();
286             }
287         } catch (Exception e) {
288                 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
289             LoggingUtils.setErrorContext("900", "Policy push error");
290             logger.error("Exception occurred during policy communication", e);
291             throw new PolicyClientException("Exception while communicating with Policy", e);
292         }
293         logger.info(LOG_POLICY_PREFIX + responseMessage);
294         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
295                 LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
296             logger.info("Policy push successful");
297             metricsLogger.info("Policy push success");
298         } else {
299                 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
300             logger.warn("Policy push failed: " + responseMessage);
301             metricsLogger.info("Policy push failure");
302             throw new BadRequestException("Policy push failed: " + responseMessage);
303         }
304         return responseMessage;
305     }
306
307     /**
308      * Use Get Config Policy API to retrieve the versions for a policy. Return
309      * versions in sorted order. Return empty list if none found.
310      *
311      * @param policyNamePrefix
312      *            The Policy Name Prefix
313      * @param prop
314      *            The ModelProperties
315      * @return The response message from policy
316      * @throws PolicyConfigException
317      *             In case of issues with policy engine
318      */
319     protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
320         ArrayList<Integer> versions = new ArrayList<>();
321         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
322         String policyName = "";
323         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
324             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
325         } else {
326             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
327         }
328         logger.info("policyName=" + policyName);
329         configRequestParameters.setPolicyName(policyName);
330         try {
331             Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
332             for (PolicyConfig policyConfig : response) {
333                 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
334                 versions.add(version);
335             }
336             Collections.sort(versions);
337             logger.info("Policy versions.size()=" + versions.size());
338         } catch (PolicyConfigException e) {
339             // just print warning - if no policy version found
340             logger.warn("policy not found...policy name - " + policyName, e);
341         }
342         return versions;
343     }
344
345     /**
346      * This method create a new policy engine.
347      * 
348      * @return A new policy engine
349      */
350     private PolicyEngine getPolicyEngine() {
351         PolicyEngine policyEngine;
352         try {
353             policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
354         } catch (IOException e1) {
355             throw new PolicyClientException("Exception when opening policy config file", e1);
356         } catch (PolicyEngineException e) {
357             throw new PolicyClientException("Exception when creating a new policy engine", e);
358         }
359         return policyEngine;
360     }
361
362     /**
363      * Format and send delete Micro Service requests to Policy.
364      *
365      * @param prop
366      *            The ModelProperties
367      * @return The response message from Policy
368      */
369     public String deleteMicrosService(ModelProperties prop) {
370         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
371         return deletePolicy(prop, policyType);
372     }
373
374     /**
375      * This method delete the Base policy.
376      *
377      * @param prop
378      *            The model Properties
379      * @return A string with the answer from policy
380      */
381     public String deleteBasePolicy(ModelProperties prop) {
382         return deletePolicy(prop, PolicyConfigType.Base.toString());
383     }
384
385     /**
386      * Format and send delete BRMS requests to Policy.
387      *
388      * @param prop
389      *            The ModelProperties
390      * @return The response message from policy
391      */
392     public String deleteBrms(ModelProperties prop) {
393         String policyType = refProp.getStringValue("policy.op.type");
394         return deletePolicy(prop, policyType);
395     }
396
397     /**
398      * Format and send delete PAP and PDP requests to Policy.
399      *
400      * @param prop
401      *            The ModelProperties
402      *
403      * @return The response message from policy
404      */
405     protected String deletePolicy(ModelProperties prop, String policyType) {
406         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
407         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
408             deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
409         } else {
410             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
411         }
412         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
413         deletePolicyParameters.setPolicyComponent("PDP");
414         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
415         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
416         deletePolicyParameters.setPolicyType(policyType);
417         // send delete request
418         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
419         logger.info("Deleting policy from PAP...");
420         deletePolicyParameters.setPolicyComponent("PAP");
421         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
422         // send delete request
423         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
424         return responseMessage.toString();
425     }
426
427     /**
428      * Send delete request to Policy.
429      *
430      * @param deletePolicyParameters
431      *            The DeletePolicyParameters
432      * @param prop
433      *            The ModelProperties
434      * @return The response message from policy
435      */
436     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
437         // Verify whether it is triggered by Validation Test button from UI
438         if (prop.isTestOnly()) {
439             return "delete not executed for test action";
440         }
441         // API method to create or update Policy.
442         PolicyChangeResponse response = null;
443         String responseMessage = "";
444         try {
445             logger.info("Attempting to delete policy...");
446             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
447             responseMessage = response.getResponseMessage();
448         } catch (Exception e) {
449             logger.error("Exception occurred during policy communnication", e);
450         }
451         logger.info(LOG_POLICY_PREFIX + responseMessage);
452         if (response != null && response.getResponseCode() == 200) {
453             logger.info("Policy delete successful");
454         } else {
455             logger.warn("Policy delete failed: " + responseMessage);
456             throw new BadRequestException("Policy delete failed: " + responseMessage);
457         }
458         return responseMessage;
459     }
460 }