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