aboutsummaryrefslogtreecommitdiff
blob: 9f59a6f3c92fcc3f7d00fdd39245c9f006d4a4f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python

import os
import signal
import shlex
import subprocess
import sys
import time
from grs.Constants import CONST

class Execute():
    """ Execute a shell command """

    def __init__(self, cmd, timeout = 1, extra_env = {}, failok = False, logfile = CONST.LOGFILE):
        """ Execute a shell command.

            cmd         - Simple string of the command to be execute as a
                          fork()-ed child.
            timeout     - The time in seconds to wait() on the child before
                          sending a SIGTERM.  timeout = None means wait indefinitely.
            extra_env   - Dictionary of extra environment variables for the fork()-ed
                          child.  Note that the child inherits all the env variables
                          of the grandparent shell in which grsrun/grsup was spawned.
            logfile     - A file to log output to.  If logfile = None, then we log
                          to sys.stdout.
        """
        def signalexit():
            pid = os.getpid()
            f.write('SENDING SIGTERM to pid = %d\n' % pid)
            f.close()
            try:
                for i in range(10):
                    os.kill(pid, signal.SIGTERM)
                    time.sleep(0.2)
                while True:
                    os.kill(pid, signal.SIGKILL)
                    time.sleep(0.2)
            except ProcessLookupError:
                pass

        args = shlex.split(cmd)
        extra_env = dict(os.environ, **extra_env)

        if logfile:
            f = open(logfile, 'a')
            proc = subprocess.Popen(args, stdout=f, stderr=f, env=extra_env)
        else:
            f = sys.stderr
            proc = subprocess.Popen(args, env=extra_env)

        try:
            proc.wait(timeout)
            timed_out = False
        except subprocess.TimeoutExpired:
            proc.kill()
            timed_out = True

        if not timed_out:
            # rc = None if we had a timeout
            rc = proc.returncode
            if rc:
                f.write('EXIT CODE: %d\n' % rc)
                if not failok:
                    signalexit()

        if timed_out:
            f.write('TIMEOUT ERROR: %s\n' % cmd)
            if not failok:
                signalexit()

        # Only close a logfile, don't close sys.stderr!
        if logfile:
            f.close()