]> git.basschouten.com Git - openhab-addons.git/blob
f846da2cdf99be3400a6de50538ba77229cf152e
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.persistence.rrd4j.internal;
14
15 import java.io.File;
16 import java.io.IOException;
17 import java.time.Instant;
18 import java.time.ZoneId;
19 import java.time.ZonedDateTime;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Locale;
25 import java.util.Map;
26 import java.util.Set;
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;
33
34 import javax.measure.Quantity;
35 import javax.measure.Unit;
36
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;
79
80 /**
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>.
84  *
85  * @author Kai Kreuzer - Initial contribution
86  * @author Jan N. Klug - some improvements
87  * @author Karel Goderis - remove TimerThread dependency
88  */
89 @NonNullByDefault
90 @Component(service = { PersistenceService.class,
91         QueryablePersistenceService.class }, configurationPid = "org.openhab.rrd4j", configurationPolicy = ConfigurationPolicy.OPTIONAL)
92 public class RRD4jPersistenceService implements QueryablePersistenceService {
93
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";
97
98     private static final Set<String> SUPPORTED_TYPES = Set.of(CoreItemFactory.SWITCH, CoreItemFactory.CONTACT,
99             CoreItemFactory.DIMMER, CoreItemFactory.NUMBER, CoreItemFactory.ROLLERSHUTTER);
100
101     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3,
102             new NamedThreadFactory("RRD4j"));
103
104     private final Map<String, @Nullable RrdDefConfig> rrdDefs = new ConcurrentHashMap<>();
105
106     private static final String DATASOURCE_STATE = "state";
107
108     public static final String DB_FOLDER = getUserPersistenceDataFolder() + File.separator + "rrd4j";
109
110     private final Logger logger = LoggerFactory.getLogger(RRD4jPersistenceService.class);
111
112     private final Map<String, @Nullable ScheduledFuture<?>> scheduledJobs = new HashMap<>();
113
114     protected final ItemRegistry itemRegistry;
115
116     @Activate
117     public RRD4jPersistenceService(final @Reference ItemRegistry itemRegistry) {
118         this.itemRegistry = itemRegistry;
119     }
120
121     @Override
122     public String getId() {
123         return "rrd4j";
124     }
125
126     @Override
127     public String getLabel(@Nullable Locale locale) {
128         return "RRD4j";
129     }
130
131     @Override
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());
135             return;
136         }
137         final String name = alias == null ? item.getName() : alias;
138         RrdDb db = getDB(name);
139         if (db != null) {
140             ConsolFun function = getConsolidationFunction(db);
141             long now = System.currentTimeMillis() / 1000;
142             if (function != ConsolFun.AVERAGE) {
143                 try {
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);
154                             sample.update();
155                             logger.debug("Stored '{}' with state '{}' in rrd4j database (again)", name,
156                                     mapToState(lastValue, item));
157                         }
158                     }
159                 } catch (IOException e) {
160                     logger.debug("Error storing last value (again): {}", e.getMessage());
161                 }
162             }
163             try {
164                 Sample sample = db.createSample();
165                 sample.setTime(now);
166
167                 Double value = null;
168
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();
173                     if (unit != null) {
174                         QuantityType<?> convertedState = qState.toUnit(unit);
175                         if (convertedState != null) {
176                             value = convertedState.doubleValue();
177                         } else {
178                             logger.warn(
179                                     "Failed to convert state '{}' to unit '{}'. Please check your item definition for correctness.",
180                                     qState, unit);
181                         }
182                     } else {
183                         value = qState.doubleValue();
184                     }
185                 } else {
186                     DecimalType state = item.getStateAs(DecimalType.class);
187                     if (state != null) {
188                         value = state.toBigDecimal().doubleValue();
189                     }
190                 }
191                 if (value != null) {
192                     if (db.getDatasource(DATASOURCE_STATE).getType() == DsType.COUNTER) { // counter values must be
193                                                                                           // adjusted by stepsize
194                         value = value * db.getRrdDef().getStep();
195                     }
196                     sample.setValue(DATASOURCE_STATE, value);
197                     sample.update();
198                     logger.debug("Stored '{}' with state '{}' in rrd4j database", name, value);
199                 }
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);
205                     if (job != null) {
206                         job.cancel(true);
207                         scheduledJobs.remove(name);
208                     }
209                     job = scheduler.schedule(() -> store(item, name), 1, TimeUnit.SECONDS);
210                     scheduledJobs.put(name, job);
211                 } else {
212                     logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
213                 }
214             } catch (Exception e) {
215                 logger.warn("Could not persist '{}' to rrd4j database: {}", name, e.getMessage());
216             }
217             try {
218                 db.close();
219             } catch (IOException e) {
220                 logger.debug("Error closing rrd4j database: {}", e.getMessage());
221             }
222         }
223     }
224
225     @Override
226     public void store(Item item) {
227         store(item, null);
228     }
229
230     @Override
231     public Iterable<HistoricItem> query(FilterCriteria filter) {
232         String itemName = filter.getItemName();
233
234         RrdDb db = getDB(itemName);
235         if (db == null) {
236             logger.debug("Could not find item '{}' in rrd4j database", itemName);
237             return List.of();
238         }
239
240         Item item = null;
241         try {
242             item = itemRegistry.getItem(itemName);
243         } catch (ItemNotFoundException e) {
244             logger.debug("Could not find item '{}' in registry", itemName);
245         }
246
247         long start = 0L;
248         long end = filter.getEndDate() == null ? System.currentTimeMillis() / 1000
249                 : filter.getEndDate().toInstant().getEpochSecond();
250
251         try {
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);
269                         } else {
270                             return List.of();
271                         }
272                     } else {
273                         start = end;
274                     }
275                 } else {
276                     throw new UnsupportedOperationException("rrd4j does not allow querys without a begin date, "
277                             + "unless order is descending and a single value is requested");
278                 }
279             } else {
280                 start = filter.getBeginDate().toInstant().getEpochSecond();
281             }
282
283             FetchRequest request = db.createFetchRequest(getConsolidationFunction(db), start, end, 1);
284             FetchData result = request.fetchData();
285
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);
294                 }
295                 ts += step;
296             }
297             return items;
298         } catch (IOException e) {
299             logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
300             return List.of();
301         }
302     }
303
304     @Override
305     public Set<PersistenceItemInfo> getItemInfo() {
306         return Set.of();
307     }
308
309     protected synchronized @Nullable RrdDb getDB(String alias) {
310         RrdDb db = null;
311         File file = new File(DB_FOLDER + File.separator + alias + ".rrd");
312         try {
313             if (file.exists()) {
314                 // recreate the RrdDb instance from the file
315                 db = new RrdDb(file.getAbsolutePath());
316             } else {
317                 File folder = new File(DB_FOLDER);
318                 if (!folder.exists()) {
319                     folder.mkdirs();
320                 }
321                 RrdDef rrdDef = getRrdDef(alias, file);
322                 if (rrdDef != null) {
323                     // create a new database file
324                     db = new RrdDb(rrdDef);
325                 } else {
326                     logger.debug(
327                             "Did not create rrd4j database for item '{}' since no rrd definition could be determined. This is likely due to an unsupported item type.",
328                             alias);
329                 }
330             }
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());
336         }
337         return db;
338     }
339
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)) {
346                 useRdc = rdc;
347                 break;
348             }
349         }
350         if (useRdc == null) { // not defined, use defaults
351             try {
352                 Item item = itemRegistry.getItem(itemName);
353                 if (!isSupportedItemType(item)) {
354                     return null;
355                 }
356                 if (item instanceof NumberItem) {
357                     NumberItem numberItem = (NumberItem) item;
358                     useRdc = numberItem.getDimension() != null ? rrdDefs.get(DEFAULT_QUANTIFIABLE)
359                             : rrdDefs.get(DEFAULT_NUMERIC);
360                 } else {
361                     useRdc = rrdDefs.get(DEFAULT_OTHER);
362                 }
363             } catch (ItemNotFoundException e) {
364                 logger.debug("Could not find item '{}' in registry", itemName);
365                 return null;
366             }
367         }
368         logger.trace("Using rrd definition '{}' for item '{}'.", useRdc, itemName);
369         return useRdc;
370     }
371
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);
381             }
382             return rrdDef;
383         } else {
384             return null;
385         }
386     }
387
388     public ConsolFun getConsolidationFunction(RrdDb db) {
389         try {
390             return db.getRrdDef().getArcDefs()[0].getConsolFun();
391         } catch (IOException e) {
392             return ConsolFun.MAX;
393         }
394     }
395
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));
404         }
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);
408     }
409
410     private boolean isSupportedItemType(Item item) {
411         return SUPPORTED_TYPES.contains(ItemUtil.getMainItemType(item.getType()));
412     }
413
414     private static String getUserPersistenceDataFolder() {
415         return OpenHAB.getUserDataFolder() + File.separator + "persistence";
416     }
417
418     @Activate
419     protected void activate(final Map<String, Object> config) {
420         modified(config);
421     }
422
423     @Modified
424     protected void modified(final Map<String, Object> config) {
425         // clean existing definitions
426         rrdDefs.clear();
427
428         // add default configurations
429
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
439         defaultNumeric
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);
442
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);
455
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);
466
467         if (config.isEmpty()) {
468             logger.debug("using default configuration only");
469             return;
470         }
471
472         Iterator<String> keys = config.keySet().iterator();
473         while (keys.hasNext()) {
474             String key = keys.next();
475
476             if (key.equals("service.pid") || key.equals("component.name")) {
477                 // ignore service.pid and name
478                 continue;
479             }
480
481             String[] subkeys = key.split("\\.");
482             if (subkeys.length != 2) {
483                 logger.debug("config '{}' should have the format 'name.configkey'", key);
484                 continue;
485             }
486
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();
492
493                 if (value.isBlank()) {
494                     logger.trace("Config is empty: {}", property);
495                     continue;
496                 } else {
497                     logger.trace("Processing config: {} = {}", property, value);
498                 }
499
500                 RrdDefConfig rrdDef = rrdDefs.get(name);
501                 if (rrdDef == null) {
502                     rrdDef = new RrdDefConfig(name);
503                     rrdDefs.put(name, rrdDef);
504                 }
505
506                 try {
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);
513                     } else {
514                         logger.debug("Unknown property {} : {}", property, value);
515                     }
516                 } catch (IllegalArgumentException e) {
517                     logger.warn("Ignoring illegal configuration: {}", e.getMessage());
518                 }
519             }
520         }
521
522         for (RrdDefConfig rrdDef : rrdDefs.values()) {
523             if (rrdDef != null) {
524                 if (rrdDef.isValid()) {
525                     logger.debug("Created {}", rrdDef);
526                 } else {
527                     logger.info("Removing invalid definition {}", rrdDef);
528                     rrdDefs.remove(rrdDef.name);
529                 }
530             }
531         }
532     }
533
534     private class RrdArchiveDef {
535         public @Nullable ConsolFun fcn;
536         public double xff;
537         public int steps, rows;
538
539         @Override
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();
546         }
547     }
548
549     private class RrdDefConfig {
550         public String name;
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;
556
557         private boolean isInitialized;
558
559         public RrdDefConfig(String name) {
560             this.name = name;
561             archives = new ArrayList<>();
562             itemNames = new ArrayList<>();
563             isInitialized = false;
564         }
565
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);
570                 return;
571             }
572
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;
581             } else {
582                 logger.warn("{}: dsType {} not supported", name, opts[0]);
583             }
584
585             heartbeat = Integer.parseInt(opts[1]);
586
587             if (opts[2].equals("U")) {
588                 min = Double.NaN;
589             } else {
590                 min = Double.parseDouble(opts[2]);
591             }
592
593             if (opts[3].equals("U")) {
594                 max = Double.NaN;
595             } else {
596                 max = Double.parseDouble(opts[3]);
597             }
598
599             step = Integer.parseInt(opts[4]);
600
601             isInitialized = true; // successfully initialized
602
603             return;
604         }
605
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);
612                     return;
613                 }
614                 RrdArchiveDef arc = new RrdArchiveDef();
615
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;
628                 } else {
629                     logger.warn("{}: consolidation function  {} not supported", name, opts[0]);
630                 }
631                 arc.xff = Double.parseDouble(opts[1]);
632                 arc.steps = Integer.parseInt(opts[2]);
633                 arc.rows = Integer.parseInt(opts[3]);
634                 archives.add(arc);
635             }
636         }
637
638         public void addItems(String itemsString) {
639             String splitItems[] = itemsString.split(",");
640             for (String item : splitItems) {
641                 itemNames.add(item);
642             }
643         }
644
645         public boolean appliesTo(String item) {
646             return itemNames.contains(item);
647         }
648
649         public boolean isValid() { // a valid configuration must be initialized
650             // and contain at least one function
651             return (isInitialized && (archives.size() > 0));
652         }
653
654         @Override
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());
664             }
665             sb.append("] ");
666             sb.append(itemNames.size()).append(" items(s) = [");
667             for (String item : itemNames) {
668                 sb.append(item).append(" ");
669             }
670             sb.append("]");
671             return sb.toString();
672         }
673     }
674
675     @Override
676     public List<PersistenceStrategy> getDefaultStrategies() {
677         return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE,
678                 new PersistenceCronStrategy("everyMinute", "0 * * * * ?"));
679     }
680 }