1#!/usr/bin/python3
2#
3# Copyright 2019, The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Run a command using multiple cores in parallel. Stop when one exits zero and save the log from
19that run.
20"""
21
22import argparse
23import concurrent.futures
24import contextlib
25import itertools
26import os
27import os.path
28import shutil
29import subprocess
30import tempfile
31
32
33def run_one(cmd, tmpfile):
34  """Run the command and log result to tmpfile. Return both the file name and returncode."""
35  with open(tmpfile, "x") as fd:
36    return tmpfile, subprocess.run(cmd, stdout=fd).returncode
37
38def main():
39  parser = argparse.ArgumentParser(
40      description="""Run a command using multiple cores and save non-zero exit log
41
42      The cmd should print all output to stdout. Stderr is not captured."""
43  )
44  parser.add_argument("--jobs", "-j", type=int, help="max number of jobs. default 60", default=60)
45  parser.add_argument("cmd", help="command to run")
46  parser.add_argument("--out", type=str, help="where to put result", default="out_log")
47  args = parser.parse_args()
48  cnt = 0
49  found_fail = False
50  ids = itertools.count(0)
51  with tempfile.TemporaryDirectory() as td:
52    print("Temporary files in {}".format(td))
53    with concurrent.futures.ProcessPoolExecutor(args.jobs) as p:
54      fs = set()
55      while len(fs) != 0 or not found_fail:
56        if not found_fail:
57          for _, idx in zip(range(args.jobs - len(fs)), ids):
58            fs.add(p.submit(run_one, args.cmd, os.path.join(td, "run_log." + str(idx))))
59        ws = concurrent.futures.wait(fs, return_when=concurrent.futures.FIRST_COMPLETED)
60        fs = ws.not_done
61        done = list(map(lambda a: a.result(), ws.done))
62        cnt += len(done)
63        print("\r{} runs".format(cnt), end="")
64        failed = [d for d,r in done if r != 0]
65        succ = [d for d,r in done if r == 0]
66        for f in succ:
67          os.remove(f)
68        if len(failed) != 0:
69          if not found_fail:
70            found_fail = True
71            print("\rFailed at {} runs".format(cnt))
72            if len(failed) != 1:
73              for f,i in zip(failed, range(len(failed))):
74                shutil.copyfile(f, args.out+"."+str(i))
75            else:
76              shutil.copyfile(failed[0], args.out)
77
78if __name__ == '__main__':
79  main()
80