2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 package org.onap.clamp.clds.client.req.policy;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
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.List;
36 import java.util.UUID;
38 import javax.ws.rs.BadRequestException;
40 import org.onap.clamp.clds.exception.policy.PolicyClientException;
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.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.beans.factory.annotation.Value;
59 import org.springframework.context.ApplicationContext;
62 * Policy utility methods - specifically, send the policy.
64 public class PolicyClient {
65 protected static final String POLICY_PREFIX_BASE = "Config_";
66 protected static final String POLICY_PREFIX_BRMS_PARAM = "Config_BRMS_Param_";
67 protected static final String POLICY_PREFIX_MICROSERVICE = "Config_MS_";
68 protected static final String LOG_POLICY_PREFIX = "Response is ";
69 protected static final EELFLogger logger = EELFManager.getInstance()
70 .getLogger(PolicyClient.class);
71 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
72 protected static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
73 protected static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
74 @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}")
75 protected String cldsPolicyConfigFile;
77 protected ApplicationContext appContext;
79 protected RefProp refProp;
82 * Perform BRMS policy type.
88 * @param policyRequestUuid
90 * @return The response message of policy
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.policyNamePrefix");
108 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
109 String policyType = refProp.getStringValue("policy.op.type");
110 push(policyType, prop);
115 * Perform send of microservice policy in JSON.
120 * The ModelProperties
121 * @param policyRequestUuid
122 * The policy Request UUID
123 * @return The response message of policy
125 public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
126 PolicyParameters policyParameters = new PolicyParameters();
128 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
129 policyParameters.setEcompName(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.policyNamePrefix");
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);
145 * Perform send of base policy in OTHER type.
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
153 * The ModelProperties
154 * @param policyRequestUuid
155 * The policy request UUID
156 * @return The answer from policy call
158 public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
159 String policyRequestUuid) {
160 PolicyParameters policyParameters = new PolicyParameters();
162 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
163 policyParameters.setEcompName(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, POLICY_PREFIX_BASE);
174 push(PolicyConfigType.Base.toString(), prop);
179 * Perform send of Microservice policy in OTHER type.
182 * The config policy string body
184 * The ModelProperties
185 * @return The answer from policy call
187 public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
188 PolicyParameters policyParameters = new PolicyParameters();
190 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
191 // policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
192 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
193 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
194 policyParameters.setConfigBody(configBody);
195 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
196 // Adding this line to clear the policy id from policy name while
197 // pushing to policy engine
198 prop.setPolicyUniqueId("");
199 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
200 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
201 push(policyType, prop);
206 * Perform send of policy.
208 * @param policyParameters
209 * The PolicyParameters
211 * The ModelProperties
212 * @return The response message of Policy
214 protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
215 // Verify whether it is triggered by Validation Test button from UI
216 if (prop.isTestOnly()) {
217 return "send not executed for test action";
219 // API method to create or update Policy.
220 PolicyChangeResponse response = null;
221 String responseMessage = "";
222 Date startTime = new Date();
224 List<Integer> versions = getVersions(policyNamePrefix, prop);
225 if (versions.isEmpty()) {
226 LoggingUtils.setTargetContext("Policy", "createPolicy");
227 logger.info("Attempting to create policy for action=" + prop.getActionCd());
228 response = getPolicyEngine().createPolicy(policyParameters);
229 responseMessage = response.getResponseMessage();
231 LoggingUtils.setTargetContext("Policy", "updatePolicy");
232 logger.info("Attempting to update policy for action=" + prop.getActionCd());
233 response = getPolicyEngine().updatePolicy(policyParameters);
234 responseMessage = response.getResponseMessage();
236 } catch (Exception e) {
237 logger.error("Exception occurred during policy communication", e);
238 throw new PolicyClientException("Exception while communicating with Policy", e);
240 logger.info(LOG_POLICY_PREFIX + responseMessage);
241 LoggingUtils.setTimeContext(startTime, new Date());
242 if (response.getResponseCode() == 200) {
243 logger.info("Policy send successful");
244 metricsLogger.info("Policy send success");
246 logger.warn("Policy send failed: " + responseMessage);
247 metricsLogger.info("Policy send failure");
248 throw new BadRequestException("Policy send failed: " + responseMessage);
250 return responseMessage;
254 * Format and send push of policy.
259 * The ModelProperties
260 * @return The response message of policy
262 protected String push(String policyType, ModelProperties prop) {
263 // Verify whether it is triggered by Validation Test button from UI
264 if (prop.isTestOnly()) {
265 return "push not executed for test action";
267 PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
268 // Parameter arguments
269 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
270 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
272 pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
274 logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
275 pushPolicyParameters.setPolicyType(policyType);
276 pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
277 pushPolicyParameters.setRequestID(null);
278 // API method to create or update Policy.
279 PolicyChangeResponse response;
280 String responseMessage = "";
282 logger.info("Attempting to push policy...");
283 response = getPolicyEngine().pushPolicy(pushPolicyParameters);
284 if (response != null) {
285 responseMessage = response.getResponseMessage();
287 } catch (Exception e) {
288 logger.error("Exception occurred during policy communication", e);
289 throw new PolicyClientException("Exception while communicating with Policy", e);
291 logger.info(LOG_POLICY_PREFIX + responseMessage);
292 if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
293 logger.info("Policy push successful");
295 logger.warn("Policy push failed: " + responseMessage);
296 throw new BadRequestException("Policy push failed: " + responseMessage);
298 return responseMessage;
302 * Use Get Config Policy API to retrieve the versions for a policy. Return
303 * versions in sorted order. Return empty list if none found.
305 * @param policyNamePrefix
306 * The Policy Name Prefix
308 * The ModelProperties
309 * @return The response message from policy
310 * @throws PolicyConfigException
311 * In case of issues with policy engine
313 protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
314 ArrayList<Integer> versions = new ArrayList<>();
315 ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
316 String policyName = "";
317 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
318 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
320 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
322 logger.info("policyName=" + policyName);
323 configRequestParameters.setPolicyName(policyName);
325 Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
326 for (PolicyConfig policyConfig : response) {
327 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
328 versions.add(version);
330 Collections.sort(versions);
331 logger.info("Policy versions.size()=" + versions.size());
332 } catch (PolicyConfigException e) {
333 // just print warning - if no policy version found
334 logger.warn("warning: policy not found...policy name - " + policyName, e.getMessage());
340 * This method create a new policy engine.
342 * @return A new policy engine
344 private PolicyEngine getPolicyEngine() {
345 PolicyEngine policyEngine;
347 policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
348 } catch (IOException e1) {
349 throw new PolicyClientException("Exception when opening policy config file", e1);
350 } catch (PolicyEngineException e) {
351 throw new PolicyClientException("Exception when creating a new policy engine", e);
357 * Format and send delete Micro Service requests to Policy.
360 * The ModelProperties
361 * @return The response message from Policy
363 public String deleteMicrosService(ModelProperties prop) {
364 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
365 return deletePolicy(prop, policyType);
369 * This method delete the Base policy.
372 * The model Properties
373 * @return A string with the answer from policy
375 public String deleteBasePolicy(ModelProperties prop) {
376 return deletePolicy(prop, PolicyConfigType.Base.toString());
380 * Format and send delete BRMS requests to Policy.
383 * The ModelProperties
384 * @return The response message from policy
386 public String deleteBrms(ModelProperties prop) {
387 String policyType = refProp.getStringValue("policy.op.type");
388 return deletePolicy(prop, policyType);
392 * Format and send delete PAP and PDP requests to Policy.
395 * The ModelProperties
397 * @return The response message from policy
399 protected String deletePolicy(ModelProperties prop, String policyType) {
400 DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
401 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
402 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
404 deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
406 logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
407 deletePolicyParameters.setPolicyComponent("PDP");
408 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
409 deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
410 deletePolicyParameters.setPolicyType(policyType);
411 // send delete request
412 StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
413 logger.info("Deleting policy from PAP...");
414 deletePolicyParameters.setPolicyComponent("PAP");
415 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
416 // send delete request
417 responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
418 return responseMessage.toString();
422 * Send delete request to Policy.
424 * @param deletePolicyParameters
425 * The DeletePolicyParameters
427 * The ModelProperties
428 * @return The response message from policy
430 protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
431 // Verify whether it is triggered by Validation Test button from UI
432 if (prop.isTestOnly()) {
433 return "delete not executed for test action";
435 // API method to create or update Policy.
436 PolicyChangeResponse response = null;
437 String responseMessage = "";
439 logger.info("Attempting to delete policy...");
440 response = getPolicyEngine().deletePolicy(deletePolicyParameters);
441 responseMessage = response.getResponseMessage();
442 } catch (Exception e) {
443 logger.error("Exception occurred during policy communnication", e);
445 logger.info(LOG_POLICY_PREFIX + responseMessage);
446 if (response != null && response.getResponseCode() == 200) {
447 logger.info("Policy delete successful");
449 logger.warn("Policy delete failed: " + responseMessage);
450 throw new BadRequestException("Policy delete failed: " + responseMessage);
452 return responseMessage;