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 subprocess
7
8from telemetry.core import util
9from telemetry.core.platform import platform_backend
10
11
12class DesktopPlatformBackend(platform_backend.PlatformBackend):
13
14  # This is an abstract class. It is OK to have abstract methods.
15  # pylint: disable=W0223
16
17  def GetFlushUtilityName(self):
18    return NotImplementedError()
19
20  def _FindNewestFlushUtility(self):
21    flush_command = None
22    flush_command_mtime = 0
23
24    chrome_root = util.GetChromiumSrcDir()
25    for build_dir, build_type in util.GetBuildDirectories():
26      candidate = os.path.join(chrome_root, build_dir, build_type,
27                               self.GetFlushUtilityName())
28      if os.access(candidate, os.X_OK):
29        candidate_mtime = os.stat(candidate).st_mtime
30        if candidate_mtime > flush_command_mtime:
31          flush_command = candidate
32          flush_command_mtime = candidate_mtime
33
34    return flush_command
35
36  def FlushSystemCacheForDirectory(self, directory, ignoring=None):
37    assert directory and os.path.exists(directory), \
38        'Target directory %s must exist' % directory
39    flush_command = self._FindNewestFlushUtility()
40    assert flush_command, \
41        'You must build %s first' % self.GetFlushUtilityName()
42
43    args = [flush_command, '--recurse']
44    directory_contents = os.listdir(directory)
45    for item in directory_contents:
46      if not ignoring or item not in ignoring:
47        args.append(os.path.join(directory, item))
48
49    if len(args) < 3:
50      return
51
52    p = subprocess.Popen(args)
53    p.wait()
54    assert p.returncode == 0, 'Failed to flush system cache'
55