Fix blueprint installation
[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 java.util.Map;
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.PolicyModelId;
42 import org.onap.clamp.loop.template.PolicyModelsService;
43 import org.onap.clamp.policy.pdpgroup.PdpGroup;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
46 import org.yaml.snakeyaml.DumperOptions;
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      * If the policy already exist in the db it returns the existing one.
91      *
92      * @param policyType    The policyType id
93      * @param policyVersion The policy version of that type
94      * @return A PolicyModel created from policyEngine data or null if nothing is found on policyEngine
95      */
96     public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
97         PolicyModel policyModelFound = policyModelsService.getPolicyModel(policyType, policyVersion);
98         if (policyModelFound == null) {
99             String policyTosca = this.downloadOnePolicy(policyType, policyVersion);
100             if (policyTosca != null && !policyTosca.isEmpty()) {
101                 return policyModelsService.savePolicyModelInNewTransaction(
102                         new PolicyModel(policyType, policyTosca, policyVersion));
103             } else {
104                 logger.error("Policy not found in the Policy Engine, returning null: " + policyType
105                         + "/" + policyVersion);
106                 return null;
107             }
108         } else {
109             logger.info("Skipping policy model download as it exists already in the database " + policyType
110                     + "/" + policyVersion);
111             return policyModelFound;
112         }
113     }
114
115     /**
116      * This method query Policy engine and create a PolicyModel object with type and version.
117      *
118      * @param microService microservice object instance
119      * @return A PolicyModel created from policyEngine data
120      */
121     public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
122         return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
123     }
124
125     /**
126      * This method synchronize the clamp database and the policy engine.
127      * So it creates the required PolicyModel.
128      */
129     public void synchronizeAllPolicies() {
130         LinkedHashMap<String, Object> loadedYaml;
131         loadedYaml = new Yaml().load(downloadAllPolicies());
132         if (loadedYaml == null || loadedYaml.isEmpty()) {
133             logger.warn("getAllPolicyType yaml returned by policy engine could not be decoded, as it's null or empty");
134             return;
135         }
136
137         LinkedHashMap<String, Object> policyTypesMap = (LinkedHashMap<String, Object>) loadedYaml
138                 .get("policy_types");
139         policyTypesMap.forEach((key, value) ->
140                 this.createPolicyModelFromPolicyEngine(key,
141                         ((String) ((LinkedHashMap<String, Object>) value).get("version"))));
142     }
143
144     /**
145      * This method can be used to download all policy types + data types defined in
146      * policy engine.
147      *
148      * @return A yaml containing all policy Types and all data types
149      */
150     public String downloadAllPolicies() {
151         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models",
152                 "Get all policies");
153     }
154
155     /**
156      * This method can be used to download a policy tosca model on the engine.
157      *
158      * @param policyType    The policy type (id)
159      * @param policyVersion The policy version
160      * @return A string with the whole policy tosca model
161      */
162     public String downloadOnePolicy(String policyType, String policyVersion) {
163         logger.info("Downloading the policy model " + policyType + "/" + policyVersion);
164         DumperOptions options = new DumperOptions();
165         options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
166         options.setIndent(4);
167         options.setPrettyFlow(true);
168         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
169         Yaml yamlParser = new Yaml(options);
170         String responseBody = callCamelRoute(
171                 ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
172                         .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model",
173                 "Get one policy");
174
175         if (responseBody == null || responseBody.isEmpty()) {
176             logger.warn("getPolicyModel returned by policy engine could not be decoded, as it's null or empty");
177             return null;
178         }
179
180         return yamlParser.dump((Map<String, Object>) yamlParser.load(responseBody));
181     }
182
183     /**
184      * This method can be used to download all Pdp Groups data from policy engine.
185      */
186     public void downloadPdpGroups() {
187         String responseBody =
188                 callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-pdp-groups",
189                         "Get Pdp Groups");
190
191         if (responseBody == null || responseBody.isEmpty()) {
192             logger.warn("getPdpGroups returned by policy engine could not be decoded, as it's null or empty");
193             return;
194         }
195
196         JsonObject jsonObj = JsonUtils.GSON.fromJson(responseBody, JsonObject.class);
197
198         List<PdpGroup> pdpGroupList = new LinkedList<>();
199         JsonArray itemsArray = (JsonArray) jsonObj.get("groups");
200
201         for (com.google.gson.JsonElement jsonElement : itemsArray) {
202             JsonObject item = (JsonObject) jsonElement;
203             PdpGroup pdpGroup = JsonUtils.GSON.fromJson(item.toString(), PdpGroup.class);
204             pdpGroupList.add(pdpGroup);
205         }
206
207         policyModelsService.updatePdpGroupInfo(pdpGroupList);
208     }
209
210     private String callCamelRoute(Exchange exchange, String camelFlow, String logMsg) {
211         for (int i = 0; i < retryLimit; i++) {
212             Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
213             if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
214                 return (String) exchangeResponse.getIn().getBody();
215             } else {
216                 logger.info(logMsg + " query " + retryInterval + "ms before retrying ...");
217                 // wait for a while and try to connect to DCAE again
218                 try {
219                     Thread.sleep(retryInterval);
220                 } catch (InterruptedException e) {
221                     Thread.currentThread().interrupt();
222                 }
223             }
224         }
225         return "";
226     }
227 }