-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
RaptorPageSink.java
350 lines (302 loc) · 13 KB
/
RaptorPageSink.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
/*
* Licensed 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 com.facebook.presto.raptor;
import com.facebook.presto.raptor.metadata.ShardInfo;
import com.facebook.presto.raptor.storage.StorageManager;
import com.facebook.presto.raptor.util.PageBuffer;
import com.facebook.presto.spi.BucketFunction;
import com.facebook.presto.spi.ConnectorPageSink;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.PageSorter;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.SortOrder;
import com.facebook.presto.spi.type.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import io.airlift.json.JsonCodec;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.airlift.units.DataSize;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.CompletableFuture;
import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.DateType.DATE;
import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP;
import static com.google.common.base.Preconditions.checkArgument;
import static io.airlift.concurrent.MoreFutures.allAsList;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.stream.Collectors.toList;
public class RaptorPageSink
implements ConnectorPageSink
{
private final long transactionId;
private final StorageManager storageManager;
private final JsonCodec<ShardInfo> shardInfoCodec;
private final PageSorter pageSorter;
private final List<Long> columnIds;
private final List<Type> columnTypes;
private final List<Integer> sortFields;
private final List<SortOrder> sortOrders;
private final OptionalInt bucketCount;
private final int[] bucketFields;
private final long maxBufferBytes;
private final OptionalInt temporalColumnIndex;
private final Optional<Type> temporalColumnType;
private final PageWriter pageWriter;
public RaptorPageSink(
PageSorter pageSorter,
StorageManager storageManager,
JsonCodec<ShardInfo> shardInfoCodec,
long transactionId,
List<Long> columnIds,
List<Type> columnTypes,
List<Long> sortColumnIds,
List<SortOrder> sortOrders,
OptionalInt bucketCount,
List<Long> bucketColumnIds,
Optional<RaptorColumnHandle> temporalColumnHandle,
DataSize maxBufferSize)
{
this.transactionId = transactionId;
this.pageSorter = requireNonNull(pageSorter, "pageSorter is null");
this.columnIds = ImmutableList.copyOf(requireNonNull(columnIds, "columnIds is null"));
this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null"));
this.storageManager = requireNonNull(storageManager, "storageManager is null");
this.shardInfoCodec = requireNonNull(shardInfoCodec, "shardInfoCodec is null");
this.maxBufferBytes = requireNonNull(maxBufferSize, "maxBufferSize is null").toBytes();
this.sortFields = ImmutableList.copyOf(sortColumnIds.stream().map(columnIds::indexOf).collect(toList()));
this.sortOrders = ImmutableList.copyOf(requireNonNull(sortOrders, "sortOrders is null"));
this.bucketCount = bucketCount;
this.bucketFields = bucketColumnIds.stream().mapToInt(columnIds::indexOf).toArray();
for (int field : bucketFields) {
if (!columnTypes.get(field).equals(BIGINT)) {
throw new PrestoException(NOT_SUPPORTED, "Bucketing is only supported for BIGINT columns");
}
}
if (temporalColumnHandle.isPresent() && columnIds.contains(temporalColumnHandle.get().getColumnId())) {
temporalColumnIndex = OptionalInt.of(columnIds.indexOf(temporalColumnHandle.get().getColumnId()));
temporalColumnType = Optional.of(columnTypes.get(temporalColumnIndex.getAsInt()));
checkArgument(temporalColumnType.get() == DATE || temporalColumnType.get() == TIMESTAMP,
"temporalColumnType can only be DATE or TIMESTAMP");
}
else {
temporalColumnIndex = OptionalInt.empty();
temporalColumnType = Optional.empty();
}
this.pageWriter = (bucketCount.isPresent() || temporalColumnIndex.isPresent()) ? new PartitionedPageWriter() : new SimplePageWriter();
}
@Override
public CompletableFuture<?> appendPage(Page page)
{
if (page.getPositionCount() == 0) {
return NOT_BLOCKED;
}
pageWriter.appendPage(page);
return NOT_BLOCKED;
}
@Override
public CompletableFuture<Collection<Slice>> finish()
{
List<CompletableFuture<? extends List<Slice>>> futureSlices = pageWriter.getPageBuffers().stream().map(pageBuffer -> {
pageBuffer.flush();
CompletableFuture<List<ShardInfo>> futureShards = pageBuffer.getStoragePageSink().commit();
return futureShards.thenApply(shards -> shards.stream()
.map(shard -> Slices.wrappedBuffer(shardInfoCodec.toJsonBytes(shard)))
.collect(toList()));
}).collect(toList());
return allAsList(futureSlices).thenApply(lists -> lists.stream()
.flatMap(Collection::stream)
.collect(toList()));
}
@Override
public void abort()
{
RuntimeException error = new RuntimeException("Exception during rollback");
for (PageBuffer pageBuffer : pageWriter.getPageBuffers()) {
try {
pageBuffer.getStoragePageSink().rollback();
}
catch (Throwable t) {
// Self-suppression not permitted
if (error != t) {
error.addSuppressed(t);
}
}
}
if (error.getSuppressed().length > 0) {
throw error;
}
}
private PageBuffer createPageBuffer(OptionalInt bucketNumber)
{
return new PageBuffer(
maxBufferBytes,
storageManager.createStoragePageSink(transactionId, bucketNumber, columnIds, columnTypes, true),
columnTypes,
sortFields,
sortOrders,
pageSorter);
}
private interface PageWriter
{
void appendPage(Page page);
List<PageBuffer> getPageBuffers();
}
private class SimplePageWriter
implements PageWriter
{
private final PageBuffer pageBuffer = createPageBuffer(OptionalInt.empty());
@Override
public void appendPage(Page page)
{
pageBuffer.add(page);
}
@Override
public List<PageBuffer> getPageBuffers()
{
return ImmutableList.of(pageBuffer);
}
}
private class PartitionedPageWriter
implements PageWriter
{
private final Optional<BucketFunction> bucketFunction;
private final Optional<TemporalFunction> temporalFunction;
private final Long2ObjectMap<PageStore> pageStores = new Long2ObjectOpenHashMap<>();
public PartitionedPageWriter()
{
checkArgument(temporalColumnIndex.isPresent() == temporalColumnType.isPresent(),
"temporalColumnIndex and temporalColumnType must be both present or absent");
this.bucketFunction = bucketCount.isPresent() ? Optional.of(new RaptorBucketFunction(bucketCount.getAsInt())) : Optional.empty();
this.temporalFunction = temporalColumnType.map(type -> TemporalFunction.create(temporalColumnType.get()));
}
@Override
public void appendPage(Page page)
{
Block temporalBlock = temporalColumnIndex.isPresent() ? page.getBlock(temporalColumnIndex.getAsInt()) : null;
Page bucketArgs = bucketFunction.isPresent() ? getBucketArgsPage(page) : null;
for (int position = 0; position < page.getPositionCount(); position++) {
int bucket = bucketFunction.isPresent() ? bucketFunction.get().getBucket(bucketArgs, position) : 0;
int day = temporalFunction.isPresent() ? temporalFunction.get().getDay(temporalBlock, position) : 0;
long partition = (((long) bucket) << 32) | (day & 0xFFFF_FFFFL);
PageStore store = pageStores.get(partition);
if (store == null) {
OptionalInt bucketNumber = bucketFunction.isPresent() ? OptionalInt.of(bucket) : OptionalInt.empty();
PageBuffer buffer = createPageBuffer(bucketNumber);
store = new PageStore(buffer, columnTypes);
pageStores.put(partition, store);
}
store.appendPosition(page, position);
}
flushIfNecessary();
}
private Page getBucketArgsPage(Page page)
{
Block[] blocks = new Block[bucketFields.length];
for (int i = 0; i < bucketFields.length; i++) {
blocks[i] = page.getBlock(bucketFields[i]);
}
return new Page(page.getPositionCount(), blocks);
}
@Override
public List<PageBuffer> getPageBuffers()
{
ImmutableList.Builder<PageBuffer> list = ImmutableList.builder();
for (PageStore store : pageStores.values()) {
store.flushToPageBuffer();
store.getPageBuffer().flush();
list.add(store.getPageBuffer());
}
return list.build();
}
private void flushIfNecessary()
{
long totalBytes = 0;
long maxBytes = 0;
PageBuffer maxBuffer = null;
for (PageStore store : pageStores.values()) {
long bytes = store.getUsedMemoryBytes();
totalBytes += bytes;
if ((maxBuffer == null) || (bytes > maxBytes)) {
maxBuffer = store.getPageBuffer();
maxBytes = bytes;
}
}
if ((totalBytes > maxBufferBytes) && (maxBuffer != null)) {
maxBuffer.flush();
}
}
}
private static class PageStore
{
private final PageBuffer pageBuffer;
private final PageBuilder pageBuilder;
public PageStore(PageBuffer pageBuffer, List<Type> columnTypes)
{
this.pageBuffer = requireNonNull(pageBuffer, "pageBuffer is null");
this.pageBuilder = new PageBuilder(columnTypes);
}
public long getUsedMemoryBytes()
{
return pageBuilder.getSizeInBytes() + pageBuffer.getUsedMemoryBytes();
}
public PageBuffer getPageBuffer()
{
return pageBuffer;
}
public void appendPosition(Page page, int position)
{
pageBuilder.declarePosition();
for (int channel = 0; channel < page.getChannelCount(); channel++) {
Block block = page.getBlock(channel);
BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(channel);
pageBuilder.getType(channel).appendTo(block, position, blockBuilder);
}
if (pageBuilder.isFull()) {
flushToPageBuffer();
}
}
public void flushToPageBuffer()
{
if (!pageBuilder.isEmpty()) {
pageBuffer.add(pageBuilder.build());
pageBuilder.reset();
}
}
}
private interface TemporalFunction
{
int getDay(Block temporalBlock, int position);
static TemporalFunction create(Type temporalColumnType)
{
if (temporalColumnType.equals(DATE)) {
return (temporalBlock, position) -> Ints.checkedCast(DATE.getLong(temporalBlock, position));
}
if (temporalColumnType.equals(TIMESTAMP)) {
return (temporalBlock, position) -> Ints.checkedCast(MILLISECONDS.toDays(temporalBlock.getLong(position, 0)));
}
throw new IllegalArgumentException("Wrong type for temporal column: " + temporalColumnType);
}
}
}