Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions cli/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use std::collections::BTreeSet;
use std::path::Path;
use std::time::Duration;

use anyhow::{Context, Result, ensure};
use serde_json::json;
Expand All @@ -14,6 +15,7 @@ pub fn run(
root: Option<&Path>,
port: i32,
metrics: bool,
observability: bool,
host: &Host,
) -> Result<()> {
ensure!(
Expand Down Expand Up @@ -80,7 +82,7 @@ pub fn run(
.capture(host.command(&helper)?.arg("--protocol-version"))
.context("local supervisor is outdated; install or rebuild matching ly and ly-dev")?;
ensure!(
protocol == "3",
protocol == "4",
"local supervisor is outdated; install or rebuild matching ly and ly-dev"
);
let build = directory.join(".lampyr/dev");
Expand Down Expand Up @@ -128,12 +130,18 @@ pub fn run(
serde_json::to_vec(&json!({
"binary": binary,
"listen": format!("127.0.0.1:{port}"),
"schemaVersion": 3,
"schemaVersion": 4,
"exposedServices": exposed,
"metrics": metrics,
"observability": observability,
"services": services,
}))?,
)?;
println!("native dev: CPU quotas, signed Grants and durable event delivery are not emulated");
host.interactive(host.command(helper)?.arg(&plan))
if observability {
// Allow request draining, bounded trace flushing, then backend removal.
host.interactive_with_grace(host.command(helper)?.arg(&plan), Duration::from_secs(30))
} else {
host.interactive(host.command(helper)?.arg(&plan))
}
}
10 changes: 9 additions & 1 deletion cli/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,18 @@ impl Host {
}

pub fn interactive(&self, command: &mut Command) -> Result<()> {
self.interactive_with_grace(command, Duration::from_secs(7))
}

pub fn interactive_with_grace(
&self,
command: &mut Command,
shutdown_grace: Duration,
) -> Result<()> {
command.stdin(Stdio::inherit());
let output = tools::execute(
command,
Output::Interactive,
Output::InteractiveWithGrace(shutdown_grace),
8 * 1024 * 1024,
None,
&self.cancellation,
Expand Down
6 changes: 5 additions & 1 deletion cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@ enum Command {
/// Print one line per completed request and a summary on exit.
#[arg(long)]
metrics: bool,
/// Start local Prometheus and Jaeger with links on the local service index.
#[arg(long)]
observability: bool,
},
/// Build the service snapshot and local OCI image.
Build {
Expand Down Expand Up @@ -473,8 +476,9 @@ fn run(cli: Cli) -> Result<()> {
directory,
port,
metrics,
observability,
} => {
lampyr_cli::dev::run(&directory, None, port, metrics, &host)?;
lampyr_cli::dev::run(&directory, None, port, metrics, observability, &host)?;
}
Command::Build {
directory,
Expand Down
18 changes: 11 additions & 7 deletions cli/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub enum Output {
Capture,
File(std::fs::File),
Interactive,
InteractiveWithGrace(std::time::Duration),
}

pub fn run(
Expand Down Expand Up @@ -110,15 +111,19 @@ mod unix {
deadline: Option<Instant>,
cancellation: &Cancellation,
) -> Result<ToolOutput> {
let interactive = matches!(&output, Output::Interactive);
let shutdown_grace = match &output {
Output::Interactive => Some(Duration::from_secs(7)),
Output::InteractiveWithGrace(grace) => Some(*grace),
_ => None,
};
match output {
Output::Capture => {
command.stdout(Stdio::piped()).stderr(Stdio::piped());
}
Output::File(file) => {
command.stdout(file).stderr(Stdio::piped());
}
Output::Interactive => {
Output::Interactive | Output::InteractiveWithGrace(_) => {
command.stdout(Stdio::inherit()).stderr(Stdio::inherit());
}
}
Expand All @@ -141,8 +146,8 @@ mod unix {
.map(|pipe| scope.spawn(move || capture(pipe, limit, deadline, cancellation)));
let status = loop {
if cancellation.is_cancelled() {
if interactive {
terminate_gracefully(&mut child)?;
if let Some(grace) = shutdown_grace {
terminate_gracefully(&mut child, grace)?;
} else {
terminate(&mut child)?;
}
Expand Down Expand Up @@ -254,12 +259,11 @@ mod unix {
Ok(())
}

fn terminate_gracefully(child: &mut Child) -> Result<()> {
fn terminate_gracefully(child: &mut Child, grace: Duration) -> Result<()> {
let pid = i32::try_from(child.id()).context("local tool PID is out of range")?;
ensure!(pid > 0, "invalid local tool process group");
signal_process(pid, libc::SIGTERM)?;
// ly-dev gets five seconds to drain requests; leave time for cleanup and summary output.
let deadline = Instant::now() + Duration::from_secs(7);
let deadline = Instant::now() + grace;
let mut reaped = false;
loop {
reaped |= child
Expand Down
3 changes: 2 additions & 1 deletion cli/tests/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ fn fixture() -> std::path::PathBuf {
}

#[test]
fn dev_help_offers_request_metrics() {
fn dev_help_offers_independent_request_metrics_and_observability() {
let output = Command::new(env!("CARGO_BIN_EXE_ly"))
.args(["dev", "--help"])
.output()
.unwrap();
assert!(output.status.success());
assert!(String::from_utf8_lossy(&output.stdout).contains("--metrics"));
assert!(String::from_utf8_lossy(&output.stdout).contains("--observability"));
}

#[test]
Expand Down
40 changes: 40 additions & 0 deletions cli/tests/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,46 @@ fn interactive_cancellation_allows_graceful_sigterm_cleanup() {
}

#[cfg(unix)]
#[test]
fn observability_cancellation_allows_drain_then_backend_cleanup() {
let directory = tempfile::tempdir().unwrap();
let started = directory.path().join("started");
let stopped = directory.path().join("stopped");
let mut command = std::process::Command::new("/bin/sh");
command
.env("STARTED", &started)
.env("STOPPED", &stopped)
.args([
"-c",
"trap 'sleep 8; printf stopped > \"$STOPPED\"; exit 0' TERM; printf started > \"$STARTED\"; while :; do :; done",
]);
let cancellation = Cancellation::default();
let cancel = cancellation.clone();
std::thread::scope(|scope| {
scope.spawn(move || {
let deadline = Instant::now() + Duration::from_secs(5);
while !started.exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
cancel.cancel();
});
assert!(
tools::execute(
&mut command,
tools::Output::InteractiveWithGrace(Duration::from_secs(30)),
1024,
None,
&cancellation,
)
.is_err()
);
});
assert_eq!(
std::fs::read_to_string(stopped).expect("backend cleanup did not finish"),
"stopped"
);
}

#[test]
fn interactive_cancellation_kills_descendants_after_grace_period() {
let directory = tempfile::tempdir().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion cmd/ly-dev/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func main() {

func run() error {
if len(os.Args) == 2 && os.Args[1] == "--protocol-version" {
fmt.Println("3")
fmt.Println("4")
return nil
}
if len(os.Args) != 2 {
Expand Down
31 changes: 31 additions & 0 deletions docs/cli/dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ upgrade process.
|---|---:|---|
| `--port` | `8080` | Local HTTP port. |
| `--metrics` | `false` | Print one line per completed request and an aggregate summary when dev exits. |
| `--observability` | `false` | Start local Prometheus and Jaeger. Show links on the local service index. |

Metrics include service, method, path, status, total duration, Fiber clone
duration, Fiber ID, and whether the Fiber was created or attached for reuse:
Expand All @@ -49,6 +50,36 @@ metric service=worker-api method=GET path="/invoke" status=200 duration_ms=128 c
metrics summary requests=3 errors=0 create=2 attach=1 avg_duration_ms=54 avg_clone_ms=39
```

## Local observability

```bash
ly dev demos/local-worker-workspace --observability
```

Open `http://localhost:8080/`. The service index includes an **Observability**
section with links to Prometheus and Jaeger. Send requests to an exposed
service. In Prometheus, query `lampyr_router_request_duration_seconds_count`.
In Jaeger, select `lampyr-local`, then **Find Traces**. Telemetry includes
internal services reached through bindings. The router preserves incoming trace
IDs. Applications must propagate trace context, such as the `traceparent` header,
on outgoing binding requests to keep calls in the same trace. This example
workspace does not forward trace context.

This option needs Docker, not Kubernetes. The first run downloads pinned
Prometheus and Jaeger images. Their browser endpoints use free loopback ports,
so multiple dev sessions can run with different `--port` values.
Prometheus scrapes a separate host listener with a random session token.
Docker uses `host.docker.internal` to reach it, with `host-gateway` on Linux.
The host firewall must allow this container-to-host connection.
Application routes, including `/metrics`, do not change.

Data is temporary. On exit, the supervisor flushes traces, removes its two
containers, and deletes their configuration. Prometheus retains up to one hour
of metrics in memory-backed storage; Jaeger retains up to 10,000 traces.
Prometheus uses 16 MB chunk segments to keep compaction within its 128 MiB volume.
Use `--metrics` as well if you want request text in the terminal.
Without `--observability`, no telemetry containers or scrape listener start.

## Workspace development

Service and workspace development both use native snapshots and the
Expand Down
Loading