2d63bb673c680a6530ddc429b6cf6aa4fcdea5ac
[holmes/rule-management.git] / rulemgt / src / main / java / org / onap / holmes / rulemgt / dcae / DcaeConfigurationPolling.java
1 /**
2  * Copyright 2017 ZTE Corporation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package org.onap.holmes.rulemgt.dcae;
15
16 import com.alibaba.fastjson.JSON;
17 import com.google.gson.Gson;
18 import com.google.gson.GsonBuilder;
19 import com.google.gson.JsonDeserializationContext;
20 import com.google.gson.JsonDeserializer;
21 import com.google.gson.JsonElement;
22 import com.google.gson.JsonParseException;
23 import com.google.gson.reflect.TypeToken;
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.lang.reflect.Type;
27 import java.util.HashMap;
28 import java.util.List;
29 import javax.ws.rs.core.MediaType;
30 import lombok.extern.slf4j.Slf4j;
31 import org.apache.http.HttpResponse;
32 import org.apache.http.client.methods.HttpDelete;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.client.methods.HttpPut;
35 import org.apache.http.entity.StringEntity;
36 import org.apache.http.impl.client.CloseableHttpClient;
37 import org.onap.holmes.common.dcae.DcaeConfigurationQuery;
38 import org.onap.holmes.common.dcae.entity.DcaeConfigurations;
39 import org.onap.holmes.common.dcae.entity.Rule;
40 import org.onap.holmes.common.exception.CorrelationException;
41 import org.onap.holmes.common.utils.GsonUtil;
42 import org.onap.holmes.common.utils.HttpsUtils;
43 import org.onap.holmes.common.utils.Md5Util;
44 import org.onap.holmes.rulemgt.bean.request.RuleCreateRequest;
45 import org.onap.holmes.rulemgt.bean.response.RuleQueryListResponse;
46 import org.onap.holmes.rulemgt.bean.response.RuleResult4API;
47
48 @Slf4j
49 public class DcaeConfigurationPolling implements Runnable {
50
51     public static final long POLLING_PERIOD = 30 * 1000L;
52
53     private String hostname;
54
55     private String url = "https://127.0.0.1:9101/api/holmes-rule-mgmt/v1/rule";
56
57     public DcaeConfigurationPolling(String hostname) {
58         this.hostname = hostname;
59     }
60
61     private String prevConfigMd5 = Md5Util.md5(null);
62
63     private boolean prevResult = false;
64
65     @Override
66     public void run() {
67         DcaeConfigurations dcaeConfigurations = null;
68         try {
69             dcaeConfigurations = DcaeConfigurationQuery.getDcaeConfigurations(hostname);
70             String md5 = Md5Util.md5(dcaeConfigurations);
71             if (prevResult && prevConfigMd5.equals(md5)){
72                 log.info("Operation aborted due to identical Configurations.");
73                 return;
74             }
75             prevConfigMd5 = md5;
76             prevResult = false;
77         } catch (CorrelationException e) {
78             log.error("Failed to fetch DCAE configurations. " + e.getMessage(), e);
79         } catch (Exception e) {
80             log.info("Failed to generate the MD5 information for new configurations.", e);
81         }
82         RuleQueryListResponse ruleQueryListResponse = null;
83         if (dcaeConfigurations != null) {
84             try {
85                 ruleQueryListResponse = getAllCorrelationRules();
86             } catch (CorrelationException e) {
87                 log.error("Failed to get right response!" + e.getMessage(), e);
88             } catch (IOException e) {
89                 log.error("Failed to extract response entity. " + e.getMessage(), e);
90             } catch (Exception e) {
91                 log.error("Failed to build http client. " + e.getMessage(), e);
92             }
93         }
94         if (ruleQueryListResponse != null) {
95             List<RuleResult4API> ruleResult4APIs = ruleQueryListResponse.getCorrelationRules();
96             deleteAllCorrelationRules(ruleResult4APIs);
97             try {
98                 prevResult = addAllCorrelationRules(dcaeConfigurations);
99             } catch (CorrelationException e) {
100                 log.error("Failed to add rules. " + e.getMessage(), e);
101                 prevResult = false;
102             }
103         }
104     }
105
106     public RuleQueryListResponse getAllCorrelationRules() throws CorrelationException, IOException {
107               HashMap<String, String> headers = new HashMap<>();
108         headers.put("Content-Type", MediaType.APPLICATION_JSON);
109         CloseableHttpClient httpClient = null;
110         HttpGet httpGet = new HttpGet(url);
111         try {
112             httpClient = HttpsUtils.getHttpClient(HttpsUtils.DEFUALT_TIMEOUT);
113             HttpResponse httpResponse = HttpsUtils.get(httpGet, headers, httpClient);
114             String response = HttpsUtils.extractResponseEntity(httpResponse);
115             return JSON.parseObject(response,RuleQueryListResponse.class);
116         } finally {
117             httpGet.releaseConnection();
118             closeHttpClient(httpClient);
119         }
120     }
121
122     private boolean addAllCorrelationRules(DcaeConfigurations dcaeConfigurations) throws CorrelationException {
123         boolean suc = false;
124         for (Rule rule : dcaeConfigurations.getDefaultRules()) {
125             RuleCreateRequest ruleCreateRequest = getRuleCreateRequest(rule);
126             String content = "";
127             try {
128                 content = GsonUtil.beanToJson(ruleCreateRequest);
129             } catch (Exception e) {
130                 throw new CorrelationException("Failed to convert the message object to a json string.", e);
131             }
132             HashMap<String, String> headers = new HashMap<>();
133             headers.put("Content-Type", MediaType.APPLICATION_JSON);
134             headers.put("Accept", MediaType.APPLICATION_JSON);
135             HttpResponse httpResponse;
136             CloseableHttpClient httpClient = null;
137             HttpPut httpPut = new HttpPut(url);
138             try {
139                 httpClient = HttpsUtils.getHttpClient(HttpsUtils.DEFUALT_TIMEOUT);
140                 httpResponse = HttpsUtils
141                         .put(httpPut, headers, new HashMap<>(), new StringEntity(content), httpClient);
142             } catch (UnsupportedEncodingException e) {
143                 throw new CorrelationException("Failed to create https entity.", e);
144             } catch (Exception e) {
145                 throw new CorrelationException(e.getMessage());
146             } finally {
147                 httpPut.releaseConnection();
148                 closeHttpClient(httpClient);
149             }
150             if (httpResponse != null) {
151                 suc = httpResponse.getStatusLine().getStatusCode() == 200;
152             }
153             if (!suc) {
154                 break;
155             }
156         }
157         return suc;
158     }
159
160     private void deleteAllCorrelationRules(List<RuleResult4API> ruleResult4APIs){
161         ruleResult4APIs.forEach(correlationRule ->{
162             HashMap<String, String> headers = new HashMap<>();
163             headers.put("Content-Type", MediaType.APPLICATION_JSON);
164             CloseableHttpClient httpClient = null;
165             HttpDelete httpDelete = new HttpDelete(url + "/" + correlationRule.getRuleId());
166             try {
167                 httpClient = HttpsUtils.getHttpClient(HttpsUtils.DEFUALT_TIMEOUT);
168                 HttpsUtils.delete(httpDelete, headers, httpClient);
169             } catch (Exception e) {
170                 log.warn("Failed to delete rule, the rule id is : " + correlationRule.getRuleId()
171                         + " exception messge is : " + e.getMessage(), e);
172             } finally {
173                 httpDelete.releaseConnection();
174                 closeHttpClient(httpClient);
175             }
176         });
177     }
178
179     private RuleCreateRequest getRuleCreateRequest(Rule rule) {
180         RuleCreateRequest ruleCreateRequest = new RuleCreateRequest();
181         ruleCreateRequest.setLoopControlName(rule.getLoopControlName());
182         ruleCreateRequest.setRuleName(rule.getName());
183         ruleCreateRequest.setContent(rule.getContents());
184         ruleCreateRequest.setDescription("");
185         ruleCreateRequest.setEnabled(1);
186         return ruleCreateRequest;
187     }
188
189     private void closeHttpClient(CloseableHttpClient httpClient) {
190         if (httpClient != null) {
191             try {
192                 httpClient.close();
193             } catch (IOException e) {
194                 log.warn("Failed to close http client!");
195             }
196         }
197     }
198 }