Пример #1
0
def run(args):
    """Handle Open Peer Power auth provider script."""
    parser = argparse.ArgumentParser(description="Manage Open Peer Power users")
    parser.add_argument("--script", choices=["auth"])
    parser.add_argument(
        "-c",
        "--config",
        default=get_default_config_dir(),
        help="Directory that contains the Open Peer Power configuration",
    )

    subparsers = parser.add_subparsers(dest="func")
    subparsers.required = True
    parser_list = subparsers.add_parser("list")
    parser_list.set_defaults(func=list_users)

    parser_add = subparsers.add_parser("add")
    parser_add.add_argument("username", type=str)
    parser_add.add_argument("password", type=str)
    parser_add.set_defaults(func=add_user)

    parser_validate_login = subparsers.add_parser("validate")
    parser_validate_login.add_argument("username", type=str)
    parser_validate_login.add_argument("password", type=str)
    parser_validate_login.set_defaults(func=validate_login)

    parser_change_pw = subparsers.add_parser("change_password")
    parser_change_pw.add_argument("username", type=str)
    parser_change_pw.add_argument("new_password", type=str)
    parser_change_pw.set_defaults(func=change_password)

    asyncio.set_event_loop_policy(runner.OppEventLoopPolicy(False))
    asyncio.run(run_command(parser.parse_args(args)))
Пример #2
0
def run(args):
    """Handle ensure config commandline script."""
    parser = argparse.ArgumentParser(
        description=(
            "Ensure a Open Peer Power config exists, creates one if necessary."
        )
    )
    parser.add_argument(
        "-c",
        "--config",
        metavar="path_to_config_dir",
        default=config_util.get_default_config_dir(),
        help="Directory that contains the Open Peer Power configuration",
    )
    parser.add_argument("--script", choices=["ensure_config"])

    args = parser.parse_args()

    config_dir = os.path.join(os.getcwd(), args.config)

    # Test if configuration directory exists
    if not os.path.isdir(config_dir):
        print("Creating directory", config_dir)
        os.makedirs(config_dir)

    opp = OpenPeerPower()
    opp.config.config_dir = config_dir
    config_path = opp.loop.run_until_complete(async_run(opp))
    print("Configuration file:", config_path)
    return 0
Пример #3
0
def ensure_config_path(config_dir: str) -> None:
    """Validate the configuration directory."""
    import openpeerpower.config as config_util

    lib_dir = os.path.join(config_dir, "deps")

    # Test if configuration directory exists
    if not os.path.isdir(config_dir):
        if config_dir != config_util.get_default_config_dir():
            print(
                f"Fatal Error: Specified configuration directory {config_dir} "
                "does not exist"
            )
            sys.exit(1)

        try:
            os.mkdir(config_dir)
        except OSError:
            print(
                "Fatal Error: Unable to create default configuration "
                f"directory {config_dir}"
            )
            sys.exit(1)

    # Test if library directory exists
    if not os.path.isdir(lib_dir):
        try:
            os.mkdir(lib_dir)
        except OSError:
            print(f"Fatal Error: Unable to create library directory {lib_dir}")
            sys.exit(1)
Пример #4
0
def extract_config_dir(args: Optional[Sequence[Text]] = None) -> str:
    """Extract the config dir from the arguments or get the default."""
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-c", "--config", default=None)
    parsed_args = parser.parse_known_args(args)[0]
    return (os.path.join(os.getcwd(), parsed_args.config)
            if parsed_args.config else get_default_config_dir())
Пример #5
0
def run(args):
    """Handle Open Peer Power auth provider script."""
    parser = argparse.ArgumentParser(
        description="Manage Open Peer Power users")
    parser.add_argument("--script", choices=["auth"])
    parser.add_argument(
        "-c",
        "--config",
        default=get_default_config_dir(),
        help="Directory that contains the Open Peer Power configuration",
    )

    subparsers = parser.add_subparsers(dest="func")
    subparsers.required = True
    parser_list = subparsers.add_parser("list")
    parser_list.set_defaults(func=list_users)

    parser_add = subparsers.add_parser("add")
    parser_add.add_argument("username", type=str)
    parser_add.add_argument("password", type=str)
    parser_add.set_defaults(func=add_user)

    parser_validate_login = subparsers.add_parser("validate")
    parser_validate_login.add_argument("username", type=str)
    parser_validate_login.add_argument("password", type=str)
    parser_validate_login.set_defaults(func=validate_login)

    parser_change_pw = subparsers.add_parser("change_password")
    parser_change_pw.add_argument("username", type=str)
    parser_change_pw.add_argument("new_password", type=str)
    parser_change_pw.set_defaults(func=change_password)

    args = parser.parse_args(args)
    loop = asyncio.get_event_loop()
    opp = OpenPeerPower(loop=loop)
    loop.run_until_complete(run_command(opp, args))

    # Triggers save on used storage helpers with delay (core auth)
    logging.getLogger("openpeerpower.core").setLevel(logging.WARNING)
    loop.run_until_complete(opp.async_stop())
Пример #6
0
def run(script_args: List) -> int:
    """Handle check config commandline script."""
    parser = argparse.ArgumentParser(
        description="Check Open Peer Power configuration.")
    parser.add_argument("--script", choices=["check_config"])
    parser.add_argument(
        "-c",
        "--config",
        default=get_default_config_dir(),
        help="Directory that contains the Open Peer Power configuration",
    )
    parser.add_argument(
        "-i",
        "--info",
        nargs="?",
        default=None,
        const="all",
        help="Show a portion of the config",
    )
    parser.add_argument("-f",
                        "--files",
                        action="store_true",
                        help="Show used configuration files")
    parser.add_argument("-s",
                        "--secrets",
                        action="store_true",
                        help="Show secret information")

    args, unknown = parser.parse_known_args()
    if unknown:
        print(color("red", "Unknown arguments:", ", ".join(unknown)))

    config_dir = os.path.join(os.getcwd(), args.config)

    print(color("bold", "Testing configuration at", config_dir))

    res = check(config_dir, args.secrets)

    domain_info: List[str] = []
    if args.info:
        domain_info = args.info.split(",")

    if args.files:
        print(color(C_HEAD, "yaml files"), "(used /",
              color("red", "not used") + ")")
        deps = os.path.join(config_dir, "deps")
        yaml_files = [
            f for f in glob(os.path.join(config_dir, "**/*.yaml"),
                            recursive=True) if not f.startswith(deps)
        ]

        for yfn in sorted(yaml_files):
            the_color = "" if yfn in res["yaml_files"] else "red"
            print(color(the_color, "-", yfn))

    if res["except"]:
        print(color("bold_white", "Failed config"))
        for domain, config in res["except"].items():
            domain_info.append(domain)
            print(" ", color("bold_red", domain + ":"),
                  color("red", "", reset="red"))
            dump_dict(config, reset="red")
            print(color("reset"))

    if domain_info:
        if "all" in domain_info:
            print(color("bold_white", "Successful config (all)"))
            for domain, config in res["components"].items():
                print(" ", color(C_HEAD, domain + ":"))
                dump_dict(config)
        else:
            print(color("bold_white", "Successful config (partial)"))
            for domain in domain_info:
                if domain == ERROR_STR:
                    continue
                print(" ", color(C_HEAD, domain + ":"))
                dump_dict(res["components"].get(domain, None))

    if args.secrets:
        flatsecret: Dict[str, str] = {}

        for sfn, sdict in res["secret_cache"].items():
            sss = []
            for skey in sdict:
                if skey in flatsecret:
                    _LOGGER.error("Duplicated secrets in files %s and %s",
                                  flatsecret[skey], sfn)
                flatsecret[skey] = sfn
                sss.append(
                    color("green", skey) if skey in res["secrets"] else skey)
            print(color(C_HEAD, "Secrets from", sfn + ":"), ", ".join(sss))

        print(color(C_HEAD, "Used Secrets:"))
        for skey, sval in res["secrets"].items():
            if sval is None:
                print(" -", skey + ":", color("red", "not found"))
                continue
            print(
                " -",
                skey + ":",
                sval,
                color("cyan", "[from:",
                      flatsecret.get(skey, "keyring") + "]"),
            )

    return len(res["except"])
Пример #7
0
def get_arguments() -> argparse.Namespace:
    """Get parsed passed in arguments."""
    import openpeerpower.config as config_util

    parser = argparse.ArgumentParser(
        description="Open Peer Power: Observe, Control, Automate."
    )
    parser.add_argument("--version", action="version", version=__version__)
    parser.add_argument(
        "-c",
        "--config",
        metavar="path_to_config_dir",
        default=config_util.get_default_config_dir(),
        help="Directory that contains the Open Peer Power configuration",
    )
    parser.add_argument(
        "--safe-mode", action="store_true", help="Start Open Peer Power in safe mode"
    )
    parser.add_argument(
        "--debug", action="store_true", help="Start Open Peer Power in debug mode"
    )
    parser.add_argument(
        "--open-ui", action="store_true", help="Open the webinterface in a browser"
    )
    parser.add_argument(
        "--skip-pip",
        action="store_true",
        help="Skips pip install of required packages on startup",
    )
    parser.add_argument(
        "-v", "--verbose", action="store_true", help="Enable verbose logging to file."
    )
    parser.add_argument(
        "--pid-file",
        metavar="path_to_pid_file",
        default=None,
        help="Path to PID file useful for running as daemon",
    )
    parser.add_argument(
        "--log-rotate-days",
        type=int,
        default=None,
        help="Enables daily log rotation and keeps up to the specified days",
    )
    parser.add_argument(
        "--log-file",
        type=str,
        default=None,
        help="Log file to write to.  If not set, CONFIG/open-peer-power.log is used",
    )
    parser.add_argument(
        "--log-no-color", action="store_true", help="Disable color logs"
    )
    parser.add_argument(
        "--runner",
        action="store_true",
        help=f"On restart exit with code {RESTART_EXIT_CODE}",
    )
    parser.add_argument(
        "--script", nargs=argparse.REMAINDER, help="Run one of the embedded scripts"
    )
    if os.name == "posix":
        parser.add_argument(
            "--daemon", action="store_true", help="Run Open Peer Power as daemon"
        )

    arguments = parser.parse_args()
    if os.name != "posix" or arguments.debug or arguments.runner:
        setattr(arguments, "daemon", False)

    return arguments