com.novell.zos.jdl
Class Exec

java.lang.Object
  extended by com.novell.zos.jdl.Exec

public class Exec
extends java.lang.Object

The Exec class is used to manage command line execution on resources. This class defines options for input, output and error stream handling, and process management including signaling, error and timeout control.

A command's standard output and error can be redirected to a file, to a stream, to write to the job log, or be discarded. By default, the output is discarded. A command's standard input can be directed from a file or a stream can be written to. By default, the input is not used.

By default, command line execution is done in behalf of the job user. Exec instances are only allowed during the running of the Joblet class on a resource. The built-in function system() can also be used for simple execution of command lines.

Example of command line invocation that writes the command's standard output and standard error to files and then reads in the standard output file if the command executed without errors:

      e = Exec()
      e.setCommand("ps -aef")
      e.setStdoutFile("/tmp/ps.out")
      e.setStderrFile("/tmp/ps.err")
      result = e.execute()
      if result == 0:
          output = open("/tmp/ps.out").read()
          print output

 

Example of a command line invocation that writes the command's standard output and standard error to the job log:

      e = Exec()
      e.setCommand("ls -la /tmp")
      e.writeStdoutToLog()
      e.writeStderrToLog()
      e.execute()
 


Field Summary
static int PROCESS_HAS_NOT_BEEN_CREATED
           
static int PROCESS_HAS_NOT_EXITED
           
static int PROCESS_TIMED_OUT
           
 
Constructor Summary
Exec()
          Construct Exec instance to run an executable
 
Method Summary
 void addEnv(java.lang.String name, java.lang.String value)
          Add an environment variable to the set of environment variables.
 void close()
          Flush and close all input and output streams
 void detach()
          Detach a process from resource.
 int execute()
          Run command.
 org.python.core.PyObject execute1()
          Run command and immediately return a stream object for standard input.
 org.python.core.PyTuple execute2()
          Run command and immediately return a tuple of stream objects for standard input and standard output.
 org.python.core.PyTuple execute3()
          Run command and immediately return a tuple of three stream objects for standard input,standard output and standard error.
 org.python.core.PyTuple execute4()
          Run command and immediately return a tuple of stream objects for standard input and one combined of standard output and standard error.
 int getExitStatus()
          Retrieve exit status of executable without blocking.
 boolean isRunning()
          Returns True if the process is still running.
 boolean isTimeout()
          Check if the process reached the timeout limit defined by setTimeout().
 void kill()
          Kill the process.
 void setAsync(boolean value)
          Whether the execute() call will continue asynchronously.
 void setCommand(java.lang.String cmd)
          Define a system command to execute.
 void setCommand(java.lang.String[] args)
          Define a system command line to execute using a list of strings.
 void setDebug(boolean debug)
          Show extra debugging information when trying to execute
 void setDir(java.lang.String dir)
          Set the working directory of the process.
 void setKillOnExit(boolean killonexit)
          Whether the process will be killed when the Joblet ends.
 void setShellCommand(java.lang.String cmd)
          Define a shell command to execute.
 void setSoftTimeout(int value)
          Set a soft timeout in seconds after which the process will be sent the SIGUSR1 signal.
 void setStderrFile(java.lang.String filename)
          File that standard error output is directed to.
 void setStdinFile(java.lang.String filename)
          File that standard Input is directed from.
 void setStdoutFile(java.lang.String filename)
          File that standard output is directed to.
 void setTimeout(int value)
          Set a timeout in seconds after which the process will be killed.
 void setUseJvmRuntimeExec(boolean useJvmRuntimeExec)
           
 void setUserEnv(boolean userenv)
          Set execution to inherit the user's environment variables.
 void signal(int sig)
          Send a signal to the process using a signal number.
 void signal(java.lang.String sigName)
          Send a signal to the process using a symbolic name.
 void signalProcessGroup(int sig)
          Send a signal to a process and its subprocesses.
 void signalProcessGroup(java.lang.String sigName)
          Send a signal to a process and its subprocesses.
 void stop()
          Stop the process.
 java.lang.String toString()
           
 void validate()
          Validate setup.
 int waitFor()
          Wait for the process to finish running or terminate and return the exit status.
 void writeStderrToLog()
          Write standard error output to the job log
 void writeStdoutToLog()
          Write the standard output to the job log
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

PROCESS_HAS_NOT_EXITED

public static final int PROCESS_HAS_NOT_EXITED
See Also:
Constant Field Values

PROCESS_HAS_NOT_BEEN_CREATED

public static final int PROCESS_HAS_NOT_BEEN_CREATED
See Also:
Constant Field Values

PROCESS_TIMED_OUT

public static final int PROCESS_TIMED_OUT
See Also:
Constant Field Values
Constructor Detail

Exec

public Exec()
Construct Exec instance to run an executable

Method Detail

waitFor

public int waitFor()
Wait for the process to finish running or terminate and return the exit status.

Block and wait for the process to finish executing or to terminate. If the process terminates abnormally, an exception is thrown to indicate the cause of termination, or the error.

Returns:
Exit status code of process, or Exec.PROCESS_TIMED_OUT
Throws:
ExecError - Thrown upon abnormal termination or errors.

kill

public void kill()
Kill the process.

Attempt to stop the process using the forceful system termination signal. This signal cannot be caught or ignored, so unless an error occurs the process will terminate. This has no effect if process is not running.

Throws:
ExecError - Thrown if it is not possible to send the kill signal.

stop

public void stop()
Stop the process.

Attempt to stop the process using the default system termination signal. The process is able to catch and/or ignore this signal, so it is not guaranteed to stop. This has no effect if process is not running.

Throws:
ExecError - Thrown if it is not possible to send the stop signal.

signal

public void signal(int sig)
Send a signal to the process using a signal number.

Parameters:
sig - the signal number, e.g. 1 for SIGHUP, 12 for SIGUSR2
Throws:
ExecError - Thrown if it is not possible to send the signal.

signal

public void signal(java.lang.String sigName)
Send a signal to the process using a symbolic name. The symbol can be case insensitive.

Parameters:
sigName - the symbolic signal name, e.g. "SIGHUP" or "sigusr2"
Throws:
ExecError - Thrown if it is not possible to send the signal.

signalProcessGroup

public void signalProcessGroup(int sig)
Send a signal to a process and its subprocesses.

Attempt to signal all processes in this process's process group. This command is only available on POSIX systems. Process groups don't exist under Win32.

For the common cases of stopping or killing a process it is better to use the system-independe stop() or kill() methods.

Parameters:
sig - The signal to send to the process
Throws:
ExecError - Thrown if it is not possible to send the signal.

signalProcessGroup

public void signalProcessGroup(java.lang.String sigName)
Send a signal to a process and its subprocesses.

Attempt to signal all processes in this process's process group. This command is only available on POSIX systems. Process groups don't exist under Win32.

For the common cases of stopping or killing a process it is better to use the system-independe stop() or kill() methods.

Parameters:
sigName - The signal to send to the process
Throws:
ExecError - Thrown if it is not possible to send the signal.

detach

public void detach()
Detach a process from resource.

Used when a Joblet starts a process it wants to leave running. If the process has pipes open, then the pipes are closed. The process is not explicitly killed, and may continue to run in the background.

Once the process is detached, it is no longer possible to obtain the exit status or to await completion, so this method should only be called when there is no longer any interest in the final result of a command.


setTimeout

public void setTimeout(int value)
Set a timeout in seconds after which the process will be killed.

isTimeout() will return True if a prcoess is terminated due to exceeding this timeout limit. The timer starts after execute() has been called and the underlying process has started.

Parameters:
value - Seconds to wait before terminating the process

setSoftTimeout

public void setSoftTimeout(int value)
Set a soft timeout in seconds after which the process will be sent the SIGUSR1 signal. This setting is used in conjuction with setTimeout(). The soft timeout must be less than the setting for setTimeout().

Parameters:
value - Seconds to wait before sending the SIGUSR1 signal

setDir

public void setDir(java.lang.String dir)
Set the working directory of the process.

Parameters:
dir - Path of working directory
Throws:
java.lang.Exception - for invalid directory

setShellCommand

public void setShellCommand(java.lang.String cmd)
Define a shell command to execute.

The command is passed to the operating system's default command interpreter. On Microsoft Windows systems this will be cmd.exe, while on POSIX systems, this will be /bin/sh.

Due to the way MS Windows processes command invocation, the "shell" type constructors are the preferred way to invoke commands on Windows, since a known valid Windows command line will just be passed verbatim to cmd.exe without any error-prone command line parsing and reassembly.

Parameters:
cmd - The command line to pass to the system command interpreter.

setCommand

public void setCommand(java.lang.String cmd)
Define a system command to execute.

The system command will be invoked directly, and not using the system command interpreter.

Parameters:
cmd - The system command line to invoke

setCommand

public void setCommand(java.lang.String[] args)
Define a system command line to execute using a list of strings. This avoids possible errors with trying to parse command lines.

Parameters:
args - list of strings to form a command line

setStdoutFile

public void setStdoutFile(java.lang.String filename)
File that standard output is directed to. Both stdout and stderr will be combined if the same filename is also set with setStderrOutput().

Parameters:
filename - Filename of file to write to

setStderrFile

public void setStderrFile(java.lang.String filename)
File that standard error output is directed to. Both stdout and stderr will be combined if the same filename is also set with setStdoutOutput().

Parameters:
filename - Filename of file to write to

setStdinFile

public void setStdinFile(java.lang.String filename)
File that standard Input is directed from.

Parameters:
filename - Filename of file to read from

writeStdoutToLog

public void writeStdoutToLog()
Write the standard output to the job log


writeStderrToLog

public void writeStderrToLog()
Write standard error output to the job log


addEnv

public void addEnv(java.lang.String name,
                   java.lang.String value)
Add an environment variable to the set of environment variables. Will overwrite an existing value.

Parameters:
name - Name of environment variable
value - Value of environment variable

setDebug

public void setDebug(boolean debug)
Show extra debugging information when trying to execute

Parameters:
debug - true to write more information to log. default is false.

validate

public void validate()
Validate setup. Called by public execute()'s


setUseJvmRuntimeExec

public void setUseJvmRuntimeExec(boolean useJvmRuntimeExec)

execute

public int execute()
Run command. This blocks until command has completed, or an error or timeout has occurred.

Returns:
exit status value from command execution
Throws:
ExecError - if command is not correctly setup or cannot be executed

execute1

public org.python.core.PyObject execute1()
Run command and immediately return a stream object for standard input.

Example to write a line of text to standard input:

  e = Exec()
  e.setCommand("mycommand")
  input = e.execute1()
  input.write("input data")
  e.waitFor()
 

Returns:
input stream object representing standard input
Throws:
ExecError - if command is not correctly setup or cannot be executed

execute2

public org.python.core.PyTuple execute2()
Run command and immediately return a tuple of stream objects for standard input and standard output. If standard error output is not redirected to a file using setStderrFile() or to the job log, it is discarded. The returned standard output stream will block on read, so use the ready() method to determine if the stream has data available.

Example to read the stdout stream and write the contents to the job log:

  e = Exec()
  e.setShellCommand("help")
  input,output = e.execute2()
  while e.isRunning():
       while output.ready():
           c = output.read()
           sys.stdout.write(c)
 

Returns:
Tuple containing two stream objects representing stdin and stdout of the process
Throws:
ExecError - if command is not correctly setup or cannot be executed

execute3

public org.python.core.PyTuple execute3()
Run command and immediately return a tuple of three stream objects for standard input,standard output and standard error. The returned stdout and stderr streams will block on read, so use the ready() method to determine if the stream has data available.

Returns:
Tuple containing three stream objects representing stdin, stdout, stderr of the process
Throws:
ExecError - if command is not correctly setup or cannot be executed

execute4

public org.python.core.PyTuple execute4()
Run command and immediately return a tuple of stream objects for standard input and one combined of standard output and standard error. The returned stdout and stderr stream will block on read, so use the ready() method to determine if the stream has data available.

Example to read the combined stdout and stderr stream and write the contents to the job log:

  e = Exec()
  e.setShellCommand("help")
  input,output = e.execute4()
  while e.getExitStatus() < 0:
       while output.ready():
           c = output.read()
           sys.stdout.write(c)
 

Returns:
Tuple containing two stream objects. The first repesenting stdin and the second a combined stdout and stderr stream of the process
Throws:
ExecError - if command is not correctly setup or cannot be executed

isTimeout

public boolean isTimeout()
Check if the process reached the timeout limit defined by setTimeout().

Example of checking whether a process has reached the timeout limit:

      class MyJob(Job):
          def job_started_event(self):
              self.schedule(MyJoblet)

      class MyJoblet(Joblet):
          def joblet_started_event(self):
              e = Exec()
              e.setCommand("sleep 62")
              # put a 60 second timeout on this
              e.setTimeout(60)
              e.execute()
              if e.isTimeout():
                  print "Command took more than 60 seconds"
 

Returns:
Returns True if process ended due to reaching the timeout limit

isRunning

public boolean isRunning()
Returns True if the process is still running.

Returns True if the process has not yet exited or terminated abnormally. If the process is killed using one of the termination methods like kill(), this method will continue to return True until the termination is confirmed by the execution manager.

Returns:
Returns True if the process is still running.

getExitStatus

public int getExitStatus()
Retrieve exit status of executable without blocking. If process has not completed or not started, or timed out, then the possible values are Exec.PROCESS_HAS_NOT_EXITED, Exec.PROCESS_HAS_NOT_BEEN_CREATED, and Exec.PROCESS_TIMED_OUT.

Returns:
Exit status from executable, or one of the above constants if the process has not completed or timed out.
Throws:
ExecError - if process was not started

close

public void close()
Flush and close all input and output streams


setUserEnv

public void setUserEnv(boolean userenv)
Set execution to inherit the user's environment variables. Requires environment variables to be retrieved at job execution. The user environment variables come down with the Joblet instance. Default is False.

Parameters:
userenv - True to set user environment variables

setAsync

public void setAsync(boolean value)
Whether the execute() call will continue asynchronously. The default is for execute() to wait until the process has completed. execute1(), execute2(), execute3(), and execute4() run asynchronously.

Parameters:
value - true for execute() to run asynchronously.

setKillOnExit

public void setKillOnExit(boolean killonexit)
Whether the process will be killed when the Joblet ends. Default is to always kill any remaining running processes.

Parameters:
killonexit - true to cleanup any remaining running process. false to leave the process running

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object


Copyright (c) 2010 Novell, Inc. All rights reserved.