blob: 461448dbc5633c07c9251087da2761f383ffe045 [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 ]
46
47 def start(self, **kwargs):
48 pass
49
50 def stop(self, **kwargs):
51 pass
52
53 def _run(self, command, timeout=None, ignore_status=True):
54 """
55 Runs command in target using SSHProcess.
56 """
57 self.logger.debug("[Running]$ %s" % " ".join(command))
58
59 starttime = time.time()
60 status, output = SSHCall(command, self.logger, timeout)
61 self.logger.debug("[Command returned '%d' after %.2f seconds]"
62 "" % (status, time.time() - starttime))
63
64 if status and not ignore_status:
65 raise AssertionError("Command '%s' returned non-zero exit "
66 "status %d:\n%s" % (command, status, output))
67
68 return (status, output)
69
70 def run(self, command, timeout=None):
71 """
72 Runs command in target.
73
74 command: Command to run on target.
75 timeout: <value>: Kill command after <val> seconds.
76 None: Kill command default value seconds.
77 0: No timeout, runs until return.
78 """
79 targetCmd = 'export PATH=/usr/sbin:/sbin:/usr/bin:/bin; %s' % command
80 sshCmd = self.ssh + [self.ip, targetCmd]
81
82 if timeout:
83 processTimeout = timeout
84 elif timeout==0:
85 processTimeout = None
86 else:
87 processTimeout = self.timeout
88
89 status, output = self._run(sshCmd, processTimeout, True)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050090 self.logger.debug('Command: %s\nOutput: %s\n' % (command, output))
Andrew Geisslerc3d88e42020-10-02 09:45:00 -050091 if (status == 255) and (('No route to host') in output):
92 self.target_dumper.dump_target()
Brad Bishop6e60e8b2018-02-01 10:27:11 -050093 return (status, output)
94
95 def copyTo(self, localSrc, remoteDst):
96 """
97 Copy file to target.
98
99 If local file is symlink, recreate symlink in target.
100 """
101 if os.path.islink(localSrc):
102 link = os.readlink(localSrc)
103 dstDir, dstBase = os.path.split(remoteDst)
104 sshCmd = 'cd %s; ln -s %s %s' % (dstDir, link, dstBase)
105 return self.run(sshCmd)
106
107 else:
108 remotePath = '%s@%s:%s' % (self.user, self.ip, remoteDst)
109 scpCmd = self.scp + [localSrc, remotePath]
110 return self._run(scpCmd, ignore_status=False)
111
Andrew Geissler635e0e42020-08-21 15:58:33 -0500112 def copyFrom(self, remoteSrc, localDst, warn_on_failure=False):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500113 """
114 Copy file from target.
115 """
116 remotePath = '%s@%s:%s' % (self.user, self.ip, remoteSrc)
117 scpCmd = self.scp + [remotePath, localDst]
Andrew Geissler635e0e42020-08-21 15:58:33 -0500118 (status, output) = self._run(scpCmd, ignore_status=warn_on_failure)
119 if warn_on_failure and status:
120 self.logger.warning("Copy returned non-zero exit status %d:\n%s" % (status, output))
121 return (status, output)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500122
123 def copyDirTo(self, localSrc, remoteDst):
124 """
125 Copy recursively localSrc directory to remoteDst in target.
126 """
127
128 for root, dirs, files in os.walk(localSrc):
129 # Create directories in the target as needed
130 for d in dirs:
131 tmpDir = os.path.join(root, d).replace(localSrc, "")
132 newDir = os.path.join(remoteDst, tmpDir.lstrip("/"))
133 cmd = "mkdir -p %s" % newDir
134 self.run(cmd)
135
136 # Copy files into the target
137 for f in files:
138 tmpFile = os.path.join(root, f).replace(localSrc, "")
139 dstFile = os.path.join(remoteDst, tmpFile.lstrip("/"))
140 srcFile = os.path.join(root, f)
141 self.copyTo(srcFile, dstFile)
142
143 def deleteFiles(self, remotePath, files):
144 """
145 Deletes files in target's remotePath.
146 """
147
148 cmd = "rm"
149 if not isinstance(files, list):
150 files = [files]
151
152 for f in files:
153 cmd = "%s %s" % (cmd, os.path.join(remotePath, f))
154
155 self.run(cmd)
156
157
158 def deleteDir(self, remotePath):
159 """
160 Deletes target's remotePath directory.
161 """
162
163 cmd = "rmdir %s" % remotePath
164 self.run(cmd)
165
166
167 def deleteDirStructure(self, localPath, remotePath):
168 """
169 Delete recursively localPath structure directory in target's remotePath.
170
171 This function is very usefult to delete a package that is installed in
172 the DUT and the host running the test has such package extracted in tmp
173 directory.
174
175 Example:
176 pwd: /home/user/tmp
177 tree: .
178 └── work
179 ├── dir1
180 │   └── file1
181 └── dir2
182
183 localpath = "/home/user/tmp" and remotepath = "/home/user"
184
185 With the above variables this function will try to delete the
186 directory in the DUT in this order:
187 /home/user/work/dir1/file1
188 /home/user/work/dir1 (if dir is empty)
189 /home/user/work/dir2 (if dir is empty)
190 /home/user/work (if dir is empty)
191 """
192
193 for root, dirs, files in os.walk(localPath, topdown=False):
194 # Delete files first
195 tmpDir = os.path.join(root).replace(localPath, "")
196 remoteDir = os.path.join(remotePath, tmpDir.lstrip("/"))
197 self.deleteFiles(remoteDir, files)
198
199 # Remove dirs if empty
200 for d in dirs:
201 tmpDir = os.path.join(root, d).replace(localPath, "")
202 remoteDir = os.path.join(remotePath, tmpDir.lstrip("/"))
203 self.deleteDir(remoteDir)
204
205def SSHCall(command, logger, timeout=None, **opts):
206
207 def run():
208 nonlocal output
209 nonlocal process
210 starttime = time.time()
211 process = subprocess.Popen(command, **options)
212 if timeout:
213 endtime = starttime + timeout
214 eof = False
215 while time.time() < endtime and not eof:
216 logger.debug('time: %s, endtime: %s' % (time.time(), endtime))
217 try:
218 if select.select([process.stdout], [], [], 5)[0] != []:
Brad Bishopc342db32019-05-15 21:57:59 -0400219 reader = codecs.getreader('utf-8')(process.stdout, 'ignore')
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700220 data = reader.read(1024, 4096)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500221 if not data:
222 process.stdout.close()
223 eof = True
224 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500225 output += data
226 logger.debug('Partial data from SSH call: %s' % data)
227 endtime = time.time() + timeout
228 except InterruptedError:
229 continue
230
231 # process hasn't returned yet
232 if not eof:
233 process.terminate()
234 time.sleep(5)
235 try:
236 process.kill()
237 except OSError:
238 pass
239 endtime = time.time() - starttime
240 lastline = ("\nProcess killed - no output for %d seconds. Total"
241 " running time: %d seconds." % (timeout, endtime))
242 logger.debug('Received data from SSH call %s ' % lastline)
243 output += lastline
244
245 else:
Brad Bishopc342db32019-05-15 21:57:59 -0400246 output = process.communicate()[0].decode('utf-8', errors='ignore')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500247 logger.debug('Data from SSH call: %s' % output.rstrip())
248
249 options = {
250 "stdout": subprocess.PIPE,
251 "stderr": subprocess.STDOUT,
252 "stdin": None,
253 "shell": False,
254 "bufsize": -1,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500255 "start_new_session": True,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500256 }
257 options.update(opts)
258 output = ''
259 process = None
260
261 # Unset DISPLAY which means we won't trigger SSH_ASKPASS
262 env = os.environ.copy()
263 if "DISPLAY" in env:
264 del env['DISPLAY']
265 options['env'] = env
266
267 try:
268 run()
269 except:
270 # Need to guard against a SystemExit or other exception ocurring
271 # whilst running and ensure we don't leave a process behind.
272 if process.poll() is None:
273 process.kill()
274 logger.debug('Something went wrong, killing SSH process')
275 raise
276 return (process.wait(), output.rstrip())