2 * Copyright (c) 2010-2023 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;
15 import java.io.IOException;
16 import java.nio.file.Files;
17 import java.nio.file.Path;
18 import java.time.Instant;
19 import java.time.ZoneId;
20 import java.time.ZonedDateTime;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Locale;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.RejectedExecutionException;
32 import java.util.concurrent.ScheduledExecutorService;
33 import java.util.concurrent.ScheduledFuture;
34 import java.util.concurrent.TimeUnit;
35 import java.util.stream.Collectors;
36 import java.util.stream.Stream;
38 import javax.measure.Quantity;
39 import javax.measure.Unit;
41 import org.eclipse.jdt.annotation.NonNullByDefault;
42 import org.eclipse.jdt.annotation.Nullable;
43 import org.openhab.core.OpenHAB;
44 import org.openhab.core.common.NamedThreadFactory;
45 import org.openhab.core.items.GroupItem;
46 import org.openhab.core.items.Item;
47 import org.openhab.core.items.ItemNotFoundException;
48 import org.openhab.core.items.ItemRegistry;
49 import org.openhab.core.items.ItemUtil;
50 import org.openhab.core.library.CoreItemFactory;
51 import org.openhab.core.library.items.ColorItem;
52 import org.openhab.core.library.items.ContactItem;
53 import org.openhab.core.library.items.DimmerItem;
54 import org.openhab.core.library.items.NumberItem;
55 import org.openhab.core.library.items.RollershutterItem;
56 import org.openhab.core.library.items.SwitchItem;
57 import org.openhab.core.library.types.DecimalType;
58 import org.openhab.core.library.types.OnOffType;
59 import org.openhab.core.library.types.OpenClosedType;
60 import org.openhab.core.library.types.PercentType;
61 import org.openhab.core.library.types.QuantityType;
62 import org.openhab.core.persistence.FilterCriteria;
63 import org.openhab.core.persistence.FilterCriteria.Ordering;
64 import org.openhab.core.persistence.HistoricItem;
65 import org.openhab.core.persistence.PersistenceItemInfo;
66 import org.openhab.core.persistence.PersistenceService;
67 import org.openhab.core.persistence.QueryablePersistenceService;
68 import org.openhab.core.persistence.strategy.PersistenceCronStrategy;
69 import org.openhab.core.persistence.strategy.PersistenceStrategy;
70 import org.openhab.core.types.State;
71 import org.osgi.service.component.annotations.Activate;
72 import org.osgi.service.component.annotations.Component;
73 import org.osgi.service.component.annotations.ConfigurationPolicy;
74 import org.osgi.service.component.annotations.Modified;
75 import org.osgi.service.component.annotations.Reference;
76 import org.rrd4j.ConsolFun;
77 import org.rrd4j.DsType;
78 import org.rrd4j.core.FetchData;
79 import org.rrd4j.core.FetchRequest;
80 import org.rrd4j.core.RrdDb;
81 import org.rrd4j.core.RrdDb.Builder;
82 import org.rrd4j.core.RrdDbPool;
83 import org.rrd4j.core.RrdDef;
84 import org.rrd4j.core.Sample;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
89 * This is the implementation of the RRD4j {@link PersistenceService}. To learn
90 * more about RRD4j please visit their
91 * <a href="https://github.com/rrd4j/rrd4j">website</a>.
93 * @author Kai Kreuzer - Initial contribution
94 * @author Jan N. Klug - some improvements
95 * @author Karel Goderis - remove TimerThread dependency
98 @Component(service = { PersistenceService.class,
99 QueryablePersistenceService.class }, configurationPid = "org.openhab.rrd4j", configurationPolicy = ConfigurationPolicy.OPTIONAL)
100 public class RRD4jPersistenceService implements QueryablePersistenceService {
102 public static final String SERVICE_ID = "rrd4j";
104 private static final String DEFAULT_OTHER = "default_other";
105 private static final String DEFAULT_NUMERIC = "default_numeric";
106 private static final String DEFAULT_QUANTIFIABLE = "default_quantifiable";
108 private static final Set<String> SUPPORTED_TYPES = Set.of(CoreItemFactory.SWITCH, CoreItemFactory.CONTACT,
109 CoreItemFactory.DIMMER, CoreItemFactory.NUMBER, CoreItemFactory.ROLLERSHUTTER, CoreItemFactory.COLOR);
111 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3,
112 new NamedThreadFactory("RRD4j"));
114 private final Map<String, RrdDefConfig> rrdDefs = new ConcurrentHashMap<>();
116 private static final String DATASOURCE_STATE = "state";
118 private static final Path DB_FOLDER = Path.of(OpenHAB.getUserDataFolder(), "persistence", "rrd4j").toAbsolutePath();
120 private static final RrdDbPool DATABASE_POOL = new RrdDbPool();
122 private final Logger logger = LoggerFactory.getLogger(RRD4jPersistenceService.class);
124 private final Map<String, ScheduledFuture<?>> scheduledJobs = new HashMap<>();
126 private final ItemRegistry itemRegistry;
128 public static Path getDatabasePath(String name) {
129 return DB_FOLDER.resolve(name + ".rrd");
132 public static RrdDbPool getDatabasePool() {
133 return DATABASE_POOL;
137 public RRD4jPersistenceService(final @Reference ItemRegistry itemRegistry) {
138 this.itemRegistry = itemRegistry;
142 public String getId() {
147 public String getLabel(@Nullable Locale locale) {
152 public void store(final Item item, @Nullable final String alias) {
153 if (!isSupportedItemType(item)) {
154 logger.trace("Ignoring item '{}' since its type {} is not supported", item.getName(), item.getType());
157 final String name = alias == null ? item.getName() : alias;
161 if (item instanceof NumberItem && item.getState() instanceof QuantityType) {
162 NumberItem nItem = (NumberItem) item;
163 QuantityType<?> qState = (QuantityType<?>) item.getState();
164 Unit<? extends Quantity<?>> unit = nItem.getUnit();
166 QuantityType<?> convertedState = qState.toUnit(unit);
167 if (convertedState != null) {
168 value = convertedState.doubleValue();
172 "Failed to convert state '{}' to unit '{}'. Please check your item definition for correctness.",
176 value = qState.doubleValue();
179 DecimalType state = item.getStateAs(DecimalType.class);
181 value = state.toBigDecimal().doubleValue();
188 // we could not convert the value
192 long now = System.currentTimeMillis() / 1000;
194 scheduler.schedule(() -> internalStore(name, value, now, true), 0, TimeUnit.SECONDS);
197 private synchronized void internalStore(String name, double value, long now, boolean retry) {
200 db = getDB(name, true);
201 } catch (Exception e) {
202 logger.warn("Failed to open rrd4j database '{}' to store data ({})", name, e.toString());
208 ConsolFun function = getConsolidationFunction(db);
209 if (function != ConsolFun.AVERAGE) {
211 // we store the last value again, so that the value change
212 // in the database is not interpolated, but
213 // happens right at this spot
214 if (now - 1 > db.getLastUpdateTime()) {
215 // only do it if there is not already a value
216 double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
217 if (!Double.isNaN(lastValue)) {
218 Sample sample = db.createSample();
219 sample.setTime(now - 1);
220 sample.setValue(DATASOURCE_STATE, lastValue);
222 logger.debug("Stored '{}' as value '{}' with timestamp {} in rrd4j database (again)", name,
226 } catch (IOException e) {
227 logger.debug("Error storing last value (again): {}", e.getMessage());
231 Sample sample = db.createSample();
233 double storeValue = value;
234 if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be
235 // adjusted by stepsize
236 storeValue = value * db.getRrdDef().getStep();
238 sample.setValue(DATASOURCE_STATE, storeValue);
240 logger.debug("Stored '{}' as value '{}' with timestamp {} in rrd4j database", name, storeValue, now);
241 } catch (IllegalArgumentException e) {
242 String message = e.getMessage();
243 if (message != null && message.contains("at least one second step is required") && retry) {
244 // we try to store the value one second later
245 ScheduledFuture<?> job = scheduledJobs.get(name);
248 scheduledJobs.remove(name);
250 job = scheduler.schedule(() -> internalStore(name, value, now + 1, false), 1, TimeUnit.SECONDS);
251 scheduledJobs.put(name, job);
253 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
255 } catch (Exception e) {
256 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
260 } catch (IOException e) {
261 logger.debug("Error closing rrd4j database: {}", e.getMessage());
266 public void store(Item item) {
271 public Iterable<HistoricItem> query(FilterCriteria filter) {
272 ZonedDateTime filterBeginDate = filter.getBeginDate();
273 ZonedDateTime filterEndDate = filter.getEndDate();
274 if (filterBeginDate != null && filterEndDate != null && filterBeginDate.isAfter(filterEndDate)) {
275 throw new IllegalArgumentException("begin (" + filterBeginDate + ") before end (" + filterEndDate + ")");
278 String itemName = filter.getItemName();
279 if (itemName == null) {
280 logger.warn("Item name is missing in filter {}", filter);
283 logger.trace("Querying rrd4j database for item '{}'", itemName);
287 db = getDB(itemName, false);
288 } catch (Exception e) {
289 logger.warn("Failed to open rrd4j database '{}' for querying ({})", itemName, e.toString());
293 logger.debug("Could not find item '{}' in rrd4j database", itemName);
300 item = itemRegistry.getItem(itemName);
301 if (item instanceof NumberItem) {
302 // we already retrieve the unit here once as it is a very costly operation,
303 // see https://github.com/openhab/openhab-addons/issues/8928
304 unit = ((NumberItem) item).getUnit();
306 } catch (ItemNotFoundException e) {
307 logger.debug("Could not find item '{}' in registry", itemName);
311 long end = filterEndDate == null ? System.currentTimeMillis() / 1000
312 : filterEndDate.toInstant().getEpochSecond();
315 if (filterBeginDate == null) {
316 // as rrd goes back for years and gets more and more
317 // inaccurate, we only support descending order
318 // and a single return value
319 // if there is no begin date is given - this case is
320 // required specifically for the historicState()
321 // query, which we want to support
322 if (filter.getOrdering() == Ordering.DESCENDING && filter.getPageSize() == 1
323 && filter.getPageNumber() == 0) {
324 if (filterEndDate == null) {
325 // we are asked only for the most recent value!
326 double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
327 if (!Double.isNaN(lastValue)) {
328 HistoricItem rrd4jItem = new RRD4jItem(itemName, mapToState(lastValue, item, unit),
329 ZonedDateTime.ofInstant(Instant.ofEpochMilli(db.getLastArchiveUpdateTime() * 1000),
330 ZoneId.systemDefault()));
331 return List.of(rrd4jItem);
339 throw new UnsupportedOperationException(
340 "rrd4j does not allow querys without a begin date, unless order is descending and a single value is requested");
343 start = filterBeginDate.toInstant().getEpochSecond();
346 // do not call method {@link RrdDb#createFetchRequest(ConsolFun, long, long, long)} if start > end to avoid
347 // an IAE to be thrown
349 logger.debug("Could not query rrd4j database for item '{}': start ({}) > end ({})", itemName, start,
354 FetchRequest request = db.createFetchRequest(getConsolidationFunction(db), start, end, 1);
355 FetchData result = request.fetchData();
357 List<HistoricItem> items = new ArrayList<>();
358 long ts = result.getFirstTimestamp();
359 long step = result.getRowCount() > 1 ? result.getStep() : 0;
360 for (double value : result.getValues(DATASOURCE_STATE)) {
361 if (!Double.isNaN(value) && (((ts >= start) && (ts <= end)) || (start == end))) {
362 RRD4jItem rrd4jItem = new RRD4jItem(itemName, mapToState(value, item, unit),
363 ZonedDateTime.ofInstant(Instant.ofEpochSecond(ts), ZoneId.systemDefault()));
364 items.add(rrd4jItem);
369 } catch (IOException e) {
370 logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
375 } catch (IOException e) {
376 logger.debug("Error closing rrd4j database: {}", e.getMessage());
382 public Set<PersistenceItemInfo> getItemInfo() {
386 protected synchronized @Nullable RrdDb getDB(String alias, boolean createFileIfAbsent) {
388 Path path = getDatabasePath(alias);
390 Builder builder = RrdDb.getBuilder();
391 builder.setPool(DATABASE_POOL);
393 if (Files.exists(path)) {
394 // recreate the RrdDb instance from the file
395 builder.setPath(path.toString());
396 db = builder.build();
397 } else if (createFileIfAbsent) {
398 if (!Files.exists(DB_FOLDER)) {
399 Files.createDirectories(DB_FOLDER);
401 RrdDef rrdDef = getRrdDef(alias, path);
402 if (rrdDef != null) {
403 // create a new database file
404 builder.setRrdDef(rrdDef);
405 db = builder.build();
408 "Did not create rrd4j database for item '{}' since no rrd definition could be determined. This is likely due to an unsupported item type.",
412 } catch (IOException e) {
413 logger.error("Could not create rrd4j database file '{}': {}", path, e.getMessage());
414 } catch (RejectedExecutionException e) {
415 // this happens if the system is shut down
416 logger.debug("Could not create rrd4j database file '{}': {}", path, e.getMessage());
421 private @Nullable RrdDefConfig getRrdDefConfig(String itemName) {
422 RrdDefConfig useRdc = null;
423 for (Map.Entry<String, RrdDefConfig> e : rrdDefs.entrySet()) {
424 // try to find special config
425 RrdDefConfig rdc = e.getValue();
426 if (rdc.appliesTo(itemName)) {
431 if (useRdc == null) { // not defined, use defaults
433 Item item = itemRegistry.getItem(itemName);
434 if (!isSupportedItemType(item)) {
437 if (item instanceof NumberItem) {
438 NumberItem numberItem = (NumberItem) item;
439 useRdc = numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE)
440 : rrdDefs.get(DEFAULT_NUMERIC);
442 useRdc = rrdDefs.get(DEFAULT_OTHER);
444 } catch (ItemNotFoundException e) {
445 logger.debug("Could not find item '{}' in registry", itemName);
449 logger.trace("Using rrd definition '{}' for item '{}'.", useRdc, itemName);
453 private @Nullable RrdDef getRrdDef(String itemName, Path path) {
454 RrdDef rrdDef = new RrdDef(path.toString());
455 RrdDefConfig useRdc = getRrdDefConfig(itemName);
456 if (useRdc != null) {
457 rrdDef.setStep(useRdc.step);
458 rrdDef.setStartTime(System.currentTimeMillis() / 1000 - 1);
459 rrdDef.addDatasource(DATASOURCE_STATE, useRdc.dsType, useRdc.heartbeat, useRdc.min, useRdc.max);
460 for (RrdArchiveDef rad : useRdc.archives) {
461 rrdDef.addArchive(rad.fcn, rad.xff, rad.steps, rad.rows);
469 public ConsolFun getConsolidationFunction(RrdDb db) {
471 return db.getRrdDef().getArcDefs()[0].getConsolFun();
472 } catch (IOException e) {
473 return ConsolFun.MAX;
477 @SuppressWarnings({ "unchecked", "rawtypes" })
478 private State mapToState(double value, @Nullable Item item, @Nullable Unit unit) {
479 if (item instanceof GroupItem) {
480 item = ((GroupItem) item).getBaseItem();
483 if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
484 return value == 0.0d ? OnOffType.OFF : OnOffType.ON;
485 } else if (item instanceof ContactItem) {
486 return value == 0.0d ? OpenClosedType.CLOSED : OpenClosedType.OPEN;
487 } else if (item instanceof DimmerItem || item instanceof RollershutterItem || item instanceof ColorItem) {
488 // make sure Items that need PercentTypes instead of DecimalTypes do receive the right information
489 return new PercentType((int) Math.round(value * 100));
490 } else if (item instanceof NumberItem) {
492 return new QuantityType(value, unit);
495 return new DecimalType(value);
498 private boolean isSupportedItemType(Item item) {
499 if (item instanceof GroupItem) {
500 final Item baseItem = ((GroupItem) item).getBaseItem();
501 if (baseItem != null) {
506 return SUPPORTED_TYPES.contains(ItemUtil.getMainItemType(item.getType()));
509 public List<String> getRrdFiles() {
510 try (Stream<Path> stream = Files.list(DB_FOLDER)) {
511 return stream.filter(file -> !Files.isDirectory(file) && file.toFile().getName().endsWith(".rrd"))
512 .map(file -> file.toFile().getName()).collect(Collectors.toList());
513 } catch (IOException e) {
519 protected void activate(final Map<String, Object> config) {
524 protected void modified(final Map<String, Object> config) {
525 // clean existing definitions
528 // add default configurations
530 RrdDefConfig defaultNumeric = new RrdDefConfig(DEFAULT_NUMERIC);
531 // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
532 defaultNumeric.setDef("GAUGE,600,U,U,10");
533 // define 5 different boxes:
534 // 1. granularity of 10s for the last hour
535 // 2. granularity of 1m for the last week
536 // 3. granularity of 15m for the last year
537 // 4. granularity of 1h for the last 5 years
538 // 5. granularity of 1d for the last 10 years
540 .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");
541 rrdDefs.put(DEFAULT_NUMERIC, defaultNumeric);
543 RrdDefConfig defaultQuantifiable = new RrdDefConfig(DEFAULT_QUANTIFIABLE);
544 // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
545 defaultQuantifiable.setDef("GAUGE,600,U,U,10");
546 // define 5 different boxes:
547 // 1. granularity of 10s for the last hour
548 // 2. granularity of 1m for the last week
549 // 3. granularity of 15m for the last year
550 // 4. granularity of 1h for the last 5 years
551 // 5. granularity of 1d for the last 10 years
552 defaultQuantifiable.addArchives(
553 "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");
554 rrdDefs.put(DEFAULT_QUANTIFIABLE, defaultQuantifiable);
556 RrdDefConfig defaultOther = new RrdDefConfig(DEFAULT_OTHER);
557 // use 5 seconds as a step size for discrete values and allow a 1h silence between updates
558 defaultOther.setDef("GAUGE,3600,U,U,5");
559 // define 4 different boxes:
560 // 1. granularity of 5s for the last hour
561 // 2. granularity of 1m for the last week
562 // 3. granularity of 15m for the last year
563 // 4. granularity of 4h for the last 10 years
564 defaultOther.addArchives("LAST,0.5,1,720:LAST,0.5,12,10080:LAST,0.5,180,35040:LAST,0.5,2880,21900");
565 rrdDefs.put(DEFAULT_OTHER, defaultOther);
567 if (config.isEmpty()) {
568 logger.debug("using default configuration only");
572 Iterator<String> keys = config.keySet().iterator();
573 while (keys.hasNext()) {
574 String key = keys.next();
576 if ("service.pid".equals(key) || "component.name".equals(key)) {
577 // ignore service.pid and name
581 String[] subkeys = key.split("\\.");
582 if (subkeys.length != 2) {
583 logger.debug("config '{}' should have the format 'name.configkey'", key);
587 Object v = config.get(key);
588 if (v instanceof String) {
589 String value = (String) v;
590 String name = subkeys[0].toLowerCase();
591 String property = subkeys[1].toLowerCase();
593 if (value.isBlank()) {
594 logger.trace("Config is empty: {}", property);
597 logger.trace("Processing config: {} = {}", property, value);
600 RrdDefConfig rrdDef = rrdDefs.get(name);
601 if (rrdDef == null) {
602 rrdDef = new RrdDefConfig(name);
603 rrdDefs.put(name, rrdDef);
607 if ("def".equals(property)) {
608 rrdDef.setDef(value);
609 } else if ("archives".equals(property)) {
610 rrdDef.addArchives(value);
611 } else if ("items".equals(property)) {
612 rrdDef.addItems(value);
614 logger.debug("Unknown property {} : {}", property, value);
616 } catch (IllegalArgumentException e) {
617 logger.warn("Ignoring illegal configuration: {}", e.getMessage());
622 for (RrdDefConfig rrdDef : rrdDefs.values()) {
623 if (rrdDef.isValid()) {
624 logger.debug("Created {}", rrdDef);
626 logger.info("Removing invalid definition {}", rrdDef);
627 rrdDefs.remove(rrdDef.name);
632 private static class RrdArchiveDef {
633 public @Nullable ConsolFun fcn;
635 public int steps, rows;
638 public String toString() {
639 StringBuilder sb = new StringBuilder(" " + fcn);
640 sb.append(" xff = ").append(xff);
641 sb.append(" steps = ").append(steps);
642 sb.append(" rows = ").append(rows);
643 return sb.toString();
647 private class RrdDefConfig {
649 public @Nullable DsType dsType;
650 public int heartbeat, step;
651 public double min, max;
652 public List<RrdArchiveDef> archives;
653 public List<String> itemNames;
655 private boolean isInitialized;
657 public RrdDefConfig(String name) {
659 archives = new ArrayList<>();
660 itemNames = new ArrayList<>();
661 isInitialized = false;
664 public void setDef(String defString) {
665 String[] opts = defString.split(",");
666 if (opts.length != 5) { // check if correct number of parameters
667 logger.warn("invalid number of parameters {}: {}", name, defString);
671 if ("ABSOLUTE".equals(opts[0])) { // dsType
672 dsType = DsType.ABSOLUTE;
673 } else if ("COUNTER".equals(opts[0])) {
674 dsType = DsType.COUNTER;
675 } else if ("DERIVE".equals(opts[0])) {
676 dsType = DsType.DERIVE;
677 } else if ("GAUGE".equals(opts[0])) {
678 dsType = DsType.GAUGE;
680 logger.warn("{}: dsType {} not supported", name, opts[0]);
683 heartbeat = Integer.parseInt(opts[1]);
685 if ("U".equals(opts[2])) {
688 min = Double.parseDouble(opts[2]);
691 if ("U".equals(opts[3])) {
694 max = Double.parseDouble(opts[3]);
697 step = Integer.parseInt(opts[4]);
699 isInitialized = true; // successfully initialized
704 public void addArchives(String archivesString) {
705 String splitArchives[] = archivesString.split(":");
706 for (String archiveString : splitArchives) {
707 String[] opts = archiveString.split(",");
708 if (opts.length != 4) { // check if correct number of parameters
709 logger.warn("invalid number of parameters {}: {}", name, archiveString);
712 RrdArchiveDef arc = new RrdArchiveDef();
714 if ("AVERAGE".equals(opts[0])) {
715 arc.fcn = ConsolFun.AVERAGE;
716 } else if ("MIN".equals(opts[0])) {
717 arc.fcn = ConsolFun.MIN;
718 } else if ("MAX".equals(opts[0])) {
719 arc.fcn = ConsolFun.MAX;
720 } else if ("LAST".equals(opts[0])) {
721 arc.fcn = ConsolFun.LAST;
722 } else if ("FIRST".equals(opts[0])) {
723 arc.fcn = ConsolFun.FIRST;
724 } else if ("TOTAL".equals(opts[0])) {
725 arc.fcn = ConsolFun.TOTAL;
727 logger.warn("{}: consolidation function {} not supported", name, opts[0]);
729 arc.xff = Double.parseDouble(opts[1]);
730 arc.steps = Integer.parseInt(opts[2]);
731 arc.rows = Integer.parseInt(opts[3]);
736 public void addItems(String itemsString) {
737 Collections.addAll(itemNames, itemsString.split(","));
740 public boolean appliesTo(String item) {
741 return itemNames.contains(item);
744 public boolean isValid() { // a valid configuration must be initialized
745 // and contain at least one function
746 return isInitialized && !archives.isEmpty();
750 public String toString() {
751 StringBuilder sb = new StringBuilder(name);
752 sb.append(" = ").append(dsType);
753 sb.append(" heartbeat = ").append(heartbeat);
754 sb.append(" min/max = ").append(min).append("/").append(max);
755 sb.append(" step = ").append(step);
756 sb.append(" ").append(archives.size()).append(" archives(s) = [");
757 for (RrdArchiveDef arc : archives) {
758 sb.append(arc.toString());
761 sb.append(itemNames.size()).append(" items(s) = [");
762 for (String item : itemNames) {
763 sb.append(item).append(" ");
766 return sb.toString();
771 public List<PersistenceStrategy> getDefaultStrategies() {
772 return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE,
773 new PersistenceCronStrategy("everyMinute", "0 * * * * ?"));