Code refactoring
[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 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             logger.error("Exception occurred during policy communication", e);
233             throw new PolicyClientException("Exception while communicating with Policy", e);
234         }
235         logger.info(LOG_POLICY_PREFIX + responseMessage);
236         LoggingUtils.setTimeContext(startTime, new Date());
237         if (response.getResponseCode() == 200) {
238             logger.info("Policy send successful");
239             metricsLogger.info("Policy send success");
240         } else {
241             logger.warn("Policy send failed: " + responseMessage);
242             metricsLogger.info("Policy send failure");
243             throw new BadRequestException("Policy send failed: " + responseMessage);
244         }
245         return responseMessage;
246     }
247
248     /**
249      * Format and send push of policy.
250      *
251      * @param policyType
252      *            The policy Type
253      * @param prop
254      *            The ModelProperties
255      * @return The response message of policy
256      */
257     protected String push(String policyType, ModelProperties prop) {
258         // Verify whether it is triggered by Validation Test button from UI
259         if (prop.isTestOnly()) {
260             return "push not executed for test action";
261         }
262         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
263         // Parameter arguments
264         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
265             pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
266         } else {
267             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
268         }
269         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
270         pushPolicyParameters.setPolicyType(policyType);
271         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
272         pushPolicyParameters.setRequestID(null);
273         // API method to create or update Policy.
274         PolicyChangeResponse response;
275         String responseMessage = "";
276         try {
277             logger.info("Attempting to push policy...");
278             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
279             if (response != null) {
280                 responseMessage = response.getResponseMessage();
281             }
282         } catch (Exception e) {
283             logger.error("Exception occurred during policy communication", e);
284             throw new PolicyClientException("Exception while communicating with Policy", e);
285         }
286         logger.info(LOG_POLICY_PREFIX + responseMessage);
287         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
288             logger.info("Policy push successful");
289         } else {
290             logger.warn("Policy push failed: " + responseMessage);
291             throw new BadRequestException("Policy push failed: " + responseMessage);
292         }
293         return responseMessage;
294     }
295
296     /**
297      * Use Get Config Policy API to retrieve the versions for a policy. Return
298      * versions in sorted order. Return empty list if none found.
299      *
300      * @param policyNamePrefix
301      *            The Policy Name Prefix
302      * @param prop
303      *            The ModelProperties
304      * @return The response message from policy
305      * @throws PolicyConfigException
306      *             In case of issues with policy engine
307      */
308     protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
309         ArrayList<Integer> versions = new ArrayList<>();
310         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
311         String policyName = "";
312         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
313             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
314         } else {
315             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
316         }
317         logger.info("policyName=" + policyName);
318         configRequestParameters.setPolicyName(policyName);
319         try {
320             Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
321             for (PolicyConfig policyConfig : response) {
322                 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
323                 versions.add(version);
324             }
325             Collections.sort(versions);
326             logger.info("Policy versions.size()=" + versions.size());
327         } catch (PolicyConfigException e) {
328             // just print warning - if no policy version found
329             logger.warn("policy not found...policy name - " + policyName, e);
330         }
331         return versions;
332     }
333
334     private PolicyEngine getPolicyEngine() {
335         PolicyEngine policyEngine;
336         try {
337             policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
338         } catch (IOException e1) {
339             throw new PolicyClientException("Exception when opening policy config file", e1);
340         } catch (PolicyEngineException e) {
341             throw new PolicyClientException("Exception when creating a new policy engine", e);
342         }
343         return policyEngine;
344     }
345
346     /**
347      * Format and send delete Micro Service requests to Policy.
348      *
349      * @param prop
350      *            The ModelProperties
351      * @return The response message from Policy
352      */
353     public String deleteMicrosService(ModelProperties prop) {
354         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
355         return deletePolicy(prop, policyType);
356     }
357
358     /**
359      * This method delete the Base policy.
360      *
361      * @param prop
362      *            The model Properties
363      * @return A string with the answer from policy
364      */
365     public String deleteBasePolicy(ModelProperties prop) {
366         return deletePolicy(prop, PolicyConfigType.Base.toString());
367     }
368
369     /**
370      * Format and send delete BRMS requests to Policy.
371      *
372      * @param prop
373      *            The ModelProperties
374      * @return The response message from policy
375      */
376     public String deleteBrms(ModelProperties prop) {
377         String policyType = refProp.getStringValue("policy.op.type");
378         return deletePolicy(prop, policyType);
379     }
380
381     /**
382      * Format and send delete PAP and PDP requests to Policy.
383      *
384      * @param prop
385      *            The ModelProperties
386      * @return The response message from policy
387      */
388     protected String deletePolicy(ModelProperties prop, String policyType) {
389         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
390         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
391             deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
392         } else {
393             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
394         }
395         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
396         deletePolicyParameters.setPolicyComponent("PDP");
397         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
398         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
399         deletePolicyParameters.setPolicyType(policyType);
400         // send delete request
401         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
402         logger.info("Deleting policy from PAP...");
403         deletePolicyParameters.setPolicyComponent("PAP");
404         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
405         // send delete request
406         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
407         return responseMessage.toString();
408     }
409
410     /**
411      * Send delete request to Policy.
412      *
413      * @param deletePolicyParameters
414      *            The DeletePolicyParameters
415      * @param prop
416      *            The ModelProperties
417      * @return The response message from policy
418      */
419     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
420         // Verify whether it is triggered by Validation Test button from UI
421         if (prop.isTestOnly()) {
422             return "delete not executed for test action";
423         }
424         // API method to create or update Policy.
425         PolicyChangeResponse response = null;
426         String responseMessage = "";
427         try {
428             logger.info("Attempting to delete policy...");
429             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
430             responseMessage = response.getResponseMessage();
431         } catch (Exception e) {
432             logger.error("Exception occurred during policy communnication", e);
433         }
434         logger.info(LOG_POLICY_PREFIX + responseMessage);
435         if (response != null && response.getResponseCode() == 200) {
436             logger.info("Policy delete successful");
437         } else {
438             logger.warn("Policy delete failed: " + responseMessage);
439             throw new BadRequestException("Policy delete failed: " + responseMessage);
440         }
441         return responseMessage;
442     }
443 }