Exemplo n.º 1
0
def _get_alembic_config_from_cache(
    force_cfg: Optional[Dict] = None, ) -> Optional[AlembicConfig]:
    """
        Creates alembic config from cfg or cache

        Returns None if cannot build url (e.g. if user requires a cache that does not exists)
    """

    # build url
    try:
        if force_cfg:
            cfg = force_cfg
        else:
            cfg = _load_cache(raise_if_error=True)

        url = build_url(**cfg)
    except Exception:
        log.debug("Cannot open cache or cannot build URL",
                  exc_info=True,
                  stack_info=True)
        click.echo("Invalid database config, please run discover first",
                   err=True)
        _reset_cache()
        return None

    # build config
    config = AlembicConfig(default_ini)
    config.set_main_option("script_location", str(migration_dir))
    config.set_main_option("sqlalchemy.url", str(url))
    return config
Exemplo n.º 2
0
def discover(**cli_inputs) -> Optional[Dict]:
    """Discovers databases and caches configs in ~/.simcore_postgres_database.json (except if --no-cache)"""
    # NOTE: Do not add defaults to user, password so we get a chance to ping urls
    # TODO: if multiple candidates online, then query user to select

    click.echo("Discovering database ...")
    cli_cfg = {key: value for key, value in cli_inputs.items() if value is not None}

    # tests different urls

    def _test_cached() -> Dict:
        """Tests cached configuration"""
        cfg = load_cache(raise_if_error=True)
        cfg.update(cli_cfg)  # overrides
        return cfg

    def _test_env() -> Dict:
        """Tests environ variables"""
        cfg = {
            "user": os.getenv("POSTGRES_USER"),
            "password": os.getenv("POSTGRES_PASSWORD"),
            "host": os.getenv("POSTGRES_HOST", DEFAULT_HOST),
            "port": int(os.getenv("POSTGRES_PORT") or DEFAULT_PORT),
            "database": os.getenv("POSTGRES_DB", DEFAULT_DB),
        }
        cfg.update(cli_cfg)
        return cfg

    def _test_swarm() -> Dict:
        """Tests published port in swarm from host"""
        cfg = _test_env()
        cfg["host"] = "127.0.0.1"
        cfg["port"] = get_service_published_port(cli_cfg.get("host", DEFAULT_HOST))
        cfg.setdefault("database", DEFAULT_DB)
        return cfg

    for test in [_test_cached, _test_env, _test_swarm]:
        try:
            click.echo("-> {0.__name__}: {0.__doc__}".format(test))

            cfg: Dict = test()
            cfg.update(cli_cfg)  # CLI always overrides
            url = build_url(**cfg)

            click.echo(f"ping {test.__name__}: {hide_url_pass(url)} ...")
            raise_if_not_responsive(url, verbose=False)

            print("Saving config ")
            click.echo(f"Saving config at {DISCOVERED_CACHE}: {hide_dict_pass(cfg)}")
            with open(DISCOVERED_CACHE, "wt") as fh:
                json.dump(cfg, fh, sort_keys=True, indent=4)

            print("Saving config at ")
            click.secho(
                f"{test.__name__} succeeded: {hide_url_pass(url)} is online",
                blink=False,
                bold=True,
                fg="green",
            )

            return cfg

        except Exception as err:  # pylint: disable=broad-except
            inline_msg = str(err).replace("\n", ". ")
            click.echo(f"<- {test.__name__} failed : {inline_msg}")

    reset_cache()
    click.secho("Sorry, database not found !!", blink=False, bold=True, fg="red")
    return None