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 * ===================================================================
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.config.CldsReferenceProperties;
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.beans.factory.annotation.Value;
59 import org.springframework.context.ApplicationContext;
60 import org.springframework.stereotype.Component;
63 * Policy utility methods - specifically, send the policy.
66 public class PolicyClient {
68 protected static final String POLICY_PREFIX_BASE = "Config_";
69 protected static final String LOG_POLICY_PREFIX = "Response is ";
70 protected static final EELFLogger logger = EELFManager.getInstance().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 CldsReferenceProperties refProp;
82 * Perform BRMS policy type.
88 * @param policyRequestUuid
90 * @return The response message of policy
92 public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
93 String policyRequestUuid) {
94 PolicyParameters policyParameters = new PolicyParameters();
95 // Set Policy Type(Mandatory)
96 policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
97 // Set Policy Name(Mandatory)
98 policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
99 // documentation says this is options, but when tested, got the
100 // following failure: java.lang.Exception: Policy send failed: PE300 -
101 // Data Issue: No policyDescription given.
102 policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
103 policyParameters.setAttributes(attributes);
104 // Set a random UUID(Mandatory)
105 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
106 String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
107 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
108 String policyType = refProp.getStringValue("policy.op.type");
109 push(policyType, prop);
114 * Perform send of microservice policy in JSON.
119 * The ModelProperties
120 * @param policyRequestUuid
121 * The policy Request UUID
122 * @return The response message of policy
124 public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
125 PolicyParameters policyParameters = new PolicyParameters();
127 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
128 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
129 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
130 policyParameters.setConfigBody(policyJson);
131 policyParameters.setConfigBodyType(PolicyType.JSON);
132 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
133 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
134 // Adding this line to clear the policy id from policy name while
135 // pushing to policy engine
136 prop.setPolicyUniqueId("");
137 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
138 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
139 push(policyType, prop);
144 * Perform send of base policy in OTHER type.
147 * The config policy string body
148 * @param configPolicyName
149 * The config policy name of the component that has been
150 * pre-deployed in DCAE
152 * The ModelProperties
153 * @param policyRequestUuid
154 * The policy request UUID
155 * @return The answer from policy call
157 public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
158 String policyRequestUuid) {
159 PolicyParameters policyParameters = new PolicyParameters();
161 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
162 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
163 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
164 policyParameters.setConfigBody(configBody);
165 policyParameters.setConfigBodyType(PolicyType.OTHER);
166 policyParameters.setConfigName("HolmesPolicy");
167 policyParameters.setPolicyName(configPolicyName);
168 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
169 // Adding this line to clear the policy id from policy name while
170 // pushing to policy engine
171 prop.setPolicyUniqueId("");
172 String rtnMsg = send(policyParameters, prop, POLICY_PREFIX_BASE);
173 push(PolicyConfigType.Base.toString(), prop);
178 * Perform send of Microservice policy in OTHER type.
181 * The config policy string body
183 * The ModelProperties
184 * @return The answer from policy call
186 public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
187 PolicyParameters policyParameters = new PolicyParameters();
189 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
190 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
191 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
192 policyParameters.setConfigBody(configBody);
193 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
194 // Adding this line to clear the policy id from policy name while
195 // pushing to policy engine
196 prop.setPolicyUniqueId("");
197 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
198 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
199 push(policyType, prop);
204 * Perform send of policy.
206 * @param policyParameters
207 * The PolicyParameters
209 * The ModelProperties
210 * @return The response message of Policy
212 protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
213 // Verify whether it is triggered by Validation Test button from UI
214 if (prop.isTestOnly()) {
215 return "send not executed for test action";
217 // API method to create or update Policy.
218 PolicyChangeResponse response = null;
219 String responseMessage = "";
220 Date startTime = new Date();
222 List<Integer> versions = getVersions(policyNamePrefix, prop);
223 if (versions.isEmpty()) {
224 LoggingUtils.setTargetContext("Policy", "createPolicy");
225 logger.info("Attempting to create policy for action=" + prop.getActionCd());
226 response = getPolicyEngine().createPolicy(policyParameters);
227 responseMessage = response.getResponseMessage();
229 LoggingUtils.setTargetContext("Policy", "updatePolicy");
230 logger.info("Attempting to update policy for action=" + prop.getActionCd());
231 response = getPolicyEngine().updatePolicy(policyParameters);
232 responseMessage = response.getResponseMessage();
234 } catch (Exception e) {
235 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
236 LoggingUtils.setErrorContext("900", "Policy send error");
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 LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
244 logger.info("Policy send successful");
245 metricsLogger.info("Policy send success");
247 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
248 logger.warn("Policy send failed: " + responseMessage);
249 metricsLogger.info("Policy send failure");
250 throw new BadRequestException("Policy send failed: " + responseMessage);
252 return responseMessage;
256 * Format and send push of policy.
261 * The ModelProperties
262 * @return The response message of policy
264 protected String push(String policyType, ModelProperties prop) {
265 // Verify whether it is triggered by Validation Test button from UI
266 if (prop.isTestOnly()) {
267 return "push not executed for test action";
269 PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
270 // Parameter arguments
271 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
272 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
274 pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
276 logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
277 pushPolicyParameters.setPolicyType(policyType);
278 pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
279 pushPolicyParameters.setRequestID(null);
280 // API method to create or update Policy.
281 PolicyChangeResponse response;
282 String responseMessage = "";
284 LoggingUtils.setTargetContext("Policy", "pushPolicy");
285 logger.info("Attempting to push policy...");
286 response = getPolicyEngine().pushPolicy(pushPolicyParameters);
287 if (response != null) {
288 responseMessage = response.getResponseMessage();
290 } catch (Exception e) {
291 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
292 LoggingUtils.setErrorContext("900", "Policy push error");
293 logger.error("Exception occurred during policy communication", e);
294 throw new PolicyClientException("Exception while communicating with Policy", e);
296 logger.info(LOG_POLICY_PREFIX + responseMessage);
297 if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
298 LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
299 logger.info("Policy push successful");
300 metricsLogger.info("Policy push success");
302 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
303 logger.warn("Policy push failed: " + responseMessage);
304 metricsLogger.info("Policy push failure");
305 throw new BadRequestException("Policy push failed: " + responseMessage);
307 return responseMessage;
311 * Use Get Config Policy API to retrieve the versions for a policy. Return
312 * versions in sorted order. Return empty list if none found.
314 * @param policyNamePrefix
315 * The Policy Name Prefix
317 * The ModelProperties
318 * @return The response message from policy
319 * @throws PolicyConfigException
320 * In case of issues with policy engine
322 protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
323 ArrayList<Integer> versions = new ArrayList<>();
324 ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
325 String policyName = "";
326 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
327 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
329 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
331 logger.info("policyName=" + policyName);
332 configRequestParameters.setPolicyName(policyName);
334 Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
335 for (PolicyConfig policyConfig : response) {
336 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
337 versions.add(version);
339 Collections.sort(versions);
340 logger.info("Policy versions.size()=" + versions.size());
341 } catch (PolicyConfigException e) {
342 // just print warning - if no policy version found
343 logger.warn("policy not found...policy name - " + policyName, e);
349 * This method create a new policy engine.
351 * @return A new policy engine
353 private PolicyEngine getPolicyEngine() {
354 PolicyEngine policyEngine;
356 policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
357 } catch (IOException e1) {
358 throw new PolicyClientException("Exception when opening policy config file", e1);
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");
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;