31c200a997a50b5128a3f25b638b5051afdf8f49
[holmes/rule-management.git] / rulemgt / src / main / java / org / onap / holmes / rulemgt / RuleAllocator.java
1 /**
2  * Copyright 2017-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;
18
19 import lombok.extern.slf4j.Slf4j;
20 import org.jvnet.hk2.annotations.Service;
21 import org.onap.holmes.common.api.entity.CorrelationRule;
22 import org.onap.holmes.common.exception.CorrelationException;
23 import org.onap.holmes.common.utils.DbDaoUtil;
24 import org.onap.holmes.rulemgt.bolt.enginebolt.EngineWrapper;
25 import org.onap.holmes.rulemgt.db.CorrelationRuleDao;
26 import org.onap.holmes.rulemgt.tools.EngineTools;
27 import org.onap.holmes.rulemgt.wrapper.RuleMgtWrapper;
28 import org.onap.holmes.rulemgt.wrapper.RuleQueryWrapper;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import javax.annotation.PostConstruct;
33 import javax.inject.Inject;
34 import java.util.*;
35 import java.util.concurrent.TimeUnit;
36
37 import static java.util.concurrent.TimeUnit.SECONDS;
38
39 @Slf4j
40 @Service
41 public class RuleAllocator {
42     private static final Logger LOGGER = LoggerFactory.getLogger(RuleAllocator.class);
43
44     public final static int ENABLE = 1;
45     public final static int RETRY_TIMES = 5;
46     public final static long RETRY_INTERVAL_SEC = 15;
47     private RuleMgtWrapper ruleMgtWrapper;
48     private RuleQueryWrapper ruleQueryWrapper;
49     private EngineWrapper engineWrapper;
50     private EngineTools engineTools;
51     private CorrelationRuleDao correlationRuleDao;
52
53     @Inject
54     public RuleAllocator(RuleMgtWrapper ruleMgtWrapper, RuleQueryWrapper ruleQueryWrapper,
55                          EngineWrapper engineWrapper, EngineTools engineTools, DbDaoUtil daoUtil) {
56         this.ruleMgtWrapper = ruleMgtWrapper;
57         this.ruleQueryWrapper = ruleQueryWrapper;
58         this.engineWrapper = engineWrapper;
59         this.engineTools = engineTools;
60         correlationRuleDao = daoUtil.getJdbiDaoByOnDemand(CorrelationRuleDao.class);
61     }
62
63     @PostConstruct
64     private void initialize() {
65         new Timer("RuleAllocatorTimer").schedule(new TimerTask() {
66
67             public void run() {
68                 try {
69                     allocateRules();
70                 } catch (Exception e) {
71                     LOGGER.error("Failed to reallocate rules.", e);
72                 }
73             }
74
75         }, SECONDS.toMillis(10), SECONDS.toMillis(30));
76     }
77
78     public synchronized void allocateRules() throws Exception {
79         List<String> engines = engineTools.getInstanceList();
80
81         if (engines == null) {
82             return;
83         }
84
85         int numOfEngines = engines.size();
86         LOGGER.info(String.format("There are %d engine instance(s) running currently.", numOfEngines));
87
88         List<String> legacyEngineInstances = engineTools.getLegacyEngineInstances();
89         if (legacyEngineInstances == null) {
90             return;
91         }
92
93         if (legacyEngineInstances.size() < numOfEngines) {
94             //extend
95             List<CorrelationRule> rules2Allocate = calculateRule(legacyEngineInstances, numOfEngines);
96             List<CorrelationRule> rules2Delete = copyList(rules2Allocate);
97             List<String> newInstanceIds = sortOutNewEngineInstances(engines, legacyEngineInstances);
98             distributeRules(newInstanceIds, rules2Allocate);
99             cleanUpRulesFromEngines(rules2Delete, legacyEngineInstances);
100         } else {
101             //destroy
102             List<String> destroyed = getDestroyedEngines(engines, legacyEngineInstances);
103             distributeRules(getRemainingEngines(engines, destroyed), getRules(destroyed));
104         }
105     }
106
107     private List<CorrelationRule> copyList(List<CorrelationRule> rules) {
108         List<CorrelationRule> ret = new ArrayList<>(rules.size());
109         for (CorrelationRule r : rules) {
110             ret.add((CorrelationRule) r.clone());
111         }
112         return ret;
113     }
114
115     // When the engine is expanding, the rules that need to be allocated are calculated.
116     private List<CorrelationRule> calculateRule(List<String> existingEngineIps,
117                                                 int latestEngineInsNum) throws CorrelationException {
118         List<CorrelationRule> enabledRules = ruleQueryWrapper.queryRuleByEnable(ENABLE);
119         int ruleCount = 0;
120         if (enabledRules != null) {
121             ruleCount = enabledRules.size();
122         }
123         // Average number of rule that's to be allocate into each instance
124         int count = ruleCount / latestEngineInsNum;
125         // The number of remaining rules (to be allocated) after each instance has been allocated with the average number of rules.
126         int remainder = ruleCount % latestEngineInsNum;
127
128         List<CorrelationRule> ret = new ArrayList<>();
129         for (String ip : existingEngineIps) {
130             List<CorrelationRule> rules = ruleQueryWrapper.queryRuleByEngineInstance(ip);
131             List<CorrelationRule> tmp = rules.subList(count + (remainder-- / existingEngineIps.size()), rules.size());
132             ret.addAll(tmp);
133         }
134         return ret;
135     }
136
137     // Rules that need to be allocated after the engine is destroyed
138     private List<CorrelationRule> getRules(List<String> destroyIpList) throws CorrelationException {
139         List<CorrelationRule> rules = new ArrayList<>();
140         try {
141             if (destroyIpList != null) {
142                 for (String ip : destroyIpList) {
143                     rules.addAll(ruleQueryWrapper.queryRuleByEngineInstance(ip));
144                 }
145             }
146         } catch (CorrelationException e) {
147             LOGGER.error("method getRules get data from DB failed !", e);
148         }
149         return rules;
150     }
151
152     // Extended IP
153     private List<String> sortOutNewEngineInstances(List<String> newIps, List<String> oldIps) {
154         List<String> ret = new ArrayList<>();
155
156         for (String ip : newIps) {
157             if (!oldIps.contains(ip)) {
158                 ret.add(ip);
159             }
160         }
161         return ret;
162     }
163
164     // Destroyed IP
165     private List<String> getDestroyedEngines(List<String> latest, List<String> existing) {
166         List<String> ret = new ArrayList<>();
167         for (String ip : existing) {
168             if (!latest.contains(ip)) {
169                 ret.add(ip);
170             }
171         }
172         return ret;
173     }
174
175     // Residual IP after destruction
176     private List<String> getRemainingEngines(List<String> all, List<String> destroyed) {
177         List<String> ret = new ArrayList<>();
178         for (String ip : all) {
179             if (!destroyed.contains(ip)) {
180                 ret.add(ip);
181             }
182         }
183         return ret;
184     }
185
186     private void distributeRules(List<String> instanceIps, List<CorrelationRule> rules) throws CorrelationException {
187         List<String> sortedIps = sortIpByRuleNumDesc(instanceIps);
188
189         for (int i = 0, j = 0; j < rules.size(); i++, j++) {
190             int index = i % sortedIps.size();
191             String ip = sortedIps.get(index);
192             CorrelationRule rule = rules.get(j);
193             rule.setEngineInstance(ip);
194             allocateRule(rule, ip);
195         }
196     }
197
198     // Sorted by the number of rules each engine contains, in a descending order.
199     private List<String> sortIpByRuleNumDesc(List<String> ips) {
200         List<CorrelationRule> rules;
201         Map<String, Integer> ruleNumOfEngines = new HashMap();
202
203         try {
204             for (String ip : ips) {
205                 rules = ruleQueryWrapper.queryRuleByEngineInstance(ip);
206                 if (rules != null) {
207                     ruleNumOfEngines.put(ip, rules.size());
208                 }
209             }
210         } catch (Exception e) {
211             LOGGER.error("getEngineWithLeastRules failed !", e);
212         }
213
214         List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(ruleNumOfEngines.entrySet());
215         Collections.sort(sortedEntries, (o1, o2) -> o2.getValue() - o1.getValue());
216
217         List<String> ret = new ArrayList<>();
218         for (Map.Entry<String, Integer> entry : sortedEntries) {
219             ret.add(entry.getKey());
220         }
221         return ret;
222     }
223
224     private void allocateRule(CorrelationRule rule, String ip) throws CorrelationException {
225         // Retry for a couple of times in case of deployment failure
226         // due to unfinished initialization procedures of engine instances.
227         for (int i = 0; i <= RETRY_TIMES; ++i) {
228             try {
229                 ruleMgtWrapper.deployRule2Engine(rule, ip);
230                 correlationRuleDao.updateRule(rule);
231                 // If the codes reach here, it means everything's okay. There's no need to run the loop more.
232                 break;
233             } catch (CorrelationException e) {
234                 LOGGER.warn(String.format("Failed to allocate rule <%s> to <%s>. Retry: %d.",
235                         rule.getName(), ip, i), e);
236                 if (i == RETRY_TIMES) {
237                     throw new CorrelationException(String.format("Failed to allocate rule <%s> to <%s>",
238                             rule.getName(), ip), e);
239                 }
240                 try {
241                     SECONDS.sleep(RETRY_INTERVAL_SEC * (i + 1));
242                 } catch (InterruptedException interruptedException) {
243                     LOGGER.info(interruptedException.getMessage(), interruptedException);
244                 }
245             }
246         }
247     }
248
249     private void cleanUpRulesFromEngines(List<CorrelationRule> rules, List<String> ipList) {
250         try {
251             for (String ip : ipList) {
252                 for (CorrelationRule rule : rules) {
253                     if (ip.equals(rule.getEngineInstance())) {
254                         engineWrapper.deleteRuleFromEngine(rule.getPackageName(), ip);
255                     }
256                 }
257             }
258         } catch (CorrelationException e) {
259             LOGGER.error("When the engine is extended, deleting rule failed", e);
260         }
261     }
262 }