View Javadoc
1   /*
2    * Copyright (C) 2017 Two Sigma Open Source
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.internal.storage.file;
45  
46  import static org.eclipse.jgit.lib.Constants.CHARSET;
47  
48  import java.io.BufferedReader;
49  import java.io.File;
50  import java.io.IOException;
51  import java.nio.file.Files;
52  import java.nio.file.NoSuchFileException;
53  import java.nio.file.attribute.FileTime;
54  import java.text.MessageFormat;
55  import java.text.ParseException;
56  import java.time.Instant;
57  
58  import org.eclipse.jgit.api.errors.JGitInternalException;
59  import org.eclipse.jgit.internal.JGitText;
60  import org.eclipse.jgit.lib.ConfigConstants;
61  import org.eclipse.jgit.util.FileUtils;
62  import org.eclipse.jgit.util.GitDateParser;
63  import org.eclipse.jgit.util.SystemReader;
64  
65  /**
66   * This class manages the gc.log file for a {@link FileRepository}.
67   */
68  class GcLog {
69  	private final FileRepository repo;
70  
71  	private final File logFile;
72  
73  	private final LockFile lock;
74  
75  	private Instant gcLogExpire;
76  
77  	private static final String LOG_EXPIRY_DEFAULT = "1.day.ago"; //$NON-NLS-1$
78  
79  	private boolean nonEmpty = false;
80  
81  	/**
82  	 * Construct a GcLog object for a {@link FileRepository}
83  	 *
84  	 * @param repo
85  	 *            the repository
86  	 */
87  	GcLog(FileRepository repo) {
88  		this.repo = repo;
89  		logFile = new File(repo.getDirectory(), "gc.log"); //$NON-NLS-1$
90  		lock = new LockFile(logFile);
91  	}
92  
93  	private Instant getLogExpiry() throws ParseException {
94  		if (gcLogExpire == null) {
95  			String logExpiryStr = repo.getConfig().getString(
96  					ConfigConstants.CONFIG_GC_SECTION, null,
97  					ConfigConstants.CONFIG_KEY_LOGEXPIRY);
98  			if (logExpiryStr == null) {
99  				logExpiryStr = LOG_EXPIRY_DEFAULT;
100 			}
101 			gcLogExpire = GitDateParser.parse(logExpiryStr, null,
102 					SystemReader.getInstance().getLocale()).toInstant();
103 		}
104 		return gcLogExpire;
105 	}
106 
107 	private boolean autoGcBlockedByOldLockFile(boolean background) {
108 		try {
109 			FileTime lastModified = Files.getLastModifiedTime(FileUtils.toPath(logFile));
110 			if (lastModified.toInstant().compareTo(getLogExpiry()) > 0) {
111 				// There is an existing log file, which is too recent to ignore
112 				if (!background) {
113 					try (BufferedReader reader = Files
114 							.newBufferedReader(FileUtils.toPath(logFile))) {
115 						char[] buf = new char[1000];
116 						int len = reader.read(buf, 0, 1000);
117 						String oldError = new String(buf, 0, len);
118 
119 						throw new JGitInternalException(MessageFormat.format(
120 								JGitText.get().gcLogExists, oldError, logFile));
121 					}
122 				}
123 				return true;
124 			}
125 		} catch (NoSuchFileException e) {
126 			// No existing log file, OK.
127 		} catch (IOException | ParseException e) {
128 			throw new JGitInternalException(e.getMessage(), e);
129 		}
130 		return false;
131 	}
132 
133 	/**
134 	 * Lock the GC log file for updates
135 	 *
136 	 * @param background
137 	 *            If true, and if gc.log already exists, unlock and return false
138 	 * @return {@code true} if we hold the lock
139 	 */
140 	boolean lock(boolean background) {
141 		try {
142 			if (!lock.lock()) {
143 				return false;
144 			}
145 		} catch (IOException e) {
146 			throw new JGitInternalException(e.getMessage(), e);
147 		}
148 		if (autoGcBlockedByOldLockFile(background)) {
149 			lock.unlock();
150 			return false;
151 		}
152 		return true;
153 	}
154 
155 	/**
156 	 * Unlock (roll back) the GC log lock
157 	 */
158 	void unlock() {
159 		lock.unlock();
160 	}
161 
162 	/**
163 	 * Commit changes to the gc log, if there have been any writes. Otherwise,
164 	 * just unlock and delete the existing file (if any)
165 	 *
166 	 * @return true if committing (or unlocking/deleting) succeeds.
167 	 */
168 	boolean commit() {
169 		if (nonEmpty) {
170 			return lock.commit();
171 		} else {
172 			logFile.delete();
173 			lock.unlock();
174 			return true;
175 		}
176 	}
177 
178 	/**
179 	 * Write to the pending gc log. Content will be committed upon a call to
180 	 * commit()
181 	 *
182 	 * @param content
183 	 *            The content to write
184 	 * @throws IOException
185 	 */
186 	void write(String content) throws IOException {
187 		if (content.length() > 0) {
188 			nonEmpty = true;
189 		}
190 		lock.write(content.getBytes(CHARSET));
191 	}
192 }