def GetResults(self, timeout): try: return timeout_retry.Run(self._GetResultsImpl, timeout, 1) except reraiser_thread.TimeoutError: print 'GetResults in FtraceAgent timed out.' return tracing_agents.TraceResult('', '')
def StopAgentTracing(self, timeout): try: return timeout_retry.Run(self._StopAgentTracingImpl, timeout, 1) except reraiser_thread.TimeoutError: print 'StopAgentTracing in FtraceAgent timed out.' return False
def timeout_retry_wrapper(*args, **kwargs): timeout = timeout_func(*args, **kwargs) retries = retries_func(*args, **kwargs) if pass_values: kwargs['timeout'] = timeout kwargs['retries'] = retries @functools.wraps(f) def impl(): return f(*args, **kwargs) try: if timeout_retry.CurrentTimeoutThreadGroup(): # Don't wrap if there's already an outer timeout thread. return impl() else: desc = '%s(%s)' % (f.__name__, ', '.join( itertools.chain( (str(a) for a in args), ('%s=%s' % (k, str(v)) for k, v in kwargs.iteritems())))) return timeout_retry.Run( impl, timeout, retries, desc=desc, retry_if_func=retry_if_func) except reraiser_thread.TimeoutError as e: raise device_errors.CommandTimeoutError(str(e)), None, (sys.exc_info()[2]) except cmd_helper.TimeoutError as e: raise device_errors.CommandTimeoutError( str(e), output=e.output), None, (sys.exc_info()[2])
def start_emulator_instance(e): def impl(e): try: e.Start(window=self._emulator_window, writable_system=self._writable_system) except avd.AvdException: logging.exception('Failed to start emulator instance.') return None try: device_utils.DeviceUtils(e.serial).WaitUntilFullyBooted() except base_error.BaseError: e.Stop() raise return e def retry_on_timeout(exc): return (isinstance(exc, device_errors.CommandTimeoutError) or isinstance(exc, reraiser_thread.TimeoutError)) return timeout_retry.Run( impl, # TODO(crbug.com/1093602): Temporarily increase the default timeout # to make sure emulators can start successfully with GLDMA disabled. timeout=120 if self._writable_system else 90, retries=2, args=[e], retry_if_func=retry_on_timeout)
def start_emulator_instance(e): def impl(e): try: e.Start(window=self._emulator_window, writable_system=self._writable_system) except avd.AvdException: logging.exception('Failed to start emulator instance.') return None try: device_utils.DeviceUtils(e.serial).WaitUntilFullyBooted() except base_error.BaseError: e.Stop() raise return e def retry_on_timeout(exc): return (isinstance(exc, device_errors.CommandTimeoutError) or isinstance(exc, reraiser_thread.TimeoutError)) return timeout_retry.Run( impl, timeout=120 if self._writable_system else 30, retries=2, args=[e], retry_if_func=retry_on_timeout)
def StartAgentTracing(self, options, categories, timeout): try: return timeout_retry.Run(self._StartAgentTracingImpl, timeout, 1, args=[options, categories]) except reraiser_thread.TimeoutError: print 'StartAgentTracing in FtraceAgent timed out.' return False
def StartAgentTracing(self, options, _, timeout=10): try: return timeout_retry.Run(self._StartAgentTracingImpl, timeout, 0, args=[options]) except reraiser_thread.TimeoutError: print 'StartAgentTracing in battor_trace_agent timed out.' return False
def Start(self, read_only=True, snapshot_save=False, window=False): """Starts the emulator running an instance of the given AVD.""" with tempfile_ext.TemporaryFileName() as socket_path, ( contextlib.closing(socket.socket(socket.AF_UNIX))) as sock: sock.bind(socket_path) emulator_cmd = [ self._emulator_path, '-avd', self._avd_name, '-report-console', 'unix:%s' % socket_path, ] if read_only: emulator_cmd.append('-read-only') if not snapshot_save: emulator_cmd.append('-no-snapshot-save') emulator_env = {} if self._emulator_home: emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home if window: if 'DISPLAY' in os.environ: emulator_env['DISPLAY'] = os.environ.get('DISPLAY') else: raise AvdException( 'Emulator failed to start: DISPLAY not defined') else: emulator_cmd.append('-no-window') sock.listen(1) logging.info('Starting emulator.') # TODO(jbudorick): Add support for logging emulator stdout & stderr at # higher logging levels. self._sink = open('/dev/null', 'w') self._emulator_proc = cmd_helper.Popen(emulator_cmd, stdout=self._sink, stderr=self._sink, env=emulator_env) # Waits for the emulator to report its serial as requested via # -report-console. See http://bit.ly/2lK3L18 for more. def listen_for_serial(s): logging.info('Waiting for connection from emulator.') with contextlib.closing(s.accept()[0]) as conn: val = conn.recv(1024) return 'emulator-%d' % int(val) try: self._emulator_serial = timeout_retry.Run(listen_for_serial, timeout=30, retries=0, args=[sock]) logging.info('%s started', self._emulator_serial) except Exception as e: self.Stop() raise AvdException('Emulator failed to start: %s' % str(e))
def RunWithTimeout(*args, **kwargs): if 'timeout' in kwargs: timeout = kwargs['timeout'] else: timeout = default_timeout try: return timeout_retry.Run(func, timeout, 0, args=args) except reraiser_thread.TimeoutError: print '%s timed out.' % func.__name__ return False
def testFirstCallHangs(self): """Ensure that reading works even if the first initializer call hangs.""" dyn = DynamicSideEffect( [lambda: time.sleep(10), lambda: 'second try worked!']) initializer = mock.Mock(side_effect=dyn) test_constant = lazy.WeakConstant(initializer) self.assertEquals('second try worked!', timeout_retry.Run(test_constant.read, 1, 1)) initializer.assert_has_calls([mock.call(), mock.call()])
def _SelectDevice(self): if self._remote_device_timeout: try: timeout_retry.Run(self._FindDeviceWithTimeout, self._remote_device_timeout, self._DEFAULT_RETRIES) except reraiser_thread.TimeoutError: self._NoDeviceFound() else: if not self._FindDevice(): self._NoDeviceFound()
def testCurrentTimeoutThreadGroup(self): def InnerFunc(): current_thread_group = timeout_retry.CurrentTimeoutThreadGroup() self.assertIsNotNone(current_thread_group) def InnerInnerFunc(): self.assertEqual(current_thread_group, timeout_retry.CurrentTimeoutThreadGroup()) return True return reraiser_thread.RunAsync((InnerInnerFunc,))[0] self.assertTrue(timeout_retry.Run(InnerFunc, _DEFAULT_TIMEOUT, 3))
def _StartInstance(self): """Starts an AVD instance. Returns: A (Popen, str) 2-tuple that includes the process and serial. """ # Start up the AVD. with tempfile_ext.TemporaryFileName() as socket_path, ( contextlib.closing(socket.socket(socket.AF_UNIX))) as sock: sock.bind(socket_path) emulator_cmd = [ self._emulator_path, '-avd', self._avd_name, '-report-console', 'unix:%s' % socket_path, '-read-only', '-no-window', ] emulator_env = {} if self._emulator_home: emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home sock.listen(1) emulator_proc = cmd_helper.Popen(emulator_cmd, env=emulator_env) def listen_for_serial(s): logging.info('Waiting for connection from emulator.') with contextlib.closing(s.accept()[0]) as conn: val = conn.recv(1024) return 'emulator-%d' % int(val) try: emulator_serial = timeout_retry.Run(listen_for_serial, timeout=30, retries=0, args=[sock]) except Exception: emulator_proc.terminate() raise return (emulator_proc, emulator_serial)
def testReturnValue(self): self.assertTrue(timeout_retry.Run(lambda: True, _DEFAULT_TIMEOUT, 3))
def testRun(self): self.assertTrue(timeout_retry.Run(lambda x: x, 30, 3, [True], {}))
def StartAgentTracing(self, options, categories, timeout=10): # pylint: disable=unused-argument # don't need the options and categories arguments in this # case, but including them for consistency with the # function prototypes for other TracingAgents return timeout_retry.Run(self._StartAgentTracingImpl, timeout, 1)
def StopAgentTracing(self, timeout=10): return timeout_retry.Run(self._StopAgentTracingImpl, timeout, 1)
def GetResults(self, timeout=30): return timeout_retry.Run(self._GetResultsImpl, timeout, 1)
def Start(self, read_only=True, snapshot_save=False, window=False, writable_system=False): """Starts the emulator running an instance of the given AVD.""" with tempfile_ext.TemporaryFileName() as socket_path, (contextlib.closing( socket.socket(socket.AF_UNIX))) as sock: sock.bind(socket_path) emulator_cmd = [ self._emulator_path, '-avd', self._avd_name, '-report-console', 'unix:%s' % socket_path, '-no-boot-anim', ] android_avd_home = os.path.join(self._emulator_home, 'avd') avd_dir = os.path.join(android_avd_home, '%s.avd' % self._avd_name) hardware_qemu_path = os.path.join(avd_dir, 'hardware-qemu.ini') if os.path.exists(hardware_qemu_path): with open(hardware_qemu_path) as hardware_qemu_file: hardware_qemu_contents = ini.load(hardware_qemu_file) else: hardware_qemu_contents = {} if read_only: emulator_cmd.append('-read-only') if not snapshot_save: emulator_cmd.append('-no-snapshot-save') if writable_system: emulator_cmd.append('-writable-system') emulator_env = {} if self._emulator_home: emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home if window: if 'DISPLAY' in os.environ: emulator_env['DISPLAY'] = os.environ.get('DISPLAY') else: raise AvdException('Emulator failed to start: DISPLAY not defined') else: emulator_cmd.append('-no-window') hardware_qemu_contents['hw.sdCard'] = 'true' if self._avd_config.avd_settings.sdcard.size: sdcard_path = os.path.join(self._emulator_home, 'avd', '%s.avd' % self._avd_name, 'cr-sdcard.img') if not os.path.exists(sdcard_path): mksdcard_path = os.path.join( os.path.dirname(self._emulator_path), 'mksdcard') mksdcard_cmd = [ mksdcard_path, self._avd_config.avd_settings.sdcard.size, sdcard_path, ] cmd_helper.RunCmd(mksdcard_cmd) emulator_cmd.extend(['-sdcard', sdcard_path]) hardware_qemu_contents['hw.sdCard.path'] = sdcard_path with open(hardware_qemu_path, 'w') as hardware_qemu_file: ini.dump(hardware_qemu_contents, hardware_qemu_file) sock.listen(1) logging.info('Starting emulator.') # TODO(jbudorick): Add support for logging emulator stdout & stderr at # higher logging levels. self._sink = open('/dev/null', 'w') self._emulator_proc = cmd_helper.Popen( emulator_cmd, stdout=self._sink, stderr=self._sink, env=emulator_env) # Waits for the emulator to report its serial as requested via # -report-console. See http://bit.ly/2lK3L18 for more. def listen_for_serial(s): logging.info('Waiting for connection from emulator.') with contextlib.closing(s.accept()[0]) as conn: val = conn.recv(1024) return 'emulator-%d' % int(val) try: self._emulator_serial = timeout_retry.Run( listen_for_serial, timeout=30, retries=0, args=[sock]) logging.info('%s started', self._emulator_serial) except Exception as e: self.Stop() raise AvdException('Emulator failed to start: %s' % str(e))
def GetResults(self, timeout=30): try: return timeout_retry.Run(self._GetResultsImpl, timeout, 1) except reraiser_thread.TimeoutError: print "GetResults in AtraceAgent timed out."
def StartAgentTracing(self, options, categories, timeout=10): return timeout_retry.Run(self._StartAgentTracingImpl, timeout, 1, args=[options, categories])
def Start(self, ensure_system_settings=True, read_only=True, window=False, writable_system=False, gpu_mode=_DEFAULT_GPU_MODE, wipe_data=False, debug_tags=None): """Starts the emulator running an instance of the given AVD. Note when ensure_system_settings is True, the program will wait until the emulator is fully booted, and then update system settings. """ is_slow_start = False # Force to load system snapshot if detected. if self.HasSystemSnapshot(): if not writable_system: logging.info( 'System snapshot found. Set "writable_system=True" ' 'to load it properly.') writable_system = True if read_only: logging.info('System snapshot found. Set "read_only=False" ' 'to load it properly.') read_only = False elif writable_system: is_slow_start = True logging.warning( 'Emulator will be slow to start, as ' '"writable_system=True" but system snapshot not found.') self._writable_system = writable_system with tempfile_ext.TemporaryFileName() as socket_path, ( contextlib.closing(socket.socket(socket.AF_UNIX))) as sock: sock.bind(socket_path) emulator_cmd = [ self._emulator_path, '-avd', self._avd_name, '-report-console', 'unix:%s' % socket_path, '-no-boot-anim', # Explicitly prevent emulator from auto-saving to snapshot on exit. '-no-snapshot-save', # Explicitly set the snapshot name for auto-load '-snapshot', self.GetSnapshotName(), ] if wipe_data: emulator_cmd.append('-wipe-data') if read_only: emulator_cmd.append('-read-only') if writable_system: emulator_cmd.append('-writable-system') # Note when "--gpu-mode" is set to "host": # * It needs a valid DISPLAY env, even if "--emulator-window" is false. # Otherwise it may throw errors like "Failed to initialize backend # EGL display". See the code in https://bit.ly/3ruiMlB as an example # to setup the DISPLAY env with xvfb. # * It will not work under remote sessions like chrome remote desktop. if gpu_mode: emulator_cmd.extend(['-gpu', gpu_mode]) if debug_tags: emulator_cmd.extend(['-debug', debug_tags]) emulator_env = {} if self._emulator_home: emulator_env['ANDROID_EMULATOR_HOME'] = self._emulator_home if 'DISPLAY' in os.environ: emulator_env['DISPLAY'] = os.environ.get('DISPLAY') if window: if 'DISPLAY' not in emulator_env: raise AvdException( 'Emulator failed to start: DISPLAY not defined') else: emulator_cmd.append('-no-window') sock.listen(1) logging.info('Starting emulator...') logging.info( ' With environments: %s', ' '.join(['%s=%s' % (k, v) for k, v in emulator_env.items()])) logging.info(' With commands: %s', ' '.join(emulator_cmd)) # TODO(jbudorick): Add support for logging emulator stdout & stderr at # higher logging levels. # Enable the emulator log when debug_tags is set. if not debug_tags: self._sink = open('/dev/null', 'w') self._emulator_proc = cmd_helper.Popen(emulator_cmd, stdout=self._sink, stderr=self._sink, env=emulator_env) # Waits for the emulator to report its serial as requested via # -report-console. See http://bit.ly/2lK3L18 for more. def listen_for_serial(s): logging.info('Waiting for connection from emulator.') with contextlib.closing(s.accept()[0]) as conn: val = conn.recv(1024) return 'emulator-%d' % int(val) try: self._emulator_serial = timeout_retry.Run(listen_for_serial, timeout=30, retries=0, args=[sock]) logging.info('%s started', self._emulator_serial) except Exception as e: self.Stop() # avd.py is executed with python2. # pylint: disable=W0707 raise AvdException('Emulator failed to start: %s' % str(e)) # Set the system settings in "Start" here instead of setting in "Create" # because "Create" is used during AVD creation, and we want to avoid extra # turn-around on rolling AVD. if ensure_system_settings: assert self.device is not None, '`instance.device` not initialized.' self.device.WaitUntilFullyBooted( timeout=120 if is_slow_start else 30) _EnsureSystemSettings(self.device)
def GetResults(self, timeout=30): try: return timeout_retry.Run(self._GetResultsImpl, timeout, 0) except reraiser_thread.TimeoutError: print 'GetResults in battor_trace_agent timed out.' return TraceResult('', '')
def StopAgentTracing(self, timeout=10): try: return timeout_retry.Run(self._StopAgentTracingImpl, timeout, 0) except reraiser_thread.TimeoutError: print 'StopAgentTracing in battor_trace_agent timed out.' return False