59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
import base64
|
|
from importlib.metadata import PackageNotFoundError
|
|
from os.path import dirname, realpath
|
|
from sysconfig import get_python_version
|
|
from importlib import metadata
|
|
import tomllib
|
|
|
|
import click
|
|
|
|
import requests
|
|
from urllib.parse import quote
|
|
|
|
from pillar_tool.schemas import HostCreateParams, HostgroupParams
|
|
from pillar_tool.util import config, load_config, Config
|
|
from pillar_tool.util.validation import split_and_validate_path, validate_fqdn
|
|
|
|
cfg: Config | None = None
|
|
_base_url: str | None = None
|
|
_auth_header: dict[str, str] | None = None
|
|
|
|
def auth_header():
|
|
global _auth_header
|
|
return _auth_header
|
|
|
|
def base_url():
|
|
global _base_url
|
|
return _base_url
|
|
|
|
def print_version_and_exit(ctx, _1, execute):
|
|
if not execute: return False
|
|
version_string = "version_undetectable"
|
|
try:
|
|
version_string = metadata.version('pillar_tool')
|
|
except PackageNotFoundError:
|
|
with (open(f"{realpath(dirname(__file__)) + '/../../..'}/pyproject.toml", "r") as f):
|
|
data = tomllib.loads(f.read())
|
|
version_string = data['project']['version']
|
|
print(f"pillar tool v{version_string}")
|
|
ctx.exit()
|
|
|
|
@click.group("command")
|
|
@click.option("--version", '-v', is_flag=True, is_eager=True, callback=print_version_and_exit)
|
|
def main(**kwargs) -> None:
|
|
global cfg, _base_url, _auth_header
|
|
|
|
# load the configuration and store it
|
|
load_config()
|
|
cfg = config()
|
|
_base_url = f"{cfg.ptcli.scheme}://{cfg.ptcli.host}:{cfg.ptcli.port}"
|
|
_auth_header = { 'Authorization': f"Basic {base64.b64encode(f"{cfg.ptcli.user}:{cfg.ptcli.password}".encode('utf-8')).decode('ascii')}" }
|
|
|
|
# health check of the api
|
|
try:
|
|
response = requests.get(f"{_base_url}/health")
|
|
response.raise_for_status()
|
|
except requests.exceptions.HTTPError as e:
|
|
raise click.ClickException(f"API seems to be unhealthy:\n{e}")
|
|
except requests.exceptions.ConnectionError as e:
|
|
raise click.ClickException("Unable to connect to PillarTool API") |