5e6d9d98d011f2dd7fbe37f5df08472f3cf1f812
[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 import com.google.gson.JsonArray;
29 import com.google.gson.JsonObject;
30 import java.util.Iterator;
31 import java.util.LinkedHashMap;
32 import java.util.LinkedList;
33 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.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.Yaml;
46
47
48 /**
49  * The class implements the communication with the Policy Engine to retrieve
50  * policy models (tosca). It mainly delegates the physical calls to Camel
51  * engine.
52  */
53 @Component
54 public class PolicyEngineServices {
55     private final CamelContext camelContext;
56
57     private final PolicyModelsService policyModelsService;
58
59     private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
60     private static int retryInterval = 0;
61     private static int retryLimit = 1;
62
63     public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
64     public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
65
66     /**
67      * Default constructor.
68      *
69      * @param camelContext        Camel context bean
70      * @param clampProperties     ClampProperties bean
71      * @param policyModelsService policyModel service
72      */
73     @Autowired
74     public PolicyEngineServices(CamelContext camelContext, ClampProperties clampProperties,
75                                 PolicyModelsService policyModelsService) {
76         this.camelContext = camelContext;
77         this.policyModelsService = policyModelsService;
78         if (clampProperties.getStringValue(POLICY_RETRY_LIMIT) != null) {
79             retryLimit = Integer.parseInt(clampProperties.getStringValue(POLICY_RETRY_LIMIT));
80         }
81         if (clampProperties.getStringValue(POLICY_RETRY_INTERVAL) != null) {
82             retryInterval = Integer.parseInt(clampProperties.getStringValue(POLICY_RETRY_INTERVAL));
83         }
84     }
85
86     /**
87      * This method query Policy engine and create a PolicyModel object with type and version.
88      *
89      * @param policyType    The policyType id
90      * @param policyVersion The policy version of that type
91      * @return A PolicyModel created from policyEngine data
92      */
93     public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
94         return new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion);
95     }
96
97     /**
98      * This method query Policy engine and create a PolicyModel object with type and version.
99      *
100      * @param microService microservice object instance
101      * @return A PolicyModel created from policyEngine data
102      */
103     public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
104         return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
105     }
106
107     /**
108      * This method synchronize the clamp database and the policy engine.
109      * So it creates the required PolicyModel.
110      */
111     public void synchronizeAllPolicies() {
112         LinkedHashMap<String, Object> loadedYaml;
113         loadedYaml = new Yaml().load(downloadAllPolicies());
114         if (loadedYaml == null || loadedYaml.isEmpty()) {
115             logger.warn("getAllPolicyType yaml returned by policy engine could not be decoded, as it's null or empty");
116             return;
117         }
118
119         LinkedHashMap<String, Object> policyTypesMap = (LinkedHashMap<String, Object>) loadedYaml
120                 .get("policy_types");
121         policyTypesMap.entrySet().stream().forEach(entryPolicyType -> {
122             policyModelsService.createPolicyInDbIfNeeded(
123                     createPolicyModelFromPolicyEngine(entryPolicyType.getKey(),
124                             ((String) ((LinkedHashMap<String, Object>) entryPolicyType.getValue()).get("version"))));
125         });
126     }
127
128     /**
129      * This method can be used to download all policy types + data types defined in
130      * policy engine.
131      *
132      * @return A yaml containing all policy Types and all data types
133      */
134     public String downloadAllPolicies() {
135         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models",
136                 "Get all policies");
137     }
138
139     /**
140      * This method can be used to download a policy tosca model on the engine.
141      *
142      * @param policyType    The policy type (id)
143      * @param policyVersion The policy version
144      * @return A string with the whole policy tosca model
145      */
146     public String downloadOnePolicy(String policyType, String policyVersion) {
147         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
148                         .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model",
149                 "Get one policy");
150     }
151
152     /**
153      * This method can be used to download all Pdp Groups data from policy engine.
154      */
155     public void downloadPdpGroups() {
156         String responseBody =
157                 callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-pdp-groups",
158                         "Get Pdp Groups");
159
160         if (responseBody == null || responseBody.isEmpty()) {
161             logger.warn("getPdpGroups returned by policy engine could not be decoded, as it's null or empty");
162             return;
163         }
164
165         JsonObject jsonObj = JsonUtils.GSON.fromJson(responseBody, JsonObject.class);
166
167         List<PdpGroup> pdpGroupList = new LinkedList<>();
168         JsonArray itemsArray = (JsonArray) jsonObj.get("groups");
169
170         Iterator it = itemsArray.iterator();
171         while (it.hasNext()) {
172             JsonObject item = (JsonObject) it.next();
173             PdpGroup pdpGroup = JsonUtils.GSON.fromJson(item.toString(), PdpGroup.class);
174             pdpGroupList.add(pdpGroup);
175         }
176
177         policyModelsService.updatePdpGroupInfo(pdpGroupList);
178     }
179
180     private String callCamelRoute(Exchange exchange, String camelFlow, String logMsg) {
181         for (int i = 0; i < retryLimit; i++) {
182             Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
183             if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
184                 return (String) exchangeResponse.getIn().getBody();
185             } else {
186                 logger.info(logMsg + " query " + retryInterval + "ms before retrying ...");
187                 // wait for a while and try to connect to DCAE again
188                 try {
189                     Thread.sleep(retryInterval);
190                 } catch (InterruptedException e) {
191                     Thread.currentThread().interrupt();
192                 }
193             }
194         }
195         return "";
196     }
197 }