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