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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
|
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
import getpass
import os
import pty
import re
import select
import subprocess
import tempfile
import time
import logger
import misc
mock_default = False
def InitCommandExecuter(mock=False):
global mock_default
# Whether to default to a mock command executer or not
mock_default = mock
def GetCommandExecuter(logger_to_set=None, mock=False):
# If the default is a mock executer, always return one.
if mock_default or mock:
return MockCommandExecuter(logger_to_set)
else:
return CommandExecuter(logger_to_set)
class CommandExecuter:
def __init__(self, logger_to_set=None):
if logger_to_set is not None:
self.logger = logger_to_set
else:
self.logger = logger.GetLogger()
def RunCommand(self, cmd, return_output=False, machine=None,
username=None, command_terminator=None,
command_timeout=None,
terminated_timeout=10,
print_to_console=True):
"""Run a command."""
cmd = str(cmd)
self.logger.LogCmd(cmd, machine, username, print_to_console)
if command_terminator and command_terminator.IsTerminated():
self.logger.LogError("Command was terminated!", print_to_console)
if return_output:
return [1, "", ""]
else:
return 1
if machine is not None:
user = ""
if username is not None:
user = username + "@"
cmd = "ssh -t -t %s%s -- '%s'" % (user, machine, cmd)
pty_fds = pty.openpty()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=pty_fds[0], shell=True)
full_stdout = ""
full_stderr = ""
# Pull output from pipes, send it to file/stdout/string
out = err = None
pipes = [p.stdout, p.stderr]
terminated_time = None
started_time = time.time()
while len(pipes):
fds = select.select(pipes, [], [], 0.1)
if command_terminator and command_terminator.IsTerminated():
self.RunCommand("sudo kill -9 " + str(p.pid))
wait = p.wait()
self.logger.LogError("Command was terminated!", print_to_console)
if return_output:
return (p.wait, full_stdout, full_stderr)
else:
return wait
for fd in fds[0]:
if fd == p.stdout:
out = os.read(p.stdout.fileno(), 16384)
if return_output:
full_stdout += out
self.logger.LogCommandOutput(out, print_to_console)
if out == "":
pipes.remove(p.stdout)
if fd == p.stderr:
err = os.read(p.stderr.fileno(), 16384)
if return_output:
full_stderr += err
self.logger.LogCommandError(err, print_to_console)
if err == "":
pipes.remove(p.stderr)
if p.poll() is not None:
if terminated_time is None:
terminated_time = time.time()
elif (terminated_timeout is not None and
time.time() - terminated_time > terminated_timeout):
m = ("Timeout of %s seconds reached since process termination."
% terminated_timeout)
self.logger.LogWarning(m, print_to_console)
break
if (command_timeout is not None and
time.time() - started_time > command_timeout):
m = ("Timeout of %s seconds reached since process started."
% command_timeout)
self.logger.LogWarning(m, print_to_console)
self.RunCommand("kill %d || sudo kill %d || sudo kill -9 %d" %
(p.pid, p.pid, p.pid))
break
if out == err == "":
break
p.wait()
os.close(pty_fds[0])
os.close(pty_fds[1])
if return_output:
return (p.returncode, full_stdout, full_stderr)
return p.returncode
def RemoteAccessInitCommand(self, chromeos_root, machine):
command = ""
command += "\nset -- --remote=" + machine
command += "\n. " + chromeos_root + "/src/scripts/common.sh"
command += "\n. " + chromeos_root + "/src/scripts/remote_access.sh"
command += "\nTMP=$(mktemp -d)"
command += "\nFLAGS \"$@\" || exit 1"
command += "\nremote_access_init"
return command
def WriteToTempShFile(self, contents):
handle, command_file = tempfile.mkstemp(prefix=os.uname()[1],
suffix=".sh")
os.write(handle, "#!/bin/bash\n")
os.write(handle, contents)
os.close(handle)
return command_file
def CrosLearnBoard(self, chromeos_root, machine):
command = self.RemoteAccessInitCommand(chromeos_root, machine)
command += "\nlearn_board"
command += "\necho ${FLAGS_board}"
retval, output, err = self.RunCommand(command, True)
self.logger.LogFatalIf(retval, "learn_board command failed")
return output.split()[-1]
def CrosRunCommand(self, cmd, return_output=False, machine=None,
username=None, command_terminator=None, chromeos_root=None,
command_timeout=None,
terminated_timeout=10,
print_to_console=True):
"""Run a command on a chromeos box"""
self.logger.LogCmd(cmd, print_to_console)
self.logger.LogFatalIf(not machine, "No machine provided!")
self.logger.LogFatalIf(not chromeos_root, "chromeos_root not given!")
chromeos_root = os.path.expanduser(chromeos_root)
# Write all commands to a file.
command_file = self.WriteToTempShFile(cmd)
self.CopyFiles(command_file, command_file,
dest_machine=machine,
command_terminator=command_terminator,
chromeos_root=chromeos_root,
dest_cros=True,
recursive=False)
command = self.RemoteAccessInitCommand(chromeos_root, machine)
command += "\nremote_sh bash %s" % command_file
command += "\necho \"$REMOTE_OUT\""
retval = self.RunCommand(command, return_output,
command_terminator=command_terminator,
command_timeout=command_timeout,
terminated_timeout=terminated_timeout)
if return_output:
connect_signature = ("Initiating first contact with remote host\n" +
"Connection OK\n")
connect_signature_re = re.compile(connect_signature)
modded_return = []
for r in retval:
modded_return.append(r)
modded_return[1] = connect_signature_re.sub("", modded_return[1])
return modded_return
return retval
def ChrootRunCommand(self, chromeos_root, command, return_output=False,
command_terminator=None, command_timeout=None,
terminated_timeout=10,
print_to_console=True):
self.logger.LogCmd(command, print_to_console)
handle, command_file = tempfile.mkstemp(dir=os.path.join(chromeos_root,
"src/scripts"),
suffix=".sh",
prefix="in_chroot_cmd")
os.write(handle, "#!/bin/bash\n")
os.write(handle, command)
os.close(handle)
os.chmod(command_file, 0777)
command = "cd %s; cros_sdk -- ./%s" % (chromeos_root,
os.path.basename(command_file))
ret = self.RunCommand(command, return_output,
command_terminator=command_terminator,
command_timeout=command_timeout,
terminated_timeout=terminated_timeout)
os.remove(command_file)
return ret
def RunCommands(self, cmdlist, return_output=False, machine=None,
username=None, command_terminator=None):
cmd = " ;\n" .join(cmdlist)
return self.RunCommand(cmd, return_output, machine, username,
command_terminator)
def CopyFiles(self, src, dest, src_machine=None, dest_machine=None,
src_user=None, dest_user=None, recursive=True,
command_terminator=None,
chromeos_root=None, src_cros=False, dest_cros=False):
src = os.path.expanduser(src)
dest = os.path.expanduser(dest)
if recursive:
src = src + "/"
dest = dest + "/"
if src_cros == True or dest_cros == True:
self.logger.LogFatalIf(not (src_cros ^ dest_cros), "Only one of src_cros "
"and desc_cros can be non-null.")
self.logger.LogFatalIf(not chromeos_root, "chromeos_root not given!")
if src_cros == True:
cros_machine = src_machine
else:
cros_machine = dest_machine
command = self.RemoteAccessInitCommand(chromeos_root, cros_machine)
src_parent, src_child = misc.GetRoot(src)
dest_parent, dest_child = misc.GetRoot(dest)
ssh_command = ("ssh -p ${FLAGS_ssh_port}" +
" -o StrictHostKeyChecking=no" +
" -o UserKnownHostsFile=$(mktemp)" +
" -i $TMP_PRIVATE_KEY")
rsync_prefix = "\nrsync -r -e \"%s\" " % ssh_command
if dest_cros == True:
command += rsync_prefix + "%s root@%s:%s" % (src, dest_machine, dest)
return self.RunCommand(command,
machine=src_machine,
username=src_user,
command_terminator=command_terminator)
else:
command += rsync_prefix + "root@%s:%s %s" % (src_machine, src, dest)
return self.RunCommand(command,
machine=dest_machine,
username=dest_user,
command_terminator=command_terminator)
if dest_machine == src_machine:
command = ("rsync -a %s %s" %
(src,
dest))
else:
if src_machine is None:
src_machine = os.uname()[1]
src_user = getpass.getuser()
command = ("rsync -a %s@%s:%s %s" %
(src_user, src_machine, src,
dest))
return self.RunCommand(command,
machine=dest_machine,
username=dest_user,
command_terminator=command_terminator)
class MockCommandExecuter(CommandExecuter):
def __init__(self, logger_to_set=None):
if logger is not None:
self.logger = logger_to_set
else:
self.logger = logger.GetLogger()
def RunCommand(self, cmd, return_output=False, machine=None, username=None,
command_terminator=None):
cmd = str(cmd)
if machine is None:
machine = "localhost"
if username is None:
username = "current"
logger.GetLogger().LogCmd("(Mock) " + cmd, machine, username)
return 0
class CommandTerminator:
def __init__(self):
self.terminated = False
def Terminate(self):
self.terminated = True
def IsTerminated(self):
return self.terminated
|