02e2dd0b6023ea08f56e08f4f068ddf11b36b621
[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 java.util.ArrayList;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import org.apache.camel.CamelContext;
33 import org.apache.camel.Exchange;
34 import org.apache.camel.builder.ExchangeBuilder;
35 import org.onap.clamp.clds.config.ClampProperties;
36 import org.onap.clamp.clds.sdc.controller.installer.BlueprintMicroService;
37 import org.onap.clamp.loop.template.PolicyModel;
38 import org.onap.clamp.loop.template.PolicyModelsService;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.stereotype.Component;
41 import org.yaml.snakeyaml.Yaml;
42
43
44
45
46 /**
47  * The class implements the communication with the Policy Engine to retrieve
48  * policy models (tosca). It mainly delegates the physical calls to Camel
49  * engine.
50  *
51  */
52 @Component
53 public class PolicyEngineServices {
54     private final CamelContext camelContext;
55
56     private final PolicyModelsService policyModelsSService;
57
58     private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
59     private static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
60     private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
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 policyModelsSService policyModel repository bean
73      */
74     @Autowired
75     public PolicyEngineServices(CamelContext camelContext, ClampProperties clampProperties,
76                                 PolicyModelsService policyModelsSService) {
77         this.camelContext = camelContext;
78         this.policyModelsSService = policyModelsSService;
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         return new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion);
96     }
97
98     /**
99      * This method query Policy engine and create a PolicyModel object with type and version.
100      *
101      * @param microService microservice object instance
102      * @return A PolicyModel created from policyEngine data
103      */
104     public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
105         return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
106     }
107
108     /**
109      * This method synchronize the clamp database and the policy engine.
110      * So it creates the required PolicyModel.
111      */
112     public void synchronizeAllPolicies() {
113         LinkedHashMap<String, Object> loadedYaml;
114         loadedYaml = new Yaml().load(downloadAllPolicies());
115         if (loadedYaml == null || loadedYaml.isEmpty()) {
116             logger.warn("getAllPolicyType yaml returned by policy engine could not be decoded, as it's null or empty");
117             return;
118         }
119
120         List<LinkedHashMap<String, Object>> policyTypesList = (List<LinkedHashMap<String, Object>>) loadedYaml
121                 .get("policy_types");
122         policyTypesList.parallelStream().forEach(policyType -> {
123             Map.Entry<String, Object> policyTypeEntry = (Map.Entry<String, Object>) new ArrayList(policyType.entrySet()).get(0);
124
125             policyModelsSService.createPolicyInDbIfNeeded(
126                     createPolicyModelFromPolicyEngine(policyTypeEntry.getKey(),
127                             ((String) ((LinkedHashMap<String, Object>) policyTypeEntry.getValue()).get("version"))));
128         });
129     }
130
131     /**
132      * This method can be used to download all policy types + data types defined in
133      * policy engine.
134      * 
135      * @return A yaml containing all policy Types and all data types
136      */
137     public String downloadAllPolicies() {
138         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models");
139     }
140
141     /**
142      * This method can be used to download a policy tosca model on the engine.
143      * 
144      * @param policyType    The policy type (id)
145      * @param policyVersion The policy version
146      * @return A string with the whole policy tosca model
147      */
148     public String downloadOnePolicy(String policyType, String policyVersion) {
149         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
150                 .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model");
151     }
152
153     private String callCamelRoute(Exchange exchange, String camelFlow) {
154         for (int i = 0; i < retryLimit; i++) {
155             Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
156             if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
157                 return (String) exchangeResponse.getIn().getBody();
158             } else {
159                 logger.info("Policy query " + retryInterval + "ms before retrying ...");
160                 // wait for a while and try to connect to DCAE again
161                 try {
162                     Thread.sleep(retryInterval);
163                 } catch (InterruptedException e) {
164                     Thread.currentThread().interrupt();
165                 }
166             }
167         }
168         return "";
169     }
170 }