]> git.basschouten.com Git - openhab-addons.git/blob
783d6aaa72ade5c3c6498e214ee82bac4b3f2b6f
[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.persistence.rrd4j.internal;
14
15 import java.io.File;
16 import java.io.IOException;
17 import java.time.Instant;
18 import java.time.ZoneId;
19 import java.time.ZonedDateTime;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.Executors;
30 import java.util.concurrent.RejectedExecutionException;
31 import java.util.concurrent.ScheduledExecutorService;
32 import java.util.concurrent.ScheduledFuture;
33 import java.util.concurrent.TimeUnit;
34
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.core.OpenHAB;
38 import org.openhab.core.common.NamedThreadFactory;
39 import org.openhab.core.items.Item;
40 import org.openhab.core.items.ItemNotFoundException;
41 import org.openhab.core.items.ItemRegistry;
42 import org.openhab.core.library.items.ContactItem;
43 import org.openhab.core.library.items.DimmerItem;
44 import org.openhab.core.library.items.NumberItem;
45 import org.openhab.core.library.items.RollershutterItem;
46 import org.openhab.core.library.items.SwitchItem;
47 import org.openhab.core.library.types.DecimalType;
48 import org.openhab.core.library.types.OnOffType;
49 import org.openhab.core.library.types.OpenClosedType;
50 import org.openhab.core.library.types.PercentType;
51 import org.openhab.core.persistence.FilterCriteria;
52 import org.openhab.core.persistence.FilterCriteria.Ordering;
53 import org.openhab.core.persistence.HistoricItem;
54 import org.openhab.core.persistence.PersistenceItemInfo;
55 import org.openhab.core.persistence.PersistenceService;
56 import org.openhab.core.persistence.QueryablePersistenceService;
57 import org.openhab.core.persistence.strategy.PersistenceCronStrategy;
58 import org.openhab.core.persistence.strategy.PersistenceStrategy;
59 import org.openhab.core.types.State;
60 import org.osgi.service.component.annotations.Activate;
61 import org.osgi.service.component.annotations.Component;
62 import org.osgi.service.component.annotations.Reference;
63 import org.rrd4j.ConsolFun;
64 import org.rrd4j.DsType;
65 import org.rrd4j.core.FetchData;
66 import org.rrd4j.core.FetchRequest;
67 import org.rrd4j.core.RrdDb;
68 import org.rrd4j.core.RrdDef;
69 import org.rrd4j.core.Sample;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 /**
74  * This is the implementation of the RRD4j {@link PersistenceService}. To learn
75  * more about RRD4j please visit their
76  * <a href="https://github.com/rrd4j/rrd4j">website</a>.
77  *
78  * @author Kai Kreuzer - Initial contribution
79  * @author Jan N. Klug - some improvements
80  * @author Karel Goderis - remove TimerThread dependency
81  */
82 @NonNullByDefault
83 @Component(service = { PersistenceService.class,
84         QueryablePersistenceService.class }, configurationPid = "org.openhab.rrd4j")
85 public class RRD4jPersistenceService implements QueryablePersistenceService {
86
87     private static final String DEFAULT_OTHER = "default_other";
88     private static final String DEFAULT_NUMERIC = "default_numeric";
89     private static final String DEFAULT_QUANTIFIABLE = "default_quantifiable";
90
91     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3,
92             new NamedThreadFactory("RRD4j"));
93
94     private final Map<String, @Nullable RrdDefConfig> rrdDefs = new ConcurrentHashMap<>();
95
96     private static final String DATASOURCE_STATE = "state";
97
98     public static final String DB_FOLDER = getUserPersistenceDataFolder() + File.separator + "rrd4j";
99
100     private final Logger logger = LoggerFactory.getLogger(RRD4jPersistenceService.class);
101
102     private final Map<String, @Nullable ScheduledFuture<?>> scheduledJobs = new HashMap<>();
103
104     protected final ItemRegistry itemRegistry;
105
106     @Activate
107     public RRD4jPersistenceService(final @Reference ItemRegistry itemRegistry) {
108         this.itemRegistry = itemRegistry;
109     }
110
111     @Override
112     public String getId() {
113         return "rrd4j";
114     }
115
116     @Override
117     public String getLabel(@Nullable Locale locale) {
118         return "RRD4j";
119     }
120
121     @Override
122     public synchronized void store(final Item item, @Nullable final String alias) {
123         final String name = alias == null ? item.getName() : alias;
124         RrdDb db = getDB(name);
125         if (db != null) {
126             ConsolFun function = getConsolidationFunction(db);
127             long now = System.currentTimeMillis() / 1000;
128             if (function != ConsolFun.AVERAGE) {
129                 try {
130                     // we store the last value again, so that the value change
131                     // in the database is not interpolated, but
132                     // happens right at this spot
133                     if (now - 1 > db.getLastUpdateTime()) {
134                         // only do it if there is not already a value
135                         double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
136                         if (!Double.isNaN(lastValue)) {
137                             Sample sample = db.createSample();
138                             sample.setTime(now - 1);
139                             sample.setValue(DATASOURCE_STATE, lastValue);
140                             sample.update();
141                             logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name,
142                                     mapToState(lastValue, item.getName()));
143                         }
144                     }
145                 } catch (IOException e) {
146                     logger.debug("Error storing last value (again): {}", e.getMessage());
147                 }
148             }
149             try {
150                 Sample sample = db.createSample();
151                 sample.setTime(now);
152
153                 DecimalType state = item.getStateAs(DecimalType.class);
154                 if (state != null) {
155                     double value = state.toBigDecimal().doubleValue();
156                     if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be
157                                                                                           // adjusted by stepsize
158                         value = value * db.getRrdDef().getStep();
159                     }
160                     sample.setValue(DATASOURCE_STATE, value);
161                     sample.update();
162                     logger.debug("Stored '{}' with state '{}' in rrd4j database", name, state);
163                 }
164             } catch (IllegalArgumentException e) {
165                 if (e.getMessage().contains("at least one second step is required")) {
166                     // we try to store the value one second later
167                     ScheduledFuture<?> job = scheduledJobs.get(name);
168                     if (job != null) {
169                         job.cancel(true);
170                         scheduledJobs.remove(name);
171                     }
172                     job = scheduler.schedule(() -> store(item, name), 1, TimeUnit.SECONDS);
173                     scheduledJobs.put(name, job);
174                 } else {
175                     logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
176                 }
177             } catch (Exception e) {
178                 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
179             }
180             try {
181                 db.close();
182             } catch (IOException e) {
183                 logger.debug("Error closing rrd4j database: {}", e.getMessage());
184             }
185         }
186     }
187
188     @Override
189     public void store(Item item) {
190         store(item, null);
191     }
192
193     @Override
194     public Iterable<HistoricItem> query(FilterCriteria filter) {
195         String itemName = filter.getItemName();
196         RrdDb db = getDB(itemName);
197         if (db != null) {
198             ConsolFun consolidationFunction = getConsolidationFunction(db);
199             long start = 0L;
200             long end = filter.getEndDate() == null ? System.currentTimeMillis() / 1000
201                     : filter.getEndDate().toInstant().getEpochSecond();
202
203             try {
204                 if (filter.getBeginDate() == null) {
205                     // as rrd goes back for years and gets more and more
206                     // inaccurate, we only support descending order
207                     // and a single return value
208                     // if there is no begin date is given - this case is
209                     // required specifically for the historicState()
210                     // query, which we want to support
211                     if (filter.getOrdering() == Ordering.DESCENDING && filter.getPageSize() == 1
212                             && filter.getPageNumber() == 0) {
213                         if (filter.getEndDate() == null) {
214                             // we are asked only for the most recent value!
215                             double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
216                             if (!Double.isNaN(lastValue)) {
217                                 HistoricItem rrd4jItem = new RRD4jItem(itemName, mapToState(lastValue, itemName),
218                                         ZonedDateTime.ofInstant(
219                                                 Instant.ofEpochMilli(db.getLastArchiveUpdateTime() * 1000),
220                                                 ZoneId.systemDefault()));
221                                 return Collections.singletonList(rrd4jItem);
222                             } else {
223                                 return Collections.emptyList();
224                             }
225                         } else {
226                             start = end;
227                         }
228                     } else {
229                         throw new UnsupportedOperationException("rrd4j does not allow querys without a begin date, "
230                                 + "unless order is descending and a single value is requested");
231                     }
232                 } else {
233                     start = filter.getBeginDate().toInstant().getEpochSecond();
234                 }
235                 FetchRequest request = db.createFetchRequest(consolidationFunction, start, end, 1);
236
237                 List<HistoricItem> items = new ArrayList<>();
238                 FetchData result = request.fetchData();
239                 long ts = result.getFirstTimestamp();
240                 long step = result.getRowCount() > 1 ? result.getStep() : 0;
241                 for (double value : result.getValues(DATASOURCE_STATE)) {
242                     if (!Double.isNaN(value) && (((ts >= start) && (ts <= end)) || (start == end))) {
243                         RRD4jItem rrd4jItem = new RRD4jItem(itemName, mapToState(value, itemName),
244                                 ZonedDateTime.ofInstant(Instant.ofEpochMilli(ts * 1000), ZoneId.systemDefault()));
245                         items.add(rrd4jItem);
246                     }
247                     ts += step;
248                 }
249                 return items;
250             } catch (IOException e) {
251                 logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
252             }
253         }
254         return Collections.emptyList();
255     }
256
257     @Override
258     public Set<PersistenceItemInfo> getItemInfo() {
259         return Collections.emptySet();
260     }
261
262     protected @Nullable synchronized RrdDb getDB(String alias) {
263         RrdDb db = null;
264         File file = new File(DB_FOLDER + File.separator + alias + ".rrd");
265         try {
266             if (file.exists()) {
267                 // recreate the RrdDb instance from the file
268                 db = new RrdDb(file.getAbsolutePath());
269             } else {
270                 File folder = new File(DB_FOLDER);
271                 if (!folder.exists()) {
272                     folder.mkdirs();
273                 }
274                 // create a new database file
275                 db = new RrdDb(getRrdDef(alias, file));
276             }
277         } catch (IOException e) {
278             logger.error("Could not create rrd4j database file '{}': {}", file.getAbsolutePath(), e.getMessage());
279         } catch (RejectedExecutionException e) {
280             // this happens if the system is shut down
281             logger.debug("Could not create rrd4j database file '{}': {}", file.getAbsolutePath(), e.getMessage());
282         }
283         return db;
284     }
285
286     private @Nullable RrdDefConfig getRrdDefConfig(String itemName) {
287         RrdDefConfig useRdc = null;
288         for (Map.Entry<String, @Nullable RrdDefConfig> e : rrdDefs.entrySet()) {
289             // try to find special config
290             RrdDefConfig rdc = e.getValue();
291             if (rdc != null && rdc.appliesTo(itemName)) {
292                 useRdc = rdc;
293                 break;
294             }
295         }
296         if (useRdc == null) { // not defined, use defaults
297             try {
298                 Item item = itemRegistry.getItem(itemName);
299                 if (item instanceof NumberItem) {
300                     NumberItem numberItem = (NumberItem) item;
301                     return numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE)
302                             : rrdDefs.get(DEFAULT_NUMERIC);
303                 }
304             } catch (ItemNotFoundException e) {
305                 logger.debug("Could not find item '{}' in registry", itemName);
306             }
307         }
308         return rrdDefs.get(DEFAULT_OTHER);
309     }
310
311     private RrdDef getRrdDef(String itemName, File file) {
312         RrdDef rrdDef = new RrdDef(file.getAbsolutePath());
313         RrdDefConfig useRdc = getRrdDefConfig(itemName);
314         if (useRdc != null) {
315             rrdDef.setStep(useRdc.step);
316             rrdDef.setStartTime(System.currentTimeMillis() / 1000 - 1);
317             rrdDef.addDatasource(DATASOURCE_STATE, useRdc.dsType, useRdc.heartbeat, useRdc.min, useRdc.max);
318             for (RrdArchiveDef rad : useRdc.archives) {
319                 rrdDef.addArchive(rad.fcn, rad.xff, rad.steps, rad.rows);
320             }
321         }
322         return rrdDef;
323     }
324
325     public ConsolFun getConsolidationFunction(RrdDb db) {
326         try {
327             return db.getRrdDef().getArcDefs()[0].getConsolFun();
328         } catch (IOException e) {
329             return ConsolFun.MAX;
330         }
331     }
332
333     private State mapToState(double value, String itemName) {
334         try {
335             Item item = itemRegistry.getItem(itemName);
336             if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
337                 return value == 0.0d ? OnOffType.OFF : OnOffType.ON;
338             } else if (item instanceof ContactItem) {
339                 return value == 0.0d ? OpenClosedType.CLOSED : OpenClosedType.OPEN;
340             } else if (item instanceof DimmerItem || item instanceof RollershutterItem) {
341                 // make sure Items that need PercentTypes instead of DecimalTypes do receive the right information
342                 return new PercentType((int) Math.round(value * 100));
343             }
344         } catch (ItemNotFoundException e) {
345             logger.debug("Could not find item '{}' in registry", itemName);
346         }
347         // just return a DecimalType as a fallback
348         return new DecimalType(value);
349     }
350
351     private static String getUserPersistenceDataFolder() {
352         return OpenHAB.getUserDataFolder() + File.separator + "persistence";
353     }
354
355     /**
356      * @{inheritDoc
357      */
358     public void activate(final Map<String, Object> config) {
359         // add default configurations
360
361         RrdDefConfig defaultNumeric = new RrdDefConfig(DEFAULT_NUMERIC);
362         // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
363         defaultNumeric.setDef("GAUGE,600,U,U,10");
364         // define 5 different boxes:
365         // 1. granularity of 10s for the last hour
366         // 2. granularity of 1m for the last week
367         // 3. granularity of 15m for the last year
368         // 4. granularity of 1h for the last 5 years
369         // 5. granularity of 1d for the last 10 years
370         defaultNumeric.addArchives("LAST,0.5,1,360:LAST,0.5,6,10080:LAST,0.5,90,36500:LAST,0.5,8640,3650");
371         rrdDefs.put(DEFAULT_NUMERIC, defaultNumeric);
372
373         RrdDefConfig defaultQuantifiable = new RrdDefConfig(DEFAULT_QUANTIFIABLE);
374         // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
375         defaultQuantifiable.setDef("GAUGE,600,U,U,10");
376         // define 5 different boxes:
377         // 1. granularity of 10s for the last hour
378         // 2. granularity of 1m for the last week
379         // 3. granularity of 15m for the last year
380         // 4. granularity of 1h for the last 5 years
381         // 5. granularity of 1d for the last 10 years
382         defaultQuantifiable
383                 .addArchives("AVERAGE,0.5,1,360:AVERAGE,0.5,6,10080:LAST,0.5,90,36500:AVERAGE,0.5,8640,3650");
384         rrdDefs.put(DEFAULT_QUANTIFIABLE, defaultQuantifiable);
385
386         RrdDefConfig defaultOther = new RrdDefConfig(DEFAULT_OTHER);
387         // use 5 seconds as a step size for discrete values and allow a 1h silence between updates
388         defaultOther.setDef("GAUGE,3600,U,U,5");
389         // define 4 different boxes:
390         // 1. granularity of 5s for the last hour
391         // 2. granularity of 1m for the last week
392         // 3. granularity of 15m for the last year
393         // 4. granularity of 4h for the last 10 years
394         defaultOther.addArchives("LAST,0.5,1,1440:LAST,0.5,12,10080:LAST,0.5,180,35040:LAST,0.5,240,21900");
395         rrdDefs.put(DEFAULT_OTHER, defaultOther);
396
397         if (config.isEmpty()) {
398             logger.debug("using default configuration only");
399             return;
400         }
401
402         Iterator<String> keys = config.keySet().iterator();
403         while (keys.hasNext()) {
404             String key = keys.next();
405
406             if (key.equals("service.pid") || key.equals("component.name")) {
407                 // ignore service.pid and name
408                 continue;
409             }
410
411             String[] subkeys = key.split("\\.");
412             if (subkeys.length != 2) {
413                 logger.debug("config '{}' should have the format 'name.configkey'", key);
414                 continue;
415             }
416
417             Object v = config.get(key);
418             if (v instanceof String) {
419                 String value = (String) v;
420                 String name = subkeys[0].toLowerCase();
421                 String property = subkeys[1].toLowerCase();
422
423                 if (value.isBlank()) {
424                     logger.trace("Config is empty: {}", property);
425                     continue;
426                 } else {
427                     logger.trace("Processing config: {} = {}", property, value);
428                 }
429
430                 RrdDefConfig rrdDef = rrdDefs.get(name);
431                 if (rrdDef == null) {
432                     rrdDef = new RrdDefConfig(name);
433                     rrdDefs.put(name, rrdDef);
434                 }
435
436                 try {
437                     if (property.equals("def")) {
438                         rrdDef.setDef(value);
439                     } else if (property.equals("archives")) {
440                         rrdDef.addArchives(value);
441                     } else if (property.equals("items")) {
442                         rrdDef.addItems(value);
443                     } else {
444                         logger.debug("Unknown property {} : {}", property, value);
445                     }
446                 } catch (IllegalArgumentException e) {
447                     logger.warn("Ignoring illegal configuration: {}", e.getMessage());
448                 }
449             }
450         }
451
452         for (RrdDefConfig rrdDef : rrdDefs.values()) {
453             if (rrdDef != null) {
454                 if (rrdDef.isValid()) {
455                     logger.debug("Created {}", rrdDef);
456                 } else {
457                     logger.info("Removing invalid definition {}", rrdDef);
458                     rrdDefs.remove(rrdDef.name);
459                 }
460             }
461         }
462     }
463
464     private class RrdArchiveDef {
465         public @Nullable ConsolFun fcn;
466         public double xff;
467         public int steps, rows;
468
469         @Override
470         public String toString() {
471             StringBuilder sb = new StringBuilder(" " + fcn);
472             sb.append(" xff = ").append(xff);
473             sb.append(" steps = ").append(steps);
474             sb.append(" rows = ").append(rows);
475             return sb.toString();
476         }
477     }
478
479     private class RrdDefConfig {
480         public String name;
481         public @Nullable DsType dsType;
482         public int heartbeat, step;
483         public double min, max;
484         public List<RrdArchiveDef> archives;
485         public List<String> itemNames;
486
487         private boolean isInitialized;
488
489         public RrdDefConfig(String name) {
490             this.name = name;
491             archives = new ArrayList<>();
492             itemNames = new ArrayList<>();
493             isInitialized = false;
494         }
495
496         public void setDef(String defString) {
497             String[] opts = defString.split(",");
498             if (opts.length != 5) { // check if correct number of parameters
499                 logger.warn("invalid number of parameters {}: {}", name, defString);
500                 return;
501             }
502
503             if (opts[0].equals("ABSOLUTE")) { // dsType
504                 dsType = DsType.ABSOLUTE;
505             } else if (opts[0].equals("COUNTER")) {
506                 dsType = DsType.COUNTER;
507             } else if (opts[0].equals("DERIVE")) {
508                 dsType = DsType.DERIVE;
509             } else if (opts[0].equals("GAUGE")) {
510                 dsType = DsType.GAUGE;
511             } else {
512                 logger.warn("{}: dsType {} not supported", name, opts[0]);
513             }
514
515             heartbeat = Integer.parseInt(opts[1]);
516
517             if (opts[2].equals("U")) {
518                 min = Double.NaN;
519             } else {
520                 min = Double.parseDouble(opts[2]);
521             }
522
523             if (opts[3].equals("U")) {
524                 max = Double.NaN;
525             } else {
526                 max = Double.parseDouble(opts[3]);
527             }
528
529             step = Integer.parseInt(opts[4]);
530
531             isInitialized = true; // successfully initialized
532
533             return;
534         }
535
536         public void addArchives(String archivesString) {
537             String splitArchives[] = archivesString.split(":");
538             for (String archiveString : splitArchives) {
539                 String[] opts = archiveString.split(",");
540                 if (opts.length != 4) { // check if correct number of parameters
541                     logger.warn("invalid number of parameters {}: {}", name, archiveString);
542                     return;
543                 }
544                 RrdArchiveDef arc = new RrdArchiveDef();
545
546                 if (opts[0].equals("AVERAGE")) {
547                     arc.fcn = ConsolFun.AVERAGE;
548                 } else if (opts[0].equals("MIN")) {
549                     arc.fcn = ConsolFun.MIN;
550                 } else if (opts[0].equals("MAX")) {
551                     arc.fcn = ConsolFun.MAX;
552                 } else if (opts[0].equals("LAST")) {
553                     arc.fcn = ConsolFun.LAST;
554                 } else if (opts[0].equals("FIRST")) {
555                     arc.fcn = ConsolFun.FIRST;
556                 } else if (opts[0].equals("TOTAL")) {
557                     arc.fcn = ConsolFun.TOTAL;
558                 } else {
559                     logger.warn("{}: consolidation function  {} not supported", name, opts[0]);
560                 }
561                 arc.xff = Double.parseDouble(opts[1]);
562                 arc.steps = Integer.parseInt(opts[2]);
563                 arc.rows = Integer.parseInt(opts[3]);
564                 archives.add(arc);
565             }
566         }
567
568         public void addItems(String itemsString) {
569             String splitItems[] = itemsString.split(",");
570             for (String item : splitItems) {
571                 itemNames.add(item);
572             }
573         }
574
575         public boolean appliesTo(String item) {
576             return itemNames.contains(item);
577         }
578
579         public boolean isValid() { // a valid configuration must be initialized
580             // and contain at least one function
581             return (isInitialized && (archives.size() > 0));
582         }
583
584         @Override
585         public String toString() {
586             StringBuilder sb = new StringBuilder(name);
587             sb.append(" = ").append(dsType);
588             sb.append(" heartbeat = ").append(heartbeat);
589             sb.append(" min/max = ").append(min).append("/").append(max);
590             sb.append(" step = ").append(step);
591             sb.append(" ").append(archives.size()).append(" archives(s) = [");
592             for (RrdArchiveDef arc : archives) {
593                 sb.append(arc.toString());
594             }
595             sb.append("] ");
596             sb.append(itemNames.size()).append(" items(s) = [");
597             for (String item : itemNames) {
598                 sb.append(item).append(" ");
599             }
600             sb.append("]");
601             return sb.toString();
602         }
603     }
604
605     @Override
606     public List<PersistenceStrategy> getDefaultStrategies() {
607         return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE,
608                 new PersistenceCronStrategy("everyMinute", "0 * * * * ?"));
609     }
610 }