View Javadoc
1   /*
2    * Copyright (C) 2017, Google Inc.
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.dfs;
45  
46  import java.io.EOFException;
47  import java.io.IOException;
48  import java.nio.ByteBuffer;
49  import java.text.MessageFormat;
50  
51  import org.eclipse.jgit.errors.PackInvalidException;
52  import org.eclipse.jgit.internal.storage.pack.PackExt;
53  
54  /** Block based file stored in {@link DfsBlockCache}. */
55  abstract class BlockBasedFile {
56  	/** Cache that owns this file and its data. */
57  	final DfsBlockCache cache;
58  
59  	/** Unique identity of this file while in-memory. */
60  	final DfsStreamKey key;
61  
62  	/** Description of the associated pack file's storage. */
63  	final DfsPackDescription desc;
64  	final PackExt ext;
65  
66  	/**
67  	 * Preferred alignment for loading blocks from the backing file.
68  	 * <p>
69  	 * It is initialized to 0 and filled in on the first read made from the
70  	 * file. Block sizes may be odd, e.g. 4091, caused by the underling DFS
71  	 * storing 4091 user bytes and 5 bytes block metadata into a lower level
72  	 * 4096 byte block on disk.
73  	 */
74  	volatile int blockSize;
75  
76  	/**
77  	 * Total number of bytes in this pack file.
78  	 * <p>
79  	 * This field initializes to -1 and gets populated when a block is loaded.
80  	 */
81  	volatile long length;
82  
83  	/** True once corruption has been detected that cannot be worked around. */
84  	volatile boolean invalid;
85  
86  	BlockBasedFile(DfsBlockCache cache, DfsPackDescription desc, PackExt ext) {
87  		this.cache = cache;
88  		this.key = desc.getStreamKey(ext);
89  		this.desc = desc;
90  		this.ext = ext;
91  	}
92  
93  	String getFileName() {
94  		return desc.getFileName(ext);
95  	}
96  
97  	boolean invalid() {
98  		return invalid;
99  	}
100 
101 	void setInvalid() {
102 		invalid = true;
103 	}
104 
105 	void setBlockSize(int newSize) {
106 		blockSize = newSize;
107 	}
108 
109 	long alignToBlock(long pos) {
110 		int size = blockSize;
111 		if (size == 0)
112 			size = cache.getBlockSize();
113 		return (pos / size) * size;
114 	}
115 
116 	int blockSize(ReadableChannel rc) {
117 		// If the block alignment is not yet known, discover it. Prefer the
118 		// larger size from either the cache or the file itself.
119 		int size = blockSize;
120 		if (size == 0) {
121 			size = rc.blockSize();
122 			if (size <= 0)
123 				size = cache.getBlockSize();
124 			else if (size < cache.getBlockSize())
125 				size = (cache.getBlockSize() / size) * size;
126 			blockSize = size;
127 		}
128 		return size;
129 	}
130 
131 	DfsBlock getOrLoadBlock(long pos, DfsReader ctx) throws IOException {
132 		try (LazyChannel c = new LazyChannel(ctx, desc, ext)) {
133 			return cache.getOrLoad(this, pos, ctx, c);
134 		}
135 	}
136 
137 	DfsBlock readOneBlock(long pos, DfsReader ctx, ReadableChannel rc)
138 			throws IOException {
139 		if (invalid)
140 			throw new PackInvalidException(getFileName());
141 
142 		ctx.stats.readBlock++;
143 		long start = System.nanoTime();
144 		try {
145 			int size = blockSize(rc);
146 			pos = (pos / size) * size;
147 
148 			// If the size of the file is not yet known, try to discover it.
149 			// Channels may choose to return -1 to indicate they don't
150 			// know the length yet, in this case read up to the size unit
151 			// given by the caller, then recheck the length.
152 			long len = length;
153 			if (len < 0) {
154 				len = rc.size();
155 				if (0 <= len)
156 					length = len;
157 			}
158 
159 			if (0 <= len && len < pos + size)
160 				size = (int) (len - pos);
161 			if (size <= 0)
162 				throw new EOFException(MessageFormat.format(
163 						DfsText.get().shortReadOfBlock, Long.valueOf(pos),
164 						getFileName(), Long.valueOf(0), Long.valueOf(0)));
165 
166 			byte[] buf = new byte[size];
167 			rc.position(pos);
168 			int cnt = read(rc, ByteBuffer.wrap(buf, 0, size));
169 			ctx.stats.readBlockBytes += cnt;
170 			if (cnt != size) {
171 				if (0 <= len) {
172 					throw new EOFException(MessageFormat.format(
173 							DfsText.get().shortReadOfBlock, Long.valueOf(pos),
174 							getFileName(), Integer.valueOf(size),
175 							Integer.valueOf(cnt)));
176 				}
177 
178 				// Assume the entire thing was read in a single shot, compact
179 				// the buffer to only the space required.
180 				byte[] n = new byte[cnt];
181 				System.arraycopy(buf, 0, n, 0, n.length);
182 				buf = n;
183 			} else if (len < 0) {
184 				// With no length at the start of the read, the channel should
185 				// have the length available at the end.
186 				length = len = rc.size();
187 			}
188 
189 			return new DfsBlock(key, pos, buf);
190 		} finally {
191 			ctx.stats.readBlockMicros += elapsedMicros(start);
192 		}
193 	}
194 
195 	static int read(ReadableChannel rc, ByteBuffer buf) throws IOException {
196 		int n;
197 		do {
198 			n = rc.read(buf);
199 		} while (0 < n && buf.hasRemaining());
200 		return buf.position();
201 	}
202 
203 	static long elapsedMicros(long start) {
204 		return (System.nanoTime() - start) / 1000L;
205 	}
206 
207 	/**
208 	 * A supplier of readable channel that opens the channel lazily.
209 	 */
210 	private static class LazyChannel
211 			implements AutoCloseable, DfsBlockCache.ReadableChannelSupplier {
212 		private final DfsReader ctx;
213 		private final DfsPackDescription desc;
214 		private final PackExt ext;
215 
216 		private ReadableChannel rc;
217 
218 		LazyChannel(DfsReader ctx, DfsPackDescription desc, PackExt ext) {
219 			this.ctx = ctx;
220 			this.desc = desc;
221 			this.ext = ext;
222 		}
223 
224 		@Override
225 		public ReadableChannel get() throws IOException {
226 			if (rc == null) {
227 				rc = ctx.db.openFile(desc, ext);
228 			}
229 			return rc;
230 		}
231 
232 		@Override
233 		public void close() throws IOException {
234 			if (rc != null) {
235 				rc.close();
236 			}
237 		}
238 	}
239 }