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.
12 from telemetry.core.platform import desktop_platform_backend
13 from telemetry.core.platform import ps_util
16 class PosixPlatformBackend(desktop_platform_backend.DesktopPlatformBackend):
18 # This is an abstract class. It is OK to have abstract methods.
19 # pylint: disable=W0223
21 def _RunCommand(self, args):
22 return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
24 def _GetFileContents(self, path):
25 with open(path, 'r') as f:
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.
33 columns: A list of require columns, e.g., ['pid', 'pss'].
34 pid: If nont None, returns only the information of the process
38 args.extend(['-p', str(pid)] if pid != None else ['-e'])
40 args.extend(['-o', c + '='])
41 return self._RunCommand(args).splitlines()
43 def _GetTopOutput(self, pid, columns):
44 """Returns output of the 'top' command as a list of lines.
47 pid: pid of process to examine.
48 columns: A list of require columns, e.g., ['idlew', 'vsize'].
51 args.extend(['-pid', str(pid), '-l', '1', '-s', '0', '-stats',
53 return self._RunCommand(args).splitlines()
55 def GetChildPids(self, pid):
56 """Returns a list of child pids of |pid|."""
57 ps_output = self._GetPsOutput(['pid', 'ppid', 'state'])
58 ps_line_re = re.compile(
59 '\s*(?P<pid>\d+)\s*(?P<ppid>\d+)\s*(?P<state>\S*)\s*')
61 for pid_ppid_state in ps_output:
62 m = ps_line_re.match(pid_ppid_state)
63 assert m, 'Did not understand ps output: %s' % pid_ppid_state
64 processes.append((m.group('pid'), m.group('ppid'), m.group('state')))
65 return ps_util.GetChildPids(processes, pid)
67 def GetCommandLine(self, pid):
68 command = self._GetPsOutput(['command'], pid)
69 return command[0] if command else None
71 def CanLaunchApplication(self, application):
72 return bool(distutils.spawn.find_executable(application))
74 def LaunchApplication(
75 self, application, parameters=None, elevate_privilege=False):
76 assert application, 'Must specify application to launch'
78 if os.path.sep not in application:
79 application = distutils.spawn.find_executable(application)
80 assert application, 'Failed to find application in path'
85 assert isinstance(parameters, list), 'parameters must be a list'
89 return (os.stat(path).st_mode & stat.S_ISUID) == stat.S_ISUID
93 ['sudo', '-nv'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
94 stderr=subprocess.STDOUT)
95 stdout = p.communicate()[0]
96 # Some versions of sudo set the returncode based on whether sudo requires
97 # a password currently. Other versions return output when password is
98 # required and no output when the user is already authenticated.
99 return not p.returncode and not stdout
101 if elevate_privilege and not IsSetUID(application):
102 args = ['sudo'] + args
104 print ('Telemetry needs to run %s under sudo. Please authenticate.' %
106 subprocess.check_call(['sudo', '-v']) # Synchronously authenticate.
108 prompt = ('Would you like to always allow %s to be run as the current '
109 'user without sudo? If so, Telemetry will '
110 '`sudo chmod +s %s`. (y/N)' % (application, application))
111 if raw_input(prompt).lower() == 'y':
112 subprocess.check_call(['sudo', 'chmod', '+s', application])
114 stderror_destination = subprocess.PIPE
115 if logging.getLogger().isEnabledFor(logging.DEBUG):
116 stderror_destination = None
118 return subprocess.Popen(
119 args, stdout=subprocess.PIPE, stderr=stderror_destination)