idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
14,600 | public static final boolean delimiterNext ( byte [ ] bytes , int startPos , byte [ ] delim ) { for ( int pos = 0 ; pos < delim . length ; pos ++ ) { if ( delim [ pos ] != bytes [ startPos + pos ] ) { return false ; } } return true ; } | Checks if the delimiter starts at the given start position of the byte array . |
14,601 | public static final boolean endsWithDelimiter ( byte [ ] bytes , int endPos , byte [ ] delim ) { if ( endPos < delim . length - 1 ) { return false ; } for ( int pos = 0 ; pos < delim . length ; ++ pos ) { if ( delim [ pos ] != bytes [ endPos - delim . length + 1 + pos ] ) { return false ; } } return true ; } | Checks if the given bytes ends with the delimiter at the given end position . |
14,602 | protected final int nextStringEndPos ( byte [ ] bytes , int startPos , int limit , byte [ ] delimiter ) { int endPos = startPos ; final int delimLimit = limit - delimiter . length + 1 ; while ( endPos < limit ) { if ( endPos < delimLimit && delimiterNext ( bytes , endPos , delimiter ) ) { break ; } endPos ++ ; } if ( endPos == startPos ) { setErrorState ( ParseErrorState . EMPTY_COLUMN ) ; return - 1 ; } return endPos ; } | Returns the end position of a string . Sets the error state if the column is empty . |
14,603 | protected static final int nextStringLength ( byte [ ] bytes , int startPos , int length , char delimiter ) { if ( length <= 0 ) { throw new IllegalArgumentException ( "Invalid input: Empty string" ) ; } int limitedLength = 0 ; final byte delByte = ( byte ) delimiter ; while ( limitedLength < length && bytes [ startPos + limitedLength ] != delByte ) { limitedLength ++ ; } return limitedLength ; } | Returns the length of a string . Throws an exception if the column is empty . |
14,604 | public static < T > Class < FieldParser < T > > getParserForType ( Class < T > type ) { Class < ? extends FieldParser < ? > > parser = PARSERS . get ( type ) ; if ( parser == null ) { return null ; } else { @ SuppressWarnings ( "unchecked" ) Class < FieldParser < T > > typedParser = ( Class < FieldParser < T > > ) parser ; return typedParser ; } } | Gets the parser for the type specified by the given class . Returns null if no parser for that class is known . |
14,605 | protected void reportAllElementKeyGroups ( ) { Preconditions . checkState ( partitioningSource . length >= numberOfElements ) ; for ( int i = 0 ; i < numberOfElements ; ++ i ) { int keyGroup = KeyGroupRangeAssignment . assignToKeyGroup ( keyExtractorFunction . extractKeyFromElement ( partitioningSource [ i ] ) , totalKeyGroups ) ; reportKeyGroupOfElementAtIndex ( i , keyGroup ) ; } } | This method iterates over the input data and reports the key - group for each element . |
14,606 | protected void reportKeyGroupOfElementAtIndex ( int index , int keyGroup ) { final int keyGroupIndex = keyGroup - firstKeyGroup ; elementKeyGroups [ index ] = keyGroupIndex ; ++ counterHistogram [ keyGroupIndex ] ; } | This method reports in the bookkeeping data that the element at the given index belongs to the given key - group . |
14,607 | public void open ( RuntimeContext runtimeContext ) { this . runtimeContext = runtimeContext ; localRateBytesPerSecond = globalRateBytesPerSecond / runtimeContext . getNumberOfParallelSubtasks ( ) ; this . rateLimiter = RateLimiter . create ( localRateBytesPerSecond ) ; } | Creates a rate limiter with the runtime context provided . |
14,608 | protected static void validateZooKeeperConfig ( Properties props ) { if ( props . getProperty ( "zookeeper.connect" ) == null ) { throw new IllegalArgumentException ( "Required property 'zookeeper.connect' has not been set in the properties" ) ; } if ( props . getProperty ( ConsumerConfig . GROUP_ID_CONFIG ) == null ) { throw new IllegalArgumentException ( "Required property '" + ConsumerConfig . GROUP_ID_CONFIG + "' has not been set in the properties" ) ; } try { Integer . parseInt ( props . getProperty ( "zookeeper.session.timeout.ms" , "0" ) ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Property 'zookeeper.session.timeout.ms' is not a valid integer" ) ; } try { Integer . parseInt ( props . getProperty ( "zookeeper.connection.timeout.ms" , "0" ) ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Property 'zookeeper.connection.timeout.ms' is not a valid integer" ) ; } } | Validate the ZK configuration checking for required parameters . |
14,609 | private static void validateAutoOffsetResetValue ( Properties config ) { final String val = config . getProperty ( ConsumerConfig . AUTO_OFFSET_RESET_CONFIG , "largest" ) ; if ( ! ( val . equals ( "largest" ) || val . equals ( "latest" ) || val . equals ( "earliest" ) || val . equals ( "smallest" ) ) ) { throw new IllegalArgumentException ( "Cannot use '" + ConsumerConfig . AUTO_OFFSET_RESET_CONFIG + "' value '" + val + "'. Possible values: 'latest', 'largest', 'earliest', or 'smallest'." ) ; } } | Check for invalid auto . offset . reset values . Should be called in constructor for eager checking before submitting the job . Note that none is also considered invalid as we don t want to deliberately throw an exception right after a task is started . |
14,610 | public boolean isCanceledOrFailed ( ) { return executionState == ExecutionState . CANCELING || executionState == ExecutionState . CANCELED || executionState == ExecutionState . FAILED ; } | Checks whether the task has failed is canceled or is being canceled at the moment . |
14,611 | private void releaseNetworkResources ( ) { LOG . debug ( "Release task {} network resources (state: {})." , taskNameWithSubtask , getExecutionState ( ) ) ; for ( ResultPartition partition : producedPartitions ) { taskEventDispatcher . unregisterPartition ( partition . getPartitionId ( ) ) ; if ( isCanceledOrFailed ( ) ) { partition . fail ( getFailureCause ( ) ) ; } } closeNetworkResources ( ) ; } | Releases network resources before task exits . We should also fail the partition to release if the task has failed is canceled or is being canceled at the moment . |
14,612 | private boolean transitionState ( ExecutionState currentState , ExecutionState newState , Throwable cause ) { if ( STATE_UPDATER . compareAndSet ( this , currentState , newState ) ) { if ( cause == null ) { LOG . info ( "{} ({}) switched from {} to {}." , taskNameWithSubtask , executionId , currentState , newState ) ; } else { LOG . info ( "{} ({}) switched from {} to {}." , taskNameWithSubtask , executionId , currentState , newState , cause ) ; } return true ; } else { return false ; } } | Try to transition the execution state from the current state to the new state . |
14,613 | public void triggerCheckpointBarrier ( final long checkpointID , final long checkpointTimestamp , final CheckpointOptions checkpointOptions , final boolean advanceToEndOfEventTime ) { final AbstractInvokable invokable = this . invokable ; final CheckpointMetaData checkpointMetaData = new CheckpointMetaData ( checkpointID , checkpointTimestamp ) ; if ( executionState == ExecutionState . RUNNING && invokable != null ) { final String taskName = taskNameWithSubtask ; final SafetyNetCloseableRegistry safetyNetCloseableRegistry = FileSystemSafetyNet . getSafetyNetCloseableRegistryForThread ( ) ; Runnable runnable = new Runnable ( ) { public void run ( ) { LOG . debug ( "Creating FileSystem stream leak safety net for {}" , Thread . currentThread ( ) . getName ( ) ) ; FileSystemSafetyNet . setSafetyNetCloseableRegistryForThread ( safetyNetCloseableRegistry ) ; try { boolean success = invokable . triggerCheckpoint ( checkpointMetaData , checkpointOptions , advanceToEndOfEventTime ) ; if ( ! success ) { checkpointResponder . declineCheckpoint ( getJobID ( ) , getExecutionId ( ) , checkpointID , new CheckpointDeclineTaskNotReadyException ( taskName ) ) ; } } catch ( Throwable t ) { if ( getExecutionState ( ) == ExecutionState . RUNNING ) { failExternally ( new Exception ( "Error while triggering checkpoint " + checkpointID + " for " + taskNameWithSubtask , t ) ) ; } else { LOG . debug ( "Encountered error while triggering checkpoint {} for " + "{} ({}) while being not in state running." , checkpointID , taskNameWithSubtask , executionId , t ) ; } } finally { FileSystemSafetyNet . setSafetyNetCloseableRegistryForThread ( null ) ; } } } ; executeAsyncCallRunnable ( runnable , String . format ( "Checkpoint Trigger for %s (%s)." , taskNameWithSubtask , executionId ) , checkpointOptions . getCheckpointType ( ) . isSynchronous ( ) ) ; } else { LOG . debug ( "Declining checkpoint request for non-running task {} ({})." , taskNameWithSubtask , executionId ) ; checkpointResponder . declineCheckpoint ( jobId , executionId , checkpointID , new CheckpointDeclineTaskNotReadyException ( taskNameWithSubtask ) ) ; } } | Calls the invokable to trigger a checkpoint . |
14,614 | private void executeAsyncCallRunnable ( Runnable runnable , String callName , boolean blocking ) { synchronized ( this ) { if ( executionState != ExecutionState . RUNNING ) { return ; } BlockingCallMonitoringThreadPool executor = this . asyncCallDispatcher ; if ( executor == null ) { checkState ( userCodeClassLoader != null , "userCodeClassLoader must not be null" ) ; executor = new BlockingCallMonitoringThreadPool ( new DispatcherThreadFactory ( TASK_THREADS_GROUP , "Async calls on " + taskNameWithSubtask , userCodeClassLoader ) ) ; this . asyncCallDispatcher = executor ; if ( executionState != ExecutionState . RUNNING ) { executor . shutdown ( ) ; asyncCallDispatcher = null ; return ; } } LOG . debug ( "Invoking async call {} on task {}" , callName , taskNameWithSubtask ) ; try { executor . submit ( runnable , blocking ) ; } catch ( RejectedExecutionException e ) { if ( executionState == ExecutionState . RUNNING ) { throw new RuntimeException ( "Async call with a " + ( blocking ? "" : "non-" ) + "blocking call was rejected, even though the task is running." , e ) ; } } } } | Utility method to dispatch an asynchronous call on the invokable . |
14,615 | public static < K , V > MergeResult < K , V > mergeRightIntoLeft ( LinkedOptionalMap < K , V > left , LinkedOptionalMap < K , V > right ) { LinkedOptionalMap < K , V > merged = new LinkedOptionalMap < > ( left ) ; merged . putAll ( right ) ; return new MergeResult < > ( merged , isLeftPrefixOfRight ( left , right ) ) ; } | Tries to merges the keys and the values of |
14,616 | public Set < String > absentKeysOrValues ( ) { return underlyingMap . entrySet ( ) . stream ( ) . filter ( LinkedOptionalMap :: keyOrValueIsAbsent ) . map ( Entry :: getKey ) . collect ( Collectors . toCollection ( LinkedHashSet :: new ) ) ; } | Returns the key names of any keys or values that are absent . |
14,617 | public boolean hasAbsentKeysOrValues ( ) { for ( Entry < String , KeyValue < K , V > > entry : underlyingMap . entrySet ( ) ) { if ( keyOrValueIsAbsent ( entry ) ) { return true ; } } return false ; } | Checks whether there are entries with absent keys or values . |
14,618 | public void addDiscoveredPartitions ( List < KafkaTopicPartition > newPartitions ) throws IOException , ClassNotFoundException { List < KafkaTopicPartitionState < KPH > > newPartitionStates = createPartitionStateHolders ( newPartitions , KafkaTopicPartitionStateSentinel . EARLIEST_OFFSET , timestampWatermarkMode , watermarksPeriodic , watermarksPunctuated , userCodeClassLoader ) ; if ( useMetrics ) { registerOffsetMetrics ( consumerMetricGroup , newPartitionStates ) ; } for ( KafkaTopicPartitionState < KPH > newPartitionState : newPartitionStates ) { subscribedPartitionStates . add ( newPartitionState ) ; unassignedPartitionsQueue . add ( newPartitionState ) ; } } | Adds a list of newly discovered partitions to the fetcher for consuming . |
14,619 | public HashMap < KafkaTopicPartition , Long > snapshotCurrentState ( ) { assert Thread . holdsLock ( checkpointLock ) ; HashMap < KafkaTopicPartition , Long > state = new HashMap < > ( subscribedPartitionStates . size ( ) ) ; for ( KafkaTopicPartitionState < KPH > partition : subscribedPartitionStates ) { state . put ( partition . getKafkaTopicPartition ( ) , partition . getOffset ( ) ) ; } return state ; } | Takes a snapshot of the partition offsets . |
14,620 | protected void emitRecord ( T record , KafkaTopicPartitionState < KPH > partitionState , long offset ) throws Exception { if ( record != null ) { if ( timestampWatermarkMode == NO_TIMESTAMPS_WATERMARKS ) { synchronized ( checkpointLock ) { sourceContext . collect ( record ) ; partitionState . setOffset ( offset ) ; } } else if ( timestampWatermarkMode == PERIODIC_WATERMARKS ) { emitRecordWithTimestampAndPeriodicWatermark ( record , partitionState , offset , Long . MIN_VALUE ) ; } else { emitRecordWithTimestampAndPunctuatedWatermark ( record , partitionState , offset , Long . MIN_VALUE ) ; } } else { synchronized ( checkpointLock ) { partitionState . setOffset ( offset ) ; } } } | Emits a record without attaching an existing timestamp to it . |
14,621 | protected void emitRecordWithTimestamp ( T record , KafkaTopicPartitionState < KPH > partitionState , long offset , long timestamp ) throws Exception { if ( record != null ) { if ( timestampWatermarkMode == NO_TIMESTAMPS_WATERMARKS ) { synchronized ( checkpointLock ) { sourceContext . collectWithTimestamp ( record , timestamp ) ; partitionState . setOffset ( offset ) ; } } else if ( timestampWatermarkMode == PERIODIC_WATERMARKS ) { emitRecordWithTimestampAndPeriodicWatermark ( record , partitionState , offset , timestamp ) ; } else { emitRecordWithTimestampAndPunctuatedWatermark ( record , partitionState , offset , timestamp ) ; } } else { synchronized ( checkpointLock ) { partitionState . setOffset ( offset ) ; } } } | Emits a record attaching a timestamp to it . |
14,622 | private void emitRecordWithTimestampAndPeriodicWatermark ( T record , KafkaTopicPartitionState < KPH > partitionState , long offset , long kafkaEventTimestamp ) { @ SuppressWarnings ( "unchecked" ) final KafkaTopicPartitionStateWithPeriodicWatermarks < T , KPH > withWatermarksState = ( KafkaTopicPartitionStateWithPeriodicWatermarks < T , KPH > ) partitionState ; final long timestamp ; synchronized ( withWatermarksState ) { timestamp = withWatermarksState . getTimestampForRecord ( record , kafkaEventTimestamp ) ; } synchronized ( checkpointLock ) { sourceContext . collectWithTimestamp ( record , timestamp ) ; partitionState . setOffset ( offset ) ; } } | Record emission if a timestamp will be attached from an assigner that is also a periodic watermark generator . |
14,623 | private void emitRecordWithTimestampAndPunctuatedWatermark ( T record , KafkaTopicPartitionState < KPH > partitionState , long offset , long kafkaEventTimestamp ) { @ SuppressWarnings ( "unchecked" ) final KafkaTopicPartitionStateWithPunctuatedWatermarks < T , KPH > withWatermarksState = ( KafkaTopicPartitionStateWithPunctuatedWatermarks < T , KPH > ) partitionState ; final long timestamp = withWatermarksState . getTimestampForRecord ( record , kafkaEventTimestamp ) ; final Watermark newWatermark = withWatermarksState . checkAndGetNewWatermark ( record , timestamp ) ; synchronized ( checkpointLock ) { sourceContext . collectWithTimestamp ( record , timestamp ) ; partitionState . setOffset ( offset ) ; } if ( newWatermark != null ) { updateMinPunctuatedWatermark ( newWatermark ) ; } } | Record emission if a timestamp will be attached from an assigner that is also a punctuated watermark generator . |
14,624 | private void updateMinPunctuatedWatermark ( Watermark nextWatermark ) { if ( nextWatermark . getTimestamp ( ) > maxWatermarkSoFar ) { long newMin = Long . MAX_VALUE ; for ( KafkaTopicPartitionState < ? > state : subscribedPartitionStates ) { @ SuppressWarnings ( "unchecked" ) final KafkaTopicPartitionStateWithPunctuatedWatermarks < T , KPH > withWatermarksState = ( KafkaTopicPartitionStateWithPunctuatedWatermarks < T , KPH > ) state ; newMin = Math . min ( newMin , withWatermarksState . getCurrentPartitionWatermark ( ) ) ; } if ( newMin > maxWatermarkSoFar ) { synchronized ( checkpointLock ) { if ( newMin > maxWatermarkSoFar ) { maxWatermarkSoFar = newMin ; sourceContext . emitWatermark ( new Watermark ( newMin ) ) ; } } } } } | Checks whether a new per - partition watermark is also a new cross - partition watermark . |
14,625 | public Elasticsearch host ( String hostname , int port , String protocol ) { final Host host = new Host ( Preconditions . checkNotNull ( hostname ) , port , Preconditions . checkNotNull ( protocol ) ) ; hosts . add ( host ) ; return this ; } | Adds an Elasticsearch host to connect to . Required . |
14,626 | public Elasticsearch failureHandlerCustom ( Class < ? extends ActionRequestFailureHandler > failureHandlerClass ) { internalProperties . putString ( CONNECTOR_FAILURE_HANDLER , ElasticsearchValidator . CONNECTOR_FAILURE_HANDLER_VALUE_CUSTOM ) ; internalProperties . putClass ( CONNECTOR_FAILURE_HANDLER_CLASS , failureHandlerClass ) ; return this ; } | Configures a failure handling strategy in case a request to Elasticsearch fails . |
14,627 | public Elasticsearch bulkFlushMaxSize ( String maxSize ) { internalProperties . putMemorySize ( CONNECTOR_BULK_FLUSH_MAX_SIZE , MemorySize . parse ( maxSize , MemorySize . MemoryUnit . BYTES ) ) ; return this ; } | Configures how to buffer elements before sending them in bulk to the cluster for efficiency . |
14,628 | public Set < String > generateIdsToAbort ( ) { Set < String > idsToAbort = new HashSet < > ( ) ; for ( int i = 0 ; i < safeScaleDownFactor ; i ++ ) { idsToAbort . addAll ( generateIdsToUse ( i * poolSize * totalNumberOfSubtasks ) ) ; } return idsToAbort ; } | If we have to abort previous transactional id in case of restart after a failure BEFORE first checkpoint completed we don t know what was the parallelism used in previous attempt . In that case we must guess the ids range to abort based on current configured pool size current parallelism and safeScaleDownFactor . |
14,629 | public void registerTableSource ( String name ) { Preconditions . checkNotNull ( name ) ; TableSource < ? > tableSource = TableFactoryUtil . findAndCreateTableSource ( this ) ; tableEnv . registerTableSource ( name , tableSource ) ; } | Searches for the specified table source configures it accordingly and registers it as a table under the given name . |
14,630 | public void registerTableSink ( String name ) { Preconditions . checkNotNull ( name ) ; TableSink < ? > tableSink = TableFactoryUtil . findAndCreateTableSink ( this ) ; tableEnv . registerTableSink ( name , tableSink ) ; } | Searches for the specified table sink configures it accordingly and registers it as a table under the given name . |
14,631 | public D withFormat ( FormatDescriptor format ) { formatDescriptor = Optional . of ( Preconditions . checkNotNull ( format ) ) ; return ( D ) this ; } | Specifies the format that defines how to read data from a connector . |
14,632 | public D withSchema ( Schema schema ) { schemaDescriptor = Optional . of ( Preconditions . checkNotNull ( schema ) ) ; return ( D ) this ; } | Specifies the resulting table schema . |
14,633 | private List < Map < StreamStateHandle , OperatorStateHandle > > initMergeMapList ( List < List < OperatorStateHandle > > parallelSubtaskStates ) { int parallelism = parallelSubtaskStates . size ( ) ; final List < Map < StreamStateHandle , OperatorStateHandle > > mergeMapList = new ArrayList < > ( parallelism ) ; for ( List < OperatorStateHandle > previousParallelSubtaskState : parallelSubtaskStates ) { mergeMapList . add ( previousParallelSubtaskState . stream ( ) . collect ( Collectors . toMap ( OperatorStateHandle :: getDelegateStateHandle , Function . identity ( ) ) ) ) ; } return mergeMapList ; } | Init the the list of StreamStateHandle - > OperatorStateHandle map with given parallelSubtaskStates when parallelism not changed . |
14,634 | private Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > collectUnionStates ( List < List < OperatorStateHandle > > parallelSubtaskStates ) { Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > unionStates = new HashMap < > ( parallelSubtaskStates . size ( ) ) ; for ( List < OperatorStateHandle > subTaskState : parallelSubtaskStates ) { for ( OperatorStateHandle operatorStateHandle : subTaskState ) { if ( operatorStateHandle == null ) { continue ; } final Set < Map . Entry < String , OperatorStateHandle . StateMetaInfo > > partitionOffsetEntries = operatorStateHandle . getStateNameToPartitionOffsets ( ) . entrySet ( ) ; partitionOffsetEntries . stream ( ) . filter ( entry -> entry . getValue ( ) . getDistributionMode ( ) . equals ( OperatorStateHandle . Mode . UNION ) ) . forEach ( entry -> { List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > stateLocations = unionStates . computeIfAbsent ( entry . getKey ( ) , k -> new ArrayList < > ( parallelSubtaskStates . size ( ) * partitionOffsetEntries . size ( ) ) ) ; stateLocations . add ( Tuple2 . of ( operatorStateHandle . getDelegateStateHandle ( ) , entry . getValue ( ) ) ) ; } ) ; } } return unionStates ; } | Collect union states from given parallelSubtaskStates . |
14,635 | @ SuppressWarnings ( "unchecked, rawtype" ) private GroupByStateNameResults groupByStateMode ( List < List < OperatorStateHandle > > previousParallelSubtaskStates ) { EnumMap < OperatorStateHandle . Mode , Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > > nameToStateByMode = new EnumMap < > ( OperatorStateHandle . Mode . class ) ; for ( OperatorStateHandle . Mode mode : OperatorStateHandle . Mode . values ( ) ) { nameToStateByMode . put ( mode , new HashMap < > ( ) ) ; } for ( List < OperatorStateHandle > previousParallelSubtaskState : previousParallelSubtaskStates ) { for ( OperatorStateHandle operatorStateHandle : previousParallelSubtaskState ) { if ( operatorStateHandle == null ) { continue ; } final Set < Map . Entry < String , OperatorStateHandle . StateMetaInfo > > partitionOffsetEntries = operatorStateHandle . getStateNameToPartitionOffsets ( ) . entrySet ( ) ; for ( Map . Entry < String , OperatorStateHandle . StateMetaInfo > e : partitionOffsetEntries ) { OperatorStateHandle . StateMetaInfo metaInfo = e . getValue ( ) ; Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > nameToState = nameToStateByMode . get ( metaInfo . getDistributionMode ( ) ) ; List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > stateLocations = nameToState . computeIfAbsent ( e . getKey ( ) , k -> new ArrayList < > ( previousParallelSubtaskStates . size ( ) * partitionOffsetEntries . size ( ) ) ) ; stateLocations . add ( Tuple2 . of ( operatorStateHandle . getDelegateStateHandle ( ) , e . getValue ( ) ) ) ; } } } return new GroupByStateNameResults ( nameToStateByMode ) ; } | Group by the different named states . |
14,636 | private List < Map < StreamStateHandle , OperatorStateHandle > > repartition ( GroupByStateNameResults nameToStateByMode , int newParallelism ) { List < Map < StreamStateHandle , OperatorStateHandle > > mergeMapList = new ArrayList < > ( newParallelism ) ; for ( int i = 0 ; i < newParallelism ; ++ i ) { mergeMapList . add ( new HashMap < > ( ) ) ; } Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > nameToDistributeState = nameToStateByMode . getByMode ( OperatorStateHandle . Mode . SPLIT_DISTRIBUTE ) ; repartitionSplitState ( nameToDistributeState , newParallelism , mergeMapList ) ; Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > nameToUnionState = nameToStateByMode . getByMode ( OperatorStateHandle . Mode . UNION ) ; repartitionUnionState ( nameToUnionState , mergeMapList ) ; Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > nameToBroadcastState = nameToStateByMode . getByMode ( OperatorStateHandle . Mode . BROADCAST ) ; repartitionBroadcastState ( nameToBroadcastState , mergeMapList ) ; return mergeMapList ; } | Repartition all named states . |
14,637 | private void repartitionSplitState ( Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > nameToDistributeState , int newParallelism , List < Map < StreamStateHandle , OperatorStateHandle > > mergeMapList ) { int startParallelOp = 0 ; for ( Map . Entry < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > e : nameToDistributeState . entrySet ( ) ) { List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > current = e . getValue ( ) ; int totalPartitions = 0 ; for ( Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > offsets : current ) { totalPartitions += offsets . f1 . getOffsets ( ) . length ; } int lstIdx = 0 ; int offsetIdx = 0 ; int baseFraction = totalPartitions / newParallelism ; int remainder = totalPartitions % newParallelism ; int newStartParallelOp = startParallelOp ; for ( int i = 0 ; i < newParallelism ; ++ i ) { int parallelOpIdx = ( i + startParallelOp ) % newParallelism ; int numberOfPartitionsToAssign = baseFraction ; if ( remainder > 0 ) { ++ numberOfPartitionsToAssign ; -- remainder ; } else if ( remainder == 0 ) { newStartParallelOp = parallelOpIdx ; -- remainder ; } while ( numberOfPartitionsToAssign > 0 ) { Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > handleWithOffsets = current . get ( lstIdx ) ; long [ ] offsets = handleWithOffsets . f1 . getOffsets ( ) ; int remaining = offsets . length - offsetIdx ; long [ ] offs ; if ( remaining > numberOfPartitionsToAssign ) { offs = Arrays . copyOfRange ( offsets , offsetIdx , offsetIdx + numberOfPartitionsToAssign ) ; offsetIdx += numberOfPartitionsToAssign ; } else { if ( OPTIMIZE_MEMORY_USE ) { handleWithOffsets . f1 = null ; } offs = Arrays . copyOfRange ( offsets , offsetIdx , offsets . length ) ; offsetIdx = 0 ; ++ lstIdx ; } numberOfPartitionsToAssign -= remaining ; Map < StreamStateHandle , OperatorStateHandle > mergeMap = mergeMapList . get ( parallelOpIdx ) ; OperatorStateHandle operatorStateHandle = mergeMap . get ( handleWithOffsets . f0 ) ; if ( operatorStateHandle == null ) { operatorStateHandle = new OperatorStreamStateHandle ( new HashMap < > ( nameToDistributeState . size ( ) ) , handleWithOffsets . f0 ) ; mergeMap . put ( handleWithOffsets . f0 , operatorStateHandle ) ; } operatorStateHandle . getStateNameToPartitionOffsets ( ) . put ( e . getKey ( ) , new OperatorStateHandle . StateMetaInfo ( offs , OperatorStateHandle . Mode . SPLIT_DISTRIBUTE ) ) ; } } startParallelOp = newStartParallelOp ; e . setValue ( null ) ; } } | Repartition SPLIT_DISTRIBUTE state . |
14,638 | private void repartitionUnionState ( Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > unionState , List < Map < StreamStateHandle , OperatorStateHandle > > mergeMapList ) { for ( Map < StreamStateHandle , OperatorStateHandle > mergeMap : mergeMapList ) { for ( Map . Entry < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > e : unionState . entrySet ( ) ) { for ( Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > handleWithMetaInfo : e . getValue ( ) ) { OperatorStateHandle operatorStateHandle = mergeMap . get ( handleWithMetaInfo . f0 ) ; if ( operatorStateHandle == null ) { operatorStateHandle = new OperatorStreamStateHandle ( new HashMap < > ( unionState . size ( ) ) , handleWithMetaInfo . f0 ) ; mergeMap . put ( handleWithMetaInfo . f0 , operatorStateHandle ) ; } operatorStateHandle . getStateNameToPartitionOffsets ( ) . put ( e . getKey ( ) , handleWithMetaInfo . f1 ) ; } } } } | Repartition UNION state . |
14,639 | private void repartitionBroadcastState ( Map < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > broadcastState , List < Map < StreamStateHandle , OperatorStateHandle > > mergeMapList ) { int newParallelism = mergeMapList . size ( ) ; for ( int i = 0 ; i < newParallelism ; ++ i ) { final Map < StreamStateHandle , OperatorStateHandle > mergeMap = mergeMapList . get ( i ) ; for ( Map . Entry < String , List < Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > > > e : broadcastState . entrySet ( ) ) { int previousParallelism = e . getValue ( ) . size ( ) ; Tuple2 < StreamStateHandle , OperatorStateHandle . StateMetaInfo > handleWithMetaInfo = e . getValue ( ) . get ( i % previousParallelism ) ; OperatorStateHandle operatorStateHandle = mergeMap . get ( handleWithMetaInfo . f0 ) ; if ( operatorStateHandle == null ) { operatorStateHandle = new OperatorStreamStateHandle ( new HashMap < > ( broadcastState . size ( ) ) , handleWithMetaInfo . f0 ) ; mergeMap . put ( handleWithMetaInfo . f0 , operatorStateHandle ) ; } operatorStateHandle . getStateNameToPartitionOffsets ( ) . put ( e . getKey ( ) , handleWithMetaInfo . f1 ) ; } } } | Repartition BROADCAST state . |
14,640 | private int binarySearch ( T record ) { int low = 0 ; int high = this . boundaries . length - 1 ; typeComparator . extractKeys ( record , keys , 0 ) ; while ( low <= high ) { final int mid = ( low + high ) >>> 1 ; final int result = compareKeys ( flatComparators , keys , this . boundaries [ mid ] ) ; if ( result > 0 ) { low = mid + 1 ; } else if ( result < 0 ) { high = mid - 1 ; } else { return mid ; } } return low ; } | Search the range index of input record . |
14,641 | public void serializeToPagesWithoutLength ( BinaryRow record , AbstractPagedOutputView out ) throws IOException { int remainSize = record . getSizeInBytes ( ) ; int posInSegOfRecord = record . getOffset ( ) ; int segmentSize = record . getSegments ( ) [ 0 ] . size ( ) ; for ( MemorySegment segOfRecord : record . getSegments ( ) ) { int nWrite = Math . min ( segmentSize - posInSegOfRecord , remainSize ) ; assert nWrite > 0 ; out . write ( segOfRecord , posInSegOfRecord , nWrite ) ; posInSegOfRecord = 0 ; remainSize -= nWrite ; if ( remainSize == 0 ) { break ; } } checkArgument ( remainSize == 0 ) ; } | Serialize row to pages without row length . The caller should make sure that the fixed - length parit can fit in output s current segment no skip check will be done here . |
14,642 | public void copyFromPagesToView ( AbstractPagedInputView source , DataOutputView target ) throws IOException { checkSkipReadForFixLengthPart ( source ) ; int length = source . readInt ( ) ; target . writeInt ( length ) ; target . write ( source , length ) ; } | Copy a binaryRow which stored in paged input view to output view . |
14,643 | public void setDriverKeyInfo ( FieldList keys , int id ) { this . setDriverKeyInfo ( keys , getTrueArray ( keys . size ( ) ) , id ) ; } | Sets the key field indexes for the specified driver comparator . |
14,644 | public void setDriverKeyInfo ( FieldList keys , boolean [ ] sortOrder , int id ) { if ( id < 0 || id >= driverKeys . length ) { throw new CompilerException ( "Invalid id for driver key information. DriverStrategy requires only " + super . getDriverStrategy ( ) . getNumRequiredComparators ( ) + " comparators." ) ; } this . driverKeys [ id ] = keys ; this . driverSortOrders [ id ] = sortOrder ; } | Sets the key field information for the specified driver comparator . |
14,645 | private void addContender ( EmbeddedLeaderElectionService service , LeaderContender contender ) { synchronized ( lock ) { checkState ( ! shutdown , "leader election service is shut down" ) ; checkState ( ! service . running , "leader election service is already started" ) ; try { if ( ! allLeaderContenders . add ( service ) ) { throw new IllegalStateException ( "leader election service was added to this service multiple times" ) ; } service . contender = contender ; service . running = true ; updateLeader ( ) . whenComplete ( ( aVoid , throwable ) -> { if ( throwable != null ) { fatalError ( throwable ) ; } } ) ; } catch ( Throwable t ) { fatalError ( t ) ; } } } | Callback from leader contenders when they start their service . |
14,646 | private void removeContender ( EmbeddedLeaderElectionService service ) { synchronized ( lock ) { if ( ! service . running || shutdown ) { return ; } try { if ( ! allLeaderContenders . remove ( service ) ) { throw new IllegalStateException ( "leader election service does not belong to this service" ) ; } service . contender = null ; service . running = false ; service . isLeader = false ; if ( currentLeaderConfirmed == service ) { currentLeaderConfirmed = null ; currentLeaderSessionId = null ; currentLeaderAddress = null ; } if ( currentLeaderProposed == service ) { currentLeaderProposed = null ; currentLeaderSessionId = null ; } updateLeader ( ) . whenComplete ( ( aVoid , throwable ) -> { if ( throwable != null ) { fatalError ( throwable ) ; } } ) ; } catch ( Throwable t ) { fatalError ( t ) ; } } } | Callback from leader contenders when they stop their service . |
14,647 | private void confirmLeader ( final EmbeddedLeaderElectionService service , final UUID leaderSessionId ) { synchronized ( lock ) { if ( ! service . running || shutdown ) { return ; } try { if ( service == currentLeaderProposed && currentLeaderSessionId . equals ( leaderSessionId ) ) { final String address = service . contender . getAddress ( ) ; LOG . info ( "Received confirmation of leadership for leader {} , session={}" , address , leaderSessionId ) ; currentLeaderConfirmed = service ; currentLeaderAddress = address ; currentLeaderProposed = null ; notifyAllListeners ( address , leaderSessionId ) ; } else { LOG . debug ( "Received confirmation of leadership for a stale leadership grant. Ignoring." ) ; } } catch ( Throwable t ) { fatalError ( t ) ; } } } | Callback from leader contenders when they confirm a leader grant . |
14,648 | private static Collection < String > getAvailableMetrics ( Collection < ? extends MetricStore . ComponentMetricStore > stores ) { Set < String > uniqueMetrics = new HashSet < > ( 32 ) ; for ( MetricStore . ComponentMetricStore store : stores ) { uniqueMetrics . addAll ( store . metrics . keySet ( ) ) ; } return uniqueMetrics ; } | Returns a JSON string containing a list of all available metrics in the given stores . Effectively this method maps the union of all key - sets to JSON . |
14,649 | private AggregatedMetricsResponseBody getAggregatedMetricValues ( Collection < ? extends MetricStore . ComponentMetricStore > stores , List < String > requestedMetrics , MetricAccumulatorFactory requestedAggregationsFactories ) { Collection < AggregatedMetric > aggregatedMetrics = new ArrayList < > ( requestedMetrics . size ( ) ) ; for ( String requestedMetric : requestedMetrics ) { final Collection < Double > values = new ArrayList < > ( stores . size ( ) ) ; try { for ( MetricStore . ComponentMetricStore store : stores ) { String stringValue = store . metrics . get ( requestedMetric ) ; if ( stringValue != null ) { values . add ( Double . valueOf ( stringValue ) ) ; } } } catch ( NumberFormatException nfe ) { log . warn ( "The metric {} is not numeric and can't be aggregated." , requestedMetric , nfe ) ; continue ; } if ( ! values . isEmpty ( ) ) { Iterator < Double > valuesIterator = values . iterator ( ) ; MetricAccumulator acc = requestedAggregationsFactories . get ( requestedMetric , valuesIterator . next ( ) ) ; valuesIterator . forEachRemaining ( acc :: add ) ; aggregatedMetrics . add ( acc . get ( ) ) ; } else { return new AggregatedMetricsResponseBody ( Collections . emptyList ( ) ) ; } } return new AggregatedMetricsResponseBody ( aggregatedMetrics ) ; } | Extracts and aggregates all requested metrics from the given metric stores and maps the result to a JSON string . |
14,650 | private static void setDeserializer ( Properties props ) { final String deSerName = ByteArrayDeserializer . class . getName ( ) ; Object keyDeSer = props . get ( ConsumerConfig . KEY_DESERIALIZER_CLASS_CONFIG ) ; Object valDeSer = props . get ( ConsumerConfig . VALUE_DESERIALIZER_CLASS_CONFIG ) ; if ( keyDeSer != null && ! keyDeSer . equals ( deSerName ) ) { LOG . warn ( "Ignoring configured key DeSerializer ({})" , ConsumerConfig . KEY_DESERIALIZER_CLASS_CONFIG ) ; } if ( valDeSer != null && ! valDeSer . equals ( deSerName ) ) { LOG . warn ( "Ignoring configured value DeSerializer ({})" , ConsumerConfig . VALUE_DESERIALIZER_CLASS_CONFIG ) ; } props . put ( ConsumerConfig . KEY_DESERIALIZER_CLASS_CONFIG , deSerName ) ; props . put ( ConsumerConfig . VALUE_DESERIALIZER_CLASS_CONFIG , deSerName ) ; } | Makes sure that the ByteArrayDeserializer is registered in the Kafka properties . |
14,651 | public void persist ( ) throws Exception { if ( ! mapping . equals ( initialMapping ) ) { state . clear ( ) ; for ( Map . Entry < W , W > window : mapping . entrySet ( ) ) { state . add ( new Tuple2 < > ( window . getKey ( ) , window . getValue ( ) ) ) ; } } } | Persist the updated mapping to the given state if the mapping changed since initialization . |
14,652 | private org . apache . hadoop . conf . Configuration loadHadoopConfigFromFlink ( ) { org . apache . hadoop . conf . Configuration hadoopConfig = new org . apache . hadoop . conf . Configuration ( ) ; for ( String key : flinkConfig . keySet ( ) ) { for ( String prefix : flinkConfigPrefixes ) { if ( key . startsWith ( prefix ) ) { String newKey = hadoopConfigPrefix + key . substring ( prefix . length ( ) ) ; String newValue = fixHadoopConfig ( key , flinkConfig . getString ( key , null ) ) ; hadoopConfig . set ( newKey , newValue ) ; LOG . debug ( "Adding Flink config entry for {} as {} to Hadoop config" , key , newKey ) ; } } } return hadoopConfig ; } | add additional config entries from the Flink config to the Hadoop config |
14,653 | private org . apache . hadoop . conf . Configuration mirrorCertainHadoopConfig ( org . apache . hadoop . conf . Configuration hadoopConfig ) { for ( String [ ] mirrored : mirroredConfigKeys ) { String value = hadoopConfig . get ( mirrored [ 0 ] , null ) ; if ( value != null ) { hadoopConfig . set ( mirrored [ 1 ] , value ) ; } } return hadoopConfig ; } | with different keys |
14,654 | private static boolean waitUntilLeaseIsRevoked ( final FileSystem fs , final Path path ) throws IOException { Preconditions . checkState ( fs instanceof DistributedFileSystem ) ; final DistributedFileSystem dfs = ( DistributedFileSystem ) fs ; dfs . recoverLease ( path ) ; final Deadline deadline = Deadline . now ( ) . plus ( Duration . ofMillis ( LEASE_TIMEOUT ) ) ; final StopWatch sw = new StopWatch ( ) ; sw . start ( ) ; boolean isClosed = dfs . isFileClosed ( path ) ; while ( ! isClosed && deadline . hasTimeLeft ( ) ) { try { Thread . sleep ( 500L ) ; } catch ( InterruptedException e1 ) { throw new IOException ( "Recovering the lease failed: " , e1 ) ; } isClosed = dfs . isFileClosed ( path ) ; } return isClosed ; } | Called when resuming execution after a failure and waits until the lease of the file we are resuming is free . |
14,655 | public CompletableFuture < Void > onStop ( ) { log . info ( "Stopping TaskExecutor {}." , getAddress ( ) ) ; Throwable throwable = null ; if ( resourceManagerConnection != null ) { resourceManagerConnection . close ( ) ; } for ( JobManagerConnection jobManagerConnection : jobManagerConnections . values ( ) ) { try { disassociateFromJobManager ( jobManagerConnection , new FlinkException ( "The TaskExecutor is shutting down." ) ) ; } catch ( Throwable t ) { throwable = ExceptionUtils . firstOrSuppressed ( t , throwable ) ; } } jobManagerHeartbeatManager . stop ( ) ; resourceManagerHeartbeatManager . stop ( ) ; try { stopTaskExecutorServices ( ) ; } catch ( Exception e ) { throwable = ExceptionUtils . firstOrSuppressed ( e , throwable ) ; } if ( throwable != null ) { return FutureUtils . completedExceptionally ( new FlinkException ( "Error while shutting the TaskExecutor down." , throwable ) ) ; } else { log . info ( "Stopped TaskExecutor {}." , getAddress ( ) ) ; return CompletableFuture . completedFuture ( null ) ; } } | Called to shut down the TaskManager . The method closes all TaskManager services . |
14,656 | public Optional < OperatorBackPressureStats > getOperatorBackPressureStats ( ExecutionJobVertex vertex ) { synchronized ( lock ) { final OperatorBackPressureStats stats = operatorStatsCache . getIfPresent ( vertex ) ; if ( stats == null || backPressureStatsRefreshInterval <= System . currentTimeMillis ( ) - stats . getEndTimestamp ( ) ) { triggerStackTraceSampleInternal ( vertex ) ; } return Optional . ofNullable ( stats ) ; } } | Returns back pressure statistics for a operator . Automatically triggers stack trace sampling if statistics are not available or outdated . |
14,657 | private boolean triggerStackTraceSampleInternal ( final ExecutionJobVertex vertex ) { assert ( Thread . holdsLock ( lock ) ) ; if ( shutDown ) { return false ; } if ( ! pendingStats . contains ( vertex ) && ! vertex . getGraph ( ) . getState ( ) . isGloballyTerminalState ( ) ) { Executor executor = vertex . getGraph ( ) . getFutureExecutor ( ) ; if ( executor != null ) { pendingStats . add ( vertex ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Triggering stack trace sample for tasks: " + Arrays . toString ( vertex . getTaskVertices ( ) ) ) ; } CompletableFuture < StackTraceSample > sample = coordinator . triggerStackTraceSample ( vertex . getTaskVertices ( ) , numSamples , delayBetweenSamples , MAX_STACK_TRACE_DEPTH ) ; sample . handleAsync ( new StackTraceSampleCompletionCallback ( vertex ) , executor ) ; return true ; } } return false ; } | Triggers a stack trace sample for a operator to gather the back pressure statistics . If there is a sample in progress for the operator the call is ignored . |
14,658 | private static String [ ] getCLDBLocations ( String authority ) throws IOException { String maprHome = System . getenv ( MAPR_HOME_ENV ) ; if ( maprHome == null ) { maprHome = DEFAULT_MAPR_HOME ; } final File maprClusterConf = new File ( maprHome , MAPR_CLUSTER_CONF_FILE ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( String . format ( "Trying to retrieve MapR cluster configuration from %s" , maprClusterConf ) ) ; } if ( ! maprClusterConf . exists ( ) ) { throw new IOException ( "Could not find CLDB configuration '" + maprClusterConf . getAbsolutePath ( ) + "', assuming MapR home is '" + maprHome + "'." ) ; } try ( BufferedReader br = new BufferedReader ( new FileReader ( maprClusterConf ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { line = line . trim ( ) ; line = line . replace ( '\t' , ' ' ) ; final String [ ] fields = line . split ( " " ) ; if ( fields . length < 1 ) { continue ; } final String clusterName = fields [ 0 ] ; if ( ! clusterName . equals ( authority ) ) { continue ; } final List < String > cldbLocations = new ArrayList < > ( ) ; for ( int i = 1 ; i < fields . length ; ++ i ) { if ( ! fields [ i ] . isEmpty ( ) && ! fields [ i ] . contains ( "=" ) ) { cldbLocations . add ( fields [ i ] ) ; } } if ( cldbLocations . isEmpty ( ) ) { throw new IOException ( String . format ( "%s contains entry for cluster %s but no CLDB locations." , maprClusterConf , authority ) ) ; } return cldbLocations . toArray ( new String [ cldbLocations . size ( ) ] ) ; } } throw new IOException ( String . format ( "Unable to find CLDB locations for cluster %s" , authority ) ) ; } | Retrieves the CLDB locations for the given MapR cluster name . |
14,659 | @ SuppressWarnings ( "unchecked" ) public static < X > PrimitiveArrayTypeInfo < X > getInfoFor ( Class < X > type ) { if ( ! type . isArray ( ) ) { throw new InvalidTypesException ( "The given class is no array." ) ; } return ( PrimitiveArrayTypeInfo < X > ) TYPES . get ( type ) ; } | Tries to get the PrimitiveArrayTypeInfo for an array . Returns null if the type is an array but the component type is not a primitive type . |
14,660 | static void adjustAutoCommitConfig ( Properties properties , OffsetCommitMode offsetCommitMode ) { if ( offsetCommitMode == OffsetCommitMode . ON_CHECKPOINTS || offsetCommitMode == OffsetCommitMode . DISABLED ) { properties . setProperty ( ConsumerConfig . ENABLE_AUTO_COMMIT_CONFIG , "false" ) ; } } | Make sure that auto commit is disabled when our offset commit mode is ON_CHECKPOINTS . This overwrites whatever setting the user configured in the properties . |
14,661 | protected FlinkKafkaConsumerBase < T > setStartFromTimestamp ( long startupOffsetsTimestamp ) { checkArgument ( startupOffsetsTimestamp >= 0 , "The provided value for the startup offsets timestamp is invalid." ) ; long currentTimestamp = System . currentTimeMillis ( ) ; checkArgument ( startupOffsetsTimestamp <= currentTimestamp , "Startup time[%s] must be before current time[%s]." , startupOffsetsTimestamp , currentTimestamp ) ; this . startupMode = StartupMode . TIMESTAMP ; this . startupOffsetsTimestamp = startupOffsetsTimestamp ; this . specificStartupOffsets = null ; return this ; } | Version - specific subclasses which can expose the functionality should override and allow public access . |
14,662 | public SharedStateRegistryKey createSharedStateRegistryKeyFromFileName ( StateHandleID shId ) { return new SharedStateRegistryKey ( String . valueOf ( backendIdentifier ) + '-' + keyGroupRange , shId ) ; } | Create a unique key to register one of our shared state handles . |
14,663 | public static < L , R > Either < L , R > Left ( L value ) { return new Left < L , R > ( value ) ; } | Create a Left value of Either |
14,664 | public static < L , R > Either < L , R > Right ( R value ) { return new Right < L , R > ( value ) ; } | Create a Right value of Either |
14,665 | public Throwable unwrap ( ) { Throwable cause = getCause ( ) ; return ( cause instanceof WrappingRuntimeException ) ? ( ( WrappingRuntimeException ) cause ) . unwrap ( ) : cause ; } | Recursively unwraps this WrappingRuntimeException and its causes getting the first non wrapping exception . |
14,666 | private Kryo getKryoInstance ( ) { try { Class < ? > chillInstantiatorClazz = Class . forName ( "org.apache.flink.runtime.types.FlinkScalaKryoInstantiator" ) ; Object chillInstantiator = chillInstantiatorClazz . newInstance ( ) ; Method m = chillInstantiatorClazz . getMethod ( "newKryo" ) ; return ( Kryo ) m . invoke ( chillInstantiator ) ; } catch ( ClassNotFoundException | InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) { LOG . warn ( "Falling back to default Kryo serializer because Chill serializer couldn't be found." , e ) ; Kryo . DefaultInstantiatorStrategy initStrategy = new Kryo . DefaultInstantiatorStrategy ( ) ; initStrategy . setFallbackInstantiatorStrategy ( new StdInstantiatorStrategy ( ) ) ; Kryo kryo = new Kryo ( ) ; kryo . setInstantiatorStrategy ( initStrategy ) ; return kryo ; } } | Returns the Chill Kryo Serializer which is implicitly added to the classpath via flink - runtime . Falls back to the default Kryo serializer if it can t be found . |
14,667 | private static LinkedHashMap < String , KryoRegistration > buildKryoRegistrations ( Class < ? > serializedType , LinkedHashSet < Class < ? > > registeredTypes , LinkedHashMap < Class < ? > , Class < ? extends Serializer < ? > > > registeredTypesWithSerializerClasses , LinkedHashMap < Class < ? > , ExecutionConfig . SerializableSerializer < ? > > registeredTypesWithSerializers ) { final LinkedHashMap < String , KryoRegistration > kryoRegistrations = new LinkedHashMap < > ( ) ; kryoRegistrations . put ( serializedType . getName ( ) , new KryoRegistration ( serializedType ) ) ; for ( Class < ? > registeredType : checkNotNull ( registeredTypes ) ) { kryoRegistrations . put ( registeredType . getName ( ) , new KryoRegistration ( registeredType ) ) ; } for ( Map . Entry < Class < ? > , Class < ? extends Serializer < ? > > > registeredTypeWithSerializerClassEntry : checkNotNull ( registeredTypesWithSerializerClasses ) . entrySet ( ) ) { kryoRegistrations . put ( registeredTypeWithSerializerClassEntry . getKey ( ) . getName ( ) , new KryoRegistration ( registeredTypeWithSerializerClassEntry . getKey ( ) , registeredTypeWithSerializerClassEntry . getValue ( ) ) ) ; } for ( Map . Entry < Class < ? > , ExecutionConfig . SerializableSerializer < ? > > registeredTypeWithSerializerEntry : checkNotNull ( registeredTypesWithSerializers ) . entrySet ( ) ) { kryoRegistrations . put ( registeredTypeWithSerializerEntry . getKey ( ) . getName ( ) , new KryoRegistration ( registeredTypeWithSerializerEntry . getKey ( ) , registeredTypeWithSerializerEntry . getValue ( ) ) ) ; } AvroUtils . getAvroUtils ( ) . addAvroGenericDataArrayRegistration ( kryoRegistrations ) ; return kryoRegistrations ; } | Utility method that takes lists of registered types and their serializers and resolve them into a single list such that the result will resemble the final registration result in Kryo . |
14,668 | @ SuppressWarnings ( "unchecked" ) public < K , VV , EV > Graph < K , VV , EV > types ( Class < K > vertexKey , Class < VV > vertexValue , Class < EV > edgeValue ) { if ( edgeReader == null ) { throw new RuntimeException ( "The edge input file cannot be null!" ) ; } DataSet < Tuple3 < K , K , EV > > edges = edgeReader . types ( vertexKey , vertexKey , edgeValue ) ; if ( vertexReader != null ) { DataSet < Tuple2 < K , VV > > vertices = vertexReader . types ( vertexKey , vertexValue ) . name ( GraphCsvReader . class . getName ( ) ) ; return Graph . fromTupleDataSet ( vertices , edges , executionContext ) ; } else if ( mapper != null ) { return Graph . fromTupleDataSet ( edges , ( MapFunction < K , VV > ) mapper , executionContext ) ; } else { throw new RuntimeException ( "Vertex values have to be specified through a vertices input file" + "or a user-defined map function." ) ; } } | Creates a Graph from CSV input with vertex values and edge values . The vertex values are specified through a vertices input file or a user - defined map function . |
14,669 | public < K , EV > Graph < K , NullValue , EV > edgeTypes ( Class < K > vertexKey , Class < EV > edgeValue ) { if ( edgeReader == null ) { throw new RuntimeException ( "The edge input file cannot be null!" ) ; } DataSet < Tuple3 < K , K , EV > > edges = edgeReader . types ( vertexKey , vertexKey , edgeValue ) . name ( GraphCsvReader . class . getName ( ) ) ; return Graph . fromTupleDataSet ( edges , executionContext ) ; } | Creates a Graph from CSV input with edge values but without vertex values . |
14,670 | public < K > Graph < K , NullValue , NullValue > keyType ( Class < K > vertexKey ) { if ( edgeReader == null ) { throw new RuntimeException ( "The edge input file cannot be null!" ) ; } DataSet < Edge < K , NullValue > > edges = edgeReader . types ( vertexKey , vertexKey ) . name ( GraphCsvReader . class . getName ( ) ) . map ( new Tuple2ToEdgeMap < > ( ) ) . name ( "Type conversion" ) ; return Graph . fromDataSet ( edges , executionContext ) ; } | Creates a Graph from CSV input without vertex values or edge values . |
14,671 | @ SuppressWarnings ( { "serial" , "unchecked" } ) public < K , VV > Graph < K , VV , NullValue > vertexTypes ( Class < K > vertexKey , Class < VV > vertexValue ) { if ( edgeReader == null ) { throw new RuntimeException ( "The edge input file cannot be null!" ) ; } DataSet < Edge < K , NullValue > > edges = edgeReader . types ( vertexKey , vertexKey ) . name ( GraphCsvReader . class . getName ( ) ) . map ( new Tuple2ToEdgeMap < > ( ) ) . name ( "To Edge" ) ; if ( vertexReader != null ) { DataSet < Vertex < K , VV > > vertices = vertexReader . types ( vertexKey , vertexValue ) . name ( GraphCsvReader . class . getName ( ) ) . map ( new Tuple2ToVertexMap < > ( ) ) . name ( "Type conversion" ) ; return Graph . fromDataSet ( vertices , edges , executionContext ) ; } else if ( mapper != null ) { return Graph . fromDataSet ( edges , ( MapFunction < K , VV > ) mapper , executionContext ) ; } else { throw new RuntimeException ( "Vertex values have to be specified through a vertices input file" + "or a user-defined map function." ) ; } } | Creates a Graph from CSV input without edge values . The vertex values are specified through a vertices input file or a user - defined map function . If no vertices input file is provided the vertex IDs are automatically created from the edges input file . |
14,672 | public static void mergeHadoopConf ( JobConf jobConf ) { org . apache . flink . configuration . Configuration flinkConfiguration = GlobalConfiguration . loadConfiguration ( ) ; Configuration hadoopConf = getHadoopConfiguration ( flinkConfiguration ) ; for ( Map . Entry < String , String > e : hadoopConf ) { if ( jobConf . get ( e . getKey ( ) ) == null ) { jobConf . set ( e . getKey ( ) , e . getValue ( ) ) ; } } } | Merge HadoopConfiguration into JobConf . This is necessary for the HDFS configuration . |
14,673 | @ SuppressWarnings ( "unchecked" ) public CompletableFuture < StackTraceSample > triggerStackTraceSample ( ExecutionVertex [ ] tasksToSample , int numSamples , Time delayBetweenSamples , int maxStackTraceDepth ) { checkNotNull ( tasksToSample , "Tasks to sample" ) ; checkArgument ( tasksToSample . length >= 1 , "No tasks to sample" ) ; checkArgument ( numSamples >= 1 , "No number of samples" ) ; checkArgument ( maxStackTraceDepth >= 0 , "Negative maximum stack trace depth" ) ; ExecutionAttemptID [ ] triggerIds = new ExecutionAttemptID [ tasksToSample . length ] ; Execution [ ] executions = new Execution [ tasksToSample . length ] ; for ( int i = 0 ; i < triggerIds . length ; i ++ ) { Execution execution = tasksToSample [ i ] . getCurrentExecutionAttempt ( ) ; if ( execution != null && execution . getState ( ) == ExecutionState . RUNNING ) { executions [ i ] = execution ; triggerIds [ i ] = execution . getAttemptId ( ) ; } else { return FutureUtils . completedExceptionally ( new IllegalStateException ( "Task " + tasksToSample [ i ] . getTaskNameWithSubtaskIndex ( ) + " is not running." ) ) ; } } synchronized ( lock ) { if ( isShutDown ) { return FutureUtils . completedExceptionally ( new IllegalStateException ( "Shut down" ) ) ; } final int sampleId = sampleIdCounter ++ ; LOG . debug ( "Triggering stack trace sample {}" , sampleId ) ; final PendingStackTraceSample pending = new PendingStackTraceSample ( sampleId , triggerIds ) ; long expectedDuration = numSamples * delayBetweenSamples . toMilliseconds ( ) ; Time timeout = Time . milliseconds ( expectedDuration + sampleTimeout ) ; pendingSamples . put ( sampleId , pending ) ; for ( Execution execution : executions ) { final CompletableFuture < StackTraceSampleResponse > stackTraceSampleFuture = execution . requestStackTraceSample ( sampleId , numSamples , delayBetweenSamples , maxStackTraceDepth , timeout ) ; stackTraceSampleFuture . handleAsync ( ( StackTraceSampleResponse stackTraceSampleResponse , Throwable throwable ) -> { if ( stackTraceSampleResponse != null ) { collectStackTraces ( stackTraceSampleResponse . getSampleId ( ) , stackTraceSampleResponse . getExecutionAttemptID ( ) , stackTraceSampleResponse . getSamples ( ) ) ; } else { cancelStackTraceSample ( sampleId , throwable ) ; } return null ; } , executor ) ; } return pending . getStackTraceSampleFuture ( ) ; } } | Triggers a stack trace sample to all tasks . |
14,674 | public void cancelStackTraceSample ( int sampleId , Throwable cause ) { synchronized ( lock ) { if ( isShutDown ) { return ; } PendingStackTraceSample sample = pendingSamples . remove ( sampleId ) ; if ( sample != null ) { if ( cause != null ) { LOG . info ( "Cancelling sample " + sampleId , cause ) ; } else { LOG . info ( "Cancelling sample {}" , sampleId ) ; } sample . discard ( cause ) ; rememberRecentSampleId ( sampleId ) ; } } } | Cancels a pending sample . |
14,675 | public void shutDown ( ) { synchronized ( lock ) { if ( ! isShutDown ) { LOG . info ( "Shutting down stack trace sample coordinator." ) ; for ( PendingStackTraceSample pending : pendingSamples . values ( ) ) { pending . discard ( new RuntimeException ( "Shut down" ) ) ; } pendingSamples . clear ( ) ; isShutDown = true ; } } } | Shuts down the coordinator . |
14,676 | public void collectStackTraces ( int sampleId , ExecutionAttemptID executionId , List < StackTraceElement [ ] > stackTraces ) { synchronized ( lock ) { if ( isShutDown ) { return ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Collecting stack trace sample {} of task {}" , sampleId , executionId ) ; } PendingStackTraceSample pending = pendingSamples . get ( sampleId ) ; if ( pending != null ) { pending . collectStackTraces ( executionId , stackTraces ) ; if ( pending . isComplete ( ) ) { pendingSamples . remove ( sampleId ) ; rememberRecentSampleId ( sampleId ) ; pending . completePromiseAndDiscard ( ) ; } } else if ( recentPendingSamples . contains ( sampleId ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Received late stack trace sample {} of task {}" , sampleId , executionId ) ; } } else { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Unknown sample ID " + sampleId ) ; } } } } | Collects stack traces of a task . |
14,677 | public final < OUT > DataStreamSource < OUT > fromElements ( Class < OUT > type , OUT ... data ) { if ( data . length == 0 ) { throw new IllegalArgumentException ( "fromElements needs at least one element as argument" ) ; } TypeInformation < OUT > typeInfo ; try { typeInfo = TypeExtractor . getForClass ( type ) ; } catch ( Exception e ) { throw new RuntimeException ( "Could not create TypeInformation for type " + type . getName ( ) + "; please specify the TypeInformation manually via " + "StreamExecutionEnvironment#fromElements(Collection, TypeInformation)" , e ) ; } return fromCollection ( Arrays . asList ( data ) , typeInfo ) ; } | Creates a new data set that contains the given elements . The framework will determine the type according to the based type user supplied . The elements should be the same or be the subclass to the based type . The sequence of elements must not be empty . Note that this operation will result in a non - parallel data stream source i . e . a data stream source with a degree of parallelism one . |
14,678 | public < OUT > DataStreamSource < OUT > fromCollection ( Collection < OUT > data ) { Preconditions . checkNotNull ( data , "Collection must not be null" ) ; if ( data . isEmpty ( ) ) { throw new IllegalArgumentException ( "Collection must not be empty" ) ; } OUT first = data . iterator ( ) . next ( ) ; if ( first == null ) { throw new IllegalArgumentException ( "Collection must not contain null elements" ) ; } TypeInformation < OUT > typeInfo ; try { typeInfo = TypeExtractor . getForObject ( first ) ; } catch ( Exception e ) { throw new RuntimeException ( "Could not create TypeInformation for type " + first . getClass ( ) + "; please specify the TypeInformation manually via " + "StreamExecutionEnvironment#fromElements(Collection, TypeInformation)" , e ) ; } return fromCollection ( data , typeInfo ) ; } | Creates a data stream from the given non - empty collection . The type of the data stream is that of the elements in the collection . |
14,679 | public < OUT > DataStreamSource < OUT > fromCollection ( Collection < OUT > data , TypeInformation < OUT > typeInfo ) { Preconditions . checkNotNull ( data , "Collection must not be null" ) ; FromElementsFunction . checkCollection ( data , typeInfo . getTypeClass ( ) ) ; SourceFunction < OUT > function ; try { function = new FromElementsFunction < > ( typeInfo . createSerializer ( getConfig ( ) ) , data ) ; } catch ( IOException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } return addSource ( function , "Collection Source" , typeInfo ) . setParallelism ( 1 ) ; } | Creates a data stream from the given non - empty collection . |
14,680 | private < OUT > DataStreamSource < OUT > fromParallelCollection ( SplittableIterator < OUT > iterator , TypeInformation < OUT > typeInfo , String operatorName ) { return addSource ( new FromSplittableIteratorFunction < > ( iterator ) , operatorName , typeInfo ) ; } | private helper for passing different names |
14,681 | @ SuppressWarnings ( "deprecation" ) public DataStream < String > readFileStream ( String filePath , long intervalMillis , FileMonitoringFunction . WatchType watchType ) { DataStream < Tuple3 < String , Long , Long > > source = addSource ( new FileMonitoringFunction ( filePath , intervalMillis , watchType ) , "Read File Stream source" ) ; return source . flatMap ( new FileReadFunction ( ) ) ; } | Creates a data stream that contains the contents of file created while system watches the given path . The file will be read with the system s default character set . |
14,682 | public StreamQueryConfig withIdleStateRetentionTime ( Time minTime , Time maxTime ) { if ( maxTime . toMilliseconds ( ) - minTime . toMilliseconds ( ) < 300000 && ! ( maxTime . toMilliseconds ( ) == 0 && minTime . toMilliseconds ( ) == 0 ) ) { throw new IllegalArgumentException ( "Difference between minTime: " + minTime . toString ( ) + " and maxTime: " + maxTime . toString ( ) + "shoud be at least 5 minutes." ) ; } minIdleStateRetentionTime = minTime . toMilliseconds ( ) ; maxIdleStateRetentionTime = maxTime . toMilliseconds ( ) ; return this ; } | Specifies a minimum and a maximum time interval for how long idle state i . e . state which was not updated will be retained . State will never be cleared until it was idle for less than the minimum time and will never be kept if it was idle for more than the maximum time . |
14,683 | public static < T > DataSet < LongValue > count ( DataSet < T > input ) { return input . map ( new MapTo < > ( new LongValue ( 1 ) ) ) . returns ( LONG_VALUE_TYPE_INFO ) . name ( "Emit 1" ) . reduce ( new AddLongValue ( ) ) . name ( "Sum" ) ; } | Count the number of elements in a DataSet . |
14,684 | public static void install ( SecurityConfiguration config ) throws Exception { List < SecurityModule > modules = new ArrayList < > ( ) ; try { for ( SecurityModuleFactory moduleFactory : config . getSecurityModuleFactories ( ) ) { SecurityModule module = moduleFactory . createModule ( config ) ; if ( module != null ) { module . install ( ) ; modules . add ( module ) ; } } } catch ( Exception ex ) { throw new Exception ( "unable to establish the security context" , ex ) ; } installedModules = modules ; try { Class . forName ( "org.apache.hadoop.security.UserGroupInformation" , false , SecurityUtils . class . getClassLoader ( ) ) ; if ( ! ( installedContext instanceof NoOpSecurityContext ) ) { LOG . warn ( "overriding previous security context" ) ; } UserGroupInformation loginUser = UserGroupInformation . getLoginUser ( ) ; installedContext = new HadoopSecurityContext ( loginUser ) ; } catch ( ClassNotFoundException e ) { LOG . info ( "Cannot install HadoopSecurityContext because Hadoop cannot be found in the Classpath." ) ; } catch ( LinkageError e ) { LOG . error ( "Cannot install HadoopSecurityContext." , e ) ; } } | Installs a process - wide security configuration . |
14,685 | private static void writeHeader ( final ByteBuf buf , final MessageType messageType ) { buf . writeInt ( VERSION ) ; buf . writeInt ( messageType . ordinal ( ) ) ; } | Helper for serializing the header . |
14,686 | private static ByteBuf writePayload ( final ByteBufAllocator alloc , final long requestId , final MessageType messageType , final byte [ ] payload ) { final int frameLength = HEADER_LENGTH + REQUEST_ID_SIZE + payload . length ; final ByteBuf buf = alloc . ioBuffer ( frameLength + Integer . BYTES ) ; buf . writeInt ( frameLength ) ; writeHeader ( buf , messageType ) ; buf . writeLong ( requestId ) ; buf . writeBytes ( payload ) ; return buf ; } | Helper for serializing the messages . |
14,687 | byte [ ] [ ] getFamilyKeys ( ) { Charset c = Charset . forName ( charset ) ; byte [ ] [ ] familyKeys = new byte [ this . familyMap . size ( ) ] [ ] ; int i = 0 ; for ( String name : this . familyMap . keySet ( ) ) { familyKeys [ i ++ ] = name . getBytes ( c ) ; } return familyKeys ; } | Returns the HBase identifiers of all registered column families . |
14,688 | String [ ] getQualifierNames ( String family ) { Map < String , TypeInformation < ? > > qualifierMap = familyMap . get ( family ) ; if ( qualifierMap == null ) { throw new IllegalArgumentException ( "Family " + family + " does not exist in schema." ) ; } String [ ] qualifierNames = new String [ qualifierMap . size ( ) ] ; int i = 0 ; for ( String qualifier : qualifierMap . keySet ( ) ) { qualifierNames [ i ] = qualifier ; i ++ ; } return qualifierNames ; } | Returns the names of all registered column qualifiers of a specific column family . |
14,689 | byte [ ] [ ] getQualifierKeys ( String family ) { Map < String , TypeInformation < ? > > qualifierMap = familyMap . get ( family ) ; if ( qualifierMap == null ) { throw new IllegalArgumentException ( "Family " + family + " does not exist in schema." ) ; } Charset c = Charset . forName ( charset ) ; byte [ ] [ ] qualifierKeys = new byte [ qualifierMap . size ( ) ] [ ] ; int i = 0 ; for ( String name : qualifierMap . keySet ( ) ) { qualifierKeys [ i ++ ] = name . getBytes ( c ) ; } return qualifierKeys ; } | Returns the HBase identifiers of all registered column qualifiers for a specific column family . |
14,690 | TypeInformation < ? > [ ] getQualifierTypes ( String family ) { Map < String , TypeInformation < ? > > qualifierMap = familyMap . get ( family ) ; if ( qualifierMap == null ) { throw new IllegalArgumentException ( "Family " + family + " does not exist in schema." ) ; } TypeInformation < ? > [ ] typeInformation = new TypeInformation [ qualifierMap . size ( ) ] ; int i = 0 ; for ( TypeInformation < ? > typeInfo : qualifierMap . values ( ) ) { typeInformation [ i ] = typeInfo ; i ++ ; } return typeInformation ; } | Returns the types of all registered column qualifiers of a specific column family . |
14,691 | public String getString ( ConfigOption < String > configOption , String overrideDefault ) { Object o = getRawValueFromOption ( configOption ) ; return o == null ? overrideDefault : o . toString ( ) ; } | Returns the value associated with the given config option as a string . If no value is mapped under any key of the option it returns the specified default instead of the option s default value . |
14,692 | public int getInteger ( ConfigOption < Integer > configOption ) { Object o = getValueOrDefaultFromOption ( configOption ) ; return convertToInt ( o , configOption . defaultValue ( ) ) ; } | Returns the value associated with the given config option as an integer . |
14,693 | public int getInteger ( ConfigOption < Integer > configOption , int overrideDefault ) { Object o = getRawValueFromOption ( configOption ) ; if ( o == null ) { return overrideDefault ; } return convertToInt ( o , configOption . defaultValue ( ) ) ; } | Returns the value associated with the given config option as an integer . If no value is mapped under any key of the option it returns the specified default instead of the option s default value . |
14,694 | public long getLong ( ConfigOption < Long > configOption ) { Object o = getValueOrDefaultFromOption ( configOption ) ; return convertToLong ( o , configOption . defaultValue ( ) ) ; } | Returns the value associated with the given config option as a long integer . |
14,695 | public long getLong ( ConfigOption < Long > configOption , long overrideDefault ) { Object o = getRawValueFromOption ( configOption ) ; if ( o == null ) { return overrideDefault ; } return convertToLong ( o , configOption . defaultValue ( ) ) ; } | Returns the value associated with the given config option as a long integer . If no value is mapped under any key of the option it returns the specified default instead of the option s default value . |
14,696 | public boolean getBoolean ( ConfigOption < Boolean > configOption ) { Object o = getValueOrDefaultFromOption ( configOption ) ; return convertToBoolean ( o ) ; } | Returns the value associated with the given config option as a boolean . |
14,697 | public boolean getBoolean ( ConfigOption < Boolean > configOption , boolean overrideDefault ) { Object o = getRawValueFromOption ( configOption ) ; if ( o == null ) { return overrideDefault ; } return convertToBoolean ( o ) ; } | Returns the value associated with the given config option as a boolean . If no value is mapped under any key of the option it returns the specified default instead of the option s default value . |
14,698 | public float getFloat ( ConfigOption < Float > configOption ) { Object o = getValueOrDefaultFromOption ( configOption ) ; return convertToFloat ( o , configOption . defaultValue ( ) ) ; } | Returns the value associated with the given config option as a float . |
14,699 | public float getFloat ( ConfigOption < Float > configOption , float overrideDefault ) { Object o = getRawValueFromOption ( configOption ) ; if ( o == null ) { return overrideDefault ; } return convertToFloat ( o , configOption . defaultValue ( ) ) ; } | Returns the value associated with the given config option as a float . If no value is mapped under any key of the option it returns the specified default instead of the option s default value . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.