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.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 LOG_POLICY_PREFIX = "Response is ";
67 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class);
68 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
69 protected static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type";
70 protected static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name";
71 @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}")
72 protected String cldsPolicyConfigFile;
74 protected ApplicationContext appContext;
76 protected RefProp refProp;
79 * Perform BRMS policy type.
85 * @param policyRequestUuid
87 * @return The response message of policy
89 public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop,
90 String policyRequestUuid) {
91 PolicyParameters policyParameters = new PolicyParameters();
92 // Set Policy Type(Mandatory)
93 policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
94 // Set Policy Name(Mandatory)
95 policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
96 // documentation says this is options, but when tested, got the
97 // following failure: java.lang.Exception: Policy send failed: PE300 -
98 // Data Issue: No policyDescription given.
99 policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
100 policyParameters.setAttributes(attributes);
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 String policyType = refProp.getStringValue("policy.op.type");
106 push(policyType, prop);
111 * Perform send of microservice policy in JSON.
116 * The ModelProperties
117 * @param policyRequestUuid
118 * The policy Request UUID
119 * @return The response message of policy
121 public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) {
122 PolicyParameters policyParameters = new PolicyParameters();
124 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
125 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
126 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
127 policyParameters.setConfigBody(policyJson);
128 policyParameters.setConfigBodyType(PolicyType.JSON);
129 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
130 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
131 // Adding this line to clear the policy id from policy name while
132 // pushing to policy engine
133 prop.setPolicyUniqueId("");
134 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
135 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
136 push(policyType, prop);
141 * Perform send of base policy in OTHER type.
144 * The config policy string body
145 * @param configPolicyName
146 * The config policy name of the component that has been
147 * pre-deployed in DCAE
149 * The ModelProperties
150 * @param policyRequestUuid
151 * The policy request UUID
152 * @return The answer from policy call
154 public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop,
155 String policyRequestUuid) {
156 PolicyParameters policyParameters = new PolicyParameters();
158 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
159 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
160 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
161 policyParameters.setConfigBody(configBody);
162 policyParameters.setConfigBodyType(PolicyType.OTHER);
163 policyParameters.setConfigName("HolmesPolicy");
164 policyParameters.setPolicyName(configPolicyName);
165 policyParameters.setRequestID(UUID.fromString(policyRequestUuid));
166 // Adding this line to clear the policy id from policy name while
167 // pushing to policy engine
168 prop.setPolicyUniqueId("");
169 String rtnMsg = send(policyParameters, prop, POLICY_PREFIX_BASE);
170 push(PolicyConfigType.Base.toString(), prop);
175 * Perform send of Microservice policy in OTHER type.
178 * The config policy string body
180 * The ModelProperties
181 * @return The answer from policy call
183 public String sendMicroServiceInOther(String configBody, ModelProperties prop) {
184 PolicyParameters policyParameters = new PolicyParameters();
186 policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
187 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
188 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
189 policyParameters.setConfigBody(configBody);
190 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
191 // Adding this line to clear the policy id from policy name while
192 // pushing to policy engine
193 prop.setPolicyUniqueId("");
194 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
195 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
196 push(policyType, prop);
201 * Perform send of policy.
203 * @param policyParameters
204 * The PolicyParameters
206 * The ModelProperties
207 * @return The response message of Policy
209 protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
210 // Verify whether it is triggered by Validation Test button from UI
211 if (prop.isTestOnly()) {
212 return "send not executed for test action";
214 // API method to create or update Policy.
215 PolicyChangeResponse response = null;
216 String responseMessage = "";
217 Date startTime = new Date();
219 List<Integer> versions = getVersions(policyNamePrefix, prop);
220 if (versions.isEmpty()) {
221 LoggingUtils.setTargetContext("Policy", "createPolicy");
222 logger.info("Attempting to create policy for action=" + prop.getActionCd());
223 response = getPolicyEngine().createPolicy(policyParameters);
224 responseMessage = response.getResponseMessage();
226 LoggingUtils.setTargetContext("Policy", "updatePolicy");
227 logger.info("Attempting to update policy for action=" + prop.getActionCd());
228 response = getPolicyEngine().updatePolicy(policyParameters);
229 responseMessage = response.getResponseMessage();
231 } catch (Exception e) {
232 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
233 LoggingUtils.setErrorContext("900", "Policy send error");
234 logger.error("Exception occurred during policy communication", e);
235 throw new PolicyClientException("Exception while communicating with Policy", e);
237 logger.info(LOG_POLICY_PREFIX + responseMessage);
238 LoggingUtils.setTimeContext(startTime, new Date());
239 if (response.getResponseCode() == 200) {
240 LoggingUtils.setResponseContext("0", "Policy send success", this.getClass().getName());
241 logger.info("Policy send successful");
242 metricsLogger.info("Policy send success");
244 LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName());
245 logger.warn("Policy send failed: " + responseMessage);
246 metricsLogger.info("Policy send failure");
247 throw new BadRequestException("Policy send failed: " + responseMessage);
249 return responseMessage;
253 * Format and send push of policy.
258 * The ModelProperties
259 * @return The response message of policy
261 protected String push(String policyType, ModelProperties prop) {
262 // Verify whether it is triggered by Validation Test button from UI
263 if (prop.isTestOnly()) {
264 return "push not executed for test action";
266 PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
267 // Parameter arguments
268 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
269 pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
271 pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
273 logger.info("Policy Name in Push policy method - " + pushPolicyParameters.getPolicyName());
274 pushPolicyParameters.setPolicyType(policyType);
275 pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
276 pushPolicyParameters.setRequestID(null);
277 // API method to create or update Policy.
278 PolicyChangeResponse response;
279 String responseMessage = "";
281 LoggingUtils.setTargetContext("Policy", "pushPolicy");
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 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
289 LoggingUtils.setErrorContext("900", "Policy push error");
290 logger.error("Exception occurred during policy communication", e);
291 throw new PolicyClientException("Exception while communicating with Policy", e);
293 logger.info(LOG_POLICY_PREFIX + responseMessage);
294 if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
295 LoggingUtils.setResponseContext("0", "Policy push success", this.getClass().getName());
296 logger.info("Policy push successful");
297 metricsLogger.info("Policy push success");
299 LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName());
300 logger.warn("Policy push failed: " + responseMessage);
301 metricsLogger.info("Policy push failure");
302 throw new BadRequestException("Policy push failed: " + responseMessage);
304 return responseMessage;
308 * Use Get Config Policy API to retrieve the versions for a policy. Return
309 * versions in sorted order. Return empty list if none found.
311 * @param policyNamePrefix
312 * The Policy Name Prefix
314 * The ModelProperties
315 * @return The response message from policy
316 * @throws PolicyConfigException
317 * In case of issues with policy engine
319 protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
320 ArrayList<Integer> versions = new ArrayList<>();
321 ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
322 String policyName = "";
323 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
324 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
326 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
328 logger.info("policyName=" + policyName);
329 configRequestParameters.setPolicyName(policyName);
331 Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
332 for (PolicyConfig policyConfig : response) {
333 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
334 versions.add(version);
336 Collections.sort(versions);
337 logger.info("Policy versions.size()=" + versions.size());
338 } catch (PolicyConfigException e) {
339 // just print warning - if no policy version found
340 logger.warn("policy not found...policy name - " + policyName, e);
346 * This method create a new policy engine.
348 * @return A new policy engine
350 private PolicyEngine getPolicyEngine() {
351 PolicyEngine policyEngine;
353 policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
354 } catch (IOException e1) {
355 throw new PolicyClientException("Exception when opening policy config file", e1);
356 } catch (PolicyEngineException e) {
357 throw new PolicyClientException("Exception when creating a new policy engine", e);
363 * Format and send delete Micro Service requests to Policy.
366 * The ModelProperties
367 * @return The response message from Policy
369 public String deleteMicrosService(ModelProperties prop) {
370 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
371 return deletePolicy(prop, policyType);
375 * This method delete the Base policy.
378 * The model Properties
379 * @return A string with the answer from policy
381 public String deleteBasePolicy(ModelProperties prop) {
382 return deletePolicy(prop, PolicyConfigType.Base.toString());
386 * Format and send delete BRMS requests to Policy.
389 * The ModelProperties
390 * @return The response message from policy
392 public String deleteBrms(ModelProperties prop) {
393 String policyType = refProp.getStringValue("policy.op.type");
394 return deletePolicy(prop, policyType);
398 * Format and send delete PAP and PDP requests to Policy.
401 * The ModelProperties
403 * @return The response message from policy
405 protected String deletePolicy(ModelProperties prop, String policyType) {
406 DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
407 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
408 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
410 deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
412 logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
413 deletePolicyParameters.setPolicyComponent("PDP");
414 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
415 deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
416 deletePolicyParameters.setPolicyType(policyType);
417 // send delete request
418 StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
419 logger.info("Deleting policy from PAP...");
420 deletePolicyParameters.setPolicyComponent("PAP");
421 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
422 // send delete request
423 responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
424 return responseMessage.toString();
428 * Send delete request to Policy.
430 * @param deletePolicyParameters
431 * The DeletePolicyParameters
433 * The ModelProperties
434 * @return The response message from policy
436 protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
437 // Verify whether it is triggered by Validation Test button from UI
438 if (prop.isTestOnly()) {
439 return "delete not executed for test action";
441 // API method to create or update Policy.
442 PolicyChangeResponse response = null;
443 String responseMessage = "";
445 logger.info("Attempting to delete policy...");
446 response = getPolicyEngine().deletePolicy(deletePolicyParameters);
447 responseMessage = response.getResponseMessage();
448 } catch (Exception e) {
449 logger.error("Exception occurred during policy communnication", e);
451 logger.info(LOG_POLICY_PREFIX + responseMessage);
452 if (response != null && response.getResponseCode() == 200) {
453 logger.info("Policy delete successful");
455 logger.warn("Policy delete failed: " + responseMessage);
456 throw new BadRequestException("Policy delete failed: " + responseMessage);
458 return responseMessage;