2302cc891eed008df3f1e33c8246a632524b700e
[clamp.git] / src / main / java / org / onap / clamp / clds / client / PolicyEngineServices.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights
6  *                             reserved.
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
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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  *
22  */
23
24 package org.onap.clamp.clds.client;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.util.ArrayList;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Map;
33
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;
47
48
49
50
51 /**
52  * The class implements the communication with the Policy Engine to retrieve
53  * policy models (tosca). It mainly delegates the physical calls to Camel
54  * engine.
55  *
56  */
57 @Component
58 public class PolicyEngineServices {
59     private final CamelContext camelContext;
60
61     private final PolicyModelsRepository policyModelsRepository;
62
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;
68
69     public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
70     public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
71
72     /**
73      * Default constructor.
74      *
75      * @param camelContext Camel context bean
76      * @param clampProperties ClampProperties bean
77      * @param policyModelsRepository policyModel repository bean
78      */
79     @Autowired
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));
86         }
87         if (clampProperties.getStringValue(POLICY_RETRY_INTERVAL) != null) {
88             retryInterval = Integer.valueOf(clampProperties.getStringValue(POLICY_RETRY_INTERVAL));
89         }
90     }
91
92     /**
93      * This method query Policy engine and create a PolicyModel object with type and version.
94      *
95      * @param policyType The policyType id
96      * @param policyVersion The policy version of that type
97      * @return A PolicyModel created from policyEngine data
98      */
99     public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
100         return new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion);
101     }
102
103     /**
104      * This method query Policy engine and create a PolicyModel object with type and version.
105      *
106      * @param microService microservice object instance
107      * @return A PolicyModel created from policyEngine data
108      */
109     public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
110         return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
111     }
112
113     /**
114      * Thie method creates an PolicyModel in Db if it does not exist.
115      *
116      * @param policyModel The policyModel to save
117      */
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);
123         }
124     }
125
126     /**
127      * This method synchronize the clamp database and the policy engine.
128      * So it creates the required PolicyModel.
129      */
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");
135             return;
136         }
137
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);
142
143             createPolicyInDbIfNeeded(
144                     createPolicyModelFromPolicyEngine(policyTypeEntry.getKey(),
145                             ((String) ((LinkedHashMap<String, Object>) policyTypeEntry.getValue()).get("version"))));
146         });
147     }
148
149     /**
150      * This method can be used to download all policy types + data types defined in
151      * policy engine.
152      * 
153      * @return A yaml containing all policy Types and all data types
154      * @throws InterruptedException In case of issue when sleeping during the retry
155      */
156     public String downloadAllPolicies() {
157         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models");
158     }
159
160     /**
161      * This method can be used to download a policy tosca model on the engine.
162      * 
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
167      */
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");
171     }
172
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();
178             } else {
179                 logger.info("Policy query " + retryInterval + "ms before retrying ...");
180                 // wait for a while and try to connect to DCAE again
181                 try {
182                     Thread.sleep(retryInterval);
183                 } catch (InterruptedException e) {
184                     Thread.currentThread().interrupt();
185                 }
186             }
187         }
188         return "";
189     }
190 }