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