def firefox_auto_open_vv(vmi): """Automatically open remote-viewer for proposed .vv file. Doesn't work as expected. See: https://github.com/SeleniumHQ/selenium/issues/3013 See content type at: ~/.mozilla/firefox/<profile_name>/mimeTypes.rdf application/x-virt-viewer """ pdir = vmi.firefox_profile_dir if not pdir: vmi.vm.error("Firefox profile dir is not defined") return user_js = os.path.join(pdir, "user.js") opts = [] opts.append("browser.helperApps.neverAsk.saveToDisk") opts.append("browser.helperApps.neverAsk.openFile") cmd = utils.Cmd("test", "-e", user_js) status, _ = act.rstatus(vmi, cmd) if status == 0: for o in opts: utils.info(vmi, "Remove old value %s from Firefox profile: %s", o, user_js) cmd = utils.Cmd("sed", "-i", "-e", "/%s/d" % o, user_js) act.run(vmi, cmd) line = 'user_pref("browser.helperApps.neverAsk.openFile",' '"application/x-virt-viewer");' cmd1 = utils.Cmd("echo", line) cmd2 = utils.Cmd(user_js) cmd = utils.combine(cmd1, ">>", cmd2) utils.info(vmi, "Add new line %s to Firefox profile: %s", line, user_js) act.run(vmi, cmd)
def klogger_start(vmi): ssn = act.new_ssn(vmi) cmd = utils.Cmd("xev", "-event", "keyboard", "-name", "klogger") utils.info(vmi, "Start key logger. Do not forget to turn it off.") ssn.sendline(str(cmd)) act.wait_for_win(vmi, "klogger", "WM_NAME") return ssn
def turn_firewall(vmi, state): utils.info(vmi, "Turn firewall: %r.", state) if utils.is_yes(state): raise NotImplemented else: cmd = utils.Cmd("iptables", "-F") act.run(vmi, cmd, admin=True)
def str_input(vmi, string): """Sends string trough vm.send_key(). The string could be spice_password. Notes ----- After string will be send Enter. Parameters ---------- string : str Arbitrary string to be send to VM as keyboard events. """ utils.info(vmi, "Passing string '%s' as kbd events.", string) char_mapping = { ":": "shift-semicolon", ",": "comma", ".": "dot", "/": "slash", "_": "shift-minus", "?": "shift-slash", " ": "spc", "=": "equal", } for character in string: if character in char_mapping: character = char_mapping[character] vmi.vm.send_key(character) # Enter vmi.vm.send_key("kp_enter")
def deploy_epel_repo(vmi): """Deploy epel repository to RHEL VM. """ # Check existence of epel repository cmd = utils.Cmd("test", "-f", "/etc/yum.repos.d/epel.repo") status, _ = act.rstatus(vmi, cmd) if status: arch = vmi.ssn.cmd("arch") if "i686" in arch: arch = "i386" else: arch = arch[:-1] if "release 5" in vmi.ssn.cmd("cat /etc/redhat-release"): cmd = ( "yum -y localinstall http://download.fedoraproject.org/" "pub/epel/5/%s/epel-release-5-4.noarch.rpm 2>&1" % arch ) utils.info(vmi, "Installing EPEL repository.") vmi.ssn.cmd(cmd) elif "release 6" in vmi.ssn.cmd("cat /etc/redhat-release"): cmd = ( "yum -y localinstall http://download.fedoraproject.org/" "pub/epel/6/%s/epel-release-6-8.noarch.rpm 2>&1" % arch ) utils.info(vmi, "Installing EPEL repository.") vmi.ssn.cmd(cmd) else: raise Exception("Unsupported RHEL guest")
def cb2text(vmi): script = vmi.cfg.helper_cb dst_script = act.chk_deps(vmi, script) cmd = utils.Cmd(dst_script, "--cb2stdout") text = act.run(vmi, cmd) utils.info(vmi, "Get from clipboard: %s", text) return text
def clear_cb(vmi): """Use the script to clear clipboard. """ script = vmi.cfg.helper_cb dst_script = act.chk_deps(vmi, script) cmd = utils.Cmd(dst_script, "--clear") utils.info(vmi, "Clear clipboard.") act.run(vmi, cmd)
def img2cb(vmi, img): """Use the clipboard script to copy an image into the clipboard. """ script = vmi.cfg.helper_cb dst_script = act.chk_deps(vmi, script) cmd = utils.Cmd(dst_script, "--img2cb", img) utils.info(vmi, "Put image %s in clipboard.", img) act.run(vmi, cmd, timeout=60)
def add_usb_policy(vmi): """Add USB policy to policykit file. .. todo:: USB_POLICY_FILE_SRC, USB_POLICY_FILE to cfg """ utils.info(vmi, "Sending: %s.", USB_POLICY_FILE_SRC) vmi.vm.copy_files_to(USB_POLICY_FILE_SRC, USB_POLICY_FILE)
def imggen(vmi, img, size): """Generate an image file. """ script = vmi.cfg.helper_cb dst_script = act.chk_deps(vmi, script) cmd = utils.Cmd(dst_script, "--genimg", size, img) utils.info(vmi, "Generate an %s image of %s size %s.", img, size) act.run(vmi, cmd)
def text2cb(vmi, text): """Use the clipboard script to copy an image into the clipboard. """ script = vmi.cfg.helper_cb dst_script = act.chk_deps(vmi, script) params = "--txt2cb" cmd = utils.Cmd(dst_script, "--txt2cb", text) utils.info(vmi, "Put in clipboard: %s", text) act.run(vmi, cmd)
def run_selenium(vmi, ssn): """Some general info. There are ways to define Firefox options globaly: * /usr/lib64/firefox/defaults/preferences/<anyname>.js * /etc/firefox/pref/<anyname>.js Format is: user_pref("some.key", "somevalue"); pref("some.key", "somevalue"); All values are defined at: about:config?filter=color Also user can define values for specific profile: http://kb.mozillazine.org/Profile_folder_-_Firefox#Linux For curent profile go to: about:support and press "Open Directory" Selenium understands next options: -Dwebdriver.firefox.profile=my-profile -Dwebdriver.firefox.bin=/path/to/firefox -trustAllSSLcertificates Also it is possible to specify Firefox profile in selenium python bindings: FirefoxProfile p = new FirefoxProfile(new File("D:\\profile2")); p.updateUserPrefs(new File("D:\\t.js")); To create a new profile call: firefox -CreateProfile <profile name> """ selenium = utils.download_asset("selenium", section=vmi.cfg.selenium_ver) fname = os.path.basename(selenium) dst_fname = os.path.join(act.workdir(vmi), fname) vmi.vm.copy_files_to(selenium, dst_fname) defs = utils.Cmd() opts = utils.Cmd() opts.append("-port") opts.append(vmi.cfg.selenium_port) opts.append("-trustAllSSLcertificates") defs = " ".join(defs) opts = " ".join(opts) cmd = "java {} -jar {} {}".format(defs, dst_fname, opts) utils.info(vmi, "selenium cmd: %s", cmd) ssn.sendline(cmd) # There should be a pause to start and running selenium server. # So next log reading acts like a pause. out = ssn.read_nonblocking(internal_timeout=20) act.info(vmi, "Selenium start log:\n%s.", out)
def x_active(vmi): """Test if X session is active. Do nothing is X active. Othrerwise throw exception. """ cmd = utils.Cmd("gnome-terminal", "-e", "/bin/true") status, _ = act.rstatus(vmi, cmd) if status: raise utils.SpiceUtilsError("X session is not present.") utils.info(vmi, "X session is present.")
def export_dbus(vmi, ssn=None): if not ssn: ssn = vmi.ssn utils.info(vmi, "Export DBUS info.") cmd = "cat /var/lib/dbus/machine-id" machine_id = ssn.cmd(cmd).rstrip("\r\n") cmd = ". /home/test/.dbus/session-bus/%s-0" % machine_id ssn.cmd(cmd) cmd = "export DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID" "DBUS_SESSION_BUS_WINDOWID" ssn.cmd(cmd)
def klogger_stop(vmi, ssn): # Send ctrl+c (SIGINT) through ssh session. time.sleep(1) ssn.send("\003") output = ssn.read_up_to_prompt() a = re.findall("KeyPress.*\n.*\n.* keycode (\d*) \(keysym ([0-9A-Fa-fx]*)", output) act.info(vmi, "Keyboard logger out: %r", a) keys = map(lambda (keycode, keysym): (int(keycode), int(keysym, base=16)), a) utils.info(vmi, "Read keys: %s" % keys) # Return list of pressed: (keycode, keysym) return keys
def x_turn_on(vmi): ssn = act.new_admin_ssn(vmi) runner = remote.RemoteRunner(session=ssn) srv_mng = service.Factory.create_service(run=runner.run) srv_mng.set_target("graphical.target") # pylint: disable=no-member cmd1 = utils.Cmd("ss", "-x", "src", "*X11-unix*") cmd2 = utils.Cmd("grep", "-q", "-s", "X11") cmd = utils.combine(cmd1, "|", cmd2) status, _ = act.rstatus(vmi, cmd) assert status == 0, "X is: off. But it should not." # TODO utils.info(vmi, "X is: on.")
def cp2vm(vmi, src, dst_dir=None, dst_name=None): if not dst_dir: dst_dir = act.dst_dir(vmi) provider_dir = asset.get_test_provider_subdirs(backend="spice")[0] src = os.path.normpath(src) src_path = os.path.join(provider_dir, src) if not dst_name: dst_name = src dst_path = os.path.join(dst_dir, dst_name) utils.info(vmi, "Copy: %s to %s", src_path, dst_path) vmi.vm.copy_files_to(src_path, dst_dir) return dst_path
def cb2img(vmi, img): """ Parameters ---------- img : str Where to save img. """ script = vmi.cfg.helper_cb dst_script = act.chk_deps(vmi, script) cmd = utils.Cmd(dst_script, "--cb2img", img) utils.info(vmi, "Dump clipboard to image %s.", img) act.run(vmi, cmd, timeout=60)
def check_usb_policy(vmi): """Check USB policy in polkit file. Returns ------- bool Status of grep command. If pattern is found 0 is returned. 0 in python is False so negative of grep is returned. .. todo: Move USB_POLICY_FILE to cfg. """ cmd = utils.Cmd("grep", "<allow_any>yes", USB_POLICY_FILE) # TODO status, _ = act.rstatus(vmi, cmd) utils.info(vmi, "USB policy is: %s.", status) return not status
def set_resolution(vmi, res, display=None): """Sets resolution of qxl device on a VM. Parameters ---------- res : str Resolution. display : str Target display. """ if not display: display = act.get_connected_displays(vmi)[0] utils.info(vmi, "Setting resolution to %s.", res) cmd = utils.Cmd("xrandr", "--output", display, "--mode", res) act.run(vmi, cmd)
def lock_scr_off(vmi): utils.info(vmi, "Disable lock screen.") # https://wiki.archlinux.org/index.php/Display_Power_Management_Signaling # Disable DPMS and prevent screen from blanking cmd = utils.Cmd("xset", "s", "off", "-dpms") act.run(vmi, cmd) cmd = utils.Cmd( "gconftool-2", "--set", "/apps/gnome-screensaver/idle_activation_enabled", "--type", "bool", "false" ) act.run(vmi, cmd) cmd = utils.Cmd("gconftool-2", "--set", "/apps/gnome-power-manager/ac_sleep_display", "--type", "int", "0") act.run(vmi, cmd) cmd = utils.Cmd("gconftool-2", "--set", "/apps/gnome-power-manager/timeout/sleep_display_ac", "--type", "int", "0") act.run(vmi, cmd) cmd = utils.Cmd("gconftool-2", "--set", "/apps/gnome-screensaver/lock_enabled", "--type", "boolean", "false") act.run(vmi, cmd) cmd = utils.Cmd("gconftool-2", "--set", "/desktop/gnome/session/idle_delay", "--type", "int", "0") act.run(vmi, cmd)
def service_vdagent(vmi, action): """Start/Stop/... on the spice-vdagentd service. Parameters ---------- action : str Action on vdagent-service: stop, start, restart, status, ... Info ---- See: avocado-vt/virttest/staging/service.py for COMMANDS """ ssn = act.new_admin_ssn(vmi) runner = remote.RemoteRunner(session=ssn) vdagentd = service.Factory.create_specific_service("spice-vdagentd", run=runner.run) func = getattr(vdagentd, action) utils.info(vmi, "spice-vdagent: %s", action) return func()
def print_rv_version(vmi): """Prints remote-viewer and spice-gtk version available inside. Parameters ---------- rv_binary : str remote-viewer binary. if cfg.rv_ld_library_path: xxcmd = "LD_LIBRARY_PATH=/usr/local/lib %s" % cfg.rv_binary else: xxcmd = cfg.rv_binary try: """ cmd = utils.Cmd(vmi.cfg.rv_binary, "-V") rv_ver = act.run(vmi, cmd) cmd = utils.Cmd(vmi.cfg.rv_binary, "--spice-gtk-version") spice_gtk_ver = act.run(vmi, cmd) utils.info(vmi, "remote-viewer version: %s", rv_ver) utils.info(vmi, "spice-gtk version: %s", spice_gtk_ver)
def turn_accessibility(vmi, on=True): """Turn accessibility on vm. Parameters ---------- on : str Spice test object. """ if utils.is_yes(on): val = "true" else: val = "false" # gconftool-2 --get "/desktop/gnome/interface/accessibility" # temporarily (for a single session) enable Accessibility: # GNOME_ACCESSIBILITY=1 # session.cmd("gconftool-2 --shutdown") utils.info(vmi, "Turning accessibility: %s.", val) cmd = utils.Cmd("gconftool-2", "--set", "/desktop/gnome/interface/accessibility", "--type", "bool", val) act.run(vmi, cmd)
def install_rpm(vmi, rpm): """Install RPM package on a VM. Parameters ---------- rpm : str Path to RPM to be installed. It could be path to .rpm file, or RPM name or URL. """ utils.info(vmi, "Install RPM : %s.", rpm) pkg = rpm if rpm.endswith(".rpm"): pkg = os.path.split(rpm)[1] pkg = pkg[:-4] cmd = utils.Cmd("rpm", "-q", pkg) status, _ = act.rstatus(vmi, cmd) if status == 0: utils.info(vmi, "RPM %s is already installed.", pkg) return if utils.url_regex.match(rpm): utils.info(vmi, "Download RPM: %s.", rpm) cmd = utils.Cmd("curl", "-s", "-O", rpm) act.run(vmi, cmd, admin=True, timeout=500) rpm = os.path.split(rpm)[1] act.run(vmi, "yes | yum -y install %s" % rpm, admin=True, timeout=500)
def get_geom(vmi, win_title): """Gets the geometry of the rv_window. Parameters ---------- win_title : str XXX. Returns ------- tuple Geometry of RV window. (x,y) """ xinfo_cmd = "xwininfo -name %s" % win_title cmd = utils.Cmd("xwininfo", "-name", win_title) cmd1 = utils.Cmd("grep", "geometry") xinfo_cmd += " | grep geometry" # Expected ' -geometry 898x700+470-13' out = act.run(vmi, cmd) res = re.findall("\d+x\d+", out)[0] utils.info(vmi, "Window %s has geometry: %s", win_title, res) return utils.str2res(res)
def export_x2ssh(vmi, var_name, fallback=None, ssn=None): """Take value from X session and export it to ssh session. Useful to export variables such as 'DBUS_SESSION_BUS_ADDRESS', 'AT_SPI_BUS'. Parameters ---------- var : str Variable name. fallback : Optional[str] If value is absent in X session, then use this value. """ var_val = act.get_x_var(vmi, var_name) if not var_val: var_val = fallback if not ssn: ssn = act.new_ssn(vmi) if var_val: utils.info(vmi, "Export %s == %s", var_name, var_val) cmd = utils.Cmd("export", "%s=%s" % (var_name, var_val)) act.run(vmi, cmd, ssn=ssn) else: utils.info(vmi, "Do not export %s var.", var_name)
def lock_scr_off(vmi): """ Info ---- See: gsettings list-recursively or use dconf-editor. https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Desktop_Migration_and_Administration_Guide/custom-default-values-system-settings.html $ dconf dump / """ utils.info(vmi, "Disable lock screen.") # The number of seconds of inactivity before the session is considered idle. cmd = utils.Cmd("gsettings", "set", "org.gnome.desktop.session", "idle-delay", "0") act.run(vmi, cmd) # Prevent the user to lock his screen. cmd = utils.Cmd("gsettings", "set", "org.gnome.desktop.lockdown", "disable-lock-screen", "true") act.run(vmi, cmd) act.run(vmi, cmd) # Set this to TRUE to lock the screen when the screensaver goes active. cmd = utils.Cmd("gsettings", "set", "org.gnome.desktop.screensaver", "lock-enabled", "false") act.run(vmi, cmd) # Whether this plugin would be activated by gnome-settings-daemon or not. cmd = utils.Cmd("gsettings", "set", "org.gnome.settings-daemon.plugins.power", "active", "false") act.run(vmi, cmd)
def get_x_var(vmi, var_name): """Gets the env variable value by its name from X session. Info ---- It is no straight way to get variable value from X session. If you try to read var value from SSH session it could be different from X session var or absent. The strategy used in this function is: 1. Find nautilus process. 2. Read its /proc/$PID/environ Parameters ---------- var_name : str Spice test object. Returns ------- str Env variable value. """ pattern = "(?<=(?:^{0}=|(?<=\n){0}=))[^\n]+".format(var_name) pids = act.wait_for_prog(vmi, "nautilus") ret = "" for pid in pids: cmd1 = utils.Cmd("cat", "/proc/%s/environ" % pid) cmd2 = utils.Cmd("xargs", "-n", "1", "-0", "echo") cmd = utils.combine(cmd1, "|", cmd2) out = act.run(vmi, cmd) val = re.findall(pattern, out) if val: ret = val[0] utils.info(vmi, "export %s=%s", var_name, ret) return ret
def is_active(): utils.info(vmi, "Test if window is active: %s", pattern) win_id = act.run(vmi, cmd_win_id) # Active windows ID. cmd = utils.Cmd("xprop", "-notype", "-id", win_id, prop) output = act.run(vmi, cmd) utils.info(vmi, "Current win name: %s", output) if pattern not in output: msg = "Can't find active window with pattern %s." % pattern raise utils.SpiceUtilsError(msg) # TODO utils.info(vmi, "Found active window: %s.", pattern)