gdb_dejagnu.py revision 036c9233742004aa773a374df381b1cf137484f5
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
7"""The gdb dejagnu test wrapper."""
8import optparse
9import os
10from os import path
11import re
12import shutil
13import stat
14import sys
15import tempfile
16import time
17
18from utils import command_executer
19from utils import logger
20from utils import misc
21
22from run_dejagnu import TryAcquireMachine
23
24_VALID_TEST_RESULTS = ['FAIL', 'UNRESOLVED', 'XPASS',
25                       'ERROR', 'UNSUPPORTED', 'PASS']
26
27
28def ProcessArguments(argv):
29  """Processing/validating script arguments."""
30  parser = optparse.OptionParser(description=(
31      'Launches gdb dejagnu test in chroot for chromeos toolchain, compares '
32      'the test result with a repository baseline and prints out the result.'),
33                                 usage='run_dejagnu options')
34  parser.add_option('-c', '--chromeos_root', dest='chromeos_root',
35                    help='Required. Specify chromeos root')
36  parser.add_option('-m', '--mount', dest='mount',
37                    help=('Specify gdb source to mount instead of "auto". '
38                          'Under "auto" mode, which is the default - gdb is '
39                          'checked out and built automatically at default '
40                          'directories. Under "mount" mode '
41                          '- the gdb_source is set to "$chromeos_'
42                          'root/chroot/usr/local/toolchain_root/gdb", which is '
43                          'the mount point for this option value.'))
44  parser.add_option('-b', '--board', dest='board',
45                    help=('Required. Specify board.'))
46  parser.add_option('-r', '--remote', dest='remote',
47                    help=('Required. Specify addresses/names of the board, '
48                          'seperate each address/name using comma(\',\').'))
49  parser.add_option('--cleanup', dest='cleanup', default=None,
50                    help=('Optional. Values to this option could be '
51                          '\'chroot\' (delete chroot) and '
52                          '\'chromeos\' (delete the whole chromeos tree).'))
53
54  options, args = parser.parse_args(argv)
55
56  if not options.chromeos_root:
57    raise Exception('Missing argument for --chromeos_root.')
58  if not options.remote:
59    raise Exception('Missing argument for --remote.')
60  if not options.board:
61    raise Exception('Missing argument for --board.')
62  if options.cleanup == 'mount' and not options.mount:
63    raise Exception('--cleanup=\'mount\' not valid unless --mount is given.')
64  if options.cleanup and not (
65      options.cleanup == 'mount' or
66      options.cleanup == 'chroot' or options.cleanup == 'chromeos'):
67    raise Exception('Invalid option value for --cleanup')
68
69  return options
70
71
72class DejagnuExecuter(object):
73  """The class wrapper for dejagnu test executer."""
74
75  def __init__(self, base_dir, source_dir, chromeos_root, remote, board,
76               cleanup):
77    self._l = logger.GetLogger()
78    self._chromeos_root = chromeos_root
79    self._chromeos_chroot = path.join(chromeos_root, 'chroot')
80
81    self._remote = remote
82    self._board = board
83    ## Compute target from board
84    self._target = misc.GetCtargetFromBoard(board, chromeos_root)
85    if not self._target:
86      raise Exception('Unsupported board "%s"' % board)
87    self._executer = command_executer.GetCommandExecuter()
88    self._base_dir = base_dir
89    self._tmp_abs = None
90    self._cleanup = cleanup
91    self._sshflag = ('-o StrictHostKeyChecking=no ' +
92                     '-o CheckHostIP=no ' +
93                     '-o UserKnownHostsFile=$(mktemp) ')
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  def SetupTestingDir(self):
104    self._tmp_abs = tempfile.mkdtemp(prefix='dejagnu_', dir=path.join(
105        self._chromeos_chroot, 'tmp'))
106    self._tmp = self._tmp_abs[len(self._chromeos_chroot):]
107    self._tmp_testing_rsa = path.join(self._tmp, 'testing_rsa')
108    self._tmp_testing_rsa_abs = path.join(self._tmp_abs, 'testing_rsa')
109
110  def PrepareTestingRsaKeys(self):
111    if not path.isfile(self._tmp_testing_rsa_abs):
112      shutil.copy(path.join(
113          self._chromeos_root,
114          'src/scripts/mod_for_test_scripts/ssh_keys/testing_rsa'),
115                  self._tmp_testing_rsa_abs)
116      os.chmod(self._tmp_testing_rsa_abs, stat.S_IRUSR)
117
118  def PrepareTestFiles(self):
119    """Prepare site.exp and board exp files."""
120    # Create the boards directory.
121    os.mkdir('%s/boards' % self._tmp_abs)
122
123    # Generate the chromeos.exp file.
124    with open('%s/boards/gdb.exp.in' % self._base_dir, 'r') as template_file:
125      content = template_file.read()
126
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.ChrootRunCommandWOutput(
165        self._chromeos_root,
166        'equery w cross-%s/gdb' % self._target)[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  def Cleanup(self):
212    if not self._cleanup:
213      return
214
215    if self._cleanup == 'chroot' or self._cleanup == 'chromeos':
216      self._l.LogOutput('[Cleanup]: Deleting chroot inside \'{0}\''.format(
217          self._chromeos_root))
218      command = 'cd %s; cros_sdk --delete' % self._chromeos_root
219      rv = self._executer.RunCommand(command)
220      if rv:
221        self._l.LogWarning('Warning - failed to delete chroot.')
222      # Delete .cache - crosbug.com/34956
223      command = 'sudo rm -fr %s' % os.path.join(self._chromeos_root, '.cache')
224      rv = self._executer.RunCommand(command)
225      if rv:
226        self._l.LogWarning('Warning - failed to delete \'.cache\'.')
227
228    if self._cleanup == 'chromeos':
229      self._l.LogOutput('[Cleanup]: Deleting chromeos tree \'{0}\' ...'.format(
230          self._chromeos_root))
231      command = 'rm -fr {0}'.format(self._chromeos_root)
232      rv = self._executer.RunCommand(command)
233      if rv:
234        self._l.LogWarning('Warning - failed to remove chromeos tree.')
235
236  def MakeCheck(self):
237    cmd = ('ssh -i {0} {1}  root@{2} "reboot && exit"'
238           .format(self._tmp_testing_rsa, self._sshflag,
239                   self._remote))
240    self._executer.ChrootRunCommand(
241        self._chromeos_root, cmd)
242    time.sleep(40)
243
244    cmd = ('ssh -i {0} {1}  root@{2} '
245           '"iptables -A INPUT -p tcp --dport 1234 -j ACCEPT"'
246           .format(self._tmp_testing_rsa, self._sshflag,
247                   self._remote))
248    self._executer.ChrootRunCommand(
249        self._chromeos_root, cmd)
250
251    cmd = ('cd %s ; '
252           'DEJAGNU=%s make check' %
253           (path.join(self._gdb_source_dir, 'gdb'),
254            path.join(self._tmp, 'site.exp')))
255    ret = self._executer.ChrootRunCommand(
256        self._chromeos_root, cmd)
257    if ret:
258      raise Exception('Make check failed.')
259
260  # This method ensures necessary mount points before executing chroot comamnd.
261  def MountSource(self, unmount=False):
262    script = os.path.join(self._base_dir, 'build_tc.py')
263    if unmount:
264      mount = '-u'
265    else:
266      mount = '-m'
267    cmd = ('python {0} --chromeos_root={1} '
268           '--gdb_dir={2} --board={3} {4}'
269           .format(script, self._chromeos_root,
270                   self._source_dir, self._board,
271                   mount))
272    rv = self._executer.RunCommand(cmd)
273    if rv:
274      raise Exception('Mount source failed.')
275
276  def ResultValidate(self):
277    self.PrepareResult()
278    result = []
279    for key, value in self.base_result.items():
280      if 'PASS' not in value:
281        continue
282      if key not in self.test_result:
283        continue
284      test_result = self.test_result[key]
285      if 'PASS' not in test_result:
286        result.append(key)
287    return result
288
289  def PrepareResult(self):
290    test_output = os.path.join(self._gdb_source_dir, 'gdb',
291                               'testsuite', 'gdb.sum')
292    test_output = misc.GetOutsideChrootPath(self._chromeos_root,
293                                            test_output)
294    base_output = os.path.join(self._base_dir, 'gdb_baseline', self._target)
295
296    self.test_result = self.ParseResult(test_output)
297    self.base_result = self.ParseResult(base_output)
298
299  def ParseResult(self, gdb_sum):
300    result = {}
301    multi_keys = {}
302    with open(gdb_sum) as input_sum:
303      for line in input_sum:
304        line = line.strip()
305        r = line.split(':', 1)
306        if r[0] in _VALID_TEST_RESULTS:
307          key = r[1]
308          if r[1] in result:
309            if r[1] in multi_keys:
310              multi_keys[r[1]] += 1
311            else:
312              multi_keys[r[1]] = 2
313            key = r[1] + '_____{0}_____'.format(multi_keys[r[1]])
314          result[key] = r[0]
315    return result
316
317
318def Main(argv):
319  opts = ProcessArguments(argv)
320  available_machine = TryAcquireMachine(opts.remote)
321  executer = DejagnuExecuter(misc.GetRoot(argv[0])[0],
322                             opts.mount, opts.chromeos_root,
323                             available_machine._name,
324                             opts.board,
325                             opts.cleanup)
326  # Return value is a 3- or 4-element tuple
327  #   element#1 - exit code
328  #   element#2 - stdout
329  #   element#3 - stderr
330  #   element#4 - exception infor
331  # Some other scripts need these detailed information.
332  ret = (1, '', '')
333  try:
334    executer.SetupTestingDir()
335    executer.PrepareTestingRsaKeys()
336    executer.PrepareTestFiles()
337    executer.PrepareGdb()
338    executer.PrepareGdbserver()
339    executer.MakeCheck()
340    result = executer.ResultValidate()
341    print result
342    if result:
343      ret = (1, result, '')
344    else:
345      ret = (0, '', '')
346
347  except Exception as e:
348    # At least log the exception on console.
349    print e
350    # The #4 element encodes the runtime exception.
351    ret = (1, '', '', 'Exception happened during execution: \n' + str(e))
352  finally:
353    executer.Cleanup()
354    return ret
355
356if __name__ == '__main__':
357  retval = Main(sys.argv)[0]
358  sys.exit(retval)
359