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