Add tests
[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 org.apache.camel.CamelContext;
30 import org.apache.camel.Exchange;
31 import org.apache.camel.builder.ExchangeBuilder;
32 import org.onap.clamp.clds.config.ClampProperties;
33 import org.onap.clamp.clds.sdc.controller.installer.BlueprintMicroService;
34 import org.onap.clamp.loop.template.PolicyModel;
35 import org.onap.clamp.loop.template.PolicyModelId;
36 import org.onap.clamp.loop.template.PolicyModelsRepository;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.stereotype.Component;
39 import org.springframework.transaction.annotation.Propagation;
40 import org.springframework.transaction.annotation.Transactional;
41
42 /**
43  * The class implements the communication with the Policy Engine to retrieve
44  * policy models (tosca). It mainly delegates the physical calls to Camel
45  * engine.
46  *
47  */
48 @Component
49 public class PolicyEngineServices {
50     private final CamelContext camelContext;
51
52     private final PolicyModelsRepository policyModelsRepository;
53
54     private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
55     private static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
56     private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
57     private static int retryInterval = 0;
58     private static int retryLimit = 1;
59
60     public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
61     public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
62
63     @Autowired
64     public PolicyEngineServices(CamelContext camelContext, ClampProperties refProp,
65             PolicyModelsRepository policyModelsRepository) {
66         this.camelContext = camelContext;
67         this.policyModelsRepository = policyModelsRepository;
68         if (refProp.getStringValue(POLICY_RETRY_LIMIT) != null) {
69             retryLimit = Integer.valueOf(refProp.getStringValue(POLICY_RETRY_LIMIT));
70         }
71         if (refProp.getStringValue(POLICY_RETRY_INTERVAL) != null) {
72             retryInterval = Integer.valueOf(refProp.getStringValue(POLICY_RETRY_INTERVAL));
73         }
74     }
75
76     public PolicyModel createPolicyModelFromPolicyEngine(String policyType, String policyVersion) {
77         return new PolicyModel(policyType, this.downloadOnePolicy(policyType, policyVersion), policyVersion);
78     }
79
80     public PolicyModel createPolicyModelFromPolicyEngine(BlueprintMicroService microService) {
81         return createPolicyModelFromPolicyEngine(microService.getModelType(), microService.getModelVersion());
82     }
83
84     @Transactional(propagation = Propagation.REQUIRES_NEW)
85     public void createPolicyInDbIfNeeded(PolicyModel policyModel) {
86         if (!policyModelsRepository
87                 .existsById(new PolicyModelId(policyModel.getPolicyModelType(), policyModel.getVersion()))) {
88             policyModelsRepository.save(policyModel);
89         }
90     }
91
92     /**
93      * This method can be used to download all policy types + data types defined in
94      * policy engine.
95      * 
96      * @return A yaml containing all policy Types and all data types
97      * @throws InterruptedException In case of issue when sleeping during the retry
98      */
99     public String downloadAllPolicies() {
100         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).build(), "direct:get-all-policy-models");
101     }
102
103     /**
104      * This method can be used to download a policy tosca model on the engine.
105      * 
106      * @param policyType    The policy type (id)
107      * @param policyVersion The policy version
108      * @return A string with the whole policy tosca model
109      * @throws InterruptedException In case of issue when sleeping during the retry
110      */
111     public String downloadOnePolicy(String policyType, String policyVersion) {
112         return callCamelRoute(ExchangeBuilder.anExchange(camelContext).withProperty("policyModelName", policyType)
113                 .withProperty("policyModelVersion", policyVersion).build(), "direct:get-policy-model");
114     }
115
116     private String callCamelRoute(Exchange exchange, String camelFlow) {
117         for (int i = 0; i < retryLimit; i++) {
118             Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
119             if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
120                 return (String) exchangeResponse.getIn().getBody();
121             } else {
122                 logger.info("Policy query " + retryInterval + "ms before retrying ...");
123                 // wait for a while and try to connect to DCAE again
124                 try {
125                     Thread.sleep(retryInterval);
126                 } catch (InterruptedException e) {
127                     Thread.currentThread().interrupt();
128                 }
129             }
130         }
131         return "";
132     }
133 }