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