summaryrefslogtreecommitdiffstats
path: root/rulemgt/src/main/java/org/onap/holmes/rulemgt/dcae/ConfigFileScanningTask.java
blob: fc042ad63e5de50d44d45c747070143566645da4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/**
 * Copyright 2021-2022 ZTE Corporation.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.holmes.rulemgt.dcae;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang3.StringUtils;
import org.onap.holmes.common.ConfigFileScanner;
import org.onap.holmes.common.utils.CommonUtils;
import org.onap.holmes.common.utils.FileUtils;
import org.onap.holmes.common.utils.JerseyClient;
import org.onap.holmes.rulemgt.bean.request.RuleCreateRequest;
import org.onap.holmes.rulemgt.bean.response.RuleQueryListResponse;
import org.onap.holmes.rulemgt.bean.response.RuleResult4API;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.MediaType;
import java.io.File;
import java.nio.file.Paths;
import java.util.*;

public class ConfigFileScanningTask implements Runnable {
    final public static long POLLING_PERIOD = 30L;
    final private static Logger LOGGER = LoggerFactory.getLogger(ConfigFileScanningTask.class);
    final private static long FILE_SIZE_LMT = 1024 * 1024 * 10; // 10MB
    private String configFile = "/opt/hrmrules/index.json";
    private ConfigFileScanner configFileScanner;
    private String url;

    public ConfigFileScanningTask(ConfigFileScanner configFileScanner) {
        this.configFileScanner = configFileScanner;
        this.url = getRequestPref() + "://127.0.0.1:9101/api/holmes-rule-mgmt/v1/rule";
    }

    @Override
    public void run() {
        List<RuleResult4API> deployedRules = null;
        boolean isRuleQueryAvailable = true;

        try {
            deployedRules = getExistingRules();
        } catch (Exception e) {
            LOGGER.warn("Failed to get existing rules for comparison.", e);
            isRuleQueryAvailable = false;
        }

        // If it fails to load rule through API, it means that something must be wrong with the
        // holmes-rule-mgmt service. Hence, there's no need to go on with remaining steps.
        if (!isRuleQueryAvailable) {
            return;
        }

        // Contents for configInEffect are <closedControlLoop>:<ruleContents> pairs.
        Map<String, String> configInEffect = new HashMap();
        for (RuleResult4API ruleResult4API : deployedRules) {
            configInEffect.put(ruleResult4API.getLoopControlName(), ruleResult4API.getContent());
        }

        if (null == configFileScanner) {
            configFileScanner = new ConfigFileScanner();
        }

        try {
            Map<String, String> newConfig = extractConfigItems(configFileScanner.scan(configFile));

            // deal with newly added rules
            final Set<String> existingKeys = new HashSet(configInEffect.keySet());
            final Set<String> newKeys = new HashSet(newConfig.keySet());
            newKeys.stream()
                    .filter(key -> !existingKeys.contains(key))
                    .forEach(key -> {
                        if (deployRule(key, newConfig.get(key))) {
                            LOGGER.info("Rule '{}' has been deployed.", key);
                        }
                    });

            // deal with removed rules
            final List<RuleResult4API> existingRules = deployedRules;
            existingKeys.stream().filter(key -> !newKeys.contains(key)).forEach(key -> {
                if (deleteRule(find(existingRules, key))) {
                    LOGGER.info("Rule '{}' has been removed.", key);
                }
            });

            // deal with changed rules
            existingKeys.stream().filter(key -> newKeys.contains(key)).forEach(key -> {
                if (changed(configInEffect.get(key), newConfig.get(key))) {
                    if (deleteRule(find(existingRules, key))) {
                        deployRule(key, newConfig.get(key));
                        LOGGER.info("Rule '{}' has been updated.", key);
                    }
                }
            });
        } catch (Exception e) {
            LOGGER.warn("Unhandled error: \n" + e.getMessage(), e);
        }
    }

    private Map<String, String> extractConfigItems(Map<String, String> configFiles) {
        Map<String, String> ret = new HashMap();
        for (Map.Entry entry : configFiles.entrySet()) {
            JsonArray ja = JsonParser.parseString(entry.getValue().toString()).getAsJsonArray();
            Iterator<JsonElement> iterator = ja.iterator();
            while (iterator.hasNext()) {
                JsonObject jo = iterator.next().getAsJsonObject();
                String contents = readFile(jo.get("file").getAsString());
                if (StringUtils.isNotBlank(contents)) {
                    ret.put(jo.get("closedControlLoopName").getAsString(), contents);
                }
            }
        }
        return ret;
    }

    private String normalizePath(String path) {
        if (!path.startsWith("/")) {
            return Paths.get(new File(configFile).getParent(), path).toString();
        }
        return path;
    }

    private String readFile(String path) {
        String finalPath = normalizePath(path);
        File file = new File(finalPath);
        if (file.exists() && !file.isDirectory() && file.length() <= FILE_SIZE_LMT) {
            return FileUtils.readTextFile(finalPath);
        } else {
            LOGGER.warn("The file {} does not exist or it is a directory or it is too large to load.", finalPath);
        }
        return null;
    }

    private RuleResult4API find(final List<RuleResult4API> rules, String clName) {
        for (RuleResult4API rule : rules) {
            if (rule.getLoopControlName().equals(clName)) {
                return rule;
            }
        }
        return null;
    }

    private boolean changed(String con1, String con2) {
        // if either of the arguments is null, consider it as invalid and unchanged
        if (con1 == null || con2 == null) {
            return false;
        }

        if (!con1.replaceAll("\\s", StringUtils.EMPTY)
                .equals(con2.replaceAll("\\s", StringUtils.EMPTY))) {
            return true;
        }

        return false;
    }

    private List<RuleResult4API> getExistingRules() {
        RuleQueryListResponse ruleQueryListResponse = JerseyClient.newInstance().get(url, RuleQueryListResponse.class);
        List<RuleResult4API> deployedRules = Collections.EMPTY_LIST;
        if (null != ruleQueryListResponse) {
            deployedRules = ruleQueryListResponse.getCorrelationRules();
        }
        return deployedRules;
    }

    private boolean deployRule(String clName, String contents) {
        RuleCreateRequest ruleCreateRequest = getRuleCreateRequest(clName, contents);
        if (JerseyClient.newInstance().header("Accept", MediaType.APPLICATION_JSON)
                .put(url, Entity.json(ruleCreateRequest)) == null) {
            LOGGER.error("Failed to deploy rule: {}.", clName);
            return false;
        }
        return true;
    }

    private RuleCreateRequest getRuleCreateRequest(String clName, String contents) {
        RuleCreateRequest ruleCreateRequest = new RuleCreateRequest();
        ruleCreateRequest.setLoopControlName(clName);
        ruleCreateRequest.setRuleName(clName);
        ruleCreateRequest.setContent(contents);
        ruleCreateRequest.setDescription("");
        ruleCreateRequest.setEnabled(1);
        return ruleCreateRequest;
    }

    private boolean deleteRule(RuleResult4API rule) {
        if (rule == null) {
            LOGGER.info("No rule found, nothing to delete.");
            return false;
        }
        if (null == JerseyClient.newInstance().delete(url + "/" + rule.getRuleId())) {
            LOGGER.warn("Failed to delete rule, the rule id is: {}", rule.getRuleId());
            return false;
        }
        return true;
    }

    private String getRequestPref() {
        return CommonUtils.isHttpsEnabled() ? JerseyClient.PROTOCOL_HTTPS : JerseyClient.PROTOCOL_HTTP;
    }
}