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