blob: 923a223b25bd3d34de23ba51ca05536ebb027ef0 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Brad Bishop6e60e8b2018-02-01 10:27:11 -05002# Copyright (C) 2016 Intel Corporation
Brad Bishopc342db32019-05-15 21:57:59 -04003#
4# SPDX-License-Identifier: MIT
5#
Brad Bishop6e60e8b2018-02-01 10:27:11 -05006
7import os
8import time
9import select
10import logging
11import subprocess
Brad Bishopd7bf8c12018-02-25 22:55:05 -050012import codecs
Brad Bishop6e60e8b2018-02-01 10:27:11 -050013
14from . import OETarget
15
16class OESSHTarget(OETarget):
17 def __init__(self, logger, ip, server_ip, timeout=300, user='root',
Andrew Geissler82c905d2020-04-13 13:39:40 -050018 port=None, server_port=0, **kwargs):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050019 if not logger:
20 logger = logging.getLogger('target')
21 logger.setLevel(logging.INFO)
22 filePath = os.path.join(os.getcwd(), 'remoteTarget.log')
23 fileHandler = logging.FileHandler(filePath, 'w', 'utf-8')
24 formatter = logging.Formatter(
25 '%(asctime)s.%(msecs)03d %(levelname)s: %(message)s',
26 '%H:%M:%S')
27 fileHandler.setFormatter(formatter)
28 logger.addHandler(fileHandler)
29
30 super(OESSHTarget, self).__init__(logger)
31 self.ip = ip
32 self.server_ip = server_ip
Andrew Geissler82c905d2020-04-13 13:39:40 -050033 self.server_port = server_port
Brad Bishop6e60e8b2018-02-01 10:27:11 -050034 self.timeout = timeout
35 self.user = user
36 ssh_options = [
37 '-o', 'UserKnownHostsFile=/dev/null',
38 '-o', 'StrictHostKeyChecking=no',
39 '-o', 'LogLevel=ERROR'
40 ]
41 self.ssh = ['ssh', '-l', self.user ] + ssh_options
42 self.scp = ['scp'] + ssh_options
43 if port:
44 self.ssh = self.ssh + [ '-p', port ]
45 self.scp = self.scp + [ '-P', port ]
Andrew Geisslerc926e172021-05-07 16:11:35 -050046 self._monitor_dumper = None
Brad Bishop6e60e8b2018-02-01 10:27:11 -050047
48 def start(self, **kwargs):
49 pass
50
51 def stop(self, **kwargs):
52 pass
53
Andrew Geisslerc926e172021-05-07 16:11:35 -050054 @property
55 def monitor_dumper(self):
56 return self._monitor_dumper
57
58 @monitor_dumper.setter
59 def monitor_dumper(self, dumper):
60 self._monitor_dumper = dumper
61 self.monitor_dumper.dump_monitor()
62
Brad Bishop6e60e8b2018-02-01 10:27:11 -050063 def _run(self, command, timeout=None, ignore_status=True):
64 """
65 Runs command in target using SSHProcess.
66 """
67 self.logger.debug("[Running]$ %s" % " ".join(command))
68
69 starttime = time.time()
70 status, output = SSHCall(command, self.logger, timeout)
71 self.logger.debug("[Command returned '%d' after %.2f seconds]"
72 "" % (status, time.time() - starttime))
73
74 if status and not ignore_status:
75 raise AssertionError("Command '%s' returned non-zero exit "
76 "status %d:\n%s" % (command, status, output))
77
78 return (status, output)
79
80 def run(self, command, timeout=None):
81 """
82 Runs command in target.
83
84 command: Command to run on target.
85 timeout: <value>: Kill command after <val> seconds.
86 None: Kill command default value seconds.
87 0: No timeout, runs until return.
88 """
89 targetCmd = 'export PATH=/usr/sbin:/sbin:/usr/bin:/bin; %s' % command
90 sshCmd = self.ssh + [self.ip, targetCmd]
91
92 if timeout:
93 processTimeout = timeout
94 elif timeout==0:
95 processTimeout = None
96 else:
97 processTimeout = self.timeout
98
99 status, output = self._run(sshCmd, processTimeout, True)
Andrew Geisslerc926e172021-05-07 16:11:35 -0500100 self.logger.debug('Command: %s\nStatus: %d Output: %s\n' % (command, status, output))
Andrew Geisslerc3d88e42020-10-02 09:45:00 -0500101 if (status == 255) and (('No route to host') in output):
Andrew Geisslerc926e172021-05-07 16:11:35 -0500102 if self.monitor_dumper:
103 self.monitor_dumper.dump_monitor()
104 if status == 255:
Andrew Geisslerc3d88e42020-10-02 09:45:00 -0500105 self.target_dumper.dump_target()
Andrew Geisslerc926e172021-05-07 16:11:35 -0500106 if self.monitor_dumper:
107 self.monitor_dumper.dump_monitor()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500108 return (status, output)
109
110 def copyTo(self, localSrc, remoteDst):
111 """
112 Copy file to target.
113
114 If local file is symlink, recreate symlink in target.
115 """
116 if os.path.islink(localSrc):
117 link = os.readlink(localSrc)
118 dstDir, dstBase = os.path.split(remoteDst)
119 sshCmd = 'cd %s; ln -s %s %s' % (dstDir, link, dstBase)
120 return self.run(sshCmd)
121
122 else:
123 remotePath = '%s@%s:%s' % (self.user, self.ip, remoteDst)
124 scpCmd = self.scp + [localSrc, remotePath]
125 return self._run(scpCmd, ignore_status=False)
126
Andrew Geissler635e0e42020-08-21 15:58:33 -0500127 def copyFrom(self, remoteSrc, localDst, warn_on_failure=False):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500128 """
129 Copy file from target.
130 """
131 remotePath = '%s@%s:%s' % (self.user, self.ip, remoteSrc)
132 scpCmd = self.scp + [remotePath, localDst]
Andrew Geissler635e0e42020-08-21 15:58:33 -0500133 (status, output) = self._run(scpCmd, ignore_status=warn_on_failure)
134 if warn_on_failure and status:
135 self.logger.warning("Copy returned non-zero exit status %d:\n%s" % (status, output))
136 return (status, output)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500137
138 def copyDirTo(self, localSrc, remoteDst):
139 """
140 Copy recursively localSrc directory to remoteDst in target.
141 """
142
143 for root, dirs, files in os.walk(localSrc):
144 # Create directories in the target as needed
145 for d in dirs:
146 tmpDir = os.path.join(root, d).replace(localSrc, "")
147 newDir = os.path.join(remoteDst, tmpDir.lstrip("/"))
148 cmd = "mkdir -p %s" % newDir
149 self.run(cmd)
150
151 # Copy files into the target
152 for f in files:
153 tmpFile = os.path.join(root, f).replace(localSrc, "")
154 dstFile = os.path.join(remoteDst, tmpFile.lstrip("/"))
155 srcFile = os.path.join(root, f)
156 self.copyTo(srcFile, dstFile)
157
158 def deleteFiles(self, remotePath, files):
159 """
160 Deletes files in target's remotePath.
161 """
162
163 cmd = "rm"
164 if not isinstance(files, list):
165 files = [files]
166
167 for f in files:
168 cmd = "%s %s" % (cmd, os.path.join(remotePath, f))
169
170 self.run(cmd)
171
172
173 def deleteDir(self, remotePath):
174 """
175 Deletes target's remotePath directory.
176 """
177
178 cmd = "rmdir %s" % remotePath
179 self.run(cmd)
180
181
182 def deleteDirStructure(self, localPath, remotePath):
183 """
184 Delete recursively localPath structure directory in target's remotePath.
185
186 This function is very usefult to delete a package that is installed in
187 the DUT and the host running the test has such package extracted in tmp
188 directory.
189
190 Example:
191 pwd: /home/user/tmp
192 tree: .
193 └── work
194 ├── dir1
195 │   └── file1
196 └── dir2
197
198 localpath = "/home/user/tmp" and remotepath = "/home/user"
199
200 With the above variables this function will try to delete the
201 directory in the DUT in this order:
202 /home/user/work/dir1/file1
203 /home/user/work/dir1 (if dir is empty)
204 /home/user/work/dir2 (if dir is empty)
205 /home/user/work (if dir is empty)
206 """
207
208 for root, dirs, files in os.walk(localPath, topdown=False):
209 # Delete files first
210 tmpDir = os.path.join(root).replace(localPath, "")
211 remoteDir = os.path.join(remotePath, tmpDir.lstrip("/"))
212 self.deleteFiles(remoteDir, files)
213
214 # Remove dirs if empty
215 for d in dirs:
216 tmpDir = os.path.join(root, d).replace(localPath, "")
217 remoteDir = os.path.join(remotePath, tmpDir.lstrip("/"))
218 self.deleteDir(remoteDir)
219
220def SSHCall(command, logger, timeout=None, **opts):
221
222 def run():
223 nonlocal output
224 nonlocal process
225 starttime = time.time()
226 process = subprocess.Popen(command, **options)
227 if timeout:
228 endtime = starttime + timeout
229 eof = False
230 while time.time() < endtime and not eof:
231 logger.debug('time: %s, endtime: %s' % (time.time(), endtime))
232 try:
233 if select.select([process.stdout], [], [], 5)[0] != []:
Brad Bishopc342db32019-05-15 21:57:59 -0400234 reader = codecs.getreader('utf-8')(process.stdout, 'ignore')
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700235 data = reader.read(1024, 4096)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500236 if not data:
237 process.stdout.close()
238 eof = True
239 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500240 output += data
241 logger.debug('Partial data from SSH call: %s' % data)
242 endtime = time.time() + timeout
243 except InterruptedError:
244 continue
245
246 # process hasn't returned yet
247 if not eof:
248 process.terminate()
249 time.sleep(5)
250 try:
251 process.kill()
252 except OSError:
253 pass
254 endtime = time.time() - starttime
255 lastline = ("\nProcess killed - no output for %d seconds. Total"
256 " running time: %d seconds." % (timeout, endtime))
257 logger.debug('Received data from SSH call %s ' % lastline)
258 output += lastline
259
260 else:
Brad Bishopc342db32019-05-15 21:57:59 -0400261 output = process.communicate()[0].decode('utf-8', errors='ignore')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500262 logger.debug('Data from SSH call: %s' % output.rstrip())
263
264 options = {
265 "stdout": subprocess.PIPE,
266 "stderr": subprocess.STDOUT,
267 "stdin": None,
268 "shell": False,
269 "bufsize": -1,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500270 "start_new_session": True,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500271 }
272 options.update(opts)
273 output = ''
274 process = None
275
276 # Unset DISPLAY which means we won't trigger SSH_ASKPASS
277 env = os.environ.copy()
278 if "DISPLAY" in env:
279 del env['DISPLAY']
280 options['env'] = env
281
282 try:
283 run()
284 except:
285 # Need to guard against a SystemExit or other exception ocurring
286 # whilst running and ensure we don't leave a process behind.
287 if process.poll() is None:
288 process.kill()
289 logger.debug('Something went wrong, killing SSH process')
290 raise
291 return (process.wait(), output.rstrip())