/
IOManagerAsync.java
497 lines (416 loc) · 16.8 KB
/
IOManagerAsync.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
* Licensed to the Apache Software Foundation (ASF) 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 org.apache.flink.runtime.io.disk.iomanager;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.util.EnvironmentInformation;
import org.apache.flink.util.IOUtils;
import org.apache.flink.util.ShutdownHookUtil;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.flink.util.Preconditions.checkState;
/**
* A version of the {@link IOManager} that uses asynchronous I/O.
*/
public class IOManagerAsync extends IOManager implements UncaughtExceptionHandler {
/** The writer threads used for asynchronous block oriented channel writing. */
private final WriterThread[] writers;
/** The reader threads used for asynchronous block oriented channel reading. */
private final ReaderThread[] readers;
/** Flag to signify that the IOManager has been shut down already */
private final AtomicBoolean isShutdown = new AtomicBoolean();
/** Shutdown hook to make sure that the directories are removed on exit */
private final Thread shutdownHook;
// -------------------------------------------------------------------------
// Constructors / Destructors
// -------------------------------------------------------------------------
/**
* Constructs a new asynchronous I/O manager, writing files to the system 's temp directory.
*/
public IOManagerAsync() {
this(EnvironmentInformation.getTemporaryFileDirectory());
}
/**
* Constructs a new asynchronous I/O manager, writing file to the given directory.
*
* @param tempDir The directory to write temporary files to.
*/
public IOManagerAsync(String tempDir) {
this(new String[] {tempDir});
}
/**
* Constructs a new asynchronous I/O manager, writing file round robin across the given directories.
*
* @param tempDirs The directories to write temporary files to.
*/
public IOManagerAsync(String[] tempDirs) {
super(tempDirs);
// start a write worker thread for each directory
this.writers = new WriterThread[tempDirs.length];
for (int i = 0; i < this.writers.length; i++) {
final WriterThread t = new WriterThread();
this.writers[i] = t;
t.setName("IOManager writer thread #" + (i + 1));
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
// start a reader worker thread for each directory
this.readers = new ReaderThread[tempDirs.length];
for (int i = 0; i < this.readers.length; i++) {
final ReaderThread t = new ReaderThread();
this.readers[i] = t;
t.setName("IOManager reader thread #" + (i + 1));
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
// install a shutdown hook that makes sure the temp directories get deleted
this.shutdownHook = ShutdownHookUtil.addShutdownHook(this::close, getClass().getSimpleName(), LOG);
}
/**
* Close method. Shuts down the reader and writer threads immediately, not waiting for their
* pending requests to be served. This method waits until the threads have actually ceased their
* operation.
*/
@Override
public void close() throws Exception {
// mark shut down and exit if it already was shut down
if (!isShutdown.compareAndSet(false, true)) {
return;
}
// Remove shutdown hook to prevent resource leaks
ShutdownHookUtil.removeShutdownHook(shutdownHook, getClass().getSimpleName(), LOG);
if (LOG.isDebugEnabled()) {
LOG.debug("Shutting down I/O manager.");
}
// close writing and reading threads with best effort and log problems
// first notify all to close, then wait until all are closed
List<AutoCloseable> closeables = new ArrayList<>(writers.length + readers.length + 2);
for (WriterThread wt : writers) {
closeables.add(getWriterThreadCloser(wt));
}
for (ReaderThread rt : readers) {
closeables.add(getReaderThreadCloser(rt));
}
closeables.add(() -> {
try {
for (WriterThread wt : writers) {
wt.join();
}
for (ReaderThread rt : readers) {
rt.join();
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
});
// make sure we call the super implementation in any case and at the last point,
// because this will clean up the I/O directories
closeables.add(super::close);
IOUtils.closeAll(closeables);
}
private static AutoCloseable getWriterThreadCloser(WriterThread thread) {
return () -> {
try {
thread.shutdown();
} catch (Throwable t) {
throw new IOException("Error while shutting down IO Manager writer thread.", t);
}
};
}
private static AutoCloseable getReaderThreadCloser(ReaderThread thread) {
return () -> {
try {
thread.shutdown();
} catch (Throwable t) {
throw new IOException("Error while shutting down IO Manager reader thread.", t);
}
};
}
@Override
public void uncaughtException(Thread t, Throwable e) {
LOG.error("IO Thread '" + t.getName() + "' terminated due to an exception. Shutting down I/O Manager.", e);
try {
close();
} catch (Exception ex) {
LOG.warn("IOManagerAsync did not shut down properly.", ex);
}
}
// ------------------------------------------------------------------------
// Reader / Writer instantiations
// ------------------------------------------------------------------------
@Override
public BlockChannelWriter<MemorySegment> createBlockChannelWriter(FileIOChannel.ID channelID,
LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException
{
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBlockWriter(channelID, this.writers[channelID.getThreadNum()].requestQueue, returnQueue);
}
@Override
public BlockChannelWriterWithCallback<MemorySegment> createBlockChannelWriter(FileIOChannel.ID channelID, RequestDoneCallback<MemorySegment> callback) throws IOException {
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBlockWriterWithCallback(channelID, this.writers[channelID.getThreadNum()].requestQueue, callback);
}
/**
* Creates a block channel reader that reads blocks from the given channel. The reader reads asynchronously,
* such that a read request is accepted, carried out at some (close) point in time, and the full segment
* is pushed to the given queue.
*
* @param channelID The descriptor for the channel to write to.
* @param returnQueue The queue to put the full buffers into.
* @return A block channel reader that reads from the given channel.
* @throws IOException Thrown, if the channel for the reader could not be opened.
*/
@Override
public BlockChannelReader<MemorySegment> createBlockChannelReader(FileIOChannel.ID channelID,
LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException
{
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBlockReader(channelID, this.readers[channelID.getThreadNum()].requestQueue, returnQueue);
}
@Override
public BufferFileWriter createBufferFileWriter(FileIOChannel.ID channelID) throws IOException {
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBufferFileWriter(channelID, writers[channelID.getThreadNum()].requestQueue);
}
@Override
public BufferFileReader createBufferFileReader(FileIOChannel.ID channelID, RequestDoneCallback<Buffer> callback) throws IOException {
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBufferFileReader(channelID, readers[channelID.getThreadNum()].requestQueue, callback);
}
@Override
public BufferFileSegmentReader createBufferFileSegmentReader(FileIOChannel.ID channelID, RequestDoneCallback<FileSegment> callback) throws IOException {
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBufferFileSegmentReader(channelID, readers[channelID.getThreadNum()].requestQueue, callback);
}
/**
* Creates a block channel reader that reads all blocks from the given channel directly in one bulk.
* The reader draws segments to read the blocks into from a supplied list, which must contain as many
* segments as the channel has blocks. After the reader is done, the list with the full segments can be
* obtained from the reader.
* <p>
* If a channel is not to be read in one bulk, but in multiple smaller batches, a
* {@link BlockChannelReader} should be used.
*
* @param channelID The descriptor for the channel to write to.
* @param targetSegments The list to take the segments from into which to read the data.
* @param numBlocks The number of blocks in the channel to read.
* @return A block channel reader that reads from the given channel.
* @throws IOException Thrown, if the channel for the reader could not be opened.
*/
@Override
public BulkBlockChannelReader createBulkBlockChannelReader(FileIOChannel.ID channelID,
List<MemorySegment> targetSegments, int numBlocks) throws IOException
{
checkState(!isShutdown.get(), "I/O-Manager is shut down.");
return new AsynchronousBulkBlockReader(channelID, this.readers[channelID.getThreadNum()].requestQueue, targetSegments, numBlocks);
}
// -------------------------------------------------------------------------
// For Testing
// -------------------------------------------------------------------------
RequestQueue<ReadRequest> getReadRequestQueue(FileIOChannel.ID channelID) {
return this.readers[channelID.getThreadNum()].requestQueue;
}
RequestQueue<WriteRequest> getWriteRequestQueue(FileIOChannel.ID channelID) {
return this.writers[channelID.getThreadNum()].requestQueue;
}
// -------------------------------------------------------------------------
// I/O Worker Threads
// -------------------------------------------------------------------------
/**
* A worker thread for asynchronous reads.
*/
private static final class ReaderThread extends Thread {
protected final RequestQueue<ReadRequest> requestQueue;
private volatile boolean alive;
// ---------------------------------------------------------------------
// Constructors / Destructors
// ---------------------------------------------------------------------
protected ReaderThread() {
this.requestQueue = new RequestQueue<ReadRequest>();
this.alive = true;
}
/**
* Shuts the thread down. This operation does not wait for all pending requests to be served, halts the thread
* immediately. All buffers of pending requests are handed back to their channel readers and an exception is
* reported to them, declaring their request queue as closed.
*/
protected void shutdown() {
synchronized (this) {
if (alive) {
alive = false;
requestQueue.close();
interrupt();
}
try {
join(1000);
}
catch (InterruptedException ignored) {}
// notify all pending write requests that the thread has been shut down
IOException ioex = new IOException("IO-Manager has been closed.");
while (!this.requestQueue.isEmpty()) {
ReadRequest request = this.requestQueue.poll();
if (request != null) {
try {
request.requestDone(ioex);
}
catch (Throwable t) {
IOManagerAsync.LOG.error("The handler of the request complete callback threw an exception"
+ (t.getMessage() == null ? "." : ": " + t.getMessage()), t);
}
}
}
}
}
// ---------------------------------------------------------------------
// Main loop
// ---------------------------------------------------------------------
@Override
public void run() {
while (alive) {
// get the next buffer. ignore interrupts that are not due to a shutdown.
ReadRequest request = null;
while (alive && request == null) {
try {
request = this.requestQueue.take();
}
catch (InterruptedException e) {
if (!this.alive) {
return;
} else {
IOManagerAsync.LOG.warn(Thread.currentThread() + " was interrupted without shutdown.");
}
}
}
// remember any IO exception that occurs, so it can be reported to the writer
IOException ioex = null;
try {
// read buffer from the specified channel
request.read();
}
catch (IOException e) {
ioex = e;
}
catch (Throwable t) {
ioex = new IOException("The buffer could not be read: " + t.getMessage(), t);
IOManagerAsync.LOG.error("I/O reading thread encountered an error" + (t.getMessage() == null ? "." : ": " + t.getMessage()), t);
}
// invoke the processed buffer handler of the request issuing reader object
try {
request.requestDone(ioex);
}
catch (Throwable t) {
IOManagerAsync.LOG.error("The handler of the request-complete-callback threw an exception" + (t.getMessage() == null ? "." : ": " + t.getMessage()), t);
}
} // end while alive
}
} // end reading thread
/**
* A worker thread that asynchronously writes the buffers to disk.
*/
private static final class WriterThread extends Thread {
protected final RequestQueue<WriteRequest> requestQueue;
private volatile boolean alive;
// ---------------------------------------------------------------------
// Constructors / Destructors
// ---------------------------------------------------------------------
protected WriterThread() {
this.requestQueue = new RequestQueue<WriteRequest>();
this.alive = true;
}
/**
* Shuts the thread down. This operation does not wait for all pending requests to be served, halts the thread
* immediately. All buffers of pending requests are handed back to their channel writers and an exception is
* reported to them, declaring their request queue as closed.
*/
protected void shutdown() {
synchronized (this) {
if (alive) {
alive = false;
requestQueue.close();
interrupt();
}
try {
join(1000);
}
catch (InterruptedException ignored) {}
// notify all pending write requests that the thread has been shut down
IOException ioex = new IOException("IO-Manager has been closed.");
while (!this.requestQueue.isEmpty()) {
WriteRequest request = this.requestQueue.poll();
if (request != null) {
try {
request.requestDone(ioex);
}
catch (Throwable t) {
IOManagerAsync.LOG.error("The handler of the request complete callback threw an exception"
+ (t.getMessage() == null ? "." : ": " + t.getMessage()), t);
}
}
}
}
}
// ---------------------------------------------------------------------
// Main loop
// ---------------------------------------------------------------------
@Override
public void run() {
while (this.alive) {
WriteRequest request = null;
// get the next buffer. ignore interrupts that are not due to a shutdown.
while (alive && request == null) {
try {
request = requestQueue.take();
}
catch (InterruptedException e) {
if (!this.alive) {
return;
} else {
IOManagerAsync.LOG.warn(Thread.currentThread() + " was interrupted without shutdown.");
}
}
}
// remember any IO exception that occurs, so it can be reported to the writer
IOException ioex = null;
try {
// write buffer to the specified channel
request.write();
}
catch (IOException e) {
ioex = e;
}
catch (Throwable t) {
ioex = new IOException("The buffer could not be written: " + t.getMessage(), t);
IOManagerAsync.LOG.error("I/O writing thread encountered an error" + (t.getMessage() == null ? "." : ": " + t.getMessage()), t);
}
// invoke the processed buffer handler of the request issuing writer object
try {
request.requestDone(ioex);
}
catch (Throwable t) {
IOManagerAsync.LOG.error("The handler of the request-complete-callback threw an exception" + (t.getMessage() == null ? "." : ": " + t.getMessage()), t);
}
} // end while alive
}
}; // end writer thread
}