def test_relative_path(self): tempdir = tempfile.mkdtemp() # make a dummy profile profile = FirefoxProfile(os.path.join(tempdir, 'testprofilepath'), restore=False) self.assertTrue(os.path.exists(os.path.join(tempdir, 'testprofilepath', 'user.js'))) # make a dummy test test = """function test() { };""" f = file(os.path.join(tempdir, 'test_dummy.js'), 'w') f.write(test) f.close() # run mozmill on it process = ProcessHandler(['mozmill', '-t', 'test_dummy.js', '--profile=testprofilepath'], cwd=tempdir, # stop mozmill from printing output to console processOutputLine=[lambda line: None]) process.run() process.wait() self.assertNotEqual(process.proc.poll(), None) # cleanup shutil.rmtree(tempdir)
def test_all_js(tests, options): print "Running JS Tests" # We run each test in its own instance since these are harness tests. # That just seems safer, no opportunity for cross-talk since # we are sorta using the framework to test itself results = JSResults() for t in tests: # write a temporary manifest manifest = TestManifest() manifest.tests = [t] fd, filename = tempfile.mkstemp(suffix=".ini") os.close(fd) fp = file(filename, "w") manifest.write(fp=fp) fp.close() # get CLI arguments to mozmill args = ["-b", options.binary] args.append("--console-level=DEBUG") args.append("-m") args.append(filename) # run the test proc = ProcessHandler("mozmill", args=args) proc.run() status = proc.waitForFinish(timeout=300) command = proc.commandline results.acquire(t["name"], proc.output, status, command) # remove the temporary manifest os.remove(filename) return results
def setup_avds(self): ''' If tooltool cache mechanism is enabled, the cached version is used by the fetch command. If the manifest includes an "unpack" field, tooltool will unpack all compressed archives mentioned in the manifest. ''' c = self.config dirs = self.query_abs_dirs() # FIXME # Clobbering and re-unpacking would not be needed if we had a way to # check whether the unpacked content already present match the # contents of the tar ball self.rmtree(dirs['abs_avds_dir']) self.mkdir_p(dirs['abs_avds_dir']) if 'avd_url' in c: # Intended for experimental setups to evaluate an avd prior to # tooltool deployment. url = c['avd_url'] self.download_unpack(url, dirs['abs_avds_dir']) else: url = self._get_repo_url(c["tooltool_manifest_path"]) self._tooltool_fetch(url, dirs['abs_avds_dir']) avd_home_dir = self.abs_dirs['abs_avds_dir'] if avd_home_dir != "/home/cltbld/.android": # Modify the downloaded avds to point to the right directory. cmd = [ 'bash', '-c', 'sed -i "s|/home/cltbld/.android|%s|" %s/test-*.ini' % (avd_home_dir, os.path.join(avd_home_dir, 'avd')) ] proc = ProcessHandler(cmd) proc.run() proc.wait()
def test_relative_path(self): tempdir = tempfile.mkdtemp() # make a dummy profile profile = FirefoxProfile(os.path.join(tempdir, 'testprofilepath'), restore=False) self.assertTrue(os.path.exists(os.path.join(tempdir, 'testprofilepath', 'user.js'))) # make a dummy test test = """var test = function () { };""" f = file(os.path.join(tempdir, 'test_dummy.js'), 'w') f.write(test) f.close() # run mozmill on it process = ProcessHandler(['mozmill', '-t', 'test_dummy.js', '--profile=testprofilepath'], cwd=tempdir) code = process.waitForFinish(timeout=120) self.assertEqual(code, 0) # cleanup shutil.rmtree(tempdir)
def build_script(self, modules=None, debug=False, profiling=False, noftu=False, noopt=False, valgrind=False): command = [os.path.join(self.b2g_home, 'build.sh')] if modules: command.extend(modules) if debug: command.insert(0, 'B2G_DEBUG=1') if profiling: command.insert(0, 'MOZ_PROFILING=1') if noftu: command.insert(0, 'NOFTU=1') if noopt: if profiling: print("Can't perform profiling if optimizer is disabled") return 1 command.insert(0, 'B2G_NOOPT=1') if valgrind: command.insert(0, 'B2G_VALGRIND=1') p = ProcessHandler(command) p.run() #TODO: Error checking. return p.wait()
def flash(self): command = os.path.join(self.b2g_home, 'flash.sh') p = ProcessHandler(command) if _is_device_attached(): p.run() return p.wait() return 1
def setup_avds(self): ''' If tooltool cache mechanism is enabled, the cached version is used by the fetch command. If the manifest includes an "unpack" field, tooltool will unpack all compressed archives mentioned in the manifest. ''' c = self.config dirs = self.query_abs_dirs() # Always start with a clean AVD: AVD includes Android images # which can be stateful. self.rmtree(dirs['abs_avds_dir']) self.mkdir_p(dirs['abs_avds_dir']) if 'avd_url' in c: # Intended for experimental setups to evaluate an avd prior to # tooltool deployment. url = c['avd_url'] self.download_unpack(url, dirs['abs_avds_dir']) else: url = self._get_repo_url(c["tooltool_manifest_path"]) self._tooltool_fetch(url, dirs['abs_avds_dir']) avd_home_dir = self.abs_dirs['abs_avds_dir'] if avd_home_dir != "/home/cltbld/.android": # Modify the downloaded avds to point to the right directory. cmd = [ 'bash', '-c', 'sed -i "s|/home/cltbld/.android|%s|" %s/test-*.ini' % (avd_home_dir, os.path.join(avd_home_dir, 'avd')) ] proc = ProcessHandler(cmd) proc.run() proc.wait()
def gdb(self): command = os.path.join(self.b2g_home, 'run-gdb.sh') p = ProcessHandler(command) p.run() #TODO The emulator requires adb to run, we should check if that is #running, catch that error or better yet, start adb. return p.wait()
class ServoRefTestExecutor(ProcessTestExecutor): convert_result = reftest_result_converter def __init__(self, browser, http_server_url, binary=None, timeout_multiplier=1, screenshot_cache=None, debug_args=None, pause_after_test=False): ProcessTestExecutor.__init__(self, browser, http_server_url, timeout_multiplier=timeout_multiplier, debug_args=debug_args) self.protocol = Protocol(self, browser, http_server_url) self.screenshot_cache = screenshot_cache self.implementation = RefTestImplementation(self) self.tempdir = tempfile.mkdtemp() def teardown(self): os.rmdir(self.tempdir) ProcessTestExecutor.teardown(self) def screenshot(self, url, timeout): full_url = urlparse.urljoin(self.http_server_url, url) with TempFilename(self.tempdir) as output_path: self.command = [self.binary, "--cpu", "--hard-fail", "--exit", "--output=%s" % output_path, full_url] self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output]) self.proc.run() rv = self.proc.wait(timeout=timeout) if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv < 0: return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, data def do_test(self, test): result = self.implementation.run_test(test) return self.convert_result(test, result) def on_output(self, line): line = line.decode("utf8", "replace") if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command))
def __init__(self, cmd, args=None, cwd=None, env=os.environ.copy(), ignore_children=False, **kwargs): ProcessHandler.__init__(self, cmd, args=args, cwd=cwd, env=env, ignore_children=ignore_children, **kwargs) self.logger = mozlog.getLogger('PEP')
def pushDir(self, localDir, remoteDir, retryLimit=None, timeout=None): # adb "push" accepts a directory as an argument, but if the directory # contains symbolic links, the links are pushed, rather than the linked # files; we either zip/unzip or re-copy the directory into a temporary # one to get around this limitation retryLimit = retryLimit or self.retryLimit if self._useZip: self.removeDir(remoteDir) self.mkDirs(remoteDir + "/x") try: localZip = tempfile.mktemp() + ".zip" remoteZip = remoteDir + "/adbdmtmp.zip" proc = ProcessHandler(["zip", "-r", localZip, '.'], cwd=localDir, processOutputLine=self._log) proc.run() proc.wait() self.pushFile(localZip, remoteZip, retryLimit=retryLimit, createDir=False) mozfile.remove(localZip) data = self._runCmd(["shell", "unzip", "-o", remoteZip, "-d", remoteDir]).output[0] self._checkCmd(["shell", "rm", remoteZip], retryLimit=retryLimit, timeout=self.short_timeout) if re.search("unzip: exiting", data) or re.search("Operation not permitted", data): raise Exception("unzip failed, or permissions error") except Exception: self._logger.warning(traceback.format_exc()) self._logger.warning("zip/unzip failure: falling back to normal push") self._useZip = False self.pushDir(localDir, remoteDir, retryLimit=retryLimit, timeout=timeout) else: localDir = os.path.normpath(localDir) remoteDir = os.path.normpath(remoteDir) tempParent = tempfile.mkdtemp() remoteName = os.path.basename(remoteDir) newLocal = os.path.join(tempParent, remoteName) dir_util.copy_tree(localDir, newLocal) # See do_sync_push in # https://android.googlesource.com/platform/system/core/+/master/adb/file_sync_client.cpp # Work around change in behavior in adb 1.0.36 where if # the remote destination directory exists, adb push will # copy the source directory *into* the destination # directory otherwise it will copy the source directory # *onto* the destination directory. if self._adb_version >= '1.0.36': remoteDir = '/'.join(remoteDir.rstrip('/').split('/')[:-1]) try: if self._checkCmd(["push", newLocal, remoteDir], retryLimit=retryLimit, timeout=timeout): raise DMError("failed to push %s (copy of %s) to %s" % (newLocal, localDir, remoteDir)) except BaseException: raise finally: mozfile.remove(tempParent)
def _isLocalZipAvailable(self): def _noOutput(line): # suppress output from zip ProcessHandler pass try: proc = ProcessHandler(["zip", "-?"], storeOutput=False, processOutputLine=_noOutput) proc.run() proc.wait() except: return False return True
def test_no_option(self): process = ProcessHandler(['mozmill', '-b', os.environ['BROWSER_PATH'], '-t', os.path.join(testdir, 'useMozmill', 'testServerRoot.js') ], # stop mozmill from printing output to console processOutputLine=[lambda line: None]) process.run() process.wait() self.assertEqual(process.proc.poll(), 1, 'Test failed')
def start_logcat(self, serial, logfile=None, stream=None, filterspec=None): logcat_args = [self.app_ctx.adb, '-s', '%s' % serial, 'logcat', '-v', 'time', '-b', 'main', '-b', 'radio'] # only log filterspec if filterspec: logcat_args.extend(['-s', filterspec]) process_args = {} if logfile: process_args['logfile'] = logfile elif stream: process_args['stream'] = stream proc = ProcessHandler(logcat_args, **process_args) proc.run() return proc
def __init__(self, cmd, args=None, cwd=None, env=None, ignore_children=False, logfile=None, **kwargs): self.firstTime = int(time.time()) * 1000 self.logfile = logfile self.results_file = None if env is None: env = os.environ.copy() ProcessHandler.__init__(self, cmd, args=args, cwd=cwd, env=env, ignore_children=ignore_children, logfile=self.logfile, **kwargs)
def test_options(self): absdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) testdir = os.path.join(absdir, 'js-tests') process = ProcessHandler(['mozmill', '-b', os.environ['BROWSER_PATH'], '-t', os.path.join(testdir, 'test_module1.js'), '-m', os.path.join(testdir, 'example.ini') ]) process.run() process.waitForFinish() self.assertNotEqual(process.proc.poll(), 0, 'Parser error due to -t and -m are mutually exclusive')
def _runCmd(self, args): """ Runs a command using adb returns: instance of ProcessHandler """ finalArgs = [self._adbPath] if self._deviceSerial: finalArgs.extend(['-s', self._deviceSerial]) finalArgs.extend(args) self._logger.debug("_runCmd - command: %s" % ' '.join(finalArgs)) proc = ProcessHandler(finalArgs, storeOutput=True, processOutputLine=self._log) proc.run() proc.returncode = proc.wait() return proc
def start(self): """ Starts a new emulator. """ if self.proc: return original_devices = set(self._get_online_devices()) qemu_log = None qemu_proc_args = {} if self.logdir: # save output from qemu to logfile qemu_log = os.path.join(self.logdir, 'qemu.log') if os.path.isfile(qemu_log): self._rotate_log(qemu_log) qemu_proc_args['logfile'] = qemu_log else: qemu_proc_args['processOutputLine'] = lambda line: None self.proc = ProcessHandler(self.args, **qemu_proc_args) self.proc.run() devices = set(self._get_online_devices()) now = datetime.datetime.now() while (devices - original_devices) == set([]): time.sleep(1) if datetime.datetime.now() - now > datetime.timedelta(seconds=60): raise TimeoutException('timed out waiting for emulator to start') devices = set(self._get_online_devices()) devices = devices - original_devices self.serial = devices.pop() self.connect()
def screenshot(self, test): full_url = self.test_url(test) with TempFilename(self.tempdir) as output_path: self.command = [self.binary, "--cpu", "--hard-fail", "--exit", "-Z", "disable-text-aa", "--output=%s" % output_path, full_url] env = os.environ.copy() env["HOST_FILE"] = self.hosts_path self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, base64.b64encode(data)
def screenshot(self, test): full_url = self.test_url(test) with TempFilename(self.tempdir) as output_path: debug_args, command = browser_command( self.binary, [ "--cpu", "--hard-fail", "--exit", "-u", "Servo/wptrunner", "-Z", "disable-text-aa", "--output=%s" % output_path, full_url, ], self.debug_info, ) for stylesheet in self.browser.user_stylesheets: command += ["--user-stylesheet", stylesheet] for pref in test.environment.get("prefs", {}): command += ["--pref", pref] self.command = debug_args + command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise else: self.proc = subprocess.Popen(self.command, env=env) try: rv = self.proc.wait() except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, base64.b64encode(data)
def run_test(self, test): self.result_data = None self.result_flag = threading.Event() self.command = [self.binary, "--cpu", "--hard-fail", urlparse.urljoin(self.http_server_url, test.url)] if self.debug_args: self.command = list(self.debug_args) + self.command self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], onFinish=self.on_finish) self.proc.run() timeout = test.timeout * self.timeout_multiplier # Now wait to get the output we expect, or until we reach the timeout self.result_flag.wait(timeout + 5) if self.result_flag.is_set() and self.result_data is not None: self.result_data["test"] = test.url result = self.convert_result(test, self.result_data) self.proc.kill() else: if self.proc.proc.poll() is not None: result = (test.result_cls("CRASH", None), []) else: self.proc.kill() result = (test.result_cls("TIMEOUT", None), []) self.runner.send_message("test_ended", test, result)
def start(self): """ Launch the emulator. """ def outputHandler(line): self.emulator_log.write("<%s>\n" % line) env = os.environ env['ANDROID_AVD_HOME'] = os.path.join(EMULATOR_HOME_DIR, "avd") command = [self.emulator_path, "-avd", self.avd_info.name, "-port", "5554"] if self.avd_info.extra_args: # -enable-kvm option is not valid on OSX if _get_host_platform() == 'macosx64' and '-enable-kvm' in self.avd_info.extra_args: self.avd_info.extra_args.remove('-enable-kvm') command += self.avd_info.extra_args log_path = os.path.join(EMULATOR_HOME_DIR, 'emulator.log') self.emulator_log = open(log_path, 'w') _log_debug("Starting the emulator with this command: %s" % ' '.join(command)) _log_debug("Emulator output will be written to '%s'" % log_path) self.proc = ProcessHandler( command, storeOutput=False, processOutputLine=outputHandler, env=env) self.proc.run() _log_debug("Emulator started with pid %d" % int(self.proc.proc.pid))
def test_option(self): process = ProcessHandler(['mozmill', '-b', os.environ['BROWSER_PATH'], '-t', os.path.join(testdir, 'useMozmill', 'testServerRoot.js'), '--server-root', os.path.join(testdir, '../../data'), ], # stop mozmill from printing output to console processOutputLine=[lambda line: None]) process.run() process.wait() self.assertEqual(process.proc.poll(), 0, 'Test was run successful')
def connect(self): """ Connects to a running device. If no serial was specified in the constructor, defaults to the first entry in `adb devices`. """ if self.connected: return if self.serial: serial = self.serial else: online_devices = self._get_online_devices() if not online_devices: raise IOError("No devices connected. Ensure the device is on and remote debugging via adb is enabled in the settings.") serial = online_devices[0] self.dm._deviceSerial = serial self.dm.connect() self.connected = True if self.logdir: # save logcat logcat_log = os.path.join(self.logdir, '%s.log' % serial) if os.path.isfile(logcat_log): self._rotate_log(logcat_log) logcat_args = [self.app_ctx.adb, '-s', '%s' % serial, 'logcat', '-v', 'time'] self.logcat_proc = ProcessHandler(logcat_args, logfile=logcat_log) self.logcat_proc.run()
def start(self): self.webdriver_port = get_free_port(4444, exclude=self.used_ports) self.used_ports.add(self.webdriver_port) env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" debug_args, command = browser_command( self.binary, [ "--hard-fail", "--webdriver", str(self.webdriver_port), "about:blank", ], self.debug_info ) for stylesheet in self.user_stylesheets: command += ["--user-stylesheet", stylesheet] self.command = command self.command = debug_args + self.command if not self.debug_info or not self.debug_info.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) self.logger.debug("Servo Started")
def start(self): """ Launch the emulator. """ if os.path.exists(EMULATOR_AUTH_FILE): os.remove(EMULATOR_AUTH_FILE) _log_debug("deleted %s" % EMULATOR_AUTH_FILE) # create an empty auth file to disable emulator authentication auth_file = open(EMULATOR_AUTH_FILE, "w") auth_file.close() def outputHandler(line): self.emulator_log.write("<%s>\n" % line) env = os.environ env["ANDROID_AVD_HOME"] = os.path.join(EMULATOR_HOME_DIR, "avd") command = [self.emulator_path, "-avd", self.avd_info.name, "-port", "5554"] if self.avd_info.extra_args: # -enable-kvm option is not valid on OSX if _get_host_platform() == "macosx64" and "-enable-kvm" in self.avd_info.extra_args: self.avd_info.extra_args.remove("-enable-kvm") command += self.avd_info.extra_args log_path = os.path.join(EMULATOR_HOME_DIR, "emulator.log") self.emulator_log = open(log_path, "w") _log_debug("Starting the emulator with this command: %s" % " ".join(command)) _log_debug("Emulator output will be written to '%s'" % log_path) self.proc = ProcessHandler(command, storeOutput=False, processOutputLine=outputHandler, env=env) self.proc.run() _log_debug("Emulator started with pid %d" % int(self.proc.proc.pid))
def connect(self, devices=None): """ Connects to an already running emulator. """ devices = list(devices or self._get_online_devices()) serial = [d for d in devices if d.startswith('emulator')][0] self.dm._deviceSerial = serial self.dm.connect() self.port = int(serial[serial.rindex('-')+1:]) self.geo.set_default_location() self.screen.initialize() print self.logdir if self.logdir: # save logcat logcat_log = os.path.join(self.logdir, '%s.log' % serial) if os.path.isfile(logcat_log): self._rotate_log(logcat_log) logcat_args = [self.app_ctx.adb, '-s', '%s' % serial, 'logcat', '-v', 'threadtime'] self.logcat_proc = ProcessHandler(logcat_args, logfile=logcat_log) self.logcat_proc.run() # setup DNS fix for networking self.app_ctx.dm.shellCheckOutput(['setprop', 'net.dns1', '10.0.2.3'])
def test_pref(self): absdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) testdir = os.path.join(absdir, 'js-modules') process = ProcessHandler(['mozmill', '-b', os.environ['BROWSER_PATH'], '-t', os.path.join(testdir, 'useMozmill', 'testPref.js'), '--pref=abc:123' ], # stop mozmill from printing output to console processOutputLine=[lambda line: None]) process.run() process.wait() self.assertEqual(process.proc.poll(), 0, 'Test passed')
def test_options(self): absdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) testdir = os.path.join(absdir, 'js-tests') process = ProcessHandler(['mozmill', '-b', os.environ['BROWSER_PATH'], '-t', os.path.join(testdir, 'testUsemozmillControllerOpen.js'), '-m', os.path.join(testdir, 'tests-null.ini') ], # stop mozmill from printing output to console processOutputLine=[lambda line: None]) process.run() process.wait() self.assertNotEqual(process.proc.poll(), 0, 'Parser error due to -t and -m are mutually exclusive')
def _runCmd(self, args, timeout=None, retryLimit=None): """ Runs a command using adb If timeout is specified, the process is killed after <timeout> seconds. returns: instance of ProcessHandler """ retryLimit = retryLimit or self.retryLimit finalArgs = [self._adbPath] if self._serverHost is not None: finalArgs.extend(['-H', self._serverHost]) if self._serverPort is not None: finalArgs.extend(['-P', str(self._serverPort)]) if self._deviceSerial: finalArgs.extend(['-s', self._deviceSerial]) finalArgs.extend(args) self._logger.debug("_runCmd - command: %s" % ' '.join(finalArgs)) if not timeout: timeout = self.default_timeout def _timeout(): self._logger.error("Timeout exceeded for _runCmd call '%s'" % ' '.join(finalArgs)) retries = 0 while retries < retryLimit: proc = ProcessHandler(finalArgs, storeOutput=True, processOutputLine=self._log, onTimeout=_timeout) proc.run(timeout=timeout) proc.returncode = proc.wait() if proc.returncode == None: proc.kill() retries += 1 else: return proc
def run_browser( command, minidump_dir, timeout=None, on_started=None, debug=None, debugger=None, debugger_args=None, **kwargs ): """ Run the browser using the given `command`. After the browser prints __endTimestamp, we give it 5 seconds to quit and kill it if it's still alive at that point. Note that this method ensure that the process is killed at the end. If this is not possible, an exception will be raised. :param command: the commad (as a string list) to run the browser :param minidump_dir: a path where to extract minidumps in case the browser hang. This have to be the same value used in `mozcrash.check_for_crashes`. :param timeout: if specified, timeout to wait for the browser before we raise a :class:`TalosError` :param on_started: a callback that can be used to do things just after the browser has been started. The callback must takes an argument, which is the psutil.Process instance :param kwargs: additional keyword arguments for the :class:`ProcessHandler` instance Returns a ProcessContext instance, with available output and pid used. """ debugger_info = find_debugger_info(debug, debugger, debugger_args) if debugger_info is not None: return run_in_debug_mode( command, debugger_info, on_started=on_started, env=kwargs.get("env") ) is_launcher = sys.platform.startswith("win") and "-wait-for-browser" in command context = ProcessContext(is_launcher) first_time = int(time.time()) * 1000 wait_for_quit_timeout = 20 event = Event() reader = Reader(event) LOG.info("Using env: %s" % pprint.pformat(kwargs["env"])) kwargs["storeOutput"] = False kwargs["processOutputLine"] = reader kwargs["onFinish"] = event.set proc = ProcessHandler(command, **kwargs) reader.proc = proc proc.run() LOG.process_start(proc.pid, " ".join(command)) try: context.process = psutil.Process(proc.pid) if on_started: on_started(context.process) # wait until we saw __endTimestamp in the proc output, # or the browser just terminated - or we have a timeout if not event.wait(timeout): LOG.info("Timeout waiting for test completion; killing browser...") # try to extract the minidump stack if the browser hangs kill_and_get_minidump(context, minidump_dir) raise TalosError("timeout") if reader.got_end_timestamp: for i in six.moves.range(1, wait_for_quit_timeout): if proc.wait(1) is not None: break if proc.poll() is None: LOG.info( "Browser shutdown timed out after {0} seconds, killing" " process.".format(wait_for_quit_timeout) ) kill_and_get_minidump(context, minidump_dir) raise TalosError( "Browser shutdown timed out after {0} seconds, killed" " process.".format(wait_for_quit_timeout) ) elif reader.got_timeout: raise TalosError("TIMEOUT: %s" % reader.timeout_message) elif reader.got_error: raise TalosError("unexpected error") finally: # this also handle KeyboardInterrupt # ensure early the process is really terminated return_code = None try: return_code = context.kill_process() if return_code is None: return_code = proc.wait(1) except Exception: # Maybe killed by kill_and_get_minidump(), maybe ended? LOG.info("Unable to kill process") LOG.info(traceback.format_exc()) reader.output.append( "__startBeforeLaunchTimestamp%d__endBeforeLaunchTimestamp" % first_time ) reader.output.append( "__startAfterTerminationTimestamp%d__endAfterTerminationTimestamp" % (int(time.time()) * 1000) ) if return_code is not None: LOG.process_exit(proc.pid, return_code) else: LOG.debug("Unable to detect exit code of the process %s." % proc.pid) context.output = reader.output return context
def screenshot(self, test, viewport_size, dpi): full_url = self.test_url(test) with TempFilename(self.tempdir) as output_path: debug_args, command = browser_command( self.binary, [ "--hard-fail", "--exit", "-u", "Servo/wptrunner", "-Z", "disable-text-aa,load-webfonts-synchronously,replace-surrogates", "--output=%s" % output_path, full_url ] + self.browser.binary_args, self.debug_info) for stylesheet in self.browser.user_stylesheets: command += ["--user-stylesheet", stylesheet] for pref, value in test.environment.get('prefs', {}).iteritems(): command += ["--pref", "%s=%s" % (pref, value)] command += ["--resolution", viewport_size or "800x600"] if self.browser.ca_certificate_path: command += ["--certificate-path", self.browser.ca_certificate_path] if dpi: command += ["--device-pixel-ratio", dpi] # Run ref tests in headless mode command += ["-z"] self.command = debug_args + command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise else: self.proc = subprocess.Popen(self.command, env=env) try: rv = self.proc.wait() except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, base64.b64encode(data)
class ServoRefTestExecutor(ProcessTestExecutor): convert_result = reftest_result_converter def __init__(self, browser, server_config, binary=None, timeout_multiplier=1, screenshot_cache=None, debug_info=None, pause_after_test=False): do_delayed_imports() ProcessTestExecutor.__init__(self, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.protocol = Protocol(self, browser) self.screenshot_cache = screenshot_cache self.implementation = RefTestImplementation(self) self.tempdir = tempfile.mkdtemp() self.hosts_path = make_hosts_file() def teardown(self): try: os.unlink(self.hosts_path) except OSError: pass os.rmdir(self.tempdir) ProcessTestExecutor.teardown(self) def screenshot(self, test, viewport_size, dpi): full_url = self.test_url(test) with TempFilename(self.tempdir) as output_path: debug_args, command = browser_command( self.binary, [ "--hard-fail", "--exit", "-u", "Servo/wptrunner", "-Z", "disable-text-aa,load-webfonts-synchronously,replace-surrogates", "--output=%s" % output_path, full_url ] + self.browser.binary_args, self.debug_info) for stylesheet in self.browser.user_stylesheets: command += ["--user-stylesheet", stylesheet] for pref, value in test.environment.get('prefs', {}).iteritems(): command += ["--pref", "%s=%s" % (pref, value)] command += ["--resolution", viewport_size or "800x600"] if self.browser.ca_certificate_path: command += ["--certificate-path", self.browser.ca_certificate_path] if dpi: command += ["--device-pixel-ratio", dpi] # Run ref tests in headless mode command += ["-z"] self.command = debug_args + command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise else: self.proc = subprocess.Popen(self.command, env=env) try: rv = self.proc.wait() except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, base64.b64encode(data) def do_test(self, test): result = self.implementation.run_test(test) return self.convert_result(test, result) def on_output(self, line): line = line.decode("utf8", "replace") if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command))
class Device(object): connected = False logcat_proc = None def __init__(self, app_ctx, logdir=None, serial=None, restore=True): self.app_ctx = app_ctx self.dm = self.app_ctx.dm self.restore = restore self.serial = serial self.logdir = os.path.abspath(os.path.expanduser(logdir)) self.added_files = set() self.backup_files = set() @property def remote_profiles(self): """ A list of remote profiles on the device. """ remote_ini = self.app_ctx.remote_profiles_ini if not self.dm.fileExists(remote_ini): raise IOError("Remote file '%s' not found" % remote_ini) local_ini = tempfile.NamedTemporaryFile() self.dm.getFile(remote_ini, local_ini.name) cfg = ConfigParser() cfg.read(local_ini.name) profiles = [] for section in cfg.sections(): if cfg.has_option(section, 'Path'): if cfg.has_option(section, 'IsRelative') and cfg.getint(section, 'IsRelative'): profiles.append(posixpath.join(posixpath.dirname(remote_ini), \ cfg.get(section, 'Path'))) else: profiles.append(cfg.get(section, 'Path')) return profiles def pull_minidumps(self): """ Saves any minidumps found in the remote profile on the local filesystem. :returns: Path to directory containing the dumps. """ remote_dump_dir = posixpath.join(self.app_ctx.remote_profile, 'minidumps') local_dump_dir = tempfile.mkdtemp() self.dm.getDirectory(remote_dump_dir, local_dump_dir) if os.listdir(local_dump_dir): for f in self.dm.listFiles(remote_dump_dir): self.dm.removeFile(posixpath.join(remote_dump_dir, f)) return local_dump_dir def setup_profile(self, profile): """ Copy profile to the device and update the remote profiles.ini to point to the new profile. :param profile: mozprofile object to copy over. """ self.dm.remount() if self.dm.dirExists(self.app_ctx.remote_profile): self.dm.shellCheckOutput(['rm', '-r', self.app_ctx.remote_profile]) self.dm.pushDir(profile.profile, self.app_ctx.remote_profile) timeout = 5 # seconds starttime = datetime.datetime.now() while datetime.datetime.now() - starttime < datetime.timedelta(seconds=timeout): if self.dm.fileExists(self.app_ctx.remote_profiles_ini): break time.sleep(1) else: print "timed out waiting for profiles.ini" local_profiles_ini = tempfile.NamedTemporaryFile() self.dm.getFile(self.app_ctx.remote_profiles_ini, local_profiles_ini.name) config = ProfileConfigParser() config.read(local_profiles_ini.name) for section in config.sections(): if 'Profile' in section: config.set(section, 'IsRelative', 0) config.set(section, 'Path', self.app_ctx.remote_profile) new_profiles_ini = tempfile.NamedTemporaryFile() config.write(open(new_profiles_ini.name, 'w')) self.backup_file(self.app_ctx.remote_profiles_ini) self.dm.pushFile(new_profiles_ini.name, self.app_ctx.remote_profiles_ini) # Ideally all applications would read the profile the same way, but in practice # this isn't true. Perform application specific profile-related setup if necessary. if hasattr(self.app_ctx, 'setup_profile'): for remote_path in self.app_ctx.remote_backup_files: self.backup_file(remote_path) self.app_ctx.setup_profile(profile) def _get_online_devices(self): return [d[0] for d in self.dm.devices() if d[1] != 'offline' if not d[0].startswith('emulator')] def connect(self): """ Connects to a running device. If no serial was specified in the constructor, defaults to the first entry in `adb devices`. """ if self.connected: return if self.serial: serial = self.serial else: online_devices = self._get_online_devices() if not online_devices: raise IOError("No devices connected. Ensure the device is on and remote debugging via adb is enabled in the settings.") serial = online_devices[0] self.dm._deviceSerial = serial self.dm.connect() self.connected = True if self.logdir: # save logcat logcat_log = os.path.join(self.logdir, '%s.log' % serial) if os.path.isfile(logcat_log): self._rotate_log(logcat_log) logcat_args = [self.app_ctx.adb, '-s', '%s' % serial, 'logcat', '-v', 'time', '-b', 'main', '-b', 'radio'] self.logcat_proc = ProcessHandler(logcat_args, logfile=logcat_log) self.logcat_proc.run() def reboot(self): """ Reboots the device via adb. """ self.dm.reboot(wait=True) def install_busybox(self, busybox): """ Installs busybox on the device. :param busybox: Path to busybox binary to install. """ self.dm.remount() print 'pushing %s' % self.app_ctx.remote_busybox self.dm.pushFile(busybox, self.app_ctx.remote_busybox, retryLimit=10) # TODO for some reason using dm.shellCheckOutput doesn't work, # while calling adb shell directly does. args = [self.app_ctx.adb, '-s', self.dm._deviceSerial, 'shell', 'cd /system/bin; chmod 555 busybox;' \ 'for x in `./busybox --list`; do ln -s ./busybox $x; done'] adb = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) adb.wait() self.dm._verifyZip() def setup_port_forwarding(self, local_port=None, remote_port=2828): """ Set up TCP port forwarding to the specified port on the device, using any availble local port (if none specified), and return the local port. :param local_port: The local port to forward from, if unspecified a random port is chosen. :param remote_port: The remote port to forward to, defaults to 2828. :returns: The local_port being forwarded. """ if not local_port: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("",0)) local_port = s.getsockname()[1] s.close() self.dm.forward('tcp:%d' % int(local_port), 'tcp:%d' % int(remote_port)) return local_port def wait_for_net(self): active = False time_out = 0 while not active and time_out < 40: proc = subprocess.Popen([self.app_ctx.adb, 'shell', '/system/bin/netcfg'], stdout=subprocess.PIPE) proc.stdout.readline() # ignore first line line = proc.stdout.readline() while line != "": if (re.search(r'UP\s+[1-9]\d{0,2}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line)): active = True break line = proc.stdout.readline() time_out += 1 time.sleep(1) return active def wait_for_port(self, port, timeout=300): starttime = datetime.datetime.now() while datetime.datetime.now() - starttime < datetime.timedelta(seconds=timeout): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', port)) data = sock.recv(16) sock.close() if ':' in data: return True except: traceback.print_exc() time.sleep(1) return False def backup_file(self, remote_path): if not self.restore: return if self.dm.fileExists(remote_path) or self.dm.dirExists(remote_path): self.dm.copyTree(remote_path, '%s.orig' % remote_path) self.backup_files.add(remote_path) else: self.added_files.add(remote_path) def cleanup(self): """ Cleanup the device. """ if not self.restore: return try: self.dm._verifyDevice() except DMError: return self.dm.remount() # Restore the original profile for added_file in self.added_files: self.dm.removeFile(added_file) for backup_file in self.backup_files: if self.dm.fileExists('%s.orig' % backup_file) or self.dm.dirExists('%s.orig' % backup_file): self.dm.moveTree('%s.orig' % backup_file, backup_file) # Perform application specific profile cleanup if necessary if hasattr(self.app_ctx, 'cleanup_profile'): self.app_ctx.cleanup_profile() # Remove the test profile self.dm.removeDir(self.app_ctx.remote_profile) def _rotate_log(self, srclog, index=1): """ Rotate a logfile, by recursively rotating logs further in the sequence, deleting the last file if necessary. """ basename = os.path.basename(srclog) basename = basename[:-len('.log')] if index > 1: basename = basename[:-len('.1')] basename = '%s.%d.log' % (basename, index) destlog = os.path.join(self.logdir, basename) if os.path.isfile(destlog): if index == 3: os.remove(destlog) else: self._rotate_log(destlog, index+1) shutil.move(srclog, destlog)
def _run_python_test(self, test): from mozprocess import ProcessHandler output = [] def _log(line): # Buffer messages if more than one worker to avoid interleaving if self.jobs > 1: output.append(line) else: self.log(logging.INFO, "python-test", {"line": line.rstrip()}, "{line}") file_displayed_test = [] # used as boolean def _line_handler(line): line = six.ensure_str(line) if not file_displayed_test: output = ( "Ran" in line or "collected" in line or line.startswith("TEST-") ) if output: file_displayed_test.append(True) # Hack to make sure treeherder highlights pytest failures if "FAILED" in line.rsplit(" ", 1)[-1]: line = line.replace("FAILED", "TEST-UNEXPECTED-FAIL") _log(line) _log(test["path"]) python = self.virtualenv_manager.python_path cmd = [python, test["path"]] env = os.environ.copy() if six.PY2: env[b"PYTHONDONTWRITEBYTECODE"] = b"1" else: env["PYTHONDONTWRITEBYTECODE"] = "1" # Homebrew on OS X will change Python's sys.executable to a custom value # which messes with mach's virtualenv handling code. Override Homebrew's # changes with the correct sys.executable value. if six.PY2: env[b"PYTHONEXECUTABLE"] = python.encode("utf-8") else: env["PYTHONEXECUTABLE"] = python proc = ProcessHandler( cmd, env=env, processOutputLine=_line_handler, storeOutput=False ) proc.run() return_code = proc.wait() if not file_displayed_test: _log( "TEST-UNEXPECTED-FAIL | No test output (missing mozunit.main() " "call?): {}".format(test["path"]) ) if self.verbose: if return_code != 0: _log("Test failed: {}".format(test["path"])) else: _log("Test passed: {}".format(test["path"])) return output, return_code, test["path"]
def lint(paths, config, binary=None, fix=None, setup=None, **lintargs): """Run eslint.""" setup_helper.set_project_root(lintargs['root']) module_path = setup_helper.get_project_root() # Valid binaries are: # - Any provided by the binary argument. # - Any pointed at by the ESLINT environmental variable. # - Those provided by |mach lint --setup|. if not binary: binary, _ = find_node_executable() if not binary: print(ESLINT_NOT_FOUND_MESSAGE) return 1 extra_args = lintargs.get('extra_args') or [] exclude_args = [] for path in config.get('exclude', []): exclude_args.extend( ['--ignore-pattern', os.path.relpath(path, lintargs['root'])]) cmd_args = [ binary, os.path.join(module_path, "node_modules", "eslint", "bin", "eslint.js"), # This keeps ext as a single argument. '--ext', '[{}]'.format(','.join(config['extensions'])), '--format', 'json', ] + extra_args + exclude_args + paths # eslint requires that --fix be set before the --ext argument. if fix: cmd_args.insert(2, '--fix') shell = False if os.environ.get('MSYSTEM') in ('MINGW32', 'MINGW64'): # The eslint binary needs to be run from a shell with msys shell = True orig = signal.signal(signal.SIGINT, signal.SIG_IGN) proc = ProcessHandler(cmd_args, env=os.environ, stream=None, shell=shell) proc.run() signal.signal(signal.SIGINT, orig) try: proc.wait() except KeyboardInterrupt: proc.kill() return [] if not proc.output: return [] # no output means success try: jsonresult = json.loads(proc.output[0]) except ValueError: print(ESLINT_ERROR_MESSAGE.format("\n".join(proc.output))) return 1 results = [] for obj in jsonresult: errors = obj['messages'] for err in errors: err.update({ 'hint': err.get('fix'), 'level': 'error' if err['severity'] == 2 else 'warning', 'lineno': err.get('line') or 0, 'path': obj['filePath'], 'rule': err.get('ruleId'), }) results.append(result.from_config(config, **err)) return results
def start_mitmproxy_playback(self, mitmdump_path, browser_path): """Startup mitmproxy and replay the specified flow file""" if self.mitmproxy_proc is not None: raise Exception("Proxy already started.") self.port = get_available_port() LOG.info("mitmdump path: %s" % mitmdump_path) LOG.info("browser path: %s" % browser_path) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env = os.environ.copy() env["PATH"] = os.path.dirname(browser_path) + os.pathsep + env["PATH"] command = [mitmdump_path] # add proxy host and port options command.extend( ["--listen-host", self.host, "--listen-port", str(self.port)]) if "playback_tool_args" in self.config: LOG.info("Staring Proxy using provided command line!") command.extend(self.config["playback_tool_args"]) elif "playback_files" in self.config: script = os.path.join( os.path.dirname(os.path.realpath(__file__)), "scripts", "alternate-server-replay.py", ) recording_paths = [ normalize_path(recording_path) for recording_path in self.config["playback_files"] ] if self.config["playback_version"] in ["4.0.4", "5.0.1"]: args = [ "-v", "--set", "upstream_cert=false", "--set", "upload_dir=" + normalize_path(self.upload_dir), "--set", "websocket=false", "--set", "server_replay_files={}".format(",".join(recording_paths)), "--scripts", normalize_path(script), ] command.extend(args) else: raise Exception("Mitmproxy version is unknown!") else: raise Exception( "Mitmproxy can't start playback! Playback settings missing.") LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"]) LOG.info("Starting mitmproxy playback using command: %s" % " ".join(command)) # to turn off mitmproxy log output, use these params for Popen: # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) self.mitmproxy_proc = ProcessHandler( command, logfile=os.path.join(self.upload_dir, "mitmproxy.log"), env=env, processStderrLine=LOG.error, storeOutput=False, ) self.mitmproxy_proc.run() end_time = time.time() + MITMDUMP_COMMAND_TIMEOUT ready = False while time.time() < end_time: ready = self.check_proxy(host=self.host, port=self.port) if ready: LOG.info( "Mitmproxy playback successfully started on %s:%d as pid %d" % (self.host, self.port, self.mitmproxy_proc.pid)) return time.sleep(0.25) # cannot continue as we won't be able to playback the pages LOG.error("Aborting: Mitmproxy process did not startup") self.stop_mitmproxy_playback() sys.exit() # XXX why do we need to do that? a raise is not enough?
def test_help(install_mozproxy): p = ProcessHandler(["mozproxy", "--help"]) p.run() assert p.wait() == 0
class Mitmproxy(Playback): def __init__(self, config): self.config = config self.mitmproxy_proc = None self.mitmdump_path = None self.browser_path = config.get("binary") self.policies_dir = None self.ignore_mitmdump_exit_failure = config.get( "ignore_mitmdump_exit_failure", False ) if self.config.get("playback_version") is None: LOG.info("mitmproxy was not provided with a 'playback_version' " "getting 'playback_version' from 'playback_binary_manifest'") if "4.0.4" in self.config["playback_binary_manifest"]: self.config["playback_version"] = "4.0.4" else: self.config["playback_version"] = "2.0.2" # mozproxy_dir is where we will download all mitmproxy required files # when running locally it comes from obj_path via mozharness/mach if self.config.get("obj_path") is not None: self.mozproxy_dir = self.config.get("obj_path") else: # in production it is ../tasks/task_N/build/, in production that dir # is not available as an envvar, however MOZ_UPLOAD_DIR is set as # ../tasks/task_N/build/blobber_upload_dir so take that and go up 1 level self.mozproxy_dir = os.path.dirname( os.path.dirname(os.environ["MOZ_UPLOAD_DIR"]) ) self.mozproxy_dir = os.path.join(self.mozproxy_dir, "testing", "mozproxy") self.upload_dir = os.environ.get("MOZ_UPLOAD_DIR", self.mozproxy_dir) LOG.info( "mozproxy_dir used for mitmproxy downloads and exe files: %s" % self.mozproxy_dir ) # setting up the MOZPROXY_DIR env variable so custom scripts know # where to get the data os.environ["MOZPROXY_DIR"] = self.mozproxy_dir def start(self): # go ahead and download and setup mitmproxy self.download() # mitmproxy must be started before setup, so that the CA cert is available self.start_mitmproxy_playback(self.mitmdump_path, self.browser_path) # In case the setup fails, we want to stop the process before raising. try: self.setup() except Exception: self.stop() raise def download(self): """Download and unpack mitmproxy binary and pageset using tooltool""" if not os.path.exists(self.mozproxy_dir): os.makedirs(self.mozproxy_dir) _manifest = os.path.join(here, self.config["playback_binary_manifest"]) transformed_manifest = transform_platform(_manifest, self.config["platform"]) # generate the mitmdump_path self.mitmdump_path = os.path.join(self.mozproxy_dir, "mitmdump-%s" % self.config["playback_version"], "mitmdump") # Check if mitmproxy bin exists if os.path.exists(self.mitmdump_path): LOG.info("mitmproxy binary already exists. Skipping download") else: # Download and unpack mitmproxy binary download_path = os.path.dirname(self.mitmdump_path) LOG.info("create mitmproxy %s dir" % self.config["playback_version"]) if not os.path.exists(download_path): os.makedirs(download_path) LOG.info("downloading mitmproxy binary") tooltool_download( transformed_manifest, self.config["run_local"], download_path) if "playback_pageset_manifest" in self.config: # we use one pageset for all platforms LOG.info("downloading mitmproxy pageset") _manifest = self.config["playback_pageset_manifest"] transformed_manifest = transform_platform( _manifest, self.config["platform"] ) tooltool_download( transformed_manifest, self.config["run_local"], self.mozproxy_dir ) if "playback_artifacts" in self.config: artifacts = self.config["playback_artifacts"].split(",") for artifact in artifacts: artifact = artifact.strip() if not artifact: continue artifact_name = artifact.split("/")[-1] if artifact_name.endswith(".manifest"): tooltool_download( artifact, self.config["run_local"], self.mozproxy_dir ) else: dest = os.path.join(self.mozproxy_dir, artifact_name) download_file_from_url(artifact, dest, extract=True) def stop(self): self.stop_mitmproxy_playback() def start_mitmproxy_playback(self, mitmdump_path, browser_path): """Startup mitmproxy and replay the specified flow file""" if self.mitmproxy_proc is not None: raise Exception("Proxy already started.") LOG.info("mitmdump path: %s" % mitmdump_path) LOG.info("browser path: %s" % browser_path) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env = os.environ.copy() env["PATH"] = os.path.dirname(browser_path) + os.pathsep + env["PATH"] command = [mitmdump_path] if "playback_tool_args" in self.config: command.extend(self.config["playback_tool_args"]) LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"]) LOG.info("Starting mitmproxy playback using command: %s" % " ".join(command)) # to turn off mitmproxy log output, use these params for Popen: # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) self.mitmproxy_proc = ProcessHandler( command, logfile=os.path.join(self.upload_dir, "mitmproxy.log"), env=env ) self.mitmproxy_proc.run() end_time = time.time() + MITMDUMP_COMMAND_TIMEOUT ready = False while time.time() < end_time: ready = self.check_proxy() if ready: LOG.info( "Mitmproxy playback successfully started as pid %d" % self.mitmproxy_proc.pid ) return time.sleep(0.25) # cannot continue as we won't be able to playback the pages LOG.error("Aborting: Mitmproxy process did not startup") self.stop_mitmproxy_playback() sys.exit() # XXX why do we need to do that? a raise is not enough? def stop_mitmproxy_playback(self): """Stop the mitproxy server playback""" if self.mitmproxy_proc is None or self.mitmproxy_proc.poll() is not None: return LOG.info( "Stopping mitmproxy playback, killing process %d" % self.mitmproxy_proc.pid ) exit_code = self.mitmproxy_proc.kill() if exit_code != 0: # I *think* we can still continue, as process will be automatically # killed anyway when mozharness is done (?) if not, we won't be able # to startup mitmxproy next time if it is already running if exit_code is None: LOG.error("Failed to kill the mitmproxy playback process") else: log_func = LOG.error if self.ignore_mitmdump_exit_failure: log_func = LOG.info log_func("Mitmproxy exited with error code %d" % exit_code) else: LOG.info("Successfully killed the mitmproxy playback process") self.mitmproxy_proc = None def check_proxy(self, host="localhost", port=8080): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) s.shutdown(socket.SHUT_RDWR) s.close() return True except socket.error: return False
def start_mitmproxy_playback(self, mitmdump_path, mitmproxy_recording_path, mitmproxy_recordings_list, browser_path): """Startup mitmproxy and replay the specified flow file""" LOG.info("mitmdump path: %s" % mitmdump_path) LOG.info("recording path: %s" % mitmproxy_recording_path) LOG.info("recordings list: %s" % mitmproxy_recordings_list) LOG.info("browser path: %s" % browser_path) mitmproxy_recordings = [] # recording names can be provided in comma-separated list; build py list including path for recording in mitmproxy_recordings_list: if not os.path.isfile( os.path.join(mitmproxy_recording_path, recording)): LOG.critical('Recording file {} cannot be found!'.format( os.path.join(mitmproxy_recording_path, recording))) raise Exception('Recording file {} cannot be found!'.format( os.path.join(mitmproxy_recording_path, recording))) mitmproxy_recordings.append( os.path.join(mitmproxy_recording_path, recording)) # cmd line to start mitmproxy playback using custom playback script is as follows: # <path>/mitmdump -s "<path>mitmdump-alternate-server-replay/alternate-server-replay.py # <path>recording-1.mp <path>recording-2.mp..." param = os.path.join(here, 'alternate-server-replay.py') env = os.environ.copy() # this part is platform-specific if mozinfo.os == 'win': param2 = '""' + param.replace('\\', '\\\\\\') + ' ' + \ ' '.join(mitmproxy_recordings).replace('\\', '\\\\\\') + '""' sys.path.insert(1, mitmdump_path) else: # mac and linux param2 = param + ' ' + ' '.join(mitmproxy_recordings) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env["PATH"] = os.path.dirname(browser_path) + ";" + env["PATH"] command = [mitmdump_path, '-k', '-q', '-s', param2] LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"]) LOG.info("Starting mitmproxy playback using command: %s" % ' '.join(command)) # to turn off mitmproxy log output, use these params for Popen: # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) mitmproxy_proc = ProcessHandler(command, env=env) mitmproxy_proc.run() time.sleep(MITMDUMP_SLEEP) data = mitmproxy_proc.poll() if data is None: # None value indicates process hasn't terminated LOG.info("Mitmproxy playback successfully started as pid %d" % mitmproxy_proc.pid) return mitmproxy_proc # cannot continue as we won't be able to playback the pages LOG.error( 'Aborting: mitmproxy playback process failed to start, poll returned: %s' % data) sys.exit()
def shell(self, cmd, outputfile, env=None, cwd=None, timeout=None, root=False): # FIXME: this function buffers all output of the command into memory, # always. :( # If requested to run as root, check that we can actually do that if root and not self._haveRootShell and not self._haveSu: raise DMError( "Shell command '%s' requested to run as root but root " "is not available on this device. Root your device or " "refactor the test/harness to not require root." % self._escapedCommandLine(cmd)) # Getting the return code is more complex than you'd think because adb # doesn't actually return the return code from a process, so we have to # capture the output to get it if root and not self._haveRootShell: cmdline = "su -c \"%s\"" % self._escapedCommandLine(cmd) else: cmdline = self._escapedCommandLine(cmd) cmdline += "; echo $?" # prepend cwd and env to command if necessary if cwd: cmdline = "cd %s; %s" % (cwd, cmdline) if env: envstr = '; '.join( map(lambda x: 'export %s=%s' % (x[0], x[1]), env.iteritems())) cmdline = envstr + "; " + cmdline # all output should be in stdout args = [self._adbPath] if self._deviceSerial: args.extend(['-s', self._deviceSerial]) args.extend(["shell", cmdline]) def _raise(): raise DMError("Timeout exceeded for shell call") self._logger.debug("shell - command: %s" % ' '.join(args)) proc = ProcessHandler(args, processOutputLine=self._log, onTimeout=_raise) if not timeout: # We are asserting that all commands will complete in this time unless otherwise specified timeout = self.default_timeout timeout = int(timeout) proc.run(timeout) proc.wait() output = proc.output if output: lastline = output[-1] if lastline: m = re.search('([0-9]+)', lastline) if m: return_code = m.group(1) for line in output: outputfile.write(line + '\n') outputfile.seek(-2, 2) outputfile.truncate() # truncate off the return code return int(return_code) return None
class ServoWebDriverBrowser(Browser): used_ports = set() def __init__(self, logger, binary, debug_info=None, webdriver_host="127.0.0.1", user_stylesheets=None): Browser.__init__(self, logger) self.binary = binary self.webdriver_host = webdriver_host self.webdriver_port = None self.proc = None self.debug_info = debug_info self.hosts_path = write_hosts_file() self.command = None self.user_stylesheets = user_stylesheets if user_stylesheets else [] def start(self, **kwargs): self.webdriver_port = get_free_port(4444, exclude=self.used_ports) self.used_ports.add(self.webdriver_port) env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" debug_args, command = browser_command(self.binary, [ "--hard-fail", "--webdriver", str(self.webdriver_port), "about:blank", ], self.debug_info) for stylesheet in self.user_stylesheets: command += ["--user-stylesheet", stylesheet] self.command = command self.command = debug_args + self.command if not self.debug_info or not self.debug_info.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) self.logger.debug("Servo Started") def stop(self, force=False): self.logger.debug("Stopping browser") if self.proc is not None: try: self.proc.kill() except OSError: # This can happen on Windows if the process is already dead pass def pid(self): if self.proc is None: return None try: return self.proc.pid except AttributeError: return None def on_output(self, line): """Write a line of output from the process to the log""" self.logger.process_output(self.pid(), line.decode("utf8", "replace"), command=" ".join(self.command)) def is_alive(self): if self.runner: return self.runner.is_running() return False def cleanup(self): self.stop() shutil.rmtree(os.path.dirname(self.hosts_file)) def executor_browser(self): assert self.webdriver_port is not None return ExecutorBrowser, { "webdriver_host": self.webdriver_host, "webdriver_port": self.webdriver_port }
def __init__(self, config, *args, **kwargs): self.config = config kwargs["stream"] = False ProcessHandler.__init__(self, *args, **kwargs)
class Mitmproxy(Playback): def __init__(self, config): self.config = config self.host = ("127.0.0.1" if "localhost" in self.config["host"] else self.config["host"]) self.port = None self.mitmproxy_proc = None self.mitmdump_path = None self.browser_path = os.path.normpath(config.get("binary")) self.policies_dir = None self.ignore_mitmdump_exit_failure = config.get( "ignore_mitmdump_exit_failure", False) if self.config.get("playback_version") is None: LOG.info("mitmproxy was not provided with a 'playback_version' " "Using default playback version: 4.0.4") self.config["playback_version"] = "4.0.4" if self.config.get("playback_binary_manifest") is None: LOG.info( "mitmproxy was not provided with a 'playback_binary_manifest' " "Using default playback_binary_manifest") self.config["playback_binary_manifest"] = ( "mitmproxy-rel-bin-%s-{platform}.manifest" % self.config["playback_version"]) # mozproxy_dir is where we will download all mitmproxy required files # when running locally it comes from obj_path via mozharness/mach if self.config.get("obj_path") is not None: self.mozproxy_dir = self.config.get("obj_path") else: # in production it is ../tasks/task_N/build/, in production that dir # is not available as an envvar, however MOZ_UPLOAD_DIR is set as # ../tasks/task_N/build/blobber_upload_dir so take that and go up 1 level self.mozproxy_dir = os.path.dirname( os.path.dirname(os.environ["MOZ_UPLOAD_DIR"])) self.mozproxy_dir = os.path.join(self.mozproxy_dir, "testing", "mozproxy") self.upload_dir = os.environ.get("MOZ_UPLOAD_DIR", self.mozproxy_dir) LOG.info( "mozproxy_dir used for mitmproxy downloads and exe files: %s" % self.mozproxy_dir) # setting up the MOZPROXY_DIR env variable so custom scripts know # where to get the data os.environ["MOZPROXY_DIR"] = self.mozproxy_dir LOG.info("Playback tool: %s" % self.config["playback_tool"]) LOG.info("Playback tool version: %s" % self.config["playback_version"]) def start(self): # go ahead and download and setup mitmproxy self.download() # mitmproxy must be started before setup, so that the CA cert is available self.start_mitmproxy_playback(self.mitmdump_path, self.browser_path) # In case the setup fails, we want to stop the process before raising. try: self.setup() except Exception: self.stop() raise def download(self): """Download and unpack mitmproxy binary and pageset using tooltool""" if not os.path.exists(self.mozproxy_dir): os.makedirs(self.mozproxy_dir) _manifest = os.path.join(here, self.config["playback_binary_manifest"]) transformed_manifest = transform_platform(_manifest, self.config["platform"]) # generate the mitmdump_path self.mitmdump_path = os.path.normpath( os.path.join( self.mozproxy_dir, "mitmdump-%s" % self.config["playback_version"], "mitmdump", )) # Check if mitmproxy bin exists if os.path.exists(self.mitmdump_path): LOG.info("mitmproxy binary already exists. Skipping download") else: # Download and unpack mitmproxy binary download_path = os.path.dirname(self.mitmdump_path) LOG.info("create mitmproxy %s dir" % self.config["playback_version"]) if not os.path.exists(download_path): os.makedirs(download_path) LOG.info("downloading mitmproxy binary") tooltool_download(transformed_manifest, self.config["run_local"], download_path) if "playback_pageset_manifest" in self.config: # we use one pageset for all platforms LOG.info("downloading mitmproxy pageset") _manifest = self.config["playback_pageset_manifest"] transformed_manifest = transform_platform(_manifest, self.config["platform"]) tooltool_download(transformed_manifest, self.config["run_local"], self.mozproxy_dir) if "playback_artifacts" in self.config: artifacts = self.config["playback_artifacts"].split(",") for artifact in artifacts: artifact = artifact.strip() if not artifact: continue artifact_name = artifact.split("/")[-1] if artifact_name.endswith(".manifest"): tooltool_download(artifact, self.config["run_local"], self.mozproxy_dir) else: dest = os.path.join(self.mozproxy_dir, artifact_name) download_file_from_url(artifact, dest, extract=True) def stop(self): self.stop_mitmproxy_playback() def start_mitmproxy_playback(self, mitmdump_path, browser_path): """Startup mitmproxy and replay the specified flow file""" if self.mitmproxy_proc is not None: raise Exception("Proxy already started.") self.port = get_available_port() LOG.info("mitmdump path: %s" % mitmdump_path) LOG.info("browser path: %s" % browser_path) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env = os.environ.copy() env["PATH"] = os.path.dirname(browser_path) + os.pathsep + env["PATH"] command = [mitmdump_path] # add proxy host and port options command.extend( ["--listen-host", self.host, "--listen-port", str(self.port)]) if "playback_tool_args" in self.config: LOG.info("Staring Proxy using provided command line!") command.extend(self.config["playback_tool_args"]) elif "playback_files" in self.config: script = os.path.join( os.path.dirname(os.path.realpath(__file__)), "scripts", "alternate-server-replay.py", ) recording_paths = [ normalize_path(recording_path) for recording_path in self.config["playback_files"] ] if self.config["playback_version"] in ["4.0.4", "5.0.1"]: args = [ "-v", "--set", "upstream_cert=false", "--set", "upload_dir=" + normalize_path(self.upload_dir), "--set", "websocket=false", "--set", "server_replay_files={}".format(",".join(recording_paths)), "--scripts", normalize_path(script), ] command.extend(args) else: raise Exception("Mitmproxy version is unknown!") else: raise Exception( "Mitmproxy can't start playback! Playback settings missing.") LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"]) LOG.info("Starting mitmproxy playback using command: %s" % " ".join(command)) # to turn off mitmproxy log output, use these params for Popen: # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) self.mitmproxy_proc = ProcessHandler( command, logfile=os.path.join(self.upload_dir, "mitmproxy.log"), env=env, processStderrLine=LOG.error, storeOutput=False, ) self.mitmproxy_proc.run() end_time = time.time() + MITMDUMP_COMMAND_TIMEOUT ready = False while time.time() < end_time: ready = self.check_proxy(host=self.host, port=self.port) if ready: LOG.info( "Mitmproxy playback successfully started on %s:%d as pid %d" % (self.host, self.port, self.mitmproxy_proc.pid)) return time.sleep(0.25) # cannot continue as we won't be able to playback the pages LOG.error("Aborting: Mitmproxy process did not startup") self.stop_mitmproxy_playback() sys.exit() # XXX why do we need to do that? a raise is not enough? def stop_mitmproxy_playback(self): """Stop the mitproxy server playback""" if self.mitmproxy_proc is None or self.mitmproxy_proc.poll( ) is not None: return LOG.info("Stopping mitmproxy playback, killing process %d" % self.mitmproxy_proc.pid) # On Windows, mozprocess brutally kills mitmproxy with TerminateJobObject # The process has no chance to gracefully shutdown. # Here, we send the process a break event to give it a chance to wrapup. # See the signal handler in the alternate-server-replay-4.0.4.py script if mozinfo.os == "win": LOG.info("Sending CTRL_BREAK_EVENT to mitmproxy") os.kill(self.mitmproxy_proc.pid, signal.CTRL_BREAK_EVENT) time.sleep(2) exit_code = self.mitmproxy_proc.kill() self.mitmproxy_proc = None if exit_code != 0: if exit_code is None: LOG.error("Failed to kill the mitmproxy playback process") return if mozinfo.os == "win": from mozprocess.winprocess import ERROR_CONTROL_C_EXIT # noqa if exit_code == ERROR_CONTROL_C_EXIT: LOG.info( "Successfully killed the mitmproxy playback process" " with exit code %d" % exit_code) return log_func = LOG.error if self.ignore_mitmdump_exit_failure: log_func = LOG.info log_func("Mitmproxy exited with error code %d" % exit_code) else: LOG.info("Successfully killed the mitmproxy playback process") def check_proxy(self, host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) s.shutdown(socket.SHUT_RDWR) s.close() return True except socket.error: return False
def _run_python_test(self, test): from mozprocess import ProcessHandler if test.get('requirements'): self.virtualenv_manager.install_pip_requirements( test['requirements'], quiet=True) output = [] def _log(line): # Buffer messages if more than one worker to avoid interleaving if self.jobs > 1: output.append(line) else: self.log(logging.INFO, 'python-test', {'line': line.rstrip()}, '{line}') file_displayed_test = [] # used as boolean def _line_handler(line): if not file_displayed_test: output = ('Ran' in line or 'collected' in line or line.startswith('TEST-')) if output: file_displayed_test.append(True) # Hack to make sure treeherder highlights pytest failures if b'FAILED' in line.rsplit(b' ', 1)[-1]: line = line.replace(b'FAILED', b'TEST-UNEXPECTED-FAIL') _log(line) _log(test['path']) python = self.virtualenv_manager.python_path cmd = [python, test['path']] env = os.environ.copy() env[b'PYTHONDONTWRITEBYTECODE'] = b'1' # Homebrew on OS X will change Python's sys.executable to a custom value # which messes with mach's virtualenv handling code. Override Homebrew's # changes with the correct sys.executable value. env[b'PYTHONEXECUTABLE'] = python.encode('utf-8') proc = ProcessHandler(cmd, env=env, processOutputLine=_line_handler, storeOutput=False) proc.run() return_code = proc.wait() if not file_displayed_test: _log( 'TEST-UNEXPECTED-FAIL | No test output (missing mozunit.main() ' 'call?): {}'.format(test['path'])) if self.verbose: if return_code != 0: _log('Test failed: {}'.format(test['path'])) else: _log('Test passed: {}'.format(test['path'])) return output, return_code, test['path']
def do_test(self, test): self.result_data = None self.result_flag = threading.Event() args = [ "--hard-fail", "-u", "Servo/wptrunner", "-Z", "replace-surrogates", "-z", self.test_url(test), ] for stylesheet in self.browser.user_stylesheets: args += ["--user-stylesheet", stylesheet] for pref, value in test.environment.get('prefs', {}).iteritems(): args += ["--pref", "%s=%s" % (pref, value)] if self.browser.ca_certificate_path: args += ["--certificate-path", self.browser.ca_certificate_path] args += self.browser.binary_args debug_args, command = browser_command(self.binary, args, self.debug_info) self.command = command if self.pause_after_test: self.command.remove("-z") self.command = debug_args + self.command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], onFinish=self.on_finish, env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) try: timeout = test.timeout * self.timeout_multiplier # Now wait to get the output we expect, or until we reach the timeout if not self.interactive and not self.pause_after_test: wait_timeout = timeout + 5 self.result_flag.wait(wait_timeout) else: wait_timeout = None self.proc.wait() proc_is_running = True if self.result_flag.is_set(): if self.result_data is not None: result = self.convert_result(test, self.result_data) else: self.proc.wait() result = (test.result_cls("CRASH", None), []) proc_is_running = False else: result = (test.result_cls("TIMEOUT", None), []) if proc_is_running: if self.pause_after_test: self.logger.info("Pausing until the browser exits") self.proc.wait() else: self.proc.kill() except KeyboardInterrupt: self.proc.kill() raise return result
class ServoRefTestExecutor(ProcessTestExecutor): convert_result = reftest_result_converter def __init__(self, browser, server_config, binary=None, timeout_multiplier=1, screenshot_cache=None, debug_info=None, pause_after_test=False): ProcessTestExecutor.__init__(self, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.protocol = Protocol(self, browser) self.screenshot_cache = screenshot_cache self.implementation = RefTestImplementation(self) self.tempdir = tempfile.mkdtemp() self.hosts_path = make_hosts_file() def teardown(self): try: os.unlink(self.hosts_path) except OSError: pass os.rmdir(self.tempdir) ProcessTestExecutor.teardown(self) def screenshot(self, test): full_url = self.test_url(test) with TempFilename(self.tempdir) as output_path: self.command = [self.binary, "--cpu", "--hard-fail", "--exit", "-u", "Servo/wptrunner", "-Z", "disable-text-aa", "--output=%s" % output_path, full_url] for stylesheet in self.browser.user_stylesheets: self.command += ["--user-stylesheet", stylesheet] env = os.environ.copy() env["HOST_FILE"] = self.hosts_path self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, base64.b64encode(data) def do_test(self, test): result = self.implementation.run_test(test) return self.convert_result(test, result) def on_output(self, line): line = line.decode("utf8", "replace") if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command))
class ServoTestharnessExecutor(ProcessTestExecutor): convert_result = testharness_result_converter def __init__(self, browser, server_config, timeout_multiplier=1, debug_info=None, pause_after_test=False): ProcessTestExecutor.__init__(self, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.pause_after_test = pause_after_test self.result_data = None self.result_flag = None self.protocol = Protocol(self, browser) self.hosts_path = make_hosts_file() def teardown(self): try: os.unlink(self.hosts_path) except OSError: pass ProcessTestExecutor.teardown(self) def do_test(self, test): self.result_data = None self.result_flag = threading.Event() args = [ "--hard-fail", "-u", "Servo/wptrunner", "-Z", "replace-surrogates", "-z", self.test_url(test), ] for stylesheet in self.browser.user_stylesheets: args += ["--user-stylesheet", stylesheet] for pref, value in test.environment.get('prefs', {}).iteritems(): args += ["--pref", "%s=%s" % (pref, value)] if self.browser.ca_certificate_path: args += ["--certificate-path", self.browser.ca_certificate_path] args += self.browser.binary_args debug_args, command = browser_command(self.binary, args, self.debug_info) self.command = command if self.pause_after_test: self.command.remove("-z") self.command = debug_args + self.command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], onFinish=self.on_finish, env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) try: timeout = test.timeout * self.timeout_multiplier # Now wait to get the output we expect, or until we reach the timeout if not self.interactive and not self.pause_after_test: wait_timeout = timeout + 5 self.result_flag.wait(wait_timeout) else: wait_timeout = None self.proc.wait() proc_is_running = True if self.result_flag.is_set(): if self.result_data is not None: result = self.convert_result(test, self.result_data) else: self.proc.wait() result = (test.result_cls("CRASH", None), []) proc_is_running = False else: result = (test.result_cls("TIMEOUT", None), []) if proc_is_running: if self.pause_after_test: self.logger.info("Pausing until the browser exits") self.proc.wait() else: self.proc.kill() except KeyboardInterrupt: self.proc.kill() raise return result def on_output(self, line): prefix = "ALERT: RESULT: " line = line.decode("utf8", "replace") if line.startswith(prefix): self.result_data = json.loads(line[len(prefix):]) self.result_flag.set() else: if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command)) def on_finish(self): self.result_flag.set()
def do_test(self, test): self.result_data = None self.result_flag = threading.Event() debug_args, command = browser_command(self.binary, [ "--cpu", "--hard-fail", "-u", "Servo/wptrunner", "-z", self.test_url(test) ], self.debug_info) self.command = command if self.pause_after_test: self.command.remove("-z") self.command = debug_args + self.command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], onFinish=self.on_finish, env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) try: timeout = test.timeout * self.timeout_multiplier # Now wait to get the output we expect, or until we reach the timeout if not self.interactive and not self.pause_after_test: wait_timeout = timeout + 5 self.result_flag.wait(wait_timeout) else: wait_timeout = None self.proc.wait() proc_is_running = True if self.result_flag.is_set(): if self.result_data is not None: result = self.convert_result(test, self.result_data) else: self.proc.wait() result = (test.result_cls("CRASH", None), []) proc_is_running = False else: result = (test.result_cls("TIMEOUT", None), []) if proc_is_running: if self.pause_after_test: self.logger.info("Pausing until the browser exits") self.proc.wait() else: self.proc.kill() except KeyboardInterrupt: self.proc.kill() raise return result
def __init__(self, config, *args, **kwargs): self.config = config kwargs["stream"] = False kwargs["universal_newlines"] = True ProcessHandler.__init__(self, *args, **kwargs)
def run_browser(command, timeout=None, on_started=None, **kwargs): """ Run the browser using the given `command`. After the browser prints __endTimestamp, we give it 5 seconds to quit and kill it if it's still alive at that point. Note that this method ensure that the process is killed at the end. If this is not possible, an exception will be raised. :param command: the commad (as a string list) to run the browser :param timeout: if specified, timeout to wait for the browser before we raise a :class:`TalosError` :param on_started: a callback that can be used to do things just after the browser has been started :param kwargs: additional keyword arguments for the :class:`ProcessHandler` instance Returns a ProcessContext instance, with available output and pid used. """ context = ProcessContext() first_time = int(time.time()) * 1000 wait_for_quit_timeout = 5 event = Event() reader = Reader(event) kwargs['storeOutput'] = False kwargs['processOutputLine'] = reader kwargs['onFinish'] = event.set proc = ProcessHandler(command, **kwargs) proc.run() try: context.process = psutil.Process(proc.pid) if on_started: on_started() # wait until we saw __endTimestamp in the proc output, # or the browser just terminated - or we have a timeout if not event.wait(timeout): # try to extract the minidump stack if the browser hangs mozcrash.kill_and_get_minidump(proc.pid) raise TalosError("timeout") if reader.got_end_timestamp: for i in range(1, wait_for_quit_timeout): if proc.wait(1) is not None: break if proc.poll() is None: logging.info( "Browser shutdown timed out after {0} seconds, terminating" " process.".format(wait_for_quit_timeout)) finally: # this also handle KeyboardInterrupt # ensure early the process is really terminated context.kill_process() reader.output.append( "__startBeforeLaunchTimestamp%d__endBeforeLaunchTimestamp" % first_time) reader.output.append( "__startAfterTerminationTimestamp%d__endAfterTerminationTimestamp" % (int(time.time()) * 1000)) logging.info("Browser exited with error code: {0}".format(proc.returncode)) context.output = reader.output return context
class BaseEmulator(Device): port = None proc = None telnet = None def __init__(self, app_ctx, **kwargs): self.arch = ArchContext( kwargs.pop("arch", "arm"), app_ctx, binary=kwargs.pop("binary", None), avd=kwargs.pop("avd", None), ) super(BaseEmulator, self).__init__(app_ctx, **kwargs) self.tmpdir = tempfile.mkdtemp() # These rely on telnet self.battery = EmulatorBattery(self) self.geo = EmulatorGeo(self) self.screen = EmulatorScreen(self) @property def args(self): """ Arguments to pass into the emulator binary. """ return [self.arch.binary] def start(self): """ Starts a new emulator. """ if self.proc: return original_devices = set(self._get_online_devices()) # QEMU relies on atexit() to remove temporary files, which does not # work since mozprocess uses SIGKILL to kill the emulator process. # Use a customized temporary directory so we can clean it up. os.environ["ANDROID_TMP"] = self.tmpdir qemu_log = None qemu_proc_args = {} if self.logdir: # save output from qemu to logfile qemu_log = os.path.join(self.logdir, "qemu.log") if os.path.isfile(qemu_log): self._rotate_log(qemu_log) qemu_proc_args["logfile"] = qemu_log else: qemu_proc_args["processOutputLine"] = lambda line: None self.proc = ProcessHandler(self.args, **qemu_proc_args) self.proc.run() devices = set(self._get_online_devices()) now = datetime.datetime.now() while (devices - original_devices) == set([]): time.sleep(1) # Sometimes it takes more than 60s to launch emulator, so we # increase timeout value to 180s. Please see bug 1143380. if datetime.datetime.now() - now > datetime.timedelta(seconds=180): raise TimeoutException( "timed out waiting for emulator to start") devices = set(self._get_online_devices()) devices = devices - original_devices self.serial = devices.pop() self.connect() def _get_online_devices(self): adbhost = ADBHost(adb=self.app_ctx.adb) return [ d["device_serial"] for d in adbhost.devices() if d["state"] != "offline" if d["device_serial"].startswith("emulator") ] def connect(self): """ Connects to a running device. If no serial was specified in the constructor, defaults to the first entry in `adb devices`. """ if self.connected: return super(BaseEmulator, self).connect() self.port = int(self.serial[self.serial.rindex("-") + 1:]) def cleanup(self): """ Cleans up and kills the emulator, if it was started by mozrunner. """ super(BaseEmulator, self).cleanup() if self.proc: self.proc.kill() self.proc = None self.connected = False # Remove temporary files if os.path.isdir(self.tmpdir): shutil.rmtree(self.tmpdir) def _get_telnet_response(self, command=None): output = [] assert self.telnet if command is not None: self.telnet.write("%s\n" % command) while True: line = self.telnet.read_until("\n") output.append(line.rstrip()) if line.startswith("OK"): return output elif line.startswith("KO:"): raise Exception("bad telnet response: %s" % line) def _run_telnet(self, command): if not self.telnet: self.telnet = Telnet("localhost", self.port) self._get_telnet_response() return self._get_telnet_response(command) def __del__(self): if self.telnet: self.telnet.write("exit\n") self.telnet.read_all()
def run(self, *args, **kwargs): orig = signal.signal(signal.SIGINT, signal.SIG_IGN) ProcessHandler.run(self, *args, **kwargs) signal.signal(signal.SIGINT, orig)
class ServoReftestExecutor(ProcessTestExecutor): convert_result = reftest_result_converter def __init__(self, *args, **kwargs): ProcessTestExecutor.__init__(self, *args, **kwargs) self.ref_hashes = {} self.ref_urls_by_hash = defaultdict(set) self.tempdir = tempfile.mkdtemp() def teardown(self): os.rmdir(self.tempdir) ProcessTestExecutor.teardown(self) def run_test(self, test): test_url, ref_type, ref_url = test.url, test.ref_type, test.ref_url hashes = {"test": None, "ref": self.ref_hashes.get(ref_url)} status = None for url_type, url in [("test", test_url), ("ref", ref_url)]: if hashes[url_type] is None: full_url = urlparse.urljoin(self.http_server_url, url) with TempFilename(self.tempdir) as output_path: self.command = [ self.binary, "--cpu", "--hard-fail", "--exit", "--output=%s" % output_path, full_url ] timeout = test.timeout * self.timeout_multiplier self.proc = ProcessHandler( self.command, processOutputLine=[self.on_output]) self.proc.run() rv = self.proc.wait(timeout=timeout) if rv is None: status = "EXTERNAL-TIMEOUT" self.proc.kill() break if rv < 0: status = "CRASH" break with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() hashes[url_type] = hashlib.sha1(data).hexdigest() if status is None: self.ref_urls_by_hash[hashes["ref"]].add(ref_url) self.ref_hashes[ref_url] = hashes["ref"] if ref_type == "==": passed = hashes["test"] == hashes["ref"] elif ref_type == "!=": passed = hashes["test"] != hashes["ref"] else: raise ValueError status = "PASS" if passed else "FAIL" result = self.convert_result(test, {"status": status, "message": None}) self.runner.send_message("test_ended", test, result) def on_output(self, line): line = line.decode("utf8", "replace") if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command))
def verify_android_device(build_obj, install=False, xre=False, debugger=False, verbose=False, app=None, device_serial=None): """ Determine if any Android device is connected via adb. If no device is found, prompt to start an emulator. If a device is found or an emulator started and 'install' is specified, also check whether Firefox is installed on the device; if not, prompt to install Firefox. If 'xre' is specified, also check with MOZ_HOST_BIN is set to a valid xre/host-utils directory; if not, prompt to set one up. If 'debugger' is specified, also check that JimDB is installed; if JimDB is not found, prompt to set up JimDB. Returns True if the emulator was started or another device was already connected. """ device_verified = False emulator = AndroidEmulator('*', substs=build_obj.substs, verbose=verbose) adb_path = _find_sdk_exe(build_obj.substs, 'adb', False) if not adb_path: adb_path = 'adb' adbhost = ADBHost(adb=adb_path, verbose=verbose, timeout=10) devices = adbhost.devices(timeout=10) if 'device' in [d['state'] for d in devices]: device_verified = True elif emulator.is_available(): response = raw_input( "No Android devices connected. Start an emulator? (Y/n) ").strip() if response.lower().startswith('y') or response == '': if not emulator.check_avd(): _log_info("Fetching AVD. This may take a while...") emulator.update_avd() _log_info("Starting emulator running %s..." % emulator.get_avd_description()) emulator.start() emulator.wait_for_start() device_verified = True if device_verified and install: # Determine if Firefox is installed on the device; if not, # prompt to install. This feature allows a test command to # launch an emulator, install Firefox, and proceed with testing # in one operation. It is also a basic safeguard against other # cases where testing is requested but Firefox installation has # been forgotten. # If Firefox is installed, there is no way to determine whether # the current build is installed, and certainly no way to # determine if the installed build is the desired build. # Installing every time is problematic because: # - it prevents testing against other builds (downloaded apk) # - installation may take a couple of minutes. if not app: app = build_obj.substs["ANDROID_PACKAGE_NAME"] device = _get_device(build_obj.substs, device_serial) if not device.is_app_installed(app): if 'fennec' not in app and 'firefox' not in app: raw_input("It looks like %s is not installed on this device,\n" "but I don't know how to install it.\n" "Install it now, then hit Enter " % app) else: response = raw_input( "It looks like %s is not installed on this device.\n" "Install Firefox? (Y/n) " % app).strip() if response.lower().startswith('y') or response == '': _log_info("Installing Firefox. This may take a while...") build_obj._run_make(directory=".", target='install', ensure_exit_code=False) if device_verified and xre: # Check whether MOZ_HOST_BIN has been set to a valid xre; if not, # prompt to install one. xre_path = os.environ.get('MOZ_HOST_BIN') err = None if not xre_path: err = "environment variable MOZ_HOST_BIN is not set to a directory " \ "containing host xpcshell" elif not os.path.isdir(xre_path): err = '$MOZ_HOST_BIN does not specify a directory' elif not os.path.isfile(os.path.join(xre_path, 'xpcshell')): err = '$MOZ_HOST_BIN/xpcshell does not exist' if err: _maybe_update_host_utils(build_obj) xre_path = glob.glob(os.path.join(EMULATOR_HOME_DIR, 'host-utils*')) for path in xre_path: if os.path.isdir(path) and os.path.isfile( os.path.join(path, 'xpcshell')): os.environ['MOZ_HOST_BIN'] = path err = None break if err: _log_info("Host utilities not found: %s" % err) response = raw_input( "Download and setup your host utilities? (Y/n) ").strip() if response.lower().startswith('y') or response == '': _install_host_utils(build_obj) if debugger: # Optionally set up JimDB. See https://wiki.mozilla.org/Mobile/Fennec/Android/GDB. build_platform = _get_device_platform(build_obj.substs) jimdb_path = os.path.join(EMULATOR_HOME_DIR, 'jimdb-%s' % build_platform) jimdb_utils_path = os.path.join(jimdb_path, 'utils') gdb_path = os.path.join(jimdb_path, 'bin', 'gdb') err = None if not os.path.isdir(jimdb_path): err = '%s does not exist' % jimdb_path elif not os.path.isfile(gdb_path): err = '%s not found' % gdb_path if err: _log_info("JimDB (%s) not found: %s" % (build_platform, err)) response = raw_input("Download and setup JimDB (%s)? (Y/n) " % build_platform).strip() if response.lower().startswith('y') or response == '': host_platform = _get_host_platform() if host_platform: _log_info( "Installing JimDB (%s/%s). This may take a while..." % (host_platform, build_platform)) path = os.path.join(MANIFEST_PATH, host_platform, 'jimdb-%s.manifest' % build_platform) _get_tooltool_manifest(build_obj.substs, path, EMULATOR_HOME_DIR, 'releng.manifest') _tooltool_fetch() if os.path.isfile(gdb_path): # Get JimDB utilities from git repository proc = ProcessHandler(['git', 'pull'], cwd=jimdb_utils_path) proc.run() git_pull_complete = False try: proc.wait() if proc.proc.returncode == 0: git_pull_complete = True except Exception: if proc.poll() is None: proc.kill(signal.SIGTERM) if not git_pull_complete: _log_warning( "Unable to update JimDB utils from git -- " "some JimDB features may be unavailable.") else: _log_warning( "Unable to install JimDB -- unable to fetch from tooltool." ) else: _log_warning( "Unable to install JimDB -- your platform is not supported!" ) if os.path.isfile(gdb_path): # sync gdbinit.local with build settings _update_gdbinit(build_obj.substs, os.path.join(jimdb_utils_path, "gdbinit.local")) # ensure JimDB is in system path, so that mozdebug can find it bin_path = os.path.join(jimdb_path, 'bin') os.environ['PATH'] = "%s:%s" % (bin_path, os.environ['PATH']) return device_verified
class AndroidEmulator(object): """ Support running the Android emulator with an AVD from Mozilla test automation. Example usage: emulator = AndroidEmulator() if not emulator.is_running() and emulator.is_available(): if not emulator.check_avd(): warn("this may take a while...") emulator.update_avd() emulator.start() emulator.wait_for_start() emulator.wait() """ def __init__(self, avd_type='4.3', verbose=False, substs=None, device_serial=None): global verbose_logging self.emulator_log = None self.emulator_path = 'emulator' verbose_logging = verbose self.substs = substs self.avd_type = self._get_avd_type(avd_type) self.avd_info = AVD_DICT[self.avd_type] self.gpu = True self.restarted = False self.device_serial = device_serial _log_debug("Running on %s" % platform.platform()) _log_debug("Emulator created with type %s" % self.avd_type) def __del__(self): if self.emulator_log: self.emulator_log.close() def is_running(self): """ Returns True if the Android emulator is running. """ for proc in psutil.process_iter(): name = proc.name() # On some platforms, "emulator" may start an emulator with # process name "emulator64-arm" or similar. if name and name.startswith('emulator'): return True return False def is_available(self): """ Returns True if an emulator executable is found. """ found = False emulator_path = _find_sdk_exe(self.substs, 'emulator', True) if emulator_path: self.emulator_path = emulator_path found = True return found def check_avd(self, force=False): """ Determine if the AVD is already installed locally. (This is usually used to determine if update_avd() is likely to require a download; it is a convenient way of determining whether a 'this may take a while' warning is warranted.) Returns True if the AVD is installed. """ avd = os.path.join(EMULATOR_HOME_DIR, 'avd', self.avd_info.name + '.avd') if force and os.path.exists(avd): shutil.rmtree(avd) if os.path.exists(avd): _log_debug("AVD found at %s" % avd) return True return False def update_avd(self, force=False): """ If required, update the AVD via tooltool. If the AVD directory is not found, or "force" is requested, download the tooltool manifest associated with the AVD and then invoke tooltool.py on the manifest. tooltool.py will download the required archive (unless already present in the local tooltool cache) and install the AVD. """ avd = os.path.join(EMULATOR_HOME_DIR, 'avd', self.avd_info.name + '.avd') ini_file = os.path.join(EMULATOR_HOME_DIR, 'avd', self.avd_info.name + '.ini') if force and os.path.exists(avd): shutil.rmtree(avd) if not os.path.exists(avd): if os.path.exists(ini_file): os.remove(ini_file) path = self.avd_info.tooltool_manifest _get_tooltool_manifest(self.substs, path, EMULATOR_HOME_DIR, 'releng.manifest') _tooltool_fetch() self._update_avd_paths() def start(self): """ Launch the emulator. """ if self.avd_info.x86 and 'linux' in _get_host_platform(): _verify_kvm(self.substs) if os.path.exists(EMULATOR_AUTH_FILE): os.remove(EMULATOR_AUTH_FILE) _log_debug("deleted %s" % EMULATOR_AUTH_FILE) # create an empty auth file to disable emulator authentication auth_file = open(EMULATOR_AUTH_FILE, 'w') auth_file.close() def outputHandler(line): self.emulator_log.write("<%s>\n" % line) if "Invalid value for -gpu" in line or "Invalid GPU mode" in line: self.gpu = False env = os.environ env['ANDROID_AVD_HOME'] = os.path.join(EMULATOR_HOME_DIR, "avd") command = [self.emulator_path, "-avd", self.avd_info.name] if self.gpu: command += ['-gpu', 'swiftshader'] if self.avd_info.extra_args: # -enable-kvm option is not valid on OSX if _get_host_platform( ) == 'macosx64' and '-enable-kvm' in self.avd_info.extra_args: self.avd_info.extra_args.remove('-enable-kvm') command += self.avd_info.extra_args log_path = os.path.join(EMULATOR_HOME_DIR, 'emulator.log') self.emulator_log = open(log_path, 'w') _log_debug("Starting the emulator with this command: %s" % ' '.join(command)) _log_debug("Emulator output will be written to '%s'" % log_path) self.proc = ProcessHandler(command, storeOutput=False, processOutputLine=outputHandler, env=env) self.proc.run() _log_debug("Emulator started with pid %d" % int(self.proc.proc.pid)) def wait_for_start(self): """ Verify that the emulator is running, the emulator device is visible to adb, and Android has booted. """ if not self.proc: _log_warning("Emulator not started!") return False if self.check_completed(): return False _log_debug("Waiting for device status...") adb_path = _find_sdk_exe(self.substs, 'adb', False) if not adb_path: adb_path = 'adb' adbhost = ADBHost(adb=adb_path, verbose=verbose_logging, timeout=10) devs = adbhost.devices(timeout=10) devs = [(d['device_serial'], d['state']) for d in devs] while ('emulator-5554', 'device') not in devs: time.sleep(10) if self.check_completed(): return False devs = adbhost.devices(timeout=10) devs = [(d['device_serial'], d['state']) for d in devs] _log_debug("Device status verified.") _log_debug("Checking that Android has booted...") device = _get_device(self.substs, self.device_serial) complete = False while not complete: output = '' try: output = device.get_prop('sys.boot_completed', timeout=5) except Exception: # adb not yet responding...keep trying pass if output.strip() == '1': complete = True else: time.sleep(10) if self.check_completed(): return False _log_debug("Android boot status verified.") if not self._verify_emulator(): return False if self.avd_info.x86: _log_info( "Running the x86 emulator; be sure to install an x86 APK!") else: _log_info( "Running the arm emulator; be sure to install an arm APK!") return True def check_completed(self): if self.proc.proc.poll() is not None: if not self.gpu and not self.restarted: _log_warning( "Emulator failed to start. Your emulator may be out of date." ) _log_warning( "Trying to restart the emulator without -gpu argument.") self.restarted = True self.start() return False _log_warning("Emulator has already completed!") log_path = os.path.join(EMULATOR_HOME_DIR, 'emulator.log') _log_warning( "See log at %s and/or use --verbose for more information." % log_path) return True return False def wait(self): """ Wait for the emulator to close. If interrupted, close the emulator. """ try: self.proc.wait() except Exception: if self.proc.poll() is None: self.cleanup() return self.proc.poll() def cleanup(self): """ Close the emulator. """ self.proc.kill(signal.SIGTERM) def get_avd_description(self): """ Return the human-friendly description of this AVD. """ return self.avd_info.description def _update_avd_paths(self): avd_path = os.path.join(EMULATOR_HOME_DIR, "avd") ini_file = os.path.join(avd_path, "test-1.ini") ini_file_new = os.path.join(avd_path, self.avd_info.name + ".ini") os.rename(ini_file, ini_file_new) avd_dir = os.path.join(avd_path, "test-1.avd") avd_dir_new = os.path.join(avd_path, self.avd_info.name + ".avd") os.rename(avd_dir, avd_dir_new) self._replace_ini_contents(ini_file_new) def _replace_ini_contents(self, path): with open(path, "r") as f: lines = f.readlines() with open(path, "w") as f: for line in lines: if line.startswith('path='): avd_path = os.path.join(EMULATOR_HOME_DIR, "avd") f.write('path=%s/%s.avd\n' % (avd_path, self.avd_info.name)) elif line.startswith('path.rel='): f.write('path.rel=avd/%s.avd\n' % self.avd_info.name) else: f.write(line) def _telnet_cmd(self, telnet, command): _log_debug(">>> " + command) telnet.write('%s\n' % command) result = telnet.read_until('OK', 10) _log_debug("<<< " + result) return result def _verify_emulator(self): telnet_ok = False tn = None while (not telnet_ok): try: tn = telnetlib.Telnet('localhost', 5554, 10) if tn is not None: tn.read_until('OK', 10) self._telnet_cmd(tn, 'avd status') self._telnet_cmd(tn, 'redir list') self._telnet_cmd(tn, 'network status') tn.write('quit\n') tn.read_all() telnet_ok = True else: _log_warning("Unable to connect to port 5554") except Exception: _log_warning("Trying again after unexpected exception") finally: if tn is not None: tn.close() if not telnet_ok: time.sleep(10) if self.proc.proc.poll() is not None: _log_warning("Emulator has already completed!") return False return telnet_ok def _get_avd_type(self, requested): if requested in AVD_DICT.keys(): return requested if self.substs: if not self.substs['TARGET_CPU'].startswith('arm'): return 'x86' return '4.3'
class Emulator(Device): logcat_proc = None port = None proc = None telnet = None def __init__(self, app_ctx, arch, resolution=None, sdcard=None, userdata=None, no_window=None, binary=None, **kwargs): Device.__init__(self, app_ctx, **kwargs) self.arch = ArchContext(arch, self.app_ctx, binary=binary) self.resolution = resolution or '320x480' self.sdcard = None if sdcard: self.sdcard = self.create_sdcard(sdcard) self.userdata = os.path.join(self.arch.sysdir, 'userdata.img') if userdata: self.userdata = tempfile.NamedTemporaryFile(prefix='qemu-userdata') shutil.copyfile(userdata, self.userdata) self.no_window = no_window self.battery = EmulatorBattery(self) self.geo = EmulatorGeo(self) self.screen = EmulatorScreen(self) @property def args(self): """ Arguments to pass into the emulator binary. """ qemu_args = [ self.arch.binary, '-kernel', self.arch.kernel, '-sysdir', self.arch.sysdir, '-data', self.userdata ] if self.no_window: qemu_args.append('-no-window') if self.sdcard: qemu_args.extend(['-sdcard', self.sdcard]) qemu_args.extend([ '-memory', '512', '-partition-size', '512', '-verbose', '-skin', self.resolution, '-gpu', 'on', '-qemu' ] + self.arch.extra_args) return qemu_args def start(self): """ Starts a new emulator. """ if self.proc: return original_devices = set(self._get_online_devices()) qemu_log = None qemu_proc_args = {} if self.logdir: # save output from qemu to logfile qemu_log = os.path.join(self.logdir, 'qemu.log') if os.path.isfile(qemu_log): self._rotate_log(qemu_log) qemu_proc_args['logfile'] = qemu_log else: qemu_proc_args['processOutputLine'] = lambda line: None self.proc = ProcessHandler(self.args, **qemu_proc_args) self.proc.run() devices = set(self._get_online_devices()) now = datetime.datetime.now() while (devices - original_devices) == set([]): time.sleep(1) if datetime.datetime.now() - now > datetime.timedelta(seconds=60): raise TimeoutException( 'timed out waiting for emulator to start') devices = set(self._get_online_devices()) devices = devices - original_devices self.serial = devices.pop() self.connect() def _get_online_devices(self): return set([ d[0] for d in self.dm.devices() if d[1] != 'offline' if d[0].startswith('emulator') ]) def connect(self): """ Connects to a running device. If no serial was specified in the constructor, defaults to the first entry in `adb devices`. """ if self.connected: return Device.connect(self) self.port = int(self.serial[self.serial.rindex('-') + 1:]) self.geo.set_default_location() self.screen.initialize() # setup DNS fix for networking self.app_ctx.dm.shellCheckOutput(['setprop', 'net.dns1', '10.0.2.3']) def create_sdcard(self, sdcard_size): """ Creates an sdcard partition in the emulator. :param sdcard_size: Size of partition to create, e.g '10MB'. """ mksdcard = self.app_ctx.which('mksdcard') path = tempfile.mktemp(prefix='sdcard') sdargs = [mksdcard, '-l', 'mySdCard', sdcard_size, path] sd = subprocess.Popen(sdargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) retcode = sd.wait() if retcode: raise Exception('unable to create sdcard: exit code %d: %s' % (retcode, sd.stdout.read())) return path def cleanup(self): """ Cleans up and kills the emulator. """ Device.cleanup(self) if self.proc: self.proc.kill() self.proc = None # Remove temporary sdcard if self.sdcard and os.path.isfile(self.sdcard): os.remove(self.sdcard) # TODO this function is B2G specific and shouldn't live here @uses_marionette def wait_for_system_message(self, marionette): marionette.set_script_timeout(45000) # Telephony API's won't be available immediately upon emulator # boot; we have to wait for the syste-message-listener-ready # message before we'll be able to use them successfully. See # bug 792647. print 'waiting for system-message-listener-ready...' try: marionette.execute_async_script(""" waitFor( function() { marionetteScriptFinished(true); }, function() { return isSystemMessageListenerReady(); } ); """) except: # Look for ScriptTimeoutException this way to avoid a # dependency on the marionette python client. exc_name = sys.exc_info()[0].__name__ if exc_name != 'ScriptTimeoutException': raise print 'timed out' # We silently ignore the timeout if it occurs, since # isSystemMessageListenerReady() isn't available on # older emulators. 45s *should* be enough of a delay # to allow telephony API's to work. pass print '...done' # TODO this function is B2G specific and shouldn't live here @uses_marionette def wait_for_homescreen(self, marionette): print 'waiting for homescreen...' marionette.set_context(marionette.CONTEXT_CONTENT) marionette.execute_async_script(""" log('waiting for mozbrowserloadend'); window.addEventListener('mozbrowserloadend', function loaded(aEvent) { log('received mozbrowserloadend for ' + aEvent.target.src); if (aEvent.target.src.indexOf('ftu') != -1 || aEvent.target.src.indexOf('homescreen') != -1) { window.removeEventListener('mozbrowserloadend', loaded); marionetteScriptFinished(); } });""", script_timeout=120000) print '...done' def _get_telnet_response(self, command=None): output = [] assert (self.telnet) if command is not None: self.telnet.write('%s\n' % command) while True: line = self.telnet.read_until('\n') output.append(line.rstrip()) if line.startswith('OK'): return output elif line.startswith('KO:'): raise Exception('bad telnet response: %s' % line) def _run_telnet(self, command): if not self.telnet: self.telnet = Telnet('localhost', self.port) self._get_telnet_response() return self._get_telnet_response(command) def __del__(self): if self.telnet: self.telnet.write('exit\n') self.telnet.read_all()
class ServoRefTestExecutor(ProcessTestExecutor): convert_result = reftest_result_converter def __init__(self, logger, browser, server_config, binary=None, timeout_multiplier=1, screenshot_cache=None, debug_info=None, pause_after_test=False, **kwargs): ProcessTestExecutor.__init__(self, logger, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.protocol = ConnectionlessProtocol(self, browser) self.screenshot_cache = screenshot_cache self.implementation = RefTestImplementation(self) self.tempdir = tempfile.mkdtemp() self.hosts_path = write_hosts_file(server_config) def reset(self): self.implementation.reset() def teardown(self): try: os.unlink(self.hosts_path) except OSError: pass os.rmdir(self.tempdir) ProcessTestExecutor.teardown(self) def screenshot(self, test, viewport_size, dpi, page_ranges): with TempFilename(self.tempdir) as output_path: extra_args = ["--exit", "--output=%s" % output_path, "--resolution", viewport_size or "800x600"] debug_opts = "disable-text-aa,load-webfonts-synchronously,replace-surrogates" if dpi: extra_args += ["--device-pixel-ratio", dpi] self.command = build_servo_command(test, self.test_url, self.browser, self.binary, False, self.debug_info, extra_args, debug_opts) env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=cast_env(env)) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise else: self.proc = subprocess.Popen(self.command, env=cast_env(env)) try: rv = self.proc.wait() except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path, "rb") as f: # Might need to strip variable headers or something here data = f.read() return True, [ensure_str(base64.b64encode(data))] def do_test(self, test): result = self.implementation.run_test(test) return self.convert_result(test, result) def on_output(self, line): line = line.decode("utf8", "replace") if self.interactive: print(line) else: self.logger.process_output(self.proc.pid, line, " ".join(self.command))
class ServoWebDriverBrowser(Browser): init_timeout = 300 # Large timeout for cases where we're booting an Android emulator def __init__(self, logger, binary, debug_info=None, webdriver_host="127.0.0.1", server_config=None, binary_args=None, user_stylesheets=None, headless=None, **kwargs): Browser.__init__(self, logger) self.binary = binary self.binary_args = binary_args or [] self.webdriver_host = webdriver_host self.webdriver_port = None self.proc = None self.debug_info = debug_info self.hosts_path = write_hosts_file(server_config) self.server_ports = server_config.ports if server_config else {} self.command = None self.user_stylesheets = user_stylesheets if user_stylesheets else [] self.headless = headless if headless else False self.ca_certificate_path = server_config.ssl_config["ca_cert_path"] def start(self, **kwargs): self.webdriver_port = get_free_port() env = os.environ.copy() env["HOST_FILE"] = self.hosts_path env["RUST_BACKTRACE"] = "1" env["EMULATOR_REVERSE_FORWARD_PORTS"] = ",".join( str(port) for _protocol, ports in self.server_ports.items() for port in ports if port) debug_args, command = browser_command( self.binary, self.binary_args + [ "--hard-fail", "--webdriver=%s" % self.webdriver_port, "about:blank", ], self.debug_info) if self.headless: command += ["--headless"] if self.ca_certificate_path: command += ["--certificate-path", self.ca_certificate_path] for stylesheet in self.user_stylesheets: command += ["--user-stylesheet", stylesheet] self.command = command self.command = debug_args + self.command if not self.debug_info or not self.debug_info.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) self.logger.debug("Servo Started") def stop(self, force=False): self.logger.debug("Stopping browser") if self.proc is not None: try: self.proc.kill() except OSError: # This can happen on Windows if the process is already dead pass def pid(self): if self.proc is None: return None try: return self.proc.pid except AttributeError: return None def on_output(self, line): """Write a line of output from the process to the log""" self.logger.process_output(self.pid(), line.decode("utf8", "replace"), command=" ".join(self.command)) def is_alive(self): return self.proc.poll() is None def cleanup(self): self.stop() os.remove(self.hosts_path) def executor_browser(self): assert self.webdriver_port is not None return ExecutorBrowser, { "webdriver_host": self.webdriver_host, "webdriver_port": self.webdriver_port, "init_timeout": self.init_timeout }
class Mitmproxy(Playback): def __init__(self, config): self.config = config self.host = ("127.0.0.1" if "localhost" in self.config["host"] else self.config["host"]) self.port = None self.mitmproxy_proc = None self.mitmdump_path = None self.record_mode = config.get("record", False) self.recording = None self.playback_files = [] self.browser_path = "" if config.get("binary", None): self.browser_path = os.path.normpath(config.get("binary")) self.policies_dir = None self.ignore_mitmdump_exit_failure = config.get( "ignore_mitmdump_exit_failure", False) if self.record_mode: if "recording_file" not in self.config: LOG.error( "recording_file value was not provided. Proxy service wont' start " ) raise Exception("Please provide a playback_files list.") if not isinstance(self.config.get("recording_file"), six.string_types): LOG.error("recording_file argument type is not str!") raise Exception("recording_file argument type invalid!") if not os.path.splitext( self.config.get("recording_file"))[1] == ".zip": LOG.error("Recording file type (%s) should be a zip. " "Please provide a valid file type!" % self.config.get("recording_file")) raise Exception("Recording file type should be a zip") if os.path.exists(self.config.get("recording_file")): LOG.error("Recording file (%s) already exists." "Please provide a valid file path!" % self.config.get("recording_file")) raise Exception("Recording file already exists.") if self.config.get("playback_files", False): LOG.error( "Record mode is True and playback_files where provided!") raise Exception("playback_files specified during record!") if self.config.get("playback_version") is None: LOG.error("mitmproxy was not provided with a 'playback_version' " "Please provide a valid playback version") raise Exception("playback_version not specified!") # mozproxy_dir is where we will download all mitmproxy required files # when running locally it comes from obj_path via mozharness/mach if self.config.get("obj_path") is not None: self.mozproxy_dir = self.config.get("obj_path") else: # in production it is ../tasks/task_N/build/, in production that dir # is not available as an envvar, however MOZ_UPLOAD_DIR is set as # ../tasks/task_N/build/blobber_upload_dir so take that and go up 1 level self.mozproxy_dir = os.path.dirname( os.path.dirname(os.environ["MOZ_UPLOAD_DIR"])) self.mozproxy_dir = os.path.join(self.mozproxy_dir, "testing", "mozproxy") self.upload_dir = os.environ.get("MOZ_UPLOAD_DIR", self.mozproxy_dir) LOG.info( "mozproxy_dir used for mitmproxy downloads and exe files: %s" % self.mozproxy_dir) # setting up the MOZPROXY_DIR env variable so custom scripts know # where to get the data os.environ["MOZPROXY_DIR"] = self.mozproxy_dir LOG.info("Playback tool: %s" % self.config["playback_tool"]) LOG.info("Playback tool version: %s" % self.config["playback_version"]) def download_mitm_bin(self): # Download and setup mitm binaries manifest = os.path.join( here, "manifests", "mitmproxy-rel-bin-%s-{platform}.manifest" % self.config["playback_version"], ) transformed_manifest = transform_platform(manifest, self.config["platform"]) # generate the mitmdump_path self.mitmdump_path = os.path.normpath( os.path.join( self.mozproxy_dir, "mitmdump-%s" % self.config["playback_version"], "mitmdump", )) # Check if mitmproxy bin exists if os.path.exists(self.mitmdump_path): LOG.info("mitmproxy binary already exists. Skipping download") else: # Download and unpack mitmproxy binary download_path = os.path.dirname(self.mitmdump_path) LOG.info("create mitmproxy %s dir" % self.config["playback_version"]) if not os.path.exists(download_path): os.makedirs(download_path) LOG.info("downloading mitmproxy binary") tooltool_download(transformed_manifest, self.config["run_local"], download_path) def download_manifest_file(self, manifest_path): # Manifest File # we use one pageset for all platforms LOG.info("downloading mitmproxy pageset") tooltool_download(manifest_path, self.config["run_local"], self.mozproxy_dir) with open(manifest_path) as manifest_file: manifest = json.load(manifest_file) for file in manifest: zip_path = os.path.join(self.mozproxy_dir, file["filename"]) LOG.info("Adding %s to recording list" % zip_path) self.playback_files.append(RecordingFile(zip_path)) def download_playback_files(self): # Detect type of file from playback_files and download accordingly if "playback_files" not in self.config: LOG.error( "playback_files value was not provided. Proxy service wont' start " ) raise Exception("Please provide a playback_files list.") if not isinstance(self.config["playback_files"], list): LOG.error("playback_files should be a list") raise Exception("playback_files should be a list") for playback_file in self.config["playback_files"]: if playback_file.startswith( "https://") and "mozilla.com" in playback_file: # URL provided dest = os.path.join(self.mozproxy_dir, os.path.basename(playback_file)) download_file_from_url(playback_file, self.mozproxy_dir, extract=False) # Add Downloaded file to playback_files list LOG.info("Adding %s to recording list" % dest) self.playback_files.append(RecordingFile(dest)) continue if not os.path.exists(playback_file): LOG.error( "Zip or manifest file path (%s) does not exist. Please provide a valid path!" % playback_file) raise Exception("Zip or manifest file path does not exist") if os.path.splitext(playback_file)[1] == ".zip": # zip file path provided LOG.info("Adding %s to recording list" % playback_file) self.playback_files.append(RecordingFile(playback_file)) elif os.path.splitext(playback_file)[1] == ".manifest": # manifest file path provided self.download_manifest_file(playback_file) def download(self): """Download and unpack mitmproxy binary and pageset using tooltool""" if not os.path.exists(self.mozproxy_dir): os.makedirs(self.mozproxy_dir) self.download_mitm_bin() if self.record_mode: self.recording = RecordingFile(self.config["recording_file"]) else: self.download_playback_files() def stop(self): LOG.info("Mitmproxy stop!!") self.stop_mitmproxy_playback() if self.record_mode: LOG.info("Record mode ON. Generating zip file ") self.recording.generate_zip_file() def wait(self, timeout=1): """Wait until the mitmproxy process has terminated.""" # We wait using this method to allow Windows to respond to the Ctrl+Break # signal so that we can exit cleanly from the command-line driver. while True: returncode = self.mitmproxy_proc.wait(timeout) if returncode is not None: return returncode def start(self): # go ahead and download and setup mitmproxy self.download() # mitmproxy must be started before setup, so that the CA cert is available self.start_mitmproxy_playback(self.mitmdump_path, self.browser_path) # In case the setup fails, we want to stop the process before raising. try: self.setup() except Exception: try: self.stop() except Exception: LOG.error("MitmProxy failed to STOP.", exc_info=True) LOG.error("Setup of MitmProxy failed.", exc_info=True) raise def start_mitmproxy_playback(self, mitmdump_path, browser_path): """Startup mitmproxy and replay the specified flow file""" if self.mitmproxy_proc is not None: raise Exception("Proxy already started.") self.port = get_available_port() LOG.info("mitmdump path: %s" % mitmdump_path) LOG.info("browser path: %s" % browser_path) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env = os.environ.copy() env["PATH"] = os.path.dirname(browser_path) + os.pathsep + env["PATH"] command = [mitmdump_path] # add proxy host and port options command.extend( ["--listen-host", self.host, "--listen-port", str(self.port)]) # record mode if self.record_mode: # generate recording script paths inject_deterministic = os.path.join( mitm_folder, "scripts", "inject-deterministic.py", ) http_protocol_extractor = os.path.join( mitm_folder, "scripts", "http_protocol_extractor.py", ) args = [ "--save-stream-file", normalize_path(self.recording.recording_path), "--set", "websocket=false", "--scripts", inject_deterministic, "--scripts", http_protocol_extractor, ] command.extend(args) else: # playback mode if len(self.playback_files) > 0: script = os.path.join( mitm_folder, "scripts", "alternate-server-replay.py", ) if self.config["playback_version"] in [ "4.0.4", "5.1.1", "6.0.2" ]: args = [ "-v", # Verbose mode "--set", "upstream_cert=false", "--set", "upload_dir=" + normalize_path(self.upload_dir), "--set", "websocket=false", "--set", "server_replay_files={}".format(",".join([ normalize_path(playback_file.recording_path) for playback_file in self.playback_files ])), "--scripts", normalize_path(script), ] command.extend(args) else: raise Exception("Mitmproxy version is unknown!") else: raise Exception( "Mitmproxy can't start playback! Playback settings missing." ) # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path env = os.environ.copy() if not os.path.dirname(self.browser_path) in env["PATH"]: env["PATH"] = os.path.dirname( self.browser_path) + os.pathsep + env["PATH"] LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"]) LOG.info("Starting mitmproxy playback using command: %s" % " ".join(command)) # to turn off mitmproxy log output, use these params for Popen: # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) self.mitmproxy_proc = ProcessHandler( command, logfile=os.path.join(self.upload_dir, "mitmproxy.log"), env=env, processStderrLine=LOG.error, storeOutput=False, ) self.mitmproxy_proc.run() end_time = time.time() + MITMDUMP_COMMAND_TIMEOUT ready = False while time.time() < end_time: ready = self.check_proxy(host=self.host, port=self.port) if ready: LOG.info( "Mitmproxy playback successfully started on %s:%d as pid %d" % (self.host, self.port, self.mitmproxy_proc.pid)) return time.sleep(0.25) # cannot continue as we won't be able to playback the pages LOG.error("Aborting: Mitmproxy process did not startup") self.stop_mitmproxy_playback() sys.exit(1) # XXX why do we need to do that? a raise is not enough? def stop_mitmproxy_playback(self): """Stop the mitproxy server playback""" if self.mitmproxy_proc is None or self.mitmproxy_proc.poll( ) is not None: return LOG.info("Stopping mitmproxy playback, killing process %d" % self.mitmproxy_proc.pid) # On Windows, mozprocess brutally kills mitmproxy with TerminateJobObject # The process has no chance to gracefully shutdown. # Here, we send the process a break event to give it a chance to wrapup. # See the signal handler in the alternate-server-replay-4.0.4.py script if mozinfo.os == "win": LOG.info("Sending CTRL_BREAK_EVENT to mitmproxy") os.kill(self.mitmproxy_proc.pid, signal.CTRL_BREAK_EVENT) time.sleep(2) exit_code = self.mitmproxy_proc.kill() self.mitmproxy_proc = None if exit_code != 0: if exit_code is None: LOG.error("Failed to kill the mitmproxy playback process") return if mozinfo.os == "win": from mozprocess.winprocess import ERROR_CONTROL_C_EXIT # noqa if exit_code == ERROR_CONTROL_C_EXIT: LOG.info( "Successfully killed the mitmproxy playback process" " with exit code %d" % exit_code) return log_func = LOG.error if self.ignore_mitmdump_exit_failure: log_func = LOG.info log_func("Mitmproxy exited with error code %d" % exit_code) else: LOG.info("Successfully killed the mitmproxy playback process") def check_proxy(self, host, port): """Check that mitmproxy process is working by doing a socket call using the proxy settings :param host: Host of the proxy server :param port: Port of the proxy server :return: True if the proxy service is working """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) s.shutdown(socket.SHUT_RDWR) s.close() return True except socket.error: return False