Ejemplo n.º 1
0
def _call(command, logoutput=False, throw_on_failure=True, 
         cwd=None, env=None, preexec_fn=None, user=None, wait_for_finish=True, timeout=None, pid_file_name=None):
  """
  Execute shell command
  
  @param command: list/tuple of arguments (recommended as more safe - don't need to escape) 
  or string of the command to execute
  @param logoutput: boolean, whether command output should be logged of not
  @param throw_on_failure: if true, when return code is not zero exception is thrown
  
  @return: retrun_code, stdout
  """
  # convert to string and escape
  if isinstance(command, (list, tuple)):
    command = ' '.join(quote_bash_args(x) for x in command)

  """
  Do not su to the supplied user (need to differentiate between when to call su and when not to)
  if user:
    command = ["su", "-", user, "-c", command]
  else:
    command = ["/bin/bash","--login","-c", command]
  """
  command = ["/bin/bash","--login","-c", command]
  proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                          cwd=cwd, env=env, shell=False,
                          preexec_fn=preexec_fn)

  if not wait_for_finish:
    if pid_file_name:
      pidfile = open(pid_file_name, 'w')
      pidfile.write(str(proc.pid))
      pidfile.close()
    return None, None
  
  if timeout:
    q = Queue()
    t = threading.Timer( timeout, on_timeout, [proc, q] )
    t.start()
    
  out = proc.communicate()[0].strip('\n')
  
  if timeout:
    if q.empty():
      t.cancel()
    # timeout occurred
    else:
      raise ExecuteTimeoutException()
   
  code = proc.returncode
  
  if logoutput and out:
    Logger.info(out)
  
  if throw_on_failure and code:
    err_msg = Logger.get_protected_text(("Execution of '%s' returned %d. %s") % (command[-1], code, out))
    raise Fail(err_msg)
  
  return code, out
Ejemplo n.º 2
0
def _call(command, logoutput=False, throw_on_failure=True, 
         cwd=None, env=None, preexec_fn=None, user=None, wait_for_finish=True, timeout=None):
  """
  Execute shell command
  
  @param command: list/tuple of arguments (recommended as more safe - don't need to escape) 
  or string of the command to execute
  @param logoutput: boolean, whether command output should be logged of not
  @param throw_on_failure: if true, when return code is not zero exception is thrown
  
  @return: retrun_code, stdout
  """
  # convert to string and escape
  if isinstance(command, (list, tuple)):
    command = ' '.join(quote_bash_args(x) for x in command)

  if user:
    command = ["su", "-", user, "-c", command]
  else:
    command = ["/bin/bash","--login","-c", command]

  proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                          cwd=cwd, env=env, shell=False,
                          preexec_fn=preexec_fn)

  if not wait_for_finish:
    return None, None
  
  if timeout:
    q = Queue()
    t = threading.Timer( timeout, on_timeout, [proc, q] )
    t.start()
    
  out = proc.communicate()[0].strip('\n')
  
  if timeout:
    if q.empty():
      t.cancel()
    # timeout occurred
    else:
      raise ExecuteTimeoutException()
   
  code = proc.returncode
  
  if logoutput and out:
    Logger.info(out)
  
  if throw_on_failure and code:
    err_msg = Logger.get_protected_text(("Execution of '%s' returned %d. %s") % (command[-1], code, out))
    raise Fail(err_msg)
  
  return code, out
Ejemplo n.º 3
0
def _call(command, logoutput=False, throw_on_failure=True, 
         cwd=None, env=None, preexec_fn=None, user=None, wait_for_finish=True, timeout=None, pid_file_name=None, poll_after=None):
  """
  Execute shell command
  
  @param command: list/tuple of arguments (recommended as more safe - don't need to escape) 
  or string of the command to execute
  @param logoutput: boolean, whether command output should be logged of not
  @param throw_on_failure: if true, when return code is not zero exception is thrown
  
  @return: retrun_code, stdout
  """
  # convert to string and escape
  if isinstance(command, (list, tuple)):
    command = ' '.join(quote_bash_args(x) for x in command)

  """
  Do not su to the supplied user (need to differentiate between when to call su and when not to)
  if user:
    command = ["su", "-", user, "-c", command]
  else:
    command = ["/bin/bash","--login","-c", command]
  """
  command = ["/bin/bash","--login","-c", command]
  #adding redirecting stdout stderr to file
  outfilename = APPLICATION_STD_OUTPUT_LOG_FILE_PREFIX + APPLICATION_STD_OUTPUT_LOG_FILE_FILE_TYPE
  errfilename = APPLICATION_STD_ERROR_LOG_FILE_PREFIX + APPLICATION_STD_ERROR_LOG_FILE_FILE_TYPE

  stdoutFile = open(outfilename, 'w+')
  stderrFile = open(errfilename, 'w+')
  
  proc = subprocess.Popen(command, stdout = stdoutFile, stderr = stderrFile, universal_newlines = True,
                          cwd=cwd, env=env, shell=False,
                          preexec_fn=preexec_fn)
  
  logAnyway = False
  if not wait_for_finish:
    if pid_file_name:
      pidfile = open(pid_file_name, 'w')
      pidfile.write(str(proc.pid))
      pidfile.close()

    ## wait poll_after seconds and poll
    if poll_after:
      time.sleep(poll_after)
      if proc.poll() is None:
        return None, None #if still running then return
      else:
        logAnyway = True #assume failure and log
        Logger.warning("Process is not up after the polling interval " + str(poll_after) + " seconds.")
    else:
      return None, None


  if timeout:
    q = Queue()
    t = threading.Timer( timeout, on_timeout, [proc, q] )
    t.start()
    
  #out = proc.communicate()[0].strip('\n')
  out = proc.communicate()
  
  if timeout:
    if q.empty():
      t.cancel()
    # timeout occurred
    else:
      raise ExecuteTimeoutException()
   
  code = proc.returncode
  
  if (logoutput or logAnyway) and out:
    Logger.info(out)
  
  if throw_on_failure and code:
    err_msg = Logger.get_protected_text(("Execution of '%s' returned %d. %s") % (command[-1], code, out))
    raise Fail(err_msg)
  
  return code, out
Ejemplo n.º 4
0
def _call(command,
          logoutput=False,
          throw_on_failure=True,
          cwd=None,
          env=None,
          preexec_fn=None,
          user=None,
          wait_for_finish=True,
          timeout=None,
          pid_file_name=None,
          poll_after=None):
    """
  Execute shell command
  
  @param command: list/tuple of arguments (recommended as more safe - don't need to escape) 
  or string of the command to execute
  @param logoutput: boolean, whether command output should be logged of not
  @param throw_on_failure: if true, when return code is not zero exception is thrown
  
  @return: retrun_code, stdout
  """
    # convert to string and escape
    if isinstance(command, (list, tuple)):
        command = ' '.join(quote_bash_args(x) for x in command)
    """
  Do not su to the supplied user (need to differentiate between when to call su and when not to)
  if user:
    command = ["su", "-", user, "-c", command]
  else:
    command = ["/bin/bash","--login","-c", command]
  """
    command = ["/bin/bash", "--login", "-c", command]
    #adding redirecting stdout stderr to file
    outfilename = APPLICATION_STD_OUTPUT_LOG_FILE_PREFIX + APPLICATION_STD_OUTPUT_LOG_FILE_FILE_TYPE
    errfilename = APPLICATION_STD_ERROR_LOG_FILE_PREFIX + APPLICATION_STD_ERROR_LOG_FILE_FILE_TYPE

    stdoutFile = open(outfilename, 'w+')
    stderrFile = open(errfilename, 'w+')

    proc = subprocess.Popen(command,
                            stdout=stdoutFile,
                            stderr=stderrFile,
                            universal_newlines=True,
                            cwd=cwd,
                            env=env,
                            shell=False,
                            preexec_fn=preexec_fn)

    logAnyway = False
    if not wait_for_finish:
        if pid_file_name:
            pidfile = open(pid_file_name, 'w')
            pidfile.write(str(proc.pid))
            pidfile.close()

        ## wait poll_after seconds and poll
        if poll_after:
            time.sleep(poll_after)
            if proc.poll() is None:
                return None, None  #if still running then return
            else:
                logAnyway = True  #assume failure and log
                Logger.warning(
                    "Process is not up after the polling interval " +
                    str(poll_after) + " seconds.")
        else:
            return None, None

    if timeout:
        q = Queue()
        t = threading.Timer(timeout, on_timeout, [proc, q])
        t.start()

    #out = proc.communicate()[0].strip('\n')
    out = proc.communicate()

    if timeout:
        if q.empty():
            t.cancel()
        # timeout occurred
        else:
            raise ExecuteTimeoutException()

    code = proc.returncode

    if (logoutput or logAnyway) and out:
        Logger.info(out)

    if throw_on_failure and code:
        err_msg = Logger.get_protected_text(
            ("Execution of '%s' returned %d. %s") % (command[-1], code, out))
        raise Fail(err_msg)

    return code, out
Ejemplo n.º 5
0
def _call(command, logoutput=False, throw_on_failure=True, 
         cwd=None, env=None, preexec_fn=None, user=None, wait_for_finish=True, timeout=None, path=None):
  """
  Execute shell command
  
  @param command: list/tuple of arguments (recommended as more safe - don't need to escape) 
  or string of the command to execute
  @param logoutput: boolean, whether command output should be logged of not
  @param throw_on_failure: if true, when return code is not zero exception is thrown
  
  @return: retrun_code, stdout
  """
  # convert to string and escape
  if isinstance(command, (list, tuple)):
    command = ' '.join(quote_bash_args(x) for x in command)

  if path:
    export_path_command = "export PATH=$PATH" + os.pathsep + os.pathsep.join(path) + " ; "
  else:
    export_path_command = ""

  if user:
    if env:
      export_path_command += "export "
      for var in env:
        export_path_command += " " + var + "=" + env[var]
      export_path_command += " ; "

    subprocess_command = ["su", "-s", "/bin/bash", "-", user, "-c", export_path_command + command]
  else:
    subprocess_command = ["/bin/bash","--login","-c", export_path_command + command]

  proc = subprocess.Popen(subprocess_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                          cwd=cwd, env=env, shell=False,
                          preexec_fn=preexec_fn)

  if not wait_for_finish:
    return None, None
  
  if timeout:
    q = Queue()
    t = threading.Timer( timeout, on_timeout, [proc, q] )
    t.start()
    
  out = proc.communicate()[0].strip('\n')
  
  if timeout:
    if q.empty():
      t.cancel()
    # timeout occurred
    else:
      raise ExecuteTimeoutException()
   
  code = proc.returncode
  
  if logoutput and out:
    Logger.info(out)
  
  if throw_on_failure and code:
    err_msg = Logger.get_protected_text(("Execution of '%s' returned %d. %s") % (command, code, out))
    raise Fail(err_msg)
  
  return code, out