Optimized Rule Deployment Logic
[holmes/engine-management.git] / engine-d / src / main / java / org / onap / holmes / engine / manager / DroolsEngine.java
1 /**
2  * Copyright 2017 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 package org.onap.holmes.engine.manager;
17
18 import java.util.*;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.stream.Collectors;
21 import javax.annotation.PostConstruct;
22 import javax.inject.Inject;
23
24 import lombok.extern.slf4j.Slf4j;
25 import org.drools.compiler.kie.builder.impl.InternalKieModule;
26 import org.drools.core.util.StringUtils;
27 import org.jvnet.hk2.annotations.Service;
28
29 import org.kie.api.KieServices;
30 import org.kie.api.builder.*;
31 import org.kie.api.builder.Message.Level;
32 import org.kie.api.io.Resource;
33 import org.kie.api.runtime.KieContainer;
34 import org.kie.api.runtime.KieSession;
35 import org.kie.api.runtime.rule.FactHandle;
36
37 import org.onap.holmes.common.api.entity.AlarmInfo;
38
39 import org.onap.holmes.common.api.stat.VesAlarm;
40 import org.onap.holmes.common.dmaap.DmaapService;
41 import org.onap.holmes.common.exception.AlarmInfoException;
42 import org.onap.holmes.common.utils.DbDaoUtil;
43 import org.onap.holmes.engine.db.AlarmInfoDao;
44 import org.onap.holmes.engine.request.DeployRuleRequest;
45 import org.onap.holmes.common.api.entity.CorrelationRule;
46 import org.onap.holmes.common.exception.CorrelationException;
47 import org.onap.holmes.common.utils.ExceptionUtil;
48 import org.onap.holmes.engine.wrapper.RuleMgtWrapper;
49
50 @Slf4j
51 @Service
52 public class DroolsEngine {
53
54     @Inject
55     private RuleMgtWrapper ruleMgtWrapper;
56     @Inject
57     private DbDaoUtil daoUtil;
58
59     private final static int ENABLE = 1;
60     private AlarmInfoDao alarmInfoDao;
61     private final Map<String, String> deployed = new ConcurrentHashMap<>();
62     private KieServices ks = KieServices.Factory.get();
63     private ReleaseId releaseId = ks.newReleaseId("org.onap.holmes", "rules", "1.0.0-SNAPSHOT");
64     private ReleaseId compilationRelease = ks.newReleaseId("org.onap.holmes", "compilation", "1.0.0-SNAPSHOT");
65     private KieContainer container;
66     private KieSession session;
67
68     @PostConstruct
69     private void init() {
70         alarmInfoDao = daoUtil.getJdbiDaoByOnDemand(AlarmInfoDao.class);
71         try {
72             log.info("Drools engine initializing...");
73             initEngine();
74             log.info("Drools engine initialized.");
75
76             log.info("Start deploy existing rules...");
77             initRules();
78             log.info("All rules were deployed.");
79
80             log.info("Synchronizing alarms...");
81             syncAlarms();
82             log.info("Alarm synchronization succeeded.");
83         } catch (Exception e) {
84             log.error("Failed to startup the engine of Holmes: " + e.getMessage(), e);
85             throw ExceptionUtil.buildExceptionResponse("Failed to startup Drools!");
86         }
87     }
88
89     public void stop() {
90         session.dispose();
91     }
92
93     public void initEngine() {
94         KieModule km = null;
95         try {
96             String drl = "package holmes;";
97             deployed.put(getPackageName(drl), drl);
98             km = createAndDeployJar(ks, releaseId, new ArrayList<>(deployed.values()));
99         } catch (Exception e) {
100             log.error("Failed to initialize the engine service module.", e);
101         }
102         container = ks.newKieContainer(km.getReleaseId());
103         session = container.newKieSession();
104         deployed.clear();
105     }
106
107     private void initRules() throws CorrelationException {
108         List<CorrelationRule> rules = ruleMgtWrapper.queryRuleByEnable(ENABLE);
109         if (rules.isEmpty()) {
110             return;
111         }
112
113         for (CorrelationRule rule : rules) {
114             if (!StringUtils.isEmpty(rule.getContent())) {
115                 deployRule(rule.getContent());
116                 DmaapService.loopControlNames.put(rule.getPackageName(), rule.getClosedControlLoopName());
117             }
118         }
119
120         session.fireAllRules();
121     }
122
123     public void syncAlarms() throws AlarmInfoException {
124         alarmInfoDao.queryAllAlarm().forEach(alarmInfo -> alarmInfoDao.deleteClearedAlarm(alarmInfo));
125         alarmInfoDao.queryAllAlarm().forEach(alarmInfo -> putRaisedIntoStream(convertAlarmInfo2VesAlarm(alarmInfo)));
126     }
127
128     public String deployRule(DeployRuleRequest rule) throws CorrelationException {
129         return deployRule(rule.getContent());
130     }
131
132     private synchronized String deployRule(String rule) throws CorrelationException {
133         final String packageName = getPackageName(rule);
134
135         if (StringUtils.isEmpty(packageName)) {
136             throw new CorrelationException("The package name can not be empty.");
137         }
138
139         if (deployed.containsKey(packageName)) {
140             throw new CorrelationException("A rule with the same package name already exists in the system.");
141         }
142
143         if (!StringUtils.isEmpty(rule)) {
144             deployed.put(packageName, rule);
145             try {
146                 refreshInMemRules();
147             } catch (CorrelationException e) {
148                 deployed.remove(packageName);
149                 throw e;
150             }
151             session.fireAllRules();
152         }
153
154         return packageName;
155     }
156
157     public synchronized void undeployRule(String packageName) throws CorrelationException {
158
159         if (StringUtils.isEmpty(packageName)) {
160             throw new CorrelationException("The package name should not be null.");
161         }
162
163         if (!deployed.containsKey(packageName)) {
164             throw new CorrelationException("The rule " + packageName + " does not exist!");
165         }
166
167         String removed = deployed.remove(packageName);
168         try {
169             refreshInMemRules();
170         } catch (Exception e) {
171             deployed.put(packageName, removed);
172             throw new CorrelationException("Failed to delete the rule: " + packageName, e);
173         }
174     }
175
176     private void refreshInMemRules() throws CorrelationException {
177         KieModule km = createAndDeployJar(ks, releaseId, new ArrayList<>(deployed.values()));
178         container.updateToVersion(km.getReleaseId());
179     }
180
181     public void compileRule(String content)
182             throws CorrelationException {
183
184         KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(compilationRelease);
185         kfs.write("src/main/resources/rules/rule.drl", content);
186         KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
187         if (builder.getResults().hasMessages(Message.Level.ERROR)) {
188             String errorMsg = "There are errors in the rule: " + builder.getResults()
189                     .getMessages(Level.ERROR).toString();
190             log.info("Compilation failure: " + errorMsg);
191             throw new CorrelationException(errorMsg);
192         }
193
194         if (deployed.containsKey(getPackageName(content))) {
195             throw new CorrelationException("There's no compilation error. But a rule with the same package name already " +
196                     "exists in the engine, which may cause a deployment failure.");
197         }
198
199         ks.getRepository().removeKieModule(compilationRelease);
200     }
201
202     public void putRaisedIntoStream(VesAlarm alarm) {
203         FactHandle factHandle = this.session.getFactHandle(alarm);
204         if (factHandle != null) {
205             Object obj = this.session.getObject(factHandle);
206             if (obj != null && obj instanceof VesAlarm) {
207                 alarm.setRootFlag(((VesAlarm) obj).getRootFlag());
208             }
209             this.session.delete(factHandle);
210
211             if (alarm.getAlarmIsCleared() == 1) {
212                 alarmInfoDao.deleteClearedAlarm(convertVesAlarm2AlarmInfo(alarm));
213             }
214         } else {
215             this.session.insert(alarm);
216         }
217
218         this.session.fireAllRules();
219     }
220
221     public List<String> queryPackagesFromEngine() {
222         return container.getKieBase().getKiePackages().stream()
223                 .filter(pkg -> pkg.getRules().size() != 0)
224                 .map(pkg -> pkg.getName())
225                 .collect(Collectors.toList());
226     }
227
228
229
230     private VesAlarm convertAlarmInfo2VesAlarm(AlarmInfo alarmInfo) {
231         VesAlarm vesAlarm = new VesAlarm();
232         vesAlarm.setEventId(alarmInfo.getEventId());
233         vesAlarm.setEventName(alarmInfo.getEventName());
234         vesAlarm.setStartEpochMicrosec(alarmInfo.getStartEpochMicroSec());
235         vesAlarm.setSourceId(alarmInfo.getSourceId());
236         vesAlarm.setSourceName(alarmInfo.getSourceName());
237         vesAlarm.setRootFlag(alarmInfo.getRootFlag());
238         vesAlarm.setAlarmIsCleared(alarmInfo.getAlarmIsCleared());
239         vesAlarm.setLastEpochMicrosec(alarmInfo.getLastEpochMicroSec());
240         return vesAlarm;
241     }
242
243     private AlarmInfo convertVesAlarm2AlarmInfo(VesAlarm vesAlarm) {
244         AlarmInfo alarmInfo = new AlarmInfo();
245         alarmInfo.setEventId(vesAlarm.getEventId());
246         alarmInfo.setEventName(vesAlarm.getEventName());
247         alarmInfo.setStartEpochMicroSec(vesAlarm.getStartEpochMicrosec());
248         alarmInfo.setLastEpochMicroSec(vesAlarm.getLastEpochMicrosec());
249         alarmInfo.setSourceId(vesAlarm.getSourceId());
250         alarmInfo.setSourceName(vesAlarm.getSourceName());
251         alarmInfo.setAlarmIsCleared(vesAlarm.getAlarmIsCleared());
252         alarmInfo.setRootFlag(vesAlarm.getRootFlag());
253
254         return alarmInfo;
255     }
256
257     private String getPackageName(String contents) {
258         String ret = contents.trim();
259         StringBuilder stringBuilder = new StringBuilder();
260         if (ret.startsWith("package")) {
261             ret = ret.substring(7).trim();
262             for (int i = 0; i < ret.length(); i++) {
263                 char tmp = ret.charAt(i);
264                 if (tmp == ';' || tmp == ' ' || tmp == '\n') {
265                     break;
266                 }
267                 stringBuilder.append(tmp);
268             }
269         }
270         return stringBuilder.toString();
271     }
272
273     private KieModule createAndDeployJar(KieServices ks, ReleaseId releaseId, List<String> drls) throws CorrelationException {
274         byte[] jar = createJar(ks, releaseId, drls);
275         KieModule km = deployJarIntoRepository(ks, jar);
276         return km;
277     }
278
279     private byte[] createJar(KieServices ks, ReleaseId releaseId, List<String> drls) throws CorrelationException {
280         KieFileSystem kfs = ks.newKieFileSystem().generateAndWritePomXML(releaseId);
281         int i = 0;
282         for (String drl : drls) {
283             if (!StringUtils.isEmpty(drl)) {
284                 kfs.write("src/main/resources/" + getPackageName(drl) + ".drl", drl);
285             }
286         }
287         KieBuilder kb = ks.newKieBuilder(kfs).buildAll();
288         if (kb.getResults().hasMessages(Message.Level.ERROR)) {
289             StringBuilder sb = new StringBuilder();
290             for (Message msg : kb.getResults().getMessages()) {
291                 sb.append(String.format("[%s]Line: %d, Col: %d\t%s\n", msg.getLevel().toString(), msg.getLine(),
292                         msg.getColumn(), msg.getText()));
293             }
294             throw new CorrelationException("Failed to compile JAR. Details: \n" + sb.toString());
295         }
296
297         InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
298                 .getKieModule(releaseId);
299
300         return kieModule.getBytes();
301     }
302
303     private KieModule deployJarIntoRepository(KieServices ks, byte[] jar) {
304         Resource jarRes = ks.getResources().newByteArrayResource(jar);
305         return ks.getRepository().addKieModule(jarRes);
306     }
307
308 }