Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
Kamilcuk committed Oct 16, 2023
1 parent 625ffd0 commit f8fc08b
Show file tree
Hide file tree
Showing 17 changed files with 1,500 additions and 756 deletions.
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ nomad-watch = "nomad_tools:nomad_watch.cli"
nomad-cp = "nomad_tools:nomad_cp.cli"
nomad-vardir = "nomad_tools:nomad_vardir.cli"
nomad-gitlab-runner = "nomad_tools:nomad_gitlab_runner.main"
nomad-port = "nomad_tools:nomad_port.cli"
#nomadt = "nomad_tools:nomadt.cli"

[project.optional-dependencies]
test = [
Expand All @@ -46,6 +48,9 @@ log_cli_date_format = "%H:%M:%S"
testpaths = [
"tests/unit",
]
filterwarnings = [
"ignore::DeprecationWarning",
]

[tool.pyright]
reportUnnecessaryComparison = "error"
39 changes: 30 additions & 9 deletions src/nomad_tools/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import click
import pkg_resources

from .nomadlib import Nomadlib
from . import nomadlib

mynomad = Nomadlib()
mynomad = nomadlib.Nomadlib()


def nomad_find_namespace(prefix: str):
Expand Down Expand Up @@ -90,14 +90,35 @@ def _print_version(ctx, param, value):
ctx.exit()


def version_option():
return click.option(
"--version",
is_flag=True,
callback=_print_version,
expose_value=False,
is_eager=True,
help="Print program version then exit.",
)


def common_options():
return composed(
click.help_option("-h", "--help"),
click.option(
"--version",
is_flag=True,
callback=_print_version,
expose_value=False,
is_eager=True,
),
version_option(),
)


class ArgumentAlloc(nomadlib.Alloc):
def __init__(self, allocid: str):
allocs = mynomad.get(f"allocations", params={"prefix": allocid})
assert len(allocs) > 0, f"Allocation with id {allocid} not found"
assert len(allocs) < 2, f"Multiple allocations found starting with id {allocid}"
super().__init__(allocs[0])


def argument_alloc():
return click.argument(
"allocid",
shell_complete=completor(lambda: (x["ID"] for x in mynomad.get("allocations"))),
type=ArgumentAlloc,
)
92 changes: 92 additions & 0 deletions src/nomad_tools/nomad_port.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later

import argparse
import logging
from typing import List

import click

from . import nomadlib
from .common import argument_alloc, common_options, complete_job, mynomad

log = logging.getLogger(__name__)


def gen_alloc(alloc: nomadlib.Alloc) -> List[str]:
out = []
log.debug(f"Parsing {alloc.ID}")
for i in alloc["AllocatedResources"]["Shared"]["Ports"]:
params = dict(
**{
k: v
for k, v in alloc.items()
if isinstance(v, str) and isinstance(k, str)
},
label=i["Label"],
host=i["HostIP"],
port=i["Value"],
)
log.debug(f"Found")
out += [args.format % params]
return out


def output(out: List[str]):
if out:
print(*out, sep=args.separator)


@click.group()
@click.option(
"-f", "--format", default="%(Name)s %(label)s %(host)s:%(port)s", show_default=True
)
@click.option("-s", "--separator", default="\n", show_default=True)
@click.option("-v", "--verbose", count=True, help="Be more verbose.")
@common_options()
def cli(**kwargs):
global args
args = argparse.Namespace(**kwargs)
logging.basicConfig(
level=(
logging.DEBUG
if args.verbose > 0
else logging.INFO
if args.verbose == 0
else logging.WARN
if args.verbose == 1
else logging.ERROR
),
)


@cli.command("alloc", help="Show ports of a single allocation.")
@argument_alloc()
def mode_alloc(alloc: nomadlib.Alloc):
out = gen_alloc(alloc)
output(out)


@cli.command("job", help="Show ports of all running or pending job allocations.")
@click.option(
"--all",
help="Show all allocation ports, not only running or pending.",
is_flag=True,
)
@click.argument(
"jobid",
shell_complete=complete_job(),
)
def mode_job(jobid, all):
jobid = mynomad.find_job(jobid)
out = []
for alloc in mynomad.get(f"job/{jobid}/allocations"):
if all or nomadlib.Alloc(alloc).is_pending_or_running():
# job/*/allocations does not have AllocatedResources information.
alloc = nomadlib.Alloc(mynomad.get(f"allocation/{alloc['ID']}"))
out += gen_alloc(alloc)
output(out)


if __name__ == "__main__":
cli()
Loading

0 comments on commit f8fc08b

Please sign in to comment.