a866743b0dee6b2e11e3b85529e1b54bb1073bd5
[controller.git] / opendaylight / config / config-persister-file-adapter / src / main / java / org / opendaylight / controller / config / persist / storage / file / FileStorageAdapter.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.config.persist.storage.file;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Charsets;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Sets;
16 import com.google.common.io.Files;
17 import org.apache.commons.lang3.StringUtils;
18 import org.opendaylight.controller.config.persist.api.storage.StorageAdapter;
19 import org.opendaylight.controller.config.stat.ConfigProvider;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.xml.sax.SAXException;
23
24 import javax.xml.parsers.ParserConfigurationException;
25 import java.io.File;
26 import java.io.IOException;
27 import java.nio.charset.Charset;
28 import java.util.Set;
29
30 /**
31  * StorageAdapter that stores configuration in a plan file.
32  */
33 public class FileStorageAdapter implements StorageAdapter {
34     private static final Logger logger = LoggerFactory.getLogger(FileStorageAdapter.class);
35
36     // TODO prefix properties
37
38     private static final Charset ENCODING = Charsets.UTF_8;
39
40     public static final String FILE_STORAGE_PROP = "fileStorage";
41     public static final String NUMBER_OF_BACKUPS = "numberOfBackups";
42
43     private static final String SEPARATOR_E_PURE = "//END OF CONFIG";
44     private static final String SEPARATOR_E = newLine(SEPARATOR_E_PURE);
45
46     private static final String SEPARATOR_M_PURE = "//END OF SNAPSHOT";
47     private static final String SEPARATOR_M = newLine(SEPARATOR_M_PURE);
48
49     private static final String SEPARATOR_S = newLine("//START OF CONFIG");
50
51     private static final String SEPARATOR_SL_PURE = "//START OF CONFIG-LAST";
52     private static final String SEPARATOR_SL = newLine(SEPARATOR_SL_PURE);
53
54     private static Integer numberOfStoredBackups;
55     private File storage;
56
57     @Override
58     public void setProperties(ConfigProvider configProvider) {
59         File storage = extractStorageFileFromProperties(configProvider);
60         logger.debug("Using file {}", storage.getAbsolutePath());
61         // Create file if it does not exist
62         File parentFile = storage.getAbsoluteFile().getParentFile();
63         if (parentFile.exists() == false) {
64             logger.debug("Creating parent folders {}", parentFile);
65             parentFile.mkdirs();
66         }
67         if (storage.exists() == false) {
68             logger.debug("Storage file does not exist, creating empty file");
69             try {
70                 boolean result = storage.createNewFile();
71                 if (result == false)
72                     throw new RuntimeException("Unable to create storage file " + storage);
73             } catch (IOException e) {
74                 throw new RuntimeException("Unable to create storage file " + storage, e);
75             }
76         }
77         if (numberOfStoredBackups == 0) {
78             throw new RuntimeException(NUMBER_OF_BACKUPS
79                     + " property should be either set to positive value, or ommited. Can not be set to 0.");
80         }
81         setFileStorage(storage);
82
83     }
84
85     @VisibleForTesting
86     void setFileStorage(File storage) {
87         this.storage = storage;
88     }
89
90     @VisibleForTesting
91     void setNumberOfBackups(Integer numberOfBackups) {
92         numberOfStoredBackups = numberOfBackups;
93     }
94
95     private static File extractStorageFileFromProperties(ConfigProvider configProvider) {
96         String fileStorageProperty = configProvider.getProperty(FILE_STORAGE_PROP);
97         Preconditions.checkNotNull(fileStorageProperty, "Unable to find " + FILE_STORAGE_PROP
98                 + " in received properties :" + configProvider);
99         File result = new File(fileStorageProperty);
100         String numberOfBAckupsAsString = configProvider.getProperty(NUMBER_OF_BACKUPS);
101         if (numberOfBAckupsAsString != null) {
102             numberOfStoredBackups = Integer.valueOf(numberOfBAckupsAsString);
103         } else {
104             numberOfStoredBackups = Integer.MAX_VALUE;
105         }
106
107         return result;
108     }
109
110     private static String newLine(String string) {
111         return string + "\n";
112     }
113
114     @Override
115     public void persistConfig(ConfigSnapshotHolder holder) throws IOException {
116         Preconditions.checkNotNull(storage, "Storage file is null");
117
118         String content = Files.toString(storage, ENCODING);
119         if (numberOfStoredBackups == Integer.MAX_VALUE) {
120             resetLastConfig(content);
121             persistLastConfig(holder);
122         } else {
123             if (numberOfStoredBackups == 1) {
124                 Files.write("", storage, ENCODING);
125                 persistLastConfig(holder);
126             } else {
127                 int count = StringUtils.countMatches(content, SEPARATOR_S);
128                 if ((count + 1) < numberOfStoredBackups) {
129                     resetLastConfig(content);
130                     persistLastConfig(holder);
131                 } else {
132                     String contentSubString = StringUtils.substringBefore(content, SEPARATOR_E);
133                     contentSubString = contentSubString.concat(SEPARATOR_E_PURE);
134                     content = StringUtils.substringAfter(content, contentSubString);
135                     resetLastConfig(content);
136                     persistLastConfig(holder);
137                 }
138             }
139         }
140     }
141
142     private void resetLastConfig(String content) throws IOException {
143         content = content.replaceFirst(SEPARATOR_SL, SEPARATOR_S);
144         Files.write(content, storage, ENCODING);
145     }
146
147     private void persistLastConfig(ConfigSnapshotHolder holder) throws IOException {
148         Files.append(SEPARATOR_SL, storage, ENCODING);
149         String snapshotAsString = holder.getConfigSnapshot();
150         Files.append(newLine(snapshotAsString), storage, ENCODING);
151         Files.append(SEPARATOR_M, storage, ENCODING);
152         Files.append(toStringCaps(holder.getCapabilities()), storage, ENCODING);
153         Files.append(SEPARATOR_E, storage, ENCODING);
154     }
155
156     private CharSequence toStringCaps(Set<String> capabilities) {
157         StringBuilder b = new StringBuilder();
158         for (String capability : capabilities) {
159             b.append(newLine(capability));
160         }
161         return b.toString();
162     }
163
164     @Override
165     public Optional<ConfigSnapshotHolder> loadLastConfig() throws IOException {
166         Preconditions.checkNotNull(storage, "Storage file is null");
167
168         if (!storage.exists()) {
169             return Optional.absent();
170         }
171
172         final LineProcessor lineProcessor = new LineProcessor();
173         String result = Files.readLines(storage, ENCODING, lineProcessor);
174
175         try {
176             if (lineProcessor.getConfigSnapshot().isPresent() == false) {
177                 return Optional.absent();
178             } else {
179                 return Optional.<ConfigSnapshotHolder> of(new PersistedConfigImpl(lineProcessor.getConfigSnapshot(),
180                         lineProcessor.getCapabilities()));
181             }
182
183         } catch (ParserConfigurationException | SAXException e) {
184             throw new IOException("Unable to load last config ", e);
185         }
186     }
187
188     private static final class LineProcessor implements com.google.common.io.LineProcessor<String> {
189
190         private boolean inLastConfig, inLastSnapshot;
191         private final StringBuffer snapshotBuffer = new StringBuffer();
192         private final Set<String> caps = Sets.newHashSet();
193
194         @Override
195         public String getResult() {
196             return null;
197         }
198
199         @Override
200         public boolean processLine(String line) throws IOException {
201             if (inLastConfig && line.equals(SEPARATOR_E_PURE)) {
202                 inLastConfig = false;
203                 return false;
204             }
205
206             if (inLastConfig && line.equals(SEPARATOR_M_PURE)) {
207                 inLastSnapshot = false;
208                 return true;
209             }
210
211             if (inLastConfig) {
212                 if (inLastSnapshot) {
213                     snapshotBuffer.append(line);
214                     snapshotBuffer.append(System.lineSeparator());
215                 } else {
216                     caps.add(line);
217                 }
218             }
219
220             if (line.equals(SEPARATOR_SL_PURE)) {
221                 inLastConfig = true;
222                 inLastSnapshot = true;
223             }
224
225             return true;
226         }
227
228         Optional<String> getConfigSnapshot() throws IOException, SAXException, ParserConfigurationException {
229             final String xmlContent = snapshotBuffer.toString();
230             if (xmlContent == null || xmlContent.equals("")) {
231                 return Optional.absent();
232             } else
233                 return Optional.of(xmlContent);
234         }
235
236         Set<String> getCapabilities() throws IOException, SAXException, ParserConfigurationException {
237             return caps;
238         }
239
240     }
241
242     @Override
243     public void close() throws IOException {
244
245     }
246
247     @Override
248     public String toString() {
249         return "FileStorageAdapter [storage=" + storage + "]";
250     }
251
252     private class PersistedConfigImpl implements ConfigSnapshotHolder {
253
254         private final String snapshot;
255         private final Set<String> caps;
256
257         public PersistedConfigImpl(Optional<String> configSnapshot, Set<String> capabilities) {
258             this.snapshot = configSnapshot.get();
259             this.caps = capabilities;
260         }
261
262         @Override
263         public String getConfigSnapshot() {
264             return snapshot;
265         }
266
267         @Override
268         public Set<String> getCapabilities() {
269             return caps;
270         }
271     }
272
273 }