bugfix - rule deployment issue during init
[holmes/rule-management.git] / rulemgt / src / main / java / org / onap / holmes / rulemgt / dcae / ConfigFileScanningTask.java
1 /**
2  * Copyright 2021 ZTE Corporation.
3  * <p>
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * <p>
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * <p>
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.holmes.rulemgt.dcae;
18
19 import com.google.gson.JsonArray;
20 import com.google.gson.JsonElement;
21 import com.google.gson.JsonObject;
22 import com.google.gson.JsonParser;
23 import org.apache.commons.lang.StringUtils;
24 import org.onap.holmes.common.ConfigFileScanner;
25 import org.onap.holmes.common.utils.CommonUtils;
26 import org.onap.holmes.common.utils.FileUtils;
27 import org.onap.holmes.common.utils.JerseyClient;
28 import org.onap.holmes.rulemgt.bean.request.RuleCreateRequest;
29 import org.onap.holmes.rulemgt.bean.response.RuleQueryListResponse;
30 import org.onap.holmes.rulemgt.bean.response.RuleResult4API;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import javax.ws.rs.client.Entity;
35 import javax.ws.rs.core.MediaType;
36 import java.io.File;
37 import java.nio.file.Paths;
38 import java.util.*;
39
40 public class ConfigFileScanningTask implements Runnable {
41     final public static long POLLING_PERIOD = 30L;
42     final private static Logger LOGGER = LoggerFactory.getLogger(ConfigFileScanningTask.class);
43     final private static long FILE_SIZE_LMT = 1024 * 1024 * 10; // 10MB
44     final private Map<String, String> configInEffect = new HashMap(); // Contents for configInEffect are <closedControlLoop>:<ruleContents> pairs.
45     private String configFile = "/opt/hrmrules/index.json";
46     private ConfigFileScanner configFileScanner;
47     private String url;
48
49     public ConfigFileScanningTask(ConfigFileScanner configFileScanner) {
50         this.configFileScanner = configFileScanner;
51         this.url = getRequestPref() + "://127.0.0.1:9101/api/holmes-rule-mgmt/v1/rule";
52     }
53
54     @Override
55     public void run() {
56         List<RuleResult4API> deployedRules = null;
57         boolean isRuleQueryAvailable = true;
58
59         try {
60             deployedRules = getExistingRules();
61         } catch (Exception e) {
62             LOGGER.warn("Failed to get existing rules for comparison.", e);
63             isRuleQueryAvailable = false;
64         }
65
66         // If it fails to load rule through API, it means that something must be wrong with the
67         // holmes-rule-mgmt service. Hence, there's no need to go on with remaining steps.
68         if (!isRuleQueryAvailable) {
69             return;
70         }
71
72         for (RuleResult4API ruleResult4API : deployedRules) {
73             configInEffect.put(ruleResult4API.getLoopControlName(), ruleResult4API.getContent());
74         }
75
76         if (null == configFileScanner) {
77             configFileScanner = new ConfigFileScanner();
78         }
79
80         try {
81             Map<String, String> newConfig = extractConfigItems(configFileScanner.scan(configFile));
82
83             // deal with newly added rules
84             final Set<String> existingKeys = new HashSet(configInEffect.keySet());
85             final Set<String> newKeys = new HashSet(newConfig.keySet());
86             newKeys.stream()
87                     .filter(key -> !existingKeys.contains(key))
88                     .forEach(key -> {
89                         if (deployRule(key, newConfig.get(key))) {
90                             LOGGER.info("Rule '{}' has been deployed.", key);
91                         }
92                     });
93
94             // deal with removed rules
95             final List<RuleResult4API> existingRules = deployedRules;
96             existingKeys.stream().filter(key -> !newKeys.contains(key)).forEach(key -> {
97                 if (deleteRule(find(existingRules, key))) {
98                     LOGGER.info("Rule '{}' has been removed.", key);
99                 }
100             });
101
102             // deal with changed rules
103             existingKeys.stream().filter(key -> newKeys.contains(key)).forEach(key -> {
104                 if (changed(configInEffect.get(key), newConfig.get(key))) {
105                     if (deleteRule(find(existingRules, key))) {
106                         deployRule(key, newConfig.get(key));
107                         LOGGER.info("Rule '{}' has been updated.", key);
108                     }
109                 }
110             });
111         } catch (Exception e) {
112             LOGGER.warn("Unhandled error: \n" + e.getMessage(), e);
113         }
114     }
115
116     private Map<String, String> extractConfigItems(Map<String, String> configFiles) {
117         Map<String, String> ret = new HashMap();
118         for (Map.Entry entry : configFiles.entrySet()) {
119             JsonArray ja = JsonParser.parseString(entry.getValue().toString()).getAsJsonArray();
120             Iterator<JsonElement> iterator = ja.iterator();
121             while (iterator.hasNext()) {
122                 JsonObject jo = iterator.next().getAsJsonObject();
123                 String contents = readFile(jo.get("file").getAsString());
124                 if (StringUtils.isNotBlank(contents)) {
125                     ret.put(jo.get("closedControlLoopName").getAsString(), contents);
126                 }
127             }
128         }
129         return ret;
130     }
131
132     private String normalizePath(String path) {
133         if (!path.startsWith("/")) {
134             return Paths.get(new File(configFile).getParent(), path).toString();
135         }
136         return path;
137     }
138
139     private String readFile(String path) {
140         String finalPath = normalizePath(path);
141         File file = new File(finalPath);
142         if (file.exists() && !file.isDirectory() && file.length() <= FILE_SIZE_LMT) {
143             return FileUtils.readTextFile(finalPath);
144         } else {
145             LOGGER.warn("The file {} does not exist or it is a directory or it is too large to load.", finalPath);
146         }
147         return null;
148     }
149
150     private RuleResult4API find(final List<RuleResult4API> rules, String clName) {
151         for (RuleResult4API rule : rules) {
152             if (rule.getLoopControlName().equals(clName)) {
153                 return rule;
154             }
155         }
156         return null;
157     }
158
159     private boolean changed(String con1, String con2) {
160         // if either of the arguments is null, consider it as invalid and unchanged
161         if (con1 == null || con2 == null) {
162             return false;
163         }
164
165         if (!con1.replaceAll("\\s", StringUtils.EMPTY)
166                 .equals(con2.replaceAll("\\s", StringUtils.EMPTY))) {
167             return true;
168         }
169
170         return false;
171     }
172
173     private List<RuleResult4API> getExistingRules() {
174         RuleQueryListResponse ruleQueryListResponse = JerseyClient.newInstance().get(url, RuleQueryListResponse.class);
175         List<RuleResult4API> deployedRules = Collections.EMPTY_LIST;
176         if (null != ruleQueryListResponse) {
177             deployedRules = ruleQueryListResponse.getCorrelationRules();
178         }
179         return deployedRules;
180     }
181
182     private boolean deployRule(String clName, String contents) {
183         RuleCreateRequest ruleCreateRequest = getRuleCreateRequest(clName, contents);
184         if (JerseyClient.newInstance().header("Accept", MediaType.APPLICATION_JSON)
185                 .put(url, Entity.json(ruleCreateRequest)) == null) {
186             LOGGER.error("Failed to deploy rule: {}.", clName);
187             return false;
188         }
189         return true;
190     }
191
192     private RuleCreateRequest getRuleCreateRequest(String clName, String contents) {
193         RuleCreateRequest ruleCreateRequest = new RuleCreateRequest();
194         ruleCreateRequest.setLoopControlName(clName);
195         ruleCreateRequest.setRuleName(clName);
196         ruleCreateRequest.setContent(contents);
197         ruleCreateRequest.setDescription("");
198         ruleCreateRequest.setEnabled(1);
199         return ruleCreateRequest;
200     }
201
202     private boolean deleteRule(RuleResult4API rule) {
203         if (rule == null) {
204             LOGGER.info("No rule found, nothing to delete.");
205             return false;
206         }
207         if (null == JerseyClient.newInstance().delete(url + "/" + rule.getRuleId())) {
208             LOGGER.warn("Failed to delete rule, the rule id is: {}", rule.getRuleId());
209             return false;
210         }
211         return true;
212     }
213
214     private String getRequestPref() {
215         return CommonUtils.isHttpsEnabled() ? JerseyClient.PROTOCOL_HTTPS : JerseyClient.PROTOCOL_HTTP;
216     }
217 }