| OLD | NEW |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
| 4 | 4 |
| 5 """Provides an interface to communicate with the device via the adb command. | 5 """Provides an interface to communicate with the device via the adb command. |
| 6 | 6 |
| 7 Assumes adb binary is currently on system path. | 7 Assumes adb binary is currently on system path. |
| 8 """ | 8 """ |
| 9 | 9 |
| 10 import collections | 10 import collections |
| 11 import datetime | 11 import datetime |
| 12 import inspect | 12 import inspect |
| 13 import logging | 13 import logging |
| 14 import os | 14 import os |
| 15 import re | 15 import re |
| 16 import shlex | 16 import shlex |
| 17 import signal | 17 import signal |
| 18 import subprocess | 18 import subprocess |
| 19 import sys | 19 import sys |
| 20 import tempfile | 20 import tempfile |
| 21 import time | 21 import time |
| 22 | 22 |
| 23 import cmd_helper | 23 import cmd_helper |
| 24 import constants | 24 import constants |
| 25 import screenshot | 25 import screenshot |
| 26 import system_properties | 26 import system_properties |
| 27 | 27 |
| 28 try: | 28 try: |
| 29 from pylib import pexpect | 29 from pylib import pexpect |
| 30 except: | 30 except ImportError: |
| 31 pexpect = None | 31 pexpect = None |
| 32 | 32 |
| 33 sys.path.append(os.path.join( | 33 sys.path.append(os.path.join( |
| 34 constants.DIR_SOURCE_ROOT, 'third_party', 'android_testrunner')) | 34 constants.DIR_SOURCE_ROOT, 'third_party', 'android_testrunner')) |
| 35 import adb_interface | 35 import adb_interface |
| 36 import am_instrument_parser | 36 import am_instrument_parser |
| 37 import errors | 37 import errors |
| 38 | 38 |
| 39 | 39 |
| 40 # Pattern to search for the next whole line of pexpect output and capture it | 40 # Pattern to search for the next whole line of pexpect output and capture it |
| (...skipping 302 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 343 retries = 3 | 343 retries = 3 |
| 344 while retries: | 344 while retries: |
| 345 try: | 345 try: |
| 346 self._adb.WaitForDevicePm() | 346 self._adb.WaitForDevicePm() |
| 347 return # Success | 347 return # Success |
| 348 except errors.WaitForResponseTimedOutError as e: | 348 except errors.WaitForResponseTimedOutError as e: |
| 349 last_err = e | 349 last_err = e |
| 350 logging.warning('Restarting and retrying after timeout: %s', e) | 350 logging.warning('Restarting and retrying after timeout: %s', e) |
| 351 retries -= 1 | 351 retries -= 1 |
| 352 self.RestartShell() | 352 self.RestartShell() |
| 353 raise last_err # Only reached after max retries, re-raise the last error. | 353 raise last_err # Only reached after max retries, re-raise the last error. |
| 354 | 354 |
| 355 def RestartShell(self): | 355 def RestartShell(self): |
| 356 """Restarts the shell on the device. Does not block for it to return.""" | 356 """Restarts the shell on the device. Does not block for it to return.""" |
| 357 self.RunShellCommand('stop') | 357 self.RunShellCommand('stop') |
| 358 self.RunShellCommand('start') | 358 self.RunShellCommand('start') |
| 359 | 359 |
| 360 def Reboot(self, full_reboot=True): | 360 def Reboot(self, full_reboot=True): |
| 361 """Reboots the device and waits for the package manager to return. | 361 """Reboots the device and waits for the package manager to return. |
| 362 | 362 |
| 363 Args: | 363 Args: |
| (...skipping 118 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 482 out = self._adb.SendCommand('remount') | 482 out = self._adb.SendCommand('remount') |
| 483 if out.strip() != 'remount succeeded': | 483 if out.strip() != 'remount succeeded': |
| 484 raise errors.MsgException('Remount failed: %s' % out) | 484 raise errors.MsgException('Remount failed: %s' % out) |
| 485 | 485 |
| 486 def RestartAdbdOnDevice(self): | 486 def RestartAdbdOnDevice(self): |
| 487 logging.info('Killing adbd on the device...') | 487 logging.info('Killing adbd on the device...') |
| 488 adb_pids = self.ExtractPid('adbd') | 488 adb_pids = self.ExtractPid('adbd') |
| 489 if not adb_pids: | 489 if not adb_pids: |
| 490 raise errors.MsgException('Unable to obtain adbd pid') | 490 raise errors.MsgException('Unable to obtain adbd pid') |
| 491 try: | 491 try: |
| 492 self.KillAll('adbd', signal=signal.SIGTERM, with_su=True) | 492 self.KillAll('adbd', signum=signal.SIGTERM, with_su=True) |
| 493 logging.info('Waiting for device to settle...') | 493 logging.info('Waiting for device to settle...') |
| 494 self._adb.SendCommand('wait-for-device') | 494 self._adb.SendCommand('wait-for-device') |
| 495 new_adb_pids = self.ExtractPid('adbd') | 495 new_adb_pids = self.ExtractPid('adbd') |
| 496 if new_adb_pids == adb_pids: | 496 if new_adb_pids == adb_pids: |
| 497 logging.warning('adbd on the device may not have been restarted.') | 497 logging.warning('adbd on the device may not have been restarted.') |
| 498 except Exception as e: | 498 except Exception as e: |
| 499 logging.error('Exception when trying to kill adbd on the device [%s]', e) | 499 logging.error('Exception when trying to kill adbd on the device [%s]', e) |
| 500 | 500 |
| 501 def RestartAdbServer(self): | 501 def RestartAdbServer(self): |
| 502 """Restart the adb server.""" | 502 """Restart the adb server.""" |
| 503 ret = self.KillAdbServer() | 503 ret = self.KillAdbServer() |
| 504 if ret != 0: | 504 if ret != 0: |
| 505 raise errors.MsgException('KillAdbServer: %d' % ret) | 505 raise errors.MsgException('KillAdbServer: %d' % ret) |
| 506 | 506 |
| 507 ret = self.StartAdbServer() | 507 ret = self.StartAdbServer() |
| 508 if ret != 0: | 508 if ret != 0: |
| 509 raise errors.MsgException('StartAdbServer: %d' % ret) | 509 raise errors.MsgException('StartAdbServer: %d' % ret) |
| 510 | 510 |
| 511 def KillAdbServer(self): | 511 @staticmethod |
| 512 def KillAdbServer(): |
| 512 """Kill adb server.""" | 513 """Kill adb server.""" |
| 513 adb_cmd = [constants.GetAdbPath(), 'kill-server'] | 514 adb_cmd = [constants.GetAdbPath(), 'kill-server'] |
| 514 ret = cmd_helper.RunCmd(adb_cmd) | 515 ret = cmd_helper.RunCmd(adb_cmd) |
| 515 retry = 0 | 516 retry = 0 |
| 516 while retry < 3: | 517 while retry < 3: |
| 517 ret, _ = cmd_helper.GetCmdStatusAndOutput(['pgrep', 'adb']) | 518 ret, _ = cmd_helper.GetCmdStatusAndOutput(['pgrep', 'adb']) |
| 518 if ret != 0: | 519 if ret != 0: |
| 519 # pgrep didn't find adb, kill-server succeeded. | 520 # pgrep didn't find adb, kill-server succeeded. |
| 520 return 0 | 521 return 0 |
| 521 retry += 1 | 522 retry += 1 |
| (...skipping 109 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 631 timeout_time: Number of seconds to wait for command to respond before | 632 timeout_time: Number of seconds to wait for command to respond before |
| 632 retrying, used by AdbInterface.SendShellCommand. | 633 retrying, used by AdbInterface.SendShellCommand. |
| 633 log_result: Boolean to indicate whether we should log the result of the | 634 log_result: Boolean to indicate whether we should log the result of the |
| 634 shell command. | 635 shell command. |
| 635 | 636 |
| 636 Returns: | 637 Returns: |
| 637 list containing the lines of output received from running the command | 638 list containing the lines of output received from running the command |
| 638 """ | 639 """ |
| 639 self._CheckCommandIsValid(command) | 640 self._CheckCommandIsValid(command) |
| 640 self._LogShell(command) | 641 self._LogShell(command) |
| 641 if "'" in command: logging.warning(command + " contains ' quotes") | 642 if "'" in command: |
| 643 logging.warning(command + " contains ' quotes") |
| 642 result = self._adb.SendShellCommand( | 644 result = self._adb.SendShellCommand( |
| 643 "'%s'" % command, timeout_time).splitlines() | 645 "'%s'" % command, timeout_time).splitlines() |
| 644 if ['error: device not found'] == result: | 646 if ['error: device not found'] == result: |
| 645 raise errors.DeviceUnresponsiveError('device not found') | 647 raise errors.DeviceUnresponsiveError('device not found') |
| 646 if log_result: | 648 if log_result: |
| 647 self._LogShell('\n'.join(result)) | 649 self._LogShell('\n'.join(result)) |
| 648 return result | 650 return result |
| 649 | 651 |
| 650 def GetShellCommandStatusAndOutput(self, command, timeout_time=20, | 652 def GetShellCommandStatusAndOutput(self, command, timeout_time=20, |
| 651 log_result=False): | 653 log_result=False): |
| 652 """See RunShellCommand() above. | 654 """See RunShellCommand() above. |
| 653 | 655 |
| 654 Returns: | 656 Returns: |
| 655 The tuple (exit code, list of output lines). | 657 The tuple (exit code, list of output lines). |
| 656 """ | 658 """ |
| 657 lines = self.RunShellCommand( | 659 lines = self.RunShellCommand( |
| 658 command + '; echo %$?', timeout_time, log_result) | 660 command + '; echo %$?', timeout_time, log_result) |
| 659 last_line = lines[-1] | 661 last_line = lines[-1] |
| 660 status_pos = last_line.rfind('%') | 662 status_pos = last_line.rfind('%') |
| 661 assert status_pos >= 0 | 663 assert status_pos >= 0 |
| 662 status = int(last_line[status_pos + 1:]) | 664 status = int(last_line[status_pos + 1:]) |
| 663 if status_pos == 0: | 665 if status_pos == 0: |
| 664 lines = lines[:-1] | 666 lines = lines[:-1] |
| 665 else: | 667 else: |
| 666 lines = lines[:-1] + [last_line[:status_pos]] | 668 lines = lines[:-1] + [last_line[:status_pos]] |
| 667 return (status, lines) | 669 return (status, lines) |
| 668 | 670 |
| 669 def KillAll(self, process, signal=9, with_su=False): | 671 def KillAll(self, process, signum=9, with_su=False): |
| 670 """Android version of killall, connected via adb. | 672 """Android version of killall, connected via adb. |
| 671 | 673 |
| 672 Args: | 674 Args: |
| 673 process: name of the process to kill off. | 675 process: name of the process to kill off. |
| 674 signal: signal to use, 9 (SIGKILL) by default. | 676 signum: signal to use, 9 (SIGKILL) by default. |
| 675 with_su: wether or not to use su to kill the processes. | 677 with_su: wether or not to use su to kill the processes. |
| 676 | 678 |
| 677 Returns: | 679 Returns: |
| 678 the number of processes killed | 680 the number of processes killed |
| 679 """ | 681 """ |
| 680 pids = self.ExtractPid(process) | 682 pids = self.ExtractPid(process) |
| 681 if pids: | 683 if pids: |
| 682 cmd = 'kill -%d %s' % (signal, ' '.join(pids)) | 684 cmd = 'kill -%d %s' % (signum, ' '.join(pids)) |
| 683 if with_su: | 685 if with_su: |
| 684 self.RunShellCommandWithSU(cmd) | 686 self.RunShellCommandWithSU(cmd) |
| 685 else: | 687 else: |
| 686 self.RunShellCommand(cmd) | 688 self.RunShellCommand(cmd) |
| 687 return len(pids) | 689 return len(pids) |
| 688 | 690 |
| 689 def KillAllBlocking(self, process, timeout_sec): | 691 def KillAllBlocking(self, process, timeout_sec): |
| 690 """Blocking version of killall, connected via adb. | 692 """Blocking version of killall, connected via adb. |
| 691 | 693 |
| 692 This waits until no process matching the corresponding name appears in ps' | 694 This waits until no process matching the corresponding name appears in ps' |
| (...skipping 11 matching lines...) Expand all Loading... |
| 704 elapsed = 0 | 706 elapsed = 0 |
| 705 wait_period = 0.1 | 707 wait_period = 0.1 |
| 706 # Note that this doesn't take into account the time spent in ExtractPid(). | 708 # Note that this doesn't take into account the time spent in ExtractPid(). |
| 707 while self.ExtractPid(process) and elapsed < timeout_sec: | 709 while self.ExtractPid(process) and elapsed < timeout_sec: |
| 708 time.sleep(wait_period) | 710 time.sleep(wait_period) |
| 709 elapsed += wait_period | 711 elapsed += wait_period |
| 710 if elapsed >= timeout_sec: | 712 if elapsed >= timeout_sec: |
| 711 return 0 | 713 return 0 |
| 712 return processes_killed | 714 return processes_killed |
| 713 | 715 |
| 714 def _GetActivityCommand(self, package, activity, wait_for_completion, action, | 716 @staticmethod |
| 717 def _GetActivityCommand(package, activity, wait_for_completion, action, |
| 715 category, data, extras, trace_file_name, force_stop, | 718 category, data, extras, trace_file_name, force_stop, |
| 716 flags): | 719 flags): |
| 717 """Creates command to start |package|'s activity on the device. | 720 """Creates command to start |package|'s activity on the device. |
| 718 | 721 |
| 719 Args - as for StartActivity | 722 Args - as for StartActivity |
| 720 | 723 |
| 721 Returns: | 724 Returns: |
| 722 the command to run on the target to start the activity | 725 the command to run on the target to start the activity |
| 723 """ | 726 """ |
| 724 cmd = 'am start -a %s' % action | 727 cmd = 'am start -a %s' % action |
| (...skipping 338 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1063 | 1066 |
| 1064 def CanAccessProtectedFileContents(self): | 1067 def CanAccessProtectedFileContents(self): |
| 1065 """Returns True if Get/SetProtectedFileContents would work via "su". | 1068 """Returns True if Get/SetProtectedFileContents would work via "su". |
| 1066 | 1069 |
| 1067 Devices running user builds don't have adb root, but may provide "su" which | 1070 Devices running user builds don't have adb root, but may provide "su" which |
| 1068 can be used for accessing protected files. | 1071 can be used for accessing protected files. |
| 1069 """ | 1072 """ |
| 1070 r = self.RunShellCommandWithSU('cat /dev/null') | 1073 r = self.RunShellCommandWithSU('cat /dev/null') |
| 1071 return r == [] or r[0].strip() == '' | 1074 return r == [] or r[0].strip() == '' |
| 1072 | 1075 |
| 1073 def GetProtectedFileContents(self, filename, log_result=False): | 1076 def GetProtectedFileContents(self, filename): |
| 1074 """Gets contents from the protected file specified by |filename|. | 1077 """Gets contents from the protected file specified by |filename|. |
| 1075 | 1078 |
| 1076 This is less efficient than GetFileContents, but will work for protected | 1079 This is less efficient than GetFileContents, but will work for protected |
| 1077 files and device files. | 1080 files and device files. |
| 1078 """ | 1081 """ |
| 1079 # Run the script as root | 1082 # Run the script as root |
| 1080 return self.RunShellCommandWithSU('cat "%s" 2> /dev/null' % filename) | 1083 return self.RunShellCommandWithSU('cat "%s" 2> /dev/null' % filename) |
| 1081 | 1084 |
| 1082 def SetProtectedFileContents(self, filename, contents): | 1085 def SetProtectedFileContents(self, filename, contents): |
| 1083 """Writes |contents| to the protected file specified by |filename|. | 1086 """Writes |contents| to the protected file specified by |filename|. |
| (...skipping 227 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1311 logging.info('<<< Waiting for logcat:' + str(success_re.pattern)) | 1314 logging.info('<<< Waiting for logcat:' + str(success_re.pattern)) |
| 1312 t0 = time.time() | 1315 t0 = time.time() |
| 1313 while True: | 1316 while True: |
| 1314 if not self._logcat: | 1317 if not self._logcat: |
| 1315 self.StartMonitoringLogcat(clear) | 1318 self.StartMonitoringLogcat(clear) |
| 1316 try: | 1319 try: |
| 1317 while True: | 1320 while True: |
| 1318 # Note this will block for upto the timeout _per log line_, so we need | 1321 # Note this will block for upto the timeout _per log line_, so we need |
| 1319 # to calculate the overall timeout remaining since t0. | 1322 # to calculate the overall timeout remaining since t0. |
| 1320 time_remaining = t0 + timeout - time.time() | 1323 time_remaining = t0 + timeout - time.time() |
| 1321 if time_remaining < 0: raise pexpect.TIMEOUT(self._logcat) | 1324 if time_remaining < 0: |
| 1325 raise pexpect.TIMEOUT(self._logcat) |
| 1322 self._logcat.expect(PEXPECT_LINE_RE, timeout=time_remaining) | 1326 self._logcat.expect(PEXPECT_LINE_RE, timeout=time_remaining) |
| 1323 line = self._logcat.match.group(1) | 1327 line = self._logcat.match.group(1) |
| 1324 if error_re: | 1328 if error_re: |
| 1325 error_match = error_re.search(line) | 1329 error_match = error_re.search(line) |
| 1326 if error_match: | 1330 if error_match: |
| 1327 return None | 1331 return None |
| 1328 success_match = success_re.search(line) | 1332 success_match = success_re.search(line) |
| 1329 if success_match: | 1333 if success_match: |
| 1330 return success_match | 1334 return success_match |
| 1331 logging.info('<<< Skipped Logcat Line:' + str(line)) | 1335 logging.info('<<< Skipped Logcat Line:' + str(line)) |
| 1332 except pexpect.TIMEOUT: | 1336 except pexpect.TIMEOUT: |
| 1333 raise pexpect.TIMEOUT( | 1337 raise pexpect.TIMEOUT( |
| 1334 'Timeout (%ds) exceeded waiting for pattern "%s" (tip: use -vv ' | 1338 'Timeout (%ds) exceeded waiting for pattern "%s" (tip: use -vv ' |
| 1335 'to debug)' % | 1339 'to debug)' % |
| 1336 (timeout, success_re.pattern)) | 1340 (timeout, success_re.pattern)) |
| 1337 except pexpect.EOF: | 1341 except pexpect.EOF: |
| 1338 # It seems that sometimes logcat can end unexpectedly. This seems | 1342 # It seems that sometimes logcat can end unexpectedly. This seems |
| 1339 # to happen during Chrome startup after a reboot followed by a cache | 1343 # to happen during Chrome startup after a reboot followed by a cache |
| 1340 # clean. I don't understand why this happens, but this code deals with | 1344 # clean. I don't understand why this happens, but this code deals with |
| 1341 # getting EOF in logcat. | 1345 # getting EOF in logcat. |
| 1342 logging.critical('Found EOF in adb logcat. Restarting...') | 1346 logging.critical('Found EOF in adb logcat. Restarting...') |
| 1343 # Rerun spawn with original arguments. Note that self._logcat.args[0] is | 1347 # Rerun spawn with original arguments. Note that self._logcat.args[0] is |
| 1344 # the path of adb, so we don't want it in the arguments. | 1348 # the path of adb, so we don't want it in the arguments. |
| 1345 self._logcat = pexpect.spawn(constants.GetAdbPath(), | 1349 self._logcat = pexpect.spawn(constants.GetAdbPath(), |
| 1346 self._logcat.args[1:], | 1350 self._logcat.args[1:], |
| 1347 timeout=self._logcat.timeout, | 1351 timeout=self._logcat.timeout, |
| 1348 logfile=self._logcat.logfile) | 1352 logfile=self._logcat.logfile) |
| 1349 | 1353 |
| 1350 def StartRecordingLogcat(self, clear=True, filters=['*:v']): | 1354 def StartRecordingLogcat(self, clear=True, filters=None): |
| 1351 """Starts recording logcat output to eventually be saved as a string. | 1355 """Starts recording logcat output to eventually be saved as a string. |
| 1352 | 1356 |
| 1353 This call should come before some series of tests are run, with either | 1357 This call should come before some series of tests are run, with either |
| 1354 StopRecordingLogcat or SearchLogcatRecord following the tests. | 1358 StopRecordingLogcat or SearchLogcatRecord following the tests. |
| 1355 | 1359 |
| 1356 Args: | 1360 Args: |
| 1357 clear: True if existing log output should be cleared. | 1361 clear: True if existing log output should be cleared. |
| 1358 filters: A list of logcat filters to be used. | 1362 filters: A list of logcat filters to be used. |
| 1359 """ | 1363 """ |
| 1364 if not filters: |
| 1365 filters = ['*:v'] |
| 1360 if clear: | 1366 if clear: |
| 1361 self._adb.SendCommand('logcat -c') | 1367 self._adb.SendCommand('logcat -c') |
| 1362 logcat_command = 'adb %s logcat -v threadtime %s' % (self._adb._target_arg, | 1368 logcat_command = 'adb %s logcat -v threadtime %s' % (self._adb._target_arg, |
| 1363 ' '.join(filters)) | 1369 ' '.join(filters)) |
| 1364 self._logcat_tmpoutfile = tempfile.NamedTemporaryFile(bufsize=0) | 1370 self._logcat_tmpoutfile = tempfile.NamedTemporaryFile(bufsize=0) |
| 1365 self.logcat_process = subprocess.Popen(logcat_command, shell=True, | 1371 self.logcat_process = subprocess.Popen(logcat_command, shell=True, |
| 1366 stdout=self._logcat_tmpoutfile) | 1372 stdout=self._logcat_tmpoutfile) |
| 1367 | 1373 |
| 1368 def GetCurrentRecordedLogcat(self): | 1374 def GetCurrentRecordedLogcat(self): |
| 1369 """Return the current content of the logcat being recorded. | 1375 """Return the current content of the logcat being recorded. |
| (...skipping 24 matching lines...) Expand all Loading... |
| 1394 if self.logcat_process.poll() is None: | 1400 if self.logcat_process.poll() is None: |
| 1395 self.logcat_process.kill() | 1401 self.logcat_process.kill() |
| 1396 self.logcat_process.wait() | 1402 self.logcat_process.wait() |
| 1397 self.logcat_process = None | 1403 self.logcat_process = None |
| 1398 self._logcat_tmpoutfile.seek(0) | 1404 self._logcat_tmpoutfile.seek(0) |
| 1399 output = self._logcat_tmpoutfile.read() | 1405 output = self._logcat_tmpoutfile.read() |
| 1400 self._logcat_tmpoutfile.close() | 1406 self._logcat_tmpoutfile.close() |
| 1401 self._logcat_tmpoutfile = None | 1407 self._logcat_tmpoutfile = None |
| 1402 return output | 1408 return output |
| 1403 | 1409 |
| 1404 def SearchLogcatRecord(self, record, message, thread_id=None, proc_id=None, | 1410 @staticmethod |
| 1411 def SearchLogcatRecord(record, message, thread_id=None, proc_id=None, |
| 1405 log_level=None, component=None): | 1412 log_level=None, component=None): |
| 1406 """Searches the specified logcat output and returns results. | 1413 """Searches the specified logcat output and returns results. |
| 1407 | 1414 |
| 1408 This method searches through the logcat output specified by record for a | 1415 This method searches through the logcat output specified by record for a |
| 1409 certain message, narrowing results by matching them against any other | 1416 certain message, narrowing results by matching them against any other |
| 1410 specified criteria. It returns all matching lines as described below. | 1417 specified criteria. It returns all matching lines as described below. |
| 1411 | 1418 |
| 1412 Args: | 1419 Args: |
| 1413 record: A string generated by Start/StopRecordingLogcat to search. | 1420 record: A string generated by Start/StopRecordingLogcat to search. |
| 1414 message: An output string to search for. | 1421 message: An output string to search for. |
| (...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1510 A tuple containg: | 1517 A tuple containg: |
| 1511 [0]: Dict of {metric:usage_kb}, for the process which has specified pid. | 1518 [0]: Dict of {metric:usage_kb}, for the process which has specified pid. |
| 1512 The metric keys which may be included are: Size, Rss, Pss, Shared_Clean, | 1519 The metric keys which may be included are: Size, Rss, Pss, Shared_Clean, |
| 1513 Shared_Dirty, Private_Clean, Private_Dirty, Referenced, Swap, | 1520 Shared_Dirty, Private_Clean, Private_Dirty, Referenced, Swap, |
| 1514 KernelPageSize, MMUPageSize, Nvidia (tablet only), VmHWM. | 1521 KernelPageSize, MMUPageSize, Nvidia (tablet only), VmHWM. |
| 1515 [1]: Detailed /proc/[PID]/smaps information. | 1522 [1]: Detailed /proc/[PID]/smaps information. |
| 1516 """ | 1523 """ |
| 1517 usage_dict = collections.defaultdict(int) | 1524 usage_dict = collections.defaultdict(int) |
| 1518 smaps = collections.defaultdict(dict) | 1525 smaps = collections.defaultdict(dict) |
| 1519 current_smap = '' | 1526 current_smap = '' |
| 1520 for line in self.GetProtectedFileContents('/proc/%s/smaps' % pid, | 1527 for line in self.GetProtectedFileContents('/proc/%s/smaps' % pid): |
| 1521 log_result=False): | |
| 1522 items = line.split() | 1528 items = line.split() |
| 1523 # See man 5 proc for more details. The format is: | 1529 # See man 5 proc for more details. The format is: |
| 1524 # address perms offset dev inode pathname | 1530 # address perms offset dev inode pathname |
| 1525 if len(items) > 5: | 1531 if len(items) > 5: |
| 1526 current_smap = ' '.join(items[5:]) | 1532 current_smap = ' '.join(items[5:]) |
| 1527 elif len(items) > 3: | 1533 elif len(items) > 3: |
| 1528 current_smap = ' '.join(items[3:]) | 1534 current_smap = ' '.join(items[3:]) |
| 1529 match = re.match(MEMORY_INFO_RE, line) | 1535 match = re.match(MEMORY_INFO_RE, line) |
| 1530 if match: | 1536 if match: |
| 1531 key = match.group('key') | 1537 key = match.group('key') |
| 1532 usage_kb = int(match.group('usage_kb')) | 1538 usage_kb = int(match.group('usage_kb')) |
| 1533 usage_dict[key] += usage_kb | 1539 usage_dict[key] += usage_kb |
| 1534 if key not in smaps[current_smap]: | 1540 if key not in smaps[current_smap]: |
| 1535 smaps[current_smap][key] = 0 | 1541 smaps[current_smap][key] = 0 |
| 1536 smaps[current_smap][key] += usage_kb | 1542 smaps[current_smap][key] += usage_kb |
| 1537 if not usage_dict or not any(usage_dict.values()): | 1543 if not usage_dict or not any(usage_dict.values()): |
| 1538 # Presumably the process died between ps and calling this method. | 1544 # Presumably the process died between ps and calling this method. |
| 1539 logging.warning('Could not find memory usage for pid ' + str(pid)) | 1545 logging.warning('Could not find memory usage for pid ' + str(pid)) |
| 1540 | 1546 |
| 1541 for line in self.GetProtectedFileContents('/d/nvmap/generic-0/clients', | 1547 for line in self.GetProtectedFileContents('/d/nvmap/generic-0/clients'): |
| 1542 log_result=False): | |
| 1543 match = re.match(NVIDIA_MEMORY_INFO_RE, line) | 1548 match = re.match(NVIDIA_MEMORY_INFO_RE, line) |
| 1544 if match and match.group('pid') == pid: | 1549 if match and match.group('pid') == pid: |
| 1545 usage_bytes = int(match.group('usage_bytes')) | 1550 usage_bytes = int(match.group('usage_bytes')) |
| 1546 usage_dict['Nvidia'] = int(round(usage_bytes / 1000.0)) # kB | 1551 usage_dict['Nvidia'] = int(round(usage_bytes / 1000.0)) # kB |
| 1547 break | 1552 break |
| 1548 | 1553 |
| 1549 peak_value_kb = 0 | 1554 peak_value_kb = 0 |
| 1550 for line in self.GetProtectedFileContents('/proc/%s/status' % pid, | 1555 for line in self.GetProtectedFileContents('/proc/%s/status' % pid): |
| 1551 log_result=False): | |
| 1552 if not line.startswith('VmHWM:'): # Format: 'VmHWM: +[0-9]+ kB' | 1556 if not line.startswith('VmHWM:'): # Format: 'VmHWM: +[0-9]+ kB' |
| 1553 continue | 1557 continue |
| 1554 peak_value_kb = int(line.split(':')[1].strip().split(' ')[0]) | 1558 peak_value_kb = int(line.split(':')[1].strip().split(' ')[0]) |
| 1555 usage_dict['VmHWM'] = peak_value_kb | 1559 usage_dict['VmHWM'] = peak_value_kb |
| 1556 if not peak_value_kb: | 1560 if not peak_value_kb: |
| 1557 logging.warning('Could not find memory peak value for pid ' + str(pid)) | 1561 logging.warning('Could not find memory peak value for pid ' + str(pid)) |
| 1558 | 1562 |
| 1559 return (usage_dict, smaps) | 1563 return (usage_dict, smaps) |
| 1560 | 1564 |
| 1561 def GetMemoryUsageForPackage(self, package): | 1565 def GetMemoryUsageForPackage(self, package): |
| (...skipping 222 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1784 """ | 1788 """ |
| 1785 def __init__(self, output): | 1789 def __init__(self, output): |
| 1786 self._output = output | 1790 self._output = output |
| 1787 | 1791 |
| 1788 def write(self, data): | 1792 def write(self, data): |
| 1789 data = data.replace('\r\r\n', '\n') | 1793 data = data.replace('\r\r\n', '\n') |
| 1790 self._output.write(data) | 1794 self._output.write(data) |
| 1791 | 1795 |
| 1792 def flush(self): | 1796 def flush(self): |
| 1793 self._output.flush() | 1797 self._output.flush() |
| OLD | NEW |