aboutsummaryrefslogtreecommitdiff
blob: 0e702215d9366471e9b55f19a75853ed2ae14dcd (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python
#
#    Execute.py: this file is part of the GRS suite
#    Copyright (C) 2015  Anthony G. Basile
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

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, shell=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()
            while True:
                os.kill(pid, signal.SIGTERM)
                time.sleep(2.0)

        if shell:
            args = cmd
        else:
            args = shlex.split(cmd)
        extra_env = dict(os.environ, **extra_env)

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

        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:
                _file.write('EXIT CODE: %d\n' % _rc)
                if not failok:
                    _file.write('SENDING SIGTERM\n')
                    _file.close()
                    signalexit()

        if timed_out:
            _file.write('TIMEOUT ERROR: %s\n' % cmd)
            if not failok:
                _file.write('SENDING SIGTERM\n')
                _file.close()
                signalexit()

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