def set(**kwargs): # pylint:disable=redefined-builtin """Set the global config values. Example: \b $ polyaxon config set --host=localhost """ try: _config = ClientConfigManager.get_config_or_default() except Exception as e: handle_cli_error(e, message="Polyaxon load configuration.") Printer.print_header( "You can reset your config by running: polyaxon config purge" ) sys.exit(1) for key, value in kwargs.items(): if value is not None: setattr(_config, key, value) ClientConfigManager.set_config(_config) Printer.print_success("Config was updated.") # Reset cli config CliConfigManager.purge()
def test_should_check(self): with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 1 assert result is True CliConfigManager.reset( current_version="0.0.5", server_versions={"cli": {"min_version": "0.0.4"}} ) with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 1 assert result is False CliConfigManager.reset( check_count=4, current_version="0.0.5", server_versions={"cli": {"min_version": "0.0.4"}}, ) with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 1 assert result is True CliConfigManager.reset( current_version="0.0.2", server_versions={"cli": {"min_version": "0.0.4"}} ) with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 1 assert result is True
def purge(): """Purge the global config values.""" ClientConfigManager.purge() CliConfigManager.purge() AuthConfigManager.purge() ProjectManager.purge() RunManager.purge() Printer.print_success("Config was removed.")
def purge(cache_only): """Purge the global config values.""" if not cache_only: ClientConfigManager.purge() CliConfigManager.purge() AuthConfigManager.purge() UserConfigManager.purge() ProjectConfigManager.purge() RunConfigManager.purge() Printer.print_success("Configs was removed.")
def set_cli_config(): from polyaxon.managers.cli import CliConfigManager global CLI_CONFIG try: CLI_CONFIG = CliConfigManager.get_config_or_default() except (TypeError, ValidationError): CliConfigManager.purge() Printer.print_warning("Your CLI Configuration was purged!")
def get_log_handler(polyaxon_client=None): polyaxon_client = polyaxon_client or PolyaxonClient() try: return polyaxon_client.versions_v1.get_log_handler() except ApiException as e: if e.status == 403: session_expired() CliConfigManager.reset(last_check=now()) handle_cli_error(e, message="Could not get cli version.") except HTTPError: CliConfigManager.reset(last_check=now()) Printer.print_error("Could not connect to remote server to fetch log handler.")
def check_cli_version(server_versions=None, current_version=None): """Check if the current cli version satisfies the server requirements""" if not CliConfigManager.should_check(): return from distutils.version import LooseVersion # pylint:disable=import-error server_versions = server_versions or get_server_versions() current_version = current_version or get_current_version() cli_config = CliConfigManager.reset( current_version=current_version, server_versions=server_versions.to_dict() ) if LooseVersion(current_version) < LooseVersion(cli_config.min_version): click.echo( """Your version of CLI ({}) is no longer compatible with server.""".format( current_version ) ) if click.confirm( "Do you want to upgrade to " "version {} now?".format(cli_config.latest_version) ): pip_upgrade() sys.exit(0) else: indentation.puts("Your can manually run:") with indentation.indent(4): indentation.puts("pip install -U polyaxon-cli") indentation.puts( "to upgrade to the latest version `{}`".format( cli_config.latest_version ) ) sys.exit(0) elif LooseVersion(current_version) < LooseVersion(cli_config.latest_version): indentation.puts( "New version of CLI ({}) is now available. To upgrade run:".format( cli_config.latest_version ) ) with indentation.indent(4): indentation.puts("pip install -U polyaxon-cli") elif LooseVersion(current_version) > LooseVersion(cli_config.latest_version): indentation.puts( "Your version of CLI ({}) is ahead of the latest version " "supported by Polyaxon Platform ({}) on your cluster, " "and might be incompatible.".format( current_version, cli_config.latest_version ) )
def get_compatibility( key: str, service: str, version: str, is_cli: bool = True, set_config: bool = True, ): if not key: installation = CliConfigManager.get_value("installation") or {} key = installation.get("key") or uuid.uuid4().hex try: version = clean_version_for_compatibility(version) except Exception as e: if set_config: CliConfigManager.reset(last_check=now()) if is_cli: handle_cli_error( e, message="Could parse the version {}.".format(version), ) polyaxon_client = PolyaxonClient(config=ClientConfig(), token=NO_AUTH) try: return polyaxon_client.versions_v1.get_compatibility( uuid=key, service=service, version=version, _request_timeout=2, ) except ApiException as e: if e.status == 403 and is_cli: session_expired() if set_config: CliConfigManager.reset(last_check=now()) if is_cli: handle_cli_error( e, message="Could not reach the compatibility API.", ) except HTTPError: if set_config: CliConfigManager.reset(last_check=now()) if is_cli: Printer.print_error( "Could not connect to remote server to fetch compatibility versions.", ) except Exception as e: if set_config: CliConfigManager.reset(last_check=now()) if is_cli: Printer.print_error( "Unexpected error %s, " "could not connect to remote server to fetch compatibility versions." % e, )
def show(): """Show the current cli, client, and user configs.""" _config = ClientConfigManager.get_config_or_default() Printer.print_header("Client config:") dict_tabulate(_config.to_dict()) _config = CliConfigManager.get_config_or_default() if _config: Printer.print_header("CLI config:") if _config.current_version: click.echo("Version {}".format(_config.current_version)) else: Printer.print_warning("This cli is not configured.") if _config.installation: config_installation = dict_to_tabulate( _config.installation, humanize_values=True, exclude_attrs=["hmac", "auth", "host"], ) dict_tabulate(config_installation) else: Printer.print_warning( "This cli is not connected to a Polyaxon Host.") _config = UserConfigManager.get_config_or_default() if _config: Printer.print_header("User config:") config_user = dict_to_tabulate( _config.to_dict(), humanize_values=True, exclude_attrs=["theme"], ) dict_tabulate(config_user)
def set_versions_config( polyaxon_client=None, set_installation: bool = True, set_compatibility: bool = True, set_handler: bool = False, service=PolyaxonServices.CLI, version=pkg.VERSION, key: str = None, ): polyaxon_client = polyaxon_client or PolyaxonClient() server_installation = None if set_installation: server_installation = get_server_installation( polyaxon_client=polyaxon_client) if not key and server_installation and server_installation.key: key = server_installation.key compatibility = None if set_compatibility: compatibility = get_compatibility(key=key, service=service, version=version) log_handler = None if set_handler: log_handler = get_log_handler(polyaxon_client=polyaxon_client) return CliConfigManager.reset( last_check=now(), current_version=version, installation=server_installation.to_dict() if server_installation else {}, compatibility=compatibility.to_dict() if compatibility else {}, log_handler=log_handler.to_dict() if log_handler else {}, )
def port_forward(port, namespace, deployment_type, release_name): """If you deploy Polyaxon using ClusterIP, you can use this command to access the gateway through `localhost:port`. """ from polyaxon.deploy.operators.kubectl import KubectlOperator if not port and deployment_type in [ DeploymentTypes.MICRO_K8S, DeploymentTypes.MINIKUBE, ]: port = 31833 port = port or 8000 namespace = namespace or "polyaxon" release_name = release_name or "polyaxon" kubectl = KubectlOperator() args = [ "port-forward", "-n", namespace, "svc/{}-polyaxon-gateway".format(release_name), "{}:80".format(port), ] try: _config = ClientConfigManager.get_config_or_default() except Exception as e: handle_cli_error(e, message="Polyaxon load configuration.") Printer.print_header( "You can reset your config by running: polyaxon config purge") sys.exit(1) _config.host = "http://localhost:{}".format(port) ClientConfigManager.set_config(_config) CliConfigManager.purge() AuthConfigManager.purge() UserConfigManager.purge() Printer.print_header("Client configuration is updated!") Printer.print_success("Polyaxon will be available at: {}".format( _config.host)) stdout = kubectl.execute(args=args, is_json=False, stream=settings.CLIENT_CONFIG.debug) click.echo(stdout)
def test_should_check(self): with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 1 assert result is True CliConfigManager.reset( last_check=now(), current_version="0.0.5", installation={"key": "uuid", "version": "1.1.4-rc11", "dist": "foo"}, compatibility={"cli": {"min": "0.0.4", "latest": "1.1.4"}}, ) with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 0 assert result is False CliConfigManager.reset( last_check=now() - timedelta(1000), current_version="0.0.5", installation={"key": "uuid", "version": "1.1.4-rc11", "dist": "foo"}, compatibility={"cli": {"min": "0.0.4", "latest": "1.1.4"}}, ) with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() assert patch_fct.call_count == 1 assert result is True CliConfigManager.reset( last_check=now(), current_version="0.0.2", installation={"key": "uuid", "version": "1.1.4-rc11", "dist": "foo"}, compatibility={"cli": {"min": "0.0.4", "latest": "1.1.4"}}, ) with patch.object(CliConfigManager, "reset") as patch_fct: result = CliConfigManager.should_check() # Although condition for showing a message, do not reset assert patch_fct.call_count == 0 assert result is False
def set_raven_client(): from polyaxon.managers.cli import CliConfigManager cli_config = CliConfigManager.get_config() if cli_config and cli_config.log_handler and cli_config.log_handler.decoded_dsn: import sentry_sdk sentry_sdk.init( dsn=cli_config.log_handler.decoded_dsn, release=cli_config.current_version, environment=cli_config.log_handler.environment, )
def get_compatibility(key: str, service: str, version: str, is_cli=True): if not key: key = uuid.uuid4().hex try: version = version.lstrip("v").replace(".", "-")[:5] except Exception as e: CliConfigManager.reset(last_check=now()) if is_cli: handle_cli_error( e, message="Could parse the version {}.".format(version), ) polyaxon_client = PolyaxonClient(config=ClientConfig(), token=NO_AUTH) try: return polyaxon_client.versions_v1.get_compatibility(uuid=key, service=service, version=version) except ApiException as e: if e.status == 403: session_expired() CliConfigManager.reset(last_check=now()) if is_cli: handle_cli_error( e, message="Could not reach the compatibility API.", ) except HTTPError: CliConfigManager.reset(last_check=now()) if is_cli: Printer.print_error( "Could not connect to remote server to fetch compatibility versions.", )
def set_raven_client() -> bool: from polyaxon import pkg from polyaxon.env_vars.keys import POLYAXON_KEYS_SERVICE from polyaxon.managers.cli import CliConfigManager cli_config = CliConfigManager.get_config() if cli_config and cli_config.log_handler and cli_config.log_handler.decoded_dsn: import sentry_sdk sentry_sdk.init( dsn=cli_config.log_handler.decoded_dsn, release=pkg.VERSION, environment=cli_config.log_handler.environment, server_name=os.environ.get(POLYAXON_KEYS_SERVICE, None), ) return True return False
def test_set_new_count(self): with patch.object(CliConfigManager, "set_config") as patch_fct: CliConfigManager.reset(check_count=4) assert patch_fct.call_count == 1
def test_get_count(self): assert CliConfigManager._get_count() == 1
def tearDown(self): path = CliConfigManager.get_config_filepath(create=False) if not os.path.exists(path): return os.remove(path)
def test_default_props(self): assert CliConfigManager.is_global() is True assert CliConfigManager.IS_POLYAXON_DIR is False assert CliConfigManager.CONFIG_FILE_NAME == ".cli" assert CliConfigManager.CONFIG == CliConfigurationConfig assert CliConfigManager.FREQUENCY == 3
def login(token, username, password): """Login to Polyaxon.""" polyaxon_client = PolyaxonClient() if username and not token: # Use user or email / password login if not password: password = click.prompt( "Please enter your password", type=str, hide_input=True ) password = password.strip() if not password: logger.info( "You entered an empty string. " "Please make sure you enter your password correctly." ) sys.exit(1) try: body = V1Credentials(username=username, password=password) access_auth = polyaxon_client.auth_v1.login(body=body) except (ApiException, HTTPError) as e: AuthConfigManager.purge() CliConfigManager.purge() handle_cli_error(e, message="Could not login.") sys.exit(1) if not access_auth.token: Printer.print_error("Failed to login") return else: if not token: token_url = "{}/profile/token".format( clean_host(polyaxon_client.config.host) ) click.confirm( "Authentication token page will now open in your browser. Continue?", abort=True, default=True, ) click.launch(token_url) logger.info("Please copy and paste the authentication token.") token = click.prompt( "This is an invisible field. Paste token and press ENTER", type=str, hide_input=True, ) if not token: logger.info( "Empty token received. " "Make sure your shell is handling the token appropriately." ) logger.info( "See docs for help: http://polyaxon.com/docs/polyaxon_cli/commands/auth" ) return access_auth = polyaxon_sdk.models.V1Auth(token=token.strip(" ")) # Set user try: AuthConfigManager.purge() polyaxon_client = PolyaxonClient(token=access_auth.token) user = polyaxon_client.users_v1.get_user() except (ApiException, HTTPError) as e: handle_cli_error(e, message="Could not load user info.") sys.exit(1) access_token = AccessTokenConfig(username=user.username, token=access_auth.token) AuthConfigManager.set_config(access_token) polyaxon_client.config.token = access_auth.token Printer.print_success("Login successful") # Reset current cli server_versions = get_server_versions(polyaxon_client=polyaxon_client) current_version = get_current_version() log_handler = get_log_handler(polyaxon_client=polyaxon_client) CliConfigManager.reset( check_count=0, current_version=current_version, server_versions=server_versions.to_dict(), log_handler=log_handler, )
def logout(): """Logout of Polyaxon.""" AuthConfigManager.purge() CliConfigManager.purge() Printer.print_success("You are logged out")
def logout(): """Logout from Polyaxon Cloud or Polyaxon EE.""" AuthConfigManager.purge() UserConfigManager.purge() CliConfigManager.purge() Printer.print_success("You are logged out")
def purge(): """Purge the global config values.""" ClientConfigManager.purge() Printer.print_success("Config was removed.") # Reset cli config CliConfigManager.purge()
def test_set_compatibility(self): with patch.object(CliConfigManager, "set_config") as patch_fct: CliConfigManager.reset(current_version=True) assert patch_fct.call_count == 1
def session_expired(): AuthConfigManager.purge() CliConfigManager.purge() click.echo("Session has expired, please try again.") sys.exit(1)