-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
FileInStream.java
338 lines (307 loc) · 11.9 KB
/
FileInStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.client.file;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import tachyon.Constants;
import tachyon.annotation.PublicApi;
import tachyon.client.BoundedStream;
import tachyon.client.ClientContext;
import tachyon.client.Seekable;
import tachyon.client.TachyonStorageType;
import tachyon.client.block.BlockInStream;
import tachyon.client.block.BufferedBlockOutStream;
import tachyon.client.block.LocalBlockInStream;
import tachyon.client.options.InStreamOptions;
import tachyon.master.block.BlockId;
import tachyon.thrift.FileInfo;
import tachyon.util.network.NetworkAddressUtils;
/**
* A streaming API to read a file. This API represents a file as a stream of bytes and provides a
* collection of {@link #read} methods to access this stream of bytes. In addition, one can seek
* into a given offset of the stream to read.
*
* <p>
* This class wraps the {@link BlockInStream} for each of the blocks in the file and abstracts the
* switching between streams. The backing streams can read from Tachyon space in the local machine,
* remote machines, or the under storage system.
*/
@PublicApi
public final class FileInStream extends InputStream implements BoundedStream, Seekable {
/** Logger for this class */
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
/** How the data should be written into Tachyon space, if at all */
private final TachyonStorageType mTachyonStorageType;
/** Standard block size in bytes of the file, guaranteed for all but the last block */
private final long mBlockSize;
/** Total length of the file in bytes */
private final long mFileLength;
/** File System context containing the FileSystemMasterClient pool */
private final FileSystemContext mContext;
/** Block ids associated with this file */
private final List<Long> mBlockIds;
/** Path to the under storage system file that backs this Tachyon file */
private final String mUfsPath;
/** If the stream is closed, this can only go from false to true */
private boolean mClosed;
/** Whether or not the current block should be cached. */
private boolean mShouldCacheCurrentBlock;
/** Current position of the stream */
private long mPos;
/** Current BlockInStream backing this stream */
private BlockInStream mCurrentBlockInStream;
/** Current BlockOutStream writing the data into Tachyon, this may be null */
private BufferedBlockOutStream mCurrentCacheStream;
/**
* Creates a new file input stream.
*
* @param info the file information
* @param options the client options
*/
public FileInStream(FileInfo info, InStreamOptions options) {
mBlockSize = info.getBlockSizeBytes();
mFileLength = info.getLength();
mBlockIds = info.getBlockIds();
mUfsPath = info.getUfsPath();
mContext = FileSystemContext.INSTANCE;
mTachyonStorageType = options.getTachyonStorageType();
mShouldCacheCurrentBlock = mTachyonStorageType.isStore();
mClosed = false;
}
@Override
public void close() throws IOException {
if (mClosed) {
return;
}
if (mCurrentBlockInStream != null) {
mCurrentBlockInStream.close();
}
closeCacheStream();
mClosed = true;
}
@Override
public int read() throws IOException {
if (mPos >= mFileLength) {
return -1;
}
checkAndAdvanceBlockInStream();
int data = mCurrentBlockInStream.read();
mPos ++;
if (mShouldCacheCurrentBlock) {
try {
mCurrentCacheStream.write(data);
} catch (IOException ioe) {
LOG.warn("Block of ID " + getCurrentBlockId() + " could not be cached into Tachyon", ioe);
mShouldCacheCurrentBlock = false;
}
}
return data;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
Preconditions.checkArgument(b != null, "Buffer is null");
Preconditions.checkArgument(off >= 0 && len >= 0 && len + off <= b.length,
String.format("Buffer length (%d), offset(%d), len(%d)", b.length, off, len));
if (len == 0) {
return 0;
} else if (mPos >= mFileLength) {
return -1;
}
int currentOffset = off;
int bytesLeftToRead = len;
while (bytesLeftToRead > 0 && mPos < mFileLength) {
checkAndAdvanceBlockInStream();
int bytesToRead = (int) Math.min(bytesLeftToRead, mCurrentBlockInStream.remaining());
int bytesRead = mCurrentBlockInStream.read(b, currentOffset, bytesToRead);
if (bytesRead > 0 && mShouldCacheCurrentBlock) {
try {
mCurrentCacheStream.write(b, currentOffset, bytesRead);
} catch (IOException ioe) {
LOG.warn("Failed to write into TachyonStorage, the block " + getCurrentBlockId()
+ " will not be in TachyonStorage", ioe);
mShouldCacheCurrentBlock = false;
}
}
if (bytesRead == -1) {
// mCurrentBlockInStream has reached its block boundary
continue;
}
mPos += bytesRead;
bytesLeftToRead -= bytesRead;
currentOffset += bytesRead;
}
return len - bytesLeftToRead;
}
@Override
public long remaining() {
return mFileLength - mPos;
}
@Override
public void seek(long pos) throws IOException {
if (mPos == pos) {
return;
}
Preconditions.checkArgument(pos >= 0, "Seek position is negative: " + pos);
Preconditions.checkArgument(pos <= mFileLength,
"Seek position is past EOF: " + pos + ", fileSize = " + mFileLength);
seekBlockInStream(pos);
checkAndAdvanceBlockInStream();
mCurrentBlockInStream.seek(mPos % mBlockSize);
}
@Override
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
long toSkip = Math.min(n, mFileLength - mPos);
long newPos = mPos + toSkip;
long toSkipInBlock = ((newPos / mBlockSize) > mPos / mBlockSize) ? newPos % mBlockSize : toSkip;
seekBlockInStream(newPos);
checkAndAdvanceBlockInStream();
if (toSkipInBlock != mCurrentBlockInStream.skip(toSkipInBlock)) {
throw new IOException("The underlying BlockInStream could not skip " + toSkip);
}
return toSkip;
}
/**
* Convenience method for updating mCurrentBlockInStream, mShouldCacheCurrentBlock, and
* mCurrentCacheStream. If the block boundary has been reached, the current BlockInStream is
* closed and a the next one is opened. mShouldCacheCurrent block is set to
* mTachyonStorageType.isCache(). mCurrentCacheStream is also closed and a new one is created for
* the next block.
*
* @throws IOException if the next BlockInStream cannot be obtained
*/
private void checkAndAdvanceBlockInStream() throws IOException {
long currentBlockId = getCurrentBlockId();
if (mCurrentBlockInStream == null || mCurrentBlockInStream.remaining() == 0) {
updateBlockInStream(currentBlockId);
closeCacheStream();
if (mShouldCacheCurrentBlock) {
try {
// TODO(calvin): Specify the location to be local.
mCurrentCacheStream =
mContext.getTachyonBlockStore().getOutStream(currentBlockId, -1,
NetworkAddressUtils.getLocalHostName(ClientContext.getConf()));
} catch (IOException ioe) {
LOG.warn("Failed to get TachyonStore stream, the block " + currentBlockId
+ " will not be in TachyonStorage", ioe);
mShouldCacheCurrentBlock = false;
}
}
}
}
/**
* Convenience method for checking if mCurrentCacheStream is not null and closing it with the
* appropriate close or cancel command.
*
* @throws IOException if the close fails
*/
private void closeCacheStream() throws IOException {
if (mCurrentCacheStream == null) {
return;
}
if (mCurrentCacheStream.remaining() == 0) {
mCurrentCacheStream.close();
} else {
mCurrentCacheStream.cancel();
}
mShouldCacheCurrentBlock = false;
}
/**
* @return the current block id based on mPos, -1 if at the end of the file
*/
private long getCurrentBlockId() {
if (mPos == mFileLength) {
return -1;
}
int index = (int) (mPos / mBlockSize);
Preconditions.checkState(index < mBlockIds.size(), "Current block index exceeds max index.");
return mBlockIds.get(index);
}
/**
* Similar to checkAndAdvanceBlockInStream, but a specific position can be specified and the
* stream pointer will be at that offset after this method completes.
*
* @param newPos the new position to set the stream to
* @throws IOException if the stream at the specified position cannot be opened
*/
private void seekBlockInStream(long newPos) throws IOException {
long oldBlockId = getCurrentBlockId();
mPos = newPos;
closeCacheStream();
long currentBlockId = getCurrentBlockId();
if (oldBlockId != currentBlockId) {
updateBlockInStream(currentBlockId);
// Reading next block entirely.
if (mPos % mBlockSize == 0 && mShouldCacheCurrentBlock) {
try {
mCurrentCacheStream =
mContext.getTachyonBlockStore().getOutStream(currentBlockId, -1,
NetworkAddressUtils.getLocalHostName(ClientContext.getConf()));
} catch (IOException ioe) {
LOG.warn("Failed to write to TachyonStore stream, block " + getCurrentBlockId()
+ " will not be in TachyonStorage.", ioe);
mShouldCacheCurrentBlock = false;
}
} else {
mShouldCacheCurrentBlock = false;
}
}
}
/**
* Helper method to checkAndAdvanceBlockInStream and seekBlockInStream. The current BlockInStream
* will be closed and a new BlockInStream for the given blockId will be opened at position 0.
*
* @param blockId blockId to set the mCurrentBlockInStream to read
* @throws IOException if the next BlockInStream cannot be obtained
*/
private void updateBlockInStream(long blockId) throws IOException {
if (mCurrentBlockInStream != null) {
mCurrentBlockInStream.close();
}
try {
if (mTachyonStorageType.isPromote()) {
try {
mContext.getTachyonBlockStore().promote(blockId);
} catch (IOException ioe) {
// Failed to promote
LOG.warn("Promotion of block " + blockId + " failed.", ioe);
}
}
mCurrentBlockInStream = mContext.getTachyonBlockStore().getInStream(blockId);
mShouldCacheCurrentBlock =
!(mCurrentBlockInStream instanceof LocalBlockInStream) && mTachyonStorageType.isStore();
} catch (IOException ioe) {
LOG.debug("Failed to get BlockInStream for " + blockId + ", using ufs instead", ioe);
if (mUfsPath == null || mUfsPath.isEmpty()) {
LOG.error("Could not obtain data for " + blockId + " from Tachyon and no checkpoint is"
+ " available in under storage.");
throw ioe;
}
long blockStart = BlockId.getSequenceNumber(blockId) * mBlockSize;
mCurrentBlockInStream = new UnderStoreFileInStream(blockStart, mBlockSize, mUfsPath);
mShouldCacheCurrentBlock = mTachyonStorageType.isStore();
}
}
}