2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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 * ===================================================================
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.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Date;
33 import java.util.List;
35 import java.util.UUID;
37 import javax.ws.rs.BadRequestException;
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;
62 * Policy utility methods - specifically, send the policy.
65 public class PolicyClient {
67 protected static final String LOG_POLICY_PREFIX = "Response is ";
68 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
69 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
70 public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
71 public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
72 public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
73 public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
74 public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix";
75 public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
77 protected ApplicationContext appContext;
79 protected ClampProperties refProp;
81 private PolicyConfiguration policyConfiguration;
84 * Perform BRMS policy type.
90 * @param policyRequestUuid
92 * @return The response message of policy
94 public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
95 String policyRequestUuid) {
96 PolicyParameters policyParameters = new PolicyParameters();
97 // Set Policy Type(Mandatory)
98 policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
99 // Set Policy Name(Mandatory)
100 policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
101 // documentation says this is options, but when tested, got the
102 // following failure: java.lang.Exception: Policy send failed: PE300 -
103 // Data Issue: No policyDescription given.
104 policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
105 policyParameters.setAttributes(attributes);
106 // Set a random UUID(Mandatory)
107 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
108 String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
109 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
110 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
111 push(policyType, prop);
116 * Perform send of microservice policy in JSON.
121 * The ModelProperties
122 * @param policyRequestUuid
123 * The policy Request UUID
124 * @return The response message of policy
126 public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
127 PolicyParameters policyParameters = new PolicyParameters();
129 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
130 policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
131 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
132 policyParameters.setConfigBody(policyJson);
133 policyParameters.setConfigBodyType(PolicyType.JSON);
134 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
135 String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
136 // Adding this line to clear the policy id from policy name while
137 // pushing to policy engine
138 prop.setPolicyUniqueId("");
139 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
140 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
141 push(policyType, prop);
146 * Perform send of base policy in OTHER type.
149 * The config policy string body
150 * @param configPolicyName
151 * The config policy name of the component that has been
152 * pre-deployed in DCAE
154 * The ModelProperties
155 * @param policyRequestUuid
156 * The policy request UUID
157 * @return The answer from policy call
159 public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
160 String policyRequestUuid) {
161 PolicyParameters policyParameters = new PolicyParameters();
163 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
164 policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
165 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
166 policyParameters.setConfigBody(configBody);
167 policyParameters.setConfigBodyType(PolicyType.OTHER);
168 policyParameters.setConfigName("HolmesPolicy");
169 policyParameters.setPolicyName(configPolicyName);
170 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
171 // Adding this line to clear the policy id from policy name while
172 // pushing to policy engine
173 prop.setPolicyUniqueId("");
174 String rtnMsg = send(policyParameters, prop, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME));
175 push(PolicyConfigType.Base.toString(), prop);
180 * Perform send of Microservice policy in OTHER type.
183 * The config policy string body
185 * The ModelProperties
186 * @return The answer from policy call
188 public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
189 PolicyParameters policyParameters = new PolicyParameters();
191 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
192 policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
193 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
194 policyParameters.setConfigBody(configBody);
195 String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
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 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
238 LoggingUtils.setErrorContext("900", "Policy send error");
239 logger.error("Exception occurred during policy communication", e);
240 throw new PolicyClientException("Exception while communicating with Policy", e);
242 logger.info(LOG_POLICY_PREFIX + responseMessage);
243 LoggingUtils.setTimeContext(startTime, new Date());
244 if (response.getResponseCode() == 200) {
245 LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
246 logger.info("Policy send successful");
247 metricsLogger.info("Policy send success");
249 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
250 logger.warn("Policy send failed: " + responseMessage);
251 metricsLogger.info("Policy send failure");
252 throw new BadRequestException("Policy send failed: " + responseMessage);
254 return responseMessage;
258 * Format and send push of policy.
263 * The ModelProperties
264 * @return The response message of policy
266 protected String push(String policyType, ModelProperties prop) {
267 // Verify whether it is triggered by Validation Test button from UI
268 if (prop.isTestOnly()) {
269 return "push not executed for test action";
271 PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
272 // Parameter arguments
273 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
274 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
276 pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
278 logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
279 pushPolicyParameters.setPolicyType(policyType);
280 pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
281 pushPolicyParameters.setRequestID(null);
282 // API method to create or update Policy.
283 PolicyChangeResponse response;
284 String responseMessage = "";
286 LoggingUtils.setTargetContext("Policy", "pushPolicy");
287 logger.info("Attempting to push policy...");
288 response = getPolicyEngine().pushPolicy(pushPolicyParameters);
289 if (response != null) {
290 responseMessage = response.getResponseMessage();
292 } catch (Exception e) {
293 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
294 LoggingUtils.setErrorContext("900", "Policy push error");
295 logger.error("Exception occurred during policy communication", e);
296 throw new PolicyClientException("Exception while communicating with Policy", e);
298 logger.info(LOG_POLICY_PREFIX + responseMessage);
299 if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
300 LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
301 logger.info("Policy push successful");
302 metricsLogger.info("Policy push success");
304 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
305 logger.warn("Policy push failed: " + responseMessage);
306 metricsLogger.info("Policy push failure");
307 throw new BadRequestException("Policy push failed: " + responseMessage);
309 return responseMessage;
313 * Use Get Config Policy API to retrieve the versions for a policy. Return
314 * versions in sorted order. Return empty list if none found.
316 * @param policyNamePrefix
317 * The Policy Name Prefix
319 * The ModelProperties
320 * @return The response message from policy
321 * @throws PolicyConfigException
322 * In case of issues with policy engine
324 protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
325 ArrayList<Integer> versions = new ArrayList<>();
326 ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
327 String policyName = "";
328 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
329 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
331 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
333 logger.info("Search in Policy Engine for policyName=" + policyName);
334 configRequestParameters.setPolicyName(policyName);
336 Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
337 for (PolicyConfig policyConfig : response) {
338 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
339 versions.add(version);
341 Collections.sort(versions);
342 logger.info("Policy versions.size()=" + versions.size());
343 } catch (PolicyConfigException e) {
344 // just print warning - if no policy version found
345 logger.warn("policy not found...policy name - " + policyName, e);
351 * This method create a new policy engine.
353 * @return A new policy engine
355 private PolicyEngine getPolicyEngine() {
356 PolicyEngine policyEngine;
358 policyEngine = new PolicyEngine(policyConfiguration.getProperties());
359 } catch (PolicyEngineException e) {
360 throw new PolicyClientException("Exception when creating a new policy engine", e);
366 * Format and send delete Micro Service requests to Policy.
369 * The ModelProperties
370 * @return The response message from Policy
372 public String deleteMicrosService(ModelProperties prop) {
373 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
374 return deletePolicy(prop, policyType);
378 * This method delete the Base policy.
381 * The model Properties
382 * @return A string with the answer from policy
384 public String deleteBasePolicy(ModelProperties prop) {
385 return deletePolicy(prop, PolicyConfigType.Base.toString());
389 * Format and send delete BRMS requests to Policy.
392 * The ModelProperties
393 * @return The response message from policy
395 public String deleteBrms(ModelProperties prop) {
396 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
397 return deletePolicy(prop, policyType);
401 * Format and send delete PAP and PDP requests to Policy.
404 * The ModelProperties
405 * @return The response message from policy
407 protected String deletePolicy(ModelProperties prop, String policyType) {
408 DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
409 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
410 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
412 deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
414 logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
415 deletePolicyParameters.setPolicyComponent("PDP");
416 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
417 deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
418 deletePolicyParameters.setPolicyType(policyType);
419 // send delete request
420 StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
421 logger.info("Deleting policy from PAP...");
422 deletePolicyParameters.setPolicyComponent("PAP");
423 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
424 // send delete request
425 responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
426 return responseMessage.toString();
430 * Send delete request to Policy.
432 * @param deletePolicyParameters
433 * The DeletePolicyParameters
435 * The ModelProperties
436 * @return The response message from policy
438 protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
439 // Verify whether it is triggered by Validation Test button from UI
440 if (prop.isTestOnly()) {
441 return "delete not executed for test action";
443 // API method to create or update Policy.
444 PolicyChangeResponse response = null;
445 String responseMessage = "";
447 logger.info("Attempting to delete policy...");
448 response = getPolicyEngine().deletePolicy(deletePolicyParameters);
449 responseMessage = response.getResponseMessage();
450 } catch (Exception e) {
451 logger.error("Exception occurred during policy communnication", e);
453 logger.info(LOG_POLICY_PREFIX + responseMessage);
454 if (response != null && response.getResponseCode() == 200) {
455 logger.info("Policy delete successful");
457 logger.warn("Policy delete failed: " + responseMessage);
458 throw new BadRequestException("Policy delete failed: " + responseMessage);
460 return responseMessage;