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;
33 import org.apache.camel.CamelContext;
34 import org.apache.camel.Exchange;
35 import org.apache.camel.builder.ExchangeBuilder;
36 import org.onap.clamp.clds.config.ClampProperties;
37 import org.onap.clamp.clds.sdc.controller.installer.BlueprintMicroService;
38 import org.onap.clamp.clds.util.JsonUtils;
39 import org.onap.clamp.loop.template.PolicyModel;
40 import org.onap.clamp.loop.template.PolicyModelId;
41 import org.onap.clamp.loop.template.PolicyModelsService;
42 import org.onap.clamp.policy.pdpgroup.PdpGroup;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.stereotype.Component;
45 import org.yaml.snakeyaml.DumperOptions;
46 import org.yaml.snakeyaml.Yaml;
50 * The class implements the communication with the Policy Engine to retrieve
51 * policy models (tosca). It mainly delegates the physical calls to Camel
55 public class PolicyEngineServices {
56 private final CamelContext camelContext;
58 private final PolicyModelsService policyModelsService;
60 private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
61 private static int retryInterval = 0;
62 private static int retryLimit = 1;
64 public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
65 public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
68 * Default constructor.
70 * @param camelContext Camel context bean
71 * @param clampProperties ClampProperties bean
72 * @param policyModelsService policyModel service
75 public PolicyEngineServices(CamelContext camelContext, ClampProperties clampProperties,
76 PolicyModelsService policyModelsService) {
77 this.camelContext = camelContext;
78 this.policyModelsService = policyModelsService;
79 if (clampProperties.getStringValue(POLICY_RETRY_LIMIT) != null) {
80 retryLimit = Integer.parseInt(clampProperties.getStringValue(POLICY_RETRY_LIMIT));
82 if (clampProperties.getStringValue(POLICY_RETRY_INTERVAL) != null) {
83 retryInterval = Integer.parseInt(clampProperties.getStringValue(POLICY_RETRY_INTERVAL));
88 * This method query Policy engine and create a PolicyModel object with type and version.
90 * @param policyType The policyType id
91 * @param policyVersion The policy version of that type
92 * @return A PolicyModel created from policyEngine data
94 public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
95 if (!policyModelsService.existsById(
96 new PolicyModelId(policyType, policyVersion))) {
97 return policyModelsService.savePolicyModelInNewTransaction(
98 new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion));
100 logger.info("Skipping policy model download as it exists already in the database " + policyType
101 + "/" + policyVersion);
106 * This method query Policy engine and create a PolicyModel object with type and version.
108 * @param microService microservice object instance
109 * @return A PolicyModel created from policyEngine data
111 public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
112 return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
116 * This method synchronize the clamp database and the policy engine.
117 * So it creates the required PolicyModel.
119 public void synchronizeAllPolicies() {
120 LinkedHashMap<String, Object> loadedYaml;
121 loadedYaml = new Yaml().load(downloadAllPolicies());
122 if (loadedYaml == null || loadedYaml.isEmpty()) {
123 logger.warn("getAllPolicyType yaml returned by policy engine could not be decoded, as it's null or empty");
127 LinkedHashMap<String, Object> policyTypesMap = (LinkedHashMap<String, Object>) loadedYaml
128 .get("policy_types");
129 policyTypesMap.forEach((key, value) ->
130 this.createPolicyModelFromPolicyEngine(key,
131 ((String) ((LinkedHashMap<String, Object>) value).get("version"))));
135 * This method can be used to download all policy types + data types defined in
138 * @return A yaml containing all policy Types and all data types
140 public String downloadAllPolicies() {
141 return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models",
146 * This method can be used to download a policy tosca model on the engine.
148 * @param policyType The policy type (id)
149 * @param policyVersion The policy version
150 * @return A string with the whole policy tosca model
152 public String downloadOnePolicy(String policyType, String policyVersion) {
153 logger.info("Downloading the policy model " + policyType + "/" + policyVersion);
154 DumperOptions options = new DumperOptions();
155 options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
156 options.setIndent(2);
157 options.setPrettyFlow(true);
158 options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
159 return (new Yaml(options)).dump(callCamelRoute(
160 ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
161 .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model",
166 * This method can be used to download all Pdp Groups data from policy engine.
168 public void downloadPdpGroups() {
169 String responseBody =
170 callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-pdp-groups",
173 if (responseBody == null || responseBody.isEmpty()) {
174 logger.warn("getPdpGroups returned by policy engine could not be decoded, as it's null or empty");
178 JsonObject jsonObj = JsonUtils.GSON.fromJson(responseBody, JsonObject.class);
180 List<PdpGroup> pdpGroupList = new LinkedList<>();
181 JsonArray itemsArray = (JsonArray) jsonObj.get("groups");
183 for (com.google.gson.JsonElement jsonElement : itemsArray) {
184 JsonObject item = (JsonObject) jsonElement;
185 PdpGroup pdpGroup = JsonUtils.GSON.fromJson(item.toString(), PdpGroup.class);
186 pdpGroupList.add(pdpGroup);
189 policyModelsService.updatePdpGroupInfo(pdpGroupList);
192 private String callCamelRoute(Exchange exchange, String camelFlow, String logMsg) {
193 for (int i = 0; i < retryLimit; i++) {
194 Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
195 if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
196 return (String) exchangeResponse.getIn().getBody();
199 logger.info(logMsg + " query " + retryInterval + "ms before retrying ...");
200 // wait for a while and try to connect to DCAE again
202 Thread.sleep(retryInterval);
203 } catch (InterruptedException e) {
204 Thread.currentThread().interrupt();