Fix remaining SOnar
[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 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
66     protected static final String POLICY_PREFIX_BASE = "Config_";
67     protected static final String POLICY_PREFIX_BRMS_PARAM = "Config_BRMS_Param_";
68     protected static final String POLICY_PREFIX_MICROSERVICE = "Config_MS_";
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("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}")
75     protected String cldsPolicyConfigFile;
76     @Autowired
77     protected ApplicationContext appContext;
78     @Autowired
79     protected RefProp 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.setEcompName(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.setEcompName(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.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
192         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
193         policyParameters.setConfigBody(configBody);
194         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
195         // Adding this line to clear the policy id from policy name while
196         // pushing to policy engine
197         prop.setPolicyUniqueId("");
198         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
199         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
200         push(policyType, prop);
201         return rtnMsg;
202     }
203
204     /**
205      * Perform send of policy.
206      *
207      * @param policyParameters
208      *            The PolicyParameters
209      * @param prop
210      *            The ModelProperties
211      * @return The response message of Policy
212      */
213     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
214         // Verify whether it is triggered by Validation Test button from UI
215         if (prop.isTestOnly()) {
216             return "send not executed for test action";
217         }
218         // API method to create or update Policy.
219         PolicyChangeResponse response = null;
220         String responseMessage = "";
221         Date startTime = new Date();
222         try {
223             List<Integer> versions = getVersions(policyNamePrefix, prop);
224             if (versions.isEmpty()) {
225                 LoggingUtils.setTargetContext("Policy", "createPolicy");
226                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
227                 response = getPolicyEngine().createPolicy(policyParameters);
228                 responseMessage = response.getResponseMessage();
229             } else {
230                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
231                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
232                 response = getPolicyEngine().updatePolicy(policyParameters);
233                 responseMessage = response.getResponseMessage();
234             }
235         } catch (Exception e) {
236             logger.error("Exception occurred during policy communication", e);
237             throw new PolicyClientException("Exception while communicating with Policy", e);
238         }
239         logger.info(LOG_POLICY_PREFIX + responseMessage);
240         LoggingUtils.setTimeContext(startTime, new Date());
241         if (response.getResponseCode() == 200) {
242             logger.info("Policy send successful");
243             metricsLogger.info("Policy send success");
244         } else {
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             logger.info("Attempting to push policy...");
282             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
283             if (response != null) {
284                 responseMessage = response.getResponseMessage();
285             }
286         } catch (Exception e) {
287             logger.error("Exception occurred during policy communication", e);
288             throw new PolicyClientException("Exception while communicating with Policy", e);
289         }
290         logger.info(LOG_POLICY_PREFIX + responseMessage);
291         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
292             logger.info("Policy push successful");
293         } else {
294             logger.warn("Policy push failed: " + responseMessage);
295             throw new BadRequestException("Policy push failed: " + responseMessage);
296         }
297         return responseMessage;
298     }
299
300     /**
301      * Use Get Config Policy API to retrieve the versions for a policy. Return
302      * versions in sorted order. Return empty list if none found.
303      *
304      * @param policyNamePrefix
305      *            The Policy Name Prefix
306      * @param prop
307      *            The ModelProperties
308      * @return The response message from policy
309      * @throws PolicyConfigException
310      *             In case of issues with policy engine
311      */
312     protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
313         ArrayList<Integer> versions = new ArrayList<>();
314         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
315         String policyName = "";
316         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
317             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
318         } else {
319             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
320         }
321         logger.info("policyName=" + policyName);
322         configRequestParameters.setPolicyName(policyName);
323         try {
324             Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
325             for (PolicyConfig policyConfig : response) {
326                 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
327                 versions.add(version);
328             }
329             Collections.sort(versions);
330             logger.info("Policy versions.size()=" + versions.size());
331         } catch (PolicyConfigException e) {
332             // just print warning - if no policy version found
333             logger.warn("policy not found...policy name - " + policyName, e);
334         }
335         return versions;
336     }
337
338     /**
339      * This method create a new policy engine.
340      * 
341      * @return A new policy engine
342      */
343     private PolicyEngine getPolicyEngine() {
344         PolicyEngine policyEngine;
345         try {
346             policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
347         } catch (IOException e1) {
348             throw new PolicyClientException("Exception when opening policy config file", e1);
349         } catch (PolicyEngineException e) {
350             throw new PolicyClientException("Exception when creating a new policy engine", e);
351         }
352         return policyEngine;
353     }
354
355     /**
356      * Format and send delete Micro Service requests to Policy.
357      *
358      * @param prop
359      *            The ModelProperties
360      * @return The response message from Policy
361      */
362     public String deleteMicrosService(ModelProperties prop) {
363         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
364         return deletePolicy(prop, policyType);
365     }
366
367     /**
368      * This method delete the Base policy.
369      *
370      * @param prop
371      *            The model Properties
372      * @return A string with the answer from policy
373      */
374     public String deleteBasePolicy(ModelProperties prop) {
375         return deletePolicy(prop, PolicyConfigType.Base.toString());
376     }
377
378     /**
379      * Format and send delete BRMS requests to Policy.
380      *
381      * @param prop
382      *            The ModelProperties
383      * @return The response message from policy
384      */
385     public String deleteBrms(ModelProperties prop) {
386         String policyType = refProp.getStringValue("policy.op.type");
387         return deletePolicy(prop, policyType);
388     }
389
390     /**
391      * Format and send delete PAP and PDP requests to Policy.
392      *
393      * @param prop
394      *            The ModelProperties
395      * @return The response message from policy
396      */
397     protected String deletePolicy(ModelProperties prop, String policyType) {
398         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
399         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
400             deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
401         } else {
402             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
403         }
404         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
405         deletePolicyParameters.setPolicyComponent("PDP");
406         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
407         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
408         deletePolicyParameters.setPolicyType(policyType);
409         // send delete request
410         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
411         logger.info("Deleting policy from PAP...");
412         deletePolicyParameters.setPolicyComponent("PAP");
413         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
414         // send delete request
415         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
416         return responseMessage.toString();
417     }
418
419     /**
420      * Send delete request to Policy.
421      *
422      * @param deletePolicyParameters
423      *            The DeletePolicyParameters
424      * @param prop
425      *            The ModelProperties
426      * @return The response message from policy
427      */
428     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
429         // Verify whether it is triggered by Validation Test button from UI
430         if (prop.isTestOnly()) {
431             return "delete not executed for test action";
432         }
433         // API method to create or update Policy.
434         PolicyChangeResponse response = null;
435         String responseMessage = "";
436         try {
437             logger.info("Attempting to delete policy...");
438             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
439             responseMessage = response.getResponseMessage();
440         } catch (Exception e) {
441             logger.error("Exception occurred during policy communnication", e);
442         }
443         logger.info(LOG_POLICY_PREFIX + responseMessage);
444         if (response != null && response.getResponseCode() == 200) {
445             logger.info("Policy delete successful");
446         } else {
447             logger.warn("Policy delete failed: " + responseMessage);
448             throw new BadRequestException("Policy delete failed: " + responseMessage);
449         }
450         return responseMessage;
451     }
452 }