Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / core / platform / posix_platform_backend.py
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
5 import distutils.spawn
6 import logging
7 import os
8 import re
9 import stat
10 import subprocess
11
12 from telemetry.core.platform import desktop_platform_backend
13 from telemetry.core.platform import ps_util
14
15
16 class PosixPlatformBackend(desktop_platform_backend.DesktopPlatformBackend):
17
18   # This is an abstract class. It is OK to have abstract methods.
19   # pylint: disable=W0223
20
21   def _RunCommand(self, args):
22     return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
23
24   def _GetFileContents(self, path):
25     with open(path, 'r') as f:
26       return f.read()
27
28   def _GetPsOutput(self, columns, pid=None):
29     """Returns output of the 'ps' command as a list of lines.
30     Subclass should override this function.
31
32     Args:
33       columns: A list of require columns, e.g., ['pid', 'pss'].
34       pid: If nont None, returns only the information of the process
35          with the pid.
36     """
37     args = ['ps']
38     args.extend(['-p', str(pid)] if pid != None else ['-e'])
39     for c in columns:
40       args.extend(['-o', c + '='])
41     return self._RunCommand(args).splitlines()
42
43   def GetChildPids(self, pid):
44     """Returns a list of child pids of |pid|."""
45     ps_output = self._GetPsOutput(['pid', 'ppid', 'state'])
46     ps_line_re = re.compile(
47         '\s*(?P<pid>\d+)\s*(?P<ppid>\d+)\s*(?P<state>\S*)\s*')
48     processes = []
49     for pid_ppid_state in ps_output:
50       m = ps_line_re.match(pid_ppid_state)
51       assert m, 'Did not understand ps output: %s' % pid_ppid_state
52       processes.append((m.group('pid'), m.group('ppid'), m.group('state')))
53     return ps_util.GetChildPids(processes, pid)
54
55   def GetCommandLine(self, pid):
56     command = self._GetPsOutput(['command'], pid)
57     return command[0] if command else None
58
59   def GetFlushUtilityName(self):
60     return 'clear_system_cache'
61
62   def CanLaunchApplication(self, application):
63     return bool(distutils.spawn.find_executable(application))
64
65   def LaunchApplication(
66       self, application, parameters=None, elevate_privilege=False):
67     assert application, 'Must specify application to launch'
68
69     if os.path.sep not in application:
70       application = distutils.spawn.find_executable(application)
71       assert application, 'Failed to find application in path'
72
73     args = [application]
74
75     if parameters:
76       assert isinstance(parameters, list), 'parameters must be a list'
77       args += parameters
78
79     def IsSetUID(path):
80       return (os.stat(path).st_mode & stat.S_ISUID) == stat.S_ISUID
81
82     def IsElevated():
83       p = subprocess.Popen(
84           ['sudo', '-nv'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
85            stderr=subprocess.STDOUT)
86       stdout = p.communicate()[0]
87       # Some versions of sudo set the returncode based on whether sudo requires
88       # a password currently. Other versions return output when password is
89       # required and no output when the user is already authenticated.
90       return not p.returncode and not stdout
91
92     if elevate_privilege and not IsSetUID(application):
93       args = ['sudo'] + args
94       if not IsElevated():
95         print ('Telemetry needs to run %s under sudo. Please authenticate.' %
96                application)
97         subprocess.check_call(['sudo', '-v'])  # Synchronously authenticate.
98
99         prompt = ('Would you like to always allow %s to be run as the current '
100                   'user without sudo? If so, Telemetry will '
101                   '`sudo chmod +s %s`. (y/N)' % (application, application))
102         if raw_input(prompt).lower() == 'y':
103           subprocess.check_call(['sudo', 'chmod', '+s', application])
104
105     stderror_destination = subprocess.PIPE
106     if logging.getLogger().isEnabledFor(logging.DEBUG):
107       stderror_destination = None
108
109     return subprocess.Popen(
110         args, stdout=subprocess.PIPE, stderr=stderror_destination)