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