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