Exemplo n.º 1
0
    def RunCryptohomeTest(self):
        """Test Cryptohome."""
        logging.info('RunCryptohomeTest: Starting chrome and logging in.')
        is_arc_available = utils.is_arc_available()
        arc_mode = arc_common.ARC_MODE_ENABLED if is_arc_available else None
        with chrome.Chrome(arc_mode=arc_mode, num_tries=1) as cr:
            # Check that the cryptohome is mounted.
            # is_vault_mounted throws an exception if it fails.
            logging.info('Checking mounted cryptohome.')
            cryptohome.is_vault_mounted(user=cr.username, allow_fail=False)
            # Navigate to about:blank.
            tab = cr.browser.tabs[0]
            tab.Navigate('about:blank')

            # Evaluate some javascript.
            logging.info('Evaluating JavaScript.')
            if tab.EvaluateJavaScript('2+2') != 4:
                raise TestFail('EvaluateJavaScript failed')

            # ARC test.
            if is_arc_available:
                arc.wait_for_adb_ready()
                logging.info('Android booted successfully.')
                arc.wait_for_android_process('org.chromium.arc.intent_helper')
                if not arc.is_package_installed('android'):
                    raise TestFail(
                        '"android" system package was not listed by '
                        'Package Manager.')

        if is_arc_available:
            utils.poll_for_condition(
                lambda: not arc.is_android_container_alive(),
                timeout=15,
                desc='Android container still running '
                'after Chrome shutdown.')
    def run_once(self):
        """
        Compare a list of processes, listening on TCP ports, to a
        baseline. Test fails if there are mismatches.
        """
        baseline_filename = _BASELINE_DEFAULT_NAME
        arc_mode = None

        if utils.is_arc_available():
            baseline_filename = _BASELINE_ARC_NAME
            arc_mode = 'enabled'

        with chrome.Chrome(arc_mode=arc_mode):
            cmd = (
                r'lsof -n -i -sTCP:LISTEN | '
                # Workaround for crosbug.com/28235 using a dynamic port #.
                r'sed "s/\\(shill.*127.0.0.1\\):.*/\1:DYNAMIC LISTEN/g"')
            cmd_output = utils.system_output(cmd,
                                             ignore_status=True,
                                             retain_output=True)
            # Use the [1:] slice to discard line 0, the lsof output header.
            lsof_lines = cmd_output.splitlines()[1:]
            # Unlike ps, we don't have a format option so we have to parse
            # lines that look like this:
            # sshd 1915 root 3u IPv4 9221 0t0 TCP *:ssh (LISTEN)
            # Out of that, we just want e.g. sshd *:ssh
            observed_set = set([])
            for line in self.remove_autotest_noise(lsof_lines):
                fields = line.split()
                observed_set.add('%s %s' %
                                 (fields[_LSOF_COMMAND], fields[_LSOF_NAME]))

            baseline_set = self.load_baseline(baseline_filename)
            # TODO(wiley) Remove when we get per-board
            #             baselines (crbug.com/406013)
            if webservd_helper.webservd_is_installed():
                baseline_set.update(self.load_baseline('baseline.webservd'))

            # If something in the observed set is not
            # covered by the baseline...
            new_listeners = observed_set.difference(baseline_set)
            if new_listeners:
                for daemon in new_listeners:
                    logging.error('Unexpected network listener: %s', daemon)

            # Or, things in baseline are missing from the system:
            missing_listeners = baseline_set.difference(observed_set)
            if missing_listeners:
                for daemon in missing_listeners:
                    logging.warning('Missing expected network listener: %s',
                                    daemon)

            # Only fail if there's unexpected listeners.
            if new_listeners:
                raise error.TestFail('Found unexpected network listeners')
Exemplo n.º 3
0
 def close(self):
     """Closes the browser.
     """
     try:
         if utils.is_arc_available():
             arc_util.pre_processing_before_close(self)
     finally:
         # Calling platform.StopAllLocalServers() to tear down the telemetry
         # server processes such as the one started by
         # platform.SetHTTPServerDirectories().  Not calling this function
         # will leak the process and may affect test results.
         # (crbug.com/663387)
         self._browser.platform.StopAllLocalServers()
         self._browser.Close()
         self._browser.platform.network_controller.Close()
 def initialize(self):
     self.keyboard = keyboard.Keyboard()
     self.username, password = arc_util.get_test_account_info()
     # Login a user session.
     if utils.is_arc_available():
         super(platform_LogoutPerf,
               self).initialize(gaia_login=True, disable_arc_opt_in=False)
         self.cr = self._chrome
     else:
         with tempfile.NamedTemporaryFile() as cap:
             file_utils.download_file(arc_util._ARCP_URL, cap.name)
             password = cap.read().rstrip()
         self.cr = chrome.Chrome(gaia_login=True,
                                 username=self.username,
                                 password=password)
def main(args):
    '''The main function.'''
    if args:
        print('No args for vm_sanity.py')
        return os.EX_USAGE

    start = datetime.datetime.now()
    logging.info('Starting chrome and logging in.')
    is_arc_available = utils.is_arc_available()
    arc_mode = arc_common.ARC_MODE_ENABLED if is_arc_available else None
    with chrome.Chrome(arc_mode=arc_mode) as cr:
        # Check that the cryptohome is mounted.
        # is_vault_mounted throws an exception if it fails.
        logging.info('Checking mounted cryptohome.')
        cryptohome.is_vault_mounted(user=cr.username, allow_fail=False)
        # Navigate to about:blank.
        tab = cr.browser.tabs[0]
        tab.Navigate('about:blank')

        # Evaluate some javascript.
        logging.info('Evaluating JavaScript.')
        if tab.EvaluateJavaScript('2+2') != 4:
            raise TestFail('EvaluateJavaScript failed')

        # ARC test.
        if is_arc_available:
            arc.wait_for_android_process('org.chromium.arc.intent_helper')
            arc.wait_for_adb_ready()
            logging.info('Android booted successfully.')
            if not arc.is_package_installed('android'):
                raise TestFail('"android" system package was not listed by '
                               'Package Manager.')

    if is_arc_available:
        utils.poll_for_condition(lambda: not arc.is_adb_connected(),
                                 timeout=15,
                                 desc='Android container still running after '
                                 'Chrome shutdown.')
    elapsed = datetime.datetime.now() - start
    logging.info('Test succeeded in %s seconds.', elapsed.seconds)
Exemplo n.º 6
0
    def __init__(self,
                 logged_in=True,
                 extension_paths=None,
                 autotest_ext=False,
                 num_tries=3,
                 extra_browser_args=None,
                 clear_enterprise_policy=True,
                 expect_policy_fetch=False,
                 dont_override_profile=False,
                 disable_gaia_services=True,
                 disable_default_apps=True,
                 auto_login=True,
                 gaia_login=False,
                 username=None,
                 password=None,
                 gaia_id=None,
                 arc_mode=None,
                 arc_timeout=None,
                 disable_arc_opt_in=True,
                 disable_arc_opt_in_verification=True,
                 disable_arc_cpu_restriction=True,
                 disable_app_sync=False,
                 disable_play_auto_install=False,
                 disable_locale_sync=True,
                 disable_play_store_auto_update=True,
                 enable_assistant=False,
                 enterprise_arc_test=False,
                 init_network_controller=False,
                 mute_audio=False,
                 proxy_server=None,
                 login_delay=0):
        """
        Constructor of telemetry wrapper.

        @param logged_in: Regular user (True) or guest user (False).
        @param extension_paths: path of unpacked extension to install.
        @param autotest_ext: Load a component extension with privileges to
                             invoke chrome.autotestPrivate.
        @param num_tries: Number of attempts to log in.
        @param extra_browser_args: Additional argument(s) to pass to the
                                   browser. It can be a string or a list.
        @param clear_enterprise_policy: Clear enterprise policy before
                                        logging in.
        @param expect_policy_fetch: Expect that chrome can reach the device
                                    management server and download policy.
        @param dont_override_profile: Don't delete cryptohome before login.
                                      Telemetry will output a warning with this
                                      option.
        @param disable_gaia_services: For enterprise autotests, this option may
                                      be used to enable policy fetch.
        @param disable_default_apps: For tests that exercise default apps.
        @param auto_login: Does not login automatically if this is False.
                           Useful if you need to examine oobe.
        @param gaia_login: Logs in to real gaia.
        @param username: Log in using this username instead of the default.
        @param password: Log in using this password instead of the default.
        @param gaia_id: Log in using this gaia_id instead of the default.
        @param arc_mode: How ARC instance should be started.  Default is to not
                         start.
        @param arc_timeout: Timeout to wait for ARC to boot.
        @param disable_arc_opt_in: For opt in flow autotest. This option is used
                                   to disable the arc opt in flow.
        @param disable_arc_opt_in_verification:
             Adds --disable-arc-opt-in-verification to browser args. This should
             generally be enabled when disable_arc_opt_in is enabled. However,
             for data migration tests where user's home data is already set up
             with opted-in state before login, this option needs to be set to
             False with disable_arc_opt_in=True to make ARC container work.
        @param disable_arc_cpu_restriction:
             Adds --disable-arc-cpu-restriction to browser args. This is enabled
             by default and will make tests run faster and is generally
             desirable unless a test is actually trying to test performance
             where ARC is running in the background for some porition of the
             test.
        @param disable_app_sync:
            Adds --arc-disable-app-sync to browser args and this disables ARC
            app sync flow. By default it is enabled.
        @param disable_play_auto_install:
            Adds --arc-disable-play-auto-install to browser args and this
            disables ARC Play Auto Install flow. By default it is enabled.
        @param enable_assistant: For tests that require to enable Google
                                  Assistant service. Default is False.
        @param enterprise_arc_test: Skips opt_in causing enterprise tests to fail
        @param disable_locale_sync:
            Adds --arc-disable-locale-sync to browser args and this
            disables locale sync between Chrome and Android container. In case
            of disabling sync, Android container is started with language and
            preference language list as it was set on the moment of starting
            full instance. Used to prevent random app restarts caused by racy
            locale change, coming from profile sync. By default locale sync is
            disabled.
        @param disable_play_store_auto_update:
            Adds --arc-play-store-auto-update=off to browser args and this
            disables Play Store, GMS Core and third-party apps auto-update.
            By default auto-update is off to have stable autotest environment.
        @param mute_audio: Mute audio.
        @param proxy_server: To launch the chrome with --proxy-server
            Adds '--proxy-server="http://$HTTP_PROXY:PORT"' to browser args. By
            default proxy-server is disabled
        @param login_delay: Time for idle in login screen to simulate the time
                            required for password typing.
        """
        self._autotest_ext_path = None

        # Force autotest extension if we need enable Play Store.
        if (utils.is_arc_available() and
            (arc_util.should_start_arc(arc_mode) or not disable_arc_opt_in)):
            autotest_ext = True

        if extension_paths is None:
            extension_paths = []

        finder_options = browser_options.BrowserFinderOptions()
        if proxy_server:
            finder_options.browser_options.AppendExtraBrowserArgs(
                ['--proxy-server="%s"' % proxy_server])
        if utils.is_arc_available() and arc_util.should_start_arc(arc_mode):
            if disable_arc_opt_in and disable_arc_opt_in_verification:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    ['--disable-arc-opt-in-verification'])
            if disable_arc_cpu_restriction:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    ['--disable-arc-cpu-restriction'])
            if disable_app_sync:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    ['--arc-disable-app-sync'])
            if disable_play_auto_install:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    ['--arc-disable-play-auto-install'])
            if disable_locale_sync:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    ['--arc-disable-locale-sync'])
            if disable_play_store_auto_update:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    ['--arc-play-store-auto-update=off'])
            logged_in = True

        if autotest_ext:
            self._autotest_ext_path = os.path.join(os.path.dirname(__file__),
                                                   'autotest_private_ext')
            extension_paths.append(self._autotest_ext_path)
            finder_options.browser_options.AppendExtraBrowserArgs(
                ['--whitelisted-extension-id=%s' % self.AUTOTEST_EXT_ID])

        self._browser_type = (self.BROWSER_TYPE_LOGIN
                              if logged_in else self.BROWSER_TYPE_GUEST)
        finder_options.browser_type = self.browser_type
        if extra_browser_args:
            finder_options.browser_options.AppendExtraBrowserArgs(
                extra_browser_args)

        # finder options must be set before parse_args(), browser options must
        # be set before Create().
        # TODO(crbug.com/360890) Below MUST be '2' so that it doesn't inhibit
        # autotest debug logs
        finder_options.verbosity = 2
        finder_options.CreateParser().parse_args(args=[])
        b_options = finder_options.browser_options
        b_options.disable_component_extensions_with_background_pages = False
        b_options.create_browser_with_oobe = True
        b_options.clear_enterprise_policy = clear_enterprise_policy
        b_options.dont_override_profile = dont_override_profile
        b_options.disable_gaia_services = disable_gaia_services
        b_options.disable_default_apps = disable_default_apps
        b_options.disable_component_extensions_with_background_pages = disable_default_apps
        b_options.disable_background_networking = False
        b_options.expect_policy_fetch = expect_policy_fetch
        b_options.auto_login = auto_login
        b_options.gaia_login = gaia_login
        b_options.mute_audio = mute_audio
        b_options.login_delay = login_delay

        if utils.is_arc_available() and not disable_arc_opt_in:
            arc_util.set_browser_options_for_opt_in(b_options)

        self.username = b_options.username if username is None else username
        self.password = b_options.password if password is None else password
        self.username = NormalizeEmail(self.username)
        b_options.username = self.username
        b_options.password = self.password
        self.gaia_id = b_options.gaia_id if gaia_id is None else gaia_id
        b_options.gaia_id = self.gaia_id

        self.arc_mode = arc_mode

        if logged_in:
            extensions_to_load = b_options.extensions_to_load
            for path in extension_paths:
                extension = extension_to_load.ExtensionToLoad(
                    path, self.browser_type)
                extensions_to_load.append(extension)
            self._extensions_to_load = extensions_to_load

        # Turn on collection of Chrome coredumps via creation of a magic file.
        # (Without this, Chrome coredumps are trashed.)
        open(constants.CHROME_CORE_MAGIC_FILE, 'w').close()

        self._browser_to_create = browser_finder.FindBrowser(finder_options)
        self._browser_to_create.SetUpEnvironment(b_options)
        for i in range(num_tries):
            try:
                self._browser = self._browser_to_create.Create()
                self._browser_pid = \
                    cros_interface.CrOSInterface().GetChromePid()
                if utils.is_arc_available():
                    if disable_arc_opt_in:
                        if arc_util.should_start_arc(arc_mode):
                            arc_util.enable_play_store(self.autotest_ext, True)
                    else:
                        if not enterprise_arc_test:
                            wait_for_provisioning = \
                                arc_mode != arc_common.ARC_MODE_ENABLED_ASYNC
                            arc_util.opt_in(
                                browser=self.browser,
                                autotest_ext=self.autotest_ext,
                                wait_for_provisioning=wait_for_provisioning)
                    arc_util.post_processing_after_browser(self, arc_timeout)
                if enable_assistant:
                    assistant_util.enable_assistant(self.autotest_ext)
                break
            except exceptions.LoginException as e:
                logging.error('Timed out logging in, tries=%d, error=%s', i,
                              repr(e))
                if i == num_tries - 1:
                    raise
        if init_network_controller:
            self._browser.platform.network_controller.Open()
    def run_once(self):
        errors = set()

        # Max procs, max threads, and file max are dependent upon total memory.
        # The kernel uses a formula similar to:
        #   MemTotal-kb / 128 = max procs
        #   MemTotal-kb / 64 = max threads
        #   MemTotal-kb / 10 = file_max
        # But note that MemTotal changes at the end of initialization.
        # The values used below for these settings should give sufficient head
        # room for usage and kernel allocation.

        ref_min = {
            'file_max': 50000,
            'kptr_restrict': 1,
            'max_open': 1024,
            'max_procs': 3000,
            'max_threads': 7000,
            'ngroups_max': 65536,
            'nr_open': 1048576,
            'pid_max': 32768,
            'mmap_min_addr': 65536,
        }

        ref_equal = {
            'leases': 1,
            'panic': -1,
            'protected_hardlinks': 1,
            'protected_symlinks': 1,
            'ptrace_scope': 1,
            'randomize_va_space': 2,
            'sched_rt_period_us': 1000000,
            'sched_rt_runtime_us': 800000,
            'sysrq': 1,
            'suid-dump': 2,
            'tcp_syncookies': 1,
        }

        refpath = {
            'file_max': '/proc/sys/fs/file-max',
            'leases': '/proc/sys/fs/leases-enable',
            'max_open': '/proc/self/limits',
            'max_procs': '/proc/self/limits',
            'max_threads': '/proc/sys/kernel/threads-max',
            'mmap_min_addr': '/proc/sys/vm/mmap_min_addr',
            'kptr_restrict': '/proc/sys/kernel/kptr_restrict',
            'ngroups_max': '/proc/sys/kernel/ngroups_max',
            'nr_open': '/proc/sys/fs/nr_open',
            'panic': '/proc/sys/kernel/panic',
            'pid_max': '/proc/sys/kernel/pid_max',
            'protected_hardlinks': '/proc/sys/fs/protected_hardlinks',
            'protected_symlinks': '/proc/sys/fs/protected_symlinks',
            'ptrace_scope': '/proc/sys/kernel/yama/ptrace_scope',
            'randomize_va_space': '/proc/sys/kernel/randomize_va_space',
            'sched_rt_period_us': '/proc/sys/kernel/sched_rt_period_us',
            'sched_rt_runtime_us': '/proc/sys/kernel/sched_rt_runtime_us',
            'suid-dump': '/proc/sys/fs/suid_dumpable',
            'sysrq': '/proc/sys/kernel/sysrq',
            'tcp_syncookies': '/proc/sys/net/ipv4/tcp_syncookies',
        }

        # Adjust arch-specific values.
        if utils.get_arch().startswith('arm'):
            ref_min['mmap_min_addr'] = 32768

        if utils.get_arch().startswith('aarch64'):
            ref_min['mmap_min_addr'] = 32768

        # ARM-compatible limit on x86 if ARC++ is present (b/30146997)
        if utils.is_arc_available():
            ref_min['mmap_min_addr'] = 32768

        # Adjust version-specific details.
        kernel_ver = os.uname()[2]
        if utils.compare_versions(kernel_ver, "3.6") < 0:
            # Prior to kernel version 3.6, Yama handled link restrictions.
            refpath['protected_hardlinks'] = \
                '/proc/sys/kernel/yama/protected_nonaccess_hardlinks'
            refpath['protected_symlinks'] = \
                '/proc/sys/kernel/yama/protected_sticky_symlinks'

        # Create osvalue dictionary with the same keys as refpath.
        osvalue = {}
        for key in refpath:
            osvalue[key] = None

        for key in ref_min:
            osvalue[key] = self.get_limit(key, refpath[key])
            if osvalue[key] < ref_min[key]:
                logging.warning('%s is %d', refpath[key], osvalue[key])
                logging.warning('%s should be at least %d', refpath[key],
                                ref_min[key])
                errors.add(key)
            else:
                logging.info('%s is %d >= %d', refpath[key], osvalue[key],
                             ref_min[key])

        for key in ref_equal:
            osvalue[key] = self.get_limit(key, refpath[key])
            if osvalue[key] != ref_equal[key]:
                logging.warning('%s is set to %d', refpath[key], osvalue[key])
                logging.warning('Expected %d', ref_equal[key])
                errors.add(key)
            else:
                logging.info('%s is %d', refpath[key], osvalue[key])

        # Look for anything from refpath that wasn't checked yet:
        for key in osvalue:
            if osvalue[key] == None:
                logging.warning('%s was never checked', key)
                errors.add(key)

        # If self.error is not zero, there were errors.
        if len(errors) > 0:
            raise error.TestFail('Found incorrect values: %s' %
                                 ', '.join(errors))
Exemplo n.º 8
0
    def __init__(self,
                 logged_in=True,
                 extension_paths=[],
                 autotest_ext=False,
                 num_tries=3,
                 extra_browser_args=None,
                 clear_enterprise_policy=True,
                 dont_override_profile=False,
                 disable_gaia_services=True,
                 disable_default_apps=True,
                 auto_login=True,
                 gaia_login=False,
                 username=None,
                 password=None,
                 gaia_id=None,
                 arc_mode=None,
                 disable_arc_opt_in=True,
                 init_network_controller=False):
        """
        Constructor of telemetry wrapper.

        @param logged_in: Regular user (True) or guest user (False).
        @param extension_paths: path of unpacked extension to install.
        @param autotest_ext: Load a component extension with privileges to
                             invoke chrome.autotestPrivate.
        @param num_tries: Number of attempts to log in.
        @param extra_browser_args: Additional argument(s) to pass to the
                                   browser. It can be a string or a list.
        @param clear_enterprise_policy: Clear enterprise policy before
                                        logging in.
        @param dont_override_profile: Don't delete cryptohome before login.
                                      Telemetry will output a warning with this
                                      option.
        @param disable_gaia_services: For enterprise autotests, this option may
                                      be used to enable policy fetch.
        @param disable_default_apps: For tests that exercise default apps.
        @param auto_login: Does not login automatically if this is False.
                           Useful if you need to examine oobe.
        @param gaia_login: Logs in to real gaia.
        @param username: Log in using this username instead of the default.
        @param password: Log in using this password instead of the default.
        @param gaia_id: Log in using this gaia_id instead of the default.
        @param arc_mode: How ARC instance should be started.  Default is to not
                         start.
        @param disable_arc_opt_in: For opt in flow autotest. This option is used
                                   to disable the arc opt in flow.
        """
        self._autotest_ext_path = None

        # Force autotest extension if we need enable Play Store.
        if (utils.is_arc_available() and
            (arc_util.should_start_arc(arc_mode) or not disable_arc_opt_in)):
            autotest_ext = True

        if autotest_ext:
            self._autotest_ext_path = os.path.join(os.path.dirname(__file__),
                                                   'autotest_private_ext')
            extension_paths.append(self._autotest_ext_path)

        finder_options = browser_options.BrowserFinderOptions()
        if utils.is_arc_available() and arc_util.should_start_arc(arc_mode):
            if disable_arc_opt_in:
                finder_options.browser_options.AppendExtraBrowserArgs(
                    arc_util.get_extra_chrome_flags())
            logged_in = True

        self._browser_type = (self.BROWSER_TYPE_LOGIN
                              if logged_in else self.BROWSER_TYPE_GUEST)
        finder_options.browser_type = self.browser_type
        if extra_browser_args:
            finder_options.browser_options.AppendExtraBrowserArgs(
                extra_browser_args)

        # finder options must be set before parse_args(), browser options must
        # be set before Create().
        # TODO(crbug.com/360890) Below MUST be '2' so that it doesn't inhibit
        # autotest debug logs
        finder_options.verbosity = 2
        finder_options.CreateParser().parse_args(args=[])
        b_options = finder_options.browser_options
        b_options.disable_component_extensions_with_background_pages = False
        b_options.create_browser_with_oobe = True
        b_options.clear_enterprise_policy = clear_enterprise_policy
        b_options.dont_override_profile = dont_override_profile
        b_options.disable_gaia_services = disable_gaia_services
        b_options.disable_default_apps = disable_default_apps
        b_options.disable_component_extensions_with_background_pages = disable_default_apps

        b_options.auto_login = auto_login
        b_options.gaia_login = gaia_login

        if utils.is_arc_available() and not disable_arc_opt_in:
            arc_util.set_browser_options_for_opt_in(b_options)

        self.username = b_options.username if username is None else username
        self.password = b_options.password if password is None else password
        self.username = NormalizeEmail(self.username)
        b_options.username = self.username
        b_options.password = self.password
        self.gaia_id = b_options.gaia_id if gaia_id is None else gaia_id
        b_options.gaia_id = self.gaia_id

        self.arc_mode = arc_mode

        if logged_in:
            extensions_to_load = b_options.extensions_to_load
            for path in extension_paths:
                extension = extension_to_load.ExtensionToLoad(
                    path, self.browser_type)
                extensions_to_load.append(extension)
            self._extensions_to_load = extensions_to_load

        # Turn on collection of Chrome coredumps via creation of a magic file.
        # (Without this, Chrome coredumps are trashed.)
        open(constants.CHROME_CORE_MAGIC_FILE, 'w').close()

        for i in range(num_tries):
            try:
                browser_to_create = browser_finder.FindBrowser(finder_options)
                self._browser = browser_to_create.Create(finder_options)
                if utils.is_arc_available():
                    if disable_arc_opt_in:
                        if arc_util.should_start_arc(arc_mode):
                            arc_util.enable_play_store(self.autotest_ext)
                    else:
                        arc_util.opt_in(self.browser, self.autotest_ext)
                    arc_util.post_processing_after_browser(self)
                break
            except exceptions.LoginException as e:
                logging.error('Timed out logging in, tries=%d, error=%s', i,
                              repr(e))
                if i == num_tries - 1:
                    raise
        if init_network_controller:
            self._browser.platform.network_controller.InitializeIfNeeded()
Exemplo n.º 9
0
    def run_once(self):
        """Test main loop."""
        t0 = time.time()

        # record the PSR related info.
        psr = power_utils.DisplayPanelSelfRefresh(init_time=t0)

        try:
            self._keyboard_backlight = power_utils.KbdBacklight()
            self._set_keyboard_backlight_level()
        except power_utils.KbdBacklightException as e:
            logging.info("Assuming no keyboard backlight due to :: %s", str(e))
            self._keyboard_backlight = None

        measurements = []
        if self._power_status.battery:
            measurements += \
                    [power_status.SystemPower(self._power_status.battery_path)]
        if power_utils.has_powercap_support():
            measurements += power_rapl.create_powercap()
        elif power_utils.has_rapl_support():
            measurements += power_rapl.create_rapl()
        self._checkpoint_logger = power_status.CheckpointLogger()
        self._plog = power_status.PowerLogger(measurements,
                seconds_period=20,
                checkpoint_logger=self._checkpoint_logger)
        self._tlog = power_status.TempLogger([],
                seconds_period=20,
                checkpoint_logger=self._checkpoint_logger)
        self._clog = power_status.CPUStatsLogger(
                seconds_period=20,
                checkpoint_logger=self._checkpoint_logger)
        self._meas_logs = [self._plog, self._tlog, self._clog]
        for log in self._meas_logs:
            log.start()
        if self._log_mem_bandwidth:
            self._mlog = memory_bandwidth_logger.MemoryBandwidthLogger(
                raw=False, seconds_period=2)
            self._mlog.start()

        # record start time and end time for each task
        self._task_tracker = []

        ext_path = os.path.join(os.path.dirname(__file__), 'extension')
        self._tmp_keyvals['username'] = self._username

        arc_mode = arc_common.ARC_MODE_DISABLED
        if utils.is_arc_available():
            arc_mode = arc_common.ARC_MODE_ENABLED

        try:
            self._browser = chrome.Chrome(extension_paths=[ext_path],
                                          gaia_login=self._gaia_login,
                                          username=self._username,
                                          password=self._password,
                                          arc_mode=arc_mode)
        except exceptions.LoginException:
            # already failed guest login
            if not self._gaia_login:
                raise
            self._gaia_login = False
            logging.warn("Unable to use GAIA acct %s.  Using GUEST instead.\n",
                         self._username)
            self._browser = chrome.Chrome(extension_paths=[ext_path],
                                          gaia_login=self._gaia_login)
        if not self._gaia_login:
            self._tmp_keyvals['username'] = '******'

        extension = self._browser.get_extension(ext_path)
        for k in params_dict:
            if getattr(self, params_dict[k]) is not '':
                extension.ExecuteJavaScript('var %s = %s;' %
                                            (k, getattr(self, params_dict[k])))

        # This opens a trap start page to capture tabs opened for first login.
        # It will be closed when startTest is run.
        extension.ExecuteJavaScript('chrome.windows.create(null, null);')

        for i in range(self._loop_count):
            start_time = time.time()
            extension.ExecuteJavaScript('startTest();')
            # the power test extension will report its status here
            latch = self._testServer.add_wait_url('/status')

            # this starts a thread in the server that listens to log
            # information from the script
            script_logging = self._testServer.add_wait_url(url='/log')

            # dump any log entry that comes from the script into
            # the debug log
            self._testServer.add_url_handler(url='/log',\
                handler_func=(lambda handler, forms, loop_counter=i:\
                    _extension_log_handler(handler, forms, loop_counter)))

            pagetime_tracking = self._testServer.add_wait_url(url='/pagetime')

            self._testServer.add_url_handler(url='/pagetime',\
                handler_func=(lambda handler, forms, test_instance=self,
                              loop_counter=i:\
                    _extension_page_time_info_handler(handler, forms,
                                                      loop_counter,
                                                      test_instance)))

            # setup a handler to simulate waking up the base of a detachable
            # on user interaction. On scrolling, wake for 1s, on page
            # navigation, wake for 10s.
            self._testServer.add_url(url='/pagenav')
            self._testServer.add_url(url='/scroll')

            self._testServer.add_url_handler(url='/pagenav',
                handler_func=(lambda handler, args, plt=self:
                              plt._detachable_handler.wake_base(10000)))

            self._testServer.add_url_handler(url='/scroll',
                handler_func=(lambda handler, args, plt=self:
                              plt._detachable_handler.wake_base(1000)))
            # reset backlight level since powerd might've modified it
            # based on ambient light
            self._set_backlight_level()
            self._set_lightbar_level()
            if self._keyboard_backlight:
                self._set_keyboard_backlight_level()
            audio_helper.set_volume_levels(self._volume_level,
                                           self._mic_gain)

            low_battery = self._do_wait(self._verbose, self._loop_time,
                                        latch)

            script_logging.set()
            pagetime_tracking.set()

            self._log_loop_checkpoint(i, start_time, time.time())

            if self._verbose:
                logging.debug('loop %d completed', i)

            if low_battery:
                logging.info('Exiting due to low battery')
                break

        # done with logging from the script, so we can collect that thread
        t1 = time.time()
        psr.refresh()
        self._tmp_keyvals['minutes_battery_life_tested'] = (t1 - t0) / 60
        self._tmp_keyvals.update(psr.get_keyvals())
 def cleanup(self):
     self.keyboard.close()
     if utils.is_arc_available():
         super(platform_LogoutPerf, self).cleanup()