Remove poliyc errors
[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  * 
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.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Date;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.UUID;
36
37 import javax.ws.rs.BadRequestException;
38
39 import org.onap.clamp.clds.config.ClampProperties;
40 import org.onap.clamp.clds.config.PolicyConfiguration;
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.context.ApplicationContext;
59 import org.springframework.stereotype.Component;
60
61 /**
62  * Policy utility methods - specifically, send the policy.
63  */
64 @Component
65 public class PolicyClient {
66
67     protected static final String LOG_POLICY_PREFIX = "Response is ";
68     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
69     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
70     public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
71     public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
72     public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
73     public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
74     public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix";
75     public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
76     @Autowired
77     protected ApplicationContext appContext;
78     @Autowired
79     protected ClampProperties refProp;
80     @Autowired
81     private PolicyConfiguration policyConfiguration;
82
83     /**
84      * Perform BRMS policy type.
85      *
86      * @param attributes
87      *            A map of attributes
88      * @param prop
89      *            The ModelProperties
90      * @param policyRequestUuid
91      *            PolicyRequest UUID
92      * @return The response message of policy
93      */
94     public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
95             String policyRequestUuid) {
96         PolicyParameters policyParameters = new PolicyParameters();
97         // Set Policy Type(Mandatory)
98         policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
99         // Set Policy Name(Mandatory)
100         policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
101         // documentation says this is options, but when tested, got the
102         // following failure: java.lang.Exception: Policy send failed: PE300 -
103         // Data Issue: No policyDescription given.
104         policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
105         policyParameters.setAttributes(attributes);
106         // Set a random UUID(Mandatory)
107         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
108         String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
109         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
110         String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
111         push(policyType, prop);
112         return rtnMsg;
113     }
114
115     /**
116      * Perform send of microservice policy in JSON.
117      *
118      * @param policyJson
119      *            The policy JSON
120      * @param prop
121      *            The ModelProperties
122      * @param policyRequestUuid
123      *            The policy Request UUID
124      * @return The response message of policy
125      */
126     public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
127         PolicyParameters policyParameters = new PolicyParameters();
128         // Set Policy Type
129         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
130         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
131         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
132         policyParameters.setConfigBody(policyJson);
133         policyParameters.setConfigBodyType(PolicyType.JSON);
134         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
135         String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
136         // Adding this line to clear the policy id from policy name while
137         // pushing to policy engine
138         prop.setPolicyUniqueId("");
139         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
140         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
141         push(policyType, prop);
142         return rtnMsg;
143     }
144
145     /**
146      * Perform send of base policy in OTHER type.
147      *
148      * @param configBody
149      *            The config policy string body
150      * @param configPolicyName
151      *            The config policy name of the component that has been
152      *            pre-deployed in DCAE
153      * @param prop
154      *            The ModelProperties
155      * @param policyRequestUuid
156      *            The policy request UUID
157      * @return The answer from policy call
158      */
159     public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
160             String policyRequestUuid) {
161         PolicyParameters policyParameters = new PolicyParameters();
162         // Set Policy Type
163         policyParameters.setPolicyConfigType(PolicyConfigType.Base);
164         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
165         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
166         policyParameters.setConfigBody(configBody);
167         policyParameters.setConfigBodyType(PolicyType.OTHER);
168         policyParameters.setConfigName("HolmesPolicy");
169         policyParameters.setPolicyName(configPolicyName);
170         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
171         // Adding this line to clear the policy id from policy name while
172         // pushing to policy engine
173         prop.setPolicyUniqueId("");
174         String rtnMsg = send(policyParameters, prop, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME));
175         push(PolicyConfigType.Base.toString(), prop);
176         return rtnMsg;
177     }
178
179     /**
180      * Perform send of Microservice policy in OTHER type.
181      * 
182      * @param configBody
183      *            The config policy string body
184      * @param prop
185      *            The ModelProperties
186      * @return The answer from policy call
187      */
188     public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
189         PolicyParameters policyParameters = new PolicyParameters();
190         // Set Policy Type
191         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
192         policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
193         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
194         policyParameters.setConfigBody(configBody);
195         String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
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             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
238             LoggingUtils.setErrorContext("900", "Policy send error");
239             logger.error("Exception occurred during policy communication", e);
240             throw new PolicyClientException("Exception while communicating with Policy", e);
241         }
242         logger.info(LOG_POLICY_PREFIX + responseMessage);
243         LoggingUtils.setTimeContext(startTime, new Date());
244         if (response.getResponseCode() == 200) {
245             LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
246             logger.info("Policy send successful");
247             metricsLogger.info("Policy send success");
248         } else {
249             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
250             logger.warn("Policy send failed: " + responseMessage);
251             metricsLogger.info("Policy send failure");
252             throw new BadRequestException("Policy send failed: " + responseMessage);
253         }
254         return responseMessage;
255     }
256
257     /**
258      * Format and send push of policy.
259      *
260      * @param policyType
261      *            The policy Type
262      * @param prop
263      *            The ModelProperties
264      * @return The response message of policy
265      */
266     protected String push(String policyType, ModelProperties prop) {
267         // Verify whether it is triggered by Validation Test button from UI
268         if (prop.isTestOnly()) {
269             return "push not executed for test action";
270         }
271         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
272         // Parameter arguments
273         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
274             pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
275         } else {
276             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
277         }
278         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
279         pushPolicyParameters.setPolicyType(policyType);
280         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
281         pushPolicyParameters.setRequestID(null);
282         // API method to create or update Policy.
283         PolicyChangeResponse response;
284         String responseMessage = "";
285         try {
286             LoggingUtils.setTargetContext("Policy", "pushPolicy");
287             logger.info("Attempting to push policy...");
288             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
289             if (response != null) {
290                 responseMessage = response.getResponseMessage();
291             }
292         } catch (Exception e) {
293             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
294             LoggingUtils.setErrorContext("900", "Policy push error");
295             logger.error("Exception occurred during policy communication", e);
296             throw new PolicyClientException("Exception while communicating with Policy", e);
297         }
298         logger.info(LOG_POLICY_PREFIX + responseMessage);
299         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
300             LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
301             logger.info("Policy push successful");
302             metricsLogger.info("Policy push success");
303         } else {
304             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
305             logger.warn("Policy push failed: " + responseMessage);
306             metricsLogger.info("Policy push failure");
307             throw new BadRequestException("Policy push failed: " + responseMessage);
308         }
309         return responseMessage;
310     }
311
312     /**
313      * Use Get Config Policy API to retrieve the versions for a policy. Return
314      * versions in sorted order. Return empty list if none found.
315      *
316      * @param policyNamePrefix
317      *            The Policy Name Prefix
318      * @param prop
319      *            The ModelProperties
320      * @return The response message from policy
321      * @throws PolicyConfigException
322      *             In case of issues with policy engine
323      */
324     protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
325         ArrayList<Integer> versions = new ArrayList<>();
326         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
327         String policyName = "";
328         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
329             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
330         } else {
331             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
332         }
333         logger.info("Search in Policy Engine for policyName=" + policyName);
334         configRequestParameters.setPolicyName(policyName);
335         try {
336             Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
337             for (PolicyConfig policyConfig : response) {
338                 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
339                 versions.add(version);
340             }
341             Collections.sort(versions);
342             logger.info("Policy versions.size()=" + versions.size());
343         } catch (PolicyConfigException e) {
344             // just print warning - if no policy version found
345             logger.warn("policy not found...policy name - " + policyName, e);
346         }
347         return versions;
348     }
349
350     /**
351      * This method create a new policy engine.
352      * 
353      * @return A new policy engine
354      */
355     private PolicyEngine getPolicyEngine() {
356         PolicyEngine policyEngine;
357         try {
358             policyEngine = new PolicyEngine(policyConfiguration.getProperties());
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_PROPERTY_NAME);
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 }