884ea311bc8a731a100ffaf2e53100e023464ade
[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         if (null == configFileScanner) {
57             configFileScanner = new ConfigFileScanner();
58         }
59
60         try {
61             Map<String, String> newConfig = extractConfigItems(configFileScanner.scan(configFile));
62
63             List<RuleResult4API> deployedRules = getExistingRules();
64
65             // deal with newly added rules
66             final Set<String> existingKeys = new HashSet(configInEffect.keySet());
67             final Set<String> newKeys = new HashSet(newConfig.keySet());
68             newKeys.stream()
69                     .filter(key -> !existingKeys.contains(key))
70                     .forEach(key -> {
71                         if (deployRule(key, newConfig.get(key))) {
72                             configInEffect.put(key, newConfig.get(key));
73                             LOGGER.info("Rule '{}' has been deployed.", key);
74                         }
75                     });
76
77             // deal with removed rules
78             existingKeys.stream().filter(key -> !newKeys.contains(key)).forEach(key -> {
79                 if (deleteRule(find(deployedRules, key))) {
80                     configInEffect.remove(key);
81                     LOGGER.info("Rule '{}' has been removed.", key);
82                 }
83             });
84
85             // deal with changed rules
86             existingKeys.stream().filter(key -> newKeys.contains(key)).forEach(key -> {
87                 if (changed(configInEffect.get(key), newConfig.get(key))) {
88                     if (deleteRule(find(deployedRules, key))) {
89                         configInEffect.remove(key);
90                         deployRule(key, newConfig.get(key));
91                         configInEffect.put(key, newConfig.get(key));
92                         LOGGER.info("Rule '{}' has been updated.", key);
93                     }
94                 }
95             });
96         } catch (Exception e) {
97             LOGGER.warn("Unhandled error: \n" + e.getMessage(), e);
98         }
99     }
100
101     private Map<String, String> extractConfigItems(Map<String, String> configFiles) {
102         Map<String, String> ret = new HashMap();
103         for (Map.Entry entry : configFiles.entrySet()) {
104             JsonArray ja = JsonParser.parseString(entry.getValue().toString()).getAsJsonArray();
105             Iterator<JsonElement> iterator = ja.iterator();
106             while (iterator.hasNext()) {
107                 JsonObject jo = iterator.next().getAsJsonObject();
108                 String contents = readFile(jo.get("file").getAsString());
109                 if (StringUtils.isNotBlank(contents)) {
110                     ret.put(jo.get("closedControlLoopName").getAsString(), contents);
111                 }
112             }
113         }
114         return ret;
115     }
116
117     private String normalizePath(String path) {
118         if (!path.startsWith("/")) {
119             return Paths.get(new File(configFile).getParent(), path).toString();
120         }
121         return path;
122     }
123
124     private String readFile(String path) {
125         String finalPath = normalizePath(path);
126         File file = new File(finalPath);
127         if (file.exists() && !file.isDirectory() && file.length() <= FILE_SIZE_LMT) {
128             return FileUtils.readTextFile(finalPath);
129         } else {
130             LOGGER.warn("The file {} does not exist or it is a directory or it is too large to load.", finalPath);
131         }
132         return null;
133     }
134
135     private RuleResult4API find(final List<RuleResult4API> rules, String clName) {
136         for (RuleResult4API rule : rules) {
137             if (rule.getLoopControlName().equals(clName)) {
138                 return rule;
139             }
140         }
141         return null;
142     }
143
144     private boolean changed(String con1, String con2) {
145         // if either of the arguments is null, consider it as invalid and unchanged
146         if (con1 == null || con2 == null) {
147             return false;
148         }
149
150         if (!con1.replaceAll("\\s", StringUtils.EMPTY)
151                 .equals(con2.replaceAll("\\s", StringUtils.EMPTY))) {
152             return true;
153         }
154
155         return false;
156     }
157
158     private List<RuleResult4API> getExistingRules() {
159         RuleQueryListResponse ruleQueryListResponse = JerseyClient.newInstance().get(url, RuleQueryListResponse.class);
160         List<RuleResult4API> deployedRules = Collections.EMPTY_LIST;
161         if (null != ruleQueryListResponse) {
162             deployedRules = ruleQueryListResponse.getCorrelationRules();
163         }
164         return deployedRules;
165     }
166
167     private boolean deployRule(String clName, String contents) {
168         RuleCreateRequest ruleCreateRequest = getRuleCreateRequest(clName, contents);
169         if (JerseyClient.newInstance().header("Accept", MediaType.APPLICATION_JSON)
170                 .put(url, Entity.json(ruleCreateRequest)) == null) {
171             LOGGER.error("Failed to deploy rule: {}.", clName);
172             return false;
173         }
174         return true;
175     }
176
177     private RuleCreateRequest getRuleCreateRequest(String clName, String contents) {
178         RuleCreateRequest ruleCreateRequest = new RuleCreateRequest();
179         ruleCreateRequest.setLoopControlName(clName);
180         ruleCreateRequest.setRuleName(clName);
181         ruleCreateRequest.setContent(contents);
182         ruleCreateRequest.setDescription("");
183         ruleCreateRequest.setEnabled(1);
184         return ruleCreateRequest;
185     }
186
187     private boolean deleteRule(RuleResult4API rule) {
188         if (rule == null) {
189             LOGGER.info("No rule found, nothing to delete.");
190             return false;
191         }
192         if (null == JerseyClient.newInstance().delete(url + "/" + rule.getRuleId())) {
193             LOGGER.warn("Failed to delete rule, the rule id is: {}", rule.getRuleId());
194             return false;
195         }
196         return true;
197     }
198
199     private String getRequestPref() {
200         return CommonUtils.isHttpsEnabled() ? JerseyClient.PROTOCOL_HTTPS : JerseyClient.PROTOCOL_HTTP;
201     }
202 }