blob: aefb576805c3109af5395c0ad82517243e878365 [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))
Brad Bishop6e60e8b2018-02-01 10:27:11 -050091 return (status, output)
92
93 def copyTo(self, localSrc, remoteDst):
94 """
95 Copy file to target.
96
97 If local file is symlink, recreate symlink in target.
98 """
99 if os.path.islink(localSrc):
100 link = os.readlink(localSrc)
101 dstDir, dstBase = os.path.split(remoteDst)
102 sshCmd = 'cd %s; ln -s %s %s' % (dstDir, link, dstBase)
103 return self.run(sshCmd)
104
105 else:
106 remotePath = '%s@%s:%s' % (self.user, self.ip, remoteDst)
107 scpCmd = self.scp + [localSrc, remotePath]
108 return self._run(scpCmd, ignore_status=False)
109
Andrew Geissler635e0e42020-08-21 15:58:33 -0500110 def copyFrom(self, remoteSrc, localDst, warn_on_failure=False):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500111 """
112 Copy file from target.
113 """
114 remotePath = '%s@%s:%s' % (self.user, self.ip, remoteSrc)
115 scpCmd = self.scp + [remotePath, localDst]
Andrew Geissler635e0e42020-08-21 15:58:33 -0500116 (status, output) = self._run(scpCmd, ignore_status=warn_on_failure)
117 if warn_on_failure and status:
118 self.logger.warning("Copy returned non-zero exit status %d:\n%s" % (status, output))
119 return (status, output)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500120
121 def copyDirTo(self, localSrc, remoteDst):
122 """
123 Copy recursively localSrc directory to remoteDst in target.
124 """
125
126 for root, dirs, files in os.walk(localSrc):
127 # Create directories in the target as needed
128 for d in dirs:
129 tmpDir = os.path.join(root, d).replace(localSrc, "")
130 newDir = os.path.join(remoteDst, tmpDir.lstrip("/"))
131 cmd = "mkdir -p %s" % newDir
132 self.run(cmd)
133
134 # Copy files into the target
135 for f in files:
136 tmpFile = os.path.join(root, f).replace(localSrc, "")
137 dstFile = os.path.join(remoteDst, tmpFile.lstrip("/"))
138 srcFile = os.path.join(root, f)
139 self.copyTo(srcFile, dstFile)
140
141 def deleteFiles(self, remotePath, files):
142 """
143 Deletes files in target's remotePath.
144 """
145
146 cmd = "rm"
147 if not isinstance(files, list):
148 files = [files]
149
150 for f in files:
151 cmd = "%s %s" % (cmd, os.path.join(remotePath, f))
152
153 self.run(cmd)
154
155
156 def deleteDir(self, remotePath):
157 """
158 Deletes target's remotePath directory.
159 """
160
161 cmd = "rmdir %s" % remotePath
162 self.run(cmd)
163
164
165 def deleteDirStructure(self, localPath, remotePath):
166 """
167 Delete recursively localPath structure directory in target's remotePath.
168
169 This function is very usefult to delete a package that is installed in
170 the DUT and the host running the test has such package extracted in tmp
171 directory.
172
173 Example:
174 pwd: /home/user/tmp
175 tree: .
176 └── work
177 ├── dir1
178 │   └── file1
179 └── dir2
180
181 localpath = "/home/user/tmp" and remotepath = "/home/user"
182
183 With the above variables this function will try to delete the
184 directory in the DUT in this order:
185 /home/user/work/dir1/file1
186 /home/user/work/dir1 (if dir is empty)
187 /home/user/work/dir2 (if dir is empty)
188 /home/user/work (if dir is empty)
189 """
190
191 for root, dirs, files in os.walk(localPath, topdown=False):
192 # Delete files first
193 tmpDir = os.path.join(root).replace(localPath, "")
194 remoteDir = os.path.join(remotePath, tmpDir.lstrip("/"))
195 self.deleteFiles(remoteDir, files)
196
197 # Remove dirs if empty
198 for d in dirs:
199 tmpDir = os.path.join(root, d).replace(localPath, "")
200 remoteDir = os.path.join(remotePath, tmpDir.lstrip("/"))
201 self.deleteDir(remoteDir)
202
203def SSHCall(command, logger, timeout=None, **opts):
204
205 def run():
206 nonlocal output
207 nonlocal process
208 starttime = time.time()
209 process = subprocess.Popen(command, **options)
210 if timeout:
211 endtime = starttime + timeout
212 eof = False
213 while time.time() < endtime and not eof:
214 logger.debug('time: %s, endtime: %s' % (time.time(), endtime))
215 try:
216 if select.select([process.stdout], [], [], 5)[0] != []:
Brad Bishopc342db32019-05-15 21:57:59 -0400217 reader = codecs.getreader('utf-8')(process.stdout, 'ignore')
Brad Bishopd5ae7d92018-06-14 09:52:03 -0700218 data = reader.read(1024, 4096)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500219 if not data:
220 process.stdout.close()
221 eof = True
222 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500223 output += data
224 logger.debug('Partial data from SSH call: %s' % data)
225 endtime = time.time() + timeout
226 except InterruptedError:
227 continue
228
229 # process hasn't returned yet
230 if not eof:
231 process.terminate()
232 time.sleep(5)
233 try:
234 process.kill()
235 except OSError:
236 pass
237 endtime = time.time() - starttime
238 lastline = ("\nProcess killed - no output for %d seconds. Total"
239 " running time: %d seconds." % (timeout, endtime))
240 logger.debug('Received data from SSH call %s ' % lastline)
241 output += lastline
242
243 else:
Brad Bishopc342db32019-05-15 21:57:59 -0400244 output = process.communicate()[0].decode('utf-8', errors='ignore')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500245 logger.debug('Data from SSH call: %s' % output.rstrip())
246
247 options = {
248 "stdout": subprocess.PIPE,
249 "stderr": subprocess.STDOUT,
250 "stdin": None,
251 "shell": False,
252 "bufsize": -1,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500253 "start_new_session": True,
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500254 }
255 options.update(opts)
256 output = ''
257 process = None
258
259 # Unset DISPLAY which means we won't trigger SSH_ASKPASS
260 env = os.environ.copy()
261 if "DISPLAY" in env:
262 del env['DISPLAY']
263 options['env'] = env
264
265 try:
266 run()
267 except:
268 # Need to guard against a SystemExit or other exception ocurring
269 # whilst running and ensure we don't leave a process behind.
270 if process.poll() is None:
271 process.kill()
272 logger.debug('Something went wrong, killing SSH process')
273 raise
274 return (process.wait(), output.rstrip())