gdb_dejagnu.py revision ae02af5938d3fe75180dea5a6e8fa7a075b302d7
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  if options.cleanup and options.keep_intermediate_files:
69    raise Exception('Only one of --keep and --cleanup could be given.')
70
71  return options
72
73
74class DejagnuExecuter(object):
75  """The class wrapper for dejagnu test executer."""
76
77  def __init__(self, base_dir, source_dir, chromeos_root, remote, board,
78               cleanup):
79    self._l = logger.GetLogger()
80    self._chromeos_root = chromeos_root
81    self._chromeos_chroot = path.join(chromeos_root, 'chroot')
82
83    self._remote = remote
84    self._board = board
85    ## Compute target from board
86    self._target = misc.GetCtargetFromBoard(board, chromeos_root)
87    if not self._target:
88      raise Exception('Unsupported board "%s"' % board)
89    self._executer = command_executer.GetCommandExecuter()
90    self._base_dir = base_dir
91    self._tmp_abs = None
92    self._cleanup = cleanup
93    self._sshflag = ('-o StrictHostKeyChecking=no ' +
94                     '-o CheckHostIP=no ' +
95                     '-o UserKnownHostsFile=$(mktemp) ')
96
97    if source_dir:
98      self._source_dir = source_dir
99      self._mount_flag = 'USE="mounted_sources"'
100      self.MountSource()
101    else:
102      self._source_dir = None
103      self._mount_flag = ''
104
105  def SetupTestingDir(self):
106    self._tmp_abs = tempfile.mkdtemp(prefix='dejagnu_', dir=path.join(
107        self._chromeos_chroot, 'tmp'))
108    self._tmp = self._tmp_abs[len(self._chromeos_chroot):]
109    self._tmp_testing_rsa = path.join(self._tmp, 'testing_rsa')
110    self._tmp_testing_rsa_abs = path.join(self._tmp_abs, 'testing_rsa')
111
112  def PrepareTestingRsaKeys(self):
113    if not path.isfile(self._tmp_testing_rsa_abs):
114      shutil.copy(path.join(
115          self._chromeos_root,
116          'src/scripts/mod_for_test_scripts/ssh_keys/testing_rsa'),
117                  self._tmp_testing_rsa_abs)
118      os.chmod(self._tmp_testing_rsa_abs, stat.S_IRUSR)
119
120  def PrepareTestFiles(self):
121    """Prepare site.exp and board exp files."""
122    # Create the boards directory.
123    os.mkdir('%s/boards' % self._tmp_abs)
124
125    # Generate the chromeos.exp file.
126    with open('%s/boards/gdb.exp.in' % self._base_dir, 'r') as template_file:
127      content = template_file.read()
128
129    substitutions = dict({
130        '__boardname__': self._board,
131        '__board_hostname__': self._remote,
132        '__tmp_testing_rsa__': self._tmp_testing_rsa,
133        '__tmp_dir__': self._tmp})
134    for pat, sub in substitutions.items():
135      content = content.replace(pat, sub)
136
137    board_file_name = '%s/boards/%s.exp' % (self._tmp_abs, self._board)
138    with open(board_file_name, 'w') as board_file:
139      board_file.write(content)
140
141    # Generate the site file
142    with open('%s/site.exp' % self._tmp_abs, 'w') as site_file:
143      site_file.write('set target_list "%s"\n' % self._board)
144
145    with open('%s/boards/gdbserver.sh.in' % self._base_dir, 'r') \
146        as template_file:
147      content = template_file.read()
148    substitutions = dict({
149        '__board_hostname__': self._remote,
150        '__tmp_testing_rsa__': self._tmp_testing_rsa,
151        '__tmp_dir__': self._tmp})
152    for pat, sub in substitutions.items():
153      content = content.replace(pat, sub)
154
155    gdbserver_file_name = '%s/boards/gdbserver.sh' % (self._tmp_abs)
156    with open(gdbserver_file_name, 'w') as board_file:
157      board_file.write(content)
158
159    st = os.stat(gdbserver_file_name)
160    os.chmod(gdbserver_file_name, st.st_mode | stat.S_IXGRP | stat.S_IXUSR)
161
162  def PrepareGdb(self):
163    self.PrepareGdbDefault()
164
165  def PrepareGdbDefault(self):
166    ret = self._executer.ChrootRunCommand(
167        self._chromeos_root,
168        'equery w cross-%s/gdb' % self._target, return_output=True)[1]
169    ret = path.basename(ret.strip())
170
171    matcher = re.match(r'(.*).ebuild', ret)
172    if matcher:
173      gdb_reversion = matcher.group(1)
174    else:
175      raise Exception('Failed to get gdb reversion.')
176    gdb_version = gdb_reversion.split('-r')[0]
177    gdb_portage_dir = '/var/tmp/portage/cross-%s/%s/work' % (
178        self._target, gdb_reversion)
179    self._gdb_source_dir = path.join(gdb_portage_dir, gdb_version)
180
181    ret = self._executer.ChrootRunCommand(
182        self._chromeos_root,
183        ('sudo %s ebuild $(equery w cross-%s/gdb) clean compile' % (
184            self._mount_flag, self._target)))
185    if ret:
186      raise Exception('ebuild gdb failed.')
187
188  def PrepareGdbserver(self):
189    self.PrepareGdbserverDefault()
190
191  def PrepareGdbserverDefault(self):
192    cmd = ('./setup_board --board {0}; '
193           '{1} emerge-{0} gdb'.format(self._board, self._mount_flag))
194    ret = self._executer.ChrootRunCommand(
195        self._chromeos_root,
196        cmd, print_to_console=True)
197    if ret:
198      raise Exception('ebuild gdbserver failed.')
199
200    cmd = ('scp -i {0}  {1} '
201           '/build/{2}/usr/bin/gdbserver root@{3}:/usr/local/bin/'
202           .format(self._tmp_testing_rsa, self._sshflag,
203                   self._board, self._remote))
204    ret = self._executer.ChrootRunCommand(
205        self._chromeos_root,
206        cmd, print_to_console=True)
207    if ret:
208      raise Exception('copy gdbserver failed.')
209
210    if self._mount_flag:
211      self.MountSource(unmount=False)
212
213  def Cleanup(self):
214    if not self._cleanup:
215      return
216
217    if self._cleanup == 'chroot' or self._cleanup == 'chromeos':
218      self._l.LogOutput('[Cleanup]: Deleting chroot inside \'{0}\''.format(
219          self._chromeos_root))
220      command = 'cd %s; cros_sdk --delete' % self._chromeos_root
221      rv = self._executer.RunCommand(command)
222      if rv:
223        self._l.LogWarning('Warning - failed to delete chroot.')
224      # Delete .cache - crosbug.com/34956
225      command = 'sudo rm -fr %s' % os.path.join(self._chromeos_root, '.cache')
226      rv = self._executer.RunCommand(command)
227      if rv:
228        self._l.LogWarning('Warning - failed to delete \'.cache\'.')
229
230    if self._cleanup == 'chromeos':
231      self._l.LogOutput('[Cleanup]: Deleting chromeos tree \'{0}\' ...'.format(
232          self._chromeos_root))
233      command = 'rm -fr {0}'.format(self._chromeos_root)
234      rv = self._executer.RunCommand(command)
235      if rv:
236        self._l.LogWarning('Warning - failed to remove chromeos tree.')
237
238  def MakeCheck(self):
239    cmd = ('ssh -i {0} {1}  root@{2} "reboot && exit"'
240           .format(self._tmp_testing_rsa, self._sshflag,
241                   self._remote))
242    self._executer.ChrootRunCommand(
243        self._chromeos_root, cmd)
244    time.sleep(40)
245
246    cmd = ('ssh -i {0} {1}  root@{2} '
247           '"iptables -A INPUT -p tcp --dport 1234 -j ACCEPT"'
248           .format(self._tmp_testing_rsa, self._sshflag,
249                   self._remote))
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    rv = self._executer.RunCommand(cmd)
275    if rv:
276      raise Exception('Mount source failed.')
277
278  def ResultValidate(self):
279    self.PrepareResult()
280    result = []
281    for key, value in self.base_result.items():
282      if 'PASS' not in value:
283        continue
284      if key not in self.test_result:
285        continue
286      test_result = self.test_result[key]
287      if 'PASS' not in test_result:
288        result.append(key)
289    return result
290
291  def PrepareResult(self):
292    test_output = os.path.join(self._gdb_source_dir, 'gdb',
293                               'testsuite', 'gdb.sum')
294    test_output = misc.GetOutsideChrootPath(self._chromeos_root,
295                                            test_output)
296    base_output = os.path.join(self._base_dir, 'gdb_baseline', self._target)
297
298    self.test_result = self.ParseResult(test_output)
299    self.base_result = self.ParseResult(base_output)
300
301  def ParseResult(self, gdb_sum):
302    result = {}
303    multi_keys = {}
304    with open(gdb_sum) as input_sum:
305      for line in input_sum:
306        line = line.strip()
307        r = line.split(':', 1)
308        if r[0] in _VALID_TEST_RESULTS:
309          key = r[1]
310          if r[1] in result:
311            if r[1] in multi_keys:
312              multi_keys[r[1]] += 1
313            else:
314              multi_keys[r[1]] = 2
315            key = r[1] + '_____{0}_____'.format(multi_keys[r[1]])
316          result[key] = r[0]
317    return result
318
319
320def Main(argv):
321  opts = ProcessArguments(argv)
322  available_machine = TryAcquireMachine(opts.remote)
323  executer = DejagnuExecuter(misc.GetRoot(argv[0])[0],
324                             opts.mount, opts.chromeos_root,
325                             available_machine._name,
326                             opts.board,
327                             opts.cleanup)
328  # Return value is a 3- or 4-element tuple
329  #   element#1 - exit code
330  #   element#2 - stdout
331  #   element#3 - stderr
332  #   element#4 - exception infor
333  # Some other scripts need these detailed information.
334  ret = (1, '', '')
335  try:
336    executer.SetupTestingDir()
337    executer.PrepareTestingRsaKeys()
338    executer.PrepareTestFiles()
339    executer.PrepareGdb()
340    executer.PrepareGdbserver()
341    executer.MakeCheck()
342    print executer.ResultValidate()
343   # ret = executer.ValidateFailures()
344  except Exception as e:
345    # At least log the exception on console.
346    print e
347    # The #4 element encodes the runtime exception.
348    ret = (1, '', '', 'Exception happened during execution: \n' + str(e))
349  finally:
350    executer.Cleanup()
351    return ret
352
353if __name__ == '__main__':
354  retval = Main(sys.argv)[0]
355  sys.exit(retval)
356