]> git.basschouten.com Git - openhab-addons.git/blob
1cc6eb9c185660c06d0e2880781f59376aa965a4
[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
36 import javax.measure.Quantity;
37 import javax.measure.Unit;
38
39 import org.eclipse.jdt.annotation.NonNullByDefault;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.openhab.core.OpenHAB;
42 import org.openhab.core.common.NamedThreadFactory;
43 import org.openhab.core.items.GroupItem;
44 import org.openhab.core.items.Item;
45 import org.openhab.core.items.ItemNotFoundException;
46 import org.openhab.core.items.ItemRegistry;
47 import org.openhab.core.items.ItemUtil;
48 import org.openhab.core.library.CoreItemFactory;
49 import org.openhab.core.library.items.ColorItem;
50 import org.openhab.core.library.items.ContactItem;
51 import org.openhab.core.library.items.DimmerItem;
52 import org.openhab.core.library.items.NumberItem;
53 import org.openhab.core.library.items.RollershutterItem;
54 import org.openhab.core.library.items.SwitchItem;
55 import org.openhab.core.library.types.DecimalType;
56 import org.openhab.core.library.types.OnOffType;
57 import org.openhab.core.library.types.OpenClosedType;
58 import org.openhab.core.library.types.PercentType;
59 import org.openhab.core.library.types.QuantityType;
60 import org.openhab.core.persistence.FilterCriteria;
61 import org.openhab.core.persistence.FilterCriteria.Ordering;
62 import org.openhab.core.persistence.HistoricItem;
63 import org.openhab.core.persistence.PersistenceItemInfo;
64 import org.openhab.core.persistence.PersistenceService;
65 import org.openhab.core.persistence.QueryablePersistenceService;
66 import org.openhab.core.persistence.strategy.PersistenceCronStrategy;
67 import org.openhab.core.persistence.strategy.PersistenceStrategy;
68 import org.openhab.core.types.State;
69 import org.osgi.service.component.annotations.Activate;
70 import org.osgi.service.component.annotations.Component;
71 import org.osgi.service.component.annotations.ConfigurationPolicy;
72 import org.osgi.service.component.annotations.Modified;
73 import org.osgi.service.component.annotations.Reference;
74 import org.rrd4j.ConsolFun;
75 import org.rrd4j.DsType;
76 import org.rrd4j.core.FetchData;
77 import org.rrd4j.core.FetchRequest;
78 import org.rrd4j.core.RrdDb;
79 import org.rrd4j.core.RrdDb.Builder;
80 import org.rrd4j.core.RrdDbPool;
81 import org.rrd4j.core.RrdDef;
82 import org.rrd4j.core.Sample;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 /**
87  * This is the implementation of the RRD4j {@link PersistenceService}. To learn
88  * more about RRD4j please visit their
89  * <a href="https://github.com/rrd4j/rrd4j">website</a>.
90  *
91  * @author Kai Kreuzer - Initial contribution
92  * @author Jan N. Klug - some improvements
93  * @author Karel Goderis - remove TimerThread dependency
94  */
95 @NonNullByDefault
96 @Component(service = { PersistenceService.class,
97         QueryablePersistenceService.class }, configurationPid = "org.openhab.rrd4j", configurationPolicy = ConfigurationPolicy.OPTIONAL)
98 public class RRD4jPersistenceService implements QueryablePersistenceService {
99
100     private static final String DEFAULT_OTHER = "default_other";
101     private static final String DEFAULT_NUMERIC = "default_numeric";
102     private static final String DEFAULT_QUANTIFIABLE = "default_quantifiable";
103
104     private static final Set<String> SUPPORTED_TYPES = Set.of(CoreItemFactory.SWITCH, CoreItemFactory.CONTACT,
105             CoreItemFactory.DIMMER, CoreItemFactory.NUMBER, CoreItemFactory.ROLLERSHUTTER, CoreItemFactory.COLOR);
106
107     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3,
108             new NamedThreadFactory("RRD4j"));
109
110     private final Map<String, RrdDefConfig> rrdDefs = new ConcurrentHashMap<>();
111
112     private static final String DATASOURCE_STATE = "state";
113
114     private static final Path DB_FOLDER = Path.of(OpenHAB.getUserDataFolder(), "persistence", "rrd4j").toAbsolutePath();
115
116     private static final RrdDbPool DATABASE_POOL = new RrdDbPool();
117
118     private final Logger logger = LoggerFactory.getLogger(RRD4jPersistenceService.class);
119
120     private final Map<String, ScheduledFuture<?>> scheduledJobs = new HashMap<>();
121
122     private final ItemRegistry itemRegistry;
123
124     public static Path getDatabasePath(String name) {
125         return DB_FOLDER.resolve(name + ".rrd");
126     }
127
128     public static RrdDbPool getDatabasePool() {
129         return DATABASE_POOL;
130     }
131
132     @Activate
133     public RRD4jPersistenceService(final @Reference ItemRegistry itemRegistry) {
134         this.itemRegistry = itemRegistry;
135     }
136
137     @Override
138     public String getId() {
139         return "rrd4j";
140     }
141
142     @Override
143     public String getLabel(@Nullable Locale locale) {
144         return "RRD4j";
145     }
146
147     @Override
148     public synchronized void store(final Item item, @Nullable final String alias) {
149         if (!isSupportedItemType(item)) {
150             logger.trace("Ignoring item '{}' since its type {} is not supported", item.getName(), item.getType());
151             return;
152         }
153         final String name = alias == null ? item.getName() : alias;
154
155         RrdDb db = null;
156         try {
157             db = getDB(name);
158         } catch (Exception e) {
159             logger.warn("Failed to open rrd4j database '{}' to store data ({})", name, e.toString());
160         }
161         if (db == null) {
162             return;
163         }
164
165         ConsolFun function = getConsolidationFunction(db);
166         long now = System.currentTimeMillis() / 1000;
167         if (function != ConsolFun.AVERAGE) {
168             try {
169                 // we store the last value again, so that the value change
170                 // in the database is not interpolated, but
171                 // happens right at this spot
172                 if (now - 1 > db.getLastUpdateTime()) {
173                     // only do it if there is not already a value
174                     double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
175                     if (!Double.isNaN(lastValue)) {
176                         Sample sample = db.createSample();
177                         sample.setTime(now - 1);
178                         sample.setValue(DATASOURCE_STATE, lastValue);
179                         sample.update();
180                         logger.debug("Stored '{}' as value '{}' in rrd4j database (again)", name, lastValue);
181                     }
182                 }
183             } catch (IOException e) {
184                 logger.debug("Error storing last value (again): {}", e.getMessage());
185             }
186         }
187         try {
188             Sample sample = db.createSample();
189             sample.setTime(now);
190
191             Double value = null;
192
193             if (item instanceof NumberItem && item.getState() instanceof QuantityType) {
194                 NumberItem nItem = (NumberItem) item;
195                 QuantityType<?> qState = (QuantityType<?>) item.getState();
196                 Unit<? extends Quantity<?>> unit = nItem.getUnit();
197                 if (unit != null) {
198                     QuantityType<?> convertedState = qState.toUnit(unit);
199                     if (convertedState != null) {
200                         value = convertedState.doubleValue();
201                     } else {
202                         logger.warn(
203                                 "Failed to convert state '{}' to unit '{}'. Please check your item definition for correctness.",
204                                 qState, unit);
205                     }
206                 } else {
207                     value = qState.doubleValue();
208                 }
209             } else {
210                 DecimalType state = item.getStateAs(DecimalType.class);
211                 if (state != null) {
212                     value = state.toBigDecimal().doubleValue();
213                 }
214             }
215             if (value != null) {
216                 if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be
217                                                                                       // adjusted by stepsize
218                     value = value * db.getRrdDef().getStep();
219                 }
220                 sample.setValue(DATASOURCE_STATE, value);
221                 sample.update();
222                 logger.debug("Stored '{}' as value '{}' in rrd4j database", name, value);
223             }
224         } catch (IllegalArgumentException e) {
225             String message = e.getMessage();
226             if (message != null && message.contains("at least one second step is required")) {
227                 // we try to store the value one second later
228                 ScheduledFuture<?> job = scheduledJobs.get(name);
229                 if (job != null) {
230                     job.cancel(true);
231                     scheduledJobs.remove(name);
232                 }
233                 job = scheduler.schedule(() -> store(item, name), 1, TimeUnit.SECONDS);
234                 scheduledJobs.put(name, job);
235             } else {
236                 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
237             }
238         } catch (Exception e) {
239             logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
240         }
241         try {
242             db.close();
243         } catch (IOException e) {
244             logger.debug("Error closing rrd4j database: {}", e.getMessage());
245         }
246     }
247
248     @Override
249     public void store(Item item) {
250         store(item, null);
251     }
252
253     @Override
254     public Iterable<HistoricItem> query(FilterCriteria filter) {
255         ZonedDateTime filterBeginDate = filter.getBeginDate();
256         ZonedDateTime filterEndDate = filter.getEndDate();
257         if (filterBeginDate != null && filterEndDate != null && filterBeginDate.isAfter(filterEndDate)) {
258             throw new IllegalArgumentException("begin (" + filterBeginDate + ") before end (" + filterEndDate + ")");
259         }
260
261         String itemName = filter.getItemName();
262
263         RrdDb db = null;
264         try {
265             db = getDB(itemName);
266         } catch (Exception e) {
267             logger.warn("Failed to open rrd4j database '{}' for querying ({})", itemName, e.toString());
268             return List.of();
269         }
270         if (db == null) {
271             logger.debug("Could not find item '{}' in rrd4j database", itemName);
272             return List.of();
273         }
274
275         Item item = null;
276         Unit<?> unit = null;
277         try {
278             item = itemRegistry.getItem(itemName);
279             if (item instanceof NumberItem) {
280                 // we already retrieve the unit here once as it is a very costly operation,
281                 // see https://github.com/openhab/openhab-addons/issues/8928
282                 unit = ((NumberItem) item).getUnit();
283             }
284         } catch (ItemNotFoundException e) {
285             logger.debug("Could not find item '{}' in registry", itemName);
286         }
287
288         long start = 0L;
289         long end = filterEndDate == null ? System.currentTimeMillis() / 1000
290                 : filterEndDate.toInstant().getEpochSecond();
291
292         try {
293             if (filterBeginDate == null) {
294                 // as rrd goes back for years and gets more and more
295                 // inaccurate, we only support descending order
296                 // and a single return value
297                 // if there is no begin date is given - this case is
298                 // required specifically for the historicState()
299                 // query, which we want to support
300                 if (filter.getOrdering() == Ordering.DESCENDING && filter.getPageSize() == 1
301                         && filter.getPageNumber() == 0) {
302                     if (filterEndDate == null) {
303                         // we are asked only for the most recent value!
304                         double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
305                         if (!Double.isNaN(lastValue)) {
306                             HistoricItem rrd4jItem = new RRD4jItem(itemName, mapToState(lastValue, item, unit),
307                                     ZonedDateTime.ofInstant(Instant.ofEpochMilli(db.getLastArchiveUpdateTime() * 1000),
308                                             ZoneId.systemDefault()));
309                             return List.of(rrd4jItem);
310                         } else {
311                             return List.of();
312                         }
313                     } else {
314                         start = end;
315                     }
316                 } else {
317                     throw new UnsupportedOperationException(
318                             "rrd4j does not allow querys without a begin date, unless order is descending and a single value is requested");
319                 }
320             } else {
321                 start = filterBeginDate.toInstant().getEpochSecond();
322             }
323
324             // do not call method {@link RrdDb#createFetchRequest(ConsolFun, long, long, long)} if start > end to avoid
325             // an IAE to be thrown
326             if (start > end) {
327                 logger.debug("Could not query rrd4j database for item '{}': start ({}) > end ({})", itemName, start,
328                         end);
329                 return List.of();
330             }
331
332             FetchRequest request = db.createFetchRequest(getConsolidationFunction(db), start, end, 1);
333             FetchData result = request.fetchData();
334
335             List<HistoricItem> items = new ArrayList<>();
336             long ts = result.getFirstTimestamp();
337             long step = result.getRowCount() > 1 ? result.getStep() : 0;
338             for (double value : result.getValues(DATASOURCE_STATE)) {
339                 if (!Double.isNaN(value) && (((ts >= start) && (ts <= end)) || (start == end))) {
340                     RRD4jItem rrd4jItem = new RRD4jItem(itemName, mapToState(value, item, unit),
341                             ZonedDateTime.ofInstant(Instant.ofEpochSecond(ts), ZoneId.systemDefault()));
342                     items.add(rrd4jItem);
343                 }
344                 ts += step;
345             }
346             return items;
347         } catch (IOException e) {
348             logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
349             return List.of();
350         } finally {
351             try {
352                 db.close();
353             } catch (IOException e) {
354                 logger.debug("Error closing rrd4j database: {}", e.getMessage());
355             }
356         }
357     }
358
359     @Override
360     public Set<PersistenceItemInfo> getItemInfo() {
361         return Set.of();
362     }
363
364     protected synchronized @Nullable RrdDb getDB(String alias) {
365         RrdDb db = null;
366         Path path = getDatabasePath(alias);
367         try {
368             Builder builder = RrdDb.getBuilder();
369             builder.setPool(DATABASE_POOL);
370
371             if (Files.exists(path)) {
372                 // recreate the RrdDb instance from the file
373                 builder.setPath(path.toString());
374                 db = builder.build();
375             } else {
376                 if (!Files.exists(DB_FOLDER)) {
377                     Files.createDirectories(DB_FOLDER);
378                 }
379                 RrdDef rrdDef = getRrdDef(alias, path);
380                 if (rrdDef != null) {
381                     // create a new database file
382                     builder.setRrdDef(rrdDef);
383                     db = builder.build();
384                 } else {
385                     logger.debug(
386                             "Did not create rrd4j database for item '{}' since no rrd definition could be determined. This is likely due to an unsupported item type.",
387                             alias);
388                 }
389             }
390         } catch (IOException e) {
391             logger.error("Could not create rrd4j database file '{}': {}", path, e.getMessage());
392         } catch (RejectedExecutionException e) {
393             // this happens if the system is shut down
394             logger.debug("Could not create rrd4j database file '{}': {}", path, e.getMessage());
395         }
396         return db;
397     }
398
399     private @Nullable RrdDefConfig getRrdDefConfig(String itemName) {
400         RrdDefConfig useRdc = null;
401         for (Map.Entry<String, RrdDefConfig> e : rrdDefs.entrySet()) {
402             // try to find special config
403             RrdDefConfig rdc = e.getValue();
404             if (rdc.appliesTo(itemName)) {
405                 useRdc = rdc;
406                 break;
407             }
408         }
409         if (useRdc == null) { // not defined, use defaults
410             try {
411                 Item item = itemRegistry.getItem(itemName);
412                 if (!isSupportedItemType(item)) {
413                     return null;
414                 }
415                 if (item instanceof NumberItem) {
416                     NumberItem numberItem = (NumberItem) item;
417                     useRdc = numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE)
418                             : rrdDefs.get(DEFAULT_NUMERIC);
419                 } else {
420                     useRdc = rrdDefs.get(DEFAULT_OTHER);
421                 }
422             } catch (ItemNotFoundException e) {
423                 logger.debug("Could not find item '{}' in registry", itemName);
424                 return null;
425             }
426         }
427         logger.trace("Using rrd definition '{}' for item '{}'.", useRdc, itemName);
428         return useRdc;
429     }
430
431     private @Nullable RrdDef getRrdDef(String itemName, Path path) {
432         RrdDef rrdDef = new RrdDef(path.toString());
433         RrdDefConfig useRdc = getRrdDefConfig(itemName);
434         if (useRdc != null) {
435             rrdDef.setStep(useRdc.step);
436             rrdDef.setStartTime(System.currentTimeMillis() / 1000 - 1);
437             rrdDef.addDatasource(DATASOURCE_STATE, useRdc.dsType, useRdc.heartbeat, useRdc.min, useRdc.max);
438             for (RrdArchiveDef rad : useRdc.archives) {
439                 rrdDef.addArchive(rad.fcn, rad.xff, rad.steps, rad.rows);
440             }
441             return rrdDef;
442         } else {
443             return null;
444         }
445     }
446
447     public ConsolFun getConsolidationFunction(RrdDb db) {
448         try {
449             return db.getRrdDef().getArcDefs()[0].getConsolFun();
450         } catch (IOException e) {
451             return ConsolFun.MAX;
452         }
453     }
454
455     @SuppressWarnings({ "unchecked", "rawtypes" })
456     private State mapToState(double value, @Nullable Item item, @Nullable Unit unit) {
457         if (item instanceof GroupItem) {
458             item = ((GroupItem) item).getBaseItem();
459         }
460
461         if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
462             return value == 0.0d ? OnOffType.OFF : OnOffType.ON;
463         } else if (item instanceof ContactItem) {
464             return value == 0.0d ? OpenClosedType.CLOSED : OpenClosedType.OPEN;
465         } else if (item instanceof DimmerItem || item instanceof RollershutterItem || item instanceof ColorItem) {
466             // make sure Items that need PercentTypes instead of DecimalTypes do receive the right information
467             return new PercentType((int) Math.round(value * 100));
468         } else if (item instanceof NumberItem) {
469             if (unit != null) {
470                 return new QuantityType(value, unit);
471             }
472         }
473         return new DecimalType(value);
474     }
475
476     private boolean isSupportedItemType(Item item) {
477         if (item instanceof GroupItem) {
478             final Item baseItem = ((GroupItem) item).getBaseItem();
479             if (baseItem != null) {
480                 item = baseItem;
481             }
482         }
483
484         return SUPPORTED_TYPES.contains(ItemUtil.getMainItemType(item.getType()));
485     }
486
487     @Activate
488     protected void activate(final Map<String, Object> config) {
489         modified(config);
490     }
491
492     @Modified
493     protected void modified(final Map<String, Object> config) {
494         // clean existing definitions
495         rrdDefs.clear();
496
497         // add default configurations
498
499         RrdDefConfig defaultNumeric = new RrdDefConfig(DEFAULT_NUMERIC);
500         // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
501         defaultNumeric.setDef("GAUGE,600,U,U,10");
502         // define 5 different boxes:
503         // 1. granularity of 10s for the last hour
504         // 2. granularity of 1m for the last week
505         // 3. granularity of 15m for the last year
506         // 4. granularity of 1h for the last 5 years
507         // 5. granularity of 1d for the last 10 years
508         defaultNumeric
509                 .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");
510         rrdDefs.put(DEFAULT_NUMERIC, defaultNumeric);
511
512         RrdDefConfig defaultQuantifiable = new RrdDefConfig(DEFAULT_QUANTIFIABLE);
513         // use 10 seconds as a step size for numeric values and allow a 10 minute silence between updates
514         defaultQuantifiable.setDef("GAUGE,600,U,U,10");
515         // define 5 different boxes:
516         // 1. granularity of 10s for the last hour
517         // 2. granularity of 1m for the last week
518         // 3. granularity of 15m for the last year
519         // 4. granularity of 1h for the last 5 years
520         // 5. granularity of 1d for the last 10 years
521         defaultQuantifiable.addArchives(
522                 "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");
523         rrdDefs.put(DEFAULT_QUANTIFIABLE, defaultQuantifiable);
524
525         RrdDefConfig defaultOther = new RrdDefConfig(DEFAULT_OTHER);
526         // use 5 seconds as a step size for discrete values and allow a 1h silence between updates
527         defaultOther.setDef("GAUGE,3600,U,U,5");
528         // define 4 different boxes:
529         // 1. granularity of 5s for the last hour
530         // 2. granularity of 1m for the last week
531         // 3. granularity of 15m for the last year
532         // 4. granularity of 4h for the last 10 years
533         defaultOther.addArchives("LAST,0.5,1,720:LAST,0.5,12,10080:LAST,0.5,180,35040:LAST,0.5,2880,21900");
534         rrdDefs.put(DEFAULT_OTHER, defaultOther);
535
536         if (config.isEmpty()) {
537             logger.debug("using default configuration only");
538             return;
539         }
540
541         Iterator<String> keys = config.keySet().iterator();
542         while (keys.hasNext()) {
543             String key = keys.next();
544
545             if ("service.pid".equals(key) || "component.name".equals(key)) {
546                 // ignore service.pid and name
547                 continue;
548             }
549
550             String[] subkeys = key.split("\\.");
551             if (subkeys.length != 2) {
552                 logger.debug("config '{}' should have the format 'name.configkey'", key);
553                 continue;
554             }
555
556             Object v = config.get(key);
557             if (v instanceof String) {
558                 String value = (String) v;
559                 String name = subkeys[0].toLowerCase();
560                 String property = subkeys[1].toLowerCase();
561
562                 if (value.isBlank()) {
563                     logger.trace("Config is empty: {}", property);
564                     continue;
565                 } else {
566                     logger.trace("Processing config: {} = {}", property, value);
567                 }
568
569                 RrdDefConfig rrdDef = rrdDefs.get(name);
570                 if (rrdDef == null) {
571                     rrdDef = new RrdDefConfig(name);
572                     rrdDefs.put(name, rrdDef);
573                 }
574
575                 try {
576                     if ("def".equals(property)) {
577                         rrdDef.setDef(value);
578                     } else if ("archives".equals(property)) {
579                         rrdDef.addArchives(value);
580                     } else if ("items".equals(property)) {
581                         rrdDef.addItems(value);
582                     } else {
583                         logger.debug("Unknown property {} : {}", property, value);
584                     }
585                 } catch (IllegalArgumentException e) {
586                     logger.warn("Ignoring illegal configuration: {}", e.getMessage());
587                 }
588             }
589         }
590
591         for (RrdDefConfig rrdDef : rrdDefs.values()) {
592             if (rrdDef.isValid()) {
593                 logger.debug("Created {}", rrdDef);
594             } else {
595                 logger.info("Removing invalid definition {}", rrdDef);
596                 rrdDefs.remove(rrdDef.name);
597             }
598         }
599     }
600
601     private static class RrdArchiveDef {
602         public @Nullable ConsolFun fcn;
603         public double xff;
604         public int steps, rows;
605
606         @Override
607         public String toString() {
608             StringBuilder sb = new StringBuilder(" " + fcn);
609             sb.append(" xff = ").append(xff);
610             sb.append(" steps = ").append(steps);
611             sb.append(" rows = ").append(rows);
612             return sb.toString();
613         }
614     }
615
616     private class RrdDefConfig {
617         public String name;
618         public @Nullable DsType dsType;
619         public int heartbeat, step;
620         public double min, max;
621         public List<RrdArchiveDef> archives;
622         public List<String> itemNames;
623
624         private boolean isInitialized;
625
626         public RrdDefConfig(String name) {
627             this.name = name;
628             archives = new ArrayList<>();
629             itemNames = new ArrayList<>();
630             isInitialized = false;
631         }
632
633         public void setDef(String defString) {
634             String[] opts = defString.split(",");
635             if (opts.length != 5) { // check if correct number of parameters
636                 logger.warn("invalid number of parameters {}: {}", name, defString);
637                 return;
638             }
639
640             if ("ABSOLUTE".equals(opts[0])) { // dsType
641                 dsType = DsType.ABSOLUTE;
642             } else if ("COUNTER".equals(opts[0])) {
643                 dsType = DsType.COUNTER;
644             } else if ("DERIVE".equals(opts[0])) {
645                 dsType = DsType.DERIVE;
646             } else if ("GAUGE".equals(opts[0])) {
647                 dsType = DsType.GAUGE;
648             } else {
649                 logger.warn("{}: dsType {} not supported", name, opts[0]);
650             }
651
652             heartbeat = Integer.parseInt(opts[1]);
653
654             if ("U".equals(opts[2])) {
655                 min = Double.NaN;
656             } else {
657                 min = Double.parseDouble(opts[2]);
658             }
659
660             if ("U".equals(opts[3])) {
661                 max = Double.NaN;
662             } else {
663                 max = Double.parseDouble(opts[3]);
664             }
665
666             step = Integer.parseInt(opts[4]);
667
668             isInitialized = true; // successfully initialized
669
670             return;
671         }
672
673         public void addArchives(String archivesString) {
674             String splitArchives[] = archivesString.split(":");
675             for (String archiveString : splitArchives) {
676                 String[] opts = archiveString.split(",");
677                 if (opts.length != 4) { // check if correct number of parameters
678                     logger.warn("invalid number of parameters {}: {}", name, archiveString);
679                     return;
680                 }
681                 RrdArchiveDef arc = new RrdArchiveDef();
682
683                 if ("AVERAGE".equals(opts[0])) {
684                     arc.fcn = ConsolFun.AVERAGE;
685                 } else if ("MIN".equals(opts[0])) {
686                     arc.fcn = ConsolFun.MIN;
687                 } else if ("MAX".equals(opts[0])) {
688                     arc.fcn = ConsolFun.MAX;
689                 } else if ("LAST".equals(opts[0])) {
690                     arc.fcn = ConsolFun.LAST;
691                 } else if ("FIRST".equals(opts[0])) {
692                     arc.fcn = ConsolFun.FIRST;
693                 } else if ("TOTAL".equals(opts[0])) {
694                     arc.fcn = ConsolFun.TOTAL;
695                 } else {
696                     logger.warn("{}: consolidation function  {} not supported", name, opts[0]);
697                 }
698                 arc.xff = Double.parseDouble(opts[1]);
699                 arc.steps = Integer.parseInt(opts[2]);
700                 arc.rows = Integer.parseInt(opts[3]);
701                 archives.add(arc);
702             }
703         }
704
705         public void addItems(String itemsString) {
706             Collections.addAll(itemNames, itemsString.split(","));
707         }
708
709         public boolean appliesTo(String item) {
710             return itemNames.contains(item);
711         }
712
713         public boolean isValid() { // a valid configuration must be initialized
714             // and contain at least one function
715             return isInitialized && !archives.isEmpty();
716         }
717
718         @Override
719         public String toString() {
720             StringBuilder sb = new StringBuilder(name);
721             sb.append(" = ").append(dsType);
722             sb.append(" heartbeat = ").append(heartbeat);
723             sb.append(" min/max = ").append(min).append("/").append(max);
724             sb.append(" step = ").append(step);
725             sb.append(" ").append(archives.size()).append(" archives(s) = [");
726             for (RrdArchiveDef arc : archives) {
727                 sb.append(arc.toString());
728             }
729             sb.append("] ");
730             sb.append(itemNames.size()).append(" items(s) = [");
731             for (String item : itemNames) {
732                 sb.append(item).append(" ");
733             }
734             sb.append("]");
735             return sb.toString();
736         }
737     }
738
739     @Override
740     public List<PersistenceStrategy> getDefaultStrategies() {
741         return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE,
742                 new PersistenceCronStrategy("everyMinute", "0 * * * * ?"));
743     }
744 }