]> git.basschouten.com Git - openhab-addons.git/blob
c08511157401227e3d5c7b107294968fa9da5225
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.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;
27 import java.util.Map;
28 import java.util.Set;
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;
37
38 import javax.measure.Quantity;
39 import javax.measure.Unit;
40
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;
87
88 /**
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>.
92  *
93  * @author Kai Kreuzer - Initial contribution
94  * @author Jan N. Klug - some improvements
95  * @author Karel Goderis - remove TimerThread dependency
96  */
97 @NonNullByDefault
98 @Component(service = { PersistenceService.class,
99         QueryablePersistenceService.class }, configurationPid = "org.openhab.rrd4j", configurationPolicy = ConfigurationPolicy.OPTIONAL)
100 public class RRD4jPersistenceService implements QueryablePersistenceService {
101
102     public static final String SERVICE_ID = "rrd4j";
103
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";
107
108     private static final Set<String> SUPPORTED_TYPES = Set.of(CoreItemFactory.SWITCH, CoreItemFactory.CONTACT,
109             CoreItemFactory.DIMMER, CoreItemFactory.NUMBER, CoreItemFactory.ROLLERSHUTTER, CoreItemFactory.COLOR);
110
111     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3,
112             new NamedThreadFactory("RRD4j"));
113
114     private final Map<String, RrdDefConfig> rrdDefs = new ConcurrentHashMap<>();
115
116     private static final String DATASOURCE_STATE = "state";
117
118     private static final Path DB_FOLDER = Path.of(OpenHAB.getUserDataFolder(), "persistence", "rrd4j").toAbsolutePath();
119
120     private static final RrdDbPool DATABASE_POOL = new RrdDbPool();
121
122     private final Logger logger = LoggerFactory.getLogger(RRD4jPersistenceService.class);
123
124     private final Map<String, ScheduledFuture<?>> scheduledJobs = new HashMap<>();
125
126     private final ItemRegistry itemRegistry;
127
128     public static Path getDatabasePath(String name) {
129         return DB_FOLDER.resolve(name + ".rrd");
130     }
131
132     public static RrdDbPool getDatabasePool() {
133         return DATABASE_POOL;
134     }
135
136     @Activate
137     public RRD4jPersistenceService(final @Reference ItemRegistry itemRegistry) {
138         this.itemRegistry = itemRegistry;
139     }
140
141     @Override
142     public String getId() {
143         return SERVICE_ID;
144     }
145
146     @Override
147     public String getLabel(@Nullable Locale locale) {
148         return "RRD4j";
149     }
150
151     @Override
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());
155             return;
156         }
157         final String name = alias == null ? item.getName() : alias;
158
159         Double value;
160
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();
165             if (unit != null) {
166                 QuantityType<?> convertedState = qState.toUnit(unit);
167                 if (convertedState != null) {
168                     value = convertedState.doubleValue();
169                 } else {
170                     value = null;
171                     logger.warn(
172                             "Failed to convert state '{}' to unit '{}'. Please check your item definition for correctness.",
173                             qState, unit);
174                 }
175             } else {
176                 value = qState.doubleValue();
177             }
178         } else {
179             DecimalType state = item.getStateAs(DecimalType.class);
180             if (state != null) {
181                 value = state.toBigDecimal().doubleValue();
182             } else {
183                 value = null;
184             }
185         }
186
187         if (value == null) {
188             // we could not convert the value
189             return;
190         }
191
192         long now = System.currentTimeMillis() / 1000;
193
194         scheduler.schedule(() -> internalStore(name, value, now, true), 0, TimeUnit.SECONDS);
195     }
196
197     private synchronized void internalStore(String name, double value, long now, boolean retry) {
198         RrdDb db = null;
199         try {
200             db = getDB(name, true);
201         } catch (Exception e) {
202             logger.warn("Failed to open rrd4j database '{}' to store data ({})", name, e.toString());
203         }
204         if (db == null) {
205             return;
206         }
207
208         ConsolFun function = getConsolidationFunction(db);
209         if (function != ConsolFun.AVERAGE) {
210             try {
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);
221                         sample.update();
222                         logger.debug("Stored '{}' as value '{}' with timestamp {} in rrd4j database (again)", name,
223                                 lastValue, now - 1);
224                     }
225                 }
226             } catch (IOException e) {
227                 logger.debug("Error storing last value (again): {}", e.getMessage());
228             }
229         }
230         try {
231             Sample sample = db.createSample();
232             sample.setTime(now);
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();
237             }
238             sample.setValue(DATASOURCE_STATE, storeValue);
239             sample.update();
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);
246                 if (job != null) {
247                     job.cancel(true);
248                     scheduledJobs.remove(name);
249                 }
250                 job = scheduler.schedule(() -> internalStore(name, value, now + 1, false), 1, TimeUnit.SECONDS);
251                 scheduledJobs.put(name, job);
252             } else {
253                 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
254             }
255         } catch (Exception e) {
256             logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
257         }
258         try {
259             db.close();
260         } catch (IOException e) {
261             logger.debug("Error closing rrd4j database: {}", e.getMessage());
262         }
263     }
264
265     @Override
266     public void store(Item item) {
267         store(item, null);
268     }
269
270     @Override
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 + ")");
276         }
277
278         String itemName = filter.getItemName();
279         if (itemName == null) {
280             logger.warn("Item name is missing in filter {}", filter);
281             return List.of();
282         }
283         logger.trace("Querying rrd4j database for item '{}'", itemName);
284
285         RrdDb db = null;
286         try {
287             db = getDB(itemName, false);
288         } catch (Exception e) {
289             logger.warn("Failed to open rrd4j database '{}' for querying ({})", itemName, e.toString());
290             return List.of();
291         }
292         if (db == null) {
293             logger.debug("Could not find item '{}' in rrd4j database", itemName);
294             return List.of();
295         }
296
297         Item item = null;
298         Unit<?> unit = null;
299         try {
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();
305             }
306         } catch (ItemNotFoundException e) {
307             logger.debug("Could not find item '{}' in registry", itemName);
308         }
309
310         long start = 0L;
311         long end = filterEndDate == null ? System.currentTimeMillis() / 1000
312                 : filterEndDate.toInstant().getEpochSecond();
313
314         try {
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);
332                         } else {
333                             return List.of();
334                         }
335                     } else {
336                         start = end;
337                     }
338                 } else {
339                     throw new UnsupportedOperationException(
340                             "rrd4j does not allow querys without a begin date, unless order is descending and a single value is requested");
341                 }
342             } else {
343                 start = filterBeginDate.toInstant().getEpochSecond();
344             }
345
346             // do not call method {@link RrdDb#createFetchRequest(ConsolFun, long, long, long)} if start > end to avoid
347             // an IAE to be thrown
348             if (start > end) {
349                 logger.debug("Could not query rrd4j database for item '{}': start ({}) > end ({})", itemName, start,
350                         end);
351                 return List.of();
352             }
353
354             FetchRequest request = db.createFetchRequest(getConsolidationFunction(db), start, end, 1);
355             FetchData result = request.fetchData();
356
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);
365                 }
366                 ts += step;
367             }
368             return items;
369         } catch (IOException e) {
370             logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
371             return List.of();
372         } finally {
373             try {
374                 db.close();
375             } catch (IOException e) {
376                 logger.debug("Error closing rrd4j database: {}", e.getMessage());
377             }
378         }
379     }
380
381     @Override
382     public Set<PersistenceItemInfo> getItemInfo() {
383         return Set.of();
384     }
385
386     protected synchronized @Nullable RrdDb getDB(String alias, boolean createFileIfAbsent) {
387         RrdDb db = null;
388         Path path = getDatabasePath(alias);
389         try {
390             Builder builder = RrdDb.getBuilder();
391             builder.setPool(DATABASE_POOL);
392
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);
400                 }
401                 RrdDef rrdDef = getRrdDef(alias, path);
402                 if (rrdDef != null) {
403                     // create a new database file
404                     builder.setRrdDef(rrdDef);
405                     db = builder.build();
406                 } else {
407                     logger.debug(
408                             "Did not create rrd4j database for item '{}' since no rrd definition could be determined. This is likely due to an unsupported item type.",
409                             alias);
410                 }
411             }
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());
417         }
418         return db;
419     }
420
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)) {
427                 useRdc = rdc;
428                 break;
429             }
430         }
431         if (useRdc == null) { // not defined, use defaults
432             try {
433                 Item item = itemRegistry.getItem(itemName);
434                 if (!isSupportedItemType(item)) {
435                     return null;
436                 }
437                 if (item instanceof NumberItem) {
438                     NumberItem numberItem = (NumberItem) item;
439                     useRdc = numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE)
440                             : rrdDefs.get(DEFAULT_NUMERIC);
441                 } else {
442                     useRdc = rrdDefs.get(DEFAULT_OTHER);
443                 }
444             } catch (ItemNotFoundException e) {
445                 logger.debug("Could not find item '{}' in registry", itemName);
446                 return null;
447             }
448         }
449         logger.trace("Using rrd definition '{}' for item '{}'.", useRdc, itemName);
450         return useRdc;
451     }
452
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);
462             }
463             return rrdDef;
464         } else {
465             return null;
466         }
467     }
468
469     public ConsolFun getConsolidationFunction(RrdDb db) {
470         try {
471             return db.getRrdDef().getArcDefs()[0].getConsolFun();
472         } catch (IOException e) {
473             return ConsolFun.MAX;
474         }
475     }
476
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();
481         }
482
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) {
491             if (unit != null) {
492                 return new QuantityType(value, unit);
493             }
494         }
495         return new DecimalType(value);
496     }
497
498     private boolean isSupportedItemType(Item item) {
499         if (item instanceof GroupItem) {
500             final Item baseItem = ((GroupItem) item).getBaseItem();
501             if (baseItem != null) {
502                 item = baseItem;
503             }
504         }
505
506         return SUPPORTED_TYPES.contains(ItemUtil.getMainItemType(item.getType()));
507     }
508
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) {
514             return List.of();
515         }
516     }
517
518     @Activate
519     protected void activate(final Map<String, Object> config) {
520         modified(config);
521     }
522
523     @Modified
524     protected void modified(final Map<String, Object> config) {
525         // clean existing definitions
526         rrdDefs.clear();
527
528         // add default configurations
529
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
539         defaultNumeric
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);
542
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);
555
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);
566
567         if (config.isEmpty()) {
568             logger.debug("using default configuration only");
569             return;
570         }
571
572         Iterator<String> keys = config.keySet().iterator();
573         while (keys.hasNext()) {
574             String key = keys.next();
575
576             if ("service.pid".equals(key) || "component.name".equals(key)) {
577                 // ignore service.pid and name
578                 continue;
579             }
580
581             String[] subkeys = key.split("\\.");
582             if (subkeys.length != 2) {
583                 logger.debug("config '{}' should have the format 'name.configkey'", key);
584                 continue;
585             }
586
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();
592
593                 if (value.isBlank()) {
594                     logger.trace("Config is empty: {}", property);
595                     continue;
596                 } else {
597                     logger.trace("Processing config: {} = {}", property, value);
598                 }
599
600                 RrdDefConfig rrdDef = rrdDefs.get(name);
601                 if (rrdDef == null) {
602                     rrdDef = new RrdDefConfig(name);
603                     rrdDefs.put(name, rrdDef);
604                 }
605
606                 try {
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);
613                     } else {
614                         logger.debug("Unknown property {} : {}", property, value);
615                     }
616                 } catch (IllegalArgumentException e) {
617                     logger.warn("Ignoring illegal configuration: {}", e.getMessage());
618                 }
619             }
620         }
621
622         for (RrdDefConfig rrdDef : rrdDefs.values()) {
623             if (rrdDef.isValid()) {
624                 logger.debug("Created {}", rrdDef);
625             } else {
626                 logger.info("Removing invalid definition {}", rrdDef);
627                 rrdDefs.remove(rrdDef.name);
628             }
629         }
630     }
631
632     private static class RrdArchiveDef {
633         public @Nullable ConsolFun fcn;
634         public double xff;
635         public int steps, rows;
636
637         @Override
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();
644         }
645     }
646
647     private class RrdDefConfig {
648         public String name;
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;
654
655         private boolean isInitialized;
656
657         public RrdDefConfig(String name) {
658             this.name = name;
659             archives = new ArrayList<>();
660             itemNames = new ArrayList<>();
661             isInitialized = false;
662         }
663
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);
668                 return;
669             }
670
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;
679             } else {
680                 logger.warn("{}: dsType {} not supported", name, opts[0]);
681             }
682
683             heartbeat = Integer.parseInt(opts[1]);
684
685             if ("U".equals(opts[2])) {
686                 min = Double.NaN;
687             } else {
688                 min = Double.parseDouble(opts[2]);
689             }
690
691             if ("U".equals(opts[3])) {
692                 max = Double.NaN;
693             } else {
694                 max = Double.parseDouble(opts[3]);
695             }
696
697             step = Integer.parseInt(opts[4]);
698
699             isInitialized = true; // successfully initialized
700
701             return;
702         }
703
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);
710                     return;
711                 }
712                 RrdArchiveDef arc = new RrdArchiveDef();
713
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;
726                 } else {
727                     logger.warn("{}: consolidation function  {} not supported", name, opts[0]);
728                 }
729                 arc.xff = Double.parseDouble(opts[1]);
730                 arc.steps = Integer.parseInt(opts[2]);
731                 arc.rows = Integer.parseInt(opts[3]);
732                 archives.add(arc);
733             }
734         }
735
736         public void addItems(String itemsString) {
737             Collections.addAll(itemNames, itemsString.split(","));
738         }
739
740         public boolean appliesTo(String item) {
741             return itemNames.contains(item);
742         }
743
744         public boolean isValid() { // a valid configuration must be initialized
745             // and contain at least one function
746             return isInitialized && !archives.isEmpty();
747         }
748
749         @Override
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());
759             }
760             sb.append("] ");
761             sb.append(itemNames.size()).append(" items(s) = [");
762             for (String item : itemNames) {
763                 sb.append(item).append(" ");
764             }
765             sb.append("]");
766             return sb.toString();
767         }
768     }
769
770     @Override
771     public List<PersistenceStrategy> getDefaultStrategies() {
772         return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE,
773                 new PersistenceCronStrategy("everyMinute", "0 * * * * ?"));
774     }
775 }