Unverified Commit f8c67ccc authored by Jakob Görgen's avatar Jakob Görgen
Browse files

added simple cli utility to create and receive namespaces as user

parent 67698ae0
...@@ -23,21 +23,69 @@ ...@@ -23,21 +23,69 @@
from pathlib import Path from pathlib import Path
from typer import Typer, Option from typer import Typer, Option
from typing_extensions import Annotated from typing_extensions import Annotated
from rich.table import Table
from rich.console import Console
from ..state import state from ..state import state
from ..utils import async_cli from ..utils import async_cli
app = Typer( app = Typer(help="Managing SimBricks namespaces.")
help="Managing SimBricks namespaces."
)
def print_namespace_table(namespaces) -> None:
table = Table()
table.add_column("Id")
table.add_column("name")
table.add_column("parent")
for ns in namespaces:
table.add_row(str(ns["id"]), str(ns["name"]), str(ns["parent_id"]))
console = Console()
console.print(table)
@app.command() @app.command()
@async_cli() @async_cli()
async def ls(): async def ls():
"""List available namespaces.""" """List available namespaces."""
print(f"Listing Namespaces in {state.namespace}:") client = state.ns_client()
namespaces = await client.get_all()
print_namespace_table(namespaces)
@app.command()
@async_cli()
async def ls_id(ident: int):
"""List namespace with given id ident."""
client = state.ns_client()
namespace = await client.get_ns(ident)
print_namespace_table([namespace])
@app.command()
@async_cli()
async def ls_cur():
"""List current namespace."""
client = state.ns_client()
namespace = await client.get_cur()
print_namespace_table([namespace])
@app.command() @app.command()
@async_cli() @async_cli()
async def create(name: str): async def create(name: str):
"""Create a new namespace.""" """Create a new namespace."""
print(f"Creating namespace {name} in {state.namespace}")
\ No newline at end of file client = state.ns_client()
# create namespace relative to current namespace
cur_ns = await client.get_cur()
cur_ns_id = int(cur_ns["id"])
# create the actual namespace
namespace = await client.create(parent_id=cur_ns_id, name=name)
ns_id = namespace["id"]
print(f"Creating namespace {name} in {state.namespace}. New namespace: {ns_id}")
...@@ -61,9 +61,7 @@ class BaseClient: ...@@ -61,9 +61,7 @@ class BaseClient:
url = f"{self._base_url}{url}" url = f"{self._base_url}{url}"
async with self.session() as session: async with self.session() as session:
async with session.post( async with session.post(url=url, data=data, **kwargs) as resp: # TODO: handel connection error
url=url, data=data, **kwargs
) as resp: # TODO: handel connection error
print(await resp.text()) print(await resp.text())
resp.raise_for_status() # TODO: handel gracefully resp.raise_for_status() # TODO: handel gracefully
yield resp yield resp
...@@ -76,9 +74,7 @@ class BaseClient: ...@@ -76,9 +74,7 @@ class BaseClient:
url = f"{self._base_url}{url}" url = f"{self._base_url}{url}"
async with self.session() as session: async with self.session() as session:
async with session.put( async with session.put(url=url, data=data, **kwargs) as resp: # TODO: handel connection error
url=url, data=data, **kwargs
) as resp: # TODO: handel connection error
print(await resp.text()) print(await resp.text())
resp.raise_for_status() # TODO: handel gracefully resp.raise_for_status() # TODO: handel gracefully
yield resp yield resp
...@@ -90,9 +86,8 @@ class BaseClient: ...@@ -90,9 +86,8 @@ class BaseClient:
url = f"{self._base_url}{url}" url = f"{self._base_url}{url}"
async with self.session() as session: async with self.session() as session:
async with session.get( async with session.get(url=url, data=data, **kwargs) as resp: # TODO: handel connection error
url=url, data=data, **kwargs print(await resp.text())
) as resp: # TODO: handel connection error
resp.raise_for_status() # TODO: handel gracefully resp.raise_for_status() # TODO: handel gracefully
yield resp yield resp
...@@ -114,18 +109,14 @@ class NSClient: ...@@ -114,18 +109,14 @@ class NSClient:
async def post( async def post(
self, url: str, data: typing.Any = None, **kwargs: typing.Any self, url: str, data: typing.Any = None, **kwargs: typing.Any
) -> typing.AsyncIterator[aiohttp.ClientResponse]: ) -> typing.AsyncIterator[aiohttp.ClientResponse]:
async with self._base_client.post( async with self._base_client.post(url=self._build_ns_prefix(url=url), data=data, **kwargs) as resp:
url=self._build_ns_prefix(url=url), data=data, **kwargs
) as resp:
yield resp yield resp
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
async def put( async def put(
self, url: str, data: typing.Any = None, **kwargs: typing.Any self, url: str, data: typing.Any = None, **kwargs: typing.Any
) -> typing.AsyncIterator[aiohttp.ClientResponse]: ) -> typing.AsyncIterator[aiohttp.ClientResponse]:
async with self._base_client.put( async with self._base_client.put(url=self._build_ns_prefix(url=url), data=data, **kwargs) as resp:
url=self._build_ns_prefix(url=url), data=data, **kwargs
) as resp:
yield resp yield resp
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
...@@ -133,15 +124,33 @@ class NSClient: ...@@ -133,15 +124,33 @@ class NSClient:
self, url: str, data: typing.Any = None, **kwargs: typing.Any self, url: str, data: typing.Any = None, **kwargs: typing.Any
) -> typing.AsyncIterator[aiohttp.ClientResponse]: ) -> typing.AsyncIterator[aiohttp.ClientResponse]:
async with self._base_client.get( async with self._base_client.get(url=self._build_ns_prefix(url=url), data=data, **kwargs) as resp:
url=self._build_ns_prefix(url=url), data=data, **kwargs
) as resp:
yield resp yield resp
async def info(self): async def info(self):
async with self.get(url="/info") as resp: async with self.get(url="/info") as resp:
return await resp.json() return await resp.json()
async def create(self, parent_id: int, name: str):
namespace_json = {"parent_id": parent_id, "name": name}
async with self.post(url="/", json=namespace_json) as resp:
return await resp.json()
# retrieve namespace ns_id, useful for retrieving a child the current namespace
async def get_ns(self, ns_id: int):
async with self.get(url=f"/one/{ns_id}") as resp:
return await resp.json()
# retrieve the current namespace
async def get_cur(self):
async with self.get(url="/") as resp:
return await resp.json()
# recursively retrieve all namespaces beginning with the current including all children
async def get_all(self):
async with self.get(url="/all") as resp:
return await resp.json()
class SimBricksClient: class SimBricksClient:
...@@ -165,13 +174,8 @@ class SimBricksClient: ...@@ -165,13 +174,8 @@ class SimBricksClient:
async with self._ns_client.get(url=f"/systems/{system_id}") as resp: async with self._ns_client.get(url=f"/systems/{system_id}") as resp:
return await resp.json() return await resp.json()
async def create_simulation( async def create_simulation(self, system_db_id: int, simulation: simulation.Simulation) -> simulation.Simulation:
self, system_db_id: int, simulation: simulation.Simulation json_obj = {"system_id": system_db_id, "sb_json": simulation.toJSON()}
) -> simulation.Simulation:
json_obj = {
"system_id": system_db_id,
"sb_json": simulation.toJSON()
}
print(json_obj) print(json_obj)
async with self._ns_client.post(url="/simulations", json=json_obj) as resp: async with self._ns_client.post(url="/simulations", json=json_obj) as resp:
return await resp.json() return await resp.json()
...@@ -184,26 +188,17 @@ class SimBricksClient: ...@@ -184,26 +188,17 @@ class SimBricksClient:
async with self._ns_client.get(url="/simulations") as resp: async with self._ns_client.get(url="/simulations") as resp:
return await resp.json() return await resp.json()
async def create_instantiation( async def create_instantiation(self, sim_db_id: int, instantiation: simulation.Simulation) -> simulation.Simulation:
self, sim_db_id: int, instantiation: simulation.Simulation json_obj = {"simulation_id": sim_db_id, "sb_json": {}} # FIXME
) -> simulation.Simulation:
json_obj = {
"simulation_id": sim_db_id,
"sb_json": {} # FIXME
}
print(json_obj) print(json_obj)
async with self._ns_client.post(url="/instantiations", json=json_obj) as resp: async with self._ns_client.post(url="/instantiations", json=json_obj) as resp:
return await resp.json() return await resp.json()
async def get_instantiation( async def get_instantiation(self, instantiation_id: int) -> instantiation.Instantiation:
self, instantiation_id: int
) -> instantiation.Instantiation:
async with self._ns_client.get(url=f"/instantiations/{instantiation_id}") as resp: async with self._ns_client.get(url=f"/instantiations/{instantiation_id}") as resp:
return await resp.json() return await resp.json()
async def create_run( async def create_run(self, inst_db_id: int) -> dict:
self, inst_db_id: int
) -> dict:
json_obj = { json_obj = {
"instantiation_id": inst_db_id, "instantiation_id": inst_db_id,
"state": "pending", "state": "pending",
...@@ -221,7 +216,6 @@ class SimBricksClient: ...@@ -221,7 +216,6 @@ class SimBricksClient:
return await resp.json() return await resp.json()
class RunnerClient: class RunnerClient:
def __init__(self, ns_client, id: int) -> None: def __init__(self, ns_client, id: int) -> None:
...@@ -235,18 +229,14 @@ class RunnerClient: ...@@ -235,18 +229,14 @@ class RunnerClient:
async def post( async def post(
self, url: str, data: typing.Any = None, **kwargs: typing.Any self, url: str, data: typing.Any = None, **kwargs: typing.Any
) -> typing.AsyncIterator[aiohttp.ClientResponse]: ) -> typing.AsyncIterator[aiohttp.ClientResponse]:
async with self._ns_client.post( async with self._ns_client.post(url=self._build_prefix(url=url), data=data, **kwargs) as resp:
url=self._build_prefix(url=url), data=data, **kwargs
) as resp:
yield resp yield resp
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
async def put( async def put(
self, url: str, data: typing.Any = None, **kwargs: typing.Any self, url: str, data: typing.Any = None, **kwargs: typing.Any
) -> typing.AsyncIterator[aiohttp.ClientResponse]: ) -> typing.AsyncIterator[aiohttp.ClientResponse]:
async with self._ns_client.put( async with self._ns_client.put(url=self._build_prefix(url=url), data=data, **kwargs) as resp:
url=self._build_prefix(url=url), data=data, **kwargs
) as resp:
yield resp yield resp
@contextlib.asynccontextmanager @contextlib.asynccontextmanager
...@@ -254,15 +244,10 @@ class RunnerClient: ...@@ -254,15 +244,10 @@ class RunnerClient:
self, url: str, data: typing.Any = None, **kwargs: typing.Any self, url: str, data: typing.Any = None, **kwargs: typing.Any
) -> typing.AsyncIterator[aiohttp.ClientResponse]: ) -> typing.AsyncIterator[aiohttp.ClientResponse]:
async with self._ns_client.get( async with self._ns_client.get(url=self._build_prefix(url=url), data=data, **kwargs) as resp:
url=self._build_prefix(url=url), data=data, **kwargs
) as resp:
yield resp yield resp
async def next_run(self) -> dict | None:
async def next_run(
self
) -> dict | None:
async with self.get(f"/next_run") as resp: async with self.get(f"/next_run") as resp:
if resp.status == 200: if resp.status == 200:
return await resp.json() return await resp.json()
...@@ -271,7 +256,6 @@ class RunnerClient: ...@@ -271,7 +256,6 @@ class RunnerClient:
else: else:
resp.raise_for_status() resp.raise_for_status()
async def update_run( async def update_run(
self, self,
run_id: int, run_id: int,
...@@ -279,10 +263,10 @@ class RunnerClient: ...@@ -279,10 +263,10 @@ class RunnerClient:
output: str, output: str,
) -> None: ) -> None:
obj = { obj = {
'state': state, "state": state,
'output': output, "output": output,
'id': run_id, "id": run_id,
'instantiation_id': 42, "instantiation_id": 42,
} }
async with self.put(url=f"/update_run/{run_id}", json=obj) as resp: async with self.put(url=f"/update_run/{run_id}", json=obj) as resp:
ret = await resp.json() ret = await resp.json()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment