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