KMR
eprun.py
1 #!/usr/bin/env python3
2 # -*-coding: utf-8;-*-
3 
4 # eprun.py - Invokes shell commands on ranks (except rank=0). It
5 # reads a file containing lines of shell commands (one per line) on
6 # rank=0. It runs mulitple commands on each node (one per core) with
7 # option "-m". USAGE: "mpiexec -n N python3 ./eprun.py
8 # ./file-of-commands"
9 
10 from mpi4py import MPI
11 import kmr4py
12 from optparse import OptionParser
13 from optparse import HelpFormatter
14 from optparse import IndentedHelpFormatter
15 import time
16 import sys
17 import re
18 
19 kmr0 = kmr4py.KMR("world")
20 NPROCS = kmr0.nprocs
21 RANK = kmr0.rank
22 
23 class NullHelpFormatter(HelpFormatter):
24  """Suppress helps on except rank=0."""
25 
26  def __init__(self,
27  indent_increment=0,
28  max_help_position=24,
29  width=None,
30  short_first=0):
31  HelpFormatter.__init__(
32  self, indent_increment, max_help_position, width, short_first)
33 
34  def format_option(self, option):
35  return ""
36 
37  def format_heading(self, heading):
38  return ""
39 
40  def format_text(self, text):
41  return ""
42 
43  def format_usage(self, usage):
44  return ""
45 
46 if (RANK == 0):
47  options = OptionParser()
48 else:
49  options = OptionParser(formatter=NullHelpFormatter())
50 
51 options.add_option("-t", "--trace",
52  dest="trace", action="store_true", default=False,
53  help="prints traces of invoking commands to stderr")
54 options.add_option("-m", "--per-core",
55  dest="percore", action="store_true", default=False,
56  help="invokes commands per core")
57 
58 def read_commands(arg):
59  k00 = kmr0.make_kvs(value="cstring")
60  if (RANK == 0):
61  f = open(arg)
62  lines = f.readlines()
63  f.close()
64  for i, line in zip(range(len(lines)), lines):
65  k00.add(i, "sh\0-c\0" + line.rstrip())
66  k00.add_kv_done()
67  return k00
68 
69 def identitymap(kv, kvi, kvo, i, *_data):
70  (k, v) = kv
71  kvo.add(k, v)
72  return 0
73 
74 ## MAIN.
75 
76 (opts, args) = options.parse_args()
77 
78 if (NPROCS == 1):
79  sys.stderr.write("eprun needs more than one rank; abort.\n")
80  sys.exit(1)
81 
82 if (len(args) != 1):
83  if (RANK == 0):
84  sys.stderr.write("Usage: python3 eprun.py [options] input-file.\n")
85  sys.exit(1)
86 
87 if (opts.trace):
88  kmr0.set_option("trace_map_ms", "1")
89 threading = (opts.percore)
90 
91 sys.stdout.flush()
92 sys.stderr.flush()
93 
94 k20 = read_commands(args[0])
95 k21 = k20.map_ms_commands(identitymap, nothreading=(not threading),
96  separator_space=False, value="cstring")
97 
98 k21.free()
99 kmr0.dismiss()
100 
101 sys.stdout.flush()
102 sys.stderr.flush()
103 
104 #time.sleep(1)
105 #if (RANK == 0):
106 # print("eprun OK")
107 #sys.stdout.flush()