Beispiel #1
0
def _get_config():

    try:
        config = load_config()
    except ConfigError as e:
        print("Error loading config file : %s" % str(e))
        sys.exit(1)

    return config
def main():

    # Arguments parsing
    parser = argparse.ArgumentParser(description="Daemon program for the Optimus Manager tool.\n"
                                                 "https://github.com/Askannz/optimus-manager")
    parser.parse_args()

    print("Optimus Manager (Daemon) version %s" % envs.VERSION)

    # Config
    try:
        config = load_config()
    except ConfigError as e:
        print("Error loading config file : %s" % str(e))

    # UNIX socket

    if os.path.exists(envs.SOCKET_PATH):
        print("Warning : the UNIX socket file %s already exists ! Either another "
              "daemon instance is running or the daemon was not exited gracefully "
              "last time.\nRemoving the file and moving on..." % envs.SOCKET_PATH)
        os.remove(envs.SOCKET_PATH)

    server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    server.settimeout(envs.SOCKET_TIMEOUT)
    server.bind(envs.SOCKET_PATH)
    os.chmod(envs.SOCKET_PATH, 0o666)

    # Signal hander
    handler = SignalHandler(server)
    signal.signal(signal.SIGTERM, handler.handler)
    signal.signal(signal.SIGINT, handler.handler)

    print("Awaiting commands")
    while True:

        r, _, _ = select.select([server], [], [])
        datagram = server.recv(1024)
        msg = datagram.decode('utf-8')

        print("Received command : %s" % msg)

        # Switching
        if msg == "intel":
            gpu_switch(config, "intel")
        elif msg == "nvidia":
            gpu_switch(config, "nvidia")

        # Startup modes
        elif msg == "startup_nvidia":
            set_startup("nvidia")
        elif msg == "startup_intel":
            set_startup("intel")
        elif msg == "startup_nvidia_once":
            set_startup("nvidia_once")
        else:
            print("Invalid command !")
Beispiel #3
0
def main():

    # Arguments parsing
    parser = argparse.ArgumentParser(
        description=
        "Display Manager setup service for the Optimus Manager tool.\n"
        "https://github.com/Askannz/optimus-manager")
    parser.add_argument('--setup-start',
                        action='store_true',
                        help='Setup Optimus before the login manager starts.')
    parser.add_argument('--setup-stop',
                        action='store_true',
                        help='Cleanup Optimus after the login manager stops.')

    args = parser.parse_args()

    print("Optimus Manager (DM setup) version %s" % envs.VERSION)

    # Config
    try:
        config = load_config()
    except ConfigError as e:
        print("Error loading config file : %s" % str(e))
        sys.exit(1)

    if args.setup_start:

        print("Setting up Optimus configuration")

        # Cleanup
        clean_autogenerated()

        try:
            requested_mode = read_requested_mode()
        except VarError as e:

            print(
                "Cannot read requested mode : %s.\nUsing startup mode instead."
                % str(e))

            try:
                startup_mode = read_startup_mode()
            except VarError as e:
                print(
                    "Cannot read startup mode : %s.\nUsing default startup mode %s instead."
                    % (str(e), envs.DEFAULT_STARTUP_MODE))
                startup_mode = envs.DEFAULT_STARTUP_MODE

            print("Startup mode :", startup_mode)
            if startup_mode == "nvidia_once":
                requested_mode = "nvidia"
                write_startup_mode("intel")
            else:
                requested_mode = startup_mode

        # We are done reading the command
        remove_requested_mode_var()

        print("Requested mode :", requested_mode)

        try:
            if requested_mode == "nvidia":
                switch_to_nvidia(config)
            elif requested_mode == "intel":
                switch_to_intel(config)
        except SwitchError as e:
            print("Cannot switch GPUS : %s" % str(e))
            sys.exit(0)

    elif args.setup_stop:

        print("Cleaning up Optimus configuration")
        clean_autogenerated()

        #
        print("Terminating X11 sessions")
        try:
            terminate_current_x11_sessions()
        except SessionError as e:
            print("Error terminating sessions : %s" % str(e))

        #
        print("Killing remaining X11 servers")
        try:
            kill_current_xorg_servers()
        except XorgError as e:
            print("Error killing X servers : %s" % str(e))

        #
        # There is a known bug causing systemd-logind to keep ownership of the GPU
        # and prevents module unloading
        print("Killing systemd-logind")
        try:
            exec_bash("pkill systemd-logind")
        except BashError:
            pass

        print("Unloading kernel modules")
        try:
            exec_bash(
                "modprobe -r nvidia_drm nvidia_modeset nvidia_uvm nvidia nouveau"
            )
        except BashError as e:
            print("Cannot unload modules : %s" % str(e))
            sys.exit(1)

        # Reset the PCI device corresponding to the Nvidia GPU
        if config["optimus"]["pci_reset"] == "yes":
            if config["optimus"]["switching"] == "bbswitch":
                print("bbswitch is enabled, pci_reset option ignored.")
            else:
                print("Resetting the GPU")
                try:
                    pci.reset_gpu()
                except pci.PCIError as e:
                    print("Error resetting the PCI device : %s" % str(e))

    else:

        print("Invalid argument")
Beispiel #4
0
def main():

    # Arguments parsing
    parser = argparse.ArgumentParser(description="Client program for the Optimus Manager tool.\n"
                                                 "https://github.com/Askannz/optimus-manager")
    parser.add_argument('-v', '--version', action='store_true', help='Print version and exit.')
    parser.add_argument('--print-mode', action='store_true',
                        help="Print the current mode.")
    parser.add_argument('--switch', metavar='MODE', action='store',
                        help="Set the GPU mode to MODE and restart the display manager. "
                             "Possible modes : intel, nvidia, auto (checks the current mode and switch to the other). "
                             "WARNING : All your applications will close ! Be sure to save your work.")
    parser.add_argument('--set-startup', metavar='STARTUP_MODE', action='store',
                        help="Set the startup mode to STARTUP_MODE. Possible modes : "
                             "intel, nvidia, nvidia_once (starts with Nvidia and reverts to Intel for the next boot)")
    parser.add_argument('--print-startup', action='store_true',
                        help="Print the current startup mode.")
    parser.add_argument('--no-confirm', action='store_true',
                        help="Do not ask for confirmation before switching GPUs.")
    parser.add_argument('--cleanup', action='store_true',
                        help="Remove auto-generated configuration files left over by the daemon.")
    args = parser.parse_args()

    # Config loading
    # Even if the client does not need any option from it (yet), we parse the config file.
    # That way the user can see parsing errors without opening a systemd log.
    if not args.version:
        try:
            load_config()
        except ConfigError as e:
            print("Error loading config file : %s" % str(e))
            sys.exit(1)

    #
    # Arguments switch

    if args.version:
        print("Optimus Manager (Client) version %s" % envs.VERSION)
        sys.exit(0)

    elif args.print_mode:

        try:
            mode = checks.read_gpu_mode()
        except checks.CheckError as e:
            print("Error reading mode : %s" % str(e))
            sys.exit(1)

        print("Current mode : %s" % mode)

    elif args.print_startup:

        try:
            startup_mode = var.read_startup_mode()
        except var.VarError as e:
            print("Error reading startup mode : %s" % str(e))
            sys.exit(1)

        print("Current startup mode : %s" % startup_mode)

    elif args.switch:

        if args.switch not in ["auto", "intel", "nvidia"]:
            print("Invalid mode : %s" % args.switch)
            sys.exit(1)

        if not checks.is_daemon_active():
            print("The optimus-manager service is not running. Please enable and start it with :\n\n"
                  "sudo systemctl enable optimus-manager\n"
                  "sudo systemctl start optimus-manager\n")
            sys.exit(1)

        if args.switch == "auto":
            try:
                gpu_mode = checks.read_gpu_mode()
            except checks.CheckError as e:
                print("Error reading mode: %s" % str(e))
                sys.exit(1)

            if gpu_mode == "nvidia":
                switch_mode = "intel"
            else:
                switch_mode = "nvidia"
            print("Switching to : %s" % switch_mode)

        else:
            switch_mode = args.switch

        if args.no_confirm:
            send_command(switch_mode)
        else:
            print("WARNING : You are about to switch GPUs. This will restart the display manager and all your applications WILL CLOSE.\n"
                  "(you can pass the --no-confirm option to disable this warning)\n"
                  "Continue ? (y/N)")
            ans = input("> ").lower()

            if ans == "y":
                send_command(switch_mode)
            elif ans == "n" or ans == "N":
                print("Aborting.")
            else:
                print("Invalid choice. Aborting")

    elif args.set_startup:

        if args.set_startup not in ["intel", "nvidia", "nvidia_once"]:
            print("Invalid startup mode : %s" % args.set_startup)
            sys.exit(1)

        send_command("startup_" + args.set_startup)

    elif args.cleanup:

        if os.geteuid() != 0:
            print("You need to execute the command as root for this action.")
            sys.exit(1)

        clean_all()

    else:

        print("Invalid arguments.")
def main():

    # Arguments parsing
    parser = argparse.ArgumentParser(
        description="Client program for the Optimus Manager tool.\n"
        "https://github.com/Askannz/optimus-manager")
    parser.add_argument('-v',
                        '--version',
                        action='store_true',
                        help='Print version and exit.')
    parser.add_argument('--print-mode',
                        action='store_true',
                        help="Print the current mode.")
    parser.add_argument(
        '--switch',
        metavar='MODE',
        action='store',
        help="Set the GPU mode to MODE and restart the display manager. "
        "Possible modes : intel, nvidia, auto (checks the current mode and switch to the other). "
        "WARNING : All your applications will close ! Be sure to save your work."
    )
    parser.add_argument(
        '--set-startup',
        metavar='STARTUP_MODE',
        action='store',
        help="Set the startup mode to STARTUP_MODE. Possible modes : "
        "intel, nvidia, nvidia_once (starts with Nvidia and reverts to Intel for the next boot)"
    )
    parser.add_argument('--print-startup',
                        action='store_true',
                        help="Print the current startup mode.")
    parser.add_argument(
        '--no-confirm',
        action='store_true',
        help="Do not ask for confirmation before switching GPUs.")
    parser.add_argument(
        '--cleanup',
        action='store_true',
        help=
        "Remove auto-generated configuration files left over by the daemon.")
    args = parser.parse_args()

    # Config loading
    if not args.version:
        try:
            config = load_config()
        except ConfigError as e:
            print("Error loading config file : %s" % str(e))
            sys.exit(1)

    #
    # Arguments switch

    if args.version:
        print("Optimus Manager (Client) version %s" % envs.VERSION)
        sys.exit(0)

    elif args.print_mode:

        try:
            mode = checks.read_gpu_mode()
        except checks.CheckError as e:
            print("Error reading mode : %s" % str(e))
            sys.exit(1)

        print("Current mode : %s" % mode)

    elif args.print_startup:

        try:
            startup_mode = var.read_startup_mode()
        except var.VarError as e:
            print("Error reading startup mode : %s" % str(e))
            sys.exit(1)

        print("Current startup mode : %s" % startup_mode)

    elif args.switch:

        if args.switch not in ["auto", "intel", "nvidia"]:
            print("Invalid mode : %s" % args.switch)
            sys.exit(1)

        if not checks.is_daemon_active():
            print(
                "The optimus-manager service is not running. Please enable and start it with :\n\n"
                "sudo systemctl enable optimus-manager\n"
                "sudo systemctl start optimus-manager\n")
            sys.exit(1)

        if args.switch == "auto":
            try:
                gpu_mode = checks.read_gpu_mode()
            except checks.CheckError as e:
                print("Error reading mode: %s" % str(e))
                sys.exit(1)

            if gpu_mode == "nvidia":
                switch_mode = "intel"
            else:
                switch_mode = "nvidia"
            print("Switching to : %s" % switch_mode)

        else:
            switch_mode = args.switch

        # Printing warnings if something is wrong
        if config["optimus"][
                "switching"] == "bbswitch" and not checks.is_module_available(
                    "bbswitch"):
            print(
                "WARNING : bbswitch is enabled in the configuration file but the bbswitch module does"
                " not seem to be available for the current kernel. Power switching will not work.\n"
                "You can install bbswitch for the default kernel with \"sudo pacman -S bbswitch\" or"
                " for all kernels with \"sudo pacman -S bbswitch-dkms\".\n")

        if switch_mode == "nvidia" and not checks.is_module_available(
                "nvidia"):
            print(
                "WARNING : the nvidia module does not seem to be available for the current kernel."
                " It is likely the Nvidia driver was not properly installed. GPU switching will probably fail,"
                " continue anyway ? (y/N)")
            ans = input("> ").lower()

            if ans == "y":
                pass
            elif ans == "n" or ans == "N":
                print("Aborting.")
                sys.exit(0)
            else:
                print("Invalid choice. Aborting")
                sys.exit(0)

        if args.no_confirm:
            send_command(switch_mode)
        else:
            print(
                "You are about to switch GPUs. This will restart the display manager and all your applications WILL CLOSE.\n"
                "(you can pass the --no-confirm option to disable this warning)\n"
                "Continue ? (y/N)")
            ans = input("> ").lower()

            if ans == "y":
                send_command(switch_mode)
            elif ans == "n" or ans == "N":
                print("Aborting.")
                sys.exit(0)
            else:
                print("Invalid choice. Aborting")
                sys.exit(0)

    elif args.set_startup:

        if args.set_startup not in ["intel", "nvidia", "nvidia_once"]:
            print("Invalid startup mode : %s" % args.set_startup)
            sys.exit(1)

        send_command("startup_" + args.set_startup)

    elif args.cleanup:

        if os.geteuid() != 0:
            print("You need to execute the command as root for this action.")
            sys.exit(1)

        clean_autogenerated()
        var.remove_startup_mode_var()
        var.remove_requested_mode_var()

    else:

        print("Invalid arguments.")