diff --git a/.env b/.env index 271a34d6..95f516bc 100644 --- a/.env +++ b/.env @@ -1,4 +1,4 @@ -DOCKER_TAG=v4.4.0 +DOCKER_TAG=v4.5.0 REPOSITORY_DOCKER_URL=ghcr.io/nasa-ammos PLANDEV_USERNAME=plandev diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7504eb23..161fe0d4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -16,7 +16,8 @@ env: jobs: unit-test: - runs-on: ubuntu-latest +# run python 3.9 test on ubuntu 24.04 since newer ubuntu dropped support + runs-on: ${{ matrix.python-version == '3.9' && 'ubuntu-24.04' || 'ubuntu-latest' }} strategy: matrix: python-version: ["3.9", "3.10", "3.11", "3.12"] diff --git a/README.md b/README.md index 9c5b761f..b01408f5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ PlanDev-CLI provides a command-line interface and user-extendable Python API for ## Upgrading from Aerie-CLI -Version 2.12.0 renames Aerie-CLI to **PlanDev-CLI** and supports [PlanDev 4.4.0](https://nasa-ammos.github.io/plandev-docs/). This release uses the new package, command, and Python API names exclusively. +Version 2.12.0+ renames Aerie-CLI to **PlanDev-CLI** and supports [PlanDev 4.4.0+](https://nasa-ammos.github.io/plandev-docs/). This release uses the new package, command, and Python API names exclusively. Use `plandev-cli` instead of `aerie-cli`, or `python3 -m plandev_cli` instead of `python3 -m aerie_cli`. @@ -31,6 +31,23 @@ plandev-cli activate Command expansion is unavailable in this CLI release - previous CLI commands used the deprecated EDSL expansion APIs. Template-based expansion is supported by the PlanDev UI; CLI support is planned for a future release. +### Plan file format change + +`plans download` now writes, and `plans upload` now reads, the **PlanTransfer v3** format shared with the PlanDev UI and Gateway. The previous CLI-specific plan format is no longer supported: files with `end_time` or `sim_id` must be converted. +For reference, a [complete JSON schema describing the new format](https://github.com/NASA-AMMOS/plandev-gateway/blob/v4.5.0/src/schemas/plan-transfer-validation-schema.ts) can be found in the PlanDev Gateway repo. + +| Previous format | PlanTransfer v3 | +|---|---| +| `end_time` | `duration`, an interval such as `"48:00:00"`. Python's `end_time` is still available as a computed `ActivityPlan*.end_time` property, but is not in the JSON. | +| _(not exported)_ | `simulation_arguments` | +| `tags` on the plan only, with tag IDs | `tags` on the plan and on each activity, as `{"tag": {"name": ..., "color": ...}}` | +| `sim_id` | _(removed from JSON; `ActivityPlanRead.sim_id` remains in Python)_ | +| _(none)_ | `"version": "3"` | + +Activity `start_offset` values are now written as `HH:MM:SS` rather than Python's `timedelta` text (e.g. `26:00:00`, not `1 day, 2:00:00`). To convert an old file, delete `sim_id`, replace `end_time` with `duration` (`end_time` minus `start_time`), and add `"version": "3"` and `"simulation_arguments": {}`. + +`plans upload` and `PlanDevClient.create_activity_plan()` now go through the Gateway's `/importPlan` and wait for the import to finish before returning the plan ID. `--model-id` is required unless the file embeds a `model`, in which case the plan is imported read-only on a new non-executable model and `--model-id` is ignored. If an import fails, the CLI reports the reason and leaves the failed plan in PlanDev; delete it with `plans delete`. This needs PlanDev 4.5.0 or later. + ## Getting Started diff --git a/pyproject.toml b/pyproject.toml index c6c69656..41274919 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "plandev-cli" -version = "2.12.0" +version = "2.13.0" description = "A CLI application and Python API for interacting with PlanDev." authors = [] license = "MIT" diff --git a/src/plandev_cli/commands/plans.py b/src/plandev_cli/commands/plans.py index 01d117a6..5234acee 100644 --- a/src/plandev_cli/commands/plans.py +++ b/src/plandev_cli/commands/plans.py @@ -25,7 +25,7 @@ def download( ), output: str = typer.Option(..., "--output", "-o", help="The output file destination", prompt=True) ): - """Download a plan and save it locally as a JSON file.""" + """Download a plan and save it locally as a PlanTransfer v3 JSON file.""" plan = CommandContext.get_client().get_activity_plan_by_id(id, full_args) with open(output, "w") as out_file: out_file.write(plan.to_json(indent=2)) @@ -163,22 +163,27 @@ def download_resources( @plans_app.command() def upload( input: str = typer.Option( - ..., "--input", "-i", help="The input file from which to create an PlanDev plan", prompt=True + ..., "--input", "-i", help="The PlanTransfer JSON file from which to create a PlanDev plan", prompt=True ), - model_id: int = typer.Option( - ..., "--model-id", "-m", help="The mission model ID to associate with the plan", prompt=True + model_id: Union[int, None] = typer.Option( + None, "--model-id", "-m", + help="The mission model ID to associate with the plan. Required unless the file embeds its model, in which case it is ignored." ), time_tag: bool = typer.Option(False, help="Append time tag to plan name"), ): - """Create a plan from an input JSON file.""" + """Create a plan from a PlanTransfer JSON file, as exported by `plans download` or the PlanDev UI. + + Waits for the import to finish. A file that embeds a `model` is imported read-only onto a new non-executable model.""" client = CommandContext.get_client() with open(input) as in_file: - contents = in_file.read() - plan_to_create = ActivityPlanCreate.from_json(contents) + plan = json.load(in_file) + if "model" not in plan and model_id is None: + model_id = typer.prompt("Model ID", type=int) + name = plan.get("name") if time_tag: - plan_to_create.name += arrow.utcnow().format("YYYY-MM-DDTHH-mm-ss") - plan_id = client.create_activity_plan(model_id, plan_to_create) + name = (name or "") + arrow.utcnow().format("YYYY-MM-DDTHH-mm-ss") + plan_id = client.import_plan(plan, model_id, name) typer.echo(f"Created plan ID: {plan_id}") diff --git a/src/plandev_cli/plandev_client.py b/src/plandev_cli/plandev_client.py index d9f024c0..23bad4b1 100644 --- a/src/plandev_cli/plandev_client.py +++ b/src/plandev_cli/plandev_client.py @@ -1,12 +1,16 @@ +import itertools +import json import sys import time from pathlib import Path from typing import Dict from typing import List +from typing import Optional from typing import Union from copy import deepcopy import arrow +from attrs import evolve from .schemas.api import ApiActivityPlanRead from .schemas.api import ApiEffectiveActivityArguments @@ -64,13 +68,18 @@ def get_activity_plan_by_id(self, plan_id: int, full_args: str = None) -> Activi name start_time duration - simulations{ + simulations { id + arguments + template: simulation_template { + arguments + } } tags { tag { id name + color } } activity_directives(order_by: { start_offset: asc }) { @@ -82,6 +91,13 @@ def get_activity_plan_by_id(self, plan_id: int, full_args: str = None) -> Activi metadata anchor_id anchored_to_start + tags { + tag { + id + name + color + } + } } } } @@ -100,13 +116,18 @@ def list_all_activity_plans(self) -> List[ActivityPlanRead]: name start_time duration - simulations{ + simulations { id + arguments + template: simulation_template { + arguments + } } tags { tag { id name + color } } } @@ -164,7 +185,7 @@ def get_plan_id_by_sim_id(self, simulation_dataset_id: int) -> int: simulation_dataset_id=simulation_dataset_id ) return resp['simulation']['plan']['id'] - + def get_tag_id_by_name(self, tag_name: str): get_tags_by_name_query = """ query GetTagByName($name: String) { @@ -184,16 +205,16 @@ def get_tag_id_by_name(self, tag_name: str): """ resp = self.plandev_host.post_to_graphql( - get_tags_by_name_query, + get_tags_by_name_query, name=tag_name ) #if a tag with the specified name exists then returns the ID, else creates a new tag with this name - if len(resp) > 0: + if len(resp) > 0: return resp[0]["id"] - else: + else: new_tag_resp = self.plandev_host.post_to_graphql( - create_new_tag, + create_new_tag, name=tag_name ) @@ -209,11 +230,11 @@ def add_plan_tag(self, plan_id: int, tag_name: str): } } """ - + #add tag to plan resp = self.plandev_host.post_to_graphql( - add_tag_to_plan, - plan_id=plan_id, + add_tag_to_plan, + plan_id=plan_id, tag_id=self.get_tag_id_by_name(tag_name) ) @@ -222,80 +243,77 @@ def add_plan_tag(self, plan_id: int, tag_name: str): def create_activity_plan( self, model_id: int, plan_to_create: ActivityPlanCreate ) -> int: + """Create a plan from an `ActivityPlanCreate` via the gateway's `/importPlan` - api_plan_create = plan_to_create.to_api_create(model_id) - create_plan_mutation = """ - mutation CreatePlan($plan: plan_insert_input!) { - createPlan: insert_plan_one(object: $plan) { - id - revision - } - } - """ - plan_resp = self.plandev_host.post_to_graphql( - create_plan_mutation, - plan=api_plan_create.to_dict(), + Waits for the import to complete. Returns the new plan ID.""" + + # Plan transfer files need a unique ID on every directive. Anchors refer to them. + used_ids = {a.id for a in plan_to_create.activities if a.id is not None} + free_ids = (i for i in itertools.count(1) if i not in used_ids) + plan_to_create = evolve( + plan_to_create, + activities=[a if a.id is not None else evolve(a, id=next(free_ids)) for a in plan_to_create.activities], ) - plan_id = plan_resp["id"] - plan_revision = plan_resp["revision"] - - #add plan tags if exists from plan_to_create - for tag in plan_to_create.tags: - self.add_plan_tag(plan_id, tag["tag"]["name"]) - - # This loop exists to make sure all anchor IDs are updated as necessary - - # Deep copy activities so we can augment and pop from the list - activities_to_upload = deepcopy(plan_to_create.activities) - - # Map of old to new directive IDs - directive_id_mapping = {} - - # Boolean catches errors to avoid an infinite loop - running = True - while len(activities_to_upload): - running = False - - for act in activities_to_upload: - # If activity is anchored and the anchor isn't known yet, pass - # If activity is anchored and the anchor is known, add it - if act.anchor_id and act.anchor_id not in directive_id_mapping.keys(): - continue - else: - if act.anchor_id: - act.anchor_id = directive_id_mapping[act.anchor_id] - directive_id_mapping[act.id] = self.create_activity(act, plan_id) - activities_to_upload.remove(act) - running = True + return self.import_plan(plan_to_create.to_dict(), model_id) - if not running: - raise RuntimeError( - f"Failed to anchor activities: {', '.join([act.name for act in activities_to_upload])}" - ) + def import_plan( + self, + plan: Dict, + model_id: Optional[int] = None, + name: Optional[str] = None, + poll_period: float = 1, + timeout: float = 900, + ) -> int: + """Import a PlanTransfer (v3, or v2) plan via the gateway's `/importPlan` and wait for it to finish - simulation_start_time = plan_to_create.start_time.isoformat() - simulation_end_time = plan_to_create.end_time.isoformat() - update_simulation_mutation = """ - mutation updateSimulationBounds($plan_id: Int!, $simulation_start_time: timestamptz!, $simulation_end_time: timestamptz!) { - update_simulation( - where: {plan_id: {_eq: $plan_id}}, - _set: { - simulation_start_time: $simulation_start_time, - simulation_end_time: $simulation_end_time - } - ){ - affected_rows + Args: + plan (Dict): Parsed PlanTransfer JSON + model_id (int, optional): Mission model for the plan. Required unless the plan embeds a `model`, + in which case it is ignored. + name (str, optional): Plan name. Defaults to the name in the plan. + poll_period (float): Seconds between checks of the import's status + timeout (float): Seconds to wait for the import to finish + + Raises: + RuntimeError: The import was rejected, failed, or did not finish in time. A failed import leaves its + plan in PlanDev so it can be inspected or deleted. + + Returns: + int: ID of the imported plan + """ + if "model" not in plan and model_id is None: + raise ValueError("model_id is required unless the plan embeds its model") + + # The gateway takes plan tags as IDs, and only from the form, not the file + tag_ids = [self.get_tag_id_by_name(t["tag"]["name"]) for t in plan.get("tags") or []] + form = {"name": name or plan.get("name"), "tags": json.dumps(tag_ids)} + if "model" not in plan: + # For a plan on an existing model the gateway reads the plan bounds from the form, not the file + form.update(model_id=model_id, start_time=plan.get("start_time"), duration=plan.get("duration")) + + resp = self.plandev_host.post_to_gateway_import_plan(form, json.dumps(plan).encode()) + plan_id = resp["plan_id"] + + query = """ + query GetPlanImportRequest($id: Int!) { + plan_import_request_by_pk(id: $id) { + status + reason } } """ - _ = self.plandev_host.post_to_graphql( - update_simulation_mutation, - plan_id=plan_id, - simulation_start_time=simulation_start_time, - simulation_end_time=simulation_end_time - ) - - return plan_id + deadline = time.monotonic() + timeout + while True: + request = self.plandev_host.post_to_graphql(query, id=resp["plan_import_request_id"]) + if request["status"] == "complete": + return plan_id + if request["status"] == "failed": + raise RuntimeError( + f"Import of plan {plan_id} failed (the plan was left in place): {json.dumps(request['reason'])}" + ) + if time.monotonic() > deadline: + raise RuntimeError(f"Import of plan {plan_id} did not finish within {timeout} seconds") + time.sleep(poll_period) def create_activity(self, activity_to_create: Activity, plan_id: int) -> int: api_activity_create = activity_to_create.to_api_create(plan_id) @@ -360,8 +378,8 @@ def get_all_activity_presets(self, m_id:int) -> List: def upload_activity_presets(self, upload_obj): upload_activity_presets_query = """ mutation upload_presets($object: [activity_presets_insert_input!]!) { - insert_activity_presets(objects: $object, - on_conflict: {constraint: activity_presets_model_id_associated_activity_type_name_key, + insert_activity_presets(objects: $object, + on_conflict: {constraint: activity_presets_model_id_associated_activity_type_name_key, update_columns: arguments} ) { returning { @@ -375,7 +393,7 @@ def upload_activity_presets(self, upload_obj): }""" resp = self.plandev_host.post_to_graphql( - upload_activity_presets_query, + upload_activity_presets_query, object = upload_obj ) @@ -418,11 +436,11 @@ def get_resource_samples(self, simulation_dataset_id: int, state_names: List=Non """Pull resource samples from a simulation dataset, optionally filtering for specific states Each resource's values are returned in a list of points {x: