2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.persistence.rrd4j.internal;
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.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Locale;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.RejectedExecutionException;
30 import java.util.concurrent.ScheduledExecutorService;
31 import java.util.concurrent.ScheduledFuture;
32 import java.util.concurrent.TimeUnit;
34 import javax.measure.Quantity;
35 import javax.measure.Unit;
37 import org.eclipse.jdt.annotation.NonNullByDefault;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.openhab.core.OpenHAB;
40 import org.openhab.core.common.NamedThreadFactory;
41 import org.openhab.core.items.Item;
42 import org.openhab.core.items.ItemNotFoundException;
43 import org.openhab.core.items.ItemRegistry;
44 import org.openhab.core.items.ItemUtil;
45 import org.openhab.core.library.CoreItemFactory;
46 import org.openhab.core.library.items.ContactItem;
47 import org.openhab.core.library.items.DimmerItem;
48 import org.openhab.core.library.items.NumberItem;
49 import org.openhab.core.library.items.RollershutterItem;
50 import org.openhab.core.library.items.SwitchItem;
51 import org.openhab.core.library.types.DecimalType;
52 import org.openhab.core.library.types.OnOffType;
53 import org.openhab.core.library.types.OpenClosedType;
54 import org.openhab.core.library.types.PercentType;
55 import org.openhab.core.library.types.QuantityType;
56 import org.openhab.core.persistence.FilterCriteria;
57 import org.openhab.core.persistence.FilterCriteria.Ordering;
58 import org.openhab.core.persistence.HistoricItem;
59 import org.openhab.core.persistence.PersistenceItemInfo;
60 import org.openhab.core.persistence.PersistenceService;
61 import org.openhab.core.persistence.QueryablePersistenceService;
62 import org.openhab.core.persistence.strategy.PersistenceCronStrategy;
63 import org.openhab.core.persistence.strategy.PersistenceStrategy;
64 import org.openhab.core.types.State;
65 import org.osgi.service.component.annotations.Activate;
66 import org.osgi.service.component.annotations.Component;
67 import org.osgi.service.component.annotations.ConfigurationPolicy;
68 import org.osgi.service.component.annotations.Modified;
69 import org.osgi.service.component.annotations.Reference;
70 import org.rrd4j.ConsolFun;
71 import org.rrd4j.DsType;
72 import org.rrd4j.core.FetchData;
73 import org.rrd4j.core.FetchRequest;
74 import org.rrd4j.core.RrdDb;
75 import org.rrd4j.core.RrdDef;
76 import org.rrd4j.core.Sample;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * This is the implementation of the RRD4j {@link PersistenceService}. To learn
82 * more about RRD4j please visit their
83 * <a href="https://github.com/rrd4j/rrd4j">website</a>.
85 * @author Kai Kreuzer - Initial contribution
86 * @author Jan N. Klug - some improvements
87 * @author Karel Goderis - remove TimerThread dependency
90 @Component(service = { PersistenceService.class,
91 QueryablePersistenceService.class }, configurationPid = "org.openhab.rrd4j", configurationPolicy = ConfigurationPolicy.OPTIONAL)
92 public class RRD4jPersistenceService implements QueryablePersistenceService {
94 private static final String DEFAULT_OTHER = "default_other";
95 private static final String DEFAULT_NUMERIC = "default_numeric";
96 private static final String DEFAULT_QUANTIFIABLE = "default_quantifiable";
98 private static final Set<String> SUPPORTED_TYPES = Set.of(CoreItemFactory.SWITCH, CoreItemFactory.CONTACT,
99 CoreItemFactory.DIMMER, CoreItemFactory.NUMBER, CoreItemFactory.ROLLERSHUTTER);
101 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3,
102 new NamedThreadFactory("RRD4j"));
104 private final Map<String, @Nullable RrdDefConfig> rrdDefs = new ConcurrentHashMap<>();
106 private static final String DATASOURCE_STATE = "state";
108 public static final String DB_FOLDER = getUserPersistenceDataFolder() + File.separator + "rrd4j";
110 private final Logger logger = LoggerFactory.getLogger(RRD4jPersistenceService.class);
112 private final Map<String, @Nullable ScheduledFuture<?>> scheduledJobs = new HashMap<>();
114 protected final ItemRegistry itemRegistry;
117 public RRD4jPersistenceService(final @Reference ItemRegistry itemRegistry) {
118 this.itemRegistry = itemRegistry;
122 public String getId() {
127 public String getLabel(@Nullable Locale locale) {
132 public synchronized void store(final Item item, @Nullable final String alias) {
133 if (!isSupportedItemType(item)) {
134 logger.trace("Ignoring item '{}' since its type {} is not supported", item.getName(), item.getType());
137 final String name = alias == null ? item.getName() : alias;
138 RrdDb db = getDB(name);
140 ConsolFun function = getConsolidationFunction(db);
141 long now = System.currentTimeMillis() / 1000;
142 if (function != ConsolFun.AVERAGE) {
144 // we store the last value again, so that the value change
145 // in the database is not interpolated, but
146 // happens right at this spot
147 if (now - 1 > db.getLastUpdateTime()) {
148 // only do it if there is not already a value
149 double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
150 if (!Double.isNaN(lastValue)) {
151 Sample sample = db.createSample();
152 sample.setTime(now - 1);
153 sample.setValue(DATASOURCE_STATE, lastValue);
155 logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name,
156 mapToState(lastValue, item));
159 } catch (IOException e) {
160 logger.debug("Error storing last value (again): {}", e.getMessage());
164 Sample sample = db.createSample();
169 if (item instanceof NumberItem && item.getState() instanceof QuantityType) {
170 NumberItem nItem = (NumberItem) item;
171 QuantityType<?> qState = (QuantityType<?>) item.getState();
172 Unit<? extends Quantity<?>> unit = nItem.getUnit();
174 QuantityType<?> convertedState = qState.toUnit(unit);
175 if (convertedState != null) {
176 value = convertedState.doubleValue();
179 "Failed to convert state '{}' to unit '{}'. Please check your item definition for correctness.",
183 value = qState.doubleValue();
186 DecimalType state = item.getStateAs(DecimalType.class);
188 value = state.toBigDecimal().doubleValue();
192 if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be
193 // adjusted by stepsize
194 value = value * db.getRrdDef().getStep();
196 sample.setValue(DATASOURCE_STATE, value);
198 logger.debug("Stored '{}' with state '{}' in rrd4j database", name, value);
200 } catch (IllegalArgumentException e) {
201 String message = e.getMessage();
202 if (message != null && message.contains("at least one second step is required")) {
203 // we try to store the value one second later
204 ScheduledFuture<?> job = scheduledJobs.get(name);
207 scheduledJobs.remove(name);
209 job = scheduler.schedule(() -> store(item, name), 1, TimeUnit.SECONDS);
210 scheduledJobs.put(name, job);
212 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
214 } catch (Exception e) {
215 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
219 } catch (IOException e) {
220 logger.debug("Error closing rrd4j database: {}", e.getMessage());
226 public void store(Item item) {
231 public Iterable<HistoricItem> query(FilterCriteria filter) {
232 String itemName = filter.getItemName();
234 RrdDb db = getDB(itemName);
236 logger.debug("Could not find item '{}' in rrd4j database", itemName);
242 item = itemRegistry.getItem(itemName);
243 } catch (ItemNotFoundException e) {
244 logger.debug("Could not find item '{}' in registry", itemName);
248 long end = filter.getEndDate() == null ? System.currentTimeMillis() / 1000
249 : filter.getEndDate().toInstant().getEpochSecond();
252 if (filter.getBeginDate() == null) {
253 // as rrd goes back for years and gets more and more
254 // inaccurate, we only support descending order
255 // and a single return value
256 // if there is no begin date is given - this case is
257 // required specifically for the historicState()
258 // query, which we want to support
259 if (filter.getOrdering() == Ordering.DESCENDING && filter.getPageSize() == 1
260 && filter.getPageNumber() == 0) {
261 if (filter.getEndDate() == null) {
262 // we are asked only for the most recent value!
263 double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
264 if (!Double.isNaN(lastValue)) {
265 HistoricItem rrd4jItem = new RRD4jItem(itemName, mapToState(lastValue, item),
266 ZonedDateTime.ofInstant(Instant.ofEpochMilli(db.getLastArchiveUpdateTime() * 1000),
267 ZoneId.systemDefault()));
268 return List.of(rrd4jItem);
276 throw new UnsupportedOperationException("rrd4j does not allow querys without a begin date, "
277 + "unless order is descending and a single value is requested");
280 start = filter.getBeginDate().toInstant().getEpochSecond();
283 FetchRequest request = db.createFetchRequest(getConsolidationFunction(db), start, end, 1);
284 FetchData result = request.fetchData();
286 List<HistoricItem> items = new ArrayList<>();
287 long ts = result.getFirstTimestamp();
288 long step = result.getRowCount() > 1 ? result.getStep() : 0;
289 for (double value : result.getValues(DATASOURCE_STATE)) {
290 if (!Double.isNaN(value) && (((ts >= start) && (ts <= end)) || (start == end))) {
291 RRD4jItem rrd4jItem = new RRD4jItem(itemName, mapToState(value, item),
292 ZonedDateTime.ofInstant(Instant.ofEpochMilli(ts * 1000), ZoneId.systemDefault()));
293 items.add(rrd4jItem);
298 } catch (IOException e) {
299 logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
305 public Set<PersistenceItemInfo> getItemInfo() {
309 protected synchronized @Nullable RrdDb getDB(String alias) {
311 File file = new File(DB_FOLDER + File.separator + alias + ".rrd");
314 // recreate the RrdDb instance from the file
315 db = new RrdDb(file.getAbsolutePath());
317 File folder = new File(DB_FOLDER);
318 if (!folder.exists()) {
321 RrdDef rrdDef = getRrdDef(alias, file);
322 if (rrdDef != null) {
323 // create a new database file
324 db = new RrdDb(rrdDef);
327 "Did not create rrd4j database for item '{}' since no rrd definition could be determined. This is likely due to an unsupported item type.",
331 } catch (IOException e) {
332 logger.error("Could not create rrd4j database file '{}': {}", file.getAbsolutePath(), e.getMessage());
333 } catch (RejectedExecutionException e) {
334 // this happens if the system is shut down
335 logger.debug("Could not create rrd4j database file '{}': {}", file.getAbsolutePath(), e.getMessage());
340 private @Nullable RrdDefConfig getRrdDefConfig(String itemName) {
341 RrdDefConfig useRdc = null;
342 for (Map.Entry<String, @Nullable RrdDefConfig> e : rrdDefs.entrySet()) {
343 // try to find special config
344 RrdDefConfig rdc = e.getValue();
345 if (rdc != null && rdc.appliesTo(itemName)) {
350 if (useRdc == null) { // not defined, use defaults
352 Item item = itemRegistry.getItem(itemName);
353 if (!isSupportedItemType(item)) {
356 if (item instanceof NumberItem) {
357 NumberItem numberItem = (NumberItem) item;
358 useRdc = numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE)
359 : rrdDefs.get(DEFAULT_NUMERIC);
361 useRdc = rrdDefs.get(DEFAULT_OTHER);
363 } catch (ItemNotFoundException e) {
364 logger.debug("Could not find item '{}' in registry", itemName);
368 logger.trace("Using rrd definition '{}' for item '{}'.", useRdc, itemName);
372 private @Nullable RrdDef getRrdDef(String itemName, File file) {
373 RrdDef rrdDef = new RrdDef(file.getAbsolutePath());
374 RrdDefConfig useRdc = getRrdDefConfig(itemName);
375 if (useRdc != null) {
376 rrdDef.setStep(useRdc.step);
377 rrdDef.setStartTime(System.currentTimeMillis() / 1000 - 1);
378 rrdDef.addDatasource(DATASOURCE_STATE, useRdc.dsType, useRdc.heartbeat, useRdc.min, useRdc.max);
379 for (RrdArchiveDef rad : useRdc.archives) {
380 rrdDef.addArchive(rad.fcn, rad.xff, rad.steps, rad.rows);
388 public ConsolFun getConsolidationFunction(RrdDb db) {
390 return db.getRrdDef().getArcDefs()[0].getConsolFun();
391 } catch (IOException e) {
392 return ConsolFun.MAX;
396 private State mapToState(double value, @Nullable Item item) {
397 if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
398 return value == 0.0d ? OnOffType.OFF : OnOffType.ON;
399 } else if (item instanceof ContactItem) {
400 return value == 0.0d ? OpenClosedType.CLOSED : OpenClosedType.OPEN;
401 } else if (item instanceof DimmerItem || item instanceof RollershutterItem) {
402 // make sure Items that need PercentTypes instead of DecimalTypes do receive the right information
403 return new PercentType((int) Math.round(value * 100));
405 // return a DecimalType as a fallback and for QuantityType values to prevent performance issues
406 // see: https://github.com/openhab/openhab-addons/issues/8928
407 return new DecimalType(value);
410 private boolean isSupportedItemType(Item item) {
411 return SUPPORTED_TYPES.contains(ItemUtil.getMainItemType(item.getType()));
414 private static String getUserPersistenceDataFolder() {
415 return OpenHAB.getUserDataFolder() + File.separator + "persistence";
419 protected void activate(final Map<String, Object> config) {
424 protected void modified(final Map<String, Object> config) {
425 // clean existing definitions
428 // add default configurations
430 RrdDefConfig defaultNumeric = new RrdDefConfig(DEFAULT_NUMERIC);
431 // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
432 defaultNumeric.setDef("GAUGE,600,U,U,10");
433 // define 5 different boxes:
434 // 1. granularity of 10s for the last hour
435 // 2. granularity of 1m for the last week
436 // 3. granularity of 15m for the last year
437 // 4. granularity of 1h for the last 5 years
438 // 5. granularity of 1d for the last 10 years
440 .addArchives("LAST,0.5,1,360:LAST,0.5,6,10080:LAST,0.5,90,36500:LAST,0.5,360,43800:LAST,0.5,8640,3650");
441 rrdDefs.put(DEFAULT_NUMERIC, defaultNumeric);
443 RrdDefConfig defaultQuantifiable = new RrdDefConfig(DEFAULT_QUANTIFIABLE);
444 // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
445 defaultQuantifiable.setDef("GAUGE,600,U,U,10");
446 // define 5 different boxes:
447 // 1. granularity of 10s for the last hour
448 // 2. granularity of 1m for the last week
449 // 3. granularity of 15m for the last year
450 // 4. granularity of 1h for the last 5 years
451 // 5. granularity of 1d for the last 10 years
452 defaultQuantifiable.addArchives(
453 "AVERAGE,0.5,1,360:AVERAGE,0.5,6,10080:AVERAGE,0.5,90,36500:AVERAGE,0.5,360,43800:AVERAGE,0.5,8640,3650");
454 rrdDefs.put(DEFAULT_QUANTIFIABLE, defaultQuantifiable);
456 RrdDefConfig defaultOther = new RrdDefConfig(DEFAULT_OTHER);
457 // use 5 seconds as a step size for discrete values and allow a 1h silence between updates
458 defaultOther.setDef("GAUGE,3600,U,U,5");
459 // define 4 different boxes:
460 // 1. granularity of 5s for the last hour
461 // 2. granularity of 1m for the last week
462 // 3. granularity of 15m for the last year
463 // 4. granularity of 4h for the last 10 years
464 defaultOther.addArchives("LAST,0.5,1,720:LAST,0.5,12,10080:LAST,0.5,180,35040:LAST,0.5,2880,21900");
465 rrdDefs.put(DEFAULT_OTHER, defaultOther);
467 if (config.isEmpty()) {
468 logger.debug("using default configuration only");
472 Iterator<String> keys = config.keySet().iterator();
473 while (keys.hasNext()) {
474 String key = keys.next();
476 if (key.equals("service.pid") || key.equals("component.name")) {
477 // ignore service.pid and name
481 String[] subkeys = key.split("\\.");
482 if (subkeys.length != 2) {
483 logger.debug("config '{}' should have the format 'name.configkey'", key);
487 Object v = config.get(key);
488 if (v instanceof String) {
489 String value = (String) v;
490 String name = subkeys[0].toLowerCase();
491 String property = subkeys[1].toLowerCase();
493 if (value.isBlank()) {
494 logger.trace("Config is empty: {}", property);
497 logger.trace("Processing config: {} = {}", property, value);
500 RrdDefConfig rrdDef = rrdDefs.get(name);
501 if (rrdDef == null) {
502 rrdDef = new RrdDefConfig(name);
503 rrdDefs.put(name, rrdDef);
507 if (property.equals("def")) {
508 rrdDef.setDef(value);
509 } else if (property.equals("archives")) {
510 rrdDef.addArchives(value);
511 } else if (property.equals("items")) {
512 rrdDef.addItems(value);
514 logger.debug("Unknown property {} : {}", property, value);
516 } catch (IllegalArgumentException e) {
517 logger.warn("Ignoring illegal configuration: {}", e.getMessage());
522 for (RrdDefConfig rrdDef : rrdDefs.values()) {
523 if (rrdDef != null) {
524 if (rrdDef.isValid()) {
525 logger.debug("Created {}", rrdDef);
527 logger.info("Removing invalid definition {}", rrdDef);
528 rrdDefs.remove(rrdDef.name);
534 private class RrdArchiveDef {
535 public @Nullable ConsolFun fcn;
537 public int steps, rows;
540 public String toString() {
541 StringBuilder sb = new StringBuilder(" " + fcn);
542 sb.append(" xff = ").append(xff);
543 sb.append(" steps = ").append(steps);
544 sb.append(" rows = ").append(rows);
545 return sb.toString();
549 private class RrdDefConfig {
551 public @Nullable DsType dsType;
552 public int heartbeat, step;
553 public double min, max;
554 public List<RrdArchiveDef> archives;
555 public List<String> itemNames;
557 private boolean isInitialized;
559 public RrdDefConfig(String name) {
561 archives = new ArrayList<>();
562 itemNames = new ArrayList<>();
563 isInitialized = false;
566 public void setDef(String defString) {
567 String[] opts = defString.split(",");
568 if (opts.length != 5) { // check if correct number of parameters
569 logger.warn("invalid number of parameters {}: {}", name, defString);
573 if (opts[0].equals("ABSOLUTE")) { // dsType
574 dsType = DsType.ABSOLUTE;
575 } else if (opts[0].equals("COUNTER")) {
576 dsType = DsType.COUNTER;
577 } else if (opts[0].equals("DERIVE")) {
578 dsType = DsType.DERIVE;
579 } else if (opts[0].equals("GAUGE")) {
580 dsType = DsType.GAUGE;
582 logger.warn("{}: dsType {} not supported", name, opts[0]);
585 heartbeat = Integer.parseInt(opts[1]);
587 if (opts[2].equals("U")) {
590 min = Double.parseDouble(opts[2]);
593 if (opts[3].equals("U")) {
596 max = Double.parseDouble(opts[3]);
599 step = Integer.parseInt(opts[4]);
601 isInitialized = true; // successfully initialized
606 public void addArchives(String archivesString) {
607 String splitArchives[] = archivesString.split(":");
608 for (String archiveString : splitArchives) {
609 String[] opts = archiveString.split(",");
610 if (opts.length != 4) { // check if correct number of parameters
611 logger.warn("invalid number of parameters {}: {}", name, archiveString);
614 RrdArchiveDef arc = new RrdArchiveDef();
616 if (opts[0].equals("AVERAGE")) {
617 arc.fcn = ConsolFun.AVERAGE;
618 } else if (opts[0].equals("MIN")) {
619 arc.fcn = ConsolFun.MIN;
620 } else if (opts[0].equals("MAX")) {
621 arc.fcn = ConsolFun.MAX;
622 } else if (opts[0].equals("LAST")) {
623 arc.fcn = ConsolFun.LAST;
624 } else if (opts[0].equals("FIRST")) {
625 arc.fcn = ConsolFun.FIRST;
626 } else if (opts[0].equals("TOTAL")) {
627 arc.fcn = ConsolFun.TOTAL;
629 logger.warn("{}: consolidation function {} not supported", name, opts[0]);
631 arc.xff = Double.parseDouble(opts[1]);
632 arc.steps = Integer.parseInt(opts[2]);
633 arc.rows = Integer.parseInt(opts[3]);
638 public void addItems(String itemsString) {
639 String splitItems[] = itemsString.split(",");
640 for (String item : splitItems) {
645 public boolean appliesTo(String item) {
646 return itemNames.contains(item);
649 public boolean isValid() { // a valid configuration must be initialized
650 // and contain at least one function
651 return (isInitialized && (archives.size() > 0));
655 public String toString() {
656 StringBuilder sb = new StringBuilder(name);
657 sb.append(" = ").append(dsType);
658 sb.append(" heartbeat = ").append(heartbeat);
659 sb.append(" min/max = ").append(min).append("/").append(max);
660 sb.append(" step = ").append(step);
661 sb.append(" ").append(archives.size()).append(" archives(s) = [");
662 for (RrdArchiveDef arc : archives) {
663 sb.append(arc.toString());
666 sb.append(itemNames.size()).append(" items(s) = [");
667 for (String item : itemNames) {
668 sb.append(item).append(" ");
671 return sb.toString();
676 public List<PersistenceStrategy> getDefaultStrategies() {
677 return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE,
678 new PersistenceCronStrategy("everyMinute", "0 * * * * ?"));