コード例 #1
0
ファイル: iutil_test.py プロジェクト: rvykydal/anaconda
    def start_program_reset_handlers_test(self):
        """Test the reset_handlers parameter of startProgram."""

        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
# Just hang out and do nothing, forever
while true ; do sleep 1 ; done
""")
            testscript.flush()

            # Start a program with reset_handlers
            proc = util.startProgram(["/bin/sh", testscript.name])

            with timer(5):
                # Kill with SIGPIPE and check that the python's SIG_IGN was not inheritted
                # The process should die on the signal.
                proc.send_signal(signal.SIGPIPE)
                proc.communicate()
                self.assertEqual(proc.returncode, -(signal.SIGPIPE))

            # Start another copy without reset_handlers
            proc = util.startProgram(["/bin/sh", testscript.name], reset_handlers=False)

            with timer(5):
                # Kill with SIGPIPE, then SIGTERM, and make sure SIGTERM was the one
                # that worked.
                proc.send_signal(signal.SIGPIPE)
                proc.terminate()
                proc.communicate()
                self.assertEqual(proc.returncode, -(signal.SIGTERM))
コード例 #2
0
    def test_start_program_reset_handlers(self):
        """Test the reset_handlers parameter of startProgram."""

        with tempfile.NamedTemporaryFile(mode="w+t") as testscript:
            testscript.write("""#!/bin/sh
# Just hang out and do nothing, forever
while true ; do sleep 1 ; done
""")
            testscript.flush()

            # Start a program with reset_handlers
            proc = util.startProgram(["/bin/sh", testscript.name])

            with timer(5):
                # Kill with SIGPIPE and check that the python's SIG_IGN was not inheritted
                # The process should die on the signal.
                proc.send_signal(signal.SIGPIPE)
                proc.communicate()
                assert proc.returncode == -(signal.SIGPIPE)

            # Start another copy without reset_handlers
            proc = util.startProgram(["/bin/sh", testscript.name],
                                     reset_handlers=False)

            with timer(5):
                # Kill with SIGPIPE, then SIGTERM, and make sure SIGTERM was the one
                # that worked.
                proc.send_signal(signal.SIGPIPE)
                proc.terminate()
                proc.communicate()
                assert proc.returncode == -(signal.SIGTERM)
コード例 #3
0
ファイル: vnc.py プロジェクト: rvykydal/anaconda
    def startVncConfig(self):
        """Attempt to start vncconfig"""

        self.log.info(_("Attempting to start vncconfig"))

        vncconfigcommand = [self.root + "/usr/bin/vncconfig", "-nowin", "-display", ":%s" % constants.X_DISPLAY_NUMBER]

        # Use startProgram to run vncconfig in the background
        util.startProgram(vncconfigcommand, stdout=self.openlogfile(), stderr=subprocess.STDOUT)
コード例 #4
0
    def startVncConfig(self):
        """Attempt to start vncconfig"""

        self.log.info(_("Attempting to start vncconfig"))

        vncconfigcommand = [self.root + "/usr/bin/vncconfig", "-nowin", "-display", ":%s" % constants.X_DISPLAY_NUMBER]

        # Use startProgram to run vncconfig in the background
        util.startProgram(vncconfigcommand, stdout=self.openlogfile(), stderr=subprocess.STDOUT)
コード例 #5
0
ファイル: users.py プロジェクト: 3838438org/anaconda-1
    def setUserPassword(self,
                        username,
                        password,
                        isCrypted,
                        lock,
                        algo=None,
                        root="/"):
        # Only set the password if it is a string, including the empty string.
        # Otherwise leave it alone (defaults to locked for new users) and reset sp_lstchg
        if password or password == "":
            if password == "":
                log.info("user account %s setup with no password", username)
            elif not isCrypted:
                password = cryptPassword(password, algo)

            if lock:
                password = "******" + password
                log.info("user account %s locked", username)

            proc = util.startProgram(["chpasswd", "-R", root, "-e"],
                                     stdin=subprocess.PIPE)
            proc.communicate(
                ("%s:%s\n" % (username, password)).encode("utf-8"))
            if proc.returncode != 0:
                raise OSError(
                    "Unable to set password for new user: status=%s" %
                    proc.returncode)

        # Reset sp_lstchg to an empty string. On systems with no rtc, this
        # field can be set to 0, which has a special meaning that the password
        # must be reset on the next login.
        util.execWithRedirect("chage", ["-R", root, "-d", "", username])
コード例 #6
0
ファイル: vnc.py プロジェクト: rvykydal/anaconda
    def connectToView(self):
        """Attempt to connect to self.vncconnecthost"""

        maxTries = 10
        self.log.info(_("Attempting to connect to vnc client on host %s..."), self.vncconnecthost)

        if self.vncconnectport != "":
            hostarg = self.vncconnecthost + ":" + self.vncconnectport
        else:
            hostarg = self.vncconnecthost

        vncconfigcommand = [self.root + "/usr/bin/vncconfig", "-display", ":%s" % constants.X_DISPLAY_NUMBER, "-connect", hostarg]

        for _i in range(maxTries):
            vncconfp = util.startProgram(vncconfigcommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  # vncconfig process
            err = vncconfp.communicate()[1].decode("utf-8")

            if err == '':
                self.log.info(_("Connected!"))
                return True
            elif err.startswith("connecting") and err.endswith("failed\n"):
                self.log.info(_("Will try to connect again in 15 seconds..."))
                time.sleep(15)
                continue
            else:
                log.critical(err)
                util.ipmi_abort(scripts=self.anaconda.ksdata.scripts)
                sys.exit(1)
        self.log.error(P_("Giving up attempting to connect after %d try!\n",
                          "Giving up attempting to connect after %d tries!\n",
                          maxTries), maxTries)
        return False
コード例 #7
0
    def run_command(self, command, stdin=None, ignore_failure=False):
        process_error = None

        try:
            sys_root = conf.target.system_root

            cmd = util.startProgram(command,
                                    stderr=subprocess.PIPE,
                                    stdin=stdin,
                                    root=sys_root)

            (stdout, stderr) = cmd.communicate()

            stdout = stdout.decode("utf-8")
            stderr = stderr.decode("utf-8")

            if not ignore_failure and cmd.returncode != 0:
                process_error = "{} failed:\nstdout: \"{}\"\nstderr: \"{}\"".format(
                    command, stdout, stderr)

        except Exception as e:
            process_error = str(e)

        if process_error:
            log.error(process_error)
            raise Exception(process_error)

        return (stdout, stderr)
コード例 #8
0
ファイル: help.py プロジェクト: sandrobonazzola/anaconda
def show_graphical_help(help_path, help_anchor=None):
    """Start a new yelp process and make sure to kill any existing ones.

    :param str help_path: a path to the help file yelp should load
    :param str help_anchor: a name of the anchor in the help file
    """
    global yelp_process

    # Kill the existing process.
    if yelp_process:
        yelp_process.kill()
        yelp_process.wait()
        yelp_process = None

    # Quit if there is nothing to show.
    if not help_path:
        log.error("No help file to show.")
        return

    # Start yelp and show the specified help file at the given anchor.
    args = []

    if help_anchor:
        args.append("ghelp:{}?{}".format(help_path, help_anchor))
    else:
        args.append(help_path)

    yelp_process = startProgram(["yelp", *args], reset_lang=False)
コード例 #9
0
    def start_dbus_session(self):
        """Start dbus session if not running already.

        :returns: True if session was started, False otherwise
        """
        self._log_file = open('/tmp/dbus.log', 'a')
        config_file = "--config-file={}".format(
            os.path.join(ANACONDA_DATA_DIR, "dbus/anaconda-bus.conf"))
        command = [
            DBusLauncher.DBUS_LAUNCH_BIN, '--print-address', "--syslog",
            config_file
        ]
        self._dbus_daemon_process = startProgram(command,
                                                 stderr=self._log_file)

        if self._dbus_daemon_process.poll() is not None:
            raise IOError("DBus wasn't properly started!")

        address = self._dbus_daemon_process.stdout.readline().decode('utf-8')

        if not address:
            raise IOError("Unable to start DBus session!")

        # pylint: disable=environment-modify
        os.environ[DBUS_ANACONDA_SESSION_ADDRESS] = address.rstrip('\n')
        return True
コード例 #10
0
    def connectToView(self):
        """Attempt to connect to self.vncconnecthost"""

        maxTries = 10
        self.log.info(_("Attempting to connect to vnc client on host %s..."), self.vncconnecthost)

        if self.vncconnectport != "":
            hostarg = self.vncconnecthost + ":" + self.vncconnectport
        else:
            hostarg = self.vncconnecthost

        vncconfigcommand = [self.root + "/usr/bin/vncconfig", "-display", ":%s" % constants.X_DISPLAY_NUMBER, "-connect", hostarg]

        for _i in range(maxTries):
            vncconfp = util.startProgram(vncconfigcommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  # vncconfig process
            err = vncconfp.communicate()[1].decode("utf-8")

            if err == '':
                self.log.info(_("Connected!"))
                return True
            elif err.startswith("connecting") and err.endswith("failed\n"):
                self.log.info(_("Will try to connect again in 15 seconds..."))
                time.sleep(15)
                continue
            else:
                log.critical(err)
                util.ipmi_abort(scripts=self.anaconda.ksdata.scripts)
                sys.exit(1)
        self.log.error(P_("Giving up attempting to connect after %d try!\n",
                          "Giving up attempting to connect after %d tries!\n",
                          maxTries), maxTries)
        return False
コード例 #11
0
def set_user_password(username, password, is_crypted, lock, root="/"):
    """Set user password.

    :param str username: username of the user
    :param str password: user password
    :param bool is_crypted: is the password already crypted ?
    :param bool lock: should the password for this username be locked ?
    :param str root: target system sysroot path
    """

    # Only set the password if it is a string, including the empty string.
    # Otherwise leave it alone (defaults to locked for new users) and reset sp_lstchg
    if password or password == "":
        if password == "":
            log.info("user account %s setup with no password", username)
        elif not is_crypted:
            password = crypt_password(password)

        if lock:
            password = "******" + password
            log.info("user account %s locked", username)

        proc = util.startProgram(["chpasswd", "-R", root, "-e"],
                                 stdin=subprocess.PIPE)
        proc.communicate(("%s:%s\n" % (username, password)).encode("utf-8"))
        if proc.returncode != 0:
            raise OSError("Unable to set password for new user: status=%s" %
                          proc.returncode)

    # Reset sp_lstchg to an empty string. On systems with no rtc, this
    # field can be set to 0, which has a special meaning that the password
    # must be reset on the next login.
    util.execWithRedirect("chage", ["-R", root, "-d", "", username])
コード例 #12
0
ファイル: util_test.py プロジェクト: yugart/anaconda
 def test_still_running():
     with timer(5):
         # Run something forever so we can kill it
         proc = util.startProgram(["/bin/sh", "-c", "while true; do sleep 1; done"])
         WatchProcesses.watch_process(proc, "test1")
         proc.kill()
         # Wait for the SIGCHLD
         signal.pause()
コード例 #13
0
ファイル: iutil_test.py プロジェクト: rvykydal/anaconda
 def test_still_running():
     with timer(5):
         # Run something forever so we can kill it
         proc = util.startProgram(["/bin/sh", "-c", "while true; do sleep 1; done"])
         WatchProcesses.watch_process(proc, "test1")
         proc.kill()
         # Wait for the SIGCHLD
         signal.pause()
コード例 #14
0
    def run(self):
        """Run the interface."""
        log.debug("web-ui: starting cockpit web view")
        if self.remote:
            startProgram([
                "/usr/libexec/cockpit-ws", "--no-tls", "--port", "9090",
                "--local-session=cockpit-bridge"
            ])

        proc = startProgram([
            "/usr/libexec/webui-desktop",
            "/cockpit/@localhost/anaconda-webui/index.html"
        ],
                            reset_lang=False)
        log.debug("cockpit web view has been started")
        with open("/run/anaconda/webui_script.pid", "w") as f:
            f.write(repr(proc.pid))
        proc.wait()
        log.debug("cockpit web view has finished running")
        return
コード例 #15
0
ファイル: display.py プロジェクト: martinpitt/anaconda-1
def start_user_systemd():
    """Start the user instance of systemd.

    The service org.a11y.Bus runs the dbus-broker-launch in
    the user scope that requires the user instance of systemd.
    """
    if not conf.system.can_start_user_systemd:
        log.debug("Don't start the user instance of systemd.")
        return

    childproc = util.startProgram(["/usr/lib/systemd/systemd", "--user"])
    WatchProcesses.watch_process(childproc, "systemd")
コード例 #16
0
 def run(self):
     """Run the interface."""
     log.debug("web-ui: starting cockpit web view")
     proc = startProgram([
         "/usr/libexec/cockpit-desktop",
         "/cockpit/@localhost/anaconda-webui/index.html"
     ],
                         reset_lang=False)
     log.debug("cockpit web view has been started")
     proc.wait()
     log.debug("cockpit web view has finished running")
     return
コード例 #17
0
ファイル: help.py プロジェクト: atodorov/anaconda
def start_yelp(help_path):
    """
    Start a new yelp process and make sure to kill any existing ones

    :param help_path: path to the help file yelp should load
    :type help_path: str or NoneType
    """

    kill_yelp()
    log.debug("starting yelp")
    global yelp_process
    # under some extreme circumstances (placeholders missing)
    # the help path can be None and we need to prevent Popen
    # receiving None as an argument instead of a string
    yelp_process = startProgram(["yelp", help_path or ""], reset_lang=False)
コード例 #18
0
ファイル: ihelp.py プロジェクト: zhangsju/anaconda
def start_yelp(help_path):
    """
    Start a new yelp process and make sure to kill any existing ones

    :param help_path: path to the help file yelp should load
    :type help_path: str or NoneType
    """

    kill_yelp()
    log.debug("starting yelp")
    global yelp_process
    # under some extreme circumstances (placeholders missing)
    # the help path can be None and we need to prevent Popen
    # receiving None as an argument instead of a string
    yelp_process = startProgram(["yelp", help_path or ""], reset_lang=False)
コード例 #19
0
ファイル: util_test.py プロジェクト: yugart/anaconda
    def start_program_stdout_test(self):
        """Test redirecting stdout with startProgram."""

        marker_text = "yo wassup man"
        # Create a temporary file that will be written by the program
        with tempfile.NamedTemporaryFile(mode="w+t") as testfile:
            # Open a new copy of the file so that the child doesn't close and
            # delete the NamedTemporaryFile
            stdout = open(testfile.name, 'w')
            with timer(5):
                proc = util.startProgram(["/bin/echo", marker_text], stdout=stdout)
                proc.communicate()

            # Rewind testfile and look for the text
            testfile.seek(0, os.SEEK_SET)
            self.assertEqual(testfile.read().strip(), marker_text)
コード例 #20
0
ファイル: iutil_test.py プロジェクト: rvykydal/anaconda
    def start_program_stdout_test(self):
        """Test redirecting stdout with startProgram."""

        marker_text = "yo wassup man"
        # Create a temporary file that will be written by the program
        with tempfile.NamedTemporaryFile(mode="w+t") as testfile:
            # Open a new copy of the file so that the child doesn't close and
            # delete the NamedTemporaryFile
            stdout = open(testfile.name, 'w')
            with timer(5):
                proc = util.startProgram(["/bin/echo", marker_text], stdout=stdout)
                proc.communicate()

            # Rewind testfile and look for the text
            testfile.seek(0, os.SEEK_SET)
            self.assertEqual(testfile.read().strip(), marker_text)
コード例 #21
0
ファイル: iutil_test.py プロジェクト: rvykydal/anaconda
    def watch_process_test(self):
        """Test watchProcess"""

        def test_still_running():
            with timer(5):
                # Run something forever so we can kill it
                proc = util.startProgram(["/bin/sh", "-c", "while true; do sleep 1; done"])
                WatchProcesses.watch_process(proc, "test1")
                proc.kill()
                # Wait for the SIGCHLD
                signal.pause()
        self.assertRaises(ExitError, test_still_running)

        # Make sure watchProcess checks that the process has not already exited
        with timer(5):
            proc = util.startProgram(["true"])
            proc.communicate()
        self.assertRaises(ExitError, WatchProcesses.watch_process, proc, "test2")
コード例 #22
0
ファイル: util_test.py プロジェクト: yugart/anaconda
    def watch_process_test(self):
        """Test watchProcess"""

        def test_still_running():
            with timer(5):
                # Run something forever so we can kill it
                proc = util.startProgram(["/bin/sh", "-c", "while true; do sleep 1; done"])
                WatchProcesses.watch_process(proc, "test1")
                proc.kill()
                # Wait for the SIGCHLD
                signal.pause()
        self.assertRaises(ExitError, test_still_running)

        # Make sure watchProcess checks that the process has not already exited
        with timer(5):
            proc = util.startProgram(["true"])
            proc.communicate()
        self.assertRaises(ExitError, WatchProcesses.watch_process, proc, "test2")
コード例 #23
0
    def setVNCPassword(self):
        """Set the vnc server password. Output to file. """
        password_string = "%s\n" % self.password

        # the -f option makes sure vncpasswd does not ask for the password again
        proc = util.startProgram(["vncpasswd", "-f"],
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)

        out, err = proc.communicate(password_string.encode("utf-8"))

        if proc.returncode != 0:
            log.error("vncpasswd has failed with %d: %s", proc.returncode,
                      err.decode("utf-8"))
            raise OSError("Unable to set the VNC password.")

        with open(self.pw_file, "wb") as pw_file:
            pw_file.write(out)
コード例 #24
0
ファイル: vnc.py プロジェクト: rvykydal/anaconda
    def setVNCPassword(self):
        """Set the vnc server password. Output to file. """
        password_string = "%s\n" % self.password

        # the -f option makes sure vncpasswd does not ask for the password again
        proc = util.startProgram(
            ["vncpasswd", "-f"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )

        out, err = proc.communicate(password_string.encode("utf-8"))

        if proc.returncode != 0:
            log.error("vncpasswd has failed with %d: %s", proc.returncode, err.decode("utf-8"))
            raise OSError("Unable to set the VNC password.")

        with open(self.pw_file, "wb") as pw_file:
            pw_file.write(out)
コード例 #25
0
def do_startup_x11_actions():
    """Start the window manager.

    When metacity actually connects to the X server is unknowable, but
    fortunately it doesn't matter. metacity does not need to be the first
    connection to Xorg, and if anaconda starts up before metacity, metacity
    will just take over and maximize the window and make everything right,
    fingers crossed.
    Add XDG_DATA_DIRS to the environment to pull in our overridden schema
    files.
    """
    datadir = os.environ.get('ANACONDA_DATADIR', '/usr/share/anaconda')
    if 'XDG_DATA_DIRS' in os.environ:
        xdg_data_dirs = datadir + '/window-manager:' + os.environ['XDG_DATA_DIRS']
    else:
        xdg_data_dirs = datadir + '/window-manager:/usr/share'

    childproc = util.startProgram(["metacity", "--display", ":1", "--sm-disable"],
                                  env_add={'XDG_DATA_DIRS': xdg_data_dirs})
    WatchProcesses.watch_process(childproc, "metacity")
コード例 #26
0
ファイル: display.py プロジェクト: zhangsju/anaconda
def do_startup_x11_actions():
    """Start the window manager.

    When metacity actually connects to the X server is unknowable, but
    fortunately it doesn't matter. metacity does not need to be the first
    connection to Xorg, and if anaconda starts up before metacity, metacity
    will just take over and maximize the window and make everything right,
    fingers crossed.
    Add XDG_DATA_DIRS to the environment to pull in our overridden schema
    files.
    """
    datadir = os.environ.get('ANACONDA_DATADIR', '/usr/share/anaconda')
    if 'XDG_DATA_DIRS' in os.environ:
        xdg_data_dirs = datadir + '/window-manager:' + os.environ['XDG_DATA_DIRS']
    else:
        xdg_data_dirs = datadir + '/window-manager:/usr/share'

    childproc = util.startProgram(["metacity", "--display", ":1", "--sm-disable"],
                                  env_add={'XDG_DATA_DIRS': xdg_data_dirs})
    WatchProcesses.watch_process(childproc, "metacity")
コード例 #27
0
    def _start_dbus_session(self):
        """Start dbus session if not running already."""
        command = [
            self.DBUS_LAUNCH_BIN,
            '--print-address',
            "--syslog",
            "--config-file={}".format(ANACONDA_BUS_CONF_FILE)
        ]

        self._log_file = open('/tmp/dbus.log', 'a')
        self._dbus_daemon_process = startProgram(command, stderr=self._log_file, reset_lang=False)

        if self._dbus_daemon_process.poll() is not None:
            raise RuntimeError("DBus wasn't properly started!")

        address = self._dbus_daemon_process.stdout.readline().decode('utf-8').strip()

        if not address:
            raise RuntimeError("Unable to start DBus session!")

        self._bus_address = address
コード例 #28
0
    def test_start_program_preexec_fn(self):
        """Test passing preexec_fn to startProgram."""

        marker_text = "yo wassup man"
        # Create a temporary file that will be written before exec
        with tempfile.NamedTemporaryFile(mode="w+t") as testfile:

            # Write something to testfile to show this method was run
            def preexec():
                # Open a copy of the file here since close_fds has already closed the descriptor
                testcopy = open(testfile.name, 'w')
                testcopy.write(marker_text)
                testcopy.close()

            with timer(5):
                # Start a program that does nothing, with a preexec_fn
                proc = util.startProgram(["/bin/true"], preexec_fn=preexec)
                proc.communicate()

            # Rewind testfile and look for the text
            testfile.seek(0, os.SEEK_SET)
            assert testfile.read() == marker_text
コード例 #29
0
ファイル: users.py プロジェクト: rvykydal/anaconda
    def setUserPassword(self, username, password, isCrypted, lock, algo=None, root="/"):
        # Only set the password if it is a string, including the empty string.
        # Otherwise leave it alone (defaults to locked for new users) and reset sp_lstchg
        if password or password == "":
            if password == "":
                log.info("user account %s setup with no password", username)
            elif not isCrypted:
                password = cryptPassword(password, algo)

            if lock:
                password = "******" + password
                log.info("user account %s locked", username)

            proc = util.startProgram(["chpasswd", "-R", root, "-e"], stdin=subprocess.PIPE)
            proc.communicate(("%s:%s\n" % (username, password)).encode("utf-8"))
            if proc.returncode != 0:
                raise OSError("Unable to set password for new user: status=%s" % proc.returncode)

        # Reset sp_lstchg to an empty string. On systems with no rtc, this
        # field can be set to 0, which has a special meaning that the password
        # must be reset on the next login.
        util.execWithRedirect("chage", ["-R", root, "-d", "", username])
コード例 #30
0
ファイル: iutil_test.py プロジェクト: rvykydal/anaconda
    def start_program_preexec_fn_test(self):
        """Test passing preexec_fn to startProgram."""

        marker_text = "yo wassup man"
        # Create a temporary file that will be written before exec
        with tempfile.NamedTemporaryFile(mode="w+t") as testfile:

            # Write something to testfile to show this method was run
            def preexec():
                # Open a copy of the file here since close_fds has already closed the descriptor
                testcopy = open(testfile.name, 'w')
                testcopy.write(marker_text)
                testcopy.close()

            with timer(5):
                # Start a program that does nothing, with a preexec_fn
                proc = util.startProgram(["/bin/true"], preexec_fn=preexec)
                proc.communicate()

            # Rewind testfile and look for the text
            testfile.seek(0, os.SEEK_SET)
            self.assertEqual(testfile.read(), marker_text)