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