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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]

### Added
- `exec` takes `:wait_for_agent` (ms): an exec on a VM still booting waits for
its guest agent to come up, probing every 2 ms, and runs as soon as it
listens, instead of answering `:agent_unavailable` and leaving the caller to
poll. `:timeout` starts once the agent answers, and the wait is its own span,
`Hyper.Node.FireVMM.Agent.wait_for_agent`. Without the option, `exec` is
unchanged.
- Spans from calls that cross nodes join the caller's trace. `Hyper.Rpc.call/5`
carries the caller's OpenTelemetry context over `:erpc`, and every one of
Hyper's own `:erpc` hops goes through it; callers outside Hyper do the same
Expand Down
4 changes: 3 additions & 1 deletion lib/hyper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ defmodule Hyper do
id/owning node is gone), `:node_unreachable` if the owning node cannot be
reached over the cluster.
`opts`: `:env` (map `%{String.t() => String.t()}`), `:cwd` (string), `:timeout`
(ms, deadline for the whole call, also sent to the guest; default 30 000).
(ms, deadline for the whole call, also sent to the guest; default 30 000), and
`:wait_for_agent` (ms to wait for a VM still booting to bring up its agent
before running `argv`, rather than answering `:agent_unavailable`; default 0).

`argv` is executed directly, not through a shell. Use an **absolute** `argv`
head (`["/bin/echo", "hi"]`): the guest runs as PID 1 with a near-empty
Expand Down
63 changes: 53 additions & 10 deletions lib/hyper/node/fire_vmm/agent.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ defmodule Hyper.Node.FireVMM.Agent do
use OpenTelemetryDecorator

alias Hyper.Agent.V1.{ExecRequest, ExecResponse, GuestAgent}
alias Hyper.Node.FireVMM.Agent.Relay
alias Hyper.Node.FireVMM.Jailer
alias OpenTelemetry.Tracer

# GRPC.Status codes stored as module attributes so they can be used in
Expand All @@ -24,6 +26,10 @@ defmodule Hyper.Node.FireVMM.Agent do

@default_timeout 30_000

# How often a VM still booting is probed for its agent: what an exec that waits for it adds at
# most, against a probe's cost, a Unix-socket connect and one CONNECT line to firecracker.
@agent_probe_ms 2

@type result ::
{:ok, %{stdout: binary(), stderr: binary(), exit_code: integer()}} | {:error, term()}

Expand Down Expand Up @@ -59,19 +65,33 @@ defmodule Hyper.Node.FireVMM.Agent do
- `:env` — environment map `%{String.t() => String.t()}` for the guest process
- `:cwd` — working directory inside the guest (`nil` → not set)
- `:timeout` — deadline for the whole call in milliseconds (default: #{@default_timeout})
- `:wait_for_agent` — how long, in milliseconds, to wait for the guest agent to come up
before running `argv` (default: 0, not at all). A VM still booting then answers as soon as
its agent listens, rather than with `:agent_unavailable`; `:timeout` starts once it does.
"""
@spec exec(Hyper.Vm.Id.t(), [String.t()], keyword()) :: result()
@decorate with_span("Hyper.Node.FireVMM.Agent.exec", include: [:vm_id, :timeout])
def exec(vm_id, argv, opts \\ []) do
timeout = Keyword.get(opts, :timeout, @default_timeout)
deadline = System.monotonic_time(:millisecond) + timeout

req = %ExecRequest{
argv: argv,
env: Map.new(Keyword.get(opts, :env, %{})),
cwd: opts[:cwd]
}

result =
with :ok <- await_agent(vm_id, Keyword.get(opts, :wait_for_agent, 0)) do
request(vm_id, req, timeout)
end

Tracer.set_attribute(:outcome, outcome(result))
result
end

@spec request(Hyper.Vm.Id.t(), ExecRequest.t(), non_neg_integer()) :: result()
defp request(vm_id, req, timeout) do
deadline = System.monotonic_time(:millisecond) + timeout
path = vm_id |> relay_socket_path() |> String.to_charlist()

# The caller owns the connection: gun monitors its owner, so a killed
Expand All @@ -85,16 +105,39 @@ defmodule Hyper.Node.FireVMM.Agent do
http2_opts: %{closing_timeout: 1}
})

result =
try do
call(conn, req, timeout, deadline)
after
_ = :gun.close(conn)
:gun.flush(conn)
end
try do
call(conn, req, timeout, deadline)
after
_ = :gun.close(conn)
:gun.flush(conn)
end
end

Tracer.set_attribute(:outcome, outcome(result))
result
@spec await_agent(Hyper.Vm.Id.t(), non_neg_integer()) :: :ok | {:error, :agent_unavailable}
defp await_agent(_vm_id, 0), do: :ok
defp await_agent(vm_id, wait_ms), do: wait_for_agent(vm_id, wait_ms)

# Its own span: how long a VM took, past the call, to answer.
@spec wait_for_agent(Hyper.Vm.Id.t(), pos_integer()) :: :ok | {:error, :agent_unavailable}
@decorate with_span("Hyper.Node.FireVMM.Agent.wait_for_agent", include: [:vm_id, :wait_ms])
defp wait_for_agent(vm_id, wait_ms),
do: probe(Jailer.host_vsock(vm_id), System.monotonic_time(:millisecond) + wait_ms)

# Nothing tells the host when the guest agent starts listening; firecracker refuses a CONNECT
# to a guest port nothing listens on at once, so the agent is probed until it answers.
@spec probe(Path.t(), integer()) :: :ok | {:error, :agent_unavailable}
defp probe(vsock, deadline) do
cond do
Relay.agent_listening?(vsock, remaining(deadline)) ->
:ok

System.monotonic_time(:millisecond) >= deadline ->
{:error, :agent_unavailable}

true ->
Process.sleep(@agent_probe_ms)
probe(vsock, deadline)
end
end

# What the span records of a call: never its output, which can hold anything.
Expand Down
16 changes: 16 additions & 0 deletions lib/hyper/node/fire_vmm/agent/relay.ex
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ defmodule Hyper.Node.FireVMM.Agent.Relay do
@spec listen_path(GenServer.server()) :: Path.t()
def listen_path(server), do: GenServer.call(server, :listen_path)

@doc """
Whether the guest agent behind firecracker's vsock socket `vsock_uds` accepts a connection
within `timeout_ms`. A VM still booting refuses one until its agent listens.
"""
@spec agent_listening?(Path.t(), non_neg_integer()) :: boolean()
def agent_listening?(vsock_uds, timeout_ms) do
case RelayDialer.dial(vsock_uds, @vsock_port, timeout_ms) do
{:ok, sock} ->
_ = :socket.close(sock)
true

{:error, _reason} ->
false
end
end

@impl GenServer
def init(%{vsock_uds: vsock_uds, listen_path: listen_path, vm_id: vm_id}) do
Process.flag(:trap_exit, true)
Expand Down
147 changes: 147 additions & 0 deletions test/hyper/node/fire_vmm/agent_wait_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
defmodule Hyper.Node.FireVMM.AgentWaitTest do
@moduledoc """
`Agent.exec/3`'s `:wait_for_agent`, through a real `Relay` and a fake
firecracker vsock that refuses every `CONNECT` until the guest "boots", as
firecracker does while nothing in the guest listens, then splices each one to
an in-process gRPC guest:

- an exec that waits answers once the agent comes up, not when its wait runs
out;
- an exec that does not wait is refused at once, as before;
- a wait that runs out first is `:agent_unavailable`, not a hang.

`async: false`: `Hyper.Cfg.Toml.put_cache/1` is process-global.
"""
use ExUnit.Case, async: false

alias Hyper.Agent.V1.{ExecResponse, HealthResponse}
alias Hyper.Node.FireVMM.Agent
alias Hyper.Node.FireVMM.Agent.Relay
alias Hyper.Node.FireVMM.Jailer

@vm_id "vwaitagent"
@up_at {__MODULE__, :up_at}

defmodule Guest do
@moduledoc false
use GRPC.Server, service: Hyper.Agent.V1.GuestAgent.Service

def exec(%{argv: ["/bin/echo" | rest]}, _stream),
do: %ExecResponse{exit_code: 0, stdout: Enum.join(rest, " ")}

def health(_req, _stream), do: %HealthResponse{ok: true}
end

setup_all do
{:ok, _} = Application.ensure_all_started(:grpc)
{:ok, _} = Application.ensure_all_started(:cowboy)
original = Hyper.Cfg.Toml.reload()
tmp = Path.join(System.tmp_dir!(), "agent-wait-#{System.unique_integer([:positive])}")
:ok = Hyper.Cfg.Toml.put_cache(Map.put(original, "work_dir", tmp))
File.mkdir_p!(Hyper.Cfg.Dirs.socket_dir())

guest_path = Path.join(Hyper.Cfg.Dirs.socket_dir(), "guest-#{@vm_id}.sock")
vsock_path = Jailer.host_vsock(@vm_id)
{:ok, _pid, _port} = GRPC.Server.start(Guest, 0, adapter_opts: [ip: {:local, guest_path}])

{:ok, fc} = :socket.open(:local, :stream)
:ok = :socket.bind(fc, %{family: :local, path: vsock_path})
:ok = :socket.listen(fc, 64)
firecracker = spawn(fn -> fake_firecracker(fc, guest_path) end)

{:ok, relay} =
Relay.start_link(%{
vm_id: @vm_id,
vsock_uds: vsock_path,
listen_path: Agent.relay_socket_path(@vm_id)
})

true = Process.unlink(relay)

on_exit(fn ->
GenServer.stop(relay)
Process.exit(firecracker, :kill)
GRPC.Server.stop(Guest)
:persistent_term.erase(@up_at)
Hyper.Cfg.Toml.put_cache(original)
File.rm_rf(tmp)
end)

:ok
end

test "an exec that waits answers once the agent comes up, not when its wait runs out" do
up_at = boot_in(150)

assert {:ok, %{stdout: "up"}} =
Agent.exec(@vm_id, ["/bin/echo", "up"], timeout: 5_000, wait_for_agent: 5_000)

answered = System.monotonic_time(:millisecond)
assert answered >= up_at
assert answered - up_at < 100
end

test "an exec that does not wait is refused at once while the agent is down" do
_ = boot_in(10_000)

{us, result} = :timer.tc(fn -> Agent.exec(@vm_id, ["/bin/echo", "x"], timeout: 5_000) end)

assert result == {:error, :agent_unavailable}
assert div(us, 1_000) < 1_000
end

test "a wait that runs out before the agent comes up is :agent_unavailable" do
_ = boot_in(10_000)

{us, result} =
:timer.tc(fn ->
Agent.exec(@vm_id, ["/bin/echo", "x"], timeout: 5_000, wait_for_agent: 200)
end)

assert result == {:error, :agent_unavailable}
assert div(us, 1_000) in 200..1_000
end

# The fake guest's agent starts listening `ms` from now; returns that instant.
defp boot_in(ms) do
up_at = System.monotonic_time(:millisecond) + ms
:persistent_term.put(@up_at, up_at)
up_at
end

defp fake_firecracker(listen, guest_path) do
with {:ok, vsock} <- :socket.accept(listen) do
_ = spawn(fn -> connect(vsock, guest_path) end)
fake_firecracker(listen, guest_path)
end
end

defp connect(vsock, guest_path) do
{:ok, "CONNECT " <> _} = :socket.recv(vsock)

if System.monotonic_time(:millisecond) >= :persistent_term.get(@up_at) do
splice(vsock, guest_path)
else
:socket.close(vsock)
end
end

defp splice(vsock, guest_path) do
:ok = :socket.send(vsock, "OK 5\n")
{:ok, guest} = :socket.open(:local, :stream)
:ok = :socket.connect(guest, %{family: :local, path: guest_path})
_ = spawn(fn -> pipe(guest, vsock) end)
pipe(vsock, guest)
end

defp pipe(from, to) do
with {:ok, data} <- :socket.recv(from),
:ok <- :socket.send(to, data) do
pipe(from, to)
else
_ ->
:socket.close(from)
:socket.close(to)
end
end
end
Loading