1# Copyright 2015 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.
4
5import os
6import re
7import time
8
9from profile_chrome import controllers
10from profile_chrome import util
11
12_DDMS_SAMPLING_FREQUENCY_US = 100
13
14
15class DdmsController(controllers.BaseController):
16  def __init__(self, device, package_info):
17    controllers.BaseController.__init__(self)
18    self._device = device
19    self._package = package_info.package
20    self._output_file = None
21    self._supports_sampling = self._SupportsSampling()
22
23  def __repr__(self):
24    return 'ddms profile'
25
26  def _SupportsSampling(self):
27    for line in self._device.RunShellCommand('am --help'):
28      if re.match(r'.*am profile start.*--sampling', line):
29        return True
30    return False
31
32  def StartTracing(self, _):
33    self._output_file = (
34        '/data/local/tmp/ddms-profile-%s' % util.GetTraceTimestamp())
35    cmd = 'am profile start '
36    if self._supports_sampling:
37      cmd += '--sampling %d ' % _DDMS_SAMPLING_FREQUENCY_US
38    cmd += '%s %s' % (self._package, self._output_file)
39    self._device.RunShellCommand(cmd)
40
41  def StopTracing(self):
42    self._device.RunShellCommand('am profile stop %s' % self._package)
43
44  def PullTrace(self):
45    if not self._output_file:
46      return None
47
48    # Wait for the trace file to get written.
49    time.sleep(1)
50
51    host_file = os.path.join(
52        os.path.curdir, os.path.basename(self._output_file))
53    self._device.PullFile(self._output_file, host_file)
54    return host_file
55