Buckets:

download
raw
14.1 kB
"""The closing summary card for the OSPREY lifecycle verbs.
``init``, ``build``, ``up -d``, ``restart -d`` and ``down`` all end the same
way: one short card saying which deployment this was, what state it is in now,
where it answers, where the command output went, and which command comes next.
One renderer for all five, so the five cannot describe the same deployment in
five shapes.
It prints after the last phase has closed, through the CLI's renderer
(:mod:`osprey.cli.output`) rather than through the phase reporter. The card is
the verb's own output, not decoration on its progress: it says what the run
left behind, so it is echo-class and prints under every reporter -- including
the one the global ``--verbose`` installs, where the phase record itself is
swallowed. Attached (non-``-d``) starts print no card at all: ``compose up``
replaces this process and the terminal belongs to the log stream.
The rows are a key/value block, which is what :func:`osprey.cli.output.section`
renders, so the card is laid out by the same code as every other block of facts
the CLI prints. Only the wording stays here: which states exist and what to run
next are this module's business, not the renderer's.
"""
from __future__ import annotations
from pathlib import Path
from osprey.deployment.subprocess_capture import SPOOL_DIR
from osprey.utils.logger import get_logger
from osprey.utils.workspace import BUILD_DIR_NAME
from . import output
from .phase_reporter import NullReporter, current_reporter
logger = get_logger("cli.summary_card")
#: What to do next, per state. Only ``running`` is reachable-anywhere, so it is
#: the only state whose card carries endpoints.
_NEXT_STEPS = {
"created": "osprey build · osprey up -d",
"built": "osprey up -d · osprey status",
"running": "osprey status · osprey logs · osprey down",
"stopped": "osprey up -d · osprey status",
}
#: Where a rendered project keeps the demo scenarios ``osprey sim apply`` reads.
#: Relative to the build directory, which is the tree the build wrote, not the
#: repo the operator is standing in.
_SCENARIOS_DIR = Path("data") / "simulation" / "scenarios"
#: The command that seeds the demo logbook from those scenarios. Appended to the
#: ``built`` card's next step, so the one next-step surface carries it instead of
#: a line of its own.
_SEED_DEMO_LOGBOOK = "osprey sim apply nominal"
def _next_step(root: Path, state: str) -> str:
"""What to run next for a deployment in ``state``, rooted at ``root``.
Fixed per state, with one exception the map cannot hold: a build that
rendered demo scenarios can seed its logbook from them, and one that did not
must not be told to run a command with nothing to apply. So the answer is
read off the rendered tree rather than declared.
:param root: The deployment repo. The build it rendered is one directory in.
:param state: One of ``created``, ``built``, ``running``, ``stopped``
"""
step = _NEXT_STEPS.get(state, "osprey status")
if state == "built" and (root / BUILD_DIR_NAME / _SCENARIOS_DIR).is_dir():
return f"{step} · {_SEED_DEMO_LOGBOOK}"
return step
def owns_summary_card() -> bool:
"""True when the calling verb is the outermost one, so the card is its own.
Asked BEFORE :func:`~osprey.cli.main.lifecycle_reporter`, and by the same
rule that decides who owns the reporter: the verb that still finds the quiet
default installed is the one about to install a reporter. A chained verb
(``init --up`` invokes ``build`` and ``up``) finds the outer verb's reporter
and leaves the card to it, so a chain prints one card at its end rather than
one per verb.
"""
active = current_reporter()
return isinstance(active, NullReporter) and not active.verbose
def _card_parts(repo_root: Path | str, state: str) -> tuple[str, list[tuple[str, str]]]:
"""The card's heading and its rows, before either is laid out.
The one derivation of what the card says. Both the printer and the
plain-text renderer start here, so there is no way for the card an operator
reads to differ from the card a test reads.
:param repo_root: The deployment repo -- its directory name IS the
deployment's name, the same one the compose project carries
:param state: One of ``created``, ``built``, ``running``, ``stopped``
"""
from osprey.deployment.deploy_summary import (
as_built_dangerously_allows_bash,
as_built_endpoint_entries,
)
from osprey.deployment.web_terminals.artifacts import DANGEROUSLY_ALLOW_BASH_KEY
root = Path(repo_root)
rows: list[tuple[str, str]] = []
if state == "running":
# URLs only: a card is the "what now" surface, and the addresses someone
# can act on are the ones they can open. The full list, bare addresses
# and the not-configured facts included, is `osprey status`.
#
# The tier each row carries there is dropped rather than printed: this
# is a handful of rows next to "command output" and "next", and section
# headings among them would turn a call to action into a table. What the
# card does inherit is the ORDER — the endpoint list is in block order,
# so the card leads with the gateway a reader is looking for instead of
# with whichever service name sorts first.
rows += [
(service, address)
for _tier, service, address in as_built_endpoint_entries(root)
if address.startswith("http://")
]
if as_built_dangerously_allows_bash(root):
# Above the housekeeping rows, on every state: a waiver of a safety
# refusal is the one fact on this card that must not be skimmed past.
rows.append(
(
DANGEROUSLY_ALLOW_BASH_KEY,
"ON -- a persona may run Bash while holding a launch token",
)
)
rows.append(("command output", str(root / SPOOL_DIR)))
rows.append(("next", _next_step(root, state)))
return f"{root.name} — {state}", rows
def format_summary_card(repo_root: Path | str, state: str) -> list[str]:
"""Render the card for ``repo_root`` in ``state`` as plain lines.
The same lines :func:`print_summary_card` puts on screen, with no styling
on them -- for a caller that wants the card as text rather than as output.
The row shape is :func:`osprey.cli.output.section`'s, which is what makes
the two agree; ``test_summary_card.py`` pins them against each other so
they cannot drift apart.
:param repo_root: The deployment repo -- its directory name IS the
deployment's name, the same one the compose project carries
:param state: One of ``created``, ``built``, ``running``, ``stopped``
"""
title, rows = _card_parts(repo_root, state)
width = max(len(label) for label, _ in rows)
return [title] + [f" {label.ljust(width)} {value}" for label, value in rows]
def print_summary_card(repo_root: Path | str, state: str) -> None:
"""Print the card through the CLI renderer; advisory, never raises.
A verb that has done its work has succeeded, and a card that cannot be
rendered -- an unreadable render, a compose file that moved -- must not turn
that into a failure.
"""
# Before the card, because the run's last three blocks answer three
# questions in the order a person asks them: what did this write, where does
# it answer, what do I do now. The ledger is the receipt for the run that
# just finished, so it belongs with that run rather than after the card; the
# card and the line under it are the "what now" surface, and they close the
# run together.
output.flush_ledger()
try:
title, rows = _card_parts(repo_root, state)
except Exception as exc:
logger.debug("Summary card skipped: %s", exc)
return
output.report("")
output.section(title, rows)
print_call_to_action(repo_root, state)
def print_call_to_action(repo_root: Path | str, state: str) -> None:
"""Print the one thing to do next, under the card; advisory, never raises.
A card is an inventory. It says a deployment is running and lists six
addresses, and every one of those rows is equally prominent, so the reader
has to work out which of them is the front door. This line says it: open the
landing page, and here is what to sign in with.
Printed for a ``running`` deployment that HAS a landing page, and skipped
otherwise. A backend-only project has no front door to send anyone to, and
the card's ``next`` row is already the right answer for it.
Said only when it is true. ``compose up -d`` returns once every dependency
edge is satisfied, and a container nothing depends on can fail its own
healthcheck after that with the verb already reporting success. The
containers are asked before the line is printed
(:func:`~osprey.deployment.container_lifecycle.unhealthy_containers`), and
an unhealthy one replaces the line with its name and the verb that shows
its log -- for a backend-only project too, which otherwise gets no line.
The address is the deployment's own external origin -- the value each
terminal checks a mutating request's ``Origin`` against -- not the deploy
host's loopback. Sending an operator to an address the terminals refuse
every write from produces a deployment that looks healthy and works for
nothing. When no origin can be derived the loopback address is printed with
a note saying it serves the landing page alone.
A multi-user deployment with no login wall gets one line more. There the
landing page routes to a terminal that answers nothing without a credential,
and the ONLY way to a first session is that user's own ``?token=`` URL — so
an operator told to "open the landing page" and nothing else is looking at a
door with no handle. The URLs themselves are deliberately not printed here:
each carries a live operator secret, and this output is read over shoulders,
pasted into tickets and captured whole by CI logs. The verb that prints one
user's URL is named instead.
:param repo_root: The deployment repo
:param state: One of ``created``, ``built``, ``running``, ``stopped``
"""
from osprey.deployment.container_lifecycle import unhealthy_containers
from osprey.deployment.deploy_summary import as_built_closing_facts
if state != "running":
return
facts = as_built_closing_facts(repo_root)
unhealthy = unhealthy_containers(repo_root)
if not facts.landing_url and not unhealthy:
return
output.report("")
if unhealthy:
verb = "is" if len(unhealthy) == 1 else "are"
output.report(f"{', '.join(unhealthy)} {verb} unhealthy. Run `osprey logs` to see why.")
else:
output.report(f"Everything is running. Open {facts.landing_url} to start.")
if not facts.landing_url:
return
if not facts.landing_url_is_external_origin:
# The address is the deploy host's own loopback, which is where the
# landing page answers and nowhere a terminal will accept a write: each
# one checks a mutating request's Origin against the deployment's
# declared origin, and this is not it. Said here rather than left to be
# discovered as a 403 inside a container.
output.note(
"this address serves the landing page only -- set deploy.fqdn (or "
"modules.web_terminals.external_origin) to the address browsers reach "
"this deployment on, or every write from a terminal is refused"
)
if facts.logins:
pairs = " · ".join(f"{user} / {password}" for user, password in facts.logins)
output.section("", [("sign in as", pairs)])
output.note("these logins come from profile.yml; change them in .env")
if facts.stale_logins:
# A default the deployed hash contradicts is withheld above; saying
# nothing would leave the operator typing the profile's password at a
# wall that refuses it, with no clue which side is wrong.
users = ", ".join(facts.stale_logins)
verbs = " · ".join(f"osprey users passwd {user}" for user in facts.stale_logins)
output.note(
f"the seeded password in .env for {users} does not match the deployed "
f"login -- an earlier deploy set a different one. Reset with: {verbs}"
)
if facts.token_login_users:
output.section(
"",
[("open a terminal with", f"osprey users login-url {facts.token_login_users[0]}")],
)
if len(facts.token_login_users) == 1:
output.note(
"this terminal has no login page: "
f"{facts.token_login_users[0]} needs its own login URL, which carries "
"that user's secret -- treat it like a password"
)
else:
output.note(
"these terminals have no login page: "
f"{', '.join(facts.token_login_users)} each need their own "
"login URL, which carries that user's secret -- treat it like a password"
)
if facts.shared_cards:
# Names, never URLs, for the same reason as the token-login line above.
# Without this line a shared card looks unreachable: it is in neither
# the sign-in pairs nor the login-url list, because it holds no
# credential of its own.
if len(facts.shared_cards) == 1:
output.note(
f"{facts.shared_cards[0]} is a shared card with no login of its "
"own -- open it by signing in with another roster user's name "
"and credential"
)
else:
output.note(
f"{', '.join(facts.shared_cards)} are shared cards with no "
"login of their own -- open each by signing in with another "
"roster user's name and credential"
)

Xet Storage Details

Size:
14.1 kB
·
Xet hash:
b99d38396e2f4bbb7ee24cb29b3da54df794c369cd69430be6fda67b23c908f7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.