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;
29 import java.util.ArrayList;
30 import java.util.LinkedHashMap;
31 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.loop.template.PolicyModel;
40 import org.onap.clamp.loop.template.PolicyModelId;
41 import org.onap.clamp.loop.template.PolicyModelsRepository;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Component;
44 import org.springframework.transaction.annotation.Propagation;
45 import org.springframework.transaction.annotation.Transactional;
46 import org.yaml.snakeyaml.Yaml;
52 * The class implements the communication with the Policy Engine to retrieve
53 * policy models (tosca). It mainly delegates the physical calls to Camel
58 public class PolicyEngineServices {
59 private final CamelContext camelContext;
61 private final PolicyModelsRepository policyModelsRepository;
63 private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
64 private static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
65 private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
66 private static int retryInterval = 0;
67 private static int retryLimit = 1;
69 public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
70 public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
73 * Default constructor.
75 * @param camelContext Camel context bean
76 * @param clampProperties ClampProperties bean
77 * @param policyModelsRepository policyModel repository bean
80 public PolicyEngineServices(CamelContext camelContext, ClampProperties clampProperties,
81 PolicyModelsRepository policyModelsRepository) {
82 this.camelContext = camelContext;
83 this.policyModelsRepository = policyModelsRepository;
84 if (clampProperties.getStringValue(POLICY_RETRY_LIMIT) != null) {
85 retryLimit = Integer.valueOf(clampProperties.getStringValue(POLICY_RETRY_LIMIT));
87 if (clampProperties.getStringValue(POLICY_RETRY_INTERVAL) != null) {
88 retryInterval = Integer.valueOf(clampProperties.getStringValue(POLICY_RETRY_INTERVAL));
93 * This method query Policy engine and create a PolicyModel object with type and version.
95 * @param policyType The policyType id
96 * @param policyVersion The policy version of that type
97 * @return A PolicyModel created from policyEngine data
99 public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
100 return new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion);
104 * This method query Policy engine and create a PolicyModel object with type and version.
106 * @param microService microservice object instance
107 * @return A PolicyModel created from policyEngine data
109 public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
110 return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
114 * Thie method creates an PolicyModel in Db if it does not exist.
116 * @param policyModel The policyModel to save
118 @Transactional(propagation = Propagation.REQUIRES_NEW)
119 public void createPolicyInDbIfNeeded(PolicyModel policyModel) {
120 if (!policyModelsRepository
121 .existsById(new PolicyModelId(policyModel.getPolicyModelType(), policyModel.getVersion()))) {
122 policyModelsRepository.save(policyModel);
127 * This method synchronize the clamp database and the policy engine.
128 * So it creates the required PolicyModel.
130 public void synchronizeAllPolicies() {
131 LinkedHashMap<String, Object> loadedYaml;
132 loadedYaml = new Yaml().load(downloadAllPolicies());
133 if (loadedYaml == null || loadedYaml.isEmpty()) {
134 logger.warn("getAllPolicyType yaml returned by policy engine could not be decoded, as it's null or empty");
138 List<LinkedHashMap<String, Object>> policyTypesList = (List<LinkedHashMap<String, Object>>) loadedYaml
139 .get("policy_types");
140 policyTypesList.parallelStream().forEach(policyType -> {
141 Map.Entry<String, Object> policyTypeEntry = (Map.Entry<String, Object>) new ArrayList(policyType.entrySet()).get(0);
143 createPolicyInDbIfNeeded(
144 createPolicyModelFromPolicyEngine(policyTypeEntry.getKey(),
145 ((String) ((LinkedHashMap<String, Object>) policyTypeEntry.getValue()).get("version"))));
150 * This method can be used to download all policy types + data types defined in
153 * @return A yaml containing all policy Types and all data types
154 * @throws InterruptedException In case of issue when sleeping during the retry
156 public String downloadAllPolicies() {
157 return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models");
161 * This method can be used to download a policy tosca model on the engine.
163 * @param policyType The policy type (id)
164 * @param policyVersion The policy version
165 * @return A string with the whole policy tosca model
166 * @throws InterruptedException In case of issue when sleeping during the retry
168 public String downloadOnePolicy(String policyType, String policyVersion) {
169 return callCamelRoute(ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
170 .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model");
173 private String callCamelRoute(Exchange exchange, String camelFlow) {
174 for (int i = 0; i < retryLimit; i++) {
175 Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
176 if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
177 return (String) exchangeResponse.getIn().getBody();
179 logger.info("Policy query " + retryInterval + "ms before retrying ...");
180 // wait for a while and try to connect to DCAE again
182 Thread.sleep(retryInterval);
183 } catch (InterruptedException e) {
184 Thread.currentThread().interrupt();