2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 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;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.JsonArray;
29 import com.google.gson.JsonObject;
30 import java.util.LinkedHashMap;
31 import java.util.LinkedList;
32 import java.util.List;
34 import org.apache.camel.CamelContext;
35 import org.apache.camel.Exchange;
36 import org.apache.camel.builder.ExchangeBuilder;
37 import org.onap.clamp.clds.config.ClampProperties;
38 import org.onap.clamp.clds.sdc.controller.installer.BlueprintMicroService;
39 import org.onap.clamp.clds.util.JsonUtils;
40 import org.onap.clamp.loop.template.PolicyModel;
41 import org.onap.clamp.loop.template.PolicyModelId;
42 import org.onap.clamp.loop.template.PolicyModelsService;
43 import org.onap.clamp.policy.pdpgroup.PdpGroup;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
46 import org.yaml.snakeyaml.DumperOptions;
47 import org.yaml.snakeyaml.Yaml;
51 * The class implements the communication with the Policy Engine to retrieve
52 * policy models (tosca). It mainly delegates the physical calls to Camel
56 public class PolicyEngineServices {
57 private final CamelContext camelContext;
59 private final PolicyModelsService policyModelsService;
61 private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
62 private static int retryInterval = 0;
63 private static int retryLimit = 1;
65 public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
66 public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
69 * Default constructor.
71 * @param camelContext Camel context bean
72 * @param clampProperties ClampProperties bean
73 * @param policyModelsService policyModel service
76 public PolicyEngineServices(CamelContext camelContext, ClampProperties clampProperties,
77 PolicyModelsService policyModelsService) {
78 this.camelContext = camelContext;
79 this.policyModelsService = policyModelsService;
80 if (clampProperties.getStringValue(POLICY_RETRY_LIMIT) != null) {
81 retryLimit = Integer.parseInt(clampProperties.getStringValue(POLICY_RETRY_LIMIT));
83 if (clampProperties.getStringValue(POLICY_RETRY_INTERVAL) != null) {
84 retryInterval = Integer.parseInt(clampProperties.getStringValue(POLICY_RETRY_INTERVAL));
89 * This method query Policy engine and create a PolicyModel object with type and version.
91 * @param policyType The policyType id
92 * @param policyVersion The policy version of that type
93 * @return A PolicyModel created from policyEngine data
95 public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
96 if (!policyModelsService.existsById(
97 new PolicyModelId(policyType, policyVersion))) {
98 return policyModelsService.savePolicyModelInNewTransaction(
99 new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion));
101 logger.info("Skipping policy model download as it exists already in the database " + policyType
102 + "/" + policyVersion);
107 * This method query Policy engine and create a PolicyModel object with type and version.
109 * @param microService microservice object instance
110 * @return A PolicyModel created from policyEngine data
112 public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
113 return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
117 * This method synchronize the clamp database and the policy engine.
118 * So it creates the required PolicyModel.
120 public void synchronizeAllPolicies() {
121 LinkedHashMap<String, Object> loadedYaml;
122 loadedYaml = new Yaml().load(downloadAllPolicies());
123 if (loadedYaml == null || loadedYaml.isEmpty()) {
124 logger.warn("getAllPolicyType yaml returned by policy engine could not be decoded, as it's null or empty");
128 LinkedHashMap<String, Object> policyTypesMap = (LinkedHashMap<String, Object>) loadedYaml
129 .get("policy_types");
130 policyTypesMap.forEach((key, value) ->
131 this.createPolicyModelFromPolicyEngine(key,
132 ((String) ((LinkedHashMap<String, Object>) value).get("version"))));
136 * This method can be used to download all policy types + data types defined in
139 * @return A yaml containing all policy Types and all data types
141 public String downloadAllPolicies() {
142 return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models",
147 * This method can be used to download a policy tosca model on the engine.
149 * @param policyType The policy type (id)
150 * @param policyVersion The policy version
151 * @return A string with the whole policy tosca model
153 public String downloadOnePolicy(String policyType, String policyVersion) {
154 logger.info("Downloading the policy model " + policyType + "/" + policyVersion);
155 DumperOptions options = new DumperOptions();
156 options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
157 options.setIndent(4);
158 options.setPrettyFlow(true);
159 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
160 Yaml yamlParser = new Yaml(options);
161 return yamlParser.dump((Map<String, Object>) yamlParser.load(callCamelRoute(
162 ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
163 .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model",
168 * This method can be used to download all Pdp Groups data from policy engine.
170 public void downloadPdpGroups() {
171 String responseBody =
172 callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-pdp-groups",
175 if (responseBody == null || responseBody.isEmpty()) {
176 logger.warn("getPdpGroups returned by policy engine could not be decoded, as it's null or empty");
180 JsonObject jsonObj = JsonUtils.GSON.fromJson(responseBody, JsonObject.class);
182 List<PdpGroup> pdpGroupList = new LinkedList<>();
183 JsonArray itemsArray = (JsonArray) jsonObj.get("groups");
185 for (com.google.gson.JsonElement jsonElement : itemsArray) {
186 JsonObject item = (JsonObject) jsonElement;
187 PdpGroup pdpGroup = JsonUtils.GSON.fromJson(item.toString(), PdpGroup.class);
188 pdpGroupList.add(pdpGroup);
191 policyModelsService.updatePdpGroupInfo(pdpGroupList);
194 private String callCamelRoute(Exchange exchange, String camelFlow, String logMsg) {
195 for (int i = 0; i < retryLimit; i++) {
196 Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
197 if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
198 return (String) exchangeResponse.getIn().getBody();
201 logger.info(logMsg + " query " + retryInterval + "ms before retrying ...");
202 // wait for a while and try to connect to DCAE again
204 Thread.sleep(retryInterval);
205 } catch (InterruptedException e) {
206 Thread.currentThread().interrupt();