idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
2,100
private ComplexCondition allocate ( ) { final ComplexCondition call = freeQueue . poll ( ) ; return call != null ? call : new ComplexCondition ( timeoutPeriod , timeoutUnits ) ; }
Allocate a condition variable . May reuse existing ones .
2,101
private void addSleeper ( final long identifier , final ComplexCondition call ) { if ( sleeperMap . put ( identifier , call ) != null ) { throw new RuntimeException ( String . format ( "Duplicate identifier [%d] in sleeper map" , identifier ) ) ; } }
Atomically add a coll to the sleeper map .
2,102
private ComplexCondition getSleeper ( final long identifier ) throws InvalidIdentifierException { final ComplexCondition call = sleeperMap . get ( identifier ) ; if ( null == call ) { throw new InvalidIdentifierException ( identifier ) ; } return call ; }
Get a reference to a sleeper with a specific identifier without removing it from the sleeper map .
2,103
private void removeSleeper ( final long identifier ) throws InvalidIdentifierException { final ComplexCondition call = sleeperMap . remove ( identifier ) ; if ( null == call ) { throw new InvalidIdentifierException ( identifier ) ; } }
Remove the specified call from the sleeper map .
2,104
@ SuppressWarnings ( "unchecked" ) private < T > T parseBoundNamedParameter ( final NamedParameterNode < T > np ) { final T ret ; @ SuppressWarnings ( "rawtypes" ) final Set < Object > boundSet = c . getBoundSet ( ( NamedParameterNode ) np ) ; if ( ! boundSet . isEmpty ( ) ) { final Set < T > ret2 = new MonotonicSet < > ( ) ; for ( final Object o : boundSet ) { if ( o instanceof String ) { try { ret2 . add ( javaNamespace . parse ( np , ( String ) o ) ) ; } catch ( final ParseException e ) { throw new IllegalStateException ( "Could not parse " + o + " which was passed into " + np + " FIXME: Parsability is not currently checked by bindSetEntry(Node,String)" , e ) ; } } else if ( o instanceof Node ) { ret2 . add ( ( T ) o ) ; } else { throw new IllegalStateException ( "Unexpected object " + o + " in bound set. " + "Should consist of nodes and strings" ) ; } } return ( T ) ret2 ; } final List < Object > boundList = c . getBoundList ( ( NamedParameterNode ) np ) ; if ( boundList != null ) { final List < T > ret2 = new ArrayList < > ( ) ; for ( final Object o : boundList ) { if ( o instanceof String ) { try { ret2 . add ( javaNamespace . parse ( np , ( String ) o ) ) ; } catch ( final ParseException e ) { throw new IllegalStateException ( "Could not parse " + o + " which was passed into " + np + " FIXME: " + "Parsability is not currently checked by bindList(Node,List)" , e ) ; } } else if ( o instanceof Node ) { ret2 . add ( ( T ) o ) ; } else { throw new IllegalStateException ( "Unexpected object " + o + " in bound list. Should consist of nodes and " + "strings" ) ; } } return ( T ) ret2 ; } else if ( namedParameterInstances . containsKey ( np ) ) { ret = ( T ) namedParameterInstances . get ( np ) ; } else { final String value = c . getNamedParameter ( np ) ; if ( value == null ) { ret = null ; } else { try { ret = javaNamespace . parse ( np , value ) ; namedParameterInstances . put ( np , ret ) ; } catch ( final BindException e ) { throw new IllegalStateException ( "Could not parse pre-validated value" , e ) ; } } } return ret ; }
Parse the bound value of np . When possible this returns a cached instance .
2,105
public void subscribe ( final Class < ? extends T > clazz , final EventHandler < ? extends T > handler ) { lock . writeLock ( ) . lock ( ) ; try { List < EventHandler < ? extends T > > list = clazzToListOfHandlersMap . get ( clazz ) ; if ( list == null ) { list = new LinkedList < EventHandler < ? extends T > > ( ) ; clazzToListOfHandlersMap . put ( clazz , list ) ; } list . add ( handler ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Subscribes an event handler for an event class type .
2,106
public void onNext ( final T event ) { LOG . log ( Level . FINEST , "Invoked for event: {0}" , event ) ; lock . readLock ( ) . lock ( ) ; final List < EventHandler < ? extends T > > list ; try { list = clazzToListOfHandlersMap . get ( event . getClass ( ) ) ; if ( list == null ) { throw new WakeRuntimeException ( "No event " + event . getClass ( ) + " handler" ) ; } for ( final EventHandler < ? extends T > handler : list ) { LOG . log ( Level . FINEST , "Invoking {0}" , handler ) ; ( ( EventHandler < T > ) handler ) . onNext ( event ) ; } } finally { lock . readLock ( ) . unlock ( ) ; } }
Invokes subscribed handlers for the event class type .
2,107
public static GroupCommunicationMessage getGCM ( final Message < GroupCommunicationMessage > msg ) { final Iterator < GroupCommunicationMessage > gcmIterator = msg . getData ( ) . iterator ( ) ; if ( gcmIterator . hasNext ( ) ) { final GroupCommunicationMessage gcm = gcmIterator . next ( ) ; if ( gcmIterator . hasNext ( ) ) { throw new RuntimeException ( "Expecting exactly one GCM object inside Message but found more" ) ; } return gcm ; } else { throw new RuntimeException ( "Expecting exactly one GCM object inside Message but found none" ) ; } }
Extract a group communication message object from a message .
2,108
public static void main ( final String [ ] args ) throws InjectionException { LOG . log ( Level . FINE , "Launching Unmanaged AM: {0}" , JAR_PATH ) ; try ( final DriverLauncher client = DriverLauncher . getLauncher ( RUNTIME_CONFIG ) ) { final String appId = client . submit ( DRIVER_CONFIG , 10000 ) ; LOG . log ( Level . INFO , "Job submitted: {0}" , appId ) ; final Configuration yarnAmConfig = UnmanagedAmYarnDriverConfiguration . CONF . set ( UnmanagedAmYarnDriverConfiguration . JOB_IDENTIFIER , appId ) . set ( UnmanagedAmYarnDriverConfiguration . JOB_SUBMISSION_DIRECTORY , DRIVER_ROOT_PATH ) . build ( ) ; try ( final REEFEnvironment reef = REEFEnvironment . fromConfiguration ( yarnAmConfig , DRIVER_CONFIG ) ) { reef . run ( ) ; final ReefServiceProtos . JobStatusProto status = reef . getLastStatus ( ) ; LOG . log ( Level . INFO , "REEF job {0} completed: state {1}" , new Object [ ] { appId , status . getState ( ) } ) ; } } ThreadLogger . logThreads ( LOG , Level . FINEST , "Threads running after DriverLauncher.close():" ) ; System . exit ( 0 ) ; }
Start Hello REEF job with Unmanaged Driver running locally in the same process .
2,109
public void onNext ( final T value ) { beforeOnNext ( ) ; executor . submit ( new Runnable ( ) { public void run ( ) { observer . onNext ( value ) ; afterOnNext ( ) ; } } ) ; }
Provides the observer with the new value .
2,110
public void onError ( final Exception error ) { submitCompletion ( new Runnable ( ) { public void run ( ) { observer . onError ( error ) ; } } ) ; }
Notifies the observer that the provider has experienced an error condition .
2,111
@ SuppressWarnings ( "checkstyle:illegalcatch" ) public void onNext ( final T value ) { beforeOnNext ( ) ; try { executor . submit ( new Runnable ( ) { public void run ( ) { try { handler . onNext ( value ) ; } catch ( final Throwable t ) { if ( errorHandler != null ) { errorHandler . onNext ( t ) ; } else { LOG . log ( Level . SEVERE , name + " Exception from event handler" , t ) ; throw t ; } } finally { afterOnNext ( ) ; } } } ) ; } catch ( final Exception e ) { LOG . log ( Level . SEVERE , "Encountered error when submitting to executor in ThreadPoolStage." ) ; afterOnNext ( ) ; throw e ; } }
Handles the event using a thread in the thread pool .
2,112
public static DriverFiles fromJobSubmission ( final JobSubmissionEvent jobSubmissionEvent , final REEFFileNames fileNames ) throws IOException { final DriverFiles driverFiles = new DriverFiles ( fileNames ) ; for ( final FileResource frp : jobSubmissionEvent . getGlobalFileSet ( ) ) { final File f = new File ( frp . getPath ( ) ) ; if ( frp . getType ( ) == FileType . LIB ) { driverFiles . addGlobalLib ( f ) ; } else { driverFiles . addGlobalFile ( f ) ; } } for ( final FileResource frp : jobSubmissionEvent . getLocalFileSet ( ) ) { final File f = new File ( frp . getPath ( ) ) ; if ( frp . getType ( ) == FileType . LIB ) { driverFiles . addLocalLib ( f ) ; } else { driverFiles . addLocalFile ( f ) ; } } return driverFiles ; }
Instantiates an instance based on the given JobSubmissionProto .
2,113
public ConfigurationModule addNamesTo ( final ConfigurationModule input , final OptionalParameter < String > globalFileField , final OptionalParameter < String > globalLibField , final OptionalParameter < String > localFileField , final OptionalParameter < String > localLibField ) { ConfigurationModule result = input ; result = this . globalFiles . addNamesTo ( result , globalFileField ) ; result = this . globalLibs . addNamesTo ( result , globalLibField ) ; result = this . localFiles . addNamesTo ( result , localFileField ) ; result = this . localLibs . addNamesTo ( result , localLibField ) ; return result ; }
Fills out a ConfigurationModule .
2,114
private File downloadToTempFolder ( final String applicationId ) throws URISyntaxException , StorageException , IOException { final File outputFolder = Files . createTempDirectory ( "reeflogs-" + applicationId ) . toFile ( ) ; if ( ! outputFolder . exists ( ) && ! outputFolder . mkdirs ( ) ) { LOG . log ( Level . WARNING , "Failed to create [{0}]" , outputFolder . getAbsolutePath ( ) ) ; } final CloudBlobDirectory logFolder = this . container . getDirectoryReference ( LOG_FOLDER_PREFIX + applicationId + "/" ) ; int fileCounter = 0 ; for ( final ListBlobItem blobItem : logFolder . listBlobs ( ) ) { if ( blobItem instanceof CloudBlob ) { try ( final OutputStream outputStream = new FileOutputStream ( new File ( outputFolder , "File-" + fileCounter ) ) ) { ( ( CloudBlob ) blobItem ) . download ( outputStream ) ; ++ fileCounter ; } } } LOG . log ( Level . FINE , "Downloaded logs to: {0}" , outputFolder . getAbsolutePath ( ) ) ; return outputFolder ; }
Downloads the logs to a local temp folder .
2,115
public void unregister ( final Identifier id ) { LOG . log ( Level . FINE , "id: " + id ) ; idToAddrMap . remove ( id ) ; }
Unregisters an identifier locally .
2,116
public InetSocketAddress lookup ( final Identifier id ) { LOG . log ( Level . FINE , "id: {0}" , id ) ; return idToAddrMap . get ( id ) ; }
Finds an address for an identifier locally .
2,117
public List < NameAssignment > lookup ( final Iterable < Identifier > identifiers ) { LOG . log ( Level . FINE , "identifiers" ) ; final List < NameAssignment > nas = new ArrayList < > ( ) ; for ( final Identifier id : identifiers ) { final InetSocketAddress addr = idToAddrMap . get ( id ) ; LOG . log ( Level . FINEST , "id : {0} addr: {1}" , new Object [ ] { id , addr } ) ; if ( addr != null ) { nas . add ( new NameAssignmentTuple ( id , addr ) ) ; } } return nas ; }
Finds addresses for identifiers locally .
2,118
private String getQueue ( final Configuration driverConfiguration ) { try { return Tang . Factory . getTang ( ) . newInjector ( driverConfiguration ) . getNamedInstance ( JobQueue . class ) ; } catch ( final InjectionException e ) { return this . defaultQueueName ; } }
Extracts the queue name from the driverConfiguration or return default if none is set .
2,119
@ SuppressWarnings ( "checkstyle:illegalcatch" ) void startTask ( final Configuration taskConfig ) throws TaskClientCodeException { synchronized ( this . contextLifeCycle ) { if ( this . task . isPresent ( ) && this . task . get ( ) . hasEnded ( ) ) { this . task = Optional . empty ( ) ; } if ( this . task . isPresent ( ) ) { throw new IllegalStateException ( "Attempting to start a Task when a Task with id '" + this . task . get ( ) . getId ( ) + "' is running." ) ; } if ( this . childContext . isPresent ( ) ) { throw new IllegalStateException ( "Attempting to start a Task on a context that is not the topmost active context" ) ; } try { final Injector taskInjector = this . contextInjector . forkInjector ( taskConfig ) ; final TaskRuntime taskRuntime = taskInjector . getInstance ( TaskRuntime . class ) ; taskRuntime . initialize ( ) ; this . taskRuntimeThread = new Thread ( taskRuntime , taskRuntime . getId ( ) ) ; this . taskRuntimeThread . start ( ) ; this . task = Optional . of ( taskRuntime ) ; LOG . log ( Level . FINEST , "Started task: {0}" , taskRuntime . getTaskId ( ) ) ; } catch ( final BindException | InjectionException e ) { throw new TaskClientCodeException ( TaskClientCodeException . getTaskId ( taskConfig ) , this . getIdentifier ( ) , "Unable to instantiate the new task" , e ) ; } catch ( final Throwable t ) { throw new TaskClientCodeException ( TaskClientCodeException . getTaskId ( taskConfig ) , this . getIdentifier ( ) , "Unable to start the new task" , t ) ; } } }
Launches a Task on this context .
2,120
void close ( ) { synchronized ( this . contextLifeCycle ) { this . contextState = ReefServiceProtos . ContextStatusProto . State . DONE ; if ( this . task . isPresent ( ) ) { LOG . log ( Level . WARNING , "Shutting down a task because the underlying context is being closed." ) ; this . task . get ( ) . close ( null ) ; } if ( this . childContext . isPresent ( ) ) { LOG . log ( Level . WARNING , "Closing a context because its parent context is being closed." ) ; this . childContext . get ( ) . close ( ) ; } this . contextLifeCycle . close ( ) ; if ( this . parentContext . isPresent ( ) ) { this . parentContext . get ( ) . resetChildContext ( ) ; } } }
Close this context . If there is a child context this recursively closes it before closing this context . If there is a Task currently running that will be closed .
2,121
public static LauncherStatus runHelloReef ( final Configuration runtimeConf , final int timeOut ) throws BindException , InjectionException { final Configuration driverConf = Configurations . merge ( HelloREEFHttp . getDriverConfiguration ( ) , getHTTPConfiguration ( ) ) ; return DriverLauncher . getLauncher ( runtimeConf ) . run ( driverConf , timeOut ) ; }
Run Hello Reef with merged configuration .
2,122
public void channelActive ( final ChannelHandlerContext ctx ) throws Exception { this . channelGroup . add ( ctx . channel ( ) ) ; this . listener . channelActive ( ctx ) ; super . channelActive ( ctx ) ; }
Handles the channel active event .
2,123
public void channelInactive ( final ChannelHandlerContext ctx ) throws Exception { this . listener . channelInactive ( ctx ) ; super . channelInactive ( ctx ) ; }
Handles the channel inactive event .
2,124
public void exceptionCaught ( final ChannelHandlerContext ctx , final Throwable cause ) { final Channel channel = ctx . channel ( ) ; LOG . log ( Level . INFO , "Unexpected exception from downstream. channel: {0} local: {1} remote: {2}" , new Object [ ] { channel , channel . localAddress ( ) , channel . remoteAddress ( ) } ) ; LOG . log ( Level . WARNING , "Unexpected exception from downstream." , cause ) ; channel . close ( ) ; this . listener . exceptionCaught ( ctx , cause ) ; }
Handles the exception event .
2,125
public RemoteEvent < T > decode ( final byte [ ] data ) { final WakeMessagePBuf pbuf ; try { pbuf = WakeMessagePBuf . parseFrom ( data ) ; return new RemoteEvent < T > ( null , null , pbuf . getSeq ( ) , decoder . decode ( pbuf . getData ( ) . toByteArray ( ) ) ) ; } catch ( final InvalidProtocolBufferException e ) { throw new RemoteRuntimeException ( e ) ; } }
Decodes a remote event from the byte array data .
2,126
public boolean setEvaluatorRestartState ( final EvaluatorRestartState to ) { if ( this . evaluatorRestartState . isLegalTransition ( to ) ) { this . evaluatorRestartState = to ; return true ; } return false ; }
sets the current process of the restart .
2,127
private static Configuration getCLRTaskConfiguration ( final String taskId ) throws BindException { final ConfigurationBuilder taskConfigurationBuilder = Tang . Factory . getTang ( ) . newConfigurationBuilder ( loadClassHierarchy ( ) ) ; taskConfigurationBuilder . bind ( "Org.Apache.Reef.Tasks.TaskConfigurationOptions+Identifier," + "Org.Apache.Reef.Tasks.ITask, Version=1.0.0.0, Culture=neutral, PublicKeyToken=69c3241e6f0468ca" , taskId ) ; taskConfigurationBuilder . bind ( "Org.Apache.Reef.Tasks.ITask, Org.Apache.Reef.Tasks.ITask, Version=1.0.0.0, " + "Culture=neutral, PublicKeyToken=69c3241e6f0468ca" , "Org.Apache.Reef.Tasks.HelloTask, " + "Org.Apache.Reef.Tasks.HelloTask, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" ) ; return taskConfigurationBuilder . build ( ) ; }
Makes a task configuration for the CLR Task .
2,128
private static ClassHierarchy loadClassHierarchy ( ) { try ( final InputStream chin = new FileInputStream ( HelloCLR . CLASS_HIERARCHY_FILENAME ) ) { final ClassHierarchyProto . Node root = ClassHierarchyProto . Node . parseFrom ( chin ) ; final ClassHierarchy ch = new ProtocolBufferClassHierarchy ( root ) ; return ch ; } catch ( final IOException e ) { final String message = "Unable to load class hierarchy." ; LOG . log ( Level . SEVERE , message , e ) ; throw new RuntimeException ( message , e ) ; } }
Loads the class hierarchy .
2,129
void onNextCLR ( final AllocatedEvaluator allocatedEvaluator ) { try { allocatedEvaluator . setProcess ( clrProcessFactory . newEvaluatorProcess ( ) ) ; final Configuration contextConfiguration = ContextConfiguration . CONF . set ( ContextConfiguration . IDENTIFIER , "HelloREEFContext" ) . build ( ) ; final Configuration taskConfiguration = getCLRTaskConfiguration ( "Hello_From_CLR" ) ; allocatedEvaluator . submitContextAndTask ( contextConfiguration , taskConfiguration ) ; } catch ( final BindException ex ) { final String message = "Unable to setup Task or Context configuration." ; LOG . log ( Level . SEVERE , message , ex ) ; throw new RuntimeException ( message , ex ) ; } }
Uses the AllocatedEvaluator to launch a CLR task .
2,130
void onNextJVM ( final AllocatedEvaluator allocatedEvaluator ) { try { final Configuration contextConfiguration = ContextConfiguration . CONF . set ( ContextConfiguration . IDENTIFIER , "HelloREEFContext" ) . build ( ) ; final Configuration taskConfiguration = TaskConfiguration . CONF . set ( TaskConfiguration . IDENTIFIER , "HelloREEFTask" ) . set ( TaskConfiguration . TASK , HelloTask . class ) . build ( ) ; allocatedEvaluator . submitContextAndTask ( contextConfiguration , taskConfiguration ) ; } catch ( final BindException ex ) { final String message = "Unable to setup Task or Context configuration." ; LOG . log ( Level . SEVERE , message , ex ) ; throw new RuntimeException ( message , ex ) ; } }
Uses the AllocatedEvaluator to launch a JVM task .
2,131
public Configuration getServiceConfiguration ( ) { final Configuration partialServiceConf = ServiceConfiguration . CONF . set ( ServiceConfiguration . SERVICES , taskOutputStreamProvider . getClass ( ) ) . set ( ServiceConfiguration . ON_CONTEXT_STOP , ContextStopHandler . class ) . set ( ServiceConfiguration . ON_TASK_STARTED , TaskStartHandler . class ) . build ( ) ; return Tang . Factory . getTang ( ) . newConfigurationBuilder ( partialServiceConf ) . bindImplementation ( OutputStreamProvider . class , taskOutputStreamProvider . getClass ( ) ) . bindImplementation ( TaskOutputStreamProvider . class , taskOutputStreamProvider . getClass ( ) ) . bindNamedParameter ( OutputPath . class , outputPath ) . build ( ) ; }
Provides a service configuration for the output service .
2,132
static LocalSubmissionFromCS fromSubmissionParameterFiles ( final File localJobSubmissionParametersFile , final File localAppSubmissionParametersFile ) throws IOException { final AvroLocalAppSubmissionParameters localAppSubmissionParameters ; final AvroLocalJobSubmissionParameters localJobSubmissionParameters ; try ( final FileInputStream fileInputStream = new FileInputStream ( localJobSubmissionParametersFile ) ) { final JsonDecoder decoder = DecoderFactory . get ( ) . jsonDecoder ( AvroLocalJobSubmissionParameters . getClassSchema ( ) , fileInputStream ) ; final SpecificDatumReader < AvroLocalJobSubmissionParameters > reader = new SpecificDatumReader < > ( AvroLocalJobSubmissionParameters . class ) ; localJobSubmissionParameters = reader . read ( null , decoder ) ; } try ( final FileInputStream fileInputStream = new FileInputStream ( localAppSubmissionParametersFile ) ) { final JsonDecoder decoder = DecoderFactory . get ( ) . jsonDecoder ( AvroLocalAppSubmissionParameters . getClassSchema ( ) , fileInputStream ) ; final SpecificDatumReader < AvroLocalAppSubmissionParameters > reader = new SpecificDatumReader < > ( AvroLocalAppSubmissionParameters . class ) ; localAppSubmissionParameters = reader . read ( null , decoder ) ; } return new LocalSubmissionFromCS ( localJobSubmissionParameters , localAppSubmissionParameters ) ; }
Takes the local job submission configuration file deserializes it and creates submission object .
2,133
public static byte [ ] toByteArray ( final ByteString bs ) { return bs == null || bs . isEmpty ( ) ? null : bs . toByteArray ( ) ; }
Converts ByteString to byte array .
2,134
public static ExceptionInfo createExceptionInfo ( final ExceptionCodec exceptionCodec , final Throwable ex ) { return ExceptionInfo . newBuilder ( ) . setName ( ex . getCause ( ) != null ? ex . getCause ( ) . toString ( ) : ex . toString ( ) ) . setMessage ( StringUtils . isNotEmpty ( ex . getMessage ( ) ) ? ex . getMessage ( ) : ex . toString ( ) ) . setData ( ByteString . copyFrom ( exceptionCodec . toBytes ( ex ) ) ) . build ( ) ; }
Create exception info from exception object .
2,135
public static EvaluatorDescriptorInfo toEvaluatorDescriptorInfo ( final EvaluatorDescriptor descriptor ) { if ( descriptor == null ) { return null ; } EvaluatorDescriptorInfo . NodeDescriptorInfo nodeDescriptorInfo = descriptor . getNodeDescriptor ( ) == null ? null : EvaluatorDescriptorInfo . NodeDescriptorInfo . newBuilder ( ) . setHostName ( descriptor . getNodeDescriptor ( ) . getName ( ) ) . setId ( descriptor . getNodeDescriptor ( ) . getId ( ) ) . setIpAddress ( descriptor . getNodeDescriptor ( ) . getInetSocketAddress ( ) . getAddress ( ) . getHostAddress ( ) ) . setPort ( descriptor . getNodeDescriptor ( ) . getInetSocketAddress ( ) . getPort ( ) ) . setRackName ( descriptor . getNodeDescriptor ( ) . getRackDescriptor ( ) == null ? "" : descriptor . getNodeDescriptor ( ) . getRackDescriptor ( ) . getName ( ) ) . build ( ) ; return EvaluatorDescriptorInfo . newBuilder ( ) . setCores ( descriptor . getNumberOfCores ( ) ) . setMemory ( descriptor . getMemory ( ) ) . setRuntimeName ( descriptor . getRuntimeName ( ) ) . setNodeDescriptorInfo ( nodeDescriptorInfo ) . build ( ) ; }
Create an evaluator descriptor info from an EvalautorDescriptor object .
2,136
public static ContextInfo toContextInfo ( final ContextBase context , final ExceptionInfo error ) { final ContextInfo . Builder builder = ContextInfo . newBuilder ( ) . setContextId ( context . getId ( ) ) . setEvaluatorId ( context . getEvaluatorId ( ) ) . setParentId ( context . getParentId ( ) . orElse ( "" ) ) . setEvaluatorDescriptorInfo ( toEvaluatorDescriptorInfo ( context . getEvaluatorDescriptor ( ) ) ) ; if ( error != null ) { builder . setException ( error ) ; } return builder . build ( ) ; }
Create a context info from a context object with an error .
2,137
private Configuration getTaskConfiguration ( final String taskId ) { try { return TaskConfiguration . CONF . set ( TaskConfiguration . IDENTIFIER , taskId ) . set ( TaskConfiguration . TASK , SleepTask . class ) . build ( ) ; } catch ( final BindException ex ) { LOG . log ( Level . SEVERE , "Failed to create Task Configuration: " + taskId , ex ) ; throw new RuntimeException ( ex ) ; } }
Build a new Task configuration for a given task ID .
2,138
String waitAndGetMessage ( ) { synchronized ( this ) { while ( this . statusMessagesToSend . isEmpty ( ) ) { try { this . wait ( ) ; } catch ( final InterruptedException e ) { LOG . log ( Level . FINE , "Interrupted. Ignoring." ) ; } } return getMessageForStatus ( this . statusMessagesToSend . poll ( ) ) ; } }
Waits for a status message to be available and returns it .
2,139
public void addTokens ( final byte [ ] tokens ) { try ( final DataInputBuffer buf = new DataInputBuffer ( ) ) { buf . reset ( tokens , tokens . length ) ; final Credentials credentials = new Credentials ( ) ; credentials . readTokenStorageStream ( buf ) ; final UserGroupInformation ugi = UserGroupInformation . getCurrentUser ( ) ; ugi . addCredentials ( credentials ) ; LOG . log ( Level . FINEST , "Added {0} tokens for user {1}" , new Object [ ] { credentials . numberOfTokens ( ) , ugi } ) ; } catch ( final IOException ex ) { LOG . log ( Level . SEVERE , "Could not access tokens in user credentials." , ex ) ; throw new RuntimeException ( ex ) ; } }
Add serialized token to teh credentials .
2,140
public static byte [ ] serializeToken ( final Token < AMRMTokenIdentifier > token ) { try ( final DataOutputBuffer dob = new DataOutputBuffer ( ) ) { final Credentials credentials = new Credentials ( ) ; credentials . addToken ( token . getService ( ) , token ) ; credentials . writeTokenStorageToStream ( dob ) ; return dob . getData ( ) ; } catch ( final IOException ex ) { LOG . log ( Level . SEVERE , "Could not write credentials to the buffer." , ex ) ; throw new RuntimeException ( ex ) ; } }
Helper method to serialize a security token .
2,141
public final synchronized void onHttpRequest ( final ParsedHttpRequest parsedHttpRequest , final HttpServletResponse response ) throws IOException , ServletException { LOG . log ( Level . INFO , "HttpServeShellCmdHandler in webserver onHttpRequest is called: {0}" , parsedHttpRequest . getRequestUri ( ) ) ; final String queryStr = parsedHttpRequest . getQueryString ( ) ; if ( parsedHttpRequest . getTargetEntity ( ) . equalsIgnoreCase ( "Evaluators" ) ) { final byte [ ] b = HttpShellJobDriver . CODEC . encode ( queryStr ) ; LOG . log ( Level . INFO , "HttpServeShellCmdHandler call HelloDriver onCommand(): {0}" , queryStr ) ; messageHandler . get ( ) . onNext ( b ) ; notify ( ) ; final long endTime = System . currentTimeMillis ( ) + WAIT_TIMEOUT ; while ( cmdOutput == null ) { final long waitTime = endTime - System . currentTimeMillis ( ) ; if ( waitTime <= 0 ) { break ; } try { wait ( WAIT_TIME ) ; } catch ( final InterruptedException e ) { LOG . log ( Level . WARNING , "HttpServeShellCmdHandler onHttpRequest InterruptedException: {0}" , e ) ; } } if ( cmdOutput != null ) { response . getOutputStream ( ) . write ( cmdOutput . getBytes ( StandardCharsets . UTF_8 ) ) ; cmdOutput = null ; } } else if ( parsedHttpRequest . getTargetEntity ( ) . equalsIgnoreCase ( "Driver" ) ) { final String commandOutput = CommandUtils . runCommand ( queryStr ) ; response . getOutputStream ( ) . write ( commandOutput . getBytes ( StandardCharsets . UTF_8 ) ) ; } }
it is called when receiving a http request .
2,142
public final synchronized void onHttpCallback ( final byte [ ] message ) { final long endTime = System . currentTimeMillis ( ) + WAIT_TIMEOUT ; while ( cmdOutput != null ) { final long waitTime = endTime - System . currentTimeMillis ( ) ; if ( waitTime <= 0 ) { break ; } try { wait ( WAIT_TIME ) ; } catch ( final InterruptedException e ) { LOG . log ( Level . WARNING , "HttpServeShellCmdHandler onHttpCallback InterruptedException: {0}" , e ) ; } } LOG . log ( Level . INFO , "HttpServeShellCmdHandler OnCallback: {0}" , HttpShellJobDriver . CODEC . decode ( message ) ) ; cmdOutput = HttpShellJobDriver . CODEC . decode ( message ) ; notify ( ) ; }
called after shell command is completed .
2,143
public static void runTaskScheduler ( final Configuration runtimeConf , final String [ ] args ) throws InjectionException , IOException , ParseException { final Tang tang = Tang . Factory . getTang ( ) ; final Configuration commandLineConf = CommandLine . parseToConfiguration ( args , Retain . class ) ; final Configuration driverConf = Configurations . merge ( getDriverConf ( ) , getHttpConf ( ) , commandLineConf ) ; final REEF reef = tang . newInjector ( runtimeConf ) . getInstance ( REEF . class ) ; reef . submit ( driverConf ) ; }
Run the Task scheduler . If - retain true option is passed via command line the scheduler reuses evaluators to submit new Tasks .
2,144
public void start ( final VortexThreadPool vortexThreadPool ) { final List < Matrix < Double > > leftSplits = generateMatrixSplits ( numRows , numColumns , divideFactor ) ; final Matrix < Double > right = generateIdentityMatrix ( numColumns ) ; final double start = System . currentTimeMillis ( ) ; final CountDownLatch latch = new CountDownLatch ( divideFactor ) ; final FutureCallback < MatMulOutput > callback = new FutureCallback < MatMulOutput > ( ) { public void onSuccess ( final MatMulOutput output ) { final int index = output . getIndex ( ) ; final Matrix < Double > result = output . getResult ( ) ; if ( result . equals ( leftSplits . get ( index ) ) ) { latch . countDown ( ) ; } else { throw new RuntimeException ( index + " th result is not correct." ) ; } } public void onFailure ( final Throwable t ) { throw new RuntimeException ( t ) ; } } ; final MatMulFunction matMulFunction = new MatMulFunction ( ) ; for ( int i = 0 ; i < divideFactor ; i ++ ) { vortexThreadPool . submit ( matMulFunction , new MatMulInput ( i , leftSplits . get ( i ) , right ) , callback ) ; } try { latch . await ( ) ; LOG . log ( Level . INFO , "Job Finish Time: " + ( System . currentTimeMillis ( ) - start ) ) ; } catch ( final InterruptedException e ) { throw new RuntimeException ( e ) ; } }
Perform a simple vector multiplication on Vortex .
2,145
private Matrix < Double > generateRandomMatrix ( final int nRows , final int nColumns ) { final List < List < Double > > rows = new ArrayList < > ( nRows ) ; final Random random = new Random ( ) ; for ( int i = 0 ; i < nRows ; i ++ ) { final List < Double > row = new ArrayList < > ( nColumns ) ; for ( int j = 0 ; j < nColumns ; j ++ ) { row . add ( random . nextDouble ( ) ) ; } rows . add ( row ) ; } return new RowMatrix ( rows ) ; }
Generate a matrix with random values .
2,146
private Matrix < Double > generateIdentityMatrix ( final int numDimension ) { final List < List < Double > > rows = new ArrayList < > ( numDimension ) ; for ( int i = 0 ; i < numDimension ; i ++ ) { final List < Double > row = new ArrayList < > ( numDimension ) ; for ( int j = 0 ; j < numDimension ; j ++ ) { final double value = i == j ? 1 : 0 ; row . add ( value ) ; } rows . add ( row ) ; } return new RowMatrix ( rows ) ; }
Generate an identity matrix .
2,147
public Topology getNewInstance ( final Class < ? extends Name < String > > operatorName , final Class < ? extends Topology > topologyClass ) throws InjectionException { final Injector newInjector = injector . forkInjector ( ) ; newInjector . bindVolatileParameter ( OperatorNameClass . class , operatorName ) ; return newInjector . getInstance ( topologyClass ) ; }
Instantiates a new Topology instance .
2,148
public static void main ( final String [ ] args ) throws InjectionException , IOException { final Configuration partialConfiguration = getEnvironmentConfiguration ( ) ; final Injector injector = Tang . Factory . getTang ( ) . newInjector ( partialConfiguration ) ; final AzureBatchRuntimeConfigurationProvider runtimeConfigurationProvider = injector . getInstance ( AzureBatchRuntimeConfigurationProvider . class ) ; final Configuration driverConfiguration = getDriverConfiguration ( ) ; try ( final REEF reef = Tang . Factory . getTang ( ) . newInjector ( runtimeConfigurationProvider . getAzureBatchRuntimeConfiguration ( ) ) . getInstance ( REEF . class ) ) { reef . submit ( driverConfiguration ) ; } LOG . log ( Level . INFO , "Job Submitted" ) ; }
Start the Hello REEF job with the Azure Batch runtime .
2,149
private void returnResults ( ) { final StringBuilder sb = new StringBuilder ( ) ; for ( final String result : this . results ) { sb . append ( result ) ; } this . results . clear ( ) ; LOG . log ( Level . INFO , "Return results to the client:\n{0}" , sb ) ; httpCallbackHandler . onNext ( CODEC . encode ( sb . toString ( ) ) ) ; }
Construct the final result and forward it to the Client .
2,150
private synchronized void submit ( final String command ) { LOG . log ( Level . INFO , "Submit command {0} to {1} evaluators. state: {2}" , new Object [ ] { command , this . contexts . size ( ) , this . state } ) ; assert this . state == State . READY ; this . expectCount = this . contexts . size ( ) ; this . state = State . WAIT_TASKS ; this . cmd = null ; for ( final ActiveContext context : this . contexts . values ( ) ) { this . submit ( context , command ) ; } }
Submit command to all available evaluators .
2,151
private synchronized void requestEvaluators ( ) { assert this . state == State . INIT ; LOG . log ( Level . INFO , "Schedule on {0} Evaluators." , this . numEvaluators ) ; this . evaluatorRequestor . newRequest ( ) . setMemory ( 128 ) . setNumberOfCores ( 1 ) . setNumber ( this . numEvaluators ) . submit ( ) ; this . state = State . WAIT_EVALUATORS ; this . expectCount = this . numEvaluators ; }
Request the evaluators .
2,152
private void submit ( final ActiveContext context ) { try { LOG . log ( Level . INFO , "Send task to context: {0}" , new Object [ ] { context } ) ; if ( JobDriver . this . handlerManager . getActiveContextHandler ( ) == 0 ) { throw new RuntimeException ( "Active Context Handler not initialized by CLR." ) ; } final ActiveContextBridge activeContextBridge = activeContextBridgeFactory . getActiveContextBridge ( context ) ; NativeInterop . clrSystemActiveContextHandlerOnNext ( JobDriver . this . handlerManager . getActiveContextHandler ( ) , activeContextBridge , JobDriver . this . interopLogger ) ; } catch ( final Exception ex ) { LOG . log ( Level . SEVERE , "Fail to submit task to active context" ) ; context . close ( ) ; throw new RuntimeException ( ex ) ; } }
Submit a Task to a single Evaluator .
2,153
private static String readFile ( final String fileName ) throws IOException { return new String ( Files . readAllBytes ( Paths . get ( fileName ) ) , StandardCharsets . UTF_8 ) ; }
read a file and output it as a String .
2,154
private void writeEvaluatorInfoJsonOutput ( final HttpServletResponse response , final List < String > ids ) throws IOException { try { final EvaluatorInfoSerializer serializer = Tang . Factory . getTang ( ) . newInjector ( ) . getInstance ( EvaluatorInfoSerializer . class ) ; final AvroEvaluatorsInfo evaluatorsInfo = serializer . toAvro ( ids , this . reefStateManager . getEvaluators ( ) ) ; writeResponse ( response , serializer . toString ( evaluatorsInfo ) ) ; } catch ( final InjectionException e ) { LOG . log ( Level . SEVERE , "Error in injecting EvaluatorInfoSerializer." , e ) ; writeResponse ( response , "Error in injecting EvaluatorInfoSerializer: " + e ) ; } }
Write Evaluator info as JSON format to HTTP Response .
2,155
private void writeEvaluatorInfoWebOutput ( final HttpServletResponse response , final List < String > ids ) throws IOException { for ( final String id : ids ) { final EvaluatorDescriptor evaluatorDescriptor = this . reefStateManager . getEvaluators ( ) . get ( id ) ; final PrintWriter writer = response . getWriter ( ) ; if ( evaluatorDescriptor != null ) { final String nodeId = evaluatorDescriptor . getNodeDescriptor ( ) . getId ( ) ; final String nodeName = evaluatorDescriptor . getNodeDescriptor ( ) . getName ( ) ; final InetSocketAddress address = evaluatorDescriptor . getNodeDescriptor ( ) . getInetSocketAddress ( ) ; writer . println ( "Evaluator Id: " + id ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Node Id: " + nodeId ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Node Name: " + nodeName ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator InternetAddress: " + address ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Memory: " + evaluatorDescriptor . getMemory ( ) ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Core: " + evaluatorDescriptor . getNumberOfCores ( ) ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Type: " + evaluatorDescriptor . getProcess ( ) ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Runtime Name: " + evaluatorDescriptor . getRuntimeName ( ) ) ; writer . write ( "<br/>" ) ; } else { writer . println ( "Incorrect Evaluator Id: " + id ) ; } } }
Write Evaluator info on the Response so that to display on web page directly . This is for direct browser queries .
2,156
private void writeEvaluatorsJsonOutput ( final HttpServletResponse response ) throws IOException { LOG . log ( Level . INFO , "HttpServerReefEventHandler writeEvaluatorsJsonOutput is called" ) ; try { final EvaluatorListSerializer serializer = Tang . Factory . getTang ( ) . newInjector ( ) . getInstance ( EvaluatorListSerializer . class ) ; final AvroEvaluatorList evaluatorList = serializer . toAvro ( this . reefStateManager . getEvaluators ( ) , this . reefStateManager . getEvaluators ( ) . size ( ) , this . reefStateManager . getStartTime ( ) ) ; writeResponse ( response , serializer . toString ( evaluatorList ) ) ; } catch ( final InjectionException e ) { LOG . log ( Level . SEVERE , "Error in injecting EvaluatorListSerializer." , e ) ; writeResponse ( response , "Error in injecting EvaluatorListSerializer: " + e ) ; } }
Get all evaluator ids and send it back to response as JSON .
2,157
private void writeEvaluatorsWebOutput ( final HttpServletResponse response ) throws IOException { LOG . log ( Level . INFO , "HttpServerReefEventHandler writeEvaluatorsWebOutput is called" ) ; final PrintWriter writer = response . getWriter ( ) ; writer . println ( "<h1>Evaluators:</h1>" ) ; for ( final Map . Entry < String , EvaluatorDescriptor > entry : this . reefStateManager . getEvaluators ( ) . entrySet ( ) ) { final String key = entry . getKey ( ) ; final EvaluatorDescriptor descriptor = entry . getValue ( ) ; writer . println ( "Evaluator Id: " + key ) ; writer . write ( "<br/>" ) ; writer . println ( "Evaluator Name: " + descriptor . getNodeDescriptor ( ) . getName ( ) ) ; writer . write ( "<br/>" ) ; } writer . write ( "<br/>" ) ; writer . println ( "Total number of Evaluators: " + this . reefStateManager . getEvaluators ( ) . size ( ) ) ; writer . write ( "<br/>" ) ; writer . println ( String . format ( "Driver Start Time:[%s]" , this . reefStateManager . getStartTime ( ) ) ) ; }
Get all evaluator ids and send it back to response so that can be displayed on web .
2,158
private void writeDriverJsonInformation ( final HttpServletResponse response ) throws IOException { LOG . log ( Level . INFO , "HttpServerReefEventHandler writeDriverJsonInformation invoked." ) ; try { final DriverInfoSerializer serializer = Tang . Factory . getTang ( ) . newInjector ( ) . getInstance ( DriverInfoSerializer . class ) ; final AvroDriverInfo driverInfo = serializer . toAvro ( this . reefStateManager . getDriverEndpointIdentifier ( ) , this . reefStateManager . getStartTime ( ) , this . reefStateManager . getServicesInfo ( ) ) ; writeResponse ( response , serializer . toString ( driverInfo ) ) ; } catch ( final InjectionException e ) { LOG . log ( Level . SEVERE , "Error in injecting DriverInfoSerializer." , e ) ; writeResponse ( response , "Error in injecting DriverInfoSerializer: " + e ) ; } }
Write Driver Info as JSON string to Response .
2,159
private void writeResponse ( final HttpServletResponse response , final String data ) throws IOException { final byte [ ] outputBody = data . getBytes ( StandardCharsets . UTF_8 ) ; response . getOutputStream ( ) . write ( outputBody ) ; }
Write a String to HTTP Response .
2,160
private void writeDriverWebInformation ( final HttpServletResponse response ) throws IOException { LOG . log ( Level . INFO , "HttpServerReefEventHandler writeDriverWebInformation invoked." ) ; final PrintWriter writer = response . getWriter ( ) ; writer . println ( "<h1>Driver Information:</h1>" ) ; writer . println ( String . format ( "Driver Remote Identifier:[%s]" , this . reefStateManager . getDriverEndpointIdentifier ( ) ) ) ; writer . write ( "<br/><br/>" ) ; writer . println ( String . format ( "Services registered on Driver:" ) ) ; writer . write ( "<br/><br/>" ) ; for ( final AvroReefServiceInfo service : this . reefStateManager . getServicesInfo ( ) ) { writer . println ( String . format ( "Service: [%s] , Information: [%s]" , service . getServiceName ( ) , service . getServiceInfo ( ) ) ) ; writer . write ( "<br/><br/>" ) ; } writer . println ( String . format ( "Driver Start Time:[%s]" , this . reefStateManager . getStartTime ( ) ) ) ; }
Get driver information .
2,161
private void writeLines ( final HttpServletResponse response , final ArrayList < String > lines , final String header ) throws IOException { LOG . log ( Level . INFO , "HttpServerReefEventHandler writeLines is called" ) ; final PrintWriter writer = response . getWriter ( ) ; writer . println ( "<h1>" + header + "</h1>" ) ; for ( final String line : lines ) { writer . println ( line ) ; writer . write ( "<br/>" ) ; } writer . write ( "<br/>" ) ; }
Write lines in ArrayList to the response writer .
2,162
public void close ( ) { LOG . log ( Level . FINE , "Closing netty transport socket address: {0}" , this . localAddress ) ; final ChannelGroupFuture clientChannelGroupFuture = this . clientChannelGroup . close ( ) ; final ChannelGroupFuture serverChannelGroupFuture = this . serverChannelGroup . close ( ) ; final ChannelFuture acceptorFuture = this . acceptor . close ( ) ; final ArrayList < Future > eventLoopGroupFutures = new ArrayList < > ( 3 ) ; eventLoopGroupFutures . add ( this . clientWorkerGroup . shutdownGracefully ( ) ) ; eventLoopGroupFutures . add ( this . serverBossGroup . shutdownGracefully ( ) ) ; eventLoopGroupFutures . add ( this . serverWorkerGroup . shutdownGracefully ( ) ) ; clientChannelGroupFuture . awaitUninterruptibly ( ) ; serverChannelGroupFuture . awaitUninterruptibly ( ) ; try { acceptorFuture . sync ( ) ; } catch ( final Exception ex ) { LOG . log ( Level . SEVERE , "Error closing the acceptor channel for " + this . localAddress , ex ) ; } for ( final Future eventLoopGroupFuture : eventLoopGroupFutures ) { eventLoopGroupFuture . awaitUninterruptibly ( ) ; } LOG . log ( Level . FINE , "Closing netty transport socket address: {0} done" , this . localAddress ) ; }
Closes all channels and releases all resources .
2,163
public < T > Link < T > get ( final SocketAddress remoteAddr ) { final LinkReference linkRef = this . addrToLinkRefMap . get ( remoteAddr ) ; return linkRef != null ? ( Link < T > ) linkRef . getLink ( ) : null ; }
Returns a link for the remote address if already cached ; otherwise returns null .
2,164
public void registerErrorHandler ( final EventHandler < Exception > handler ) { this . clientEventListener . registerErrorHandler ( handler ) ; this . serverEventListener . registerErrorHandler ( handler ) ; }
Registers the exception event handler .
2,165
@ SuppressWarnings ( "checkstyle:diamondoperatorforvariabledefinition" ) public AutoCloseable registerHandler ( final RemoteIdentifier sourceIdentifier , final Class < ? extends T > messageType , final EventHandler < ? super T > theHandler ) { final Tuple2 < RemoteIdentifier , Class < ? extends T > > tuple = new Tuple2 < RemoteIdentifier , Class < ? extends T > > ( sourceIdentifier , messageType ) ; this . tupleToHandlerMap . put ( tuple , theHandler ) ; LOG . log ( Level . FINER , "Add handler for tuple: {0},{1}" , new Object [ ] { tuple . getT1 ( ) , tuple . getT2 ( ) . getCanonicalName ( ) } ) ; return new SubscriptionHandler < > ( tuple , this . unsubscribeTuple ) ; }
Subscribe for events from a given source and message type .
2,166
public AutoCloseable registerHandler ( final Class < ? extends T > messageType , final EventHandler < RemoteMessage < ? extends T > > theHandler ) { this . msgTypeToHandlerMap . put ( messageType , theHandler ) ; LOG . log ( Level . FINER , "Add handler for class: {0}" , messageType . getCanonicalName ( ) ) ; return new SubscriptionHandler < > ( messageType , this . unsubscribeClass ) ; }
Subscribe for events of a given message type .
2,167
public AutoCloseable registerErrorHandler ( final EventHandler < Exception > theHandler ) { this . transport . registerErrorHandler ( theHandler ) ; return new SubscriptionHandler < > ( new Exception ( "Token for finding the error handler subscription" ) , this . unsubscribeException ) ; }
Specify handler for error messages .
2,168
public void unsubscribe ( final Subscription < T > subscription ) { final T token = subscription . getToken ( ) ; LOG . log ( Level . FINER , "RemoteManager: {0} token {1}" , new Object [ ] { this . name , token } ) ; if ( token instanceof Exception ) { this . transport . registerErrorHandler ( null ) ; } else if ( token instanceof Tuple2 ) { this . tupleToHandlerMap . remove ( token ) ; } else if ( token instanceof Class ) { this . msgTypeToHandlerMap . remove ( token ) ; } else { throw new RemoteRuntimeException ( "Unknown subscription type: " + subscription . getClass ( ) . getCanonicalName ( ) ) ; } }
Unsubscribes a handler .
2,169
@ SuppressWarnings ( "checkstyle:diamondoperatorforvariabledefinition" ) public synchronized void onNext ( final RemoteEvent < byte [ ] > value ) { LOG . log ( Level . FINER , "RemoteManager: {0} value: {1}" , new Object [ ] { this . name , value } ) ; final T decodedEvent = this . codec . decode ( value . getEvent ( ) ) ; final Class < ? extends T > clazz = ( Class < ? extends T > ) decodedEvent . getClass ( ) ; LOG . log ( Level . FINEST , "RemoteManager: {0} decoded event {1} :: {2}" , new Object [ ] { this . name , clazz . getCanonicalName ( ) , decodedEvent } ) ; final SocketRemoteIdentifier id = new SocketRemoteIdentifier ( ( InetSocketAddress ) value . remoteAddress ( ) ) ; final Tuple2 < RemoteIdentifier , Class < ? extends T > > tuple = new Tuple2 < RemoteIdentifier , Class < ? extends T > > ( id , clazz ) ; final EventHandler < ? super T > tupleHandler = this . tupleToHandlerMap . get ( tuple ) ; if ( tupleHandler != null ) { LOG . log ( Level . FINER , "Tuple handler: {0},{1}" , new Object [ ] { tuple . getT1 ( ) , tuple . getT2 ( ) . getCanonicalName ( ) } ) ; tupleHandler . onNext ( decodedEvent ) ; } else { final EventHandler < RemoteMessage < ? extends T > > messageHandler = this . msgTypeToHandlerMap . get ( clazz ) ; if ( messageHandler == null ) { final RuntimeException ex = new RemoteRuntimeException ( "Unknown message type in dispatch: " + clazz . getCanonicalName ( ) + " from " + id ) ; LOG . log ( Level . WARNING , "Unknown message type in dispatch." , ex ) ; throw ex ; } LOG . log ( Level . FINER , "Message handler: {0}" , clazz . getCanonicalName ( ) ) ; messageHandler . onNext ( new DefaultRemoteMessage < > ( id , decodedEvent ) ) ; } }
Dispatch message received from the remote to proper event handler .
2,170
public void signal ( ) { if ( lockVar . isHeldByCurrentThread ( ) ) { throw new RuntimeException ( "signal() must not be called on same thread as await()" ) ; } try { lockVar . lock ( ) ; LOG . log ( Level . INFO , "Signalling sleeper..." ) ; isSignal = true ; conditionVar . signal ( ) ; } finally { lockVar . unlock ( ) ; } }
Wakes the thread sleeping in (
2,171
public < T > EventHandler < T > getHandler ( final RemoteIdentifier destinationIdentifier , final Class < ? extends T > messageType ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . log ( Level . FINE , "RemoteManager: {0} destinationIdentifier: {1} messageType: {2}" , new Object [ ] { this . name , destinationIdentifier , messageType . getCanonicalName ( ) } ) ; } return new ProxyEventHandler < > ( this . myIdentifier , destinationIdentifier , "default" , this . reSendStage . < T > getHandler ( ) , this . seqGen ) ; }
Returns a proxy event handler for a remote identifier and a message type .
2,172
public < T , U extends T > AutoCloseable registerHandler ( final Class < U > messageType , final EventHandler < RemoteMessage < T > > theHandler ) { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . log ( Level . FINE , "RemoteManager: {0} messageType: {1} handler: {2}" , new Object [ ] { this . name , messageType . getCanonicalName ( ) , theHandler . getClass ( ) . getCanonicalName ( ) } ) ; } return this . handlerContainer . registerHandler ( messageType , theHandler ) ; }
Registers an event handler for a message type and returns a subscription .
2,173
public void onResourceRequested ( final ResourceRequestEvent resourceRequestEvent , final String containerId , final URI jarFileUri ) { try { createAzureBatchTask ( containerId , jarFileUri ) ; this . outstandingResourceRequests . put ( containerId , resourceRequestEvent ) ; this . outstandingResourceRequestCount . incrementAndGet ( ) ; this . updateRuntimeStatus ( ) ; } catch ( IOException e ) { LOG . log ( Level . SEVERE , "Failed to create Azure Batch task with the following exception: {0}" , e ) ; throw new RuntimeException ( e ) ; } }
This method is called when a resource is requested . It will add a task to the existing Azure Batch job which is equivalent to requesting a container in Azure Batch . When the request is fulfilled and the evaluator shim is started it will send a message back to the driver which signals that a resource request was fulfilled .
2,174
public void onNext ( final RemoteMessage < EvaluatorShimProtocol . EvaluatorShimStatusProto > statusMessage ) { EvaluatorShimProtocol . EvaluatorShimStatusProto message = statusMessage . getMessage ( ) ; String containerId = message . getContainerId ( ) ; String remoteId = message . getRemoteIdentifier ( ) ; LOG . log ( Level . INFO , "Got a status message from evaluator shim = {0} with containerId = {1} and status = {2}." , new String [ ] { remoteId , containerId , message . getStatus ( ) . toString ( ) } ) ; if ( message . getStatus ( ) != EvaluatorShimProtocol . EvaluatorShimStatus . ONLINE ) { LOG . log ( Level . SEVERE , "Unexpected status returned from the evaluator shim: {0}. Ignoring the message." , message . getStatus ( ) . toString ( ) ) ; return ; } this . onResourceAllocated ( containerId , remoteId , Optional . < CloudTask > empty ( ) ) ; }
This method is invoked by the RemoteManager when a message from the evaluator shim is received .
2,175
public void onClose ( ) { try { this . evaluatorShimCommandChannel . close ( ) ; } catch ( Exception e ) { LOG . log ( Level . WARNING , "An unexpected exception while closing the Evaluator Shim Command channel: {0}" , e ) ; throw new RuntimeException ( e ) ; } }
Closes the evaluator shim remote manager command channel .
2,176
public URI generateShimJarFile ( ) { try { Set < FileResource > globalFiles = new HashSet < > ( ) ; final File globalFolder = new File ( this . reefFileNames . getGlobalFolderPath ( ) ) ; final File [ ] filesInGlobalFolder = globalFolder . listFiles ( ) ; for ( final File fileEntry : filesInGlobalFolder != null ? filesInGlobalFolder : new File [ ] { } ) { globalFiles . add ( getFileResourceFromFile ( fileEntry , FileType . LIB ) ) ; } File jarFile = this . jobJarMaker . newBuilder ( ) . addGlobalFileSet ( globalFiles ) . build ( ) ; return uploadFile ( jarFile ) ; } catch ( IOException ex ) { LOG . log ( Level . SEVERE , "Failed to build JAR file" , ex ) ; throw new RuntimeException ( ex ) ; } }
A utility method which builds the evaluator shim JAR file and uploads it to Azure Storage .
2,177
private synchronized Path getWritePath ( ) throws IOException { if ( pathToWriteTo == null ) { final boolean originalExists = fileSystem . exists ( changeLogPath ) ; final boolean altExists = fileSystem . exists ( changeLogAltPath ) ; if ( originalExists && altExists ) { final FileStatus originalStatus = fileSystem . getFileStatus ( changeLogPath ) ; final FileStatus altStatus = fileSystem . getFileStatus ( changeLogAltPath ) ; final long originalLen = originalStatus . getLen ( ) ; final long altLen = altStatus . getLen ( ) ; if ( originalLen < altLen ) { pathToWriteTo = changeLogPath ; } else { pathToWriteTo = changeLogAltPath ; } } else if ( originalExists ) { pathToWriteTo = changeLogAltPath ; } else { pathToWriteTo = changeLogPath ; } } final Path returnPath = pathToWriteTo ; pathToWriteTo = getAlternativePath ( pathToWriteTo ) ; return returnPath ; }
Gets the path to write to .
2,178
public synchronized void close ( ) throws Exception { if ( this . fileSystem != null && ! this . fsClosed ) { this . fileSystem . close ( ) ; this . fsClosed = true ; } }
Closes the FileSystem .
2,179
public byte [ ] call ( final byte [ ] memento ) throws Exception { final ExecutorService schedulerThread = Executors . newSingleThreadExecutor ( ) ; final ExecutorService commandExecutor = Executors . newFixedThreadPool ( numOfThreads ) ; final ConcurrentMap < Integer , Future > futures = new ConcurrentHashMap < > ( ) ; schedulerThread . execute ( new Runnable ( ) { @ SuppressWarnings ( "InfiniteLoopStatement" ) public void run ( ) { while ( true ) { final byte [ ] message ; try { message = pendingRequests . takeFirst ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } final MasterToWorkerRequest masterToWorkerRequest = ( MasterToWorkerRequest ) kryoUtils . deserialize ( message ) ; switch ( masterToWorkerRequest . getType ( ) ) { case AggregateTasklets : final TaskletAggregationRequest taskletAggregationRequest = ( TaskletAggregationRequest ) masterToWorkerRequest ; aggregates . put ( taskletAggregationRequest . getAggregateFunctionId ( ) , new AggregateContainer ( heartBeatTriggerManager , kryoUtils , workerReports , taskletAggregationRequest ) ) ; break ; case ExecuteAggregateTasklet : executeAggregateTasklet ( commandExecutor , masterToWorkerRequest ) ; break ; case ExecuteTasklet : executeTasklet ( commandExecutor , futures , masterToWorkerRequest ) ; break ; case CancelTasklet : final TaskletCancellationRequest cancellationRequest = ( TaskletCancellationRequest ) masterToWorkerRequest ; LOG . log ( Level . FINE , "Cancelling Tasklet with ID {0}." , cancellationRequest . getTaskletId ( ) ) ; final Future future = futures . get ( cancellationRequest . getTaskletId ( ) ) ; if ( future != null ) { future . cancel ( true ) ; } break ; default : throw new RuntimeException ( "Unknown Command" ) ; } } } } ) ; terminated . await ( ) ; return null ; }
Starts the scheduler and executor and waits until termination .
2,180
public InetSocketAddress get ( final Identifier key , final Callable < InetSocketAddress > valueFetcher ) throws ExecutionException { return cache . get ( key , valueFetcher ) ; }
Gets an address for an identifier .
2,181
void onResourceReleaseRequest ( final ResourceReleaseEvent releaseRequest ) { synchronized ( this . theContainers ) { LOG . log ( Level . FINEST , "Release container: {0}" , releaseRequest . getIdentifier ( ) ) ; this . theContainers . release ( releaseRequest . getIdentifier ( ) ) ; this . checkRequestQueue ( ) ; } }
Receives and processes a resource release request .
2,182
void onResourceLaunchRequest ( final ResourceLaunchEvent launchRequest ) { synchronized ( this . theContainers ) { final Container c = this . theContainers . get ( launchRequest . getIdentifier ( ) ) ; try ( final LoggingScope lb = this . loggingScopeFactory . getNewLoggingScope ( "ResourceManager.onResourceLaunchRequest:evaluatorConfigurationFile" ) ) { c . addGlobalFiles ( this . fileNames . getGlobalFolder ( ) ) ; c . addLocalFiles ( getLocalFiles ( launchRequest ) ) ; final File evaluatorConfigurationFile = new File ( c . getFolder ( ) , fileNames . getEvaluatorConfigurationPath ( ) ) ; try { this . configurationSerializer . toFile ( launchRequest . getEvaluatorConf ( ) , evaluatorConfigurationFile ) ; } catch ( final IOException | BindException e ) { throw new RuntimeException ( "Unable to write configuration." , e ) ; } } try ( final LoggingScope lc = this . loggingScopeFactory . getNewLoggingScope ( "ResourceManager.onResourceLaunchRequest:runCommand" ) ) { final List < String > command = getLaunchCommand ( launchRequest , c . getMemory ( ) ) ; LOG . log ( Level . FINEST , "Launching container: {0}" , c ) ; c . run ( command ) ; } } }
Processes a resource launch request .
2,183
public Identifier getNewInstance ( final String str ) { final int index = str . indexOf ( "://" ) ; if ( index < 0 ) { throw new RemoteRuntimeException ( "Invalid remote identifier name: " + str ) ; } final String type = str . substring ( 0 , index ) ; final Class < ? extends Identifier > clazz = typeToClazzMap . get ( type ) ; try { final Constructor < ? extends Identifier > constructor = clazz . getDeclaredConstructor ( CONSTRUCTOR_ARG_TYPES ) ; final Object [ ] args = new Object [ ] { str . substring ( index + 3 ) } ; final Identifier instance = constructor . newInstance ( args ) ; LOG . log ( Level . FINER , "Created new identifier: {0} for {1}" , new Object [ ] { instance , str } ) ; return instance ; } catch ( final NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { LOG . log ( Level . SEVERE , "Cannot create new identifier for: " + str , e ) ; throw new RemoteRuntimeException ( e ) ; } }
Creates a new remote identifier instance .
2,184
static Codec < NamingMessage > createLookupCodec ( final IdentifierFactory factory ) { final Map < Class < ? extends NamingMessage > , Codec < ? extends NamingMessage > > clazzToCodecMap = new HashMap < > ( ) ; clazzToCodecMap . put ( NamingLookupRequest . class , new NamingLookupRequestCodec ( factory ) ) ; clazzToCodecMap . put ( NamingLookupResponse . class , new NamingLookupResponseCodec ( factory ) ) ; final Codec < NamingMessage > codec = new MultiCodec < > ( clazzToCodecMap ) ; return codec ; }
Creates a codec only for lookup .
2,185
static Codec < NamingMessage > createRegistryCodec ( final IdentifierFactory factory ) { final Map < Class < ? extends NamingMessage > , Codec < ? extends NamingMessage > > clazzToCodecMap = new HashMap < > ( ) ; clazzToCodecMap . put ( NamingRegisterRequest . class , new NamingRegisterRequestCodec ( factory ) ) ; clazzToCodecMap . put ( NamingRegisterResponse . class , new NamingRegisterResponseCodec ( new NamingRegisterRequestCodec ( factory ) ) ) ; clazzToCodecMap . put ( NamingUnregisterRequest . class , new NamingUnregisterRequestCodec ( factory ) ) ; final Codec < NamingMessage > codec = new MultiCodec < > ( clazzToCodecMap ) ; return codec ; }
Creates a codec only for registration .
2,186
static Codec < NamingMessage > createFullCodec ( final IdentifierFactory factory ) { final Map < Class < ? extends NamingMessage > , Codec < ? extends NamingMessage > > clazzToCodecMap = new HashMap < > ( ) ; clazzToCodecMap . put ( NamingLookupRequest . class , new NamingLookupRequestCodec ( factory ) ) ; clazzToCodecMap . put ( NamingLookupResponse . class , new NamingLookupResponseCodec ( factory ) ) ; clazzToCodecMap . put ( NamingRegisterRequest . class , new NamingRegisterRequestCodec ( factory ) ) ; clazzToCodecMap . put ( NamingRegisterResponse . class , new NamingRegisterResponseCodec ( new NamingRegisterRequestCodec ( factory ) ) ) ; clazzToCodecMap . put ( NamingUnregisterRequest . class , new NamingUnregisterRequestCodec ( factory ) ) ; final Codec < NamingMessage > codec = new MultiCodec < > ( clazzToCodecMap ) ; return codec ; }
Creates a codec for both lookup and registration .
2,187
public void submit ( final Configuration runtimeConfiguration , final String jobName ) throws Exception { final Configuration driverConfiguration = getDriverConfiguration ( jobName ) ; Tang . Factory . getTang ( ) . newInjector ( runtimeConfiguration ) . getInstance ( REEF . class ) . submit ( driverConfiguration ) ; }
Runs BGD on the given runtime .
2,188
public LauncherStatus run ( final Configuration runtimeConfiguration , final String jobName , final int timeout ) throws Exception { final Configuration driverConfiguration = getDriverConfiguration ( jobName ) ; return DriverLauncher . getLauncher ( runtimeConfiguration ) . run ( driverConfiguration , timeout ) ; }
Runs BGD on the given runtime - with timeout .
2,189
public AvroDriverInfo toAvro ( final String id , final String startTime , final List < AvroReefServiceInfo > services ) { return AvroDriverInfo . newBuilder ( ) . setRemoteId ( id ) . setStartTime ( startTime ) . setServices ( services ) . build ( ) ; }
Build AvroDriverInfo object .
2,190
public void onNext ( final TransportEvent value ) { LOG . log ( Level . FINEST , "{0}" , value ) ; stage . onNext ( value ) ; }
Handles the received event .
2,191
public void onNext ( final T event ) { final EventHandler < T > handler = ( EventHandler < T > ) map . get ( event . getClass ( ) ) ; if ( handler == null ) { throw new WakeRuntimeException ( "No event " + event . getClass ( ) + " handler" ) ; } handler . onNext ( event ) ; }
Invokes a specific handler for the event class type if it exists .
2,192
public void close ( ) { LOG . log ( Level . FINE , "EvaluatorIdlenessThreadPool shutdown: begin" ) ; this . executor . shutdown ( ) ; boolean isTerminated = false ; try { isTerminated = this . executor . awaitTermination ( this . waitInMillis , TimeUnit . MILLISECONDS ) ; } catch ( final InterruptedException ex ) { LOG . log ( Level . WARNING , "EvaluatorIdlenessThreadPool shutdown: Interrupted" , ex ) ; } if ( isTerminated ) { LOG . log ( Level . FINE , "EvaluatorIdlenessThreadPool shutdown: Terminated successfully" ) ; } else { final List < Runnable > pendingJobs = this . executor . shutdownNow ( ) ; LOG . log ( Level . SEVERE , "EvaluatorIdlenessThreadPool shutdown: {0} jobs after timeout" , pendingJobs . size ( ) ) ; LOG . log ( Level . FINE , "EvaluatorIdlenessThreadPool shutdown: pending jobs: {0}" , pendingJobs ) ; } }
Shutdown the thread pool of idleness checkers .
2,193
public EvaluatorContext newContext ( final String contextId , final Optional < String > parentID ) { synchronized ( this . priorIds ) { if ( this . priorIds . contains ( contextId ) ) { throw new IllegalStateException ( "Creating second EvaluatorContext instance for id " + contextId ) ; } this . priorIds . add ( contextId ) ; } return new EvaluatorContext ( contextId , this . evaluatorId , this . evaluatorDescriptor , parentID , this . configurationSerializer , this . contextControlHandler , this . messageDispatcher , this . exceptionCodec , this . contextRepresenters . get ( ) ) ; }
Instantiate a new Context representer with the given id and parent id .
2,194
public MultiRuntimeDefinitionBuilder addRuntime ( final Configuration config , final String runtimeName ) { Validate . notNull ( config , "runtime configuration module should not be null" ) ; Validate . isTrue ( StringUtils . isNotBlank ( runtimeName ) , "runtimeName should be non empty and non blank string" ) ; final AvroRuntimeDefinition rd = createRuntimeDefinition ( config , runtimeName ) ; this . runtimes . put ( runtimeName , rd ) ; return this ; }
Adds runtime configuration module to the builder .
2,195
public MultiRuntimeDefinitionBuilder setDefaultRuntimeName ( final String runtimeName ) { Validate . isTrue ( StringUtils . isNotBlank ( runtimeName ) , "runtimeName should be non empty and non blank string" ) ; this . defaultRuntime = runtimeName ; return this ; }
Sets default runtime name .
2,196
public AvroMultiRuntimeDefinition build ( ) { Validate . isTrue ( this . runtimes . size ( ) == 1 || ! StringUtils . isEmpty ( this . defaultRuntime ) , "Default runtime " + "should be set if more than a single runtime provided" ) ; if ( StringUtils . isEmpty ( this . defaultRuntime ) ) { this . defaultRuntime = this . runtimes . keySet ( ) . iterator ( ) . next ( ) ; } Validate . isTrue ( this . runtimes . containsKey ( this . defaultRuntime ) , "Default runtime should be configured" ) ; return new AvroMultiRuntimeDefinition ( defaultRuntime , new ArrayList < > ( this . runtimes . values ( ) ) ) ; }
Builds multi runtime definition .
2,197
void copyTo ( final File destinationFolder ) throws IOException { for ( final File f : this . theFiles ) { final File destinationFile = new File ( destinationFolder , f . getName ( ) ) ; Files . copy ( f . toPath ( ) , destinationFile . toPath ( ) , java . nio . file . StandardCopyOption . REPLACE_EXISTING ) ; } }
Copies all files in the current FileSet to the given destinationFolder .
2,198
void createSymbolicLinkTo ( final File destinationFolder ) throws IOException { for ( final File f : this . theFiles ) { final File destinationFile = new File ( destinationFolder , f . getName ( ) ) ; Files . createSymbolicLink ( destinationFile . toPath ( ) , f . toPath ( ) ) ; } }
Creates symbolic links for the current FileSet into the given destinationFolder .
2,199
ConfigurationModule addNamesTo ( final ConfigurationModule input , final OptionalParameter < String > field ) { ConfigurationModule result = input ; for ( final String fileName : this . fileNames ( ) ) { result = result . set ( field , fileName ) ; } return result ; }
Adds the file names of this FileSet to the given field of the given ConfigurationModule .