idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
14,700 | public String getValue ( ConfigOption < ? > configOption ) { Object o = getValueOrDefaultFromOption ( configOption ) ; return o == null ? null : o . toString ( ) ; } | Returns the value associated with the given config option as a string . |
14,701 | public < T extends Enum < T > > T getEnum ( final Class < T > enumClass , final ConfigOption < String > configOption ) { checkNotNull ( enumClass , "enumClass must not be null" ) ; checkNotNull ( configOption , "configOption must not be null" ) ; final String configValue = getString ( configOption ) ; try { return Enum . valueOf ( enumClass , configValue . toUpperCase ( Locale . ROOT ) ) ; } catch ( final IllegalArgumentException | NullPointerException e ) { final String errorMessage = String . format ( "Value for config option %s must be one of %s (was %s)" , configOption . key ( ) , Arrays . toString ( enumClass . getEnumConstants ( ) ) , configValue ) ; throw new IllegalArgumentException ( errorMessage , e ) ; } } | Returns the value associated with the given config option as an enum . |
14,702 | public void addAll ( Configuration other , String prefix ) { final StringBuilder bld = new StringBuilder ( ) ; bld . append ( prefix ) ; final int pl = bld . length ( ) ; synchronized ( this . confData ) { synchronized ( other . confData ) { for ( Map . Entry < String , Object > entry : other . confData . entrySet ( ) ) { bld . setLength ( pl ) ; bld . append ( entry . getKey ( ) ) ; this . confData . put ( bld . toString ( ) , entry . getValue ( ) ) ; } } } } | Adds all entries from the given configuration into this configuration . The keys are prepended with the given prefix . |
14,703 | public boolean contains ( ConfigOption < ? > configOption ) { synchronized ( this . confData ) { if ( this . confData . containsKey ( configOption . key ( ) ) ) { return true ; } else if ( configOption . hasFallbackKeys ( ) ) { for ( FallbackKey fallbackKey : configOption . fallbackKeys ( ) ) { if ( this . confData . containsKey ( fallbackKey . getKey ( ) ) ) { loggingFallback ( fallbackKey , configOption ) ; return true ; } } } return false ; } } | Checks whether there is an entry for the given config option . |
14,704 | public < T > boolean removeConfig ( ConfigOption < T > configOption ) { synchronized ( this . confData ) { Object oldValue = this . confData . remove ( configOption . key ( ) ) ; if ( oldValue == null ) { for ( FallbackKey fallbackKey : configOption . fallbackKeys ( ) ) { oldValue = this . confData . remove ( fallbackKey . getKey ( ) ) ; if ( oldValue != null ) { loggingFallback ( fallbackKey , configOption ) ; return true ; } } return false ; } return true ; } } | Removes given config option from the configuration . |
14,705 | public void uploadPart ( RefCountedFSOutputStream file ) throws IOException { checkState ( file . isClosed ( ) ) ; final CompletableFuture < PartETag > future = new CompletableFuture < > ( ) ; uploadsInProgress . add ( future ) ; final long partLength = file . getPos ( ) ; currentUploadInfo . registerNewPart ( partLength ) ; file . retain ( ) ; uploadThreadPool . execute ( new UploadTask ( s3AccessHelper , currentUploadInfo , file , future ) ) ; } | Adds a part to the uploads without any size limitations . |
14,706 | public S3Recoverable snapshotAndGetRecoverable ( final RefCountedFSOutputStream incompletePartFile ) throws IOException { final String incompletePartObjectName = safelyUploadSmallPart ( incompletePartFile ) ; awaitPendingPartsUpload ( ) ; final String objectName = currentUploadInfo . getObjectName ( ) ; final String uploadId = currentUploadInfo . getUploadId ( ) ; final List < PartETag > completedParts = currentUploadInfo . getCopyOfEtagsOfCompleteParts ( ) ; final long sizeInBytes = currentUploadInfo . getExpectedSizeInBytes ( ) ; if ( incompletePartObjectName == null ) { return new S3Recoverable ( objectName , uploadId , completedParts , sizeInBytes ) ; } else { return new S3Recoverable ( objectName , uploadId , completedParts , sizeInBytes , incompletePartObjectName , incompletePartFile . getPos ( ) ) ; } } | Creates a snapshot of this MultiPartUpload from which the upload can be resumed . |
14,707 | public ConnectedStreams < IN1 , IN2 > keyBy ( int keyPosition1 , int keyPosition2 ) { return new ConnectedStreams < > ( this . environment , inputStream1 . keyBy ( keyPosition1 ) , inputStream2 . keyBy ( keyPosition2 ) ) ; } | KeyBy operation for connected data stream . Assigns keys to the elements of input1 and input2 according to keyPosition1 and keyPosition2 . |
14,708 | public ConnectedStreams < IN1 , IN2 > keyBy ( int [ ] keyPositions1 , int [ ] keyPositions2 ) { return new ConnectedStreams < > ( environment , inputStream1 . keyBy ( keyPositions1 ) , inputStream2 . keyBy ( keyPositions2 ) ) ; } | KeyBy operation for connected data stream . Assigns keys to the elements of input1 and input2 according to keyPositions1 and keyPositions2 . |
14,709 | public ConnectedStreams < IN1 , IN2 > keyBy ( KeySelector < IN1 , ? > keySelector1 , KeySelector < IN2 , ? > keySelector2 ) { return new ConnectedStreams < > ( environment , inputStream1 . keyBy ( keySelector1 ) , inputStream2 . keyBy ( keySelector2 ) ) ; } | KeyBy operation for connected data stream . Assigns keys to the elements of input1 and input2 using keySelector1 and keySelector2 . |
14,710 | public < KEY > ConnectedStreams < IN1 , IN2 > keyBy ( KeySelector < IN1 , KEY > keySelector1 , KeySelector < IN2 , KEY > keySelector2 , TypeInformation < KEY > keyType ) { return new ConnectedStreams < > ( environment , inputStream1 . keyBy ( keySelector1 , keyType ) , inputStream2 . keyBy ( keySelector2 , keyType ) ) ; } | KeyBy operation for connected data stream . Assigns keys to the elements of input1 and input2 using keySelector1 and keySelector2 with explicit type information for the common key type . |
14,711 | public List < MemorySegment > close ( ) throws IOException { writeSegment ( getCurrentSegment ( ) , getCurrentPositionInSegment ( ) , true ) ; clear ( ) ; final LinkedBlockingQueue < MemorySegment > queue = this . writer . getReturnQueue ( ) ; this . writer . close ( ) ; ArrayList < MemorySegment > list = new ArrayList < MemorySegment > ( this . numSegments ) ; for ( int i = 0 ; i < this . numSegments ; i ++ ) { final MemorySegment m = queue . poll ( ) ; if ( m == null ) { throw new RuntimeException ( "ChannelWriterOutputView: MemorySegments have been taken from return queue by different actor." ) ; } list . add ( m ) ; } return list ; } | Closes this OutputView closing the underlying writer and returning all memory segments . |
14,712 | public TypeSerializer < UK > getKeySerializer ( ) { final TypeSerializer < Map < UK , UV > > rawSerializer = getSerializer ( ) ; if ( ! ( rawSerializer instanceof MapSerializer ) ) { throw new IllegalStateException ( "Unexpected serializer type." ) ; } return ( ( MapSerializer < UK , UV > ) rawSerializer ) . getKeySerializer ( ) ; } | Gets the serializer for the keys in the state . |
14,713 | protected boolean isElementLate ( StreamRecord < IN > element ) { return ( windowAssigner . isEventTime ( ) ) && ( element . getTimestamp ( ) + allowedLateness <= internalTimerService . currentWatermark ( ) ) ; } | Decide if a record is currently late based on current watermark and allowed lateness . |
14,714 | protected void deleteCleanupTimer ( W window ) { long cleanupTime = cleanupTime ( window ) ; if ( cleanupTime == Long . MAX_VALUE ) { return ; } if ( windowAssigner . isEventTime ( ) ) { triggerContext . deleteEventTimeTimer ( cleanupTime ) ; } else { triggerContext . deleteProcessingTimeTimer ( cleanupTime ) ; } } | Deletes the cleanup timer set for the contents of the provided window . |
14,715 | public Rowtime watermarksPeriodicBounded ( long delay ) { internalProperties . putString ( ROWTIME_WATERMARKS_TYPE , ROWTIME_WATERMARKS_TYPE_VALUE_PERIODIC_BOUNDED ) ; internalProperties . putLong ( ROWTIME_WATERMARKS_DELAY , delay ) ; return this ; } | Sets a built - in watermark strategy for rowtime attributes which are out - of - order by a bounded time interval . |
14,716 | public Map < String , Accumulator < ? , ? > > deserializeUserAccumulators ( ClassLoader classLoader ) throws IOException , ClassNotFoundException { return userAccumulators . deserializeValue ( classLoader ) ; } | Gets the user - defined accumulators values . |
14,717 | public void reset ( ) { nextWindow = null ; watermark = Long . MIN_VALUE ; triggerWindowStartIndex = 0 ; emptyWindowTriggered = true ; resetBuffer ( ) ; } | Reset for next group . |
14,718 | public boolean hasTriggerWindow ( ) { skipEmptyWindow ( ) ; Preconditions . checkState ( watermark == Long . MIN_VALUE || nextWindow != null , "next trigger window cannot be null." ) ; return nextWindow != null && nextWindow . getEnd ( ) <= watermark ; } | Check if there are windows could be triggered according to the current watermark . |
14,719 | public void userEventTriggered ( ChannelHandlerContext ctx , Object msg ) throws Exception { if ( msg instanceof RemoteInputChannel ) { boolean triggerWrite = inputChannelsWithCredit . isEmpty ( ) ; inputChannelsWithCredit . add ( ( RemoteInputChannel ) msg ) ; if ( triggerWrite ) { writeAndFlushNextMessageIfPossible ( ctx . channel ( ) ) ; } } else { ctx . fireUserEventTriggered ( msg ) ; } } | Triggered by notifying credit available in the client handler pipeline . |
14,720 | private void writeAndFlushNextMessageIfPossible ( Channel channel ) { if ( channelError . get ( ) != null || ! channel . isWritable ( ) ) { return ; } while ( true ) { RemoteInputChannel inputChannel = inputChannelsWithCredit . poll ( ) ; if ( inputChannel == null ) { return ; } if ( ! inputChannel . isReleased ( ) ) { AddCredit msg = new AddCredit ( inputChannel . getPartitionId ( ) , inputChannel . getAndResetUnannouncedCredit ( ) , inputChannel . getInputChannelId ( ) ) ; channel . writeAndFlush ( msg ) . addListener ( writeListener ) ; return ; } } } | Tries to write&flush unannounced credits for the next input channel in queue . |
14,721 | public List < KafkaTopicPartitionLeader > getPartitionLeadersForTopics ( List < String > topics ) { List < KafkaTopicPartitionLeader > partitions = new LinkedList < > ( ) ; retryLoop : for ( int retry = 0 ; retry < numRetries ; retry ++ ) { brokersLoop : for ( int arrIdx = 0 ; arrIdx < seedBrokerAddresses . length ; arrIdx ++ ) { LOG . info ( "Trying to get topic metadata from broker {} in try {}/{}" , seedBrokerAddresses [ currentContactSeedBrokerIndex ] , retry , numRetries ) ; try { partitions . clear ( ) ; for ( TopicMetadata item : consumer . send ( new TopicMetadataRequest ( topics ) ) . topicsMetadata ( ) ) { if ( item . errorCode ( ) != ErrorMapping . NoError ( ) ) { LOG . warn ( "Error while getting metadata from broker {} to find partitions for {}. Error: {}." , seedBrokerAddresses [ currentContactSeedBrokerIndex ] , topics . toString ( ) , ErrorMapping . exceptionFor ( item . errorCode ( ) ) . getMessage ( ) ) ; useNextAddressAsNewContactSeedBroker ( ) ; continue brokersLoop ; } if ( ! topics . contains ( item . topic ( ) ) ) { LOG . warn ( "Received metadata from topic " + item . topic ( ) + " even though it was not requested. Skipping ..." ) ; useNextAddressAsNewContactSeedBroker ( ) ; continue brokersLoop ; } for ( PartitionMetadata part : item . partitionsMetadata ( ) ) { Node leader = brokerToNode ( part . leader ( ) ) ; KafkaTopicPartition ktp = new KafkaTopicPartition ( item . topic ( ) , part . partitionId ( ) ) ; KafkaTopicPartitionLeader pInfo = new KafkaTopicPartitionLeader ( ktp , leader ) ; partitions . add ( pInfo ) ; } } break retryLoop ; } catch ( Exception e ) { validateSeedBrokers ( seedBrokerAddresses , e ) ; LOG . warn ( "Error communicating with broker {} to find partitions for {}. {} Message: {}" , seedBrokerAddresses [ currentContactSeedBrokerIndex ] , topics , e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; LOG . debug ( "Detailed trace" , e ) ; try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e1 ) { } useNextAddressAsNewContactSeedBroker ( ) ; } } } return partitions ; } | Send request to Kafka to get partitions for topics . |
14,722 | private void useNextAddressAsNewContactSeedBroker ( ) { if ( ++ currentContactSeedBrokerIndex == seedBrokerAddresses . length ) { currentContactSeedBrokerIndex = 0 ; } URL newContactUrl = NetUtils . getCorrectHostnamePort ( seedBrokerAddresses [ currentContactSeedBrokerIndex ] ) ; this . consumer = new SimpleConsumer ( newContactUrl . getHost ( ) , newContactUrl . getPort ( ) , soTimeout , bufferSize , dummyClientId ) ; } | Re - establish broker connection using the next available seed broker address . |
14,723 | private static Node brokerToNode ( Broker broker ) { return new Node ( broker . id ( ) , broker . host ( ) , broker . port ( ) ) ; } | Turn a broker instance into a node instance . |
14,724 | private static void validateSeedBrokers ( String [ ] seedBrokers , Exception exception ) { if ( ! ( exception instanceof ClosedChannelException ) ) { return ; } int unknownHosts = 0 ; for ( String broker : seedBrokers ) { URL brokerUrl = NetUtils . getCorrectHostnamePort ( broker . trim ( ) ) ; try { InetAddress . getByName ( brokerUrl . getHost ( ) ) ; } catch ( UnknownHostException e ) { unknownHosts ++ ; } } if ( unknownHosts == seedBrokers . length ) { throw new IllegalArgumentException ( "All the servers provided in: '" + ConsumerConfig . BOOTSTRAP_SERVERS_CONFIG + "' config are invalid. (unknown hosts)" ) ; } } | Validate that at least one seed broker is valid in case of a ClosedChannelException . |
14,725 | public static void maxNormalizedKey ( MemorySegment target , int offset , int numBytes ) { for ( int i = 0 ; i < numBytes ; i ++ ) { target . put ( offset + i , ( byte ) - 1 ) ; } } | Max unsigned byte is - 1 . |
14,726 | public static void putDecimalNormalizedKey ( Decimal record , MemorySegment target , int offset , int len ) { assert record . getPrecision ( ) <= Decimal . MAX_COMPACT_PRECISION ; putLongNormalizedKey ( record . toUnscaledLong ( ) , target , offset , len ) ; } | Just support the compact precision decimal . |
14,727 | public static void mergeHadoopConf ( Configuration hadoopConfig ) { org . apache . flink . configuration . Configuration flinkConfiguration = GlobalConfiguration . loadConfiguration ( ) ; Configuration hadoopConf = org . apache . flink . api . java . hadoop . mapred . utils . HadoopUtils . getHadoopConfiguration ( flinkConfiguration ) ; for ( Map . Entry < String , String > e : hadoopConf ) { if ( hadoopConfig . get ( e . getKey ( ) ) == null ) { hadoopConfig . set ( e . getKey ( ) , e . getValue ( ) ) ; } } } | Merge HadoopConfiguration into Configuration . This is necessary for the HDFS configuration . |
14,728 | public TableStats copy ( ) { TableStats copy = new TableStats ( this . rowCount ) ; for ( Map . Entry < String , ColumnStats > entry : this . colStats . entrySet ( ) ) { copy . colStats . put ( entry . getKey ( ) , entry . getValue ( ) . copy ( ) ) ; } return copy ; } | Create a deep copy of this instance . |
14,729 | private static LinkedHashSet < Class < ? > > getRegisteredSubclassesFromExecutionConfig ( Class < ? > basePojoClass , ExecutionConfig executionConfig ) { LinkedHashSet < Class < ? > > subclassesInRegistrationOrder = new LinkedHashSet < > ( executionConfig . getRegisteredPojoTypes ( ) . size ( ) ) ; for ( Class < ? > registeredClass : executionConfig . getRegisteredPojoTypes ( ) ) { if ( registeredClass . equals ( basePojoClass ) ) { continue ; } if ( ! basePojoClass . isAssignableFrom ( registeredClass ) ) { continue ; } subclassesInRegistrationOrder . add ( registeredClass ) ; } return subclassesInRegistrationOrder ; } | Extracts the subclasses of the base POJO class registered in the execution config . |
14,730 | private static LinkedHashMap < Class < ? > , Integer > createRegisteredSubclassTags ( LinkedHashSet < Class < ? > > registeredSubclasses ) { final LinkedHashMap < Class < ? > , Integer > classToTag = new LinkedHashMap < > ( ) ; int id = 0 ; for ( Class < ? > registeredClass : registeredSubclasses ) { classToTag . put ( registeredClass , id ) ; id ++ ; } return classToTag ; } | Builds map of registered subclasses to their class tags . Class tags will be integers starting from 0 assigned incrementally with the order of provided subclasses . |
14,731 | private static TypeSerializer < ? > [ ] createRegisteredSubclassSerializers ( LinkedHashSet < Class < ? > > registeredSubclasses , ExecutionConfig executionConfig ) { final TypeSerializer < ? > [ ] subclassSerializers = new TypeSerializer [ registeredSubclasses . size ( ) ] ; int i = 0 ; for ( Class < ? > registeredClass : registeredSubclasses ) { subclassSerializers [ i ] = TypeExtractor . createTypeInfo ( registeredClass ) . createSerializer ( executionConfig ) ; i ++ ; } return subclassSerializers ; } | Creates an array of serializers for provided list of registered subclasses . Order of returned serializers will correspond to order of provided subclasses . |
14,732 | TypeSerializer < ? > getSubclassSerializer ( Class < ? > subclass ) { TypeSerializer < ? > result = subclassSerializerCache . get ( subclass ) ; if ( result == null ) { result = createSubclassSerializer ( subclass ) ; subclassSerializerCache . put ( subclass , result ) ; } return result ; } | Fetches cached serializer for a non - registered subclass ; also creates the serializer if it doesn t exist yet . |
14,733 | private static < T > PojoSerializerSnapshot < T > buildSnapshot ( Class < T > pojoType , LinkedHashMap < Class < ? > , Integer > registeredSubclassesToTags , TypeSerializer < ? > [ ] registeredSubclassSerializers , Field [ ] fields , TypeSerializer < ? > [ ] fieldSerializers , Map < Class < ? > , TypeSerializer < ? > > nonRegisteredSubclassSerializerCache ) { final LinkedHashMap < Class < ? > , TypeSerializer < ? > > subclassRegistry = new LinkedHashMap < > ( registeredSubclassesToTags . size ( ) ) ; for ( Map . Entry < Class < ? > , Integer > entry : registeredSubclassesToTags . entrySet ( ) ) { subclassRegistry . put ( entry . getKey ( ) , registeredSubclassSerializers [ entry . getValue ( ) ] ) ; } return new PojoSerializerSnapshot < > ( pojoType , fields , fieldSerializers , subclassRegistry , nonRegisteredSubclassSerializerCache ) ; } | Build and return a snapshot of the serializer s parameters and currently cached serializers . |
14,734 | public static < T > Class < T > compile ( ClassLoader cl , String name , String code ) { Tuple2 < ClassLoader , String > cacheKey = Tuple2 . of ( cl , name ) ; Class < ? > clazz = COMPILED_CACHE . getIfPresent ( cacheKey ) ; if ( clazz == null ) { clazz = doCompile ( cl , name , code ) ; COMPILED_CACHE . put ( cacheKey , clazz ) ; } return ( Class < T > ) clazz ; } | Compiles a generated code to a Class . |
14,735 | private static String addLineNumber ( String code ) { String [ ] lines = code . split ( "\n" ) ; StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < lines . length ; i ++ ) { builder . append ( "/* " ) . append ( i + 1 ) . append ( " */" ) . append ( lines [ i ] ) . append ( "\n" ) ; } return builder . toString ( ) ; } | To output more information when an error occurs . Generally when cook fails it shows which line is wrong . This line number starts at 1 . |
14,736 | protected final void addCloseableInternal ( Closeable closeable , T metaData ) { synchronized ( getSynchronizationLock ( ) ) { closeableToRef . put ( closeable , metaData ) ; } } | Adds a mapping to the registry map respecting locking . |
14,737 | private void bufferRows1 ( ) throws IOException { BinaryRow copy = key1 . copy ( ) ; buffer1 . reset ( ) ; do { buffer1 . add ( row1 ) ; } while ( nextRow1 ( ) && keyComparator . compare ( key1 , copy ) == 0 ) ; buffer1 . complete ( ) ; } | Buffer rows from iterator1 with same key . |
14,738 | private void bufferRows2 ( ) throws IOException { BinaryRow copy = key2 . copy ( ) ; buffer2 . reset ( ) ; do { buffer2 . add ( row2 ) ; } while ( nextRow2 ( ) && keyComparator . compare ( key2 , copy ) == 0 ) ; buffer2 . complete ( ) ; } | Buffer rows from iterator2 with same key . |
14,739 | public static < T > TypeSerializerSchemaCompatibility < T > compatibleWithReconfiguredSerializer ( TypeSerializer < T > reconfiguredSerializer ) { return new TypeSerializerSchemaCompatibility < > ( Type . COMPATIBLE_WITH_RECONFIGURED_SERIALIZER , Preconditions . checkNotNull ( reconfiguredSerializer ) ) ; } | Returns a result that indicates a reconfigured version of the new serializer is compatible and should be used instead of the original new serializer . |
14,740 | public static CheckpointProperties forCheckpoint ( CheckpointRetentionPolicy policy ) { switch ( policy ) { case NEVER_RETAIN_AFTER_TERMINATION : return CHECKPOINT_NEVER_RETAINED ; case RETAIN_ON_FAILURE : return CHECKPOINT_RETAINED_ON_FAILURE ; case RETAIN_ON_CANCELLATION : return CHECKPOINT_RETAINED_ON_CANCELLATION ; default : throw new IllegalArgumentException ( "unknown policy: " + policy ) ; } } | Creates the checkpoint properties for a checkpoint . |
14,741 | public LongParameter setMinimumValue ( long minimumValue ) { if ( hasMaximumValue ) { Util . checkParameter ( minimumValue <= maximumValue , "Minimum value (" + minimumValue + ") must be less than or equal to maximum (" + maximumValue + ")" ) ; } this . hasMinimumValue = true ; this . minimumValue = minimumValue ; return this ; } | Set the minimum value . |
14,742 | public LongParameter setMaximumValue ( long maximumValue ) { if ( hasMinimumValue ) { Util . checkParameter ( maximumValue >= minimumValue , "Maximum value (" + maximumValue + ") must be greater than or equal to minimum (" + minimumValue + ")" ) ; } this . hasMaximumValue = true ; this . maximumValue = maximumValue ; return this ; } | Set the maximum value . |
14,743 | protected void cleanFile ( String path ) { try { PrintWriter writer ; writer = new PrintWriter ( path ) ; writer . print ( "" ) ; writer . close ( ) ; } catch ( FileNotFoundException e ) { throw new RuntimeException ( "An error occurred while cleaning the file: " + e . getMessage ( ) , e ) ; } } | Creates target file if it does not exist cleans it if it exists . |
14,744 | public Iterator < Map . Entry < K , V > > iterator ( ) { return Collections . unmodifiableSet ( state . entrySet ( ) ) . iterator ( ) ; } | Iterates over all the mappings in the state . The iterator cannot remove elements . |
14,745 | public static void sendNotModified ( ChannelHandlerContext ctx ) { FullHttpResponse response = new DefaultFullHttpResponse ( HTTP_1_1 , NOT_MODIFIED ) ; setDateHeader ( response ) ; ctx . writeAndFlush ( response ) . addListener ( ChannelFutureListener . CLOSE ) ; } | Send the 304 Not Modified response . This response can be used when the file timestamp is the same as what the browser is sending up . |
14,746 | public static void setContentTypeHeader ( HttpResponse response , File file ) { String mimeType = MimeTypes . getMimeTypeForFileName ( file . getName ( ) ) ; String mimeFinal = mimeType != null ? mimeType : MimeTypes . getDefaultMimeType ( ) ; response . headers ( ) . set ( CONTENT_TYPE , mimeFinal ) ; } | Sets the content type header for the HTTP Response . |
14,747 | public void addDataSink ( GenericDataSinkBase < ? > sink ) { checkNotNull ( sink , "The data sink must not be null." ) ; if ( ! this . sinks . contains ( sink ) ) { this . sinks . add ( sink ) ; } } | Adds a data sink to the set of sinks in this program . |
14,748 | public void accept ( Visitor < Operator < ? > > visitor ) { for ( GenericDataSinkBase < ? > sink : this . sinks ) { sink . accept ( visitor ) ; } } | Traverses the job depth first from all data sinks on towards the sources . |
14,749 | public static int calOperatorParallelism ( double rowCount , Configuration tableConf ) { int maxParallelism = getOperatorMaxParallelism ( tableConf ) ; int minParallelism = getOperatorMinParallelism ( tableConf ) ; int resultParallelism = ( int ) ( rowCount / getRowCountPerPartition ( tableConf ) ) ; return Math . max ( Math . min ( resultParallelism , maxParallelism ) , minParallelism ) ; } | Calculates operator parallelism based on rowcount of the operator . |
14,750 | public CheckpointStatsSnapshot createSnapshot ( ) { CheckpointStatsSnapshot snapshot = latestSnapshot ; if ( dirty && statsReadWriteLock . tryLock ( ) ) { try { snapshot = new CheckpointStatsSnapshot ( counts . createSnapshot ( ) , summary . createSnapshot ( ) , history . createSnapshot ( ) , latestRestoredCheckpoint ) ; latestSnapshot = snapshot ; dirty = false ; } finally { statsReadWriteLock . unlock ( ) ; } } return snapshot ; } | Creates a new snapshot of the available stats . |
14,751 | PendingCheckpointStats reportPendingCheckpoint ( long checkpointId , long triggerTimestamp , CheckpointProperties props ) { ConcurrentHashMap < JobVertexID , TaskStateStats > taskStateStats = createEmptyTaskStateStatsMap ( ) ; PendingCheckpointStats pending = new PendingCheckpointStats ( checkpointId , triggerTimestamp , props , totalSubtaskCount , taskStateStats , new PendingCheckpointStatsCallback ( ) ) ; statsReadWriteLock . lock ( ) ; try { counts . incrementInProgressCheckpoints ( ) ; history . addInProgressCheckpoint ( pending ) ; dirty = true ; } finally { statsReadWriteLock . unlock ( ) ; } return pending ; } | Creates a new pending checkpoint tracker . |
14,752 | void reportRestoredCheckpoint ( RestoredCheckpointStats restored ) { checkNotNull ( restored , "Restored checkpoint" ) ; statsReadWriteLock . lock ( ) ; try { counts . incrementRestoredCheckpoints ( ) ; latestRestoredCheckpoint = restored ; dirty = true ; } finally { statsReadWriteLock . unlock ( ) ; } } | Callback when a checkpoint is restored . |
14,753 | private void reportCompletedCheckpoint ( CompletedCheckpointStats completed ) { statsReadWriteLock . lock ( ) ; try { latestCompletedCheckpoint = completed ; counts . incrementCompletedCheckpoints ( ) ; history . replacePendingCheckpointById ( completed ) ; summary . updateSummary ( completed ) ; dirty = true ; } finally { statsReadWriteLock . unlock ( ) ; } } | Callback when a checkpoint completes . |
14,754 | private void reportFailedCheckpoint ( FailedCheckpointStats failed ) { statsReadWriteLock . lock ( ) ; try { counts . incrementFailedCheckpoints ( ) ; history . replacePendingCheckpointById ( failed ) ; dirty = true ; } finally { statsReadWriteLock . unlock ( ) ; } } | Callback when a checkpoint fails . |
14,755 | private void registerMetrics ( MetricGroup metricGroup ) { metricGroup . gauge ( NUMBER_OF_CHECKPOINTS_METRIC , new CheckpointsCounter ( ) ) ; metricGroup . gauge ( NUMBER_OF_IN_PROGRESS_CHECKPOINTS_METRIC , new InProgressCheckpointsCounter ( ) ) ; metricGroup . gauge ( NUMBER_OF_COMPLETED_CHECKPOINTS_METRIC , new CompletedCheckpointsCounter ( ) ) ; metricGroup . gauge ( NUMBER_OF_FAILED_CHECKPOINTS_METRIC , new FailedCheckpointsCounter ( ) ) ; metricGroup . gauge ( LATEST_RESTORED_CHECKPOINT_TIMESTAMP_METRIC , new LatestRestoredCheckpointTimestampGauge ( ) ) ; metricGroup . gauge ( LATEST_COMPLETED_CHECKPOINT_SIZE_METRIC , new LatestCompletedCheckpointSizeGauge ( ) ) ; metricGroup . gauge ( LATEST_COMPLETED_CHECKPOINT_DURATION_METRIC , new LatestCompletedCheckpointDurationGauge ( ) ) ; metricGroup . gauge ( LATEST_COMPLETED_CHECKPOINT_ALIGNMENT_BUFFERED_METRIC , new LatestCompletedCheckpointAlignmentBufferedGauge ( ) ) ; metricGroup . gauge ( LATEST_COMPLETED_CHECKPOINT_EXTERNAL_PATH_METRIC , new LatestCompletedCheckpointExternalPathGauge ( ) ) ; } | Register the exposed metrics . |
14,756 | public void configure ( Configuration parameters ) { super . configure ( parameters ) ; if ( Arrays . equals ( delimiter , new byte [ ] { '\n' } ) ) { String delimString = parameters . getString ( RECORD_DELIMITER , null ) ; if ( delimString != null ) { setDelimiter ( delimString ) ; } } if ( numLineSamples == NUM_SAMPLES_UNDEFINED ) { String samplesString = parameters . getString ( NUM_STATISTICS_SAMPLES , null ) ; if ( samplesString != null ) { try { setNumLineSamples ( Integer . parseInt ( samplesString ) ) ; } catch ( NumberFormatException e ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( "Invalid value for number of samples to take: " + samplesString + ". Skipping sampling." ) ; } setNumLineSamples ( 0 ) ; } } } } | Configures this input format by reading the path to the file from the configuration and the string that defines the record delimiter . |
14,757 | private boolean fillBuffer ( int offset ) throws IOException { int maxReadLength = this . readBuffer . length - offset ; if ( this . splitLength == FileInputFormat . READ_WHOLE_SPLIT_FLAG ) { int read = this . stream . read ( this . readBuffer , offset , maxReadLength ) ; if ( read == - 1 ) { this . stream . close ( ) ; this . stream = null ; return false ; } else { this . readPos = offset ; this . limit = read ; return true ; } } int toRead ; if ( this . splitLength > 0 ) { toRead = this . splitLength > maxReadLength ? maxReadLength : ( int ) this . splitLength ; } else { toRead = maxReadLength ; this . overLimit = true ; } int read = this . stream . read ( this . readBuffer , offset , toRead ) ; if ( read == - 1 ) { this . stream . close ( ) ; this . stream = null ; return false ; } else { this . splitLength -= read ; this . readPos = offset ; this . limit = read + offset ; return true ; } } | Fills the read buffer with bytes read from the file starting from an offset . |
14,758 | public void set ( final Iterator < Tuple2 < KEY , VALUE > > iterator ) { this . iterator = iterator ; if ( this . hasNext ( ) ) { final Tuple2 < KEY , VALUE > tuple = iterator . next ( ) ; this . curKey = keySerializer . copy ( tuple . f0 ) ; this . firstValue = tuple . f1 ; this . atFirst = true ; } else { this . atFirst = false ; } } | Set the Flink iterator to wrap . |
14,759 | private static void fix ( IndexedSortable s , int pN , int pO , int rN , int rO ) { if ( s . compare ( pN , pO , rN , rO ) > 0 ) { s . swap ( pN , pO , rN , rO ) ; } } | Fix the records into sorted order swapping when the first record is greater than the second record . |
14,760 | public static < W extends Window > AfterFirstElementPeriodic < W > every ( Duration time ) { return new AfterFirstElementPeriodic < > ( time . toMillis ( ) ) ; } | Creates a trigger that fires by a certain interval after reception of the first element . |
14,761 | public void invoke ( IN value ) throws Exception { byte [ ] msg = schema . serialize ( value ) ; try { outputStream . write ( msg ) ; if ( autoFlush ) { outputStream . flush ( ) ; } } catch ( IOException e ) { if ( maxNumRetries == 0 ) { throw new IOException ( "Failed to send message '" + value + "' to socket server at " + hostName + ":" + port + ". Connection re-tries are not enabled." , e ) ; } LOG . error ( "Failed to send message '" + value + "' to socket server at " + hostName + ":" + port + ". Trying to reconnect..." , e ) ; synchronized ( lock ) { IOException lastException = null ; retries = 0 ; while ( isRunning && ( maxNumRetries < 0 || retries < maxNumRetries ) ) { try { if ( outputStream != null ) { outputStream . close ( ) ; } } catch ( IOException ee ) { LOG . error ( "Could not close output stream from failed write attempt" , ee ) ; } try { if ( client != null ) { client . close ( ) ; } } catch ( IOException ee ) { LOG . error ( "Could not close socket from failed write attempt" , ee ) ; } retries ++ ; try { createConnection ( ) ; outputStream . write ( msg ) ; return ; } catch ( IOException ee ) { lastException = ee ; LOG . error ( "Re-connect to socket server and send message failed. Retry time(s): " + retries , ee ) ; } lock . wait ( CONNECTION_RETRY_DELAY ) ; } if ( isRunning ) { throw new IOException ( "Failed to send message '" + value + "' to socket server at " + hostName + ":" + port + ". Failed after " + retries + " retries." , lastException ) ; } } } } | Called when new data arrives to the sink and forwards it to Socket . |
14,762 | boolean reportSubtaskStats ( JobVertexID jobVertexId , SubtaskStateStats subtask ) { TaskStateStats taskStateStats = taskStats . get ( jobVertexId ) ; if ( taskStateStats != null && taskStateStats . reportSubtaskStats ( subtask ) ) { currentNumAcknowledgedSubtasks ++ ; latestAcknowledgedSubtask = subtask ; currentStateSize += subtask . getStateSize ( ) ; long alignmentBuffered = subtask . getAlignmentBuffered ( ) ; if ( alignmentBuffered > 0 ) { currentAlignmentBuffered += alignmentBuffered ; } return true ; } else { return false ; } } | Reports statistics for a single subtask . |
14,763 | CompletedCheckpointStats . DiscardCallback reportCompletedCheckpoint ( String externalPointer ) { CompletedCheckpointStats completed = new CompletedCheckpointStats ( checkpointId , triggerTimestamp , props , numberOfSubtasks , new HashMap < > ( taskStats ) , currentNumAcknowledgedSubtasks , currentStateSize , currentAlignmentBuffered , latestAcknowledgedSubtask , externalPointer ) ; trackerCallback . reportCompletedCheckpoint ( completed ) ; return completed . getDiscardCallback ( ) ; } | Reports a successfully completed pending checkpoint . |
14,764 | public void setBroadcastInputs ( Map < Operator < ? > , OptimizerNode > operatorToNode , ExecutionMode defaultExchangeMode ) { if ( ! ( getOperator ( ) instanceof AbstractUdfOperator < ? , ? > ) ) { return ; } AbstractUdfOperator < ? , ? > operator = ( ( AbstractUdfOperator < ? , ? > ) getOperator ( ) ) ; for ( Map . Entry < String , Operator < ? > > input : operator . getBroadcastInputs ( ) . entrySet ( ) ) { OptimizerNode predecessor = operatorToNode . get ( input . getValue ( ) ) ; DagConnection connection = new DagConnection ( predecessor , this , ShipStrategyType . BROADCAST , defaultExchangeMode ) ; addBroadcastConnection ( input . getKey ( ) , connection ) ; predecessor . addOutgoingConnection ( connection ) ; } } | This function connects the operators that produce the broadcast inputs to this operator . |
14,765 | public void setParallelism ( int parallelism ) { if ( parallelism < 1 && parallelism != ExecutionConfig . PARALLELISM_DEFAULT ) { throw new IllegalArgumentException ( "Parallelism of " + parallelism + " is invalid." ) ; } this . parallelism = parallelism ; } | Sets the parallelism for this optimizer node . The parallelism denotes how many parallel instances of the operator will be spawned during the execution . |
14,766 | public void computeUnionOfInterestingPropertiesFromSuccessors ( ) { List < DagConnection > conns = getOutgoingConnections ( ) ; if ( conns . size ( ) == 0 ) { this . intProps = new InterestingProperties ( ) ; } else { this . intProps = conns . get ( 0 ) . getInterestingProperties ( ) . clone ( ) ; for ( int i = 1 ; i < conns . size ( ) ; i ++ ) { this . intProps . addInterestingProperties ( conns . get ( i ) . getInterestingProperties ( ) ) ; } } this . intProps . dropTrivials ( ) ; } | Computes all the interesting properties that are relevant to this node . The interesting properties are a union of the interesting properties on each outgoing connection . However if two interesting properties on the outgoing connections overlap the interesting properties will occur only once in this set . For that this method deduplicates and merges the interesting properties . This method returns copies of the original interesting properties objects and leaves the original objects contained by the connections unchanged . |
14,767 | protected boolean areBranchCompatible ( PlanNode plan1 , PlanNode plan2 ) { if ( plan1 == null || plan2 == null ) { throw new NullPointerException ( ) ; } if ( this . hereJoinedBranches == null || this . hereJoinedBranches . isEmpty ( ) ) { return true ; } for ( OptimizerNode joinedBrancher : hereJoinedBranches ) { final PlanNode branch1Cand = plan1 . getCandidateAtBranchPoint ( joinedBrancher ) ; final PlanNode branch2Cand = plan2 . getCandidateAtBranchPoint ( joinedBrancher ) ; if ( branch1Cand != null && branch2Cand != null && branch1Cand != branch2Cand ) { return false ; } } return true ; } | Checks whether to candidate plans for the sub - plan of this node are comparable . The two alternative plans are comparable if |
14,768 | public < I , O > HeartbeatManager < I , O > createHeartbeatManager ( ResourceID resourceId , HeartbeatListener < I , O > heartbeatListener , ScheduledExecutor scheduledExecutor , Logger log ) { return new HeartbeatManagerImpl < > ( heartbeatTimeout , resourceId , heartbeatListener , scheduledExecutor , scheduledExecutor , log ) ; } | Creates a heartbeat manager which does not actively send heartbeats . |
14,769 | public < I , O > HeartbeatManager < I , O > createHeartbeatManagerSender ( ResourceID resourceId , HeartbeatListener < I , O > heartbeatListener , ScheduledExecutor scheduledExecutor , Logger log ) { return new HeartbeatManagerSenderImpl < > ( heartbeatInterval , heartbeatTimeout , resourceId , heartbeatListener , scheduledExecutor , scheduledExecutor , log ) ; } | Creates a heartbeat manager which actively sends heartbeats to monitoring targets . |
14,770 | protected long adjustRunLoopFrequency ( long processingStartTimeNanos , long processingEndTimeNanos ) throws InterruptedException { long endTimeNanos = processingEndTimeNanos ; if ( fetchIntervalMillis != 0 ) { long processingTimeNanos = processingEndTimeNanos - processingStartTimeNanos ; long sleepTimeMillis = fetchIntervalMillis - ( processingTimeNanos / 1_000_000 ) ; if ( sleepTimeMillis > 0 ) { Thread . sleep ( sleepTimeMillis ) ; endTimeNanos = System . nanoTime ( ) ; shardMetricsReporter . setSleepTimeMillis ( sleepTimeMillis ) ; } } return endTimeNanos ; } | Adjusts loop timing to match target frequency if specified . |
14,771 | private int adaptRecordsToRead ( long runLoopTimeNanos , int numRecords , long recordBatchSizeBytes , int maxNumberOfRecordsPerFetch ) { if ( useAdaptiveReads && numRecords != 0 && runLoopTimeNanos != 0 ) { long averageRecordSizeBytes = recordBatchSizeBytes / numRecords ; double loopFrequencyHz = 1000000000.0d / runLoopTimeNanos ; double bytesPerRead = KINESIS_SHARD_BYTES_PER_SECOND_LIMIT / loopFrequencyHz ; maxNumberOfRecordsPerFetch = ( int ) ( bytesPerRead / averageRecordSizeBytes ) ; maxNumberOfRecordsPerFetch = Math . max ( 1 , Math . min ( maxNumberOfRecordsPerFetch , ConsumerConfigConstants . DEFAULT_SHARD_GETRECORDS_MAX ) ) ; shardMetricsReporter . setAverageRecordSizeBytes ( averageRecordSizeBytes ) ; shardMetricsReporter . setLoopFrequencyHz ( loopFrequencyHz ) ; shardMetricsReporter . setBytesPerRead ( bytesPerRead ) ; } return maxNumberOfRecordsPerFetch ; } | Calculates how many records to read each time through the loop based on a target throughput and the measured frequenecy of the loop . |
14,772 | public Class < ? extends AbstractInvokable > getInvokableClass ( ClassLoader cl ) { if ( cl == null ) { throw new NullPointerException ( "The classloader must not be null." ) ; } if ( invokableClassName == null ) { return null ; } try { return Class . forName ( invokableClassName , true , cl ) . asSubclass ( AbstractInvokable . class ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "The user-code class could not be resolved." , e ) ; } catch ( ClassCastException e ) { throw new RuntimeException ( "The user-code class is no subclass of " + AbstractInvokable . class . getName ( ) , e ) ; } } | Returns the invokable class which represents the task of this vertex |
14,773 | public void setResources ( ResourceSpec minResources , ResourceSpec preferredResources ) { this . minResources = checkNotNull ( minResources ) ; this . preferredResources = checkNotNull ( preferredResources ) ; } | Sets the minimum and preferred resources for the task . |
14,774 | public void setSlotSharingGroup ( SlotSharingGroup grp ) { if ( this . slotSharingGroup != null ) { this . slotSharingGroup . removeVertexFromGroup ( id ) ; } this . slotSharingGroup = grp ; if ( grp != null ) { grp . addVertexToGroup ( id ) ; } } | Associates this vertex with a slot sharing group for scheduling . Different vertices in the same slot sharing group can run one subtask each in the same slot . |
14,775 | private void ensureCapacity ( int minCapacity ) { long currentCapacity = data . length ; if ( minCapacity <= currentCapacity ) { return ; } long expandedCapacity = Math . max ( minCapacity , currentCapacity + ( currentCapacity >> 1 ) ) ; int newCapacity = ( int ) Math . min ( MAX_ARRAY_SIZE , expandedCapacity ) ; if ( newCapacity < minCapacity ) { throw new RuntimeException ( "Requested array size " + minCapacity + " exceeds limit of " + MAX_ARRAY_SIZE ) ; } data = Arrays . copyOf ( data , newCapacity ) ; } | If the size of the array is insufficient to hold the given capacity then copy the array into a new larger array . |
14,776 | private void unregisterJobFromHighAvailability ( ) { try { runningJobsRegistry . setJobFinished ( jobGraph . getJobID ( ) ) ; } catch ( Throwable t ) { log . error ( "Could not un-register from high-availability services job {} ({})." + "Other JobManager's may attempt to recover it and re-execute it." , jobGraph . getName ( ) , jobGraph . getJobID ( ) , t ) ; } } | Marks this runner s job as not running . Other JobManager will not recover the job after this call . |
14,777 | private void failover ( long globalModVersionOfFailover ) { if ( ! executionGraph . getRestartStrategy ( ) . canRestart ( ) ) { executionGraph . failGlobal ( new FlinkException ( "RestartStrategy validate fail" ) ) ; } else { JobStatus curStatus = this . state ; if ( curStatus . equals ( JobStatus . RUNNING ) ) { cancel ( globalModVersionOfFailover ) ; } else if ( curStatus . equals ( JobStatus . CANCELED ) ) { reset ( globalModVersionOfFailover ) ; } else { LOG . info ( "FailoverRegion {} is {} when notified to failover." , id , state ) ; } } } | Notice the region to failover |
14,778 | private void cancel ( final long globalModVersionOfFailover ) { executionGraph . getJobMasterMainThreadExecutor ( ) . assertRunningInMainThread ( ) ; while ( true ) { JobStatus curStatus = this . state ; if ( curStatus . equals ( JobStatus . RUNNING ) ) { if ( transitionState ( curStatus , JobStatus . CANCELLING ) ) { createTerminationFutureOverAllConnectedVertexes ( ) . thenAccept ( ( nullptr ) -> allVerticesInTerminalState ( globalModVersionOfFailover ) ) ; break ; } } else { LOG . info ( "FailoverRegion {} is {} when cancel." , id , state ) ; break ; } } } | cancel all executions in this sub graph |
14,779 | private void reset ( long globalModVersionOfFailover ) { try { final Collection < CoLocationGroup > colGroups = new HashSet < > ( ) ; final long restartTimestamp = System . currentTimeMillis ( ) ; for ( ExecutionVertex ev : connectedExecutionVertexes ) { CoLocationGroup cgroup = ev . getJobVertex ( ) . getCoLocationGroup ( ) ; if ( cgroup != null && ! colGroups . contains ( cgroup ) ) { cgroup . resetConstraints ( ) ; colGroups . add ( cgroup ) ; } ev . resetForNewExecution ( restartTimestamp , globalModVersionOfFailover ) ; } if ( transitionState ( JobStatus . CANCELED , JobStatus . CREATED ) ) { restart ( globalModVersionOfFailover ) ; } else { LOG . info ( "FailoverRegion {} switched from CANCELLING to CREATED fail, will fail this region again." , id ) ; failover ( globalModVersionOfFailover ) ; } } catch ( GlobalModVersionMismatch e ) { state = JobStatus . RUNNING ; } catch ( Throwable e ) { LOG . info ( "FailoverRegion {} reset fail, will failover again." , id ) ; failover ( globalModVersionOfFailover ) ; } } | reset all executions in this sub graph |
14,780 | private void restart ( long globalModVersionOfFailover ) { try { if ( transitionState ( JobStatus . CREATED , JobStatus . RUNNING ) ) { if ( executionGraph . getCheckpointCoordinator ( ) != null ) { executionGraph . getCheckpointCoordinator ( ) . abortPendingCheckpoints ( new CheckpointException ( CheckpointFailureReason . JOB_FAILOVER_REGION ) ) ; executionGraph . getCheckpointCoordinator ( ) . restoreLatestCheckpointedState ( tasks , false , true ) ; } HashSet < AllocationID > previousAllocationsInRegion = new HashSet < > ( connectedExecutionVertexes . size ( ) ) ; for ( ExecutionVertex connectedExecutionVertex : connectedExecutionVertexes ) { AllocationID latestPriorAllocation = connectedExecutionVertex . getLatestPriorAllocation ( ) ; if ( latestPriorAllocation != null ) { previousAllocationsInRegion . add ( latestPriorAllocation ) ; } } for ( ExecutionVertex ev : connectedExecutionVertexes ) { try { ev . scheduleForExecution ( executionGraph . getSlotProvider ( ) , executionGraph . isQueuedSchedulingAllowed ( ) , LocationPreferenceConstraint . ANY , previousAllocationsInRegion ) ; } catch ( Throwable e ) { failover ( globalModVersionOfFailover ) ; } } } else { LOG . info ( "FailoverRegion {} switched from CREATED to RUNNING fail, will fail this region again." , id ) ; failover ( globalModVersionOfFailover ) ; } } catch ( Exception e ) { LOG . info ( "FailoverRegion {} restart failed, failover again." , id , e ) ; failover ( globalModVersionOfFailover ) ; } } | restart all executions in this sub graph |
14,781 | public static long getManagedMemorySize ( Configuration configuration ) { long managedMemorySize ; String managedMemorySizeDefaultVal = TaskManagerOptions . MANAGED_MEMORY_SIZE . defaultValue ( ) ; if ( ! configuration . getString ( TaskManagerOptions . MANAGED_MEMORY_SIZE ) . equals ( managedMemorySizeDefaultVal ) ) { try { managedMemorySize = MemorySize . parse ( configuration . getString ( TaskManagerOptions . MANAGED_MEMORY_SIZE ) , MEGA_BYTES ) . getMebiBytes ( ) ; } catch ( IllegalArgumentException e ) { throw new IllegalConfigurationException ( "Could not read " + TaskManagerOptions . MANAGED_MEMORY_SIZE . key ( ) , e ) ; } } else { managedMemorySize = Long . valueOf ( managedMemorySizeDefaultVal ) ; } checkConfigParameter ( configuration . getString ( TaskManagerOptions . MANAGED_MEMORY_SIZE ) . equals ( TaskManagerOptions . MANAGED_MEMORY_SIZE . defaultValue ( ) ) || managedMemorySize > 0 , managedMemorySize , TaskManagerOptions . MANAGED_MEMORY_SIZE . key ( ) , "MemoryManager needs at least one MB of memory. " + "If you leave this config parameter empty, the system automatically pick a fraction of the available memory." ) ; return managedMemorySize ; } | Parses the configuration to get the managed memory size and validates the value . |
14,782 | public static float getManagedMemoryFraction ( Configuration configuration ) { float managedMemoryFraction = configuration . getFloat ( TaskManagerOptions . MANAGED_MEMORY_FRACTION ) ; checkConfigParameter ( managedMemoryFraction > 0.0f && managedMemoryFraction < 1.0f , managedMemoryFraction , TaskManagerOptions . MANAGED_MEMORY_FRACTION . key ( ) , "MemoryManager fraction of the free memory must be between 0.0 and 1.0" ) ; return managedMemoryFraction ; } | Parses the configuration to get the fraction of managed memory and validates the value . |
14,783 | public static MemoryType getMemoryType ( Configuration configuration ) { final MemoryType memType ; if ( configuration . getBoolean ( TaskManagerOptions . MEMORY_OFF_HEAP ) ) { memType = MemoryType . OFF_HEAP ; } else { memType = MemoryType . HEAP ; } return memType ; } | Parses the configuration to get the type of memory . |
14,784 | public static int getSlot ( Configuration configuration ) { int slots = configuration . getInteger ( TaskManagerOptions . NUM_TASK_SLOTS , 1 ) ; if ( slots == - 1 ) { slots = 1 ; } ConfigurationParserUtils . checkConfigParameter ( slots >= 1 , slots , TaskManagerOptions . NUM_TASK_SLOTS . key ( ) , "Number of task slots must be at least one." ) ; return slots ; } | Parses the configuration to get the number of slots and validates the value . |
14,785 | public static void checkConfigParameter ( boolean condition , Object parameter , String name , String errorMessage ) throws IllegalConfigurationException { if ( ! condition ) { throw new IllegalConfigurationException ( "Invalid configuration value for " + name + " : " + parameter + " - " + errorMessage ) ; } } | Validates a condition for a config parameter and displays a standard exception if the the condition does not hold . |
14,786 | public static YarnHighAvailabilityServices forSingleJobAppMaster ( Configuration flinkConfig , org . apache . hadoop . conf . Configuration hadoopConfig ) throws IOException { checkNotNull ( flinkConfig , "flinkConfig" ) ; checkNotNull ( hadoopConfig , "hadoopConfig" ) ; final HighAvailabilityMode mode = HighAvailabilityMode . fromConfig ( flinkConfig ) ; switch ( mode ) { case NONE : return new YarnIntraNonHaMasterServices ( flinkConfig , hadoopConfig ) ; case ZOOKEEPER : throw new UnsupportedOperationException ( "to be implemented" ) ; default : throw new IllegalConfigurationException ( "Unrecognized high availability mode: " + mode ) ; } } | Creates the high - availability services for a single - job Flink YARN application to be used in the Application Master that runs both ResourceManager and JobManager . |
14,787 | public static YarnHighAvailabilityServices forYarnTaskManager ( Configuration flinkConfig , org . apache . hadoop . conf . Configuration hadoopConfig ) throws IOException { checkNotNull ( flinkConfig , "flinkConfig" ) ; checkNotNull ( hadoopConfig , "hadoopConfig" ) ; final HighAvailabilityMode mode = HighAvailabilityMode . fromConfig ( flinkConfig ) ; switch ( mode ) { case NONE : return new YarnPreConfiguredMasterNonHaServices ( flinkConfig , hadoopConfig , HighAvailabilityServicesUtils . AddressResolution . TRY_ADDRESS_RESOLUTION ) ; case ZOOKEEPER : throw new UnsupportedOperationException ( "to be implemented" ) ; default : throw new IllegalConfigurationException ( "Unrecognized high availability mode: " + mode ) ; } } | Creates the high - availability services for the TaskManagers participating in a Flink YARN application . |
14,788 | public List < MemorySegment > close ( ) throws IOException { if ( this . closed ) { throw new IllegalStateException ( "Already closed." ) ; } this . closed = true ; ArrayList < MemorySegment > list = this . freeMem ; final MemorySegment current = getCurrentSegment ( ) ; if ( current != null ) { list . add ( current ) ; } clear ( ) ; final LinkedBlockingQueue < MemorySegment > queue = this . reader . getReturnQueue ( ) ; this . reader . close ( ) ; while ( list . size ( ) < this . numSegments ) { final MemorySegment m = queue . poll ( ) ; if ( m == null ) { throw new RuntimeException ( "Bug in ChannelReaderInputView: MemorySegments lost." ) ; } list . add ( m ) ; } return list ; } | Closes this InputView closing the underlying reader and returning all memory segments . |
14,789 | protected void sendReadRequest ( MemorySegment seg ) throws IOException { if ( this . numRequestsRemaining != 0 ) { this . reader . readBlock ( seg ) ; if ( this . numRequestsRemaining != - 1 ) { this . numRequestsRemaining -- ; } } else { this . freeMem . add ( seg ) ; } } | Sends a new read requests if further requests remain . Otherwise this method adds the segment directly to the readers return queue . |
14,790 | public static < T > TypeInformation < T > of ( Class < T > typeClass ) { try { return TypeExtractor . createTypeInfo ( typeClass ) ; } catch ( InvalidTypesException e ) { throw new FlinkRuntimeException ( "Cannot extract TypeInformation from Class alone, because generic parameters are missing. " + "Please use TypeInformation.of(TypeHint) instead, or another equivalent method in the API that " + "accepts a TypeHint instead of a Class. " + "For example for a Tuple2<Long, String> pass a 'new TypeHint<Tuple2<Long, String>>(){}'." ) ; } } | Creates a TypeInformation for the type described by the given class . |
14,791 | public static int calculateFixLengthPartSize ( InternalType type ) { if ( type . equals ( InternalTypes . BOOLEAN ) ) { return 1 ; } else if ( type . equals ( InternalTypes . BYTE ) ) { return 1 ; } else if ( type . equals ( InternalTypes . SHORT ) ) { return 2 ; } else if ( type . equals ( InternalTypes . INT ) ) { return 4 ; } else if ( type . equals ( InternalTypes . FLOAT ) ) { return 4 ; } else if ( type . equals ( InternalTypes . CHAR ) ) { return 2 ; } else if ( type . equals ( InternalTypes . DATE ) ) { return 4 ; } else if ( type . equals ( InternalTypes . TIME ) ) { return 4 ; } else { return 8 ; } } | It store real value when type is primitive . It store the length and offset of variable - length part when type is string map etc . |
14,792 | public Collection < CompletableFuture < TaskManagerLocation > > getPreferredLocationsBasedOnState ( ) { TaskManagerLocation priorLocation ; if ( currentExecution . getTaskRestore ( ) != null && ( priorLocation = getLatestPriorLocation ( ) ) != null ) { return Collections . singleton ( CompletableFuture . completedFuture ( priorLocation ) ) ; } else { return null ; } } | Gets the preferred location to execute the current task execution attempt based on the state that the execution attempt will resume . |
14,793 | public Execution resetForNewExecution ( final long timestamp , final long originatingGlobalModVersion ) throws GlobalModVersionMismatch { LOG . debug ( "Resetting execution vertex {} for new execution." , getTaskNameWithSubtaskIndex ( ) ) ; synchronized ( priorExecutions ) { final long actualModVersion = getExecutionGraph ( ) . getGlobalModVersion ( ) ; if ( actualModVersion > originatingGlobalModVersion ) { throw new GlobalModVersionMismatch ( originatingGlobalModVersion , actualModVersion ) ; } final Execution oldExecution = currentExecution ; final ExecutionState oldState = oldExecution . getState ( ) ; if ( oldState . isTerminal ( ) ) { priorExecutions . add ( oldExecution . archive ( ) ) ; final Execution newExecution = new Execution ( getExecutionGraph ( ) . getFutureExecutor ( ) , this , oldExecution . getAttemptNumber ( ) + 1 , originatingGlobalModVersion , timestamp , timeout ) ; currentExecution = newExecution ; synchronized ( inputSplits ) { InputSplitAssigner assigner = jobVertex . getSplitAssigner ( ) ; if ( assigner != null ) { assigner . returnInputSplit ( inputSplits , getParallelSubtaskIndex ( ) ) ; inputSplits . clear ( ) ; } } CoLocationGroup grp = jobVertex . getCoLocationGroup ( ) ; if ( grp != null ) { locationConstraint = grp . getLocationConstraint ( subTaskIndex ) ; } getExecutionGraph ( ) . registerExecution ( newExecution ) ; if ( oldState == FINISHED ) { getExecutionGraph ( ) . vertexUnFinished ( ) ; } for ( IntermediateResultPartition resultPartition : resultPartitions . values ( ) ) { resultPartition . resetForNewExecution ( ) ; } return newExecution ; } else { throw new IllegalStateException ( "Cannot reset a vertex that is in non-terminal state " + oldState ) ; } } } | Archives the current Execution and creates a new Execution for this vertex . |
14,794 | void scheduleOrUpdateConsumers ( ResultPartitionID partitionId ) { final Execution execution = currentExecution ; if ( ! partitionId . getProducerId ( ) . equals ( execution . getAttemptId ( ) ) ) { return ; } final IntermediateResultPartition partition = resultPartitions . get ( partitionId . getPartitionId ( ) ) ; if ( partition == null ) { throw new IllegalStateException ( "Unknown partition " + partitionId + "." ) ; } partition . markDataProduced ( ) ; if ( partition . getIntermediateResult ( ) . getResultType ( ) . isPipelined ( ) ) { execution . scheduleOrUpdateConsumers ( partition . getConsumers ( ) ) ; } else { throw new IllegalArgumentException ( "ScheduleOrUpdateConsumers msg is only valid for" + "pipelined partitions." ) ; } } | Schedules or updates the consumer tasks of the result partition with the given ID . |
14,795 | boolean checkInputDependencyConstraints ( ) { if ( getInputDependencyConstraint ( ) == InputDependencyConstraint . ANY ) { return IntStream . range ( 0 , inputEdges . length ) . anyMatch ( this :: isInputConsumable ) ; } else { return IntStream . range ( 0 , inputEdges . length ) . allMatch ( this :: isInputConsumable ) ; } } | Check whether the InputDependencyConstraint is satisfied for this vertex . |
14,796 | boolean isInputConsumable ( int inputNumber ) { return Arrays . stream ( inputEdges [ inputNumber ] ) . map ( ExecutionEdge :: getSource ) . anyMatch ( IntermediateResultPartition :: isConsumable ) ; } | Get whether an input of the vertex is consumable . An input is consumable when when any partition in it is consumable . |
14,797 | void notifyStateTransition ( Execution execution , ExecutionState newState , Throwable error ) { if ( currentExecution == execution ) { getExecutionGraph ( ) . notifyExecutionChange ( execution , newState , error ) ; } } | Simply forward this notification . |
14,798 | private static void getContainedGenericTypes ( CompositeType < ? > typeInfo , List < GenericTypeInfo < ? > > target ) { for ( int i = 0 ; i < typeInfo . getArity ( ) ; i ++ ) { TypeInformation < ? > type = typeInfo . getTypeAt ( i ) ; if ( type instanceof CompositeType ) { getContainedGenericTypes ( ( CompositeType < ? > ) type , target ) ; } else if ( type instanceof GenericTypeInfo ) { if ( ! target . contains ( type ) ) { target . add ( ( GenericTypeInfo < ? > ) type ) ; } } } } | Returns all GenericTypeInfos contained in a composite type . |
14,799 | public RefCountedFile apply ( File file ) throws IOException { final File directory = tempDirectories [ nextIndex ( ) ] ; while ( true ) { try { if ( file == null ) { final File newFile = new File ( directory , ".tmp_" + UUID . randomUUID ( ) ) ; final OutputStream out = Files . newOutputStream ( newFile . toPath ( ) , StandardOpenOption . CREATE_NEW ) ; return RefCountedFile . newFile ( newFile , out ) ; } else { final OutputStream out = Files . newOutputStream ( file . toPath ( ) , StandardOpenOption . APPEND ) ; return RefCountedFile . restoredFile ( file , out , file . length ( ) ) ; } } catch ( FileAlreadyExistsException ignored ) { } } } | Gets the next temp file and stream to temp file . This creates the temp file atomically making sure no previous file is overwritten . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.