2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.config.persist.storage.file;
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.osgi.framework.BundleContext;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.xml.sax.SAXException;
24 import javax.xml.parsers.ParserConfigurationException;
26 import java.io.IOException;
27 import java.nio.charset.Charset;
31 * StorageAdapter that stores configuration in a plan file.
33 public class FileStorageAdapter implements StorageAdapter {
34 private static final Logger logger = LoggerFactory.getLogger(FileStorageAdapter.class);
36 // TODO prefix properties
38 private static final Charset ENCODING = Charsets.UTF_8;
40 public static final String FILE_STORAGE_PROP = "fileStorage";
41 public static final String NUMBER_OF_BACKUPS = "numberOfBackups";
43 private static final String SEPARATOR_E_PURE = "//END OF CONFIG";
44 private static final String SEPARATOR_E = newLine(SEPARATOR_E_PURE);
46 private static final String SEPARATOR_M_PURE = "//END OF SNAPSHOT";
47 private static final String SEPARATOR_M = newLine(SEPARATOR_M_PURE);
49 private static final String SEPARATOR_S = newLine("//START OF CONFIG");
51 private static final String SEPARATOR_SL_PURE = "//START OF CONFIG-LAST";
52 private static final String SEPARATOR_SL = newLine(SEPARATOR_SL_PURE);
54 private static Integer numberOfStoredBackups;
58 public void setProperties(BundleContext bundleContext) {
59 File storage = extractStorageFileFromProperties(bundleContext);
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);
67 if (storage.exists() == false) {
68 logger.debug("Storage file does not exist, creating empty file");
70 boolean result = storage.createNewFile();
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);
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.");
81 setFileStorage(storage);
86 void setFileStorage(File storage) {
87 this.storage = storage;
91 void setNumberOfBackups(Integer numberOfBackups) {
92 numberOfStoredBackups = numberOfBackups;
95 private static File extractStorageFileFromProperties(BundleContext bundleContext) {
96 String fileStorageProperty = bundleContext.getProperty(FILE_STORAGE_PROP);
97 Preconditions.checkNotNull(fileStorageProperty, "Unable to find " + FILE_STORAGE_PROP
98 + " in received context :" + bundleContext);
99 File result = new File(fileStorageProperty);
100 String numberOfBAckupsAsString = bundleContext.getProperty(NUMBER_OF_BACKUPS);
101 if (numberOfBAckupsAsString != null) {
102 numberOfStoredBackups = Integer.valueOf(numberOfBAckupsAsString);
104 numberOfStoredBackups = Integer.MAX_VALUE;
110 private static String newLine(String string) {
111 return string + "\n";
115 public void persistConfig(ConfigSnapshotHolder holder) throws IOException {
116 Preconditions.checkNotNull(storage, "Storage file is null");
118 String content = Files.toString(storage, ENCODING);
119 if (numberOfStoredBackups == Integer.MAX_VALUE) {
120 resetLastConfig(content);
121 persistLastConfig(holder);
123 if (numberOfStoredBackups == 1) {
124 Files.write("", storage, ENCODING);
125 persistLastConfig(holder);
127 int count = StringUtils.countMatches(content, SEPARATOR_S);
128 if ((count + 1) < numberOfStoredBackups) {
129 resetLastConfig(content);
130 persistLastConfig(holder);
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);
142 private void resetLastConfig(String content) throws IOException {
143 content = content.replaceFirst(SEPARATOR_SL, SEPARATOR_S);
144 Files.write(content, storage, ENCODING);
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);
156 private CharSequence toStringCaps(Set<String> capabilities) {
157 StringBuilder b = new StringBuilder();
158 for (String capability : capabilities) {
159 b.append(newLine(capability));
165 public Optional<ConfigSnapshotHolder> loadLastConfig() throws IOException {
166 Preconditions.checkNotNull(storage, "Storage file is null");
168 if (!storage.exists()) {
169 return Optional.absent();
172 final LineProcessor lineProcessor = new LineProcessor();
173 String result = Files.readLines(storage, ENCODING, lineProcessor);
176 if (lineProcessor.getConfigSnapshot().isPresent() == false) {
177 return Optional.absent();
179 return Optional.<ConfigSnapshotHolder> of(new PersistedConfigImpl(lineProcessor.getConfigSnapshot(),
180 lineProcessor.getCapabilities()));
183 } catch (ParserConfigurationException | SAXException e) {
184 throw new IOException("Unable to load last config ", e);
188 private static final class LineProcessor implements com.google.common.io.LineProcessor<String> {
190 private boolean inLastConfig, inLastSnapshot;
191 private final StringBuffer snapshotBuffer = new StringBuffer();
192 private final Set<String> caps = Sets.newHashSet();
195 public String getResult() {
200 public boolean processLine(String line) throws IOException {
201 if (inLastConfig && line.equals(SEPARATOR_E_PURE)) {
202 inLastConfig = false;
206 if (inLastConfig && line.equals(SEPARATOR_M_PURE)) {
207 inLastSnapshot = false;
212 if (inLastSnapshot) {
213 snapshotBuffer.append(line);
214 snapshotBuffer.append(System.lineSeparator());
220 if (line.equals(SEPARATOR_SL_PURE)) {
222 inLastSnapshot = true;
228 Optional<String> getConfigSnapshot() throws IOException, SAXException, ParserConfigurationException {
229 final String xmlContent = snapshotBuffer.toString();
230 if (xmlContent == null || xmlContent.equals("")) {
231 return Optional.absent();
233 return Optional.of(xmlContent);
236 Set<String> getCapabilities() throws IOException, SAXException, ParserConfigurationException {
243 public void close() throws IOException {
248 public String toString() {
249 return "FileStorageAdapter [storage=" + storage + "]";
252 private class PersistedConfigImpl implements ConfigSnapshotHolder {
254 private final String snapshot;
255 private final Set<String> caps;
257 public PersistedConfigImpl(Optional<String> configSnapshot, Set<String> capabilities) {
258 this.snapshot = configSnapshot.get();
259 this.caps = capabilities;
263 public String getConfigSnapshot() {
268 public Set<String> getCapabilities() {