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