Merge "logstash input"
[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.Collection;
30 import java.util.Date;
31 import java.util.Map;
32 import java.util.UUID;
33
34 import javax.ws.rs.BadRequestException;
35
36 import org.onap.clamp.clds.config.ClampProperties;
37 import org.onap.clamp.clds.config.PolicyConfiguration;
38 import org.onap.clamp.clds.exception.policy.PolicyClientException;
39 import org.onap.clamp.clds.model.properties.ModelProperties;
40 import org.onap.clamp.clds.util.LoggingUtils;
41 import org.onap.policy.api.AttributeType;
42 import org.onap.policy.api.ConfigRequestParameters;
43 import org.onap.policy.api.DeletePolicyCondition;
44 import org.onap.policy.api.DeletePolicyParameters;
45 import org.onap.policy.api.PolicyChangeResponse;
46 import org.onap.policy.api.PolicyConfigException;
47 import org.onap.policy.api.PolicyConfigType;
48 import org.onap.policy.api.PolicyEngine;
49 import org.onap.policy.api.PolicyEngineException;
50 import org.onap.policy.api.PolicyParameters;
51 import org.onap.policy.api.PolicyType;
52 import org.onap.policy.api.PushPolicyParameters;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.context.ApplicationContext;
55 import org.springframework.context.annotation.Primary;
56 import org.springframework.stereotype.Component;
57
58 /**
59  * Policy utility methods - specifically, send the policy.
60  */
61 @Component
62 @Primary
63 public class PolicyClient {
64
65     protected PolicyEngine policyEngine;
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     public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
70     public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
71     public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
72     public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
73     public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix";
74     public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
75     @Autowired
76     protected ApplicationContext appContext;
77     @Autowired
78     protected ClampProperties refProp;
79     @Autowired
80     private PolicyConfiguration policyConfiguration;
81
82     /**
83      * Perform BRMS policy type.
84      *
85      * @param attributes
86      *            A map of attributes
87      * @param prop
88      *            The ModelProperties
89      * @param policyRequestUuid
90      *            PolicyRequest UUID
91      * @return The response message of policy
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_NAME_PREFIX_PROPERTY_NAME);
108         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
109         String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
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.setOnapName(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_NAME_PREFIX_PROPERTY_NAME);
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.setOnapName(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, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME));
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.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
193         policyParameters.setConfigBody(configBody);
194         String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
195         // Adding this line to clear the policy id from policy name while
196         // pushing to policy engine
197         prop.setPolicyUniqueId("");
198         String rtnMsg = send(policyParameters, prop, policyNamePrefix);
199         String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
200         push(policyType, prop);
201         return rtnMsg;
202     }
203
204     /**
205      * Perform send of policy.
206      *
207      * @param policyParameters
208      *            The PolicyParameters
209      * @param prop
210      *            The ModelProperties
211      * @return The response message of Policy
212      */
213     protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
214         // Verify whether it is triggered by Validation Test button from UI
215         if (prop.isTestOnly()) {
216             return "send not executed for test action";
217         }
218         // API method to create or update Policy.
219         PolicyChangeResponse response = null;
220         String responseMessage = "";
221         Date startTime = new Date();
222         try {
223             if (!checkPolicyExists(policyNamePrefix, prop)) {
224                 LoggingUtils.setTargetContext("Policy", "createPolicy");
225                 logger.info("Attempting to create policy for action=" + prop.getActionCd());
226                 response = getPolicyEngine().createPolicy(policyParameters);
227                 responseMessage = response.getResponseMessage();
228             } else {
229                 LoggingUtils.setTargetContext("Policy", "updatePolicy");
230                 logger.info("Attempting to update policy for action=" + prop.getActionCd());
231                 response = getPolicyEngine().updatePolicy(policyParameters);
232                 responseMessage = response.getResponseMessage();
233             }
234         } catch (Exception e) {
235             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
236             LoggingUtils.setErrorContext("900", "Policy send error");
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             LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
244             logger.info("Policy send successful");
245             metricsLogger.info("Policy send success");
246         } else {
247             LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
248             logger.warn("Policy send failed: " + responseMessage);
249             metricsLogger.info("Policy send failure");
250             throw new BadRequestException("Policy send failed: " + responseMessage);
251         }
252         return responseMessage;
253     }
254
255     /**
256      * Format and send push of policy.
257      *
258      * @param policyType
259      *            The policy Type
260      * @param prop
261      *            The ModelProperties
262      * @return The response message of policy
263      */
264     protected String push(String policyType, ModelProperties prop) {
265         // Verify whether it is triggered by Validation Test button from UI
266         if (prop.isTestOnly()) {
267             return "push not executed for test action";
268         }
269         PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
270         // Parameter arguments
271         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
272             pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
273         } else {
274             pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
275         }
276         logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
277         pushPolicyParameters.setPolicyType(policyType);
278         pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
279         pushPolicyParameters.setRequestID(null);
280         // API method to create or update Policy.
281         PolicyChangeResponse response;
282         String responseMessage = "";
283         try {
284             LoggingUtils.setTargetContext("Policy", "pushPolicy");
285             logger.info("Attempting to push policy...");
286             response = getPolicyEngine().pushPolicy(pushPolicyParameters);
287             if (response != null) {
288                 responseMessage = response.getResponseMessage();
289             }
290         } catch (Exception e) {
291             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
292             LoggingUtils.setErrorContext("900", "Policy push error");
293             logger.error("Exception occurred during policy communication", e);
294             throw new PolicyClientException("Exception while communicating with Policy", e);
295         }
296         logger.info(LOG_POLICY_PREFIX + responseMessage);
297         if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
298             LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
299             logger.info("Policy push successful");
300             metricsLogger.info("Policy push success");
301         } else {
302             LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
303             logger.warn("Policy push failed: " + responseMessage);
304             metricsLogger.info("Policy push failure");
305             throw new BadRequestException("Policy push failed: " + responseMessage);
306         }
307         return responseMessage;
308     }
309
310     /**
311      * Use list Policy API to retrieve the policy. Return true if policy exists
312      * otherwise return false.
313      *
314      * @param policyNamePrefix
315      *            The Policy Name Prefix
316      * @param prop
317      *            The ModelProperties
318      * @return The response message from policy
319      * @throws PolicyConfigException
320      *             In case of issues with policy engine
321      */
322     protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
323         boolean policyexists = false;
324         ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
325         String policyName = "";
326         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
327             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
328         } else {
329             policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
330         }
331         logger.info("Search in Policy Engine for policyName=" + policyName);
332         configRequestParameters.setPolicyName(policyName);
333         try {
334             Collection<String> response = getPolicyEngine().listConfig(configRequestParameters);
335             if (response != null && !response.isEmpty()) {
336                 policyexists = true;
337             }
338         } catch (PolicyConfigException e) {
339             // just print warning - if no policy version found
340             logger.warn("policy not found...policy name - " + policyName, e);
341         }
342         return policyexists;
343     }
344
345     /**
346      * This method create a new policy engine.
347      *
348      * @return A new policy engine
349      */
350     private synchronized PolicyEngine getPolicyEngine() {
351         try {
352             if (policyEngine == null) {
353                 policyEngine = new PolicyEngine(policyConfiguration.getProperties());
354             }
355         } catch (PolicyEngineException e) {
356             throw new PolicyClientException("Exception when creating a new policy engine", e);
357         }
358         return policyEngine;
359     }
360
361     /**
362      * Format and send delete Micro Service requests to Policy.
363      *
364      * @param prop
365      *            The ModelProperties
366      * @return The response message from Policy
367      */
368     public String deleteMicrosService(ModelProperties prop) {
369         String deletePolicyResponse = "";
370         try {
371             String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
372             if (checkPolicyExists(policyNamePrefix, prop)) {
373                 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
374                 deletePolicyResponse = deletePolicy(prop, policyType);
375             }
376         } catch (Exception e) {
377             logger.error("Exception occurred during policy communication", e);
378             throw new PolicyClientException("Exception while communicating with Policy", e);
379         }
380         return deletePolicyResponse;
381     }
382
383     /**
384      * This method delete the Base policy.
385      *
386      * @param prop
387      *            The model Properties
388      * @return A string with the answer from policy
389      */
390     public String deleteBasePolicy(ModelProperties prop) {
391         return deletePolicy(prop, PolicyConfigType.Base.toString());
392     }
393
394     /**
395      * Format and send delete BRMS requests to Policy.
396      *
397      * @param prop
398      *            The ModelProperties
399      * @return The response message from policy
400      */
401     public String deleteBrms(ModelProperties prop) {
402         String deletePolicyResponse = "";
403         try {
404             String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
405             if (checkPolicyExists(policyNamePrefix, prop)) {
406                 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
407                 deletePolicyResponse = deletePolicy(prop, policyType);
408             }
409         } catch (Exception e) {
410             logger.error("Exception occurred during policy communication", e);
411             throw new PolicyClientException("Exception while communicating with Policy", e);
412         }
413         return deletePolicyResponse;
414     }
415
416     /**
417      * Format and send delete PAP and PDP requests to Policy.
418      *
419      * @param prop
420      *            The ModelProperties
421      * @return The response message from policy
422      */
423     protected String deletePolicy(ModelProperties prop, String policyType) {
424         DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
425         if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
426             deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
427         } else {
428             deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
429         }
430         logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
431         deletePolicyParameters.setPolicyComponent("PDP");
432         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
433         deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
434         deletePolicyParameters.setPolicyType(policyType);
435         // send delete request
436         StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
437         logger.info("Deleting policy from PAP...");
438         deletePolicyParameters.setPolicyComponent("PAP");
439         deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
440         // send delete request
441         responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
442         return responseMessage.toString();
443     }
444
445     /**
446      * Send delete request to Policy.
447      *
448      * @param deletePolicyParameters
449      *            The DeletePolicyParameters
450      * @param prop
451      *            The ModelProperties
452      * @return The response message from policy
453      */
454     protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
455         // Verify whether it is triggered by Validation Test button from UI
456         if (prop.isTestOnly()) {
457             return "delete not executed for test action";
458         }
459         // API method to create or update Policy.
460         PolicyChangeResponse response = null;
461         String responseMessage = "";
462         try {
463             logger.info("Attempting to delete policy...");
464             response = getPolicyEngine().deletePolicy(deletePolicyParameters);
465             responseMessage = response.getResponseMessage();
466         } catch (Exception e) {
467             logger.error("Exception occurred during policy communnication", e);
468         }
469         logger.info(LOG_POLICY_PREFIX + responseMessage);
470         if (response != null && response.getResponseCode() == 200) {
471             logger.info("Policy delete successful");
472         } else {
473             logger.warn("Policy delete failed: " + responseMessage);
474             throw new BadRequestException("Policy delete failed: " + responseMessage);
475         }
476         return responseMessage;
477     }
478 }