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 PolicyEngine policyEngine;
68 protected static final String LOG_POLICY_PREFIX = "Response is ";
69 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
70 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
71 public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
72 public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
73 public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix";
74 public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix";
75 public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix";
76 public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type";
78 protected ApplicationContext appContext;
80 protected ClampProperties refProp;
82 private PolicyConfiguration policyConfiguration;
85 * Perform BRMS policy type.
91 * @param policyRequestUuid
93 * @return The response message of policy
95 public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
96 String policyRequestUuid) {
97 PolicyParameters policyParameters = new PolicyParameters();
98 // Set Policy Type(Mandatory)
99 policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
100 // Set Policy Name(Mandatory)
101 policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
102 // documentation says this is options, but when tested, got the
103 // following failure: java.lang.Exception: Policy send failed: PE300 -
104 // Data Issue: No policyDescription given.
105 policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
106 policyParameters.setAttributes(attributes);
107 // Set a random UUID(Mandatory)
108 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
109 String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
110 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
111 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
112 push(policyType, prop);
117 * Perform send of microservice policy in JSON.
122 * The ModelProperties
123 * @param policyRequestUuid
124 * The policy Request UUID
125 * @return The response message of policy
127 public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
128 PolicyParameters policyParameters = new PolicyParameters();
130 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
131 policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
132 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
133 policyParameters.setConfigBody(policyJson);
134 policyParameters.setConfigBodyType(PolicyType.JSON);
135 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
136 String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
137 // Adding this line to clear the policy id from policy name while
138 // pushing to policy engine
139 prop.setPolicyUniqueId("");
140 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
141 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
142 push(policyType, prop);
147 * Perform send of base policy in OTHER type.
150 * The config policy string body
151 * @param configPolicyName
152 * The config policy name of the component that has been
153 * pre-deployed in DCAE
155 * The ModelProperties
156 * @param policyRequestUuid
157 * The policy request UUID
158 * @return The answer from policy call
160 public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
161 String policyRequestUuid) {
162 PolicyParameters policyParameters = new PolicyParameters();
164 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
165 policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
166 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
167 policyParameters.setConfigBody(configBody);
168 policyParameters.setConfigBodyType(PolicyType.OTHER);
169 policyParameters.setConfigName("HolmesPolicy");
170 policyParameters.setPolicyName(configPolicyName);
171 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
172 // Adding this line to clear the policy id from policy name while
173 // pushing to policy engine
174 prop.setPolicyUniqueId("");
175 String rtnMsg = send(policyParameters, prop, refProp.getStringValue(POLICY_BASENAME_PREFIX_PROPERTY_NAME));
176 push(PolicyConfigType.Base.toString(), prop);
181 * Perform send of Microservice policy in OTHER type.
184 * The config policy string body
186 * The ModelProperties
187 * @return The answer from policy call
189 public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
190 PolicyParameters policyParameters = new PolicyParameters();
192 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
193 policyParameters.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
194 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
195 policyParameters.setConfigBody(configBody);
196 String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
197 // Adding this line to clear the policy id from policy name while
198 // pushing to policy engine
199 prop.setPolicyUniqueId("");
200 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
201 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
202 push(policyType, prop);
207 * Perform send of policy.
209 * @param policyParameters
210 * The PolicyParameters
212 * The ModelProperties
213 * @return The response message of Policy
215 protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
216 // Verify whether it is triggered by Validation Test button from UI
217 if (prop.isTestOnly()) {
218 return "send not executed for test action";
220 // API method to create or update Policy.
221 PolicyChangeResponse response = null;
222 String responseMessage = "";
223 Date startTime = new Date();
225 List<Integer> versions = getVersions(policyNamePrefix, prop);
226 if (versions.isEmpty()) {
227 LoggingUtils.setTargetContext("Policy", "createPolicy");
228 logger.info("Attempting to create policy for action=" + prop.getActionCd());
229 response = getPolicyEngine().createPolicy(policyParameters);
230 responseMessage = response.getResponseMessage();
232 LoggingUtils.setTargetContext("Policy", "updatePolicy");
233 logger.info("Attempting to update policy for action=" + prop.getActionCd());
234 response = getPolicyEngine().updatePolicy(policyParameters);
235 responseMessage = response.getResponseMessage();
237 } catch (Exception e) {
238 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
239 LoggingUtils.setErrorContext("900", "Policy send error");
240 logger.error("Exception occurred during policy communication", e);
241 throw new PolicyClientException("Exception while communicating with Policy", e);
243 logger.info(LOG_POLICY_PREFIX + responseMessage);
244 LoggingUtils.setTimeContext(startTime, new Date());
245 if (response.getResponseCode() == 200) {
246 LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
247 logger.info("Policy send successful");
248 metricsLogger.info("Policy send success");
250 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
251 logger.warn("Policy send failed: " + responseMessage);
252 metricsLogger.info("Policy send failure");
253 throw new BadRequestException("Policy send failed: " + responseMessage);
255 return responseMessage;
259 * Format and send push of policy.
264 * The ModelProperties
265 * @return The response message of policy
267 protected String push(String policyType, ModelProperties prop) {
268 // Verify whether it is triggered by Validation Test button from UI
269 if (prop.isTestOnly()) {
270 return "push not executed for test action";
272 PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
273 // Parameter arguments
274 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
275 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
277 pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
279 logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
280 pushPolicyParameters.setPolicyType(policyType);
281 pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
282 pushPolicyParameters.setRequestID(null);
283 // API method to create or update Policy.
284 PolicyChangeResponse response;
285 String responseMessage = "";
287 LoggingUtils.setTargetContext("Policy", "pushPolicy");
288 logger.info("Attempting to push policy...");
289 response = getPolicyEngine().pushPolicy(pushPolicyParameters);
290 if (response != null) {
291 responseMessage = response.getResponseMessage();
293 } catch (Exception e) {
294 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
295 LoggingUtils.setErrorContext("900", "Policy push error");
296 logger.error("Exception occurred during policy communication", e);
297 throw new PolicyClientException("Exception while communicating with Policy", e);
299 logger.info(LOG_POLICY_PREFIX + responseMessage);
300 if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
301 LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
302 logger.info("Policy push successful");
303 metricsLogger.info("Policy push success");
305 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
306 logger.warn("Policy push failed: " + responseMessage);
307 metricsLogger.info("Policy push failure");
308 throw new BadRequestException("Policy push failed: " + responseMessage);
310 return responseMessage;
314 * Use Get Config Policy API to retrieve the versions for a policy. Return
315 * versions in sorted order. Return empty list if none found.
317 * @param policyNamePrefix
318 * The Policy Name Prefix
320 * The ModelProperties
321 * @return The response message from policy
322 * @throws PolicyConfigException
323 * In case of issues with policy engine
325 protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
326 ArrayList<Integer> versions = new ArrayList<>();
327 ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
328 String policyName = "";
329 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
330 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
332 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
334 logger.info("Search in Policy Engine for policyName=" + policyName);
335 configRequestParameters.setPolicyName(policyName);
337 Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
338 for (PolicyConfig policyConfig : response) {
339 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
340 versions.add(version);
342 Collections.sort(versions);
343 logger.info("Policy versions.size()=" + versions.size());
344 } catch (PolicyConfigException e) {
345 // just print warning - if no policy version found
346 logger.warn("policy not found...policy name - " + policyName, e);
352 * This method create a new policy engine.
354 * @return A new policy engine
356 private synchronized PolicyEngine getPolicyEngine() {
358 if (policyEngine == null) {
359 policyEngine = new PolicyEngine(policyConfiguration.getProperties());
361 } catch (PolicyEngineException e) {
362 throw new PolicyClientException("Exception when creating a new policy engine", e);
368 * Format and send delete Micro Service requests to Policy.
371 * The ModelProperties
372 * @return The response message from Policy
374 public String deleteMicrosService(ModelProperties prop) {
375 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
376 return deletePolicy(prop, policyType);
380 * This method delete the Base policy.
383 * The model Properties
384 * @return A string with the answer from policy
386 public String deleteBasePolicy(ModelProperties prop) {
387 return deletePolicy(prop, PolicyConfigType.Base.toString());
391 * Format and send delete BRMS requests to Policy.
394 * The ModelProperties
395 * @return The response message from policy
397 public String deleteBrms(ModelProperties prop) {
398 String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
399 return deletePolicy(prop, policyType);
403 * Format and send delete PAP and PDP requests to Policy.
406 * The ModelProperties
407 * @return The response message from policy
409 protected String deletePolicy(ModelProperties prop, String policyType) {
410 DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
411 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
412 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
414 deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
416 logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
417 deletePolicyParameters.setPolicyComponent("PDP");
418 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
419 deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
420 deletePolicyParameters.setPolicyType(policyType);
421 // send delete request
422 StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
423 logger.info("Deleting policy from PAP...");
424 deletePolicyParameters.setPolicyComponent("PAP");
425 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
426 // send delete request
427 responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
428 return responseMessage.toString();
432 * Send delete request to Policy.
434 * @param deletePolicyParameters
435 * The DeletePolicyParameters
437 * The ModelProperties
438 * @return The response message from policy
440 protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
441 // Verify whether it is triggered by Validation Test button from UI
442 if (prop.isTestOnly()) {
443 return "delete not executed for test action";
445 // API method to create or update Policy.
446 PolicyChangeResponse response = null;
447 String responseMessage = "";
449 logger.info("Attempting to delete policy...");
450 response = getPolicyEngine().deletePolicy(deletePolicyParameters);
451 responseMessage = response.getResponseMessage();
452 } catch (Exception e) {
453 logger.error("Exception occurred during policy communnication", e);
455 logger.info(LOG_POLICY_PREFIX + responseMessage);
456 if (response != null && response.getResponseCode() == 200) {
457 logger.info("Policy delete successful");
459 logger.warn("Policy delete failed: " + responseMessage);
460 throw new BadRequestException("Policy delete failed: " + responseMessage);
462 return responseMessage;