]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.acorn/src/org/simantics/acorn/internal/AcornDatabase.java
db83f1395d005babeb09dbd500f5034d2326f503
[simantics/platform.git] / bundles / org.simantics.acorn / src / org / simantics / acorn / internal / AcornDatabase.java
1 package org.simantics.acorn.internal;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.nio.channels.FileChannel;
6 import java.nio.channels.FileLock;
7 import java.nio.file.DirectoryStream;
8 import java.nio.file.FileAlreadyExistsException;
9 import java.nio.file.FileVisitOption;
10 import java.nio.file.FileVisitResult;
11 import java.nio.file.Files;
12 import java.nio.file.Path;
13 import java.nio.file.SimpleFileVisitor;
14 import java.nio.file.StandardOpenOption;
15 import java.nio.file.attribute.BasicFileAttributes;
16 import java.util.EnumSet;
17 import java.util.Properties;
18
19 import org.simantics.acorn.GraphClientImpl2;
20 import org.simantics.db.Database;
21 import org.simantics.db.DatabaseUserAgent;
22 import org.simantics.db.ServiceLocator;
23 import org.simantics.db.server.DatabaseStartException;
24 import org.simantics.db.server.ProCoreException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * @author Tuukka Lehtonen
30  */
31 public class AcornDatabase implements Database {
32
33     private static final Logger LOGGER = LoggerFactory.getLogger(AcornDatabase.class);
34
35     private static final String LOCK_FILE_NAME = "lock";
36
37     private final Path folder;
38     private final Path lockFile;
39
40     private GraphClientImpl2 currentClient;
41
42     private DatabaseUserAgent userAgent;
43
44     private FileChannel lockFileChannel;
45
46     private FileLock lock;
47
48     private boolean isRunning;
49
50     public AcornDatabase(Path folder) {
51         this.folder = folder;
52         this.lockFile = folder.resolve(LOCK_FILE_NAME);
53     }
54
55     @Override
56     public DatabaseUserAgent getUserAgent() {
57         return userAgent;
58     }
59
60     @Override
61     public void setUserAgent(DatabaseUserAgent dbUserAgent) {
62         userAgent = dbUserAgent;
63     }
64
65     @Override
66     public Status getStatus() {
67         return Status.Local;
68     }
69
70     @Override
71     public File getFolder() {
72         return folder.toFile();
73     }
74
75     @Override
76     public boolean isFolderOk() {
77         return isFolderOk(folder.toFile());
78     }
79
80     @Override
81     public boolean isFolderOk(File aFolder) {
82         if (!aFolder.isDirectory())
83             return false;
84         return true;
85     }
86
87     @Override
88     public boolean isFolderEmpty() {
89         return isFolderEmpty(folder.toFile());
90     }
91
92     @Override
93     public boolean isFolderEmpty(File aFolder) {
94         Path path = aFolder.toPath();
95         if (!Files.isDirectory(path))
96             return false;
97         try (DirectoryStream<Path> folderStream = Files.newDirectoryStream(path)) {
98             return !folderStream.iterator().hasNext();
99         } catch (IOException e) {
100             LOGGER.error("Failed to open folder stream. folder=" + path, e);
101             return false;
102         }
103     }
104
105     @Override
106     public void initFolder(Properties properties) throws ProCoreException {
107         try {
108             Files.createDirectories(folder);
109         } catch (IOException e) {
110             throw new ProCoreException(e);
111         }
112     }
113
114     @Override
115     public void deleteFiles() throws ProCoreException {
116         deleteTree(folder);
117     }
118
119     @Override
120     public synchronized void start() throws ProCoreException {
121         try {
122             lockFileChannel = lockFile.getFileSystem().provider().newFileChannel(lockFile,
123                     EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE));
124
125             lock = lockFileChannel.tryLock();
126             if (lock == null) {
127                 safeLoggingClose(lockFileChannel, lockFile);
128                 throw new ProCoreException("The database in folder " + folder.toAbsolutePath() + " is already in use!");
129             }
130
131             isRunning = true;
132         } catch (IOException e) {
133             LOGGER.error("Failed to start database at " + folder.toAbsolutePath(), e);
134             safeLoggingClose(lockFileChannel, lockFile);
135         }
136     }
137
138     @Override
139     public boolean isRunning() throws ProCoreException {
140         return isRunning;
141     }
142
143     @Override
144     public synchronized boolean tryToStop() throws ProCoreException {
145         if (!isRunning)
146             return false;
147         try {
148             safeLoggingClose(lock, lockFile);
149             lock = null;
150             safeLoggingClose(lockFileChannel, lockFile);
151             lockFileChannel = null;
152             Files.deleteIfExists(lockFile);
153             isRunning = false;
154         } catch (IOException e) {
155             LOGGER.error("Failed to start database at " + folder.toAbsolutePath(), e);
156         }
157         return true;
158     }
159
160     @Override
161     public void connect() throws ProCoreException {
162     }
163
164     @Override
165     public boolean isConnected() throws ProCoreException {
166         return isRunning;
167     }
168
169     @Override
170     public String execute(String command) throws ProCoreException {
171         throw new UnsupportedOperationException("execute(" + command + ")");
172     }
173
174     @Override
175     public void disconnect() throws ProCoreException {
176     }
177
178     @Override
179     public void clone(File to, int revision, boolean saveHistory) throws ProCoreException {
180         // TODO: implement
181         throw new UnsupportedOperationException();
182     }
183
184     @Override
185     public Path createFromChangeSets(int revision) throws ProCoreException {
186         // TODO: implement
187         throw new UnsupportedOperationException();
188     }
189
190     @Override
191     public void deleteGuard() throws ProCoreException {
192         // TODO: implement
193         throw new UnsupportedOperationException();
194     }
195
196     @Override
197     public Path dumpChangeSets() throws ProCoreException {
198         // TODO: implement
199         throw new UnsupportedOperationException();
200     }
201
202     @Override
203     public void purgeDatabase() throws ProCoreException {
204         if(currentClient == null) throw new IllegalStateException("No current session.");
205         currentClient.purgeDatabase();
206     }
207
208     @Override
209     public long serverGetTailChangeSetId() throws ProCoreException {
210         if(currentClient == null) throw new IllegalStateException("No current session.");
211         return currentClient.getTailChangeSetId();
212     }
213
214     @Override
215     public Session newSession(ServiceLocator locator) throws ProCoreException {
216         try {
217                 if(currentClient != null) throw new DatabaseStartException(folder.toFile(), "A session is already running. Only one session is supported.");
218                 currentClient = new GraphClientImpl2(this, folder, locator); 
219             return currentClient;
220         } catch (IOException e) {
221             throw new ProCoreException(e);
222         }
223     }
224
225     @Override
226     public Journal getJournal() throws ProCoreException {
227         // TODO: implement
228         throw new UnsupportedOperationException();
229     }
230
231     private static void deleteTree(Path path) throws ProCoreException {
232         if (!Files.exists(path))
233             return;
234
235         class Visitor extends SimpleFileVisitor<Path> {
236             @Override
237             public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
238                 try {
239                     Files.delete(file);
240                 } catch (IOException ioe) {
241                     ioe.printStackTrace();
242                     throw ioe;
243                 }
244                 return FileVisitResult.CONTINUE;
245             }
246             @Override
247             public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
248                 if (e == null) {
249                     try {
250                         Files.delete(dir);
251                     } catch (IOException ioe) {
252                         ioe.printStackTrace();
253                         throw ioe;
254                     }
255                     return FileVisitResult.CONTINUE;
256                 }
257                 throw e;
258             }
259         }
260         try {
261             Visitor v = new Visitor();
262             EnumSet<FileVisitOption> opts = EnumSet.noneOf(FileVisitOption.class);
263             Files.walkFileTree(path, opts, Integer.MAX_VALUE, v);
264         } catch (IOException e) {
265             throw new ProCoreException("Could not delete " + path, e);
266         }
267     }
268
269         @Override
270         public String getCompression() {
271                 return "LZ4";
272         }
273
274     private static void safeLoggingClose(AutoCloseable closeable, Path file) {
275         if (closeable == null)
276             return;
277         try (AutoCloseable c = closeable) {
278         } catch (Exception e) {
279             LOGGER.error("Failed to close " + closeable.getClass() + " of " + file.toAbsolutePath());
280         }
281     }
282
283 }