idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
2,200
public AvroEvaluatorList toAvro ( final Map < String , EvaluatorDescriptor > evaluatorMap , final int totalEvaluators , final String startTime ) { final List < AvroEvaluatorEntry > evaluatorEntities = new ArrayList < > ( ) ; for ( final Map . Entry < String , EvaluatorDescriptor > entry : evaluatorMap . entrySet ( ) ) { final EvaluatorDescriptor descriptor = entry . getValue ( ) ; evaluatorEntities . add ( AvroEvaluatorEntry . newBuilder ( ) . setId ( entry . getKey ( ) ) . setName ( descriptor . getNodeDescriptor ( ) . getName ( ) ) . build ( ) ) ; } return AvroEvaluatorList . newBuilder ( ) . setEvaluators ( evaluatorEntities ) . setTotal ( totalEvaluators ) . setStartTime ( startTime != null ? startTime : new Date ( ) . toString ( ) ) . build ( ) ; }
Build AvroEvaluatorList object .
2,201
public T decode ( final byte [ ] data ) { final WakeTuplePBuf tuple ; try { tuple = WakeTuplePBuf . parseFrom ( data ) ; } catch ( final InvalidProtocolBufferException e ) { e . printStackTrace ( ) ; throw new RemoteRuntimeException ( e ) ; } final String className = tuple . getClassName ( ) ; final byte [ ] message = tuple . getData ( ) . toByteArray ( ) ; final Class < ? > clazz ; try { clazz = Class . forName ( className ) ; } catch ( final ClassNotFoundException e ) { e . printStackTrace ( ) ; throw new RemoteRuntimeException ( e ) ; } return clazzToDecoderMap . get ( clazz ) . decode ( message ) ; }
Decodes byte array .
2,202
void start ( ) { final ContextStart contextStart = new ContextStartImpl ( this . identifier ) ; for ( final EventHandler < ContextStart > startHandler : this . contextStartHandlers ) { startHandler . onNext ( contextStart ) ; } }
Fires ContextStart to all registered event handlers .
2,203
void close ( ) { final ContextStop contextStop = new ContextStopImpl ( this . identifier ) ; for ( final EventHandler < ContextStop > stopHandler : this . contextStopHandlers ) { stopHandler . onNext ( contextStop ) ; } }
Fires ContextStop to all registered event handlers .
2,204
public MatMulOutput call ( final MatMulInput input ) throws Exception { final int index = input . getIndex ( ) ; final Matrix < Double > leftMatrix = input . getLeftMatrix ( ) ; final Matrix < Double > rightMatrix = input . getRightMatrix ( ) ; final Matrix < Double > result = leftMatrix . multiply ( rightMatrix ) ; return new MatMulOutput ( index , result ) ; }
Computes multiplication of two matrices .
2,205
public void submitTask ( final String evaluatorConfiguration , final String taskConfiguration ) { final Configuration contextConfiguration = ContextConfiguration . CONF . set ( ContextConfiguration . IDENTIFIER , "RootContext_" + this . getId ( ) ) . build ( ) ; final String contextConfigurationString = this . configurationSerializer . toString ( contextConfiguration ) ; this . launchWithConfigurationString ( evaluatorConfiguration , contextConfigurationString , Optional . < String > empty ( ) , Optional . of ( taskConfiguration ) ) ; }
Submit Task with configuration strings . This method should be called from bridge and the configuration strings are serialized at . Net side .
2,206
public void submitContext ( final String evaluatorConfiguration , final String contextConfiguration ) { launchWithConfigurationString ( evaluatorConfiguration , contextConfiguration , Optional . < String > empty ( ) , Optional . < String > empty ( ) ) ; }
Submit Context with configuration strings . This method should be called from bridge and the configuration strings are serialized at . Net side .
2,207
public void submitContextAndService ( final String evaluatorConfiguration , final String contextConfiguration , final String serviceConfiguration ) { launchWithConfigurationString ( evaluatorConfiguration , contextConfiguration , Optional . of ( serviceConfiguration ) , Optional . < String > empty ( ) ) ; }
Submit Context and Service with configuration strings . This method should be called from bridge and the configuration strings are serialized at . Net side .
2,208
public void submitContextAndTask ( final String evaluatorConfiguration , final String contextConfiguration , final String taskConfiguration ) { this . launchWithConfigurationString ( evaluatorConfiguration , contextConfiguration , Optional . < String > empty ( ) , Optional . of ( taskConfiguration ) ) ; }
Submit Context and Task with configuration strings . This method should be called from bridge and the configuration strings are serialized at . Net side .
2,209
public void submitContextAndServiceAndTask ( final String evaluatorConfiguration , final String contextConfiguration , final String serviceConfiguration , final String taskConfiguration ) { launchWithConfigurationString ( evaluatorConfiguration , contextConfiguration , Optional . of ( serviceConfiguration ) , Optional . of ( taskConfiguration ) ) ; }
Submit Context and Service with configuration strings . This method should be called from bridge and the configuration strings are serialized at . Net side
2,210
private void launchWithConfigurationString ( final String evaluatorConfiguration , final String contextConfiguration , final Optional < String > serviceConfiguration , final Optional < String > taskConfiguration ) { try ( final LoggingScope lb = loggingScopeFactory . evaluatorLaunch ( this . getId ( ) ) ) { final Configuration submissionEvaluatorConfiguration = makeEvaluatorConfiguration ( contextConfiguration , Optional . ofNullable ( evaluatorConfiguration ) , serviceConfiguration , taskConfiguration ) ; resourceBuildAndLaunch ( submissionEvaluatorConfiguration ) ; } }
Submit Context Service and Task with configuration strings . This method should be called from bridge and the configuration strings are serialized at . Net side
2,211
private Configuration makeEvaluatorConfiguration ( final Configuration contextConfiguration , final Optional < Configuration > serviceConfiguration , final Optional < Configuration > taskConfiguration ) { final String contextConfigurationString = this . configurationSerializer . toString ( contextConfiguration ) ; final Optional < String > taskConfigurationString ; if ( taskConfiguration . isPresent ( ) ) { taskConfigurationString = Optional . of ( this . configurationSerializer . toString ( taskConfiguration . get ( ) ) ) ; } else { taskConfigurationString = Optional . empty ( ) ; } final Optional < Configuration > mergedServiceConfiguration = makeRootServiceConfiguration ( serviceConfiguration ) ; if ( mergedServiceConfiguration . isPresent ( ) ) { final String serviceConfigurationString = this . configurationSerializer . toString ( mergedServiceConfiguration . get ( ) ) ; return makeEvaluatorConfiguration ( contextConfigurationString , Optional . < String > empty ( ) , Optional . of ( serviceConfigurationString ) , taskConfigurationString ) ; } else { return makeEvaluatorConfiguration ( contextConfigurationString , Optional . < String > empty ( ) , Optional . < String > empty ( ) , taskConfigurationString ) ; } }
Make configuration for evaluator .
2,212
private Configuration makeEvaluatorConfiguration ( final String contextConfiguration , final Optional < String > evaluatorConfiguration , final Optional < String > serviceConfiguration , final Optional < String > taskConfiguration ) { final ConfigurationModule evaluatorConfigModule ; if ( this . evaluatorManager . getEvaluatorDescriptor ( ) . getProcess ( ) instanceof CLRProcess ) { evaluatorConfigModule = EvaluatorConfiguration . CONFCLR ; } else if ( this . evaluatorManager . getEvaluatorDescriptor ( ) . getProcess ( ) instanceof DotNetProcess ) { evaluatorConfigModule = EvaluatorConfiguration . CONFDOTNET ; } else { evaluatorConfigModule = EvaluatorConfiguration . CONF ; } ConfigurationModule evaluatorConfigurationModule = evaluatorConfigModule . set ( EvaluatorConfiguration . APPLICATION_IDENTIFIER , this . jobIdentifier ) . set ( EvaluatorConfiguration . DRIVER_REMOTE_IDENTIFIER , this . remoteID ) . set ( EvaluatorConfiguration . EVALUATOR_IDENTIFIER , this . getId ( ) ) . set ( EvaluatorConfiguration . ROOT_CONTEXT_CONFIGURATION , contextConfiguration ) ; if ( evaluatorConfiguration . isPresent ( ) ) { evaluatorConfigurationModule = evaluatorConfigurationModule . set ( EvaluatorConfiguration . EVALUATOR_CONFIGURATION , evaluatorConfiguration . get ( ) ) ; } if ( serviceConfiguration . isPresent ( ) ) { evaluatorConfigurationModule = evaluatorConfigurationModule . set ( EvaluatorConfiguration . ROOT_SERVICE_CONFIGURATION , serviceConfiguration . get ( ) ) ; } else { evaluatorConfigurationModule = evaluatorConfigurationModule . set ( EvaluatorConfiguration . ROOT_SERVICE_CONFIGURATION , this . configurationSerializer . toString ( Tang . Factory . getTang ( ) . newConfigurationBuilder ( ) . build ( ) ) ) ; } if ( taskConfiguration . isPresent ( ) ) { evaluatorConfigurationModule = evaluatorConfigurationModule . set ( EvaluatorConfiguration . TASK_CONFIGURATION , taskConfiguration . get ( ) ) ; } return evaluatorConfigurationModule . build ( ) ; }
Make configuration for Evaluator .
2,213
private Optional < Configuration > makeRootServiceConfiguration ( final Optional < Configuration > serviceConfiguration ) { final EvaluatorType evaluatorType = this . evaluatorManager . getEvaluatorDescriptor ( ) . getProcess ( ) . getType ( ) ; if ( EvaluatorType . CLR == evaluatorType ) { LOG . log ( Level . FINE , "Not using the ConfigurationProviders as we are configuring a {0} Evaluator." , evaluatorType ) ; return serviceConfiguration ; } if ( ! serviceConfiguration . isPresent ( ) && this . evaluatorConfigurationProviders . isEmpty ( ) ) { LOG . info ( "No service configuration given and no ConfigurationProviders set." ) ; return Optional . empty ( ) ; } else { final ConfigurationBuilder configurationBuilder = getConfigurationBuilder ( serviceConfiguration ) ; for ( final ConfigurationProvider configurationProvider : this . evaluatorConfigurationProviders ) { configurationBuilder . addConfiguration ( configurationProvider . getConfiguration ( ) ) ; } return Optional . of ( configurationBuilder . build ( ) ) ; } }
Merges the Configurations provided by the evaluatorConfigurationProviders into the given serviceConfiguration if any .
2,214
public static < T extends Identifier > List < T > parseList ( final String ids , final IdentifierFactory factory ) { final List < T > result = new ArrayList < > ( ) ; for ( final String token : ids . split ( DELIMITER ) ) { result . add ( ( T ) factory . getNewInstance ( token . trim ( ) ) ) ; } return result ; }
Parse a string of multiple IDs .
2,215
public Connection < T > newConnection ( final Identifier destId ) { final Connection < T > connection = connectionMap . get ( destId ) ; if ( connection == null ) { final Connection < T > newConnection = new NetworkConnection < > ( this , destId ) ; connectionMap . putIfAbsent ( destId , newConnection ) ; return connectionMap . get ( destId ) ; } return connection ; }
Creates a new connection .
2,216
public void start ( ) throws ContextClientCodeException { synchronized ( this . contextStack ) { LOG . log ( Level . FINEST , "Instantiating root context." ) ; this . contextStack . push ( this . launchContext . get ( ) . getRootContext ( ) ) ; if ( this . launchContext . get ( ) . getInitialTaskConfiguration ( ) . isPresent ( ) ) { LOG . log ( Level . FINEST , "Launching the initial Task" ) ; try { this . contextStack . peek ( ) . startTask ( this . launchContext . get ( ) . getInitialTaskConfiguration ( ) . get ( ) ) ; } catch ( final TaskClientCodeException e ) { this . handleTaskException ( e ) ; } } } }
Start the context manager . This initiates the root context .
2,217
private void addContext ( final EvaluatorRuntimeProtocol . AddContextProto addContextProto ) throws ContextClientCodeException { synchronized ( this . contextStack ) { try { final ContextRuntime currentTopContext = this . contextStack . peek ( ) ; if ( ! currentTopContext . getIdentifier ( ) . equals ( addContextProto . getParentContextId ( ) ) ) { throw new IllegalStateException ( "Trying to instantiate a child context on context with id `" + addContextProto . getParentContextId ( ) + "` while the current top context id is `" + currentTopContext . getIdentifier ( ) + "`" ) ; } final Configuration contextConfiguration = this . configurationSerializer . fromString ( addContextProto . getContextConfiguration ( ) ) ; final ContextRuntime newTopContext ; if ( addContextProto . hasServiceConfiguration ( ) ) { newTopContext = currentTopContext . spawnChildContext ( contextConfiguration , this . configurationSerializer . fromString ( addContextProto . getServiceConfiguration ( ) ) ) ; } else { newTopContext = currentTopContext . spawnChildContext ( contextConfiguration ) ; } this . contextStack . push ( newTopContext ) ; } catch ( final IOException | BindException e ) { throw new RuntimeException ( "Unable to read configuration." , e ) ; } } }
Add a context to the stack .
2,218
private void removeContext ( final String contextID ) { synchronized ( this . contextStack ) { if ( ! contextID . equals ( this . contextStack . peek ( ) . getIdentifier ( ) ) ) { throw new IllegalStateException ( "Trying to close context with id `" + contextID + "`. But the top context has id `" + this . contextStack . peek ( ) . getIdentifier ( ) + "`" ) ; } this . contextStack . peek ( ) . close ( ) ; if ( this . contextStack . size ( ) > 1 ) { this . heartBeatManager . sendHeartbeat ( ) ; } this . contextStack . pop ( ) ; System . gc ( ) ; } }
Remove the context with the given ID from the stack .
2,219
private void startTask ( final EvaluatorRuntimeProtocol . StartTaskProto startTaskProto ) throws TaskClientCodeException { synchronized ( this . contextStack ) { final ContextRuntime currentActiveContext = this . contextStack . peek ( ) ; final String expectedContextId = startTaskProto . getContextId ( ) ; if ( ! expectedContextId . equals ( currentActiveContext . getIdentifier ( ) ) ) { throw new IllegalStateException ( "Task expected context `" + expectedContextId + "` but the active context has ID `" + currentActiveContext . getIdentifier ( ) + "`" ) ; } try { final Configuration taskConfig = this . configurationSerializer . fromString ( startTaskProto . getConfiguration ( ) ) ; currentActiveContext . startTask ( taskConfig ) ; } catch ( IOException | BindException e ) { throw new RuntimeException ( "Unable to read configuration." , e ) ; } } }
Launch a Task .
2,220
public void mark ( final long n ) { tickIfNecessary ( ) ; count . addAndGet ( n ) ; m1Thp . update ( n ) ; m5Thp . update ( n ) ; m15Thp . update ( n ) ; }
Marks the number of events .
2,221
public double getMeanThp ( ) { if ( getCount ( ) == 0 ) { return 0.0 ; } else { final double elapsed = getTick ( ) - startTime ; return getCount ( ) / elapsed * TimeUnit . SECONDS . toNanos ( 1 ) ; } }
Gets the mean throughput .
2,222
private Optional < String > getPreferredNode ( final List < String > nodeNames ) { for ( final String nodeName : nodeNames ) { final String possibleRack = this . racksPerNode . get ( nodeName ) ; if ( possibleRack != null && this . freeNodesPerRack . get ( possibleRack ) . containsKey ( nodeName ) ) { return Optional . of ( nodeName ) ; } } return Optional . empty ( ) ; }
Returns the node name of the container to be allocated if it s available selected from the list of preferred node names . If the list is empty then an empty optional is returned .
2,223
Optional < Container > allocateContainer ( final ResourceRequestEvent requestEvent ) { Container container = null ; final Optional < String > nodeName = getPreferredNode ( requestEvent . getNodeNameList ( ) ) ; if ( nodeName . isPresent ( ) ) { container = allocateBasedOnNode ( requestEvent . getMemorySize ( ) . orElse ( this . defaultMemorySize ) , requestEvent . getVirtualCores ( ) . orElse ( this . defaultNumberOfCores ) , nodeName . get ( ) ) ; } else { final Optional < String > rackName = getPreferredRack ( requestEvent . getRackNameList ( ) ) ; if ( rackName . isPresent ( ) ) { container = allocateBasedOnRack ( requestEvent . getMemorySize ( ) . orElse ( this . defaultMemorySize ) , requestEvent . getVirtualCores ( ) . orElse ( this . defaultNumberOfCores ) , rackName . get ( ) ) ; } } return Optional . ofNullable ( container ) ; }
Allocates a container based on a request event . First it tries to match a given node if it cannot it tries to get a spot in a rack .
2,224
private < TEvent > void unimplemented ( final long identifier , final TEvent event ) { LOG . log ( Level . SEVERE , "Unimplemented event: [{0}]: {1}" , new Object [ ] { identifier , event } ) ; throw new RuntimeException ( "Event not supported: " + event ) ; }
Called when an event is received that does not have an onNext method definition in TSubCls . Override in TSubClas to handle the error .
2,225
public < TEvent > void onNext ( final long identifier , final TEvent event ) throws IllegalAccessException , InvocationTargetException { final Method onNext = methodMap . get ( event . getClass ( ) . getName ( ) ) ; if ( onNext != null ) { onNext . invoke ( this , identifier , event ) ; } else { unimplemented ( identifier , event ) ; } }
Generic event onNext method in the base interface which maps the call to a concrete event onNext method in TSubCls if one exists otherwise unimplemented is invoked .
2,226
public void run ( ) { this . stateLock . lock ( ) ; try { if ( this . state != RunnableProcessState . INIT ) { throw new IllegalStateException ( "The RunnableProcess can't be reused" ) ; } final File errFile = new File ( folder , standardErrorFileName ) ; final File outFile = new File ( folder , standardOutFileName ) ; try { LOG . log ( Level . FINEST , "Launching process \"{0}\"\nSTDERR can be found in {1}\nSTDOUT can be found in {2}" , new Object [ ] { this . id , errFile . getAbsolutePath ( ) , outFile . getAbsolutePath ( ) } ) ; this . process = new ProcessBuilder ( ) . command ( this . command ) . directory ( this . folder ) . redirectError ( errFile ) . redirectOutput ( outFile ) . start ( ) ; this . setState ( RunnableProcessState . RUNNING ) ; this . processObserver . onProcessStarted ( this . id ) ; } catch ( final IOException ex ) { LOG . log ( Level . SEVERE , "Unable to spawn process " + this . id + " with command " + this . command , ex ) ; } } finally { this . stateLock . unlock ( ) ; } try { LOG . log ( Level . FINER , "Wait for process completion: {0}" , this . id ) ; final int returnValue = this . process . waitFor ( ) ; this . processObserver . onProcessExit ( this . id , returnValue ) ; this . stateLock . lock ( ) ; try { this . setState ( RunnableProcessState . ENDED ) ; this . doneCond . signalAll ( ) ; } finally { this . stateLock . unlock ( ) ; } LOG . log ( Level . FINER , "Process \"{0}\" returned {1}" , new Object [ ] { this . id , returnValue } ) ; } catch ( final InterruptedException ex ) { LOG . log ( Level . SEVERE , "Interrupted while waiting for the process \"{0}\" to complete. Exception: {1}" , new Object [ ] { this . id , ex } ) ; } }
Runs the configured process .
2,227
public void cancel ( ) { this . stateLock . lock ( ) ; try { if ( this . state == RunnableProcessState . RUNNING ) { this . process . destroy ( ) ; if ( ! this . doneCond . await ( DESTROY_WAIT_TIME , TimeUnit . MILLISECONDS ) ) { LOG . log ( Level . FINE , "{0} milliseconds elapsed" , DESTROY_WAIT_TIME ) ; } } if ( this . state == RunnableProcessState . RUNNING ) { LOG . log ( Level . WARNING , "The child process survived Process.destroy()" ) ; if ( OSUtils . isUnix ( ) || OSUtils . isWindows ( ) ) { LOG . log ( Level . WARNING , "Attempting to kill the process via the kill command line" ) ; try { final long pid = readPID ( ) ; OSUtils . kill ( pid ) ; } catch ( final IOException | InterruptedException | NumberFormatException e ) { LOG . log ( Level . SEVERE , "Unable to kill the process." , e ) ; } } } } catch ( final InterruptedException ex ) { LOG . log ( Level . SEVERE , "Interrupted while waiting for the process \"{0}\" to complete. Exception: {1}" , new Object [ ] { this . id , ex } ) ; } finally { this . stateLock . unlock ( ) ; } }
Cancels the running process if it is running .
2,228
private void setState ( final RunnableProcessState newState ) { if ( ! this . state . isLegal ( newState ) ) { throw new IllegalStateException ( "Transition from " + this . state + " to " + newState + " is illegal" ) ; } this . state = newState ; }
Sets a new state for the process .
2,229
public void close ( ) { LOG . log ( Level . FINER , "Closing the evaluators - begin" ) ; final List < EvaluatorManager > evaluatorsCopy ; synchronized ( this ) { evaluatorsCopy = new ArrayList < > ( this . evaluators . values ( ) ) ; } for ( final EvaluatorManager evaluatorManager : evaluatorsCopy ) { if ( ! evaluatorManager . isClosedOrClosing ( ) ) { LOG . log ( Level . WARNING , "Unclean shutdown of evaluator {0}" , evaluatorManager . getId ( ) ) ; evaluatorManager . close ( ) ; } } LOG . log ( Level . FINER , "Closing the evaluators - end" ) ; }
Closes all EvaluatorManager instances managed .
2,230
public synchronized void put ( final EvaluatorManager evaluatorManager ) { final String evaluatorId = evaluatorManager . getId ( ) ; if ( this . wasClosed ( evaluatorId ) ) { throw new IllegalArgumentException ( "Trying to re-add an Evaluator that has already been closed: " + evaluatorId ) ; } final EvaluatorManager prev = this . evaluators . put ( evaluatorId , evaluatorManager ) ; LOG . log ( Level . FINEST , "Adding: {0} previous: {1}" , new Object [ ] { evaluatorId , prev } ) ; if ( prev != null ) { throw new IllegalArgumentException ( "Trying to re-add an Evaluator that is already known: " + evaluatorId ) ; } }
Adds an EvaluatorManager .
2,231
public synchronized void removeClosedEvaluator ( final EvaluatorManager evaluatorManager ) { final String evaluatorId = evaluatorManager . getId ( ) ; LOG . log ( Level . FINE , "Removing closed evaluator: {0}" , evaluatorId ) ; if ( ! evaluatorManager . isClosed ( ) ) { throw new IllegalArgumentException ( "Removing evaluator that has not been closed yet: " + evaluatorId ) ; } if ( ! this . evaluators . containsKey ( evaluatorId ) && ! this . closedEvaluatorIds . contains ( evaluatorId ) ) { throw new IllegalArgumentException ( "Removing unknown evaluator: " + evaluatorId ) ; } if ( ! this . evaluators . containsKey ( evaluatorId ) && this . closedEvaluatorIds . contains ( evaluatorId ) ) { LOG . log ( Level . FINE , "Removing closed evaluator which has already been removed: {0}" , evaluatorId ) ; return ; } evaluatorManager . shutdown ( ) ; this . evaluators . remove ( evaluatorId ) ; this . closedEvaluatorIds . add ( evaluatorId ) ; LOG . log ( Level . FINEST , "Closed evaluator removed: {0}" , evaluatorId ) ; }
Moves evaluator from map of active evaluators to set of closed evaluators .
2,232
public void submit ( final File clrFolder , final boolean submitDriver , final boolean local , final Configuration clientConfig ) { try ( final LoggingScope ls = this . loggingScopeFactory . driverSubmit ( submitDriver ) ) { if ( ! local ) { this . driverConfiguration = Configurations . merge ( this . driverConfiguration , getYarnConfiguration ( ) ) ; } try { addCLRFiles ( clrFolder ) ; } catch ( final BindException e ) { LOG . log ( Level . FINE , "Failed to bind" , e ) ; } if ( submitDriver ) { this . reef . submit ( this . driverConfiguration ) ; } else { final File driverConfig = new File ( System . getProperty ( "user.dir" ) + "/driver.config" ) ; try { new AvroConfigurationSerializer ( ) . toFile ( Configurations . merge ( this . driverConfiguration , clientConfig ) , driverConfig ) ; LOG . log ( Level . INFO , "Driver configuration file created at " + driverConfig . getAbsolutePath ( ) ) ; } catch ( final IOException e ) { throw new RuntimeException ( "Cannot create driver configuration file at " + driverConfig . getAbsolutePath ( ) , e ) ; } } } }
Launch the job driver .
2,233
@ SuppressWarnings ( "checkstyle:hiddenfield" ) public void setDriverInfo ( final String identifier , final int memory , final String jobSubmissionDirectory ) { if ( identifier == null || identifier . isEmpty ( ) ) { throw new RuntimeException ( "driver id cannot be null or empty" ) ; } if ( memory <= 0 ) { throw new RuntimeException ( "driver memory cannot be negative number: " + memory ) ; } this . driverMemory = memory ; this . driverId = identifier ; if ( jobSubmissionDirectory != null && ! jobSubmissionDirectory . equals ( "empty" ) ) { this . jobSubmissionDirectory = jobSubmissionDirectory ; } else { LOG . log ( Level . FINE , "No job submission directory provided by CLR user, will use " + this . jobSubmissionDirectory ) ; } }
Set the driver memory .
2,234
public void waitForCompletion ( final int waitTime ) { LOG . info ( "Waiting for the Job Driver to complete: " + waitTime ) ; if ( waitTime == 0 ) { close ( 0 ) ; return ; } else if ( waitTime < 0 ) { waitTillDone ( ) ; } final long endTime = System . currentTimeMillis ( ) + waitTime * 1000 ; close ( endTime ) ; }
Wait for the job driver to complete .
2,235
public boolean cancel ( final boolean mayInterruptIfRunning ) { try { return cancel ( mayInterruptIfRunning , Optional . < Long > empty ( ) , Optional . < TimeUnit > empty ( ) ) ; } catch ( final TimeoutException e ) { LOG . log ( Level . WARNING , "Received a TimeoutException in VortexFuture.cancel(). Should not have occurred." ) ; return false ; } }
Sends a cancel signal and blocks and waits until the task is cancelled completed or failed .
2,236
public boolean cancel ( final boolean mayInterruptIfRunning , final long timeout , final TimeUnit unit ) throws TimeoutException { return cancel ( mayInterruptIfRunning , Optional . of ( timeout ) , Optional . of ( unit ) ) ; }
Sends a cancel signal and blocks and waits until the task is cancelled completed or failed or if the timeout has expired .
2,237
public TOutput get ( ) throws InterruptedException , ExecutionException , CancellationException { countDownLatch . await ( ) ; if ( userResult != null ) { return userResult . get ( ) ; } else { assert this . cancelled . get ( ) || userException != null ; if ( userException != null ) { throw new ExecutionException ( userException ) ; } throw new CancellationException ( "Tasklet was cancelled." ) ; } }
Infinitely wait for the result of the task .
2,238
public TOutput get ( final long timeout , final TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException , CancellationException { if ( ! countDownLatch . await ( timeout , unit ) ) { throw new TimeoutException ( "Waiting for the results of the task timed out. Timeout = " + timeout + " in time units: " + unit ) ; } return get ( ) ; }
Wait a certain period of time for the result of the task .
2,239
public void completed ( final int pTaskletId , final TOutput result ) { assert taskletId == pTaskletId ; this . userResult = Optional . ofNullable ( result ) ; if ( callbackHandler != null ) { executor . execute ( new Runnable ( ) { public void run ( ) { callbackHandler . onSuccess ( userResult . get ( ) ) ; } } ) ; } this . countDownLatch . countDown ( ) ; }
Called by VortexMaster to let the user know that the Tasklet completed .
2,240
public void threwException ( final int pTaskletId , final Exception exception ) { assert taskletId == pTaskletId ; this . userException = exception ; if ( callbackHandler != null ) { executor . execute ( new Runnable ( ) { public void run ( ) { callbackHandler . onFailure ( exception ) ; } } ) ; } this . countDownLatch . countDown ( ) ; }
Called by VortexMaster to let the user know that the Tasklet threw an exception .
2,241
public void cancelled ( final int pTaskletId ) { assert taskletId == pTaskletId ; this . cancelled . set ( true ) ; if ( callbackHandler != null ) { executor . execute ( new Runnable ( ) { public void run ( ) { callbackHandler . onFailure ( new InterruptedException ( "VortexFuture has been cancelled on request." ) ) ; } } ) ; } this . countDownLatch . countDown ( ) ; }
Called by VortexMaster to let the user know that the Tasklet was cancelled .
2,242
private Resource getResource ( final JobSubmissionEvent jobSubmissionEvent ) { return new Resource ( ) . setMemory ( jobSubmissionEvent . getDriverMemory ( ) . get ( ) ) . setvCores ( jobSubmissionEvent . getDriverCPUCores ( ) . get ( ) ) ; }
Extracts the resource demands from the jobSubmissionEvent .
2,243
private List < String > getCommandList ( final JobSubmissionEvent jobSubmissionEvent ) { return new JavaLaunchCommandBuilder ( ) . setJavaPath ( "%JAVA_HOME%/bin/java" ) . setConfigurationFilePaths ( Collections . singletonList ( this . filenames . getDriverConfigurationPath ( ) ) ) . setClassPath ( this . classpath . getDriverClasspath ( ) ) . setMemory ( jobSubmissionEvent . getDriverMemory ( ) . get ( ) ) . setStandardErr ( ApplicationConstants . LOG_DIR_EXPANSION_VAR + "/" + this . filenames . getDriverStderrFileName ( ) ) . setStandardOut ( ApplicationConstants . LOG_DIR_EXPANSION_VAR + "/" + this . filenames . getDriverStdoutFileName ( ) ) . build ( ) ; }
Assembles the command to execute the Driver in list form .
2,244
public void run ( ) { while ( ! this . closed ) { final EventSource < T > nextSource = sources . poll ( ) ; if ( null != nextSource ) { final T message = nextSource . getNext ( ) ; if ( null != message ) { sources . add ( nextSource ) ; this . output . onNext ( message ) ; } else { Logger . getLogger ( Pull2Push . class . getName ( ) ) . log ( Level . INFO , "Droping message source {0} from the queue" , nextSource . toString ( ) ) ; } } } }
Executes the message loop .
2,245
public CommunicationGroupDriver getNewInstance ( final Class < ? extends Name < String > > groupName , final Class < ? extends Topology > topologyClass , final int numberOfTasks , final int customFanOut ) throws InjectionException { final Injector newInjector = injector . forkInjector ( ) ; newInjector . bindVolatileParameter ( CommGroupNameClass . class , groupName ) ; newInjector . bindVolatileParameter ( TopologyClass . class , topologyClass ) ; newInjector . bindVolatileParameter ( CommGroupNumTask . class , numberOfTasks ) ; newInjector . bindVolatileParameter ( TreeTopologyFanOut . class , customFanOut ) ; return newInjector . getInstance ( CommunicationGroupDriver . class ) ; }
Instantiates a new CommunicationGroupDriver instance .
2,246
public byte [ ] call ( final byte [ ] memento ) throws IOException { try ( final DataOutputStream outputStream = outputStreamProvider . create ( "hello" ) ) { outputStream . writeBytes ( "Hello REEF!" ) ; } return null ; }
Receives an output stream from the output service and writes Hello REEF! on it .
2,247
public static void main ( final String [ ] args ) { try { final Configuration config = getClientConfiguration ( args ) ; LOG . log ( Level . INFO , "Configuration:\n--\n{0}--" , Configurations . toString ( config , true ) ) ; final Injector injector = Tang . Factory . getTang ( ) . newInjector ( config ) ; final SuspendClient client = injector . getInstance ( SuspendClient . class ) ; client . submit ( ) ; client . waitForCompletion ( ) ; LOG . info ( "Done!" ) ; } catch ( final BindException | IOException | InjectionException ex ) { LOG . log ( Level . SEVERE , "Cannot launch: configuration error" , ex ) ; } catch ( final Exception ex ) { LOG . log ( Level . SEVERE , "Cleanup error" , ex ) ; } }
Main method that runs the example .
2,248
public String getTrackingUrl ( ) { if ( this . httpServer == null ) { return "" ; } try { return InetAddress . getLocalHost ( ) . getHostAddress ( ) + ":" + httpServer . getPort ( ) ; } catch ( final UnknownHostException e ) { LOG . log ( Level . WARNING , "Cannot get host address." , e ) ; throw new RuntimeException ( "Cannot get host address." , e ) ; } }
get tracking URI .
2,249
private void kill ( final String applicationId ) throws IOException { LOG . log ( Level . INFO , "Killing application [{0}]" , applicationId ) ; this . hdInsightInstance . killApplication ( applicationId ) ; }
Kills the application with the given id .
2,250
private void logs ( final String applicationId ) throws IOException { LOG . log ( Level . INFO , "Fetching logs for application [{0}]" , applicationId ) ; this . logFetcher . fetch ( applicationId , new OutputStreamWriter ( System . out , StandardCharsets . UTF_8 ) ) ; }
Fetches the logs for the application with the given id and prints them to System . out .
2,251
private void logs ( final String applicationId , final File folder ) throws IOException { LOG . log ( Level . FINE , "Fetching logs for application [{0}] and storing them in folder [{1}]" , new Object [ ] { applicationId , folder . getAbsolutePath ( ) } ) ; if ( ! folder . exists ( ) && ! folder . mkdirs ( ) ) { LOG . log ( Level . WARNING , "Failed to create [{0}]" , folder . getAbsolutePath ( ) ) ; } this . logFetcher . fetch ( applicationId , folder ) ; }
Fetches the logs for the application with the given id and stores them in the given folder . One file per container .
2,252
private void list ( ) throws IOException { LOG . log ( Level . FINE , "Listing applications" ) ; final List < ApplicationState > applications = this . hdInsightInstance . listApplications ( ) ; for ( final ApplicationState appState : applications ) { if ( appState . getState ( ) . equals ( "RUNNING" ) ) { System . out . println ( appState . getId ( ) + "\t" + appState . getName ( ) ) ; } } }
Fetches a list of all running applications .
2,253
public byte [ ] toBytes ( final DefinedRuntimes definedRuntimes ) { final DatumWriter < DefinedRuntimes > configurationWriter = new SpecificDatumWriter < > ( DefinedRuntimes . class ) ; try ( final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ) { final BinaryEncoder binaryEncoder = EncoderFactory . get ( ) . binaryEncoder ( out , null ) ; configurationWriter . write ( definedRuntimes , binaryEncoder ) ; binaryEncoder . flush ( ) ; out . flush ( ) ; return out . toByteArray ( ) ; } catch ( final IOException e ) { throw new RuntimeException ( "Unable to serialize DefinedRuntimes" , e ) ; } }
Serializes DefinedRuntimes .
2,254
private static boolean couldBeYarnConfigurationPath ( final String path ) { return path . contains ( "conf" ) || path . contains ( "etc" ) || path . contains ( HadoopEnvironment . HADOOP_CONF_DIR ) ; }
The oracle that tells us whether a given path could be a YARN configuration path .
2,255
public static String parseIp ( final String remoteIdentifier ) { return remoteIdentifier . substring ( PROTOCOL . length ( ) , remoteIdentifier . lastIndexOf ( ':' ) ) ; }
Get the IP address from the remote identifier .
2,256
public void onNext ( final JobSubmissionEvent jobSubmissionEvent ) { LOG . log ( Level . FINEST , "Submitting job: {0}" , jobSubmissionEvent ) ; try { this . applicationId = createApplicationId ( jobSubmissionEvent ) ; final String folderName = this . azureBatchFileNames . getStorageJobFolder ( this . applicationId ) ; LOG . log ( Level . FINE , "Creating a job folder on Azure at: {0}." , folderName ) ; final URI jobFolderURL = this . azureStorageClient . getJobSubmissionFolderUri ( folderName ) ; LOG . log ( Level . FINE , "Getting a shared access signature for {0}." , folderName ) ; final String storageContainerSAS = this . azureStorageClient . createContainerSharedAccessSignature ( ) ; LOG . log ( Level . FINE , "Assembling Configuration for the Driver." ) ; final Configuration driverConfiguration = makeDriverConfiguration ( jobSubmissionEvent , this . applicationId , jobFolderURL ) ; LOG . log ( Level . FINE , "Making Job JAR." ) ; final File jobSubmissionJarFile = this . jobJarMaker . createJobSubmissionJAR ( jobSubmissionEvent , driverConfiguration ) ; LOG . log ( Level . FINE , "Uploading Job JAR to Azure." ) ; final URI jobJarSasUri = this . azureStorageClient . uploadFile ( folderName , jobSubmissionJarFile ) ; LOG . log ( Level . FINE , "Assembling application submission." ) ; final String command = this . launchCommandBuilder . buildDriverCommand ( jobSubmissionEvent ) ; this . azureBatchHelper . submitJob ( getApplicationId ( ) , storageContainerSAS , jobJarSasUri , command ) ; } catch ( final IOException e ) { LOG . log ( Level . SEVERE , "Error submitting Azure Batch request: {0}" , e ) ; throw new RuntimeException ( e ) ; } }
Invoked when JobSubmissionEvent is triggered .
2,257
public static void main ( final String [ ] args ) throws InjectionException , IOException { final JavaConfigurationBuilder driverConfigBuilder = TANG . newConfigurationBuilder ( STATIC_DRIVER_CONFIG ) ; new CommandLine ( driverConfigBuilder ) . registerShortNameOfClass ( Command . class ) . registerShortNameOfClass ( NumEvaluators . class ) . registerShortNameOfClass ( RuntimeName . class ) . processCommandLine ( args ) ; final Configuration driverConfig = driverConfigBuilder . build ( ) ; final Injector injector = TANG . newInjector ( driverConfig ) ; final int numEvaluators = injector . getNamedInstance ( NumEvaluators . class ) ; final String runtimeName = injector . getNamedInstance ( RuntimeName . class ) ; final String command = injector . getNamedInstance ( Command . class ) ; LOG . log ( Level . INFO , "REEF distributed shell: {0} evaluators on {1} runtime :: {2}" , new Object [ ] { numEvaluators , runtimeName , command } ) ; final Configuration runtimeConfig ; switch ( runtimeName ) { case "local" : runtimeConfig = LocalRuntimeConfiguration . CONF . set ( LocalRuntimeConfiguration . MAX_NUMBER_OF_EVALUATORS , numEvaluators ) . build ( ) ; break ; case "yarn" : runtimeConfig = YarnClientConfiguration . CONF . build ( ) ; break ; default : LOG . log ( Level . SEVERE , "Unknown runtime: {0}" , runtimeName ) ; throw new IllegalArgumentException ( "Unknown runtime: " + runtimeName ) ; } final LauncherStatus status = DriverLauncher . getLauncher ( runtimeConfig ) . run ( driverConfig , JOB_TIMEOUT ) ; LOG . log ( Level . INFO , "REEF job completed: {0}" , status ) ; }
Start the distributed shell job .
2,258
synchronized void add ( final Container container ) { final String containerId = container . getId ( ) . toString ( ) ; if ( this . hasContainer ( containerId ) ) { throw new RuntimeException ( "Trying to add a Container that is already known: " + containerId ) ; } this . containers . put ( containerId , container ) ; }
Registers the given container .
2,259
synchronized Container removeAndGet ( final String containerId ) { final Container result = this . containers . remove ( containerId ) ; if ( null == result ) { throw new RuntimeException ( "Unknown container to remove: " + containerId ) ; } return result ; }
Removes the container with the given ID .
2,260
public static void main ( final String [ ] args ) throws Exception { LOG . log ( Level . INFO , "Entering EvaluatorShimLauncher.main()." ) ; final Injector injector = Tang . Factory . getTang ( ) . newInjector ( parseCommandLine ( args ) ) ; final EvaluatorShimLauncher launcher = injector . getInstance ( EvaluatorShimLauncher . class ) ; launcher . launch ( ) ; }
The starting point of the evaluator shim launcher .
2,261
public void onNext ( final RemoteEvent < T > value ) { try { LOG . log ( Level . FINEST , "Link: {0} event: {1}" , new Object [ ] { linkRef , value } ) ; if ( linkRef . get ( ) == null ) { queue . add ( value ) ; final Link < byte [ ] > link = transport . get ( value . remoteAddress ( ) ) ; if ( link != null ) { LOG . log ( Level . FINEST , "transport get link: {0}" , link ) ; setLink ( link ) ; return ; } final ConnectFutureTask < Link < byte [ ] > > cf = new ConnectFutureTask < > ( new ConnectCallable ( transport , value . localAddress ( ) , value . remoteAddress ( ) ) , new ConnectEventHandler < > ( this ) ) ; executor . submit ( cf ) ; } else { LOG . log ( Level . FINEST , "Send: {0} event: {1}" , new Object [ ] { linkRef , value } ) ; linkRef . get ( ) . write ( encoder . encode ( value ) ) ; } } catch ( final RemoteRuntimeException ex ) { LOG . log ( Level . SEVERE , "Remote Exception" , ex ) ; throw ex ; } }
Handles the event to send to a remote node .
2,262
public byte [ ] recvFromChildren ( ) { LOG . entering ( "OperatorTopologyStructImpl" , "recvFromChildren" , getQualifiedName ( ) ) ; for ( final NodeStruct child : children ) { childrenToRcvFrom . add ( child . getId ( ) ) ; } byte [ ] retVal = new byte [ 0 ] ; while ( ! childrenToRcvFrom . isEmpty ( ) ) { LOG . finest ( getQualifiedName ( ) + "Waiting for some child to send data" ) ; final NodeStruct child = nodesWithDataTakeUnsafe ( ) ; final byte [ ] receivedVal = recvFromNodeCheckBigMsg ( child , ReefNetworkGroupCommProtos . GroupCommMessage . Type . Gather ) ; if ( receivedVal != null ) { retVal = ArrayUtils . addAll ( retVal , receivedVal ) ; } childrenToRcvFrom . remove ( child . getId ( ) ) ; } LOG . exiting ( "OperatorTopologyStructImpl" , "recvFromChildren" , getQualifiedName ( ) ) ; return retVal ; }
Receive data from all children as a single byte array . Messages from children are simply byte - concatenated . This method is currently used only by the Gather operator .
2,263
public MultiRuntimeConfigurationBuilder addRuntime ( final String runtimeName ) { Validate . isTrue ( SUPPORTED_RUNTIMES . contains ( runtimeName ) , "unsupported runtime " + runtimeName ) ; this . runtimeNames . add ( runtimeName ) ; return this ; }
Adds runtime name to the builder .
2,264
public MultiRuntimeConfigurationBuilder setDefaultRuntime ( final String runtimeName ) { Validate . isTrue ( SUPPORTED_RUNTIMES . contains ( runtimeName ) , "Unsupported runtime " + runtimeName ) ; Validate . isTrue ( ! this . defaultRuntime . isPresent ( ) , "Default runtime was already added" ) ; this . defaultRuntime = Optional . of ( runtimeName ) ; return this ; }
Sets default runtime . Default runtime is used when no runtime was specified for evaluator
2,265
public MultiRuntimeConfigurationBuilder setSubmissionRuntime ( final String runtimeName ) { Validate . isTrue ( SUPPORTED_SUBMISSION_RUNTIMES . contains ( runtimeName ) , "Unsupported submission runtime " + runtimeName ) ; Validate . isTrue ( this . submissionRuntime == null , "Submission runtime was already added" ) ; this . submissionRuntime = runtimeName ; return this ; }
Sets the submission runtime . Submission runtime is used for launching the job driver .
2,266
public Configuration build ( ) { Validate . notNull ( this . submissionRuntime , "Default Runtime was not defined" ) ; if ( ! this . defaultRuntime . isPresent ( ) || this . runtimeNames . size ( ) == 1 ) { this . defaultRuntime = Optional . of ( this . runtimeNames . toArray ( new String [ 0 ] ) [ 0 ] ) ; } Validate . isTrue ( this . defaultRuntime . isPresent ( ) , "Default runtime was not defined, and multiple runtimes were specified" ) ; if ( ! this . runtimeNames . contains ( this . defaultRuntime . get ( ) ) ) { this . runtimeNames . add ( this . defaultRuntime . get ( ) ) ; } JavaConfigurationBuilder conf = Tang . Factory . getTang ( ) . newConfigurationBuilder ( ) ; for ( Map . Entry < Class , Object > entry : this . namedParameters . entrySet ( ) ) { conf = conf . bindNamedParameter ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } conf = conf . bindNamedParameter ( DefaultRuntimeName . class , this . defaultRuntime . get ( ) ) ; for ( final String runtimeName : this . runtimeNames ) { conf = conf . bindSetEntry ( RuntimeNames . class , runtimeName ) ; } if ( ! this . submissionRuntime . equalsIgnoreCase ( RuntimeIdentifier . RUNTIME_NAME ) ) { throw new RuntimeException ( "Unsupported submission runtime " + this . submissionRuntime ) ; } conf = conf . bindImplementation ( MultiRuntimeMainConfigurationGenerator . class , YarnMultiRuntimeMainConfigurationGeneratorImpl . class ) ; return Configurations . merge ( conf . build ( ) , ExtensibleYarnClientConfiguration . CONF . set ( ExtensibleYarnClientConfiguration . DRIVER_CONFIGURATION_PROVIDER , MultiRuntimeDriverConfigurationProvider . class ) . build ( ) ) ; }
Builds the configuration .
2,267
@ SuppressWarnings ( "unchecked" ) public < T > T parseDefaultValue ( final NamedParameterNode < T > name ) { final String [ ] vals = name . getDefaultInstanceAsStrings ( ) ; final T [ ] ret = ( T [ ] ) new Object [ vals . length ] ; for ( int i = 0 ; i < vals . length ; i ++ ) { final String val = vals [ i ] ; try { ret [ i ] = parse ( name , val ) ; } catch ( final ParseException e ) { throw new ClassHierarchyException ( "Could not parse default value" , e ) ; } } if ( name . isSet ( ) ) { return ( T ) new HashSet < T > ( Arrays . asList ( ret ) ) ; } else if ( name . isList ( ) ) { return ( T ) new ArrayList < T > ( Arrays . asList ( ret ) ) ; } else { if ( ret . length == 0 ) { return null ; } else if ( ret . length == 1 ) { return ret [ 0 ] ; } else { throw new IllegalStateException ( "Multiple defaults for non-set named parameter! " + name . getFullName ( ) ) ; } } }
A helper method that returns the parsed default value of a given NamedParameter .
2,268
public Class < ? > classForName ( final String name ) throws ClassNotFoundException { return ReflectionUtilities . classForName ( name , loader ) ; }
Helper method that converts a String to a Class using this ClassHierarchy s classloader .
2,269
@ SuppressWarnings ( "unchecked" ) private < T > Node registerClass ( final Class < T > c ) throws ClassHierarchyException { if ( c . isArray ( ) ) { throw new UnsupportedOperationException ( "Can't register array types" ) ; } try { return getAlreadyBoundNode ( c ) ; } catch ( final NameResolutionException ignored ) { } final Node n = buildPathToNode ( c ) ; if ( n instanceof ClassNode ) { final ClassNode < T > cn = ( ClassNode < T > ) n ; final Class < T > superclass = ( Class < T > ) c . getSuperclass ( ) ; if ( superclass != null ) { try { ( ( ClassNode < T > ) getAlreadyBoundNode ( superclass ) ) . putImpl ( cn ) ; } catch ( final NameResolutionException e ) { throw new IllegalStateException ( e ) ; } } for ( final Class < ? > interf : c . getInterfaces ( ) ) { try { ( ( ClassNode < T > ) getAlreadyBoundNode ( interf ) ) . putImpl ( cn ) ; } catch ( final NameResolutionException e ) { throw new IllegalStateException ( e ) ; } } } return n ; }
Assumes that all of the parents of c have been registered already .
2,270
private static void logToken ( final Level logLevel , final String msgPrefix , final UserGroupInformation user ) { if ( LOG . isLoggable ( logLevel ) ) { LOG . log ( logLevel , "{0} number of tokens: [{1}]." , new Object [ ] { msgPrefix , user . getCredentials ( ) . numberOfTokens ( ) } ) ; for ( final org . apache . hadoop . security . token . Token t : user . getCredentials ( ) . getAllTokens ( ) ) { LOG . log ( logLevel , "Token service: {0}, token kind: {1}." , new Object [ ] { t . getService ( ) , t . getKind ( ) } ) ; } } }
Log all the tokens in the container for thr user .
2,271
private void writeDriverHttpEndPoint ( final File driverFolder , final String applicationId , final Path dfsPath ) throws IOException { final FileSystem fs = FileSystem . get ( yarnConfiguration ) ; final Path httpEndpointPath = new Path ( dfsPath , fileNames . getDriverHttpEndpoint ( ) ) ; String trackingUri = null ; LOG . log ( Level . INFO , "Attempt to reading " + httpEndpointPath . toString ( ) ) ; for ( int i = 0 ; i < 60 ; i ++ ) { try { LOG . log ( Level . FINE , "Attempt " + i + " reading " + httpEndpointPath . toString ( ) ) ; if ( fs . exists ( httpEndpointPath ) ) { final FSDataInputStream input = fs . open ( httpEndpointPath ) ; final BufferedReader reader = new BufferedReader ( new InputStreamReader ( input , StandardCharsets . UTF_8 ) ) ; trackingUri = reader . readLine ( ) ; reader . close ( ) ; break ; } } catch ( Exception ignored ) { } try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException ex2 ) { break ; } } if ( null == trackingUri ) { trackingUri = "" ; LOG . log ( Level . WARNING , "Failed reading " + httpEndpointPath . toString ( ) ) ; } else { LOG . log ( Level . INFO , "Completed reading trackingUri :" + trackingUri ) ; } final File driverHttpEndpointFile = new File ( driverFolder , fileNames . getDriverHttpEndpoint ( ) ) ; BufferedWriter out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( driverHttpEndpointFile ) , StandardCharsets . UTF_8 ) ) ; out . write ( applicationId + "\n" ) ; out . write ( trackingUri + "\n" ) ; String addr = yarnConfiguration . get ( "yarn.resourcemanager.webapp.address" ) ; if ( null == addr || addr . startsWith ( "0.0.0.0" ) ) { String str2 = yarnConfiguration . get ( "yarn.resourcemanager.ha.rm-ids" ) ; if ( null != str2 ) { for ( String rm : str2 . split ( "," ) ) { out . write ( yarnConfiguration . get ( "yarn.resourcemanager.webapp.address." + rm ) + "\n" ) ; } } } else { out . write ( addr + "\n" ) ; } out . close ( ) ; }
We leave a file behind in job submission directory so that clr client can figure out the applicationId and yarn rest endpoint .
2,272
public void start ( final VortexThreadPool vortexThreadPool ) { final Vector < Integer > inputVector = new Vector < > ( ) ; for ( int i = 0 ; i < dimension ; i ++ ) { inputVector . add ( i ) ; } final List < VortexFuture < Integer > > futures = new ArrayList < > ( ) ; final AddOneFunction addOneFunction = new AddOneFunction ( ) ; for ( final int i : inputVector ) { futures . add ( vortexThreadPool . submit ( addOneFunction , i ) ) ; } final Vector < Integer > outputVector = new Vector < > ( ) ; for ( final VortexFuture < Integer > future : futures ) { try { outputVector . add ( future . get ( ) ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ) ; } } System . out . println ( "RESULT:" ) ; System . out . println ( outputVector ) ; }
Perform a simple vector calculation on Vortex .
2,273
public static int getTotalPhysicalMemorySizeInMB ( ) { int memorySizeInMB ; try { long memorySizeInBytes = ( ( com . sun . management . OperatingSystemMXBean ) ManagementFactory . getOperatingSystemMXBean ( ) ) . getTotalPhysicalMemorySize ( ) ; memorySizeInMB = ( int ) ( memorySizeInBytes / BYTES_IN_MEGABYTE ) ; } catch ( Exception e ) { memorySizeInMB = - 1 ; } return memorySizeInMB ; }
Returns the total amount of physical memory on the current machine in megabytes .
2,274
public void submitContextAndTaskString ( final String evaluatorConfigurationString , final String contextConfigurationString , final String taskConfigurationString ) { final DateFormat dateFormat = new SimpleDateFormat ( "yyyy/MM/dd HH:mm:ss" ) ; LOG . log ( Level . FINE , "AllocatedEvaluatorBridge:submitContextAndTaskString for evaluator id: {0}, time: {1}." , new Object [ ] { evaluatorId , dateFormat . format ( new Date ( ) ) } ) ; if ( evaluatorConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty evaluatorConfigurationString provided." ) ; } if ( contextConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty contextConfigurationString provided." ) ; } if ( taskConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty taskConfigurationString provided." ) ; } ( ( AllocatedEvaluatorImpl ) jallocatedEvaluator ) . submitContextAndTask ( evaluatorConfigurationString , contextConfigurationString , taskConfigurationString ) ; }
Bridge function for REEF . NET to submit context and task configurations for the allocated evaluator .
2,275
public void submitContextString ( final String evaluatorConfigurationString , final String contextConfigurationString ) { if ( evaluatorConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty evaluatorConfigurationString provided." ) ; } if ( contextConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty contextConfigurationString provided." ) ; } ( ( AllocatedEvaluatorImpl ) jallocatedEvaluator ) . submitContext ( evaluatorConfigurationString , contextConfigurationString ) ; }
Bridge function for REEF . NET to submit context configuration for the allocated evaluator .
2,276
public void submitContextAndServiceString ( final String evaluatorConfigurationString , final String contextConfigurationString , final String serviceConfigurationString ) { if ( evaluatorConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty evaluatorConfigurationString provided." ) ; } if ( contextConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty contextConfigurationString provided." ) ; } if ( serviceConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty serviceConfigurationString provided." ) ; } ( ( AllocatedEvaluatorImpl ) jallocatedEvaluator ) . submitContextAndService ( evaluatorConfigurationString , contextConfigurationString , serviceConfigurationString ) ; }
Bridge function for REEF . NET to submit context and service configurations for the allocated evaluator .
2,277
public void submitContextAndServiceAndTaskString ( final String evaluatorConfigurationString , final String contextConfigurationString , final String serviceConfigurationString , final String taskConfigurationString ) { if ( evaluatorConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty evaluatorConfigurationString provided." ) ; } if ( contextConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty contextConfigurationString provided." ) ; } if ( serviceConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty serviceConfigurationString provided." ) ; } if ( taskConfigurationString . isEmpty ( ) ) { throw new RuntimeException ( "empty taskConfigurationString provided." ) ; } ( ( AllocatedEvaluatorImpl ) jallocatedEvaluator ) . submitContextAndServiceAndTask ( evaluatorConfigurationString , contextConfigurationString , serviceConfigurationString , taskConfigurationString ) ; }
Bridge function for REEF . NET to submit context service . and task configurations for the allocated evaluator .
2,278
public String getEvaluatorDescriptorString ( ) { final String descriptorString = Utilities . getEvaluatorDescriptorString ( jallocatedEvaluator . getEvaluatorDescriptor ( ) ) ; LOG . log ( Level . INFO , "allocated evaluator - serialized evaluator descriptor: " + descriptorString ) ; return descriptorString ; }
Gets the serialized evaluator descriptor from the Java allocated evaluator .
2,279
public static String getGraphvizString ( final InjectionPlan < ? > injectionPlan , final boolean showLegend ) { final GraphvizInjectionPlanVisitor visitor = new GraphvizInjectionPlanVisitor ( showLegend ) ; Walk . preorder ( visitor , visitor , injectionPlan ) ; return visitor . toString ( ) ; }
Produce a Graphviz DOT string for a given TANG injection plan .
2,280
public boolean visit ( final Constructor < ? > node ) { this . graphStr . append ( " \"" ) . append ( node . getClass ( ) ) . append ( '_' ) . append ( node . getNode ( ) . getName ( ) ) . append ( "\" [label=\"" ) . append ( node . getNode ( ) . getName ( ) ) . append ( "\", shape=box];\n" ) ; return true ; }
Process current injection plan node of Constructor type .
2,281
public boolean visit ( final JavaInstance < ? > node ) { this . graphStr . append ( " \"" ) . append ( node . getClass ( ) ) . append ( '_' ) . append ( node . getNode ( ) . getName ( ) ) . append ( "\" [label=\"" ) . append ( node . getNode ( ) . getName ( ) ) . append ( " = " ) . append ( node . getInstanceAsString ( ) ) . append ( "\", shape=box, style=bold];\n" ) ; return true ; }
Process current injection plan node of JavaInstance type .
2,282
public boolean visit ( final InjectionPlan < ? > nodeFrom , final InjectionPlan < ? > nodeTo ) { this . graphStr . append ( " \"" ) . append ( nodeFrom . getClass ( ) ) . append ( '_' ) . append ( nodeFrom . getNode ( ) . getName ( ) ) . append ( "\" -> \"" ) . append ( nodeTo . getClass ( ) ) . append ( '_' ) . append ( nodeTo . getNode ( ) . getName ( ) ) . append ( "\" [style=solid];\n" ) ; return true ; }
Process current edge of the injection plan .
2,283
public static void main ( final String [ ] args ) { LOG . log ( Level . INFO , "Entering Launch at :::" + new Date ( ) ) ; try { if ( args == null || args . length == 0 ) { throw new IllegalArgumentException ( "No arguments provided, at least a clrFolder should be supplied." ) ; } final File dotNetFolder = new File ( args [ 0 ] ) . getAbsoluteFile ( ) ; final String [ ] removedArgs = Arrays . copyOfRange ( args , 1 , args . length ) ; final Configuration config = getClientConfiguration ( removedArgs ) ; final Injector commandLineInjector = Tang . Factory . getTang ( ) . newInjector ( parseCommandLine ( removedArgs ) ) ; final int waitTime = commandLineInjector . getNamedInstance ( WaitTimeForDriver . class ) ; final int driverMemory = commandLineInjector . getNamedInstance ( DriverMemoryInMb . class ) ; final boolean isLocal = commandLineInjector . getNamedInstance ( Local . class ) ; final String driverIdentifier = commandLineInjector . getNamedInstance ( DriverIdentifier . class ) ; final String jobSubmissionDirectory = commandLineInjector . getNamedInstance ( DriverJobSubmissionDirectory . class ) ; final boolean submit = commandLineInjector . getNamedInstance ( Submit . class ) ; final Injector injector = Tang . Factory . getTang ( ) . newInjector ( config ) ; final JobClient client = injector . getInstance ( JobClient . class ) ; client . setDriverInfo ( driverIdentifier , driverMemory , jobSubmissionDirectory ) ; if ( submit ) { client . submit ( dotNetFolder , true , isLocal , null ) ; client . waitForCompletion ( waitTime ) ; } else { client . submit ( dotNetFolder , false , isLocal , config ) ; client . waitForCompletion ( 0 ) ; } LOG . info ( "Done!" ) ; } catch ( final BindException | InjectionException | IOException ex ) { LOG . log ( Level . SEVERE , "Job configuration error" , ex ) ; } }
Main method that starts the CLR Bridge from Java .
2,284
public static String getIdentifier ( final Configuration c ) { try { return Tang . Factory . getTang ( ) . newInjector ( c ) . getNamedInstance ( ContextIdentifier . class ) ; } catch ( final InjectionException e ) { throw new RuntimeException ( "Unable to determine context identifier. Giving up." , e ) ; } }
Extracts a context id from the given configuration .
2,285
private void log ( final String message ) { if ( this . optionalParams . isPresent ( ) ) { logger . log ( logLevel , message , params ) ; } else { logger . log ( logLevel , message ) ; } }
Log message .
2,286
String getWhereTaskletWasScheduledTo ( final int taskletId ) { for ( final Map . Entry < String , VortexWorkerManager > entry : runningWorkers . entrySet ( ) ) { final String workerId = entry . getKey ( ) ; final VortexWorkerManager vortexWorkerManager = entry . getValue ( ) ; if ( vortexWorkerManager . containsTasklet ( taskletId ) ) { return workerId ; } } return null ; }
Find where a tasklet is scheduled to .
2,287
public static void logThreads ( final Logger logger , final Level level , final String prefix , final String threadPrefix , final String stackElementPrefix ) { if ( logger . isLoggable ( level ) ) { logger . log ( level , getFormattedThreadList ( prefix , threadPrefix , stackElementPrefix ) ) ; } }
Logs the currently active threads and their stack trace to the given Logger and Level .
2,288
public static String getFormattedThreadList ( final String prefix , final String threadPrefix , final String stackElementPrefix ) { final TreeMap < String , StackTraceElement [ ] > threadNames = new TreeMap < > ( ) ; for ( final Map . Entry < Thread , StackTraceElement [ ] > entry : Thread . getAllStackTraces ( ) . entrySet ( ) ) { final Thread t = entry . getKey ( ) ; final String tg = t . getThreadGroup ( ) == null ? null : t . getThreadGroup ( ) . getName ( ) ; if ( ! "system" . equals ( tg ) ) { threadNames . put ( String . format ( "TG %s THREAD %s :: %s, %s, %s, %s" , tg , t . getName ( ) , t . getState ( ) , t . isAlive ( ) ? "Alive" : "NOT alive" , t . isInterrupted ( ) ? "Interrupted" : "NOT interrupted" , t . isDaemon ( ) ? "Daemon" : "NOT daemon" ) , entry . getValue ( ) ) ; } } final StringBuilder message = new StringBuilder ( prefix ) ; for ( final Map . Entry < String , StackTraceElement [ ] > entry : threadNames . entrySet ( ) ) { message . append ( threadPrefix ) . append ( entry . getKey ( ) ) ; for ( final StackTraceElement element : entry . getValue ( ) ) { message . append ( stackElementPrefix ) . append ( element ) ; } } return message . toString ( ) ; }
Produces a String representation of the currently running threads .
2,289
public static String getFormattedDeadlockInfo ( final String prefix , final String threadPrefix , final String stackElementPrefix ) { final StringBuilder message = new StringBuilder ( prefix ) ; final DeadlockInfo deadlockInfo = new DeadlockInfo ( ) ; final ThreadInfo [ ] deadlockedThreads = deadlockInfo . getDeadlockedThreads ( ) ; if ( 0 == deadlockedThreads . length ) { message . append ( " none " ) ; return message . toString ( ) ; } for ( final ThreadInfo threadInfo : deadlockedThreads ) { message . append ( threadPrefix ) . append ( "Thread '" ) . append ( threadInfo . getThreadName ( ) ) . append ( "' with state " ) . append ( threadInfo . getThreadState ( ) ) ; boolean firstElement = true ; for ( final StackTraceElement stackTraceElement : threadInfo . getStackTrace ( ) ) { message . append ( stackElementPrefix ) . append ( "at " ) . append ( stackTraceElement ) ; if ( firstElement ) { final String waitingLockString = deadlockInfo . getWaitingLockString ( threadInfo ) ; if ( waitingLockString != null ) { message . append ( stackElementPrefix ) . append ( "- waiting to lock: " ) . append ( waitingLockString ) ; } firstElement = false ; } for ( final MonitorInfo info : deadlockInfo . getMonitorLockedElements ( threadInfo , stackTraceElement ) ) { message . append ( stackElementPrefix ) . append ( "- locked: " ) . append ( info ) ; } } for ( final LockInfo lockInfo : threadInfo . getLockedSynchronizers ( ) ) { message . append ( stackElementPrefix ) . append ( "* holds locked synchronizer: " ) . append ( lockInfo ) ; } } return message . toString ( ) ; }
Produces a String representation of threads that are deadlocked including lock information .
2,290
void parseOneFile ( final Path inputPath , final Writer outputWriter ) throws IOException { try ( final TFile . Reader . Scanner scanner = this . getScanner ( inputPath ) ) { while ( ! scanner . atEnd ( ) ) { new LogFileEntry ( scanner . entry ( ) ) . write ( outputWriter ) ; scanner . advance ( ) ; } } }
Parses the given file and writes its contents into the outputWriter for all logs in it .
2,291
void parseOneFile ( final Path inputPath , final File outputFolder ) throws IOException { try ( final TFile . Reader . Scanner scanner = this . getScanner ( inputPath ) ) { while ( ! scanner . atEnd ( ) ) { new LogFileEntry ( scanner . entry ( ) ) . write ( outputFolder ) ; scanner . advance ( ) ; } } }
Parses the given file and stores the logs for each container in a file named after the container in the given . outputFolder
2,292
public byte [ ] encode ( final NSMessage < T > obj ) { if ( isStreamingCodec ) { final StreamingCodec < T > streamingCodec = ( StreamingCodec < T > ) codec ; try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ) { try ( DataOutputStream daos = new DataOutputStream ( baos ) ) { daos . writeUTF ( obj . getSrcId ( ) . toString ( ) ) ; daos . writeUTF ( obj . getDestId ( ) . toString ( ) ) ; daos . writeInt ( obj . getData ( ) . size ( ) ) ; for ( final T rec : obj . getData ( ) ) { streamingCodec . encodeToStream ( rec , daos ) ; } } return baos . toByteArray ( ) ; } catch ( final IOException e ) { throw new RuntimeException ( "IOException" , e ) ; } } else { final NSMessagePBuf . Builder pbuf = NSMessagePBuf . newBuilder ( ) ; pbuf . setSrcid ( obj . getSrcId ( ) . toString ( ) ) ; pbuf . setDestid ( obj . getDestId ( ) . toString ( ) ) ; for ( final T rec : obj . getData ( ) ) { final NSRecordPBuf . Builder rbuf = NSRecordPBuf . newBuilder ( ) ; rbuf . setData ( ByteString . copyFrom ( codec . encode ( rec ) ) ) ; pbuf . addMsgs ( rbuf ) ; } return pbuf . build ( ) . toByteArray ( ) ; } }
Encodes a network service message to bytes .
2,293
public NSMessage < T > decode ( final byte [ ] buf ) { if ( isStreamingCodec ) { final StreamingCodec < T > streamingCodec = ( StreamingCodec < T > ) codec ; try ( ByteArrayInputStream bais = new ByteArrayInputStream ( buf ) ) { try ( DataInputStream dais = new DataInputStream ( bais ) ) { final Identifier srcId = factory . getNewInstance ( dais . readUTF ( ) ) ; final Identifier destId = factory . getNewInstance ( dais . readUTF ( ) ) ; final int size = dais . readInt ( ) ; final List < T > list = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { list . add ( streamingCodec . decodeFromStream ( dais ) ) ; } return new NSMessage < > ( srcId , destId , list ) ; } } catch ( final IOException e ) { throw new RuntimeException ( "IOException" , e ) ; } } else { final NSMessagePBuf pbuf ; try { pbuf = NSMessagePBuf . parseFrom ( buf ) ; } catch ( final InvalidProtocolBufferException e ) { e . printStackTrace ( ) ; throw new NetworkRuntimeException ( e ) ; } final List < T > list = new ArrayList < > ( ) ; for ( final NSRecordPBuf rbuf : pbuf . getMsgsList ( ) ) { list . add ( codec . decode ( rbuf . getData ( ) . toByteArray ( ) ) ) ; } return new NSMessage < > ( factory . getNewInstance ( pbuf . getSrcid ( ) ) , factory . getNewInstance ( pbuf . getDestid ( ) ) , list ) ; } }
Decodes a network service message from bytes .
2,294
@ SuppressWarnings ( "checkstyle:illegalcatch" ) public void beforeTaskStart ( ) throws TaskStartHandlerFailure { LOG . log ( Level . FINEST , "Sending TaskStart event to the registered event handlers." ) ; for ( final EventHandler < TaskStart > startHandler : this . taskStartHandlers ) { try { startHandler . onNext ( this . taskStart ) ; } catch ( final Throwable throwable ) { throw new TaskStartHandlerFailure ( startHandler , throwable ) ; } } LOG . log ( Level . FINEST , "Done sending TaskStart event to the registered event handlers." ) ; }
Sends the TaskStart event to the handlers for it .
2,295
@ SuppressWarnings ( "checkstyle:illegalcatch" ) public void afterTaskExit ( ) throws TaskStopHandlerFailure { LOG . log ( Level . FINEST , "Sending TaskStop event to the registered event handlers." ) ; for ( final EventHandler < TaskStop > stopHandler : this . taskStopHandlers ) { try { stopHandler . onNext ( this . taskStop ) ; } catch ( final Throwable throwable ) { throw new TaskStopHandlerFailure ( stopHandler , throwable ) ; } } LOG . log ( Level . FINEST , "Done sending TaskStop event to the registered event handlers." ) ; }
Sends the TaskStop event to the handlers for it .
2,296
public void write ( final T message ) { LOG . log ( Level . FINEST , "write {0} :: {1}" , new Object [ ] { channel , message } ) ; final ChannelFuture future = channel . writeAndFlush ( Unpooled . wrappedBuffer ( encoder . encode ( message ) ) ) ; if ( listener != null ) { future . addListener ( new NettyChannelFutureListener < > ( message , listener ) ) ; } }
Writes the message to this link .
2,297
private static Configuration readConfigurationFromDisk ( final String configPath , final ConfigurationSerializer serializer ) { LOG . log ( Level . FINER , "Loading configuration file: {0}" , configPath ) ; final File evaluatorConfigFile = new File ( configPath ) ; if ( ! evaluatorConfigFile . exists ( ) ) { throw fatal ( "Configuration file " + configPath + " does not exist. Can be an issue in job submission." , new FileNotFoundException ( configPath ) ) ; } if ( ! evaluatorConfigFile . canRead ( ) ) { throw fatal ( "Configuration file " + configPath + " exists, but can't be read." , new IOException ( configPath ) ) ; } try { final Configuration config = serializer . fromFile ( evaluatorConfigFile ) ; LOG . log ( Level . FINEST , "Configuration file loaded: {0}" , configPath ) ; return config ; } catch ( final IOException e ) { throw fatal ( "Unable to parse the configuration file: " + configPath , e ) ; } }
Read configuration from a given file and deserialize it into Tang configuration object that can be used for injection . Configuration is currently serialized using Avro . This method also prints full deserialized configuration into log .
2,298
synchronized ResourceRequestEvent satisfyOne ( ) { final ResourceRequest req = this . requestQueue . element ( ) ; req . satisfyOne ( ) ; if ( req . isSatisfied ( ) ) { this . requestQueue . poll ( ) ; } return req . getRequestProto ( ) ; }
Satisfies one resource for the front - most request . If that satisfies the request it is removed from the queue .
2,299
public void serialize ( final ByteArrayOutputStream outputStream , final SpecificRecord message , final long sequence ) throws IOException { final BinaryEncoder encoder = EncoderFactory . get ( ) . binaryEncoder ( outputStream , null ) ; headerWriter . write ( new Header ( sequence , msgMetaClassName ) , encoder ) ; messageWriter . write ( ( TMessage ) message , encoder ) ; encoder . flush ( ) ; }
Deserialize messages of type TMessage from input outputStream .