]> git.basschouten.com Git - openhab-addons.git/blob
0d51e746bc27c587553f5902e9ca7720ea4950b9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.mapdb.internal;
14
15 import java.io.File;
16 import java.io.IOException;
17 import java.nio.file.DirectoryStream;
18 import java.nio.file.Files;
19 import java.nio.file.Path;
20 import java.time.Instant;
21 import java.util.Date;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.Set;
27 import java.util.concurrent.ExecutorService;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.mapdb.DB;
34 import org.mapdb.DBMaker;
35 import org.openhab.core.OpenHAB;
36 import org.openhab.core.common.ThreadPoolManager;
37 import org.openhab.core.items.Item;
38 import org.openhab.core.persistence.FilterCriteria;
39 import org.openhab.core.persistence.HistoricItem;
40 import org.openhab.core.persistence.PersistenceItemInfo;
41 import org.openhab.core.persistence.PersistenceService;
42 import org.openhab.core.persistence.QueryablePersistenceService;
43 import org.openhab.core.persistence.strategy.PersistenceStrategy;
44 import org.openhab.core.types.State;
45 import org.openhab.core.types.UnDefType;
46 import org.osgi.service.component.annotations.Activate;
47 import org.osgi.service.component.annotations.Component;
48 import org.osgi.service.component.annotations.Deactivate;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import com.google.gson.Gson;
53 import com.google.gson.GsonBuilder;
54
55 /**
56  * This is the implementation of the MapDB {@link PersistenceService}. To learn more about MapDB please visit their
57  * <a href="http://www.mapdb.org/">website</a>.
58  *
59  * @author Jens Viebig - Initial contribution
60  * @author Martin Kühl - Port to 3.x
61  */
62 @NonNullByDefault
63 @Component(service = { PersistenceService.class, QueryablePersistenceService.class })
64 public class MapDbPersistenceService implements QueryablePersistenceService {
65
66     private static final String SERVICE_ID = "mapdb";
67     private static final String SERVICE_LABEL = "MapDB";
68     private static final Path DB_DIR = new File(OpenHAB.getUserDataFolder(), "persistence").toPath().resolve("mapdb");
69     private static final Path BACKUP_DIR = DB_DIR.resolve("backup");
70     private static final String DB_FILE_NAME = "storage.mapdb";
71
72     private final Logger logger = LoggerFactory.getLogger(MapDbPersistenceService.class);
73
74     private final ExecutorService threadPool = ThreadPoolManager.getPool(getClass().getSimpleName());
75
76     /**
77      * holds the local instance of the MapDB database
78      */
79
80     private @NonNullByDefault({}) DB db;
81     private @NonNullByDefault({}) Map<String, String> map;
82
83     private transient Gson mapper = new GsonBuilder().registerTypeHierarchyAdapter(State.class, new StateTypeAdapter())
84             .create();
85
86     @Activate
87     public void activate() {
88         logger.debug("MapDB persistence service is being activated");
89
90         try {
91             Files.createDirectories(DB_DIR);
92         } catch (IOException e) {
93             logger.warn("Failed to create one or more directories in the path '{}'", DB_DIR);
94             logger.warn("MapDB persistence service activation has failed.");
95             return;
96         }
97
98         File dbFile = DB_DIR.resolve(DB_FILE_NAME).toFile();
99         try {
100             db = DBMaker.newFileDB(dbFile).closeOnJvmShutdown().make();
101             map = db.createTreeMap("itemStore").makeOrGet();
102         } catch (RuntimeException re) {
103             Throwable cause = re.getCause();
104             if (cause instanceof ClassNotFoundException cnf) {
105                 logger.warn(
106                         "The MapDB in {} is incompatible with openHAB {}: {}. A new and empty MapDB will be used instead.",
107                         dbFile, OpenHAB.getVersion(), cnf.getMessage());
108
109                 try {
110                     Files.createDirectories(BACKUP_DIR);
111                 } catch (IOException ioe) {
112                     logger.warn("Failed to create one or more directories in the path '{}'", BACKUP_DIR);
113                     logger.warn("MapDB persistence service activation has failed.");
114                     return;
115                 }
116
117                 try (DirectoryStream<Path> stream = Files.newDirectoryStream(DB_DIR)) {
118                     long epochMilli = Instant.now().toEpochMilli();
119                     for (Path path : stream) {
120                         if (!Files.isDirectory(path)) {
121                             Path newPath = BACKUP_DIR.resolve(epochMilli + "--" + path.getFileName());
122                             Files.move(path, newPath);
123                             logger.info("Moved incompatible MapDB file '{}' to '{}'", path, newPath);
124                         }
125                     }
126                 } catch (IOException ioe) {
127                     logger.warn("Failed to read files from '{}': {}", DB_DIR, ioe.getMessage());
128                     logger.warn("MapDB persistence service activation has failed.");
129                     return;
130                 }
131
132                 db = DBMaker.newFileDB(dbFile).closeOnJvmShutdown().make();
133                 map = db.createTreeMap("itemStore").makeOrGet();
134             } else {
135                 logger.warn("Failed to create or open the MapDB: {}", re.getMessage());
136                 logger.warn("MapDB persistence service activation has failed.");
137             }
138         }
139         logger.debug("MapDB persistence service is now activated");
140     }
141
142     @Deactivate
143     public void deactivate() {
144         logger.debug("MapDB persistence service deactivated");
145         if (db != null) {
146             db.close();
147         }
148     }
149
150     @Override
151     public String getId() {
152         return SERVICE_ID;
153     }
154
155     @Override
156     public String getLabel(@Nullable Locale locale) {
157         return SERVICE_LABEL;
158     }
159
160     @Override
161     public Set<PersistenceItemInfo> getItemInfo() {
162         return map.values().stream().map(this::deserialize).flatMap(MapDbPersistenceService::streamOptional)
163                 .collect(Collectors.<PersistenceItemInfo> toUnmodifiableSet());
164     }
165
166     @Override
167     public void store(Item item) {
168         store(item, item.getName());
169     }
170
171     @Override
172     public void store(Item item, @Nullable String alias) {
173         if (item.getState() instanceof UnDefType) {
174             return;
175         }
176
177         // PersistenceManager passes SimpleItemConfiguration.alias which can be null
178         String localAlias = alias == null ? item.getName() : alias;
179         logger.debug("store called for {}", localAlias);
180
181         State state = item.getState();
182         MapDbItem mItem = new MapDbItem();
183         mItem.setName(localAlias);
184         mItem.setState(state);
185         mItem.setTimestamp(new Date());
186         threadPool.submit(() -> {
187             String json = serialize(mItem);
188             map.put(localAlias, json);
189             db.commit();
190             logger.debug("Stored '{}' with state '{}' as '{}' in MapDB database", localAlias, state, json);
191         });
192     }
193
194     @Override
195     public Iterable<HistoricItem> query(FilterCriteria filter) {
196         String json = map.get(filter.getItemName());
197         if (json == null) {
198             return List.of();
199         }
200         Optional<MapDbItem> item = deserialize(json);
201         return item.isPresent() ? List.of(item.get()) : List.of();
202     }
203
204     private String serialize(MapDbItem item) {
205         return mapper.toJson(item);
206     }
207
208     @SuppressWarnings("null")
209     private Optional<MapDbItem> deserialize(String json) {
210         MapDbItem item = mapper.fromJson(json, MapDbItem.class);
211         if (item == null || !item.isValid()) {
212             logger.warn("Deserialized invalid item: {}", item);
213             return Optional.empty();
214         } else if (logger.isDebugEnabled()) {
215             logger.debug("Deserialized '{}' with state '{}' from '{}'", item.getName(), item.getState(), json);
216         }
217
218         return Optional.of(item);
219     }
220
221     private static <T> Stream<T> streamOptional(Optional<T> opt) {
222         return opt.isPresent() ? Stream.of(opt.get()) : Stream.empty();
223     }
224
225     @Override
226     public List<PersistenceStrategy> getDefaultStrategies() {
227         return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE);
228     }
229 }