]> git.basschouten.com Git - openhab-addons.git/blob
9ed8377d3fc7db559555b5b5116c09f8f114c894
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.logreader.internal.handler;
14
15 import static org.openhab.binding.logreader.internal.LogReaderBindingConstants.*;
16
17 import java.time.ZonedDateTime;
18 import java.util.regex.PatternSyntaxException;
19
20 import org.openhab.binding.logreader.internal.config.LogReaderConfiguration;
21 import org.openhab.binding.logreader.internal.filereader.api.FileReaderListener;
22 import org.openhab.binding.logreader.internal.filereader.api.LogFileReader;
23 import org.openhab.binding.logreader.internal.searchengine.SearchEngine;
24 import org.openhab.core.library.types.DateTimeType;
25 import org.openhab.core.library.types.DecimalType;
26 import org.openhab.core.library.types.StringType;
27 import org.openhab.core.thing.ChannelUID;
28 import org.openhab.core.thing.Thing;
29 import org.openhab.core.thing.ThingStatus;
30 import org.openhab.core.thing.ThingStatusDetail;
31 import org.openhab.core.thing.binding.BaseThingHandler;
32 import org.openhab.core.types.Command;
33 import org.openhab.core.types.RefreshType;
34 import org.openhab.core.types.State;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * The {@link LogHandler} is responsible for handling commands, which are
40  * sent to one of the channels.
41  *
42  * @author Miika Jukka - Initial contribution
43  * @author Pauli Anttila - Rewrite
44  */
45 public class LogHandler extends BaseThingHandler implements FileReaderListener {
46     private final Logger logger = LoggerFactory.getLogger(LogHandler.class);
47
48     private LogReaderConfiguration configuration;
49
50     private LogFileReader fileReader;
51
52     private SearchEngine errorEngine;
53     private SearchEngine warningEngine;
54     private SearchEngine customEngine;
55
56     public LogHandler(Thing thing, LogFileReader fileReader) {
57         super(thing);
58         this.fileReader = fileReader;
59     }
60
61     @Override
62     public void handleCommand(ChannelUID channelUID, Command command) {
63         switch (channelUID.getId()) {
64             case CHANNEL_ERRORS:
65                 updateChannel(channelUID, command, errorEngine);
66                 break;
67
68             case CHANNEL_WARNINGS:
69                 updateChannel(channelUID, command, warningEngine);
70                 break;
71
72             case CHANNEL_CUSTOMEVENTS:
73                 updateChannel(channelUID, command, customEngine);
74                 break;
75
76             default:
77                 logger.debug("Unsupported command '{}' received for channel '{}'", command, channelUID);
78         }
79     }
80
81     @Override
82     public void initialize() {
83         String logDir = System.getProperty("openhab.logdir");
84         if (logDir == null) {
85             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
86                     "Cannot determine system log directory.");
87             return;
88         }
89
90         configuration = getConfigAs(LogReaderConfiguration.class);
91         configuration.filePath = configuration.filePath.replaceFirst("\\$\\{OPENHAB_LOGDIR\\}", logDir);
92
93         logger.debug("Using configuration: {}", configuration);
94
95         clearCounters();
96
97         try {
98             warningEngine = new SearchEngine(configuration.warningPatterns, configuration.warningBlacklistingPatterns);
99             errorEngine = new SearchEngine(configuration.errorPatterns, configuration.errorBlacklistingPatterns);
100             customEngine = new SearchEngine(configuration.customPatterns, configuration.customBlacklistingPatterns);
101
102         } catch (PatternSyntaxException e) {
103             logger.debug("Illegal search pattern syntax '{}'. ", e.getMessage(), e);
104             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
105             return;
106         }
107
108         logger.debug("Start file reader");
109
110         try {
111             fileReader.registerListener(this);
112             fileReader.start(configuration.filePath, configuration.refreshRate);
113             updateStatus(ThingStatus.ONLINE);
114         } catch (Exception e) {
115             logger.debug("Exception occurred during initalization: {}. ", e.getMessage(), e);
116             shutdown();
117             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
118         }
119     }
120
121     @Override
122     public void dispose() {
123         logger.debug("Stopping thing");
124         shutdown();
125     }
126
127     private void updateChannel(ChannelUID channelUID, Command command, SearchEngine matcher) {
128         if (command instanceof DecimalType) {
129             matcher.setMatchCount(((DecimalType) command).longValue());
130         } else if (command instanceof RefreshType) {
131             updateState(channelUID.getId(), new DecimalType(matcher.getMatchCount()));
132         } else {
133             logger.debug("Unsupported command '{}' received for channel '{}'", command, channelUID);
134         }
135     }
136
137     private void clearCounters() {
138         if (errorEngine != null) {
139             errorEngine.clearMatchCount();
140         }
141         if (warningEngine != null) {
142             warningEngine.clearMatchCount();
143         }
144         if (customEngine != null) {
145             customEngine.clearMatchCount();
146         }
147     }
148
149     private void updateChannelIfLinked(String channelID, State state) {
150         if (isLinked(channelID)) {
151             updateState(channelID, state);
152         }
153     }
154
155     private void shutdown() {
156         logger.debug("Stop file reader");
157         fileReader.unregisterListener(this);
158         fileReader.stop();
159     }
160
161     @Override
162     public void fileNotFound() {
163         final String msg = String.format("Log file '%s' does not exist", configuration.filePath);
164         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, msg);
165     }
166
167     @Override
168     public void fileRotated() {
169         logger.debug("Log rotated");
170         updateChannelIfLinked(CHANNEL_LOGROTATED, new DateTimeType(ZonedDateTime.now()));
171     }
172
173     @Override
174     public void handle(String line) {
175         if (line == null) {
176             return;
177         }
178
179         if (!(thing.getStatus() == ThingStatus.ONLINE)) {
180             updateStatus(ThingStatus.ONLINE);
181         }
182
183         if (errorEngine.isMatching(line)) {
184             updateChannelIfLinked(CHANNEL_ERRORS, new DecimalType(errorEngine.getMatchCount()));
185             updateChannelIfLinked(CHANNEL_LASTERROR, new StringType(line));
186             triggerChannel(CHANNEL_NEWERROR, line);
187         }
188         if (warningEngine.isMatching(line)) {
189             updateChannelIfLinked(CHANNEL_WARNINGS, new DecimalType(warningEngine.getMatchCount()));
190             updateChannelIfLinked(CHANNEL_LASTWARNING, new StringType(line));
191             triggerChannel(CHANNEL_NEWWARNING, line);
192         }
193         if (customEngine.isMatching(line)) {
194             updateChannelIfLinked(CHANNEL_CUSTOMEVENTS, new DecimalType(customEngine.getMatchCount()));
195             updateChannelIfLinked(CHANNEL_LASTCUSTOMEVENT, new StringType(line));
196             triggerChannel(CHANNEL_NEWCUSTOM, line);
197         }
198     }
199
200     @Override
201     public void handle(Exception ex) {
202         final String msg = ex != null ? ex.getMessage() : "";
203         logger.debug("Error while trying to read log file: {}. ", msg, ex);
204         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, msg);
205     }
206 }