1 package org.apache.lucene.index;
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.ArrayList;
27 import java.util.Map.Entry;
28 import java.io.IOException;
30 import org.apache.lucene.store.Directory;
33 * An {@link IndexDeletionPolicy} that wraps around any other
34 * {@link IndexDeletionPolicy} and adds the ability to hold and later release
35 * snapshots of an index. While a snapshot is held, the {@link IndexWriter} will
36 * not remove any files associated with it even if the index is otherwise being
37 * actively, arbitrarily changed. Because we wrap another arbitrary
38 * {@link IndexDeletionPolicy}, this gives you the freedom to continue using
39 * whatever {@link IndexDeletionPolicy} you would normally want to use with your
43 * This class maintains all snapshots in-memory, and so the information is not
44 * persisted and not protected against system failures. If persistency is
45 * important, you can use {@link PersistentSnapshotDeletionPolicy} (or your own
46 * extension) and when creating a new instance of this deletion policy, pass the
47 * persistent snapshots information to
48 * {@link #SnapshotDeletionPolicy(IndexDeletionPolicy, Map)}.
50 * @lucene.experimental
52 public class SnapshotDeletionPolicy implements IndexDeletionPolicy {
54 /** Holds a Snapshot's information. */
55 private static class SnapshotInfo {
57 String segmentsFileName;
60 public SnapshotInfo(String id, String segmentsFileName, IndexCommit commit) {
62 this.segmentsFileName = segmentsFileName;
67 public String toString() {
68 return id + " : " + segmentsFileName;
72 protected class SnapshotCommitPoint extends IndexCommit {
73 protected IndexCommit cp;
75 protected SnapshotCommitPoint(IndexCommit cp) {
80 public String toString() {
81 return "SnapshotDeletionPolicy.SnapshotCommitPoint(" + cp + ")";
85 * Returns true if this segment can be deleted. The default implementation
86 * returns false if this segment is currently held as snapshot.
88 protected boolean shouldDelete(String segmentsFileName) {
89 return !segmentsFileToIDs.containsKey(segmentsFileName);
93 public void delete() {
94 synchronized (SnapshotDeletionPolicy.this) {
95 // Suppress the delete request if this commit point is
96 // currently snapshotted.
97 if (shouldDelete(getSegmentsFileName())) {
104 public Directory getDirectory() {
105 return cp.getDirectory();
109 public Collection<String> getFileNames() throws IOException {
110 return cp.getFileNames();
114 public long getGeneration() {
115 return cp.getGeneration();
119 public String getSegmentsFileName() {
120 return cp.getSegmentsFileName();
124 public Map<String, String> getUserData() throws IOException {
125 return cp.getUserData();
129 public long getVersion() {
130 return cp.getVersion();
134 public boolean isDeleted() {
135 return cp.isDeleted();
139 public int getSegmentCount() {
140 return cp.getSegmentCount();
144 /** Snapshots info */
145 private Map<String, SnapshotInfo> idToSnapshot = new HashMap<String, SnapshotInfo>();
147 // multiple IDs could point to the same commit point (segments file name)
148 private Map<String, Set<String>> segmentsFileToIDs = new HashMap<String, Set<String>>();
150 private IndexDeletionPolicy primary;
151 protected IndexCommit lastCommit;
153 public SnapshotDeletionPolicy(IndexDeletionPolicy primary) {
154 this.primary = primary;
158 * {@link SnapshotDeletionPolicy} wraps another {@link IndexDeletionPolicy} to
159 * enable flexible snapshotting.
162 * the {@link IndexDeletionPolicy} that is used on non-snapshotted
163 * commits. Snapshotted commits, are not deleted until explicitly
164 * released via {@link #release(String)}
165 * @param snapshotsInfo
166 * A mapping of snapshot ID to the segments filename that is being
167 * snapshotted. The expected input would be the output of
168 * {@link #getSnapshots()}. A null value signals that there are no
169 * initial snapshots to maintain.
171 public SnapshotDeletionPolicy(IndexDeletionPolicy primary,
172 Map<String, String> snapshotsInfo) {
175 if (snapshotsInfo != null) {
176 // Add the ID->segmentIDs here - the actual IndexCommits will be
177 // reconciled on the call to onInit()
178 for (Entry<String, String> e : snapshotsInfo.entrySet()) {
179 registerSnapshotInfo(e.getKey(), e.getValue(), null);
185 * Checks if the given id is already used by another snapshot, and throws
186 * {@link IllegalStateException} if it is.
188 protected void checkSnapshotted(String id) {
189 if (isSnapshotted(id)) {
190 throw new IllegalStateException("Snapshot ID " + id
191 + " is already used - must be unique");
195 /** Registers the given snapshot information. */
196 protected void registerSnapshotInfo(String id, String segment, IndexCommit commit) {
197 idToSnapshot.put(id, new SnapshotInfo(id, segment, commit));
198 Set<String> ids = segmentsFileToIDs.get(segment);
200 ids = new HashSet<String>();
201 segmentsFileToIDs.put(segment, ids);
206 protected List<IndexCommit> wrapCommits(List<? extends IndexCommit> commits) {
207 List<IndexCommit> wrappedCommits = new ArrayList<IndexCommit>(commits.size());
208 for (IndexCommit ic : commits) {
209 wrappedCommits.add(new SnapshotCommitPoint(ic));
211 return wrappedCommits;
215 * Get a snapshotted IndexCommit by ID. The IndexCommit can then be used to
216 * open an IndexReader on a specific commit point, or rollback the index by
217 * opening an IndexWriter with the IndexCommit specified in its
218 * {@link IndexWriterConfig}.
221 * a unique identifier of the commit that was snapshotted.
222 * @throws IllegalStateException
223 * if no snapshot exists by the specified ID.
224 * @return The {@link IndexCommit} for this particular snapshot.
226 public synchronized IndexCommit getSnapshot(String id) {
227 SnapshotInfo snapshotInfo = idToSnapshot.get(id);
228 if (snapshotInfo == null) {
229 throw new IllegalStateException("No snapshot exists by ID: " + id);
231 return snapshotInfo.commit;
235 * Get all the snapshots in a map of snapshot IDs to the segments they
236 * 'cover.' This can be passed to
237 * {@link #SnapshotDeletionPolicy(IndexDeletionPolicy, Map)} in order to
238 * initialize snapshots at construction.
240 public synchronized Map<String, String> getSnapshots() {
241 Map<String, String> snapshots = new HashMap<String, String>();
242 for (Entry<String, SnapshotInfo> e : idToSnapshot.entrySet()) {
243 snapshots.put(e.getKey(), e.getValue().segmentsFileName);
249 * Returns true if the given ID is already used by a snapshot. You can call
250 * this method before {@link #snapshot(String)} if you are not sure whether
251 * the ID is already used or not.
253 public boolean isSnapshotted(String id) {
254 return idToSnapshot.containsKey(id);
257 public synchronized void onCommit(List<? extends IndexCommit> commits)
259 primary.onCommit(wrapCommits(commits));
260 lastCommit = commits.get(commits.size() - 1);
263 public synchronized void onInit(List<? extends IndexCommit> commits)
265 primary.onInit(wrapCommits(commits));
266 lastCommit = commits.get(commits.size() - 1);
269 * Assign snapshotted IndexCommits to their correct snapshot IDs as
270 * specified in the constructor.
272 for (IndexCommit commit : commits) {
273 Set<String> ids = segmentsFileToIDs.get(commit.getSegmentsFileName());
275 for (String id : ids) {
276 idToSnapshot.get(id).commit = commit;
282 * Second, see if there are any instances where a snapshot ID was specified
283 * in the constructor but an IndexCommit doesn't exist. In this case, the ID
286 * Note: This code is protective for extreme cases where IDs point to
287 * non-existent segments. As the constructor should have received its
288 * information via a call to getSnapshots(), the data should be well-formed.
290 // Find lost snapshots
291 ArrayList<String> idsToRemove = null;
292 for (Entry<String, SnapshotInfo> e : idToSnapshot.entrySet()) {
293 if (e.getValue().commit == null) {
294 if (idsToRemove == null) {
295 idsToRemove = new ArrayList<String>();
297 idsToRemove.add(e.getKey());
300 // Finally, remove those 'lost' snapshots.
301 if (idsToRemove != null) {
302 for (String id : idsToRemove) {
303 SnapshotInfo info = idToSnapshot.remove(id);
304 segmentsFileToIDs.remove(info.segmentsFileName);
310 * Release a snapshotted commit by ID.
313 * a unique identifier of the commit that is un-snapshotted.
314 * @throws IllegalStateException
315 * if no snapshot exists by this ID.
317 public synchronized void release(String id) throws IOException {
318 SnapshotInfo info = idToSnapshot.remove(id);
320 throw new IllegalStateException("Snapshot doesn't exist: " + id);
322 Set<String> ids = segmentsFileToIDs.get(info.segmentsFileName);
325 if (ids.size() == 0) {
326 segmentsFileToIDs.remove(info.segmentsFileName);
332 * Snapshots the last commit. Once a commit is 'snapshotted,' it is protected
333 * from deletion (as long as this {@link IndexDeletionPolicy} is used). The
334 * commit can be removed by calling {@link #release(String)} using the same ID
335 * parameter followed by a call to {@link IndexWriter#deleteUnusedFiles()}.
337 * <b>NOTE:</b> ID must be unique in the system. If the same ID is used twice,
338 * an {@link IllegalStateException} is thrown.
340 * <b>NOTE:</b> while the snapshot is held, the files it references will not
341 * be deleted, which will consume additional disk space in your index. If you
342 * take a snapshot at a particularly bad time (say just before you call
343 * forceMerge) then in the worst case this could consume an extra 1X of your
344 * total index size, until you release the snapshot.
347 * a unique identifier of the commit that is being snapshotted.
348 * @throws IllegalStateException
349 * if either there is no 'last commit' to snapshot, or if the
350 * parameter 'ID' refers to an already snapshotted commit.
351 * @return the {@link IndexCommit} that was snapshotted.
353 public synchronized IndexCommit snapshot(String id) throws IOException {
354 if (lastCommit == null) {
355 // no commit exists. Really shouldn't happen, but might be if SDP is
356 // accessed before onInit or onCommit were called.
357 throw new IllegalStateException("No index commit to snapshot");
360 // Can't use the same snapshot ID twice...
361 checkSnapshotted(id);
363 registerSnapshotInfo(id, lastCommit.getSegmentsFileName(), lastCommit);