1# Copyright 2013 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 StringIO
7import zipfile
8
9from telemetry.internal.platform import profiler
10from telemetry.timeline import trace_data as trace_data_module
11from telemetry.timeline import tracing_config
12
13
14class TraceProfiler(profiler.Profiler):
15
16  def __init__(self, browser_backend, platform_backend, output_path, state,
17               categories=None):
18    super(TraceProfiler, self).__init__(
19        browser_backend, platform_backend, output_path, state)
20    assert self._browser_backend.supports_tracing
21    # We always want flow events when tracing via telemetry.
22    categories_with_flow = 'disabled-by-default-toplevel.flow'
23    if categories:
24      categories_with_flow += ',%s' % categories
25    config = tracing_config.TracingConfig()
26    config.enable_chrome_trace = True
27    self._browser_backend.StartTracing(
28        config, categories_with_flow, timeout=10)
29
30  @classmethod
31  def name(cls):
32    return 'trace'
33
34  @classmethod
35  def is_supported(cls, browser_type):
36    return True
37
38  def CollectProfile(self):
39    print 'Processing trace...'
40
41    trace_result_builder = trace_data_module.TraceDataBuilder()
42    self._browser_backend.StopTracing(trace_result_builder)
43    trace_result = trace_result_builder.AsData()
44
45    trace_file = '%s.zip' % self._output_path
46
47    with zipfile.ZipFile(trace_file, 'w', zipfile.ZIP_DEFLATED) as z:
48      trace_data = StringIO.StringIO()
49      trace_result.Serialize(trace_data)
50      trace_name = '%s.json' % os.path.basename(self._output_path)
51      z.writestr(trace_name, trace_data.getvalue())
52
53    print 'Trace saved as %s' % trace_file
54    print 'To view, open in chrome://tracing'
55
56    return [trace_file]
57
58
59class TraceDetailedProfiler(TraceProfiler):
60
61  def __init__(self, browser_backend, platform_backend, output_path, state):
62    super(TraceDetailedProfiler, self).__init__(
63        browser_backend, platform_backend, output_path, state,
64        categories='disabled-by-default-cc.debug*')
65
66  @classmethod
67  def name(cls):
68    return 'trace-detailed'
69
70
71class TraceAllProfiler(TraceProfiler):
72
73  def __init__(self, browser_backend, platform_backend, output_path, state):
74    super(TraceAllProfiler, self).__init__(
75        browser_backend, platform_backend, output_path, state,
76        categories='disabled-by-default-*')
77
78  @classmethod
79  def name(cls):
80    return 'trace-all'
81