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
| # 先看下整体流程 @Override public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { return (DataStreamSinkProvider) dataStream -> { RowType rowType = (RowType) schema.toRowDataType().notNull().getLogicalType(); int numWriteTasks = conf.getInteger(FlinkOptions.WRITE_TASKS); StreamWriteOperatorFactory<HoodieRecord> operatorFactory = new StreamWriteOperatorFactory<>(conf); DataStream<Object> pipeline = dataStream .map(new RowDataToHoodieFunction<>(rowType, conf), TypeInformation.of(HoodieRecord.class)) .keyBy(HoodieRecord::getRecordKey) .transform( "bucket_assigner", TypeInformation.of(HoodieRecord.class), new KeyedProcessOperator<>(new BucketAssignFunction<>(conf))) .uid("uid_bucket_assigner") .keyBy(record -> record.getCurrentLocation().getFileId()) .transform("hoodie_stream_write", TypeInformation.of(Object.class), operatorFactory) .uid("uid_hoodie_stream_write") .setParallelism(numWriteTasks); if (StreamerUtil.needsScheduleCompaction(conf)) { return pipeline.transform("compact_plan_generate", TypeInformation.of(CompactionPlanEvent.class), new CompactionPlanOperator(conf)) .uid("uid_compact_plan_generate") .setParallelism(1) .keyBy(event -> event.getOperation().hashCode()) .transform("compact_task", TypeInformation.of(CompactionCommitEvent.class), new KeyedProcessOperator<>(new CompactFunction(conf))) .setParallelism(conf.getInteger(FlinkOptions.COMPACTION_TASKS)) .addSink(new CompactionCommitSink(conf)) .name("compact_commit") .setParallelism(1); } else { return pipeline.addSink(new CleanFunction<>(conf)) .setParallelism(1) .name("clean_commits").uid("uid_clean_commits"); } }; }
# RowDataToHoodieFunction @Override public void open(Configuration parameters) throws Exception { super.open(parameters); this.avroSchema = StreamerUtil.getSourceSchema(this.config); this.converter = RowDataToAvroConverters.createConverter(this.rowType); this.keyGenerator = StreamerUtil.createKeyGenerator(FlinkOptions.flatOptions(this.config)); this.payloadCreation = PayloadCreation.instance(config); }
@SuppressWarnings("unchecked") @Override public O map(I i) throws Exception { return (O) toHoodieRecord(i); }
@SuppressWarnings("rawtypes") private HoodieRecord toHoodieRecord(I record) throws Exception { GenericRecord gr = (GenericRecord) this.converter.convert(this.avroSchema, record); final HoodieKey hoodieKey = keyGenerator.getKey(gr); final boolean isDelete = record.getRowKind() == RowKind.DELETE; HoodieRecordPayload payload = payloadCreation.createPayload(gr, isDelete); return new HoodieRecord<>(hoodieKey, payload); }
public HoodieRecordPayload<?> createPayload(GenericRecord record, boolean isDelete) throws Exception { if (shouldCombine) { ValidationUtils.checkState(preCombineField != null); Comparable<?> orderingVal = (Comparable<?>) HoodieAvroUtils.getNestedFieldVal(record, preCombineField, false); return (HoodieRecordPayload<?>) constructor.newInstance( isDelete ? null : record, orderingVal); } else { return (HoodieRecordPayload<?>) this.constructor.newInstance(Option.of(record)); } }
# BucketAssignFunction @Override public void open(Configuration parameters) throws Exception { super.open(parameters); HoodieWriteConfig writeConfig = StreamerUtil.getHoodieClientConfig(this.conf); this.hadoopConf = StreamerUtil.getHadoopConf(); this.context = new HoodieFlinkEngineContext( new SerializableConfiguration(this.hadoopConf), new FlinkTaskContextSupplier(getRuntimeContext())); this.bucketAssigner = BucketAssigners.create( getRuntimeContext().getIndexOfThisSubtask(), getRuntimeContext().getNumberOfParallelSubtasks(), WriteOperationType.isOverwrite(WriteOperationType.fromValue(conf.getString(FlinkOptions.OPERATION))), HoodieTableType.valueOf(conf.getString(FlinkOptions.TABLE_TYPE)), context, writeConfig); }
public static BucketAssigner create( int taskID, int numTasks, boolean isOverwrite, HoodieTableType tableType, HoodieFlinkEngineContext context, HoodieWriteConfig config) { if (isOverwrite) { return new OverwriteBucketAssigner(taskID, numTasks, context, config); } switch (tableType) { case COPY_ON_WRITE: return new BucketAssigner(taskID, numTasks, context, config); case MERGE_ON_READ: return new DeltaBucketAssigner(taskID, numTasks, context, config); default: throw new AssertionError(); } }
@Override public void processElement(I value, Context ctx, Collector<O> out) throws Exception { HoodieRecord<?> record = (HoodieRecord<?>) value; final HoodieKey hoodieKey = record.getKey(); final BucketInfo bucketInfo; final HoodieRecordLocation location;
if (bootstrapIndex && !partitionLoadState.contains(hoodieKey.getPartitionPath())) { loadRecords(hoodieKey.getPartitionPath()); } if (isChangingRecords && this.indexState.contains(hoodieKey)) { location = new HoodieRecordLocation("U", this.indexState.get(hoodieKey).getFileId()); this.bucketAssigner.addUpdate(record.getPartitionPath(), location.getFileId()); } else { bucketInfo = this.bucketAssigner.addInsert(hoodieKey.getPartitionPath()); switch (bucketInfo.getBucketType()) { case INSERT: location = new HoodieRecordLocation("I", bucketInfo.getFileIdPrefix()); break; case UPDATE: location = new HoodieRecordLocation("U", bucketInfo.getFileIdPrefix()); break; default: throw new AssertionError(); } if (isChangingRecords) { this.indexState.put(hoodieKey, location); } } record.unseal(); record.setCurrentLocation(location); record.seal(); out.collect((O) record); }
# DeltaBucketAssigner--->BucketAssigner 主要还是看父类操作,子类只是获取小文件列表 public BucketInfo addUpdate(String partitionPath, String fileIdHint) { final String key = StreamerUtil.generateBucketKey(partitionPath, fileIdHint); if (!bucketInfoMap.containsKey(key)) { BucketInfo bucketInfo = new BucketInfo(BucketType.UPDATE, fileIdHint, partitionPath); bucketInfoMap.put(key, bucketInfo); } return bucketInfoMap.get(key); }
public BucketInfo addInsert(String partitionPath) { List<SmallFile> smallFiles = getSmallFilesForPartition(partitionPath);
for (SmallFile smallFile : smallFiles) { final String key = StreamerUtil.generateBucketKey(partitionPath, smallFile.location.getFileId()); SmallFileAssignState assignState = smallFileAssignStates.get(key); assert assignState != null; if (assignState.canAssign()) { assignState.assign(); BucketInfo bucketInfo; if (bucketInfoMap.containsKey(key)) { bucketInfo = bucketInfoMap.get(key); } else { bucketInfo = addUpdate(partitionPath, smallFile.location.getFileId()); } return bucketInfo; } }
if (newFileAssignStates.containsKey(partitionPath)) { NewFileAssignState newFileAssignState = newFileAssignStates.get(partitionPath); if (newFileAssignState.canAssign()) { newFileAssignState.assign(); } final String key = StreamerUtil.generateBucketKey(partitionPath, newFileAssignState.fileId); return bucketInfoMap.get(key); } BucketInfo bucketInfo = new BucketInfo(BucketType.INSERT, FSUtils.createNewFileIdPfx(), partitionPath); final String key = StreamerUtil.generateBucketKey(partitionPath, bucketInfo.getFileIdPrefix()); bucketInfoMap.put(key, bucketInfo); newFileAssignStates.put(partitionPath, new NewFileAssignState(bucketInfo.getFileIdPrefix(), insertRecordsPerBucket)); return bucketInfo; }
# StreamWriteOperatorFactory
@Override @SuppressWarnings("unchecked") public <T extends StreamOperator<Object>> T createStreamOperator(StreamOperatorParameters<Object> parameters) { final OperatorID operatorID = parameters.getStreamConfig().getOperatorID(); final OperatorEventDispatcher eventDispatcher = parameters.getOperatorEventDispatcher();
this.operator.setOperatorEventGateway(eventDispatcher.getOperatorEventGateway(operatorID)); this.operator.setup(parameters.getContainingTask(), parameters.getStreamConfig(), parameters.getOutput()); this.operator.setProcessingTimeService(this.processingTimeService); eventDispatcher.registerEventHandler(operatorID, operator); return (T) operator; }
@Override public OperatorCoordinator.Provider getCoordinatorProvider(String s, OperatorID operatorID) { return new StreamWriteOperatorCoordinator.Provider(operatorID, this.conf); }
# StreamWriteOperator
# StreamWriteFunction
private void bufferRecord(I value) { final String bucketID = getBucketID(value);
DataBucket bucket = this.buckets.computeIfAbsent(bucketID, k -> new DataBucket(this.config.getDouble(FlinkOptions.WRITE_BATCH_SIZE))); boolean flushBucket = bucket.detector.detect(value); boolean flushBuffer = this.tracer.trace(bucket.detector.lastRecordSize); if (flushBucket) { flushBucket(bucket); this.tracer.countDown(bucket.detector.totalSize); bucket.reset(); } else if (flushBuffer) { List<DataBucket> sortedBuckets = this.buckets.values().stream() .sorted((b1, b2) -> Long.compare(b2.detector.totalSize, b1.detector.totalSize)) .collect(Collectors.toList()); final DataBucket bucketToFlush = sortedBuckets.get(0); flushBucket(bucketToFlush); this.tracer.countDown(bucketToFlush.detector.totalSize); bucketToFlush.reset(); } bucket.records.add((HoodieRecord<?>) value); }
@SuppressWarnings("unchecked, rawtypes") private void flushBucket(DataBucket bucket) { final String instant = this.writeClient.getLastPendingInstant(this.actionType);
if (instant == null) { LOG.info("No inflight instant when flushing data, cancel."); return; }
boolean shift = confirming && StreamerUtil.equal(instant, this.currentInstant); final String flushInstant = shift ? StreamerUtil.instantTimePlus(instant, 1) : instant;
List<HoodieRecord> records = bucket.records; ValidationUtils.checkState(records.size() > 0, "Data bucket to flush has no buffering records"); if (config.getBoolean(FlinkOptions.INSERT_DROP_DUPS)) { records = FlinkWriteHelper.newInstance().deduplicateRecords(records, (HoodieIndex) null, -1); } final List<WriteStatus> writeStatus = new ArrayList<>(writeFunction.apply(records, flushInstant)); final BatchWriteSuccessEvent event = BatchWriteSuccessEvent.builder() .taskID(taskID) .instantTime(instant) .writeStatus(writeStatus) .isLastBatch(false) .isEndInput(false) .build(); this.eventGateway.sendEventToCoordinator(event); }
# StreamWriteOperatorCoordinator @Override public void handleEventFromOperator(int i, OperatorEvent operatorEvent) { executor.execute( () -> { ValidationUtils.checkState(operatorEvent instanceof BatchWriteSuccessEvent, "The coordinator can only handle BatchWriteSuccessEvent"); BatchWriteSuccessEvent event = (BatchWriteSuccessEvent) operatorEvent; ValidationUtils.checkState( HoodieTimeline.compareTimestamps(instant, HoodieTimeline.GREATER_THAN_OR_EQUALS, event.getInstantTime()), String.format("Receive an unexpected event for instant %s from task %d", event.getInstantTime(), event.getTaskID())); if (this.eventBuffer[event.getTaskID()] != null) { this.eventBuffer[event.getTaskID()].mergeWith(event); } else { this.eventBuffer[event.getTaskID()] = event; } if (event.isEndInput() && allEventsReceived()) { commitInstant(); } }, "handle write success event for instant %s", this.instant ); }
|