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