1 # Copyright 2016 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
6 from recipe_engine import recipe_api
11 """SSH flavor, used for running code on a remote device via SSH.
13 Must be subclassed to set self.device_dirs. The default implementation assumes
18 class SSHFlavor(default.DefaultFlavor):
20 def __init__(self, m, app_name):
21 super(SSHFlavor, self).__init__(m, app_name)
27 path = '/tmp/ssh_machine.json'
28 ssh_info = self.m.file.read_json('read ssh_machine.json', path,
29 test_data={'user_ip':'foo@127.0.0.1'})
30 self._user_ip = ssh_info.get(u'user_ip')
33 def ssh(self, title, *cmd, **kwargs):
34 if 'infra_step' not in kwargs:
35 kwargs['infra_step'] = True
37 ssh_cmd = ['ssh', '-oConnectTimeout=15', '-oBatchMode=yes',
38 '-t', '-t', self.user_ip] + list(cmd)
40 return self._run(title, ssh_cmd, **kwargs)
42 def ensure_device_dir(self, path):
43 self.ssh('mkdir %s' % path, 'mkdir', '-p', path)
46 self.ensure_device_dir(self.device_dirs.resource_dir)
48 self.create_clean_device_dir(self.device_dirs.bin_dir)
49 host_path = self.host_dirs.bin_dir.join(self.app_name)
50 device_path = self.device_path_join(self.device_dirs.bin_dir, self.app_name)
51 self.copy_file_to_device(host_path, device_path)
52 self.ssh('make %s executable' % self.app_name, 'chmod', '+x', device_path)
54 def create_clean_device_dir(self, path):
55 # use -f to silently return if path doesn't exist
56 self.ssh('rm %s' % path, 'rm', '-rf', path)
57 self.ensure_device_dir(path)
59 def read_file_on_device(self, path, **kwargs):
60 rv = self.ssh('read %s' % path,
61 'cat', path, stdout=self.m.raw_io.output(),
63 return rv.stdout.decode('utf-8').rstrip() if rv and rv.stdout else None
65 def remove_file_on_device(self, path):
66 # use -f to silently return if path doesn't exist
67 self.ssh('rm %s' % path, 'rm', '-f', path)
69 def scp_device_path(self, device_path):
70 return '%s:%s' % (self.user_ip, device_path)
72 def copy_file_to_device(self, host_path, device_path):
73 device_path = self.scp_device_path(device_path)
74 self._run('scp %s %s' % (host_path, device_path),
75 ['scp', host_path, device_path], infra_step=True)
77 # TODO(benjaminwagner): implement with rsync
78 #def copy_directory_contents_to_device(self, host_path, device_path):
80 # TODO(benjaminwagner): implement with rsync
81 #def copy_directory_contents_to_host(self, device_path, host_path):
83 def step(self, name, cmd, **kwargs):
84 # Run cmd (installed above)
85 cmd[0] = self.device_path_join(self.device_dirs.bin_dir, cmd[0])
86 self.ssh(str(name), *cmd)