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 {
66 protected static final String POLICY_PREFIX_BASE = "Config_";
67 protected static final String POLICY_PREFIX_BRMS_PARAM = "Config_BRMS_Param_";
68 protected static final String POLICY_PREFIX_MICROSERVICE = "Config_MS_";
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 RefProp 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.setOnapName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
191 policyParameters.setEcompName(refProp.getStringValue(POLICY_ONAPNAME_PROPERTY_NAME));
192 policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
193 policyParameters.setConfigBody(configBody);
194 String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
195 // Adding this line to clear the policy id from policy name while
196 // pushing to policy engine
197 prop.setPolicyUniqueId("");
198 String rtnMsg = send(policyParameters, prop, policyNamePrefix);
199 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
200 push(policyType, prop);
205 * Perform send of policy.
207 * @param policyParameters
208 * The PolicyParameters
210 * The ModelProperties
211 * @return The response message of Policy
213 protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) {
214 // Verify whether it is triggered by Validation Test button from UI
215 if (prop.isTestOnly()) {
216 return "send not executed for test action";
218 // API method to create or update Policy.
219 PolicyChangeResponse response = null;
220 String responseMessage = "";
221 Date startTime = new Date();
223 List<Integer> versions = getVersions(policyNamePrefix, prop);
224 if (versions.isEmpty()) {
225 LoggingUtils.setTargetContext("Policy", "createPolicy");
226 logger.info("Attempting to create policy for action=" + prop.getActionCd());
227 response = getPolicyEngine().createPolicy(policyParameters);
228 responseMessage = response.getResponseMessage();
230 LoggingUtils.setTargetContext("Policy", "updatePolicy");
231 logger.info("Attempting to update policy for action=" + prop.getActionCd());
232 response = getPolicyEngine().updatePolicy(policyParameters);
233 responseMessage = response.getResponseMessage();
235 } catch (Exception e) {
236 logger.error("Exception occurred during policy communication", e);
237 throw new PolicyClientException("Exception while communicating with Policy", e);
239 logger.info(LOG_POLICY_PREFIX + responseMessage);
240 LoggingUtils.setTimeContext(startTime, new Date());
241 if (response.getResponseCode() == 200) {
242 logger.info("Policy send successful");
243 metricsLogger.info("Policy send success");
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 logger.info("Attempting to push policy...");
282 response = getPolicyEngine().pushPolicy(pushPolicyParameters);
283 if (response != null) {
284 responseMessage = response.getResponseMessage();
286 } catch (Exception e) {
287 logger.error("Exception occurred during policy communication", e);
288 throw new PolicyClientException("Exception while communicating with Policy", e);
290 logger.info(LOG_POLICY_PREFIX + responseMessage);
291 if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
292 logger.info("Policy push successful");
294 logger.warn("Policy push failed: " + responseMessage);
295 throw new BadRequestException("Policy push failed: " + responseMessage);
297 return responseMessage;
301 * Use Get Config Policy API to retrieve the versions for a policy. Return
302 * versions in sorted order. Return empty list if none found.
304 * @param policyNamePrefix
305 * The Policy Name Prefix
307 * The ModelProperties
308 * @return The response message from policy
309 * @throws PolicyConfigException
310 * In case of issues with policy engine
312 protected List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException {
313 ArrayList<Integer> versions = new ArrayList<>();
314 ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
315 String policyName = "";
316 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
317 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId();
319 policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
321 logger.info("policyName=" + policyName);
322 configRequestParameters.setPolicyName(policyName);
324 Collection<PolicyConfig> response = getPolicyEngine().getConfig(configRequestParameters);
325 for (PolicyConfig policyConfig : response) {
326 Integer version = Integer.valueOf(policyConfig.getPolicyVersion());
327 versions.add(version);
329 Collections.sort(versions);
330 logger.info("Policy versions.size()=" + versions.size());
331 } catch (PolicyConfigException e) {
332 // just print warning - if no policy version found
333 logger.warn("policy not found...policy name - " + policyName, e);
339 * This method create a new policy engine.
341 * @return A new policy engine
343 private PolicyEngine getPolicyEngine() {
344 PolicyEngine policyEngine;
346 policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
347 } catch (IOException e1) {
348 throw new PolicyClientException("Exception when opening policy config file", e1);
349 } catch (PolicyEngineException e) {
350 throw new PolicyClientException("Exception when creating a new policy engine", e);
356 * Format and send delete Micro Service requests to Policy.
359 * The ModelProperties
360 * @return The response message from Policy
362 public String deleteMicrosService(ModelProperties prop) {
363 String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
364 return deletePolicy(prop, policyType);
368 * This method delete the Base policy.
371 * The model Properties
372 * @return A string with the answer from policy
374 public String deleteBasePolicy(ModelProperties prop) {
375 return deletePolicy(prop, PolicyConfigType.Base.toString());
379 * Format and send delete BRMS requests to Policy.
382 * The ModelProperties
383 * @return The response message from policy
385 public String deleteBrms(ModelProperties prop) {
386 String policyType = refProp.getStringValue("policy.op.type");
387 return deletePolicy(prop, policyType);
391 * Format and send delete PAP and PDP requests to Policy.
394 * The ModelProperties
395 * @return The response message from policy
397 protected String deletePolicy(ModelProperties prop, String policyType) {
398 DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
399 if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) {
400 deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId());
402 deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
404 logger.info("Policy Name in delete policy method - " + deletePolicyParameters.getPolicyName());
405 deletePolicyParameters.setPolicyComponent("PDP");
406 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
407 deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
408 deletePolicyParameters.setPolicyType(policyType);
409 // send delete request
410 StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop));
411 logger.info("Deleting policy from PAP...");
412 deletePolicyParameters.setPolicyComponent("PAP");
413 deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
414 // send delete request
415 responseMessage.append(sendDeletePolicy(deletePolicyParameters, prop));
416 return responseMessage.toString();
420 * Send delete request to Policy.
422 * @param deletePolicyParameters
423 * The DeletePolicyParameters
425 * The ModelProperties
426 * @return The response message from policy
428 protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) {
429 // Verify whether it is triggered by Validation Test button from UI
430 if (prop.isTestOnly()) {
431 return "delete not executed for test action";
433 // API method to create or update Policy.
434 PolicyChangeResponse response = null;
435 String responseMessage = "";
437 logger.info("Attempting to delete policy...");
438 response = getPolicyEngine().deletePolicy(deletePolicyParameters);
439 responseMessage = response.getResponseMessage();
440 } catch (Exception e) {
441 logger.error("Exception occurred during policy communnication", e);
443 logger.info(LOG_POLICY_PREFIX + responseMessage);
444 if (response != null && response.getResponseCode() == 200) {
445 logger.info("Policy delete successful");
447 logger.warn("Policy delete failed: " + responseMessage);
448 throw new BadRequestException("Policy delete failed: " + responseMessage);
450 return responseMessage;