1# Copyright 2014 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.
4from telemetry.internal.platform.profiler import profiler_finder
5
6
7class ProfilingControllerBackend(object):
8  def __init__(self, platform_backend, browser_backend):
9    self._platform_backend = platform_backend
10    self._browser_backend = browser_backend
11    self._active_profilers = []
12    self._profilers_states = {}
13
14  def Start(self, profiler_name, base_output_file):
15    """Starts profiling using |profiler_name|. Results are saved to
16    |base_output_file|.<process_name>."""
17    assert not self._active_profilers, 'Already profiling. Must stop first.'
18
19    profiler_class = profiler_finder.FindProfiler(profiler_name)
20
21    if not profiler_class.is_supported(self._browser_backend.browser_type):
22      raise Exception('The %s profiler is not '
23                      'supported on this platform.' % profiler_name)
24
25    if not profiler_class in self._profilers_states:
26      self._profilers_states[profiler_class] = {}
27
28    self._active_profilers.append(
29        profiler_class(self._browser_backend, self._platform_backend,
30            base_output_file, self._profilers_states[profiler_class]))
31
32  def Stop(self):
33    """Stops all active profilers and saves their results.
34
35    Returns:
36      A list of filenames produced by the profiler.
37    """
38    output_files = []
39    for profiler in self._active_profilers:
40      output_files.extend(profiler.CollectProfile())
41    self._active_profilers = []
42    return output_files
43
44  def WillCloseBrowser(self):
45    for profiler_class in self._profilers_states:
46      profiler_class.WillCloseBrowser(
47        self._browser_backend, self._platform_backend)
48