e1ef0d93677ca012302446973fef7d91ce186ec8
[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.client.req.TcaRequestFormatter;
41 import org.onap.clamp.clds.exception.policy.PolicyClientException;
42 import org.onap.clamp.clds.model.prop.ModelProperties;
43 import org.onap.clamp.clds.model.refprop.RefProp;
44 import org.onap.clamp.clds.util.LoggingUtils;
45 import org.onap.policy.api.AttributeType;
46 import org.onap.policy.api.ConfigRequestParameters;
47 import org.onap.policy.api.DeletePolicyCondition;
48 import org.onap.policy.api.DeletePolicyParameters;
49 import org.onap.policy.api.PolicyChangeResponse;
50 import org.onap.policy.api.PolicyConfig;
51 import org.onap.policy.api.PolicyConfigException;
52 import org.onap.policy.api.PolicyConfigType;
53 import org.onap.policy.api.PolicyEngine;
54 import org.onap.policy.api.PolicyEngineException;
55 import org.onap.policy.api.PolicyParameters;
56 import org.onap.policy.api.PolicyType;
57 import org.onap.policy.api.PushPolicyParameters;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.beans.factory.annotation.Value;
60 import org.springframework.context.ApplicationContext;
61
62 /**
63  * Policy utility methods - specifically, send the policy.
64  */
65 public class PolicyClient {
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.onap.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 configPolicyName
169      *            The config policy name of the component that has been pre-deployed in DCAE
170      * @param prop
171      *            The ModelProperties
172      * @param policyRequestUuid
173      *            The policy request UUID
174      * @return The answer from policy call
175      */
176     public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop, String policyRequestUuid) {
177
178         PolicyParameters policyParameters = new PolicyParameters();
179
180         // Set Policy Type
181         policyParameters.setPolicyConfigType(PolicyConfigType.Base);
182         policyParameters.setEcompName(refProp.getStringValue("policy.onap.name"));
183         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
184
185         policyParameters.setConfigBody(configBody);
186         policyParameters.setConfigBodyType(PolicyType.OTHER);
187         policyParameters.setConfigName("HolmesPolicy");
188         policyParameters.setPolicyName(configPolicyName);
189
190         policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
191
192         // Adding this line to clear the policy id from policy name while
193         // pushing to policy engine
194         prop.setPolicyUniqueId("");
195
196         String rtnMsg = send(policyParameters, prop, POLICY_PREFIX_BASE);
197         push(PolicyConfigType.Base.toString(), prop);
198
199         return rtnMsg;
200     }
201
202     /**
203      * Perform send of Microservice policy in OTHER type.
204      * 
205      * @param configBody
206      *            The config policy string body
207      * @param prop
208      *            The ModelProperties
209      * @param policyRequestUuid
210      *            The policy request UUID
211      * @return The answer from policy call
212      */
213     public String sendMicroServiceInOther(String configBody, ModelProperties prop, String policyRequestUuid) {
214
215         PolicyParameters policyParameters = new PolicyParameters();
216         // Set Policy Type 
217         policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
218         policyParameters.setOnapName("DCAE");
219         policyParameters.setEcompName(refProp.getStringValue("policy.onap.name"));
220         policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
221         policyParameters.setConfigBody(configBody);
222         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
223
224         // Adding this line to clear the policy id from policy name while
225         // pushing to policy engine
226         prop.setPolicyUniqueId("");
227
228         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
229         String policyType = refProp.getStringValue("policy.ms.type");
230         push(policyType, prop);
231
232         return rtnMsg;
233     }
234
235     /**
236      * Perform send of policy.
237      *
238      * @param policyParameters
239      *            The PolicyParameters
240      * @param prop
241      *            The ModelProperties
242      * @return The response message of Policy
243      */
244     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
245         // Verify whether it is triggered by Validation Test button from UI
246         if (prop.isTest()) {
247             return "send not executed for test action";
248         }
249
250         // API method to create or update Policy.
251         PolicyChangeResponse response = null;
252         String responseMessage = "";
253         Date startTime = new Date();
254         try {
255             List<Integer> versions = getVersions(policyNamePrefix, prop);
256             if (versions.isEmpty()) {
257                 LoggingUtils.setTargetContext("Policy", "createPolicy");
258                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
259                 response = getPolicyEngine().createPolicy(policyParameters);
260                 responseMessage = response.getResponseMessage();
261             } else {
262                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
263                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
264                 response = getPolicyEngine().updatePolicy(policyParameters);
265                 responseMessage = response.getResponseMessage();
266             }
267         } catch (Exception e) {
268             logger.error("Exception occurred during policy communication", e);
269             throw new PolicyClientException("Exception while communicating with Policy", e);
270         }
271         logger.info(LOG_POLICY_PREFIX + responseMessage);
272
273         LoggingUtils.setTimeContext(startTime, new Date());
274
275         if (response.getResponseCode() == 200) {
276             logger.info("Policy send successful");
277             metricsLogger.info("Policy send success");
278         } else {
279             logger.warn("Policy send failed: " + responseMessage);
280             metricsLogger.info("Policy send failure");
281             throw new BadRequestException("Policy send failed: " + responseMessage);
282         }
283
284         return responseMessage;
285     }
286
287     /**
288      * Format and send push of policy.
289      *
290      * @param policyType
291      *            The policy Type
292      * @param prop
293      *            The ModelProperties
294      * @return The response message of policy
295      */
296     protected String push(String policyType, ModelProperties prop) {
297         // Verify whether it is triggered by Validation Test button from UI
298         if (prop.isTest()) {
299             return "push not executed for test action";
300         }
301
302         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
303
304         // Parameter arguments
305         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
306             pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
307         } else {
308             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
309         }
310         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
311
312         pushPolicyParameters.setPolicyType(policyType);
313         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
314         pushPolicyParameters.setRequestID(null);
315
316         // API method to create or update Policy.
317         PolicyChangeResponse response = null;
318         String responseMessage = "";
319         try {
320             logger.info("Attempting to push policy...");
321             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
322             responseMessage = response.getResponseMessage();
323         } catch (Exception e) {
324             logger.error("Exception occurred during policy communication", e);
325         }
326         logger.info(LOG_POLICY_PREFIX + responseMessage);
327
328         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
329             logger.info("Policy push successful");
330         } else {
331             logger.warn("Policy push failed: " + responseMessage);
332             throw new BadRequestException("Policy push failed: " + responseMessage);
333         }
334
335         return responseMessage;
336     }
337
338     /**
339      * Use Get Config Policy API to retrieve the versions for a policy. Return
340      * versions in sorted order. Return empty list if none found.
341      *
342      * @param policyNamePrefix
343      *            The Policy Name Prefix
344      * @param prop
345      *            The ModelProperties
346      * @return The response message from policy
347      * @throws PolicyConfigException
348      *             In case of issues with policy engine
349      */
350     protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
351
352         ArrayList<Integer> versions = new ArrayList<>();
353         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
354         String policyName = "";
355
356         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
357             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
358         } else {
359             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
360         }
361
362         logger.info("policyName=" + policyName);
363         configRequestParameters.setPolicyName(policyName);
364         try {
365             Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
366             for (PolicyConfig policyConfig : response) {
367                 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
368                 versions.add(version);
369             }
370             Collections.sort(versions);
371             logger.info("Policy versions.size()=" + versions.size());
372         } catch (PolicyConfigException e) {
373             // just print warning - if no policy version found
374             logger.warn("warning: policy not found...policy name - " + policyName, e.getMessage());
375         }
376         return versions;
377
378     }
379
380     /**
381      * This method create a new policy engine.
382      * 
383      * @return A new policy engine
384      */
385     private PolicyEngine getPolicyEngine() {
386         PolicyEngine policyEngine;
387         try {
388             policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
389         } catch (IOException e1) {
390             throw new PolicyClientException("Exception when opening policy config file", e1);
391         } catch (PolicyEngineException e) {
392             throw new PolicyClientException("Exception when creating a new policy engine", e);
393         }
394         return policyEngine;
395     }
396
397     /**
398      * Format and send delete Micro Service requests to Policy.
399      *
400      * @param prop
401      *            The ModelProperties
402      * @return The response message from Policy
403      */
404     public String deleteMicrosService(ModelProperties prop) {
405         String policyType = refProp.getStringValue("policy.ms.type");
406         return deletePolicy(prop, policyType);
407     }
408
409     /**
410      * This method delete the Base policy.
411      *
412      * @param prop
413      *            The model Properties
414      * @return A string with the answer from policy
415      */
416     public String deleteBasePolicy(ModelProperties prop) {
417         return deletePolicy(prop, PolicyConfigType.Base.toString());
418     }
419
420     /**
421      * Format and send delete BRMS requests to Policy.
422      *
423      * @param prop
424      *            The ModelProperties
425      * @return The response message from policy
426      */
427     public String deleteBrms(ModelProperties prop) {
428         String policyType = refProp.getStringValue("policy.op.type");
429         return deletePolicy(prop, policyType);
430     }
431
432     /**
433      * Format and send delete PAP and PDP requests to Policy.
434      *
435      * @param prop
436      *            The ModelProperties
437      *
438      * @return The response message from policy
439      */
440     protected String deletePolicy(ModelProperties prop, String policyType) {
441         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
442
443         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
444             deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
445         } else {
446             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
447         }
448         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
449         deletePolicyParameters.setPolicyComponent("PDP");
450         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
451         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
452         deletePolicyParameters.setPolicyType(policyType);
453         // send delete request
454         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
455
456         logger.info("Deleting policy from PAP...");
457         deletePolicyParameters.setPolicyComponent("PAP");
458         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
459
460         // send delete request
461         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
462
463         return responseMessage.toString();
464     }
465
466     /**
467      * Send delete request to Policy.
468      *
469      * @param deletePolicyParameters
470      *            The DeletePolicyParameters
471      * @param prop
472      *            The ModelProperties
473      * @return The response message from policy
474      */
475     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
476         // Verify whether it is triggered by Validation Test button from UI
477         if (prop.isTest()) {
478             return "delete not executed for test action";
479         }
480
481         // API method to create or update Policy.
482         PolicyChangeResponse response = null;
483         String responseMessage = "";
484         try {
485             logger.info("Attempting to delete policy...");
486             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
487             responseMessage = response.getResponseMessage();
488         } catch (Exception e) {
489             logger.error("Exception occurred during policy communnication", e);
490         }
491         logger.info(LOG_POLICY_PREFIX + responseMessage);
492
493         if (response != null && response.getResponseCode() == 200) {
494             logger.info("Policy delete successful");
495         } else {
496             logger.warn("Policy delete failed: " + responseMessage);
497             throw new BadRequestException("Policy delete failed: " + responseMessage);
498         }
499
500         return responseMessage;
501     }
502 }