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