#!/usr/bin/python
#INTEL CONFIDENTIAL
#Copyright (c) 2009-2012  Intel Corporation All Rights Reserved. 
#The source code contained or described herein and all documents related to the
#source code ("Material") are owned by Intel Corporation or its suppliers or
#licensors. Title to the Material remains with Intel Corporation or its
#suppliers and licensors. The Material contains trade secrets and proprietary
#and confidential information of Intel or its suppliers and licensors.
#The Material is protected by worldwide copyright and trade secret laws and
#treaty provisions.No part of the Material may be used, copied, reproduced,
#modified, published,uploaded, posted, transmitted, distributed, or disclosed in
#any way without Intel.s prior express written permission.
#
#No license under any patent, copyright, trade secret or other intellectual
#property right is granted to or conferred upon you by disclosure or delivery of
#the Materials, either expressly, by implication, inducement, estoppel or
#otherwise. Any license under such intellectual property rights must be express
#and approved by Intel in writing.

# shmemrun is a wrapper script for running SHMEM programs using mpirun.
# The main purpose of the script is to call mpirun with additional
# options to specify the SHMEM library directory so that its dynamic
# libraries can be resolved. The script detects which mpirun is being
# used and remaps some common mpirun options to present a convenient
# and consistent interface to SHMEM users. It also enables PSM support
# in the underlying mpirun if required, and auto-propagates PSM, IPATH and
# SHMEM environment variables to the MPI processes. shmemrun automatically 
# determines the correct directories by finding them relative to its 
# own location. The standard directory layout of the Intel SHMEM 
# software is assumed.
# 
# By default mpirun is picked up from the path, and is assumed to
# be called "mpirun". Alternatively, the pathname of mpirun can be specified
# with the $SHMEM_MPIRUN environment variable.
# 
# If -show is in the options given to shmemrun, it will show the command
# line that would be used to invoke mpirun but will not invoke it.
# Options that specify the number of processes and the hosts file
# are mapped by shmemrun to options that are accepted by the underlying
# mpirun. Additionally, the contents of the host file can be parsed
# and regenerated if necessary, and options to propagate environment
# variables are provided. The rationale for this script is to allow you to
# use the familiar options from the mpirun of your choosing, and they will
# automatically be remapped as required for the actual mpirun. This makes
# it possible to write scripts that call shmemrun without exposing these
# details of the underlying mpirun command.
#
# If shmemrun finds the special option -- while processing the option
# list, that option is deleted and subsequent options and command line
# arguments are passed through without any modification. This can be
# useful to prevent shmemrun from modifying options of the program
# that is being run!
# 
# If you do not wish to use this wrapper script, then you must arrange
# for the SHMEM libraries to be found at run-time using $LD_LIBRARY_PATH
# or equivalent mechanism, and ensure that PSM support is enabled
# in your MPI implementation. The libaries can be found at:
#
#   $SHMEM_DIR/lib64/$MPI
#
# where $SHMEM_DIR denotes the top-level directory of the SHMEM
# installation, typically /usr/shmem/intel, and $MPI is your choice
# of MPI.
#
# Additionally, PSM back-trace must be disabled using:
#
#   export IPATH_NO_BACKTRACE=1
#
# Intel SHMEM supports passive and active progress modes of operation
# using the SHMEM_PROGRESS environment variable. If you wish to achieve
# the same effect without using shmemrun, active progress (the default)
# requires these environment variables:
#
#   export PSM_RCVTHREAD=0
#
# while passive progress requires these environment variables:
#
#   export PSM_RCVTHREAD=1
#   export SHMEM_GET_LONG_SIZE=0
#   export SHMEM_PUT_LONG_SIZE=0

import exceptions
import os
import re
import signal
import stat
import string
import subprocess
import sys
import tempfile
import time

my_cmd_name = os.path.basename(sys.argv[0])

verbose_env_name = 'SHMEMRUN_VERBOSE'
sleep_env_name = 'SHMEMRUN_SLEEP'
timeout_env_name = 'SHMEMRUN_TIMEOUT'
mpirun_env_name_list = ('SHMEM_MPIRUN', 'SHMEMRUN_MPIRUN')
progress_env_name = 'SHMEM_PROGRESS'

verbose = 0
if verbose_env_name in os.environ and os.environ[verbose_env_name] != '' :
  verbose = 1

sleep = 0
if sleep_env_name in os.environ and \
   re.match('\d+$', os.environ[sleep_env_name]) :
  sleep = int(os.environ[sleep_env_name])

timeout = 0
if timeout_env_name in os.environ and \
   re.match('\d+$', os.environ[timeout_env_name]) :
  timeout = int(os.environ[timeout_env_name])

unknown_mpirun = 0
qlogic_mpirun = 1
hpmpi_mpirun = 2
openmpi_mpirun = 3
mvapich_mpirun = 4
mvapich2_mpirun = 5
platform_mpirun = 6
mvapich_rsh_mpirun = 7
mvapich2_rsh_mpirun = 8

mpilibname_map = {}
mpilibname_map[unknown_mpirun] = 'unknown'
mpilibname_map[qlogic_mpirun] = 'qlogic'
mpilibname_map[hpmpi_mpirun] = 'hpmpi'
mpilibname_map[openmpi_mpirun] = 'openmpi'
mpilibname_map[mvapich_mpirun] = 'mvapich'
mpilibname_map[mvapich2_mpirun] = 'mvapich2'
mpilibname_map[platform_mpirun] = 'platform'
mpilibname_map[mvapich_rsh_mpirun] = 'mvapich'
mpilibname_map[mvapich2_rsh_mpirun] = 'mvapich2'

mpiformalname_map = {}
mpiformalname_map[unknown_mpirun] = 'Unknown MPI'
mpiformalname_map[qlogic_mpirun] = 'QLogic MPI'
mpiformalname_map[hpmpi_mpirun] = 'HP MPI'
mpiformalname_map[openmpi_mpirun] = 'OpenMPI'
mpiformalname_map[mvapich_mpirun] = 'MVAPICH'
mpiformalname_map[mvapich2_mpirun] = 'MVAPICH2'
mpiformalname_map[platform_mpirun] = 'Platform MPI'
mpiformalname_map[mvapich_rsh_mpirun] = 'MVAPICH (using mpirun_rsh)'
mpiformalname_map[mvapich2_rsh_mpirun] = 'MVAPICH2 (using mpirun_rsh)'

canonical_env = '--env'
canonical_hostlist = '--hostlist'
canonical_machinefile = '--machinefile'
canonical_numprocs = '--numprocs'
canonical_ppn = '--ppn'

# These option maps provide a mapping from the canonical options
# to a list of the corresponding target options. The first entry in the
# list is the preferred option. However, if the user provides any of
# the options in the list, then that option will be used instead of the
# preferred option. This is to avoid unnecessary remapping of the user
# provided option list, just in case the user knows better than the tool.

unknown_mpirun_option_map = {
}

qlogic_mpirun_option_map = {
  # NOTE: env is not available
  canonical_hostlist    : ['-H', '-hostlist'],
  canonical_machinefile : ['-m', '-machinefile'],
  canonical_numprocs    : ['-np'],
  canonical_ppn         : ['-ppn']
}

hpmpi_mpirun_option_map = {
  # NOTE: ppn is not available
  canonical_env         : ['-e'],
  canonical_hostlist    : ['-hostlist'],
  canonical_machinefile : ['-hostfile'],
  canonical_numprocs    : ['-np']
}

openmpi_mpirun_option_map = {
  canonical_env         : ['-x'],
  canonical_hostlist    : ['-H', '-host', '--host'],
  canonical_machinefile : ['-machinefile', '--machinefile'],
  canonical_numprocs    : ['-np', '--np', '-n', '--n', '-c'],
  canonical_ppn         : ['-npernode']
}

mvapich_mpirun_option_map = {
  # NOTE: env, hostlist and ppn are not available
  canonical_machinefile : ['-machinefile'],
  canonical_numprocs    : ['-np']
}

mvapich2_mpirun_option_map = {
  # NOTE: env, hostlist and ppn are not available
  canonical_machinefile : ['-f'],
  canonical_numprocs    : ['-np']
}

platform_mpirun_option_map = {
  # NOTE: env and hostlist is not available
  canonical_machinefile : ['-machinefile', '-hostfile'],
  canonical_numprocs    : ['-np'],
  canonical_ppn         : ['-npn']
}

mvapich_rsh_mpirun_option_map = {
  # NOTE: env, hostlist and ppn are not available
  canonical_machinefile : ['-hostfile'],
  canonical_numprocs    : ['-np']
}

mvapich2_rsh_mpirun_option_map = {
  # NOTE: env, hostlist and ppn are not available
  canonical_machinefile : ['-hostfile'],
  canonical_numprocs    : ['-np']
}

mpirun_option_map = {}
mpirun_option_map[unknown_mpirun] = unknown_mpirun_option_map
mpirun_option_map[qlogic_mpirun] = qlogic_mpirun_option_map
mpirun_option_map[hpmpi_mpirun] = hpmpi_mpirun_option_map
mpirun_option_map[openmpi_mpirun] = openmpi_mpirun_option_map
mpirun_option_map[mvapich_mpirun] = mvapich_mpirun_option_map
mpirun_option_map[mvapich2_mpirun] = mvapich2_mpirun_option_map
mpirun_option_map[platform_mpirun] = platform_mpirun_option_map
mpirun_option_map[mvapich_rsh_mpirun] = mvapich_rsh_mpirun_option_map
mpirun_option_map[mvapich2_rsh_mpirun] = mvapich2_rsh_mpirun_option_map

# This provides the mapping from options that the user can specify to
# canonical options. Note that the canonical options 
# can be arbitrary strings and do that themselves occur in the user
# option list or generated command.

my_option_map = {
  '-e'                  : canonical_env,
  '-H'                  : canonical_hostlist,
  '-host'               : canonical_hostlist,
  '--host'              : canonical_hostlist,
  '-hosts'              : canonical_hostlist,
  '-hostlist'           : canonical_hostlist,
  '-m'                  : canonical_machinefile,
  '-machinefile'        : canonical_machinefile,
  '--machinefile'       : canonical_machinefile,
  '-hostfile'           : canonical_machinefile,
  '--hostfile'          : canonical_machinefile,
  '-np'                 : canonical_numprocs,
  '--np'                : canonical_numprocs,
  '-n'                  : canonical_numprocs,
  '--n'                 : canonical_numprocs,
  '-ppn'                : canonical_ppn,
  '-npernode'           : canonical_ppn,
  '--npernode'          : canonical_ppn,
  '-npn'                : canonical_ppn,
  '-x'                  : canonical_env
}

# Feature list per mpirun:
#  colon_in_machinefile : supports host:ppn syntax in machinefile
#  colon_in_hostlist : supports host:ppn syntax in hostlist
#  round_robin_machinefile : assigns processes to host file entries round robin
#                         (otherwise need to fully expand the machinefile)
#  slots_in_machinefile : supports host slots=ppn syntax in machinefile

no_mpirun_features = {
  'colon_in_machinefile' : 0,
  'colon_in_hostlist' : 0,
  'round_robin_machinefile' : 0,
  'slots_in_machinefile' : 0
}

qlogic_mpirun_features = {
  'colon_in_machinefile' : 1,
  'colon_in_hostlist' : 0,
  'round_robin_machinefile' : 1,
  'slots_in_machinefile' : 0
}

hpmpi_mpirun_features = {
  'colon_in_machinefile' : 0,
  'colon_in_hostlist' : 0,
  'round_robin_machinefile' : 1,
  'slots_in_machinefile' : 0
}

openmpi_mpirun_features = {
  'colon_in_machinefile' : 0,
  'colon_in_hostlist' : 0,
  'round_robin_machinefile' : 0,
  'slots_in_machinefile' : 1
}

platform_mpirun_features = {
  'colon_in_machinefile' : 0,
  'colon_in_hostlist' : 0,
  'round_robin_machinefile' : 1,
  'slots_in_machinefile' : 0
}

mpirun_features = {}
mpirun_features[unknown_mpirun] = no_mpirun_features
mpirun_features[qlogic_mpirun] = qlogic_mpirun_features
mpirun_features[hpmpi_mpirun] = hpmpi_mpirun_features
mpirun_features[openmpi_mpirun] = openmpi_mpirun_features
mpirun_features[mvapich_mpirun] = no_mpirun_features
mpirun_features[mvapich2_mpirun] = no_mpirun_features
mpirun_features[platform_mpirun] = platform_mpirun_features
mpirun_features[mvapich_rsh_mpirun] = no_mpirun_features
mpirun_features[mvapich2_rsh_mpirun] = no_mpirun_features

def is_executable (pathname) :
  if os.path.isfile(pathname) :
    filestat = os.stat(pathname)
    st_mode = filestat[stat.ST_MODE]
    s_imode = stat.S_IMODE(st_mode)
    if (s_imode & 0111) != 0 :
      return True
  return False

def find_executable (name) :
  if name == '' or name[0] == '/' :
    return name
  else :
    path = os.environ['PATH']
    for pathdir in string.split(path, ':') :
      pathname = '%s/%s' % (pathdir, name)
      if is_executable(pathname) :
        return pathname
  return name

# TODO: this is not safe with an executable hosts file!
def find_first_executable (args) :
  for i in range(1, len(args)) :
    if args[i] != None and \
       args[i] != '' and \
       args[i][0] != '-' and \
       is_executable(find_executable(args[i])) :
      return i
  return -1

def find_mpi_dir (mpirun) :
  return os.path.abspath('%s/..' % os.path.dirname(mpirun))

def detect_mpirun (mpirun) :
  if verbose :
    print '%s: using mpirun %s' % (my_cmd_name, mpirun)
  which_mpirun = unknown_mpirun
  p1 = subprocess.Popen('%s -version' % mpirun, shell=True, stdin=None,
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                        close_fds=True)
  p2 = subprocess.Popen('%s --allow-run-as-root -version' % mpirun, shell=True, stdin=None,
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                        close_fds=True)
  p3 = subprocess.Popen('%s -h' % mpirun, shell=True, stdin=None,
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                        close_fds=True)
  for fd in (p1.stdout, p1.stderr, p2.stdout, p2.stderr, p3.stdout, p3.stderr) :
    if which_mpirun == unknown_mpirun :
      for line in fd :
        if re.search('InfiniPath', line) or re.search('QLogic', line) :
          which_mpirun = qlogic_mpirun
          break
        if re.search('HP MPI', line) :
          which_mpirun = hpmpi_mpirun
          break
        if re.search('Open MPI', line) :
          which_mpirun = openmpi_mpirun
          break
        if re.search('mvapich2.*mpirun_rsh', line) :
          which_mpirun = mvapich2_rsh_mpirun
          break
        if re.search('mvapich2', line) :
          which_mpirun = mvapich2_mpirun
          break
        if re.search('mvapich.*mpirun_rsh', line) :
          which_mpirun = mvapich_rsh_mpirun
          break
        if re.search('mvapich', line) :
          which_mpirun = mvapich_mpirun
          break
        if re.search('ScaMPI', line) :
          which_mpirun = platform_mpirun
          break
      fd.close()
  p1.wait()
  p2.wait()
  if verbose :
    print '%s: detected MPI as %s' % \
          (my_cmd_name, mpiformalname_map[which_mpirun])
  return which_mpirun

def map_to_canonical_option (option) :
  if option in my_option_map :
    return my_option_map[option]
  else :
    return None

def map_to_target_option (option, canonical_option, which_mpirun) :
  target_option = option
  if (canonical_option != None) and \
     (canonical_option in mpirun_option_map[which_mpirun]) and \
     (not option in mpirun_option_map[which_mpirun][canonical_option]) :
    target_option = mpirun_option_map[which_mpirun][canonical_option][0]
  return target_option

def get_tmp_machinefile (machinefile) :
  try_dirs = []
  try_dirs.append(os.path.dirname(os.path.abspath(machinefile)))
  try_dirs.append(os.getcwd())
  try_dirs.append(os.path.expanduser('~'))
  if verbose :
    print '%s: temporary directory list for hosts file is %s' % \
          (my_cmd_name, str(try_dirs))
  for try_dir in try_dirs :
    try :
      # The temporary machine file will be automatically deleted on exit
      file = tempfile.NamedTemporaryFile(mode='w', dir=try_dir)
      if file :
        return file
    except exceptions.OSError, exceptions.IOError :
      pass
  return None

def map_machinefile (hostlist, machinefile, np, ppn, which_mpirun) :
  has_ppn = (canonical_ppn in mpirun_option_map[which_mpirun])
  has_hostlist = (canonical_hostlist in mpirun_option_map[which_mpirun])
  has_colon1 = mpirun_features[which_mpirun]['colon_in_machinefile']
  has_colon2 = mpirun_features[which_mpirun]['colon_in_hostlist']
  has_slots = mpirun_features[which_mpirun]['slots_in_machinefile']
  has_round_robin = mpirun_features[which_mpirun]['round_robin_machinefile']
  hosts = []
  got_colon1 = 0
  got_colon2 = 0
  got_slots = 0
  num_hosts = 0

  if machinefile :
    try :
      file = open(machinefile, 'r')
      for line in file :
        line = line.strip()
        if re.match('#', line) :
          continue
        match1 = re.match('(.*)\s*:\s*(\d+)$', line)
        match2 = re.match('(.*)\s*slots\s*=\s*(\d+)$', line)
        if match1 or match2 :
          # line has "host:ppn" or "host slots=ppn" syntax
          if match1 :
            got_colon1 = 1
            match = match1
          else :
            got_slots = 1
            match = match2
          this_host = match.group(1)
          if ppn >= 1 :
            # command line ppn over-rides ppn in machine file
            this_ppn = ppn
          else :
            this_ppn = int(match.group(2))
          hosts.append([this_host, this_ppn])
          num_hosts += this_ppn
        elif line != '' :
          # line has plain host
          if ppn > 1 :
            hosts.append([line, ppn])
            num_hosts += ppn
          else :
            hosts.append([line, 1])
            num_hosts += 1
      file.close()
    except exceptions.IOError :
      if verbose :
        print '%s: cannot read hosts file "%s"' % (my_cmd_name, machinefile)
      return (None, None, None)

  if hostlist :
    for line in hostlist.split(',') :
      line = line.strip()
      match = re.match('(.*)\s*:\s*(\d+)$', line)
      if match :
        this_host = match.group(1)
        if ppn >= 1 :
          # command line ppn over-rides ppn in host list
          this_ppn = ppn
        else :
          this_ppn = int(match.group(2))
        hosts.append([this_host, this_ppn])
        got_colon2 = 1
        num_hosts += this_ppn
      elif line != '' :
        if ppn > 1 :
          hosts.append([line, ppn])
          num_hosts += ppn
        else :
          hosts.append([line, 1])
          num_hosts += 1

  # if np has not been specified, set np to number of hosts found
  if np == -1 :
    np = num_hosts
    if verbose :
      print '%s: number of processes not specified, default to %d' % \
            (my_cmd_name, np)

  if verbose :
    print '%s: input hosts is %s' % (my_cmd_name, str(hosts))

  if not hosts :
    if verbose :
      print '%s: input hosts is empty so cannot parse it' % (my_cmd_name)
    return (None, None, None)

  canonical = 0
  if ppn >= 1 and not has_ppn :
    canonical = 1
    if verbose :
      print '%s: %s needs new hosts file because of ppn' % \
            (my_cmd_name, mpiformalname_map[which_mpirun])

  if hostlist and not has_hostlist :
    canonical = 1
    if verbose :
      print '%s: %s needs new hosts file because of hosts list' % \
            (my_cmd_name, mpiformalname_map[which_mpirun])

  if got_colon1 and not has_colon1 :
    canonical = 1
    if verbose :
      print '%s: %s needs new hosts file because of colon in hosts file' % \
            (my_cmd_name, mpiformalname_map[which_mpirun])

  if got_colon2 and not has_colon2 :
    canonical = 1
    if verbose :
      print '%s: %s needs new hosts file because of colon in hosts list' % \
            (my_cmd_name, mpiformalname_map[which_mpirun])

  if got_slots and not has_slots :
    canonical = 1
    if verbose :
      print '%s: %s needs new hosts file because of slots in hosts file' % \
            (my_cmd_name, mpiformalname_map[which_mpirun])

  if np > num_hosts and not has_round_robin :
    canonical = 1
    if verbose :
      print '%s: %s needs new hosts file because of wraparound' % \
            (my_cmd_name, mpiformalname_map[which_mpirun])

  if canonical :
    outhosts = []
    count = 0
    ppn = 0	# indicates that any ppn argument must be deleted
    while count < np :
      for host in hosts :
        for p in range(0, host[1]) :
          if np == 0 or count < np : 
            outhosts.append(host[0])
            count += 1
    if verbose :
      print '%s: output hosts is %s' % (my_cmd_name, str(outhosts))
    outfile = get_tmp_machinefile(machinefile)
    if not outfile :
      if verbose :
        print '%s: cannot open a temporary hosts file' % my_cmd_name
      return (None, None, None)
    for host in outhosts :
      outfile.write('%s\n' % host)
    outfile.flush()
    return (outfile, ppn, np)
  else :
    return (None, ppn, np)

def alarm_handler (signum, frame) :
  raise IOError, "Timeout"

mpirun = 'mpirun'
for mpirun_env_name in mpirun_env_name_list :
  if mpirun_env_name in os.environ and os.environ[mpirun_env_name] != '' :
    mpirun = os.environ[mpirun_env_name]
    break
mpirun = find_executable(mpirun)
which_mpirun = detect_mpirun(mpirun)

ld_library_path = None
show_ld_library_path = None

# List of environment variable regular expressions to auto propagate
auto_prop_list = ['PSM_', 'IPATH_']

show = 0
run = 1

env_list = []
env_args = []
extra_env_list = []
hostlist = ''
hostlist_arg = 0
machinefile = ''
machinefile_arg = 0
np = -1
np_arg = 0
ppn = 0
ppn_arg = 0

machinefile_new_fd = -1
machinefile_new = ''
ppn_new = -1
np_new = -1

def find_shmem_dir () :
  my_name = sys.argv[0]
  my_dir = os.path.dirname(sys.argv[0])
  if my_dir == '' :
    my_dir = os.path.dirname(find_executable(sys.argv[0]))
  return os.path.abspath('%s/..' % my_dir)

shmem_dir = find_shmem_dir()
lib_dir = '%s/%s/%s' % (shmem_dir, 'lib64', mpilibname_map[which_mpirun])
lib_file = '%s/%s' % (lib_dir, 'libintel_shmem.so.1.0')
if not os.path.isdir(lib_dir) or not os.path.isfile(lib_file) :
  print >>sys.stderr, \
        ('%s fatal error: %s is not supported by Intel SHMEM') % \
        (my_cmd_name, mpiformalname_map[which_mpirun])
  sys.exit(-1)
if verbose :
  print '%s: shmem library directory is %s' % (my_cmd_name, lib_dir)
  print '%s: shmem library file is %s' % (my_cmd_name, lib_file)
if 'LD_LIBRARY_PATH' in os.environ:
  # The shmem library directory is appended so that an alternate location
  # provided by the user will take precedence.
  ld_library_path = '%s:%s' % (os.environ['LD_LIBRARY_PATH'], lib_dir)
else :
  ld_library_path = lib_dir

if not progress_env_name in os.environ or \
   os.environ[progress_env_name] == '0' or \
   os.environ[progress_env_name].lower() == 'active' :
  # use SHMEM active progress mechanism
  os.environ['PSM_RCVTHREAD'] = "0"
else :
  # use SHMEM passive progress progress mechanism
  os.environ['PSM_RCVTHREAD'] = "1"
  os.environ['SHMEM_GET_LONG_SIZE'] = "0"
  os.environ['SHMEM_PUT_LONG_SIZE'] = "0"

# Disable PSM's back-trace handler since it interferes with SHMEM termination
os.environ['IPATH_NO_BACKTRACE'] = "1"

# Auto-propagate all environment variables beginning with SHMEM_
auto_prop_list.append('SHMEM_')

inargv = []
matched_dash_dash = 0
matched_executable = 0
for arg in sys.argv :
  matched = 0
  if arg == '--' :
    matched_dash_dash = 1
  if is_executable(find_executable(arg)) :
    matched_executable = 1
  if matched_dash_dash or matched_executable :
    inargv.append(arg)
    continue
  for prefix in ['-np', '-n', '-ppn', '-npn'] :
    match = re.match('(%s)(\d+)$' % prefix, arg)
    if match :
      inargv.append(match.group(1))
      inargv.append(match.group(2))
      matched = 1
      if verbose :
        print '%s: mapped option "%s" to "%s %s"' % \
              (my_cmd_name, arg, match.group(1), match.group(2))
      break
  if not matched :
    inargv.append(arg)

# NOTE: keep arguments in corresponding positions between inargv and outargv
i = 1
outargv = [mpirun]
matched_dash_dash = 0
matched_executable = 0
for arg in inargv[1:] :
  if arg == '-show' :
    show = 1
    run = 0
    outargv.append(None)
  elif arg == '--' :
    matched_dash_dash = 1
    outargv.append(None)
    if verbose :
      print '%s: found -- option, subsequent args not modified' % \
            (my_cmd_name)
  elif is_executable(find_executable(arg)) :
    matched_executable = 1
    outargv.append(arg)
    if verbose :
      print '%s: found executable "%s", subsequent args not modified' % \
            (my_cmd_name, arg)
  elif matched_dash_dash or matched_executable :
    if verbose :
      print '%s: pass arg "%s" through without modification' % \
            (my_cmd_name, arg)
    outargv.append(arg)
  else :
    canonical_option = map_to_canonical_option(arg)
    if canonical_option == canonical_env and len(inargv) > i + 1 :
      match = re.match('(.*)=(.*)', inargv[i + 1])
      if match :
        env_list.append([match.group(1), match.group(2)])
        env_args.append(i)
    if canonical_option == canonical_hostlist and len(inargv) > i + 1 :
      hostlist = inargv[i + 1]
      hostlist_arg = i
    if canonical_option == canonical_machinefile and len(inargv) > i + 1 :
      machinefile = inargv[i + 1]
      machinefile_arg = i
    if canonical_option == canonical_numprocs and len(inargv) > i + 1 :
      match = re.match('(\d+)', inargv[i + 1])
      if match :
        np = int(match.group(1))
        np_arg = i
    if canonical_option == canonical_ppn and len(inargv) > i + 1 :
      match = re.match('(\d+)', inargv[i + 1])
      if match :
        ppn = int(match.group(1))
        ppn_arg = i
    target_option = map_to_target_option(arg, canonical_option, which_mpirun)
    if verbose :
      if canonical_option :
        print '%s: map input arg "%s" to output arg "%s" (canonical "%s")' % \
              (my_cmd_name, arg, target_option, canonical_option)
      else :
        print '%s: map input arg "%s" to output arg "%s"' % \
              (my_cmd_name, arg, target_option)
    outargv.append(target_option)
  i = i + 1

if verbose :
  if env_args :
    print '%s: env list contains: %s' % (my_cmd_name, env_list)
  if hostlist_arg :
    print '%s: hostlist is "%s" at argument %d' % \
          (my_cmd_name, hostlist, hostlist_arg)
  if machinefile_arg :
    print '%s: machinefile is "%s" at argument %d' % \
          (my_cmd_name, machinefile, machinefile_arg)
  if np_arg :
    print '%s: np is "%s" at argument %d' % \
          (my_cmd_name, np, np_arg)
  if ppn_arg :
    print '%s: ppn is "%s" at argument %d' % \
          (my_cmd_name, ppn, ppn_arg)

if hostlist or machinefile :
  (machinefile_new_fd, ppn_new, np_new) = \
    map_machinefile(hostlist, machinefile, np, ppn, which_mpirun)
  if machinefile_new_fd :
    machinefile_new = machinefile_new_fd.name
    if verbose :
      print '%s: use new hosts file %s' % \
            (my_cmd_name, machinefile_new)
      try :
        file = open(machinefile_new, 'r')
        print '%s: new hosts file contains:' % my_cmd_name
        for line in file :
          print line,
      except IOError :
        print '%s: could not open new hosts file %s' % \
              (my_cmd_name, machinefile_new)

    if machinefile_arg :
      outargv[machinefile_arg + 1] = machinefile_new
      if hostlist_arg :
        outargv[hostlist_arg] = None
        outargv[hostlist_arg + 1] = None
    else :
      outargv[hostlist_arg ] = map_to_target_option(canonical_machinefile,
                                                    canonical_machinefile,
                                                    which_mpirun)
      outargv[hostlist_arg + 1] = machinefile_new

    # Update ppn value in outargv if changed
    if ppn_arg and ppn_new != ppn and ppn_new != None :
      if ppn_new == 0 :
        outargv[ppn_arg] = None
        outargv[ppn_arg + 1] = None
      else :
        outargv[ppn_arg + 1] = ppn_new

# Now start inserting/deleting/moving entries in outargv which means 
# that any argument position variables will now be wrong

# Auto-propagation of environment variables to the MPI processes
for env in os.environ :
  for auto_prop in auto_prop_list :
    if re.match(auto_prop, env) :
      extra_env_list.append([env, os.environ[env]])
      break

if which_mpirun == mvapich_mpirun or which_mpirun == mvapich_rsh_mpirun :
  if not 'VIADEV_USE_AFFINITY' in os.environ :
    # disable MVAPICH's default affinity mechanism since it will 
    # over-ride choices made by SHMEM, PSM or the user
    extra_env_list.append(['VIADEV_USE_AFFINITY', '0'])

has_env = (canonical_env in mpirun_option_map[which_mpirun])

if extra_env_list :
  if has_env :
    option = mpirun_option_map[which_mpirun][canonical_env][0]
    arg = 1
    for env in extra_env_list :
      outargv.insert(arg, option)
      outargv.insert(arg + 1, '%s=%s' % (env[0], env[1]))
      arg = arg + 2
  else :
    env_list.extend(extra_env_list)    
  
first = find_first_executable(outargv)
if env_list and not has_env and first != -1 :
  if env_args :
    env_args.reverse()
    for arg in env_args :
      outargv[arg] = None
      outargv[arg + 1] = None
  arg = find_first_executable (outargv)
  if arg != -1 :
    outargv.insert(arg, '/usr/bin/env')
    for env in env_list :
      arg = arg + 1
      outargv.insert(arg, '%s=%s' % (env[0], env[1]))

# Insert np argument if one was not specified and it has been calculated
if not np_arg and np_new != -1 and np_new != None :
  option = map_to_target_option(canonical_numprocs, canonical_numprocs,
                                which_mpirun)
  arg = 1
  outargv.insert(arg, option)
  outargv.insert(arg + 1, '%d' % np_new)

# Delete outargv entries that have been set to None
for arg in range(len(outargv) - 1, -1, -1) :
  if outargv[arg] == None :
    del outargv[arg]

if which_mpirun == qlogic_mpirun :
  mpi_dir = find_mpi_dir(mpirun)
  if ld_library_path : 
    os.environ['LD_LIBRARY_PATH'] = ld_library_path
    show_ld_library_path = ld_library_path
  # must not use QLogic MPI progress check for SHMEM programs. This check
  # makes sure that MPI traffic is flowing, otherwise it deduces that the
  # program has hung and kills the processes. This is not true for SHMEM
  # programs since SHMEM traffic flows through SHMEM not through MPI.
  outargv.insert(1, '-disable-mpi-progress-check')
  # automatically set up $MPICH_ROOT if this is a prefixed install
  if mpi_dir != '/usr' :
    os.environ['MPICH_ROOT'] = mpi_dir

if which_mpirun == mvapich_mpirun or which_mpirun == mvapich_rsh_mpirun :
  if ld_library_path :
    os.environ['LD_LIBRARY_PATH'] = ld_library_path
    show_ld_library_path = ld_library_path

if which_mpirun == mvapich2_mpirun :
  mpi_dir = find_mpi_dir(mpirun)
  if ld_library_path : 
    ld_library_path = '%s/lib:%s' % (mpi_dir, ld_library_path)
  else :
    ld_library_path = '%s/lib' % mpi_dir
  outargv.insert(1, '-env')
  outargv.insert(2, 'LD_LIBRARY_PATH')
  outargv.insert(3, ld_library_path)

if which_mpirun == mvapich2_rsh_mpirun :
  mpi_dir = find_mpi_dir(mpirun)
  if ld_library_path : 
    ld_library_path = '%s/lib:%s' % (mpi_dir, ld_library_path)
  else :
    ld_library_path = '%s/lib' % mpi_dir
  os.environ['LD_LIBRARY_PATH'] = ld_library_path
  show_ld_library_path = ld_library_path

if which_mpirun == hpmpi_mpirun :
  outargv.insert(1, '-PSM')
  if ld_library_path : 
    outargv.insert(2, '-e')
    outargv.insert(3, 'LD_LIBRARY_PATH=%s' % ld_library_path)

if which_mpirun == openmpi_mpirun :
  mpi_dir = find_mpi_dir(mpirun)
  if ld_library_path : 
    ld_library_path = '%s/lib64:%s' % (mpi_dir, ld_library_path)
  else :
    ld_library_path = '%s/lib64' % mpi_dir
  outargv.insert(1, '--allow-run-as-root')
  outargv.insert(2, '-mca')
  outargv.insert(3, 'mtl')
  outargv.insert(4, 'psm')
  outargv.insert(5, '-x')
  outargv.insert(6, 'LD_LIBRARY_PATH=%s' % ld_library_path)

if which_mpirun == platform_mpirun :
  mpi_dir = find_mpi_dir(mpirun)
  if ld_library_path : 
    ld_library_path = '%s/lib64:%s' % (mpi_dir, ld_library_path)
  else :
    ld_library_path = '%s/lib64' % mpi_dir
  os.environ['LD_LIBRARY_PATH'] = ld_library_path
  show_ld_library_path = ld_library_path
  outargv.insert(1, '-q')
  outargv.insert(2, '-networks')
  outargv.insert(3, 'infinipath')

if show or verbose :
  if show_ld_library_path :
    print 'export LD_LIBRARY_PATH="%s"' % show_ld_library_path
  for arg in outargv :
    print arg,
  print

result = 0

sys.stdout.flush()
sys.stderr.flush()

if run :
  if not is_executable(mpirun) :
    print >>sys.stderr, '%s fatal error: cannot execute %s' % \
          (my_cmd_name, mpirun)
    result = -1
  elif timeout == 0 :
    try :
      result = os.spawnve(os.P_WAIT, mpirun, outargv, os.environ)
    except exceptions.SystemExit :
      pass
    except :
      result = -1
  else :
    command = outargv
    try :
      child = subprocess.Popen(command, env = os.environ)
    except :
      print >>sys.stderr, '%s fatal error: cannot run command "%s"' % \
            (my_cmd_name, str(command))
      result = -1
    if result == 0 :
      signal.signal(signal.SIGALRM, alarm_handler)
      signal.alarm(timeout)
      try :
        child.communicate()
        result = child.returncode
        if verbose :
          print '%s: completed with result %d' % (my_cmd_name, result)
      except exceptions.IOError :
        print >>sys.stderr, \
              '%s fatal error: command timed out after %d seconds' % \
              (my_cmd_name, timeout)
        os.kill(child.pid, signal.SIGKILL)
        result = -1
      except :
        print >>sys.stderr, \
              '%s fatal error: command failed for some other reason' % \
              my_cmd_name
        result = -1
      signal.alarm(0) 

if sleep :
  time.sleep(sleep)

sys.exit(result)
