idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
1,900
public static Set < String > getAllClasspathJars ( final String ... excludeEnv ) { final Set < String > jars = new HashSet < > ( ) ; final Set < Path > excludePaths = new HashSet < > ( ) ; for ( final String env : excludeEnv ) { final String path = System . getenv ( env ) ; if ( null != path ) { final File file = new File ( path ) ; if ( file . exists ( ) ) { excludePaths . add ( file . toPath ( ) ) ; } } } for ( final String path : System . getProperty ( "java.class.path" ) . split ( File . pathSeparator ) ) { try { final File file = new File ( path ) ; if ( file . exists ( ) ) { final Path absolutePath = file . toPath ( ) ; boolean toBeAdded = true ; for ( final Path prefix : excludePaths ) { if ( absolutePath . startsWith ( prefix ) ) { toBeAdded = false ; } } if ( toBeAdded ) { jars . add ( absolutePath . toString ( ) ) ; } } } catch ( final InvalidPathException ex ) { LOG . log ( Level . FINE , "Skip path: {0}: {1}" , new Object [ ] { path , ex } ) ; } } return jars ; }
Get a set of all classpath entries EXCEPT of those under excludeEnv directories . Every excludeEnv entry is an environment variable name .
1,901
public synchronized void onPotentiallyIdle ( final IdleMessage reason ) { final DriverStatusManager driverStatusManagerImpl = this . driverStatusManager . get ( ) ; if ( driverStatusManagerImpl . isClosing ( ) ) { LOG . log ( IDLE_REASONS_LEVEL , "Ignoring idle call from [{0}] for reason [{1}]" , new Object [ ] { reason . getComponentName ( ) , reason . getReason ( ) } ) ; return ; } LOG . log ( IDLE_REASONS_LEVEL , "Checking for idle because {0} reported idleness for reason [{1}]" , new Object [ ] { reason . getComponentName ( ) , reason . getReason ( ) } ) ; boolean isIdle = true ; for ( final DriverIdlenessSource idlenessSource : this . idlenessSources ) { final IdleMessage idleMessage = idlenessSource . getIdleStatus ( ) ; LOG . log ( IDLE_REASONS_LEVEL , "[{0}] is reporting {1} because [{2}]." , new Object [ ] { idleMessage . getComponentName ( ) , idleMessage . isIdle ( ) ? "idle" : "not idle" , idleMessage . getReason ( ) } ) ; isIdle &= idleMessage . isIdle ( ) ; } LOG . log ( IDLE_REASONS_LEVEL , "onPotentiallyIdle: isIdle: " + isIdle ) ; if ( isIdle ) { LOG . log ( Level . INFO , "All components indicated idle. Initiating Driver shutdown." ) ; driverStatusManagerImpl . onComplete ( ) ; } }
Check whether all Driver components are idle and initiate driver shutdown if they are .
1,902
public static void serialize ( final File file , final ClassHierarchy classHierarchy ) throws IOException { final ClassHierarchyProto . Node node = serializeNode ( classHierarchy . getNamespace ( ) ) ; try ( final FileOutputStream output = new FileOutputStream ( file ) ) { try ( final DataOutputStream dos = new DataOutputStream ( output ) ) { node . writeTo ( dos ) ; } } }
serialize a class hierarchy into a file .
1,903
public Optional < String > trySchedule ( final Tasklet tasklet ) { for ( int i = 0 ; i < idList . size ( ) ; i ++ ) { final int index = ( nextIndex + i ) % idList . size ( ) ; final String workerId = idList . get ( index ) ; if ( idLoadMap . get ( workerId ) < workerCapacity ) { nextIndex = ( index + 1 ) % idList . size ( ) ; return Optional . of ( workerId ) ; } } return Optional . empty ( ) ; }
Checking from nextIndex choose the first worker that fits to schedule the tasklet onto .
1,904
public static LauncherStatus launchLocal ( final VortexJobConf vortexConf ) { final Configuration runtimeConf = LocalRuntimeConfiguration . CONF . set ( LocalRuntimeConfiguration . MAX_NUMBER_OF_EVALUATORS , MAX_NUMBER_OF_EVALUATORS ) . build ( ) ; return launch ( runtimeConf , vortexConf . getConfiguration ( ) ) ; }
Launch a Vortex job using the local runtime .
1,905
public void handle ( final String target , final HttpServletRequest request , final HttpServletResponse response , final int i ) throws IOException , ServletException { LOG . log ( Level . INFO , "JettyHandler handle is entered with target: {0} " , target ) ; final Request baseRequest = ( request instanceof Request ) ? ( Request ) request : HttpConnection . getCurrentConnection ( ) . getRequest ( ) ; response . setContentType ( "text/html;charset=utf-8" ) ; final ParsedHttpRequest parsedHttpRequest = new ParsedHttpRequest ( request ) ; final HttpHandler handler = validate ( request , response , parsedHttpRequest ) ; if ( handler != null ) { LOG . log ( Level . INFO , "calling HttpHandler.onHttpRequest from JettyHandler.handle() for {0}." , handler . getUriSpecification ( ) ) ; handler . onHttpRequest ( parsedHttpRequest , response ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; } baseRequest . setHandled ( true ) ; LOG . log ( Level . INFO , "JettyHandler handle exists" ) ; }
handle http request .
1,906
private HttpHandler validate ( final HttpServletRequest request , final HttpServletResponse response , final ParsedHttpRequest parsedHttpRequest ) throws IOException , ServletException { final String specification = parsedHttpRequest . getTargetSpecification ( ) ; final String version = parsedHttpRequest . getVersion ( ) ; if ( specification == null ) { writeMessage ( response , "Specification is not provided in the request." , HttpServletResponse . SC_BAD_REQUEST ) ; return null ; } final HttpHandler handler = eventHandlers . get ( specification . toLowerCase ( ) ) ; if ( handler == null ) { writeMessage ( response , String . format ( "No event handler registered for: [%s]." , specification ) , HttpServletResponse . SC_NOT_FOUND ) ; return null ; } if ( version == null ) { writeMessage ( response , "Version is not provided in the request." , HttpServletResponse . SC_BAD_REQUEST ) ; return null ; } return handler ; }
Validate request and get http handler for the request .
1,907
private void writeMessage ( final HttpServletResponse response , final String message , final int status ) throws IOException { response . getWriter ( ) . println ( message ) ; response . setStatus ( status ) ; }
process write message and status on the response .
1,908
final void addHandler ( final HttpHandler handler ) { if ( handler != null ) { if ( ! eventHandlers . containsKey ( handler . getUriSpecification ( ) . toLowerCase ( ) ) ) { eventHandlers . put ( handler . getUriSpecification ( ) . toLowerCase ( ) , handler ) ; } else { LOG . log ( Level . WARNING , "JettyHandler handle is already registered: {0} " , handler . getUriSpecification ( ) ) ; } } }
Add a handler explicitly instead of through injection . This is for handlers created on the fly .
1,909
public void waitForCompletion ( ) throws Exception { LOG . info ( "Waiting for the Job Driver to complete." ) ; try { synchronized ( this ) { this . wait ( ) ; } } catch ( final InterruptedException ex ) { LOG . log ( Level . WARNING , "Waiting for result interrupted." , ex ) ; } this . reef . close ( ) ; this . controlListener . close ( ) ; }
Wait for the job to complete .
1,910
public < T > EventHandler < RemoteEvent < T > > getHandler ( ) { return new RemoteSenderEventHandler < T > ( encoder , transport , executor ) ; }
Returns a new remote sender event handler .
1,911
public URI uploadFile ( final String jobFolder , final File file ) throws IOException { LOG . log ( Level . INFO , "Uploading [{0}] to [{1}]" , new Object [ ] { file , jobFolder } ) ; try { final CloudBlobClient cloudBlobClient = this . cloudBlobClientProvider . getCloudBlobClient ( ) ; final CloudBlobContainer container = cloudBlobClient . getContainerReference ( this . azureStorageContainerName ) ; final String destination = String . format ( "%s/%s" , jobFolder , file . getName ( ) ) ; final CloudBlockBlob blob = container . getBlockBlobReference ( destination ) ; try ( FileInputStream fis = new FileInputStream ( file ) ) { blob . upload ( fis , file . length ( ) ) ; } LOG . log ( Level . FINE , "Uploaded to: {0}" , blob . getStorageUri ( ) . getPrimaryUri ( ) ) ; return this . cloudBlobClientProvider . generateSharedAccessSignature ( blob , getSharedAccessBlobPolicy ( ) ) ; } catch ( final URISyntaxException | StorageException e ) { throw new IOException ( e ) ; } }
Upload a file to the storage account .
1,912
private static ConfigurationModule addAll ( final ConfigurationModule conf , final OptionalParameter < String > param , final File folder ) { ConfigurationModule result = conf ; final File [ ] files = folder . listFiles ( ) ; if ( files != null ) { for ( final File f : files ) { if ( f . canRead ( ) && f . exists ( ) && f . isFile ( ) ) { result = result . set ( param , f . getAbsolutePath ( ) ) ; } } } return result ; }
1000 sec .
1,913
public int getResubmissionAttempts ( ) { final String containerIdString = YarnUtilities . getContainerIdString ( ) ; final ApplicationAttemptId appAttemptID = YarnUtilities . getAppAttemptId ( containerIdString ) ; if ( containerIdString == null || appAttemptID == null ) { LOG . log ( Level . WARNING , "Was not able to fetch application attempt, container ID is [" + containerIdString + "] and application attempt is [" + appAttemptID + "]. Determining restart based on previous containers." ) ; if ( this . isRestartByPreviousContainers ( ) ) { LOG . log ( Level . WARNING , "Driver is a restarted instance based on the number of previous containers. " + "As returned by the Resource Manager. Returning default resubmission attempts " + DEFAULT_RESTART_RESUBMISSION_ATTEMPTS + "." ) ; return DEFAULT_RESTART_RESUBMISSION_ATTEMPTS ; } return 0 ; } int appAttempt = appAttemptID . getAttemptId ( ) ; LOG . log ( Level . FINE , "Application attempt: " + appAttempt ) ; assert appAttempt > 0 ; return appAttempt - 1 ; }
Determines the number of times the Driver has been submitted based on the container ID environment variable provided by YARN . If that fails determine whether the application master is a restart based on the number of previous containers reported by YARN . In the failure scenario returns 1 if restart 0 otherwise .
1,914
private synchronized void initializeListOfPreviousContainers ( ) { if ( this . previousContainers == null ) { final List < Container > yarnPrevContainers = this . registration . getRegistration ( ) . getContainersFromPreviousAttempts ( ) ; if ( yarnPrevContainers == null ) { this . previousContainers = Collections . unmodifiableSet ( new HashSet < Container > ( ) ) ; } else { this . previousContainers = Collections . unmodifiableSet ( new HashSet < > ( yarnPrevContainers ) ) ; } yarnContainerManager . onContainersRecovered ( this . previousContainers ) ; } }
Initializes the list of previous containers as reported by YARN .
1,915
public void informAboutEvaluatorFailures ( final Set < String > evaluatorIds ) { for ( String evaluatorId : evaluatorIds ) { LOG . log ( Level . WARNING , "Container [" + evaluatorId + "] has failed during driver restart process, FailedEvaluatorHandler will be triggered, but " + "no additional evaluator can be requested due to YARN-2433." ) ; this . reefEventHandlers . onResourceStatus ( ResourceStatusEventImpl . newBuilder ( ) . setIdentifier ( evaluatorId ) . setState ( State . FAILED ) . setExitCode ( 1 ) . setDiagnostics ( "Container [" + evaluatorId + "] failed during driver restart process." ) . build ( ) ) ; } }
Calls the appropriate handler via REEFEventHandlers which is a runtime specific implementation of the YARN runtime .
1,916
public void start ( final VortexThreadPool vortexThreadPool ) { final VortexFuture future = vortexThreadPool . submit ( new HelloVortexFunction ( ) , null ) ; try { future . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } }
Run the function .
1,917
public synchronized EvaluatorContext getContext ( final String contextId ) { for ( final EvaluatorContext context : this . contextStack ) { if ( context . getId ( ) . equals ( contextId ) ) { return context ; } } throw new RuntimeException ( "Unknown evaluator context " + contextId ) ; }
Fetch the context with the given ID .
1,918
public synchronized List < FailedContext > getFailedContextsForEvaluatorFailure ( ) { final List < FailedContext > failedContextList = new ArrayList < > ( ) ; final List < EvaluatorContext > activeContexts = new ArrayList < > ( this . contextStack ) ; Collections . reverse ( activeContexts ) ; for ( final EvaluatorContext context : activeContexts ) { failedContextList . add ( context . getFailedContextForEvaluatorFailure ( ) ) ; } return failedContextList ; }
Create the failed contexts for a FailedEvaluator event .
1,919
public synchronized void onContextStatusMessages ( final Iterable < ContextStatusPOJO > contextStatusPOJOs , final boolean notifyClientOnNewActiveContext ) { for ( final ContextStatusPOJO contextStatus : contextStatusPOJOs ) { this . onContextStatusMessage ( contextStatus , notifyClientOnNewActiveContext ) ; } }
Process heartbeats from the contexts on an Evaluator .
1,920
private synchronized void onContextStatusMessage ( final ContextStatusPOJO contextStatus , final boolean notifyClientOnNewActiveContext ) { LOG . log ( Level . FINER , "Processing context status message for context {0}" , contextStatus . getContextId ( ) ) ; switch ( contextStatus . getContextState ( ) ) { case READY : this . onContextReady ( contextStatus , notifyClientOnNewActiveContext ) ; break ; case FAIL : this . onContextFailed ( contextStatus ) ; break ; case DONE : this . onContextDone ( contextStatus ) ; break ; default : this . onUnknownContextStatus ( contextStatus ) ; break ; } LOG . log ( Level . FINER , "Done processing context status message for context {0}" , contextStatus . getContextId ( ) ) ; }
Process a heartbeat from a context .
1,921
private synchronized void onContextReady ( final ContextStatusPOJO contextStatus , final boolean notifyClientOnNewActiveContext ) { assert ContextState . READY == contextStatus . getContextState ( ) ; final String contextID = contextStatus . getContextId ( ) ; if ( this . isUnknownContextId ( contextID ) ) { this . onNewContext ( contextStatus , notifyClientOnNewActiveContext ) ; } for ( final ContextMessagePOJO contextMessage : contextStatus . getContextMessageList ( ) ) { final byte [ ] theMessage = contextMessage . getMessage ( ) ; final String sourceID = contextMessage . getSourceId ( ) ; final long sequenceNumber = contextMessage . getSequenceNumber ( ) ; this . messageDispatcher . onContextMessage ( new ContextMessageImpl ( theMessage , contextID , sourceID , sequenceNumber ) ) ; } }
Process a message with status READY from a context .
1,922
private synchronized void onNewContext ( final ContextStatusPOJO contextStatus , final boolean notifyClientOnNewActiveContext ) { final String contextID = contextStatus . getContextId ( ) ; LOG . log ( Level . FINE , "Adding new context {0}." , contextID ) ; final Optional < String > parentID = contextStatus . hasParentId ( ) ? Optional . of ( contextStatus . getParentId ( ) ) : Optional . < String > empty ( ) ; final EvaluatorContext context = contextFactory . newContext ( contextID , parentID ) ; this . addContext ( context ) ; if ( notifyClientOnNewActiveContext ) { if ( driverRestartManager . getEvaluatorRestartState ( context . getEvaluatorId ( ) ) == EvaluatorRestartState . REREGISTERED ) { driverRestartManager . setEvaluatorProcessed ( context . getEvaluatorId ( ) ) ; this . messageDispatcher . onDriverRestartContextActive ( context ) ; } this . messageDispatcher . onContextActive ( context ) ; } }
Create and add a new context representer .
1,923
private synchronized void addContext ( final EvaluatorContext context ) { this . contextStack . add ( context ) ; this . contextIds . add ( context . getId ( ) ) ; }
Add the given context to the data structures .
1,924
private synchronized void removeContext ( final EvaluatorContext context ) { this . contextStack . remove ( context ) ; this . contextIds . remove ( context . getId ( ) ) ; }
Remove the given context from the data structures .
1,925
public static void setLoggingLevel ( final Level level ) { final Handler [ ] handlers = Logger . getLogger ( "" ) . getHandlers ( ) ; ConsoleHandler ch = null ; for ( final Handler h : handlers ) { if ( h instanceof ConsoleHandler ) { ch = ( ConsoleHandler ) h ; break ; } } if ( ch == null ) { ch = new ConsoleHandler ( ) ; Logger . getLogger ( "" ) . addHandler ( ch ) ; } ch . setLevel ( level ) ; Logger . getLogger ( "" ) . setLevel ( level ) ; }
Sets the logging level .
1,926
private EvaluatorManager getNewEvaluatorManagerInstance ( final String id , final EvaluatorDescriptor desc ) { LOG . log ( Level . FINEST , "Creating Evaluator Manager for Evaluator ID {0}" , id ) ; final Injector child = this . injector . forkInjector ( ) ; try { child . bindVolatileParameter ( EvaluatorManager . EvaluatorIdentifier . class , id ) ; child . bindVolatileParameter ( EvaluatorManager . EvaluatorDescriptorName . class , desc ) ; } catch ( final BindException e ) { throw new RuntimeException ( "Unable to bind evaluator identifier and name." , e ) ; } final EvaluatorManager result ; try { result = child . getInstance ( EvaluatorManager . class ) ; } catch ( final InjectionException e ) { throw new RuntimeException ( "Unable to instantiate a new EvaluatorManager for Evaluator ID: " + id , e ) ; } return result ; }
Helper method to create a new EvaluatorManager instance .
1,927
public EvaluatorManager getNewEvaluatorManagerForNewEvaluator ( final ResourceAllocationEvent resourceAllocationEvent ) { final EvaluatorManager evaluatorManager = getNewEvaluatorManagerInstanceForResource ( resourceAllocationEvent ) ; evaluatorManager . fireEvaluatorAllocatedEvent ( ) ; return evaluatorManager ; }
Instantiates a new EvaluatorManager based on a resource allocation . Fires the EvaluatorAllocatedEvent .
1,928
public EvaluatorManager getNewEvaluatorManagerForEvaluatorFailedDuringDriverRestart ( final ResourceStatusEvent resourceStatusEvent ) { return getNewEvaluatorManagerInstance ( resourceStatusEvent . getIdentifier ( ) , this . evaluatorDescriptorBuilderFactory . newBuilder ( ) . setMemory ( 128 ) . setNumberOfCores ( 1 ) . setEvaluatorProcess ( processFactory . newEvaluatorProcess ( ) ) . setRuntimeName ( resourceStatusEvent . getRuntimeName ( ) ) . build ( ) ) ; }
Instantiates a new EvaluatorManager for a failed evaluator during driver restart . Does not fire an EvaluatorAllocatedEvent .
1,929
public static String getGraphvizString ( final Configuration config , final boolean showImpl , final boolean showLegend ) { final GraphvizConfigVisitor visitor = new GraphvizConfigVisitor ( config , showImpl , showLegend ) ; final Node root = config . getClassHierarchy ( ) . getNamespace ( ) ; Walk . preorder ( visitor , visitor , root ) ; return visitor . toString ( ) ; }
Produce a Graphviz DOT string for a given TANG configuration .
1,930
public boolean visit ( final ClassNode < ? > node ) { this . graphStr . append ( " " ) . append ( node . getName ( ) ) . append ( " [label=\"" ) . append ( node . getName ( ) ) . append ( "\", shape=box" ) . append ( "];\n" ) ; final ClassNode < ? > boundImplNode = config . getBoundImplementation ( node ) ; if ( boundImplNode != null ) { this . graphStr . append ( " " ) . append ( node . getName ( ) ) . append ( " -> " ) . append ( boundImplNode . getName ( ) ) . append ( " [style=solid, dir=back, arrowtail=normal];\n" ) ; } for ( final Object implNodeObj : node . getKnownImplementations ( ) ) { final ClassNode < ? > implNode = ( ClassNode < ? > ) implNodeObj ; if ( implNode != boundImplNode && implNode != node && ( implNode . isExternalConstructor ( ) || this . showImpl ) ) { this . graphStr . append ( " " ) . append ( node . getName ( ) ) . append ( " -> " ) . append ( implNode . getName ( ) ) . append ( " [style=\"dashed" ) . append ( implNode . isExternalConstructor ( ) ? ",bold" : "" ) . append ( "\", dir=back, arrowtail=empty];\n" ) ; } } return true ; }
Process current class configuration node .
1,931
public boolean visit ( final PackageNode node ) { if ( ! node . getName ( ) . isEmpty ( ) ) { this . graphStr . append ( " " ) . append ( node . getName ( ) ) . append ( " [label=\"" ) . append ( node . getFullName ( ) ) . append ( "\", shape=folder];\n" ) ; } return true ; }
Process current package configuration node .
1,932
public boolean visit ( final NamedParameterNode < ? > node ) { this . graphStr . append ( " " ) . append ( node . getName ( ) ) . append ( " [label=\"" ) . append ( node . getSimpleArgName ( ) ) . append ( "\\n" ) . append ( node . getName ( ) ) . append ( " = " ) . append ( config . getNamedParameter ( node ) ) . append ( "\\n(default = " ) . append ( instancesToString ( node . getDefaultInstanceAsStrings ( ) ) ) . append ( ")\", shape=oval];\n" ) ; return true ; }
Process current configuration node for the named parameter .
1,933
public boolean visit ( final Node nodeFrom , final Node nodeTo ) { if ( ! nodeFrom . getName ( ) . isEmpty ( ) ) { this . graphStr . append ( " " ) . append ( nodeFrom . getName ( ) ) . append ( " -> " ) . append ( nodeTo . getName ( ) ) . append ( " [style=solid, dir=back, arrowtail=diamond];\n" ) ; } return true ; }
Process current edge of the configuration graph .
1,934
private void init ( final Map < DistributedDataSetPartition , InputSplit [ ] > splitsPerPartition ) { final Pair < InputSplit [ ] , DistributedDataSetPartition [ ] > splitsAndPartitions = getSplitsAndPartitions ( splitsPerPartition ) ; final InputSplit [ ] splits = splitsAndPartitions . getFirst ( ) ; final DistributedDataSetPartition [ ] partitions = splitsAndPartitions . getSecond ( ) ; Validate . isTrue ( splits . length == partitions . length ) ; for ( int splitNum = 0 ; splitNum < splits . length ; splitNum ++ ) { LOG . log ( Level . FINE , "Processing split: " + splitNum ) ; final InputSplit split = splits [ splitNum ] ; final NumberedSplit < InputSplit > numberedSplit = new NumberedSplit < > ( split , splitNum , partitions [ splitNum ] ) ; unallocatedSplits . add ( numberedSplit ) ; updateLocations ( numberedSplit ) ; } if ( LOG . isLoggable ( Level . FINE ) ) { for ( final Map . Entry < String , BlockingQueue < NumberedSplit < InputSplit > > > locSplit : locationToSplits . entrySet ( ) ) { LOG . log ( Level . FINE , locSplit . getKey ( ) + ": " + locSplit . getValue ( ) . toString ( ) ) ; } } }
Initializes the locations of the splits where we d like to be loaded into . Sets all the splits to unallocated
1,935
protected NumberedSplit < InputSplit > allocateSplit ( final String evaluatorId , final BlockingQueue < NumberedSplit < InputSplit > > value ) { if ( value == null ) { LOG . log ( Level . FINE , "Queue of splits can't be empty. Returning null" ) ; return null ; } while ( true ) { final NumberedSplit < InputSplit > split = value . poll ( ) ; if ( split == null ) { return null ; } if ( value == unallocatedSplits || unallocatedSplits . remove ( split ) ) { LOG . log ( Level . FINE , "Found split-" + split . getIndex ( ) + " in the queue" ) ; final NumberedSplit < InputSplit > old = evaluatorToSplits . putIfAbsent ( evaluatorId , split ) ; if ( old != null ) { throw new RuntimeException ( "Trying to assign different splits to the same evaluator is not supported" ) ; } else { LOG . log ( Level . FINE , "Returning " + split . getIndex ( ) ) ; return split ; } } } }
Allocates the first available split into the evaluator .
1,936
public synchronized IdleMessage getIdleStatus ( ) { if ( this . isIdle ( ) ) { return IDLE_MESSAGE ; } final String message = String . format ( "There are %d outstanding container requests and %d allocated containers" , this . outstandingContainerRequests , this . containerAllocationCount ) ; return new IdleMessage ( COMPONENT_NAME , message , false ) ; }
Driver is idle if regardless of status it has no evaluators allocated and no pending container requests . This method is used in the DriverIdleManager . If all DriverIdlenessSource components are idle DriverIdleManager will initiate Driver shutdown .
1,937
public static void main ( final String [ ] args ) throws InjectionException { try ( final REEFEnvironment reef = REEFEnvironment . fromConfiguration ( LOCAL_DRIVER_MODULE , DRIVER_CONFIG , ENVIRONMENT_CONFIG ) ) { reef . run ( ) ; final ReefServiceProtos . JobStatusProto status = reef . getLastStatus ( ) ; LOG . log ( Level . INFO , "REEF job completed: {0}" , status ) ; } }
Start Hello REEF job with Driver and Client sharing the same process .
1,938
public byte [ ] encode ( final RemoteEvent < T > obj ) { if ( obj . getEvent ( ) == null ) { throw new RemoteRuntimeException ( "Event is null" ) ; } final WakeMessagePBuf . Builder builder = WakeMessagePBuf . newBuilder ( ) ; builder . setSeq ( obj . getSeq ( ) ) ; builder . setData ( ByteString . copyFrom ( encoder . encode ( obj . getEvent ( ) ) ) ) ; return builder . build ( ) . toByteArray ( ) ; }
Encodes the remote event object to bytes .
1,939
public static EvaluatorRequest fromString ( final String serializedRequest ) { try { final Decoder decoder = DecoderFactory . get ( ) . jsonDecoder ( AvroEvaluatorRequest . getClassSchema ( ) , serializedRequest ) ; final SpecificDatumReader < AvroEvaluatorRequest > reader = new SpecificDatumReader < > ( AvroEvaluatorRequest . class ) ; return fromAvro ( reader . read ( null , decoder ) ) ; } catch ( final IOException ex ) { throw new RuntimeException ( "Unable to deserialize compute request" , ex ) ; } }
Deserialize EvaluatorRequest .
1,940
public Void call ( final Void input ) throws Exception { System . out . println ( "Hello, Vortex!" ) ; return null ; }
Prints to stdout .
1,941
public Thread newThread ( final Runnable r ) { final Thread t = new Thread ( this . group , r , String . format ( "%s:thread-%03d" , this . prefix , this . threadNumber . getAndIncrement ( ) ) , 0 ) ; if ( t . isDaemon ( ) ) { t . setDaemon ( false ) ; } if ( t . getPriority ( ) != Thread . NORM_PRIORITY ) { t . setPriority ( Thread . NORM_PRIORITY ) ; } if ( this . uncaughtExceptionHandler != null ) { t . setUncaughtExceptionHandler ( this . uncaughtExceptionHandler ) ; } return t ; }
Creates a new thread .
1,942
public Configuration getConfiguration ( ) { return Tang . Factory . getTang ( ) . newConfigurationBuilder ( ) . bindNamedParameter ( TcpPortRangeBegin . class , String . valueOf ( portRangeBegin ) ) . bindNamedParameter ( TcpPortRangeCount . class , String . valueOf ( portRangeCount ) ) . bindNamedParameter ( TcpPortRangeTryCount . class , String . valueOf ( portRangeTryCount ) ) . bindSetEntry ( EvaluatorConfigurationProviders . class , TcpPortConfigurationProvider . class ) . build ( ) ; }
returns a configuration for the class that implements TcpPortProvider so that class can be instantiated . somewhere else
1,943
public synchronized void onInit ( ) { LOG . entering ( CLASS_NAME , "onInit" ) ; this . clientConnection . send ( this . getInitMessage ( ) ) ; this . setStatus ( DriverStatus . INIT ) ; LOG . exiting ( CLASS_NAME , "onInit" ) ; }
Changes the driver status to INIT and sends message to the client about the transition .
1,944
public synchronized void onError ( final Throwable exception ) { LOG . entering ( CLASS_NAME , "onError" , exception ) ; if ( this . isClosing ( ) ) { LOG . log ( Level . WARNING , "Received an exception while already in shutdown." , exception ) ; } else { LOG . log ( Level . WARNING , "Shutting down the Driver with an exception: " , exception ) ; this . shutdownCause = Optional . of ( exception ) ; this . clock . stop ( exception ) ; this . setStatus ( DriverStatus . FAILING ) ; } LOG . exiting ( CLASS_NAME , "onError" , exception ) ; }
End the Driver with an exception .
1,945
public synchronized void onComplete ( ) { LOG . entering ( CLASS_NAME , "onComplete" ) ; if ( this . isClosing ( ) ) { LOG . log ( Level . WARNING , "Ignoring second call to onComplete()" , new Exception ( "Dummy exception to get the call stack" ) ) ; } else { LOG . log ( Level . INFO , "Clean shutdown of the Driver." ) ; if ( LOG . isLoggable ( Level . FINEST ) ) { LOG . log ( Level . FINEST , "Call stack: " , new Exception ( "Dummy exception to get the call stack" ) ) ; } this . clock . close ( ) ; this . setStatus ( DriverStatus . SHUTTING_DOWN ) ; } LOG . exiting ( CLASS_NAME , "onComplete" ) ; }
Perform a clean shutdown of the Driver .
1,946
private synchronized void setStatus ( final DriverStatus toStatus ) { if ( this . driverStatus . isLegalTransition ( toStatus ) ) { this . driverStatus = toStatus ; } else { LOG . log ( Level . WARNING , "Illegal state transition: {0} -> {1}" , new Object [ ] { this . driverStatus , toStatus } ) ; } }
Helper method to set the status . This also checks whether the transition from the current status to the new one is legal .
1,947
public BatchCredentials getCredentials ( ) { final TokenCredentials tokenCredentials = new TokenCredentials ( null , System . getenv ( AZ_BATCH_AUTH_TOKEN_ENV ) ) ; return new BatchCredentials ( ) { public String baseUrl ( ) { return azureBatchAccountUri ; } public void applyCredentialsFilter ( final OkHttpClient . Builder builder ) { tokenCredentials . applyCredentialsFilter ( builder ) ; } } ; }
Returns credentials for Azure Batch account .
1,948
< T > Link < NetworkConnectionServiceMessage < T > > openLink ( final Identifier connectionFactoryId , final Identifier remoteEndPointId ) throws NetworkException { final Identifier remoteId = getEndPointIdWithConnectionFactoryId ( connectionFactoryId , remoteEndPointId ) ; try { final SocketAddress address = nameResolver . lookup ( remoteId ) ; if ( address == null ) { throw new NetworkException ( "Lookup " + remoteId + " is null" ) ; } return transport . open ( address , nsCodec , nsLinkListener ) ; } catch ( final Exception e ) { throw new NetworkException ( e ) ; } }
Open a channel for destination identifier of NetworkConnectionService .
1,949
public < T > ConnectionFactory < T > getConnectionFactory ( final Identifier connFactoryId ) { final ConnectionFactory < T > connFactory = connFactoryMap . get ( connFactoryId . toString ( ) ) ; if ( connFactory == null ) { throw new RuntimeException ( "Cannot find ConnectionFactory of " + connFactoryId + "." ) ; } return connFactory ; }
Gets a ConnectionFactory .
1,950
public < TInput , TOutput > VortexFuture < TOutput > enqueueTasklet ( final VortexFunction < TInput , TOutput > function , final TInput input , final Optional < FutureCallback < TOutput > > callback ) { final VortexFuture < TOutput > vortexFuture ; final int id = taskletIdCounter . getAndIncrement ( ) ; if ( callback . isPresent ( ) ) { vortexFuture = new VortexFuture < > ( executor , this , id , callback . get ( ) ) ; } else { vortexFuture = new VortexFuture < > ( executor , this , id ) ; } final Tasklet tasklet = new Tasklet < > ( id , Optional . < Integer > empty ( ) , function , input , vortexFuture ) ; putDelegate ( Collections . singletonList ( tasklet ) , vortexFuture ) ; this . pendingTasklets . addLast ( tasklet ) ; return vortexFuture ; }
Add a new tasklet to pendingTasklets .
1,951
public < TInput , TOutput > VortexAggregateFuture < TInput , TOutput > enqueueTasklets ( final VortexAggregateFunction < TOutput > aggregateFunction , final VortexFunction < TInput , TOutput > vortexFunction , final VortexAggregatePolicy policy , final List < TInput > inputs , final Optional < FutureCallback < AggregateResult < TInput , TOutput > > > callback ) { final int aggregateFunctionId = aggregateIdCounter . getAndIncrement ( ) ; aggregateFunctionRepository . put ( aggregateFunctionId , aggregateFunction , policy ) ; final List < Tasklet > tasklets = new ArrayList < > ( inputs . size ( ) ) ; final Map < Integer , TInput > taskletIdInputMap = new HashMap < > ( inputs . size ( ) ) ; for ( final TInput input : inputs ) { taskletIdInputMap . put ( taskletIdCounter . getAndIncrement ( ) , input ) ; } final VortexAggregateFuture < TInput , TOutput > vortexAggregateFuture ; if ( callback . isPresent ( ) ) { vortexAggregateFuture = new VortexAggregateFuture < > ( executor , taskletIdInputMap , callback . get ( ) ) ; } else { vortexAggregateFuture = new VortexAggregateFuture < > ( executor , taskletIdInputMap , null ) ; } for ( final Map . Entry < Integer , TInput > taskletIdInputEntry : taskletIdInputMap . entrySet ( ) ) { final Tasklet tasklet = new Tasklet < > ( taskletIdInputEntry . getKey ( ) , Optional . of ( aggregateFunctionId ) , vortexFunction , taskletIdInputEntry . getValue ( ) , vortexAggregateFuture ) ; tasklets . add ( tasklet ) ; pendingTasklets . addLast ( tasklet ) ; } putDelegate ( tasklets , vortexAggregateFuture ) ; return vortexAggregateFuture ; }
Add aggregate - able Tasklets to pendingTasklets .
1,952
public void workerPreempted ( final String id ) { final Optional < Collection < Tasklet > > preemptedTasklets = runningWorkers . removeWorker ( id ) ; if ( preemptedTasklets . isPresent ( ) ) { for ( final Tasklet tasklet : preemptedTasklets . get ( ) ) { pendingTasklets . addFirst ( tasklet ) ; } } }
Remove the worker from runningWorkers and add back the lost tasklets to pendingTasklets .
1,953
private synchronized void putDelegate ( final List < Tasklet > tasklets , final VortexFutureDelegate delegate ) { for ( final Tasklet tasklet : tasklets ) { taskletFutureMap . put ( tasklet . getId ( ) , delegate ) ; } }
Puts a delegate to associate with a Tasklet .
1,954
private synchronized VortexFutureDelegate fetchDelegate ( final List < Integer > taskletIds ) { VortexFutureDelegate delegate = null ; for ( final int taskletId : taskletIds ) { final VortexFutureDelegate currDelegate = taskletFutureMap . remove ( taskletId ) ; if ( currDelegate == null ) { throw new RuntimeException ( "Tasklet should only be removed once." ) ; } if ( delegate == null ) { delegate = currDelegate ; } else { assert delegate == currDelegate ; } } return delegate ; }
Fetches a delegate that maps to the list of Tasklets .
1,955
private File makeGlobalJar ( ) throws IOException { final File jarFile = new File ( this . fileNames . getGlobalFolderName ( ) + this . fileNames . getJarFileSuffix ( ) ) ; new JARFileMaker ( jarFile ) . addChildren ( this . fileNames . getGlobalFolder ( ) ) . close ( ) ; return jarFile ; }
Creates the JAR file for upload .
1,956
@ SuppressWarnings ( "unchecked" ) public static < T > T [ ] nullToEmpty ( final T [ ] array ) { return array == null ? ( T [ ] ) EMPTY_ARRAY : array ; }
Return an empty array if input is null ; works as identity function otherwise . This function is useful in for statements if the iterable can be null .
1,957
public void set ( final String name , final UserCredentials other ) throws IOException { throw new RuntimeException ( "Not implemented! Attempt to set user " + name + " from: " + other ) ; }
Copy credentials from another existing user . This method can be called only once per instance . This default implementation should never be called .
1,958
public Time scheduleAlarm ( final int offset , final EventHandler < Alarm > handler ) { final Time alarm = new ClientAlarm ( this . timer . getCurrent ( ) + offset , handler ) ; if ( LOG . isLoggable ( Level . FINEST ) ) { final int eventQueueLen ; synchronized ( this . schedule ) { eventQueueLen = this . numClientAlarms ; } LOG . log ( Level . FINEST , "Schedule alarm: {0} Outstanding client alarms: {1}" , new Object [ ] { alarm , eventQueueLen } ) ; } synchronized ( this . schedule ) { if ( this . isClosed ) { throw new IllegalStateException ( "Scheduling alarm on a closed clock" ) ; } if ( alarm . getTimestamp ( ) > this . lastClientAlarm ) { this . lastClientAlarm = alarm . getTimestamp ( ) ; } assert this . numClientAlarms >= 0 ; ++ this . numClientAlarms ; this . schedule . add ( alarm ) ; this . schedule . notify ( ) ; } return alarm ; }
Schedule a new Alarm event in offset milliseconds into the future and supply an event handler to be called at that time .
1,959
public void stop ( final Throwable exception ) { LOG . entering ( CLASS_NAME , "stop" ) ; synchronized ( this . schedule ) { if ( this . isClosed ) { LOG . log ( Level . FINEST , "Clock has already been closed" ) ; return ; } this . isClosed = true ; this . exceptionCausedStop = exception ; final Time stopEvent = new StopTime ( this . timer . getCurrent ( ) ) ; LOG . log ( Level . FINE , "Stop scheduled immediately: {0} Outstanding client alarms: {1}" , new Object [ ] { stopEvent , this . numClientAlarms } ) ; assert this . numClientAlarms >= 0 ; this . numClientAlarms = 0 ; this . schedule . clear ( ) ; this . schedule . add ( stopEvent ) ; this . schedule . notify ( ) ; } LOG . exiting ( CLASS_NAME , "stop" ) ; }
Stop the clock on exception . Remove all other events from the schedule and fire StopTimer event immediately .
1,960
public void close ( ) { LOG . entering ( CLASS_NAME , "close" ) ; synchronized ( this . schedule ) { if ( this . isClosed ) { LOG . exiting ( CLASS_NAME , "close" , "Clock has already been closed" ) ; return ; } this . isClosed = true ; final Time stopEvent = new StopTime ( Math . max ( this . timer . getCurrent ( ) , this . lastClientAlarm + 1 ) ) ; LOG . log ( Level . FINE , "Graceful shutdown scheduled: {0} Outstanding client alarms: {1}" , new Object [ ] { stopEvent , this . numClientAlarms } ) ; this . schedule . add ( stopEvent ) ; this . schedule . notify ( ) ; } LOG . exiting ( CLASS_NAME , "close" ) ; }
Wait for all client alarms to finish executing and gracefully shutdown the clock .
1,961
@ SuppressWarnings ( "checkstyle:hiddenfield" ) private < T extends Time > void subscribe ( final Class < T > eventClass , final Set < EventHandler < T > > handlers ) { for ( final EventHandler < T > handler : handlers ) { LOG . log ( Level . FINEST , "Subscribe: event {0} handler {1}" , new Object [ ] { eventClass . getName ( ) , handler } ) ; this . handlers . subscribe ( eventClass , handler ) ; } }
Register event handlers for the given event class .
1,962
void release ( final String containerId ) { LOG . log ( Level . FINE , "Release container: {0}" , containerId ) ; final Container container = this . containers . removeAndGet ( containerId ) ; this . resourceManager . releaseAssignedContainer ( container . getId ( ) ) ; updateRuntimeStatus ( ) ; }
Release the given container .
1,963
void onStart ( ) { LOG . log ( Level . FINEST , "YARN registration: begin" ) ; this . nodeManager . init ( this . yarnConf ) ; this . nodeManager . start ( ) ; try { this . yarnProxyUser . doAs ( new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws Exception { resourceManager . init ( yarnConf ) ; resourceManager . start ( ) ; return null ; } } ) ; LOG . log ( Level . FINE , "YARN registration: register AM at \"{0}:{1}\" tracking URL \"{2}\"" , new Object [ ] { amRegistrationHost , AM_REGISTRATION_PORT , this . trackingUrl } ) ; this . registration . setRegistration ( this . resourceManager . registerApplicationMaster ( amRegistrationHost , AM_REGISTRATION_PORT , this . trackingUrl ) ) ; LOG . log ( Level . FINE , "YARN registration: AM registered: {0}" , this . registration ) ; final FileSystem fs = FileSystem . get ( this . yarnConf ) ; final Path outputFileName = new Path ( this . jobSubmissionDirectory , this . reefFileNames . getDriverHttpEndpoint ( ) ) ; try ( final FSDataOutputStream out = fs . create ( outputFileName ) ) { out . writeBytes ( this . trackingUrl + '\n' ) ; } } catch ( final Exception e ) { LOG . log ( Level . WARNING , "Unable to register application master." , e ) ; onRuntimeError ( e ) ; } LOG . log ( Level . FINEST , "YARN registration: done: {0}" , this . registration ) ; }
Start the YARN container manager . This method is called from DriverRuntimeStartHandler via YARNRuntimeStartHandler .
1,964
void onStop ( final Throwable exception ) { LOG . log ( Level . FINE , "Stop Runtime: RM status {0}" , this . resourceManager . getServiceState ( ) ) ; if ( this . resourceManager . getServiceState ( ) == Service . STATE . STARTED ) { try { this . reefEventHandlers . close ( ) ; if ( exception == null ) { this . resourceManager . unregisterApplicationMaster ( FinalApplicationStatus . SUCCEEDED , "Success!" , this . trackingUrl ) ; } else { final String failureMsg = String . format ( "Application failed due to:%n%s%n" + "With stack trace:%n%s" , exception . getMessage ( ) , ExceptionUtils . getStackTrace ( exception ) ) ; this . resourceManager . unregisterApplicationMaster ( FinalApplicationStatus . FAILED , failureMsg , this . trackingUrl ) ; } this . resourceManager . close ( ) ; LOG . log ( Level . FINEST , "Container ResourceManager stopped successfully" ) ; } catch ( final Exception e ) { LOG . log ( Level . WARNING , "Error shutting down YARN application" , e ) ; } } if ( this . nodeManager . getServiceState ( ) == Service . STATE . STARTED ) { try { this . nodeManager . close ( ) ; LOG . log ( Level . FINEST , "Container NodeManager stopped successfully" ) ; } catch ( final IOException e ) { LOG . log ( Level . WARNING , "Error closing YARN Node Manager" , e ) ; } } }
Shut down YARN container manager . This method is called from DriverRuntimeStopHandler via YARNRuntimeStopHandler .
1,965
private void onContainerStatus ( final ContainerStatus value ) { final String containerId = value . getContainerId ( ) . toString ( ) ; final boolean hasContainer = this . containers . hasContainer ( containerId ) ; if ( hasContainer ) { LOG . log ( Level . FINE , "Received container status: {0}" , containerId ) ; final ResourceStatusEventImpl . Builder status = ResourceStatusEventImpl . newBuilder ( ) . setIdentifier ( containerId ) ; switch ( value . getState ( ) ) { case COMPLETE : LOG . log ( Level . FINE , "Container completed: status {0}" , value . getExitStatus ( ) ) ; switch ( value . getExitStatus ( ) ) { case 0 : status . setState ( State . DONE ) ; break ; case 143 : status . setState ( State . KILLED ) ; break ; default : status . setState ( State . FAILED ) ; } status . setExitCode ( value . getExitStatus ( ) ) ; break ; default : LOG . info ( "Container running" ) ; status . setState ( State . RUNNING ) ; } if ( value . getDiagnostics ( ) != null ) { LOG . log ( Level . FINE , "Container diagnostics: {0}" , value . getDiagnostics ( ) ) ; status . setDiagnostics ( value . getDiagnostics ( ) ) ; } this . reefEventHandlers . onResourceStatus ( status . build ( ) ) ; } }
Handles container status reports . Calls come from YARN .
1,966
private void handleNewContainer ( final Container container ) { LOG . log ( Level . FINE , "allocated container: id[ {0} ]" , container . getId ( ) ) ; synchronized ( this ) { if ( ! matchContainerWithPendingRequest ( container ) ) { LOG . log ( Level . WARNING , "Got an extra container {0} that doesn't match, releasing..." , container . getId ( ) ) ; this . resourceManager . releaseAssignedContainer ( container . getId ( ) ) ; return ; } final AMRMClient . ContainerRequest matchedRequest = this . requestsAfterSentToRM . peek ( ) ; this . containerRequestCounter . decrement ( ) ; this . containers . add ( container ) ; LOG . log ( Level . FINEST , "{0} matched with {1}" , new Object [ ] { container , matchedRequest } ) ; if ( this . requestsAfterSentToRM . size ( ) > 1 ) { try { this . resourceManager . removeContainerRequest ( matchedRequest ) ; } catch ( final Exception e ) { LOG . log ( Level . WARNING , "Error removing request from Async AMRM client queue: " + matchedRequest , e ) ; } } this . requestsAfterSentToRM . remove ( ) ; this . doHomogeneousRequests ( ) ; LOG . log ( Level . FINEST , "Allocated Container: memory = {0}, core number = {1}" , new Object [ ] { container . getResource ( ) . getMemory ( ) , container . getResource ( ) . getVirtualCores ( ) } ) ; this . reefEventHandlers . onResourceAllocation ( ResourceEventImpl . newAllocationBuilder ( ) . setIdentifier ( container . getId ( ) . toString ( ) ) . setNodeId ( container . getNodeId ( ) . toString ( ) ) . setResourceMemory ( container . getResource ( ) . getMemory ( ) ) . setVirtualCores ( container . getResource ( ) . getVirtualCores ( ) ) . setRackName ( rackNameFormatter . getRackName ( container ) ) . setRuntimeName ( RuntimeIdentifier . RUNTIME_NAME ) . build ( ) ) ; this . updateRuntimeStatus ( ) ; } }
Handles new container allocations . Calls come from YARN .
1,967
private boolean matchContainerWithPendingRequest ( final Container container ) { if ( this . requestsAfterSentToRM . isEmpty ( ) ) { return false ; } final AMRMClient . ContainerRequest request = this . requestsAfterSentToRM . peek ( ) ; final boolean resourceCondition = container . getResource ( ) . getMemory ( ) >= request . getCapability ( ) . getMemory ( ) ; final boolean nodeCondition = request . getNodes ( ) == null || request . getNodes ( ) . contains ( container . getNodeId ( ) . getHost ( ) ) ; final boolean rackCondition = request . getRacks ( ) == null || request . getRacks ( ) . contains ( this . nodeIdToRackName . get ( container . getNodeId ( ) . toString ( ) ) ) ; return resourceCondition && ( request . getRelaxLocality ( ) || rackCondition && nodeCondition ) ; }
Match to see whether the container satisfies the request . We take into consideration that RM has some freedom in rounding up the allocation and in placing containers on other machines .
1,968
private void updateRuntimeStatus ( ) { final RuntimeStatusEventImpl . Builder builder = RuntimeStatusEventImpl . newBuilder ( ) . setName ( RUNTIME_NAME ) . setState ( State . RUNNING ) . setOutstandingContainerRequests ( this . containerRequestCounter . get ( ) ) ; for ( final String allocatedContainerId : this . containers . getContainerIds ( ) ) { builder . addContainerAllocation ( allocatedContainerId ) ; } this . reefEventHandlers . onRuntimeStatus ( builder . build ( ) ) ; }
Update the driver with my current status .
1,969
private void refreshEffectiveTopology ( ) throws ParentDeadException { LOG . entering ( "OperatorTopologyImpl" , "refreshEffectiveTopology" , getQualifiedName ( ) ) ; LOG . finest ( getQualifiedName ( ) + "Waiting to acquire topoLock" ) ; synchronized ( topologyLock ) { LOG . finest ( getQualifiedName ( ) + "Acquired topoLock" ) ; assert effectiveTopology != null ; final Set < GroupCommunicationMessage > deletionDeltasSet = new HashSet < > ( ) ; copyDeletionDeltas ( deletionDeltasSet ) ; LOG . finest ( getQualifiedName ( ) + "Updating effective topology struct with deletion msgs" ) ; effectiveTopology . update ( deletionDeltasSet ) ; LOG . finest ( getQualifiedName ( ) + "Released topoLock" ) ; } LOG . exiting ( "OperatorTopologyImpl" , "refreshEffectiveTopology" , getQualifiedName ( ) ) ; }
Only refreshes the effective topology with deletion msgs from . deletionDeltas queue
1,970
public void write ( final Writer outputWriter ) throws IOException { try ( final DataInputStream keyStream = entry . getKeyStream ( ) ; final DataInputStream valueStream = entry . getValueStream ( ) ; ) { outputWriter . write ( "Container: " ) ; outputWriter . write ( keyStream . readUTF ( ) ) ; outputWriter . write ( "\n" ) ; this . writeFiles ( valueStream , outputWriter ) ; } }
Writes the contents of the entry into the given outputWriter .
1,971
public void write ( final File folder ) throws IOException { try ( final DataInputStream keyStream = entry . getKeyStream ( ) ; final DataInputStream valueStream = entry . getValueStream ( ) ; ) { final String containerId = keyStream . readUTF ( ) ; try ( final Writer outputWriter = new OutputStreamWriter ( new FileOutputStream ( new File ( folder , containerId + ".txt" ) ) , StandardCharsets . UTF_8 ) ) { this . writeFiles ( valueStream , outputWriter ) ; } } }
Writes the logs stored in the entry as text files in folder one per container .
1,972
private void writeFiles ( final DataInputStream valueStream , final Writer outputWriter ) throws IOException { while ( valueStream . available ( ) > 0 ) { final String strFileName = valueStream . readUTF ( ) ; final int entryLength = Integer . parseInt ( valueStream . readUTF ( ) ) ; outputWriter . write ( "=====================================================\n" ) ; outputWriter . write ( "File Name: " + strFileName + "\n" ) ; outputWriter . write ( "File Length: " + entryLength + "\n" ) ; outputWriter . write ( "-----------------------------------------------------\n" ) ; this . write ( valueStream , outputWriter , entryLength ) ; outputWriter . write ( "\n" ) ; } }
Writes the logs of the next container to the given writer . Assumes that the valueStream is suitably positioned .
1,973
private void write ( final DataInputStream stream , final Writer outputWriter , final int numberOfBytes ) throws IOException { final byte [ ] buf = new byte [ 65535 ] ; int lenRemaining = numberOfBytes ; while ( lenRemaining > 0 ) { final int len = stream . read ( buf , 0 , lenRemaining > 65535 ? 65535 : lenRemaining ) ; if ( len > 0 ) { outputWriter . write ( new String ( buf , 0 , len , "UTF-8" ) ) ; lenRemaining -= len ; } else { break ; } } }
Writes the next numberOfBytes bytes from the stream to the outputWriter assuming that the bytes are UTF - 8 encoded characters .
1,974
public void set ( final String name , final UserCredentials hostUser ) throws IOException { assert this . proxyUGI == null ; assert hostUser instanceof YarnProxyUser ; LOG . log ( Level . FINE , "UGI: user {0} copy from: {1}" , new Object [ ] { name , hostUser } ) ; final UserGroupInformation hostUGI = ( ( YarnProxyUser ) hostUser ) . get ( ) ; final Collection < Token < ? extends TokenIdentifier > > tokens = hostUGI . getCredentials ( ) . getAllTokens ( ) ; this . set ( name , hostUGI , tokens . toArray ( new Token [ tokens . size ( ) ] ) ) ; }
Set YARN user . This method can be called only once per class instance .
1,975
public final void set ( final String proxyName , final UserGroupInformation hostUGI , final Token < ? extends TokenIdentifier > ... tokens ) { assert this . proxyUGI == null ; this . proxyUGI = UserGroupInformation . createProxyUser ( proxyName , hostUGI ) ; for ( final Token < ? extends TokenIdentifier > token : tokens ) { this . proxyUGI . addToken ( token ) ; } LOG . log ( Level . FINE , "UGI: user {0} set to: {1}" , new Object [ ] { proxyName , this } ) ; }
Create YARN proxy user and add security tokens to its credentials . This method can be called only once per class instance .
1,976
public < T > T doAs ( final PrivilegedExceptionAction < T > action ) throws Exception { LOG . log ( Level . FINE , "{0} execute {1}" , new Object [ ] { this , action } ) ; return this . proxyUGI == null ? action . run ( ) : this . proxyUGI . doAs ( action ) ; }
Execute the privileged action as a given user . If user credentials are not set execute the action outside the user context .
1,977
public byte [ ] call ( final byte [ ] memento ) { LOG . log ( Level . FINE , "Task started: sleep for: {0} msec." , this . delay ) ; final long ts = System . currentTimeMillis ( ) ; for ( long period = this . delay ; period > 0 ; period -= System . currentTimeMillis ( ) - ts ) { try { Thread . sleep ( period ) ; } catch ( final InterruptedException ex ) { LOG . log ( Level . FINEST , "Interrupted: {0}" , ex ) ; } } LOG . log ( Level . FINE , "Task finished after {0} msec." , System . currentTimeMillis ( ) - ts ) ; return null ; }
Sleep for delay milliseconds and return .
1,978
JobSubmissionEventImpl . Builder getJobSubmissionBuilder ( final Configuration driverConfiguration ) throws InjectionException , IOException { final Injector injector = Tang . Factory . getTang ( ) . newInjector ( driverConfiguration ) ; final boolean preserveEvaluators = injector . getNamedInstance ( ResourceManagerPreserveEvaluators . class ) ; final int maxAppSubmissions = injector . getNamedInstance ( MaxApplicationSubmissions . class ) ; final JobSubmissionEventImpl . Builder jbuilder = JobSubmissionEventImpl . newBuilder ( ) . setIdentifier ( returnOrGenerateDriverId ( injector . getNamedInstance ( DriverIdentifier . class ) ) ) . setDriverMemory ( injector . getNamedInstance ( DriverMemory . class ) ) . setDriverCpuCores ( injector . getNamedInstance ( DriverCPUCores . class ) ) . setUserName ( System . getProperty ( "user.name" ) ) . setPreserveEvaluators ( preserveEvaluators ) . setMaxApplicationSubmissions ( maxAppSubmissions ) . setConfiguration ( driverConfiguration ) ; for ( final String globalFileName : injector . getNamedInstance ( JobGlobalFiles . class ) ) { LOG . log ( Level . FINEST , "Adding global file: {0}" , globalFileName ) ; jbuilder . addGlobalFile ( getFileResourceProto ( globalFileName , FileType . PLAIN ) ) ; } for ( final String globalLibraryName : injector . getNamedInstance ( JobGlobalLibraries . class ) ) { LOG . log ( Level . FINEST , "Adding global library: {0}" , globalLibraryName ) ; jbuilder . addGlobalFile ( getFileResourceProto ( globalLibraryName , FileType . LIB ) ) ; } for ( final String localFileName : injector . getNamedInstance ( DriverLocalFiles . class ) ) { LOG . log ( Level . FINEST , "Adding local file: {0}" , localFileName ) ; jbuilder . addLocalFile ( getFileResourceProto ( localFileName , FileType . PLAIN ) ) ; } for ( final String localLibraryName : injector . getNamedInstance ( DriverLocalLibraries . class ) ) { LOG . log ( Level . FINEST , "Adding local library: {0}" , localLibraryName ) ; jbuilder . addLocalFile ( getFileResourceProto ( localLibraryName , FileType . LIB ) ) ; } return jbuilder ; }
Fils out a JobSubmissionProto based on the driver configuration given .
1,979
private static FileResource getFileResourceProto ( final String fileName , final FileType type ) throws IOException { File file = new File ( fileName ) ; if ( file . exists ( ) ) { if ( file . isDirectory ( ) ) { file = toJar ( file ) ; } return FileResourceImpl . newBuilder ( ) . setName ( file . getName ( ) ) . setPath ( file . getPath ( ) ) . setType ( type ) . build ( ) ; } else { try { final URI uri = new URI ( fileName ) ; final String path = uri . getPath ( ) ; final String name = path . substring ( path . lastIndexOf ( '/' ) + 1 ) ; return FileResourceImpl . newBuilder ( ) . setName ( name ) . setPath ( uri . toString ( ) ) . setType ( type ) . build ( ) ; } catch ( final URISyntaxException e ) { throw new IOException ( "Unable to parse URI." , e ) ; } } }
Turns a pathname into the right protocol for job submission .
1,980
private static File toJar ( final File file ) throws IOException { final File tempFolder = Files . createTempDirectory ( "reef-tmp-tempFolder" ) . toFile ( ) ; final File jarFile = File . createTempFile ( file . getCanonicalFile ( ) . getName ( ) , ".jar" , tempFolder ) ; LOG . log ( Level . FINEST , "Adding contents of folder {0} to {1}" , new Object [ ] { file , jarFile } ) ; try ( final JARFileMaker jarMaker = new JARFileMaker ( jarFile ) ) { jarMaker . addChildren ( file ) ; } return jarFile ; }
Turns temporary folder foo into a jar file foo . jar .
1,981
private static Throwable getThrowable ( final RuntimeErrorProto error ) { final byte [ ] data = getData ( error ) ; if ( data != null ) { try { return CODEC . decode ( data ) ; } catch ( final RemoteRuntimeException ex ) { LOG . log ( Level . FINE , "Could not decode exception {0}: {1}" , new Object [ ] { error , ex } ) ; } } return null ; }
Retrieve Java exception from protobuf object if possible . Otherwise return null . This is a utility method used in the FailedRuntime constructor .
1,982
public ApplicationID getApplicationID ( ) throws IOException { final String url = "ws/v1/cluster/apps/new-application" ; final HttpPost post = preparePost ( url ) ; try ( final CloseableHttpResponse response = this . httpClient . execute ( post , this . httpClientContext ) ) { final String message = IOUtils . toString ( response . getEntity ( ) . getContent ( ) ) ; final ApplicationID result = this . objectMapper . readValue ( message , ApplicationID . class ) ; return result ; } }
Request an ApplicationId from the cluster .
1,983
public void submitApplication ( final ApplicationSubmission applicationSubmission ) throws IOException { final String url = "ws/v1/cluster/apps" ; final HttpPost post = preparePost ( url ) ; final StringWriter writer = new StringWriter ( ) ; try { this . objectMapper . writeValue ( writer , applicationSubmission ) ; } catch ( final IOException e ) { throw new RuntimeException ( e ) ; } final String message = writer . toString ( ) ; LOG . log ( Level . FINE , "Sending:\n{0}" , message . replace ( "\n" , "\n\t" ) ) ; post . setEntity ( new StringEntity ( message , ContentType . APPLICATION_JSON ) ) ; try ( final CloseableHttpResponse response = this . httpClient . execute ( post , this . httpClientContext ) ) { final String responseMessage = IOUtils . toString ( response . getEntity ( ) . getContent ( ) ) ; LOG . log ( Level . FINE , "Response: {0}" , responseMessage . replace ( "\n" , "\n\t" ) ) ; } }
Submits an application for execution .
1,984
public void killApplication ( final String applicationId ) throws IOException { final String url = this . getApplicationURL ( applicationId ) + "/state" ; final HttpPut put = preparePut ( url ) ; put . setEntity ( new StringEntity ( APPLICATION_KILL_MESSAGE , ContentType . APPLICATION_JSON ) ) ; this . httpClient . execute ( put , this . httpClientContext ) ; }
Issues a YARN kill command to the application .
1,985
public ApplicationState getApplication ( final String applicationId ) throws IOException { final String url = this . getApplicationURL ( applicationId ) ; final HttpGet get = prepareGet ( url ) ; try ( final CloseableHttpResponse response = this . httpClient . execute ( get , this . httpClientContext ) ) { final String message = IOUtils . toString ( response . getEntity ( ) . getContent ( ) ) ; final ApplicationResponse result = this . objectMapper . readValue ( message , ApplicationResponse . class ) ; return result . getApplicationState ( ) ; } }
Gets the application state given a YARN application ID .
1,986
private HttpGet prepareGet ( final String url ) { final HttpGet httpGet = new HttpGet ( this . instanceUrl + url ) ; for ( final Header header : this . headers ) { httpGet . addHeader ( header ) ; } return httpGet ; }
Creates a HttpGet request with all the common headers .
1,987
private HttpPost preparePost ( final String url ) { final HttpPost httpPost = new HttpPost ( this . instanceUrl + url ) ; for ( final Header header : this . headers ) { httpPost . addHeader ( header ) ; } return httpPost ; }
Creates a HttpPost request with all the common headers .
1,988
private HttpPut preparePut ( final String url ) { final HttpPut httpPut = new HttpPut ( this . instanceUrl + url ) ; for ( final Header header : this . headers ) { httpPut . addHeader ( header ) ; } return httpPut ; }
Creates a HttpPut request with all the common headers .
1,989
public void onNext ( final Alarm alarm ) { String jobId = this . azureBatchHelper . getAzureBatchJobId ( ) ; List < CloudTask > allTasks = this . azureBatchHelper . getTaskStatusForJob ( jobId ) ; LOG . log ( Level . FINER , "Found {0} tasks from job id {1}" , new Object [ ] { allTasks . size ( ) , jobId } ) ; for ( CloudTask task : allTasks ) { Optional < EvaluatorManager > optionalEvaluatorManager = this . evaluators . get ( task . id ( ) ) ; if ( ! optionalEvaluatorManager . isPresent ( ) && ! TaskState . COMPLETED . equals ( task . state ( ) ) ) { LOG . log ( Level . FINE , "No Evaluator found for Azure Batch task id = {0}. Ignoring." , task . id ( ) ) ; } else if ( ! optionalEvaluatorManager . isPresent ( ) && TaskState . COMPLETED . equals ( task . state ( ) ) ) { LOG . log ( Level . INFO , "Azure Batch task id = {0} is in 'COMPLETED' state, but it does not have " + "an Evaluator associated with it. This indicates that the evaluator shim has failed before " + "it could send a callback to the driver." , task . id ( ) ) ; this . evaluatorShimManager . get ( ) . onResourceAllocated ( task . id ( ) , PLACEHOLDER_REMOTE_ID , Optional . of ( task ) ) ; } else if ( optionalEvaluatorManager . get ( ) . isClosedOrClosing ( ) ) { LOG . log ( Level . FINE , "Evaluator id = {0} is closed. Ignoring." , task . id ( ) ) ; } else { LOG . log ( Level . FINE , "Reporting status for Task Id: {0} is [Azure Batch Status]:{1} " , new Object [ ] { task . id ( ) , task . state ( ) . toString ( ) } ) ; this . evaluatorShimManager . get ( ) . onAzureBatchTaskStatus ( task ) ; } } synchronized ( this ) { if ( this . isAlarmEnabled ( ) ) { this . scheduleAlarm ( ) ; } } }
This method is periodically invoked by the Runtime Clock . It will call Azure Batch APIs to determine the status of tasks running inside the job and notify REEF of tasks statuses that correspond to running evaluators .
1,990
public synchronized void enableAlarm ( ) { if ( ! this . isAlarmEnabled ) { LOG . log ( Level . FINE , "Enabling the alarm and scheduling it to fire in {0} ms." , this . taskStatusCheckPeriod ) ; this . isAlarmEnabled = true ; this . scheduleAlarm ( ) ; } else { LOG . log ( Level . FINE , "Alarm is already enabled." ) ; } }
Enable the period alarm to send status updates .
1,991
public synchronized int submitCommand ( final String command ) { final Integer id = scheduler . assignTaskId ( ) ; scheduler . addTask ( new TaskEntity ( id , command ) ) ; if ( state == State . READY ) { notify ( ) ; } else if ( state == State . RUNNING && nMaxEval > nActiveEval + nRequestedEval ) { requestEvaluator ( 1 ) ; } return id ; }
Submit a command to schedule .
1,992
public synchronized int setMaxEvaluators ( final int targetNum ) throws UnsuccessfulException { if ( targetNum < nActiveEval + nRequestedEval ) { throw new UnsuccessfulException ( nActiveEval + nRequestedEval + " evaluators are used now. Should be larger than that." ) ; } nMaxEval = targetNum ; if ( scheduler . hasPendingTasks ( ) ) { final int nToRequest = Math . min ( scheduler . getNumPendingTasks ( ) , nMaxEval - nActiveEval ) - nRequestedEval ; requestEvaluator ( nToRequest ) ; } return nMaxEval ; }
Update the maximum number of evaluators to hold . Request more evaluators in case there are pending tasks in the queue and the number of evaluators is less than the limit .
1,993
private synchronized void requestEvaluator ( final int numToRequest ) { if ( numToRequest <= 0 ) { throw new IllegalArgumentException ( "The number of evaluator request should be a positive integer" ) ; } nRequestedEval += numToRequest ; requestor . newRequest ( ) . setMemory ( 32 ) . setNumber ( numToRequest ) . submit ( ) ; }
Request evaluators . Passing a non positive number is illegal so it does not make a trial for that situation .
1,994
private synchronized void waitForCommands ( final ActiveContext context ) { while ( ! scheduler . hasPendingTasks ( ) ) { try { wait ( ) ; } catch ( final InterruptedException e ) { LOG . log ( Level . WARNING , "InterruptedException occurred in SchedulerDriver" , e ) ; } } state = State . RUNNING ; scheduler . submitTask ( context ) ; }
Pick up a command from the queue and run it . Wait until any command coming up if no command exists .
1,995
private synchronized void retainEvaluator ( final ActiveContext context ) { if ( scheduler . hasPendingTasks ( ) ) { scheduler . submitTask ( context ) ; } else if ( nActiveEval > 1 ) { nActiveEval -- ; context . close ( ) ; } else { state = State . READY ; waitForCommands ( context ) ; } }
Retain the complete evaluators submitting another task until there is no need to reuse them .
1,996
private synchronized void reallocateEvaluator ( final ActiveContext context ) { nActiveEval -- ; context . close ( ) ; if ( scheduler . hasPendingTasks ( ) ) { requestEvaluator ( 1 ) ; } else if ( nActiveEval <= 0 ) { state = State . WAIT_EVALUATORS ; requestEvaluator ( 1 ) ; } }
Always close the complete evaluators and allocate a new evaluator if necessary .
1,997
Map < String , LocalResource > getResources ( final ResourceLaunchEvent resourceLaunchEvent ) throws IOException { final Map < String , LocalResource > result = new HashMap < > ( ) ; result . putAll ( getGlobalResources ( ) ) ; final File localStagingFolder = this . tempFileCreator . createTempDirectory ( this . fileNames . getEvaluatorFolderPrefix ( ) ) ; final File configurationFile = new File ( localStagingFolder , this . fileNames . getEvaluatorConfigurationName ( ) ) ; this . configurationSerializer . toFile ( makeEvaluatorConfiguration ( resourceLaunchEvent ) , configurationFile ) ; JobJarMaker . copy ( resourceLaunchEvent . getFileSet ( ) , localStagingFolder ) ; final File localFile = tempFileCreator . createTempFile ( this . fileNames . getEvaluatorFolderPrefix ( ) , this . fileNames . getJarFileSuffix ( ) ) ; new JARFileMaker ( localFile ) . addChildren ( localStagingFolder ) . close ( ) ; final Path pathToEvaluatorJar = this . uploader . uploadToJobFolder ( localFile ) ; result . put ( this . fileNames . getLocalFolderPath ( ) , this . uploader . makeLocalResourceForJarFile ( pathToEvaluatorJar ) ) ; if ( this . deleteTempFiles ) { LOG . log ( Level . FINE , "Marking [{0}] for deletion at the exit of this JVM and deleting [{1}]" , new Object [ ] { localFile . getAbsolutePath ( ) , localStagingFolder . getAbsolutePath ( ) } ) ; localFile . deleteOnExit ( ) ; if ( ! localStagingFolder . delete ( ) ) { LOG . log ( Level . WARNING , "Failed to delete [{0}]" , localStagingFolder . getAbsolutePath ( ) ) ; } } else { LOG . log ( Level . FINE , "The evaluator staging folder will be kept at [{0}], the JAR at [{1}]" , new Object [ ] { localFile . getAbsolutePath ( ) , localStagingFolder . getAbsolutePath ( ) } ) ; } return result ; }
Sets up the LocalResources for a new Evaluator .
1,998
private Configuration makeEvaluatorConfiguration ( final ResourceLaunchEvent resourceLaunchEvent ) throws IOException { return Tang . Factory . getTang ( ) . newConfigurationBuilder ( resourceLaunchEvent . getEvaluatorConf ( ) ) . build ( ) ; }
Assembles the configuration for an Evaluator .
1,999
public synchronized boolean detectRestart ( ) { if ( this . state . hasNotRestarted ( ) ) { resubmissionAttempts = driverRuntimeRestartManager . getResubmissionAttempts ( ) ; if ( resubmissionAttempts > 0 ) { this . state = DriverRestartState . BEGAN ; } } return this . state . hasRestarted ( ) ; }
Triggers the state machine if the application is a restart instance . Returns true