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