Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
3 changes: 2 additions & 1 deletion lib/hyper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ defmodule Hyper do
@spec create_vm(Hyper.Vm.Spec.t()) :: {:ok, Hyper.Vm.t()} | {:error, term()}
def create_vm(%Hyper.Vm.Spec{} = spec) do
with {:ok, arch} <- resolve_arch(spec.arch),
{:ok, guest_services} <- Hyper.GuestService.resolve_all(spec.guest_services),
:ok <- fits_disk(spec.img_id, spec.type) do
vm_id = Hyper.Vm.Id.generate()
spec = %{spec | arch: arch}
spec = %{spec | arch: arch, guest_services: guest_services}
instance_spec = Hyper.Vm.Instance.spec(spec.type)

start_fun = fn -> Hyper.Node.start_image_vm(vm_id, spec) end
Expand Down
113 changes: 113 additions & 0 deletions lib/hyper/guest_service.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
defmodule Hyper.GuestService do
@moduledoc """
Guest services are a mechanism for Hyper VMs to communicate with the hypervisor.

Think of guest services as little servers, injected from the hypervisor to the guest, that the
guest can query at any point.

You can implement guest services however you like. See `Hyper.GuestService.Handler` for a guide
on how to implement services. You can inject multiple guest services into a VM. Each guest
service has a name, and an associated interface (defined in `Hyper.GuestService.Handler`) which
must be implemented.

Guest services communicate between the hypervisor and the guest over an `AF_SOCK` vsock, passed
through to the VM. This is a req-rep mechanism. Each request over this socket must contain the
name of the service "my-guest-service\0", followed by a null character (up to 256 characters,
including NUL). Passing the name allows the hypervisor to route the request to the appropriate
service handler. From then, any arbitrary binary data can be passed in the request. There are
no further constraints in the protocol.
"""

alias Hyper.GuestService.Header
alias Unit.Time

@reserved_prefix "hyper-"

@enforce_keys [:handler]
@derive {Inspect, except: [:handler]}
defstruct [:name, :handler, max_connections: 16, idle_timeout: Time.s(300)]

@type name :: String.t()
@type t :: %__MODULE__{
name: name() | nil,
handler: {module(), term()},
max_connections: pos_integer(),
idle_timeout: Time.t()
}

@type resolve_error ::
{:guest_service_handler_not_loaded, module()}
| {:invalid_guest_service, term(),
:handler | :name | :reserved_name | :max_connections | :idle_timeout}
| {:duplicate_guest_service, name()}

@spec resolve_all([t()]) :: {:ok, [t()]} | {:error, resolve_error()}
def resolve_all(services) do
with {:ok, resolved} <- resolve_each(services),
:ok <- unique(resolved) do
{:ok, resolved}
end
end

@spec ensure_loaded([t()]) :: :ok | {:error, {:guest_service_handler_not_loaded, module()}}
def ensure_loaded([]), do: :ok

def ensure_loaded([%__MODULE__{handler: {mod, _arg}} | rest]) do
if handler?(mod),
do: ensure_loaded(rest),
else: {:error, {:guest_service_handler_not_loaded, mod}}
end

defp resolve_each([]), do: {:ok, []}

defp resolve_each([service | rest]) do
with {:ok, resolved} <- resolve(service),
{:ok, others} <- resolve_each(rest) do
{:ok, [resolved | others]}
end
end

defp resolve(%__MODULE__{handler: {mod, _arg}} = service) when is_atom(mod) do
with :ok <- ensure_loaded([service]),
name = service.name || mod.name(),
:ok <- check(service, mod, name) do
{:ok, %{service | name: name}}
end
end

defp resolve(%__MODULE__{handler: handler}),
do: {:error, {:invalid_guest_service, handler, :handler}}

defp check(service, mod, name) do
cond do
not Header.valid_name?(name) ->
{:error, {:invalid_guest_service, mod, :name}}

String.starts_with?(name, @reserved_prefix) ->
{:error, {:invalid_guest_service, mod, :reserved_name}}

not (is_integer(service.max_connections) and service.max_connections > 0) ->
{:error, {:invalid_guest_service, mod, :max_connections}}

Time.as_ms(service.idle_timeout) <= 0 ->
{:error, {:invalid_guest_service, mod, :idle_timeout}}

true ->
:ok
end
end

defp unique(services) do
names = Enum.map(services, & &1.name)

case names -- Enum.uniq(names) do
[] -> :ok
[name | _] -> {:error, {:duplicate_guest_service, name}}
end
end

defp handler?(mod) do
Code.ensure_loaded?(mod) and function_exported?(mod, :name, 0) and
function_exported?(mod, :init, 2) and function_exported?(mod, :handle_data, 2)
end
end
8 changes: 8 additions & 0 deletions lib/hyper/guest_service/conn.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
defmodule Hyper.GuestService.Conn do
@moduledoc "Struct which models an active connection for a guest service."

@enforce_keys [:vm_id, :service]
defstruct [:vm_id, :service]

@type t :: %__MODULE__{vm_id: Hyper.Vm.Id.t(), service: Hyper.GuestService.name()}
end
38 changes: 38 additions & 0 deletions lib/hyper/guest_service/handler.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
defmodule Hyper.GuestService.Handler do
@moduledoc """
Behaviour for implementing `Hyper.GuestService`s.
"""

@type action :: {:continue, term()} | {:reply, iodata(), term()} | {:close, term()}

@doc """
The name of this guest service.

This is an address the VM can reach your service at, if the service is injected into the VM.
"""
@callback name() :: Hyper.GuestService.name()

@doc "Initialize the guest service. Called per VM."
@callback init(Hyper.GuestService.Conn.t(), arg :: term()) ::
{:ok, state :: term()} | {:close, reason :: term()}

@doc """
Handle a request (partial or complete) called by the VM.

Returning `{:continue, term()}` allows you to fetch more data from the client.
"""
@callback handle_data(binary(), state :: term()) :: action()

@doc """
Handle a message sent to the handler's process by something other than the VM.

Returning `{:reply, iodata(), term()}` allows you to push data to the client without waiting
for a request. If you don't implement this, the message is dropped.
"""
@callback handle_info(term(), state :: term()) :: action()

@doc "Called when the handler is torn down."
@callback terminate(reason :: term(), state :: term()) :: term()

@optional_callbacks handle_info: 2, terminate: 2
end
32 changes: 32 additions & 0 deletions lib/hyper/guest_service/header.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
defmodule Hyper.GuestService.Header do
@moduledoc false

@max_bytes 256
@name ~r/\A[a-z0-9_-]{1,255}\z/

@spec parse(binary()) ::
{:ok, Hyper.GuestService.name(), binary()} | :more | {:error, :too_long | :bad_name}
def parse(buffer) do
case :binary.match(buffer, <<0>>) do
{at, 1} when at < @max_bytes -> named(buffer, at)
{_at, 1} -> {:error, :too_long}
:nomatch when byte_size(buffer) >= @max_bytes -> {:error, :too_long}
:nomatch -> partial(buffer)
end
end

@spec valid_name?(term()) :: boolean()
def valid_name?(name) when is_binary(name), do: Regex.match?(@name, name)
def valid_name?(_), do: false

defp named(buffer, at) do
<<name::binary-size(^at), 0, rest::binary>> = buffer
if valid_name?(name), do: {:ok, name, rest}, else: {:error, :bad_name}
end

defp partial(""), do: :more

defp partial(buffer) do
if valid_name?(buffer), do: :more, else: {:error, :bad_name}
end
end
16 changes: 11 additions & 5 deletions lib/hyper/node.ex
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ defmodule Hyper.Node do
@spec start_image_vm(Hyper.Vm.Id.t(), Hyper.Vm.Spec.t()) :: {:ok, pid()} | {:error, term()}
@decorate with_span("Hyper.Node.start_image_vm", include: [:vm_id, :spec])
def start_image_vm(vm_id, %Hyper.Vm.Spec{} = spec) do
with {:ok, uid, net_id} <- claim_ids(),
with :ok <- Hyper.GuestService.ensure_loaded(spec.guest_services),
{:ok, uid, net_id} <- claim_ids(),
{:ok, mutable} <-
acquire_or_release(uid, net_id, fn ->
Img.create_mutable(spec.img_id, vm_id, Hyper.Vm.Instance.spec(spec.type).disk)
Expand All @@ -121,10 +122,12 @@ defmodule Hyper.Node do
type: parent.type,
arch: parent.arch,
boot_args: parent.boot_args,
firewall: parent.firewall
firewall: parent.firewall,
guest_services: parent.guest_services
}

with {:ok, uid, net_id} <- claim_ids(),
with :ok <- Hyper.GuestService.ensure_loaded(spec.guest_services),
{:ok, uid, net_id} <- claim_ids(),
{:ok, mutable} <-
acquire_or_release(uid, net_id, fn ->
Img.create_fork(
Expand Down Expand Up @@ -279,7 +282,8 @@ defmodule Hyper.Node do
type: Hyper.Vm.Instance.t(),
arch: Hyper.Vm.Instance.arch(),
boot_args: String.t() | nil,
firewall: Hyper.Vm.Firewall.t()
firewall: Hyper.Vm.Firewall.t(),
guest_services: [Hyper.GuestService.t()]
}}
| {:error, term()}
@decorate with_span("Hyper.Node.publish_fork_image", include: [:vm_id])
Expand All @@ -294,7 +298,8 @@ defmodule Hyper.Node do
type: parent.type,
arch: parent.arch,
boot_args: parent.boot_args,
firewall: parent.firewall
firewall: parent.firewall,
guest_services: parent.guest_services
}}
end
end
Expand All @@ -318,6 +323,7 @@ defmodule Hyper.Node do
gid: uid,
net_id: net_id,
firewall: spec.firewall,
guest_services: spec.guest_services,
type: spec.type,
arch: spec.arch,
img_id: spec.img_id,
Expand Down
57 changes: 35 additions & 22 deletions lib/hyper/node/fire_vmm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ defmodule Hyper.Node.FireVMM do
alias Hyper.Node.FireVMM.Agent.Relay
alias Hyper.Node.FireVMM.Client
alias Hyper.Node.FireVMM.Core
alias Hyper.Node.FireVMM.GuestServices.Listener
alias Hyper.Node.FireVMM.Jailer
alias Hyper.Node.FireVMM.Meter
alias Hyper.Node.FireVMM.Policy
Expand Down Expand Up @@ -55,7 +56,8 @@ defmodule Hyper.Node.FireVMM do
:mutable,
:kernel,
:boot_args,
:firewall
:firewall,
guest_services: []
]

@type t :: %__MODULE__{
Expand All @@ -69,7 +71,8 @@ defmodule Hyper.Node.FireVMM do
mutable: pid(),
kernel: Path.t(),
boot_args: String.t() | nil,
firewall: Hyper.Vm.Firewall.t()
firewall: Hyper.Vm.Firewall.t(),
guest_services: [Hyper.GuestService.t()]
}
end

Expand Down Expand Up @@ -98,26 +101,30 @@ defmodule Hyper.Node.FireVMM do
# incarnation - decline the start and let the supervisor retry clean.
case Hyper.Cluster.Routing.register_self({opts.vm_id, :supervisor}) do
:ok ->
children = [
# Client must be registered before Core: Core starts the State machine,
# which calls Client.run while waiting for the daemon's API. Client
# depends only on vm_id (an independent peer), so no reverse dependency.
{Client, %Client.Opts{vm_id: opts.vm_id}},
# Before Core: its Daemon launches under the current policy, and a
# firecracker crash restarts Core without resetting what was set since.
{Policy, opts},
{Core, opts},
{Relay,
%{
vm_id: opts.vm_id,
vsock_uds: Jailer.host_vsock(opts.vm_id),
listen_path: Agent.relay_socket_path(opts.vm_id)
}},
# Last on purpose: children stop in reverse start order, so the meter
# stops first at teardown and flushes its final usage window while
# Core's Daemon (and the cgroup it removes) is still alive.
{Meter, %Meter.Opts{vm_id: opts.vm_id, cgroup_dir: Jailer.cgroup_dir(opts.vm_id)}}
]
children =
[
# Client must be registered before Core: Core starts the State machine,
# which calls Client.run while waiting for the daemon's API. Client
# depends only on vm_id (an independent peer), so no reverse dependency.
{Client, %Client.Opts{vm_id: opts.vm_id}},
# Before Core: its Daemon launches under the current policy, and a
# firecracker crash restarts Core without resetting what was set since.
{Policy, opts}
] ++
guest_services(opts) ++
[
{Core, opts},
{Relay,
%{
vm_id: opts.vm_id,
vsock_uds: Jailer.host_vsock(opts.vm_id),
listen_path: Agent.relay_socket_path(opts.vm_id)
}},
# Last on purpose: children stop in reverse start order, so the meter
# stops first at teardown and flushes its final usage window while
# Core's Daemon (and the cgroup it removes) is still alive.
{Meter, %Meter.Opts{vm_id: opts.vm_id, cgroup_dir: Jailer.cgroup_dir(opts.vm_id)}}
]

Supervisor.init(children, strategy: :one_for_one)

Expand All @@ -126,6 +133,12 @@ defmodule Hyper.Node.FireVMM do
end
end

@spec guest_services(Opts.t()) :: [{module(), Listener.Opts.t()}]
defp guest_services(%Opts{guest_services: []}), do: []

defp guest_services(%Opts{vm_id: vm_id, guest_services: services}),
do: [{Listener, %Listener.Opts{vm_id: vm_id, services: services}}]

@doc "Test whether the system can run firecracker VMMs."
@spec test_system() :: :ok | {:error, term()}
def test_system do
Expand Down
Loading
Loading