Fix #128 - [NS3] Test ns-3 with localhost
[nepi.git] / src / nepi / util / execfuncs.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License as published by
7 #    the Free Software Foundation, either version 3 of the License, or
8 #    (at your option) any later version.
9 #
10 #    This program is distributed in the hope that it will be useful,
11 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #    GNU General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20 from nepi.util.sshfuncs import ProcStatus, STDOUT, log, shell_escape
21
22 import logging
23 import shlex
24 import subprocess
25
26 def lexec(command, 
27         user = None, 
28         sudo = False,
29         env = None):
30     """
31     Executes a local command, returns ((stdout,stderr),process)
32     """
33     if env:
34         export = ''
35         for envkey, envval in env.iteritems():
36             export += '%s=%s ' % (envkey, envval)
37         command = "%s %s" % (export, command)
38
39     if sudo:
40         command = "sudo %s" % command
41     elif user:
42         command = "su %s ; %s " % (user, command)
43
44     proc = subprocess.Popen(command,
45                 shell = True, 
46                 stdout = subprocess.PIPE, 
47                 stderr = subprocess.PIPE)
48
49     out = err = ""
50     log_msg = "lexec - command %s " % command
51
52     try:
53         out, err = proc.communicate()
54         log(log_msg, logging.DEBUG, out, err)
55     except:
56         log(log_msg, logging.ERROR, out, err)
57         raise
58
59     return ((out, err), proc)
60
61 def lcopy(source, dest, recursive = False):
62     """
63     Copies from/to localy.
64     """
65     
66     args = ["cp"]
67     if recursive:
68         args.append("-r")
69   
70     if isinstance(source, list):
71         args.extend(source)
72     else:
73         args.append(source)
74
75     if isinstance(dest, list):
76         args.extend(dest)
77     else:
78         args.append(dest)
79
80     proc = subprocess.Popen(args, 
81         stdout=subprocess.PIPE, 
82         stderr=subprocess.PIPE)
83
84     out = err = ""
85     command = " ".join(args)
86     log_msg = " lcopy - command %s " % command
87
88     try:
89         out, err = proc.communicate()
90         log(log_msg, logging.DEBUG, out, err)
91     except:
92         log(log_msg, logging.ERROR, out, err)
93         raise
94
95     return ((out, err), proc)
96    
97 def lspawn(command, pidfile, 
98         stdout = '/dev/null', 
99         stderr = STDOUT, 
100         stdin = '/dev/null', 
101         home = None, 
102         create_home = False, 
103         sudo = False,
104         user = None): 
105     """
106     Spawn a local command such that it will continue working asynchronously.
107     
108     Parameters:
109         command: the command to run - it should be a single line.
110         
111         pidfile: path of a (ideally unique to this task) pidfile for tracking the process.
112         
113         stdout: path of a file to redirect standard output to - must be a string.
114             Defaults to /dev/null
115         stderr: path of a file to redirect standard error to - string or the special STDOUT value
116             to redirect to the same file stdout was redirected to. Defaults to STDOUT.
117         stdin: path of a file with input to be piped into the command's standard input
118         
119         home: path of a folder to use as working directory - should exist, unless you specify create_home
120         
121         create_home: if True, the home folder will be created first with mkdir -p
122         
123         sudo: whether the command needs to be executed as root
124         
125     Returns:
126         (stdout, stderr), process
127         
128         Of the spawning process, which only captures errors at spawning time.
129         Usually only useful for diagnostics.
130     """
131     # Start process in a "daemonized" way, using nohup and heavy
132     # stdin/out redirection to avoid connection issues
133     if stderr is STDOUT:
134         stderr = '&1'
135     else:
136         stderr = ' ' + stderr
137     
138     daemon_command = '{ { %(command)s  > %(stdout)s 2>%(stderr)s < %(stdin)s & } ; echo $! 1 > %(pidfile)s ; }' % {
139         'command' : command,
140         'pidfile' : shell_escape(pidfile),
141         'stdout' : stdout,
142         'stderr' : stderr,
143         'stdin' : stdin,
144     }
145     
146     cmd = "%(create)s%(gohome)s rm -f %(pidfile)s ; %(sudo)s bash -c %(command)s " % {
147             'command' : shell_escape(daemon_command),
148             'sudo' : 'sudo -S' if sudo else '',
149             'pidfile' : shell_escape(pidfile),
150             'gohome' : 'cd %s ; ' % (shell_escape(home),) if home else '',
151             'create' : 'mkdir -p %s ; ' % (shell_escape(home),) if create_home else '',
152         }
153
154     (out,err), proc = lexec(cmd)
155     
156     if proc.wait():
157         raise RuntimeError, "Failed to set up application on host %s: %s %s" % (host, out,err,)
158
159     return ((out,err), proc)
160
161 def lgetpid(pidfile):
162     """
163     Check the pidfile of a process spawned with remote_spawn.
164     
165     Parameters:
166         pidfile: the pidfile passed to remote_span
167         
168     Returns:
169         
170         A (pid, ppid) tuple useful for calling remote_status and remote_kill,
171         or None if the pidfile isn't valid yet (maybe the process is still starting).
172     """
173
174     (out,err), proc = lexec("cat %s" % pidfile )
175         
176     if proc.wait():
177         return None
178     
179     if out:
180         try:
181             return map(int,out.strip().split(' ',1))
182         except:
183             # Ignore, many ways to fail that don't matter that much
184             return None
185
186 def lstatus(pid, ppid): 
187     """
188     Check the status of a process spawned with remote_spawn.
189     
190     Parameters:
191         pid/ppid: pid and parent-pid of the spawned process. See remote_check_pid
192         
193     Returns:
194         
195         One of NOT_STARTED, RUNNING, FINISHED
196     """
197
198     (out,err), proc = lexec(
199         # Check only by pid. pid+ppid does not always work (especially with sudo) 
200         " (( ps --pid %(pid)d -o pid | grep -c %(pid)d && echo 'wait')  || echo 'done' ) | tail -n 1" % {
201             'ppid' : ppid,
202             'pid' : pid,
203         })
204     
205     if proc.wait():
206         return ProcStatus.NOT_STARTED
207     
208     status = False
209     if out:
210         status = (out.strip() == 'wait')
211     else:
212         return ProcStatus.NOT_STARTED
213
214     return ProcStatus.RUNNING if status else ProcStatus.FINISHED
215
216 def lkill(pid, ppid, sudo = False):
217     """
218     Kill a process spawned with lspawn.
219     
220     First tries a SIGTERM, and if the process does not end in 10 seconds,
221     it sends a SIGKILL.
222     
223     Parameters:
224         pid/ppid: pid and parent-pid of the spawned process. See remote_check_pid
225         
226         sudo: whether the command was run with sudo - careful killing like this.
227     
228     Returns:
229         
230         Nothing, should have killed the process
231     """
232     
233     subkill = "$(ps --ppid %(pid)d -o pid h)" % { 'pid' : pid }
234     cmd = """
235 SUBKILL="%(subkill)s" ;
236 %(sudo)s kill -- -%(pid)d $SUBKILL || /bin/true
237 %(sudo)s kill %(pid)d $SUBKILL || /bin/true
238 for x in 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ; do 
239     sleep 0.2 
240     if [ `ps --pid %(pid)d -o pid | grep -c %(pid)d` == '0' ]; then
241         break
242     else
243         %(sudo)s kill -- -%(pid)d $SUBKILL || /bin/true
244         %(sudo)s kill %(pid)d $SUBKILL || /bin/true
245     fi
246     sleep 1.8
247 done
248 if [ `ps --pid %(pid)d -o pid | grep -c %(pid)d` != '0' ]; then
249     %(sudo)s kill -9 -- -%(pid)d $SUBKILL || /bin/true
250     %(sudo)s kill -9 %(pid)d $SUBKILL || /bin/true
251 fi
252 """
253     if nowait:
254         cmd = "( %s ) >/dev/null 2>/dev/null </dev/null &" % (cmd,)
255
256     (out,err),proc = lexec(
257         cmd % {
258             'ppid' : ppid,
259             'pid' : pid,
260             'sudo' : 'sudo -S' if sudo else '',
261             'subkill' : subkill,
262         })
263     
264