gdb_dejagnu.py revision f5533e3b5edce07360f6362569f51c726e7ff838
1#! /usr/bin/python
2
3# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7import getpass
8import optparse
9import os
10from os import path
11import re
12import shutil
13import stat
14import sys
15import tempfile
16import time
17
18import lock_machine
19import tc_enter_chroot
20
21from utils import command_executer
22from utils import constants
23from utils import logger
24from utils import misc
25
26
27def ProcessArguments(argv):
28  """Processing/validating script arguments."""
29  parser = optparse.OptionParser(description=(
30      'Launches gdb dejagnu test in chroot for chromeos toolchain, compares '
31      'the test result with a repository baseline and prints out the result.'),
32                                 usage='run_dejagnu options')
33  parser.add_option('-c', '--chromeos_root', dest='chromeos_root',
34                    help='Required. Specify chromeos root')
35  parser.add_option('-m', '--mount', dest='mount',
36                    help=('Specify gdb source to mount instead of "auto". '
37                          'Under "auto" mode, which is the default - gdb is '
38                          'checked out and built automatically at default '
39                          'directories. Under "mount" mode '
40                          '- the gdb_source is set to "$chromeos_'
41                          'root/chroot/usr/local/toolchain_root/gdb", which is '
42                          'the mount point for this option value.'))
43  parser.add_option('-b', '--board', dest='board',
44                    help=('Required. Specify board.'))
45  parser.add_option('-r', '--remote', dest='remote',
46                    help=('Required. Specify addresses/names of the board, '
47                          'seperate each address/name using comma(\',\').'))
48  parser.add_option('--cleanup', dest='cleanup', default=None,
49                    help=('Optional. Values to this option could be '
50                          '\'chroot\' (delete chroot) and '
51                          '\'chromeos\' (delete the whole chromeos tree).'))
52
53  options, args = parser.parse_args(argv)
54
55  if not options.chromeos_root:
56    raise Exception('Missing argument for --chromeos_root.')
57  if not options.remote:
58    raise Exception('Missing argument for --remote.')
59  if not options.board:
60    raise Exception('Missing argument for --board.')
61  if options.cleanup == 'mount' and not options.mount:
62    raise Exception('--cleanup=\'mount\' not valid unless --mount is given.')
63  if options.cleanup and not (
64    options.cleanup == 'mount' or \
65      options.cleanup == 'chroot' or options.cleanup == 'chromeos'):
66    raise Exception('Invalid option value for --cleanup')
67  if options.cleanup and options.keep_intermediate_files:
68    raise Exception('Only one of --keep and --cleanup could be given.')
69
70  return options
71
72
73class DejagnuExecuter(object):
74  """The class wrapper for dejagnu test executer."""
75
76  def __init__(self, base_dir, source_dir, chromeos_root, remote, board,
77               tools, cleanup):
78    self._l = logger.GetLogger()
79    self._chromeos_root = chromeos_root
80    self._chromeos_chroot = path.join(chromeos_root, 'chroot')
81
82    self._remote = remote
83    self._board = board
84    ## Compute target from board
85    self._target = misc.GetCtargetFromBoard(board, chromeos_root)
86    if not self._target:
87      raise Exception('Unsupported board "%s"' % board)
88    self._executer = command_executer.GetCommandExecuter()
89    self._base_dir = base_dir
90    self._tmp_abs = None
91    self._tools = tools.split(',')
92    self._cleanup = cleanup
93    self._sshflag = " -o StrictHostKeyChecking=no -o CheckHostIP=no"
94
95    if source_dir:
96      self._source_dir = source_dir
97      self._mount_flag = 'USE="mounted_sources"'
98      self.MountSource()
99    else:
100      self._source_dir = None
101      self._mount_flag = ''
102
103
104  def SetupTestingDir(self):
105    self._tmp_abs = tempfile.mkdtemp(prefix='dejagnu_', dir=path.join(
106        self._chromeos_chroot, 'tmp'))
107    self._tmp = self._tmp_abs[len(self._chromeos_chroot):]
108    self._tmp_testing_rsa = path.join(self._tmp, 'testing_rsa')
109    self._tmp_testing_rsa_abs = path.join(self._tmp_abs, 'testing_rsa')
110
111  def PrepareTestingRsaKeys(self):
112    if not path.isfile(self._tmp_testing_rsa_abs):
113      shutil.copy(path.join(
114          self._chromeos_root,
115          'src/scripts/mod_for_test_scripts/ssh_keys/testing_rsa'),
116                  self._tmp_testing_rsa_abs)
117      os.chmod(self._tmp_testing_rsa_abs, stat.S_IRUSR)
118
119  def PrepareTestFiles(self):
120    """Prepare site.exp and board exp files."""
121    # Create the boards directory.
122    os.mkdir('%s/boards' % self._tmp_abs)
123
124    # Generate the chromeos.exp file.
125    with open('%s/boards/gdb.exp.in' % self._base_dir, 'r') as template_file:
126      content = template_file.read()
127    substitutions = dict({
128        '__boardname__': self._board,
129        '__board_hostname__': self._remote,
130        '__tmp_testing_rsa__': self._tmp_testing_rsa,
131        '__tmp_dir__': self._tmp})
132    for pat, sub in substitutions.items():
133      content = content.replace(pat, sub)
134
135    board_file_name = '%s/boards/%s.exp' % (self._tmp_abs, self._board)
136    with open(board_file_name, 'w') as board_file:
137      board_file.write(content)
138
139    # Generate the site file
140    with open('%s/site.exp' % self._tmp_abs, 'w') as site_file:
141      site_file.write('set target_list "%s"\n' % self._board)
142
143    with open('%s/boards/gdbserver.sh.in' % self._base_dir, 'r')
144    as template_file:
145      content = template_file.read()
146    substitutions = dict({
147        '__board_hostname__': self._remote,
148        '__tmp_testing_rsa__': self._tmp_testing_rsa,
149         '__tmp_dir__': self._tmp})
150    for pat, sub in substitutions.items():
151      content = content.replace(pat, sub)
152
153    gdbserver_file_name = '%s/boards/gdbserver.sh' % (self._tmp_abs)
154    with open(gdbserver_file_name, 'w') as board_file:
155      board_file.write(content)
156
157    st = os.stat(gdbserver_file_name)
158    os.chmod(gdbserver_file_name, st.st_mode | stat.S_IXGRP | stat.S_IXUSR)
159
160  def PrepareGdb(self):
161    self.PrepareGdbDefault()
162
163  def PrepareGdbDefault(self):
164    ret = self._executer.ChrootRunCommand(
165        self._chromeos_root,
166        'equery w cross-%s/gdb' % self._target, return_output=True)[1]
167    ret = path.basename(ret.strip())
168
169    matcher = re.match(r'(.*).ebuild', ret)
170    if matcher:
171      gdb_reversion = matcher.group(1)
172    else:
173      raise Exception('Failed to get gdb reversion.')
174    gdb_version=gdb_reversion.split('-r')[0]
175    gdb_portage_dir = '/var/tmp/portage/cross-%s/%s/work' % (
176        self._target, gdb_reversion)
177    self._gdb_source_dir = path.join(gdb_portage_dir, gdb_version)
178
179    ret = self._executer.ChrootRunCommand(
180        self._chromeos_root,
181        ('sudo %s ebuild $(equery w cross-%s/gdb) clean compile' % (
182            self._mount_flag, self._target)))
183    if ret:
184      raise Exception('ebuild gdb failed.')
185
186  def PrepareGdbserver(self):
187    self.PrepareGdbserverDefault()
188
189  def PrepareGdbserverDefault(self):
190    cmd = ('./setup_board --board {0}; '
191           '{1} emerge-{0} gdb'.format(self._board, self._mount_flag))
192    ret = self._executer.ChrootRunCommand(
193        self._chromeos_root,
194        cmd, print_to_console=True)
195    if ret:
196      raise Exception('ebuild gdbserver failed.')
197
198    cmd = ('scp -i {0}  {1} '
199           '/build/{2}/usr/bin/gdbserver root@{3}:/usr/local/bin/'
200           .format(self._tmp_testing_rsa, self._sshflag,
201                   self._board, self._remote))
202    ret = self._executer.ChrootRunCommand(
203        self._chromeos_root,
204        cmd, print_to_console=True)
205    if ret:
206      raise Exception('copy gdbserver failed.')
207
208    if self._mount_flag:
209      self.MountSource(unmount=False)
210
211
212  def Cleanup(self):
213    if not self._cleanup:
214      return
215
216    if self._cleanup == 'chroot' or self._cleanup == 'chromeos':
217      self._l.LogOutput('[Cleanup]: Deleting chroot inside \'{0}\''.format(
218        self._chromeos_root))
219      command = "cd %s; cros_sdk --delete" % self._chromeos_root
220      rv = self._executer.RunCommand(command)
221      if rv:
222        self._l.LogWarning('Warning - failed to delete chroot.')
223      # Delete .cache - crosbug.com/34956
224      command = "sudo rm -fr %s" % os.path.join(self._chromeos_root, ".cache")
225      rv = self._executer.RunCommand(command)
226      if rv:
227        self._l.LogWarning('Warning - failed to delete \'.cache\'.')
228
229    if self._cleanup == 'chromeos':
230      self._l.LogOutput('[Cleanup]: Deleting chromeos tree \'{0}\' ...'.format(
231        self._chromeos_root))
232      command = 'rm -fr {0}'.format(self._chromeos_root)
233      rv = self._executer.RunCommand(command)
234      if rv:
235        self._l.LogWarning('Warning - failed to remove chromeos tree.')
236
237  def MakeCheck(self):
238    cmd = ('ssh -i {0} {1}  root@{2} "reboot && exit"'
239           .format(self._tmp_testing_rsa, self._sshflag,
240                   self._remote))
241    self._executer.ChrootRunCommand(
242        self._chromeos_root, cmd)
243    time.sleep(40)
244
245    cmd = ('ssh -i {0} {1}  root@{2} '
246           '"iptables -A INPUT -p tcp --dport 1234 -j ACCEPT"'
247           .format(self._tmp_testing_rsa, self._sshflag,
248                   self._remote
249                   ))
250    self._executer.ChrootRunCommand(
251        self._chromeos_root, cmd)
252
253    cmd = ('cd %s ; '
254           'DEJAGNU=%s make check' %
255           (path.join(self._gdb_source_dir, 'gdb'),
256            path.join(self._tmp, 'site.exp')))
257    ret = self._executer.ChrootRunCommand(
258        self._chromeos_root, cmd)
259    if ret:
260      raise Exception('Make check failed.')
261
262  # This method ensures necessary mount points before executing chroot comamnd.
263  def MountSource(self, unmount=False):
264    script = os.path.join(self._base_dir, 'build_tc.py')
265    if unmount:
266      mount = '-u'
267    else:
268      mount = '-m'
269    cmd = ('python {0} --chromeos_root={1} '
270           '--gdb_dir={2} --board={3} {4}'
271           .format(script, self._chromeos_root,
272                   self._source_dir, self._board,
273                   mount))
274
275
276def Main(argv):
277  opts = ProcessArguments(argv)
278  available_machine = opts.remote
279  executer = DejagnuExecuter(misc.GetRoot(argv[0])[0],
280                             opts.mount, opts.chromeos_root,
281                             available_machine,
282                             opts.board, opts.flags,
283                             opts.keep_intermediate_files, "",
284                             opts.cleanup)
285  # Return value is a 3- or 4-element tuple
286  #   element#1 - exit code
287  #   element#2 - stdout
288  #   element#3 - stderr
289  #   element#4 - exception infor
290  # Some other scripts need these detailed information.
291  ret = (1, '', '')
292  try:
293    executer.SetupTestingDir()
294    executer.PrepareTestingRsaKeys()
295    executer.PrepareTestFiles()
296    executer.PrepareGdb()
297    executer.PrepareGdbserver()
298    executer.MakeCheck()
299   # ret = executer.ValidateFailures()
300  except Exception as e:
301    # At least log the exception on console.
302    print e
303    # The #4 element encodes the runtime exception.
304    ret = (1, '', '', 'Exception happened during execution: \n' + str(e))
305  finally:
306    #available_machine.Unlock(exclusive=True)
307    #executer.CleanupIntermediateFiles()
308    #executer.Cleanup()
309    return ret
310
311if __name__ == '__main__':
312  retval = Main(sys.argv)[0]
313  sys.exit(retval)
314D
315