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