diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..7fd10c70 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,29 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "mix_task", + "name": "mix (Default task)", + "request": "launch", + "projectDir": "${workspaceRoot}" + }, + { + "type": "mix_task", + "name": "mix test", + "request": "launch", + "task": "test", + "taskArgs": [ + "--trace" + ], + "startApps": true, + "projectDir": "${workspaceRoot}", + "requireFiles": [ + "test/**/test_helper.exs", + "test/**/*_test.exs" + ] + } + ] +} \ No newline at end of file diff --git a/docs/cookbook/config.md b/docs/cookbook/config.md index a1b3377d..23085087 100644 --- a/docs/cookbook/config.md +++ b/docs/cookbook/config.md @@ -176,6 +176,8 @@ cred = { cert = "/etc/hyper/tls/cert.pem", key = "/etc/hyper/tls/key.pem" } ``` +# add server config here + ## Telemetry Configuration You can configure telemetry with Hyper by adding this section to your diff --git a/lib/hyper/application.ex b/lib/hyper/application.ex index 4a0a280b..964f6d73 100644 --- a/lib/hyper/application.ex +++ b/lib/hyper/application.ex @@ -27,7 +27,7 @@ defmodule Hyper.Application do # registries on boot. Hyper.Cluster, Hyper.Node - ] ++ Hyper.Grpc.server_children() + ] ++ Hyper.Grpc.server_children() ++ Hyper.Http.server_children() Supervisor.start_link(children, strategy: :one_for_one, name: Hyper.Supervisor) end diff --git a/lib/hyper/cfg/http.ex b/lib/hyper/cfg/http.ex new file mode 100644 index 00000000..647044c8 --- /dev/null +++ b/lib/hyper/cfg/http.ex @@ -0,0 +1,96 @@ +defmodule Hyper.Cfg.Http do + @moduledoc """ + + Http server configuration, read from application env into a struct: + + config :hyper, Hyper.Cfg.Http, + enabled: true, + port: 8081, + http_server_opts: opts + + Fields: + + * `:enabled` -- whether the server starts. Defaults to `false`. + * `:port` -- the listen port. Defaults to `8081`. + * `:http_server_opts` -- options forwarded to the http server, e.g. + `[ip: {0, 0, 0, 0}]`. + + """ + + import Hyper.Cfg, only: [get_cfg: 1] + + @default_port 8081 + + defstruct enabled: false, port: @default_port, http_server_opts: [] + + # Add the Credential after clarifying + + @type t :: %__MODULE__{ + enabled: boolean(), + port: :inet.port_number(), + http_server_opts: keyword() + } + + @type ip_address :: :inet.ip4_address() | :inet.ip6_address() + + @doc "Load the Http server configuration: config.exs > [server] toml > defaults." + @spec load() :: t() + def load do + %__MODULE__{ + enabled: + get_cfg(runtime: {__MODULE__, :enabled}, toml: "http_server.enabled", default: false), + port: + get_cfg(runtime: {__MODULE__, :port}, toml: "http_server.port", default: @default_port), + http_server_opts: + get_cfg( + runtime: {__MODULE__, :http_server_opts}, + toml: "http_server.options", + default: [] + ) + } + end + + @spec ip(term()) :: ip_address() | nil + defp ip(nil), do: nil + + defp ip(ip) when is_binary(ip) do + case :inet.parse_address(String.to_charlist(ip)) do + {:ok, addr} -> addr + {:error, _} -> nil + end + end + + defp ip(ip) when is_list(ip), do: ip |> List.to_tuple() |> ip() + + defp ip(ip) when is_tuple(ip) do + case :inet.ntoa(ip) do + {:error, _} -> nil + _ -> ip + end + end + + defp ip(_), do: nil + + @doc """ + The `Http.Server.Supervisor` options for this config: the endpoint and port, + and http server options when set. + """ + @spec server_options(t()) :: keyword() + def server_options(%__MODULE__{} = config) do + base_opts = + case config.http_server_opts do + opts when is_map(opts) -> Enum.map(opts, fn {k, v} -> {to_atom(k), v} end) + opts -> opts + end + + options = + base_opts + |> Keyword.put(:port, config.port) + |> Keyword.put(:ip, ip(Keyword.get(base_opts, :ip)) || {127, 0, 0, 1}) + + [scheme: :http, plug: Hyper.Http.Router, options: options] + end + + defp to_atom(k) when is_atom(k), do: k + defp to_atom(k) when is_binary(k), do: String.to_atom(k) +end diff --git a/lib/hyper/http.ex b/lib/hyper/http.ex new file mode 100644 index 00000000..daf05fb5 --- /dev/null +++ b/lib/hyper/http.ex @@ -0,0 +1,22 @@ +defmodule Hyper.Http do + @moduledoc """ + Public Http Interface to a Hyper Cluster + """ + + alias Hyper.Cfg.Http, as: Config + + @doc """ + The Http Server's Supervisor child, or `[]` when the server is diabled i.e. the default. + Spliced into the application's supervision tree at boot. + """ + @spec server_children :: [{module(), keyword()}] + def server_children do + config = Config.load() + + if config.enabled do + [{Plug.Cowboy, Config.server_options(config)}] + else + [] + end + end +end diff --git a/lib/hyper/http/plugs/verify_request.ex b/lib/hyper/http/plugs/verify_request.ex new file mode 100644 index 00000000..0c9d069b --- /dev/null +++ b/lib/hyper/http/plugs/verify_request.ex @@ -0,0 +1,57 @@ +defmodule Hyper.Http.Plugs.VerifyRequest do + @moduledoc """ + Verify specific fields in a request body + """ + + defmodule IncompleteRequestError do + @moduledoc """ + Error raised when a required field is missing. + """ + defexception message: "", plug_status: 400 + end + + def init(options), do: options + + def call(conn, opts) do + %Plug.Conn{ + request_path: path, + method: method, + body_params: payload + } = conn + + if requires_verification?(path, method) do + verify_request!(payload, opts[:fields]) + end + + conn + end + + def verify_request!(params, fields) do + keys = Map.keys(params) + + if !contains_fields?(fields) do + missing_fields = fields -- keys + + raise IncompleteRequestError, + message: "missing required field(s): #{Enum.join(missing_fields, ", ")}" + end + end + + # change this to simple methods to verify the required fields and _ for missing fields + # defp contains_fields?(keys, fields), do: Enum.all?(fields, fn x -> x in keys end) + + defp contains_fields?(%{ + "image" => _, + "boot_args" => _, + "type" => _, + "architecture" => _, + "label" => _ + }), + do: true + + defp contains_fields?(%{"image" => _, "boot_args" => _, "type" => _}), do: true + defp contains_fields?(_), do: false + + defp requires_verification?(["/v1/vms"], "POST"), do: true + defp requires_verification?(_, _), do: false +end diff --git a/lib/hyper/http/router.ex b/lib/hyper/http/router.ex new file mode 100644 index 00000000..4c6efe8e --- /dev/null +++ b/lib/hyper/http/router.ex @@ -0,0 +1,216 @@ +defmodule Hyper.Http.Router do + @moduledoc """ + Public HTTP interface for Hyper VMs. + + * `GET /health` - liveness probe; no dependency checks. + * `GET /ready` - readiness probe for the database and cluster. + * `GET /v0/vms` - list VMs using `page_size` and `page_token`; responds with + `vms` and `next_page_token`. + * `POST /v0/vms` - create a VM from `image`, `instance_type`, `boot_args`, + and optional `arch` and `label`. + * `GET /v0/vms/:id` - get one VM. + * `POST /v0/vms/:id/fork` - fork a VM. + * `POST /v0/vms/:id` - stop a VM. + * `PUT /v0/vms/:id/firewall` - set a VM firewall. + * `GET /v0/vms/:id/usage` - metered usage for a VM. + * `POST /v0/vms/:id/exec` - execute a command in the guest. + * `POST /v0/images` - load an OCI image. + """ + + use Plug.Router + use Plug.ErrorHandler + + alias Hyper.Http.Plugs.VerifyRequest + + plug(:match) + + plug(Plug.Parsers, + parsers: [:json], + pass: ["application/json"], + json_decoder: Jason + ) + + plug(VerifyRequest, + create_vm_fields: ["image", "instance_type", "boot_args"], + paths: ["/v0/vms"] + ) + + plug(:dispatch) + + get "/health" do + send_json_response(conn, 200, %{status: "Hyper System is live"}) + end + + get "/ready" do + case Hyper.Http.Server.ready() do + :ok -> + send_json_response(conn, 200, %{status: "Hyper System DB and Cluster are ready"}) + + :error -> + send_json_response(conn, 503, %{ + status: "Hyper System DB and Cluster not ready, Please try again later" + }) + end + end + + # TODO - create a vm router and forward all requests that come from path /vm to it + + get "/v0/vms" do + params = conn.query_params + + page_size = + case Map.get(params, "page_size", "10") |> Integer.parse() do + {size, ""} -> size + _ -> 0 + end + + page_token = Map.get(params, "page_token", "") + + case Hyper.Http.Server.list_vms(page_size, page_token) do + {:ok, vms, next_token} -> + send_json_response(conn, 200, %{vms: vms, next_page_token: next_token}) + + {:error, bad_page_token} -> + send_json_response(conn, 400, %{ + error: "Could not fetch VMs. Bad page token #{bad_page_token}" + }) + end + end + + post "/v0/vms" do + case Hyper.Http.Server.create_vm(conn) do + {:created, vm_id, node_id, ipv6} -> + send_json_response(conn, 201, %{ + status: "created", + vm_id: vm_id, + node: node_id, + ip_address: ipv6 + }) + + {:error, :machine_unreachable} -> + send_json_response(conn, 503, %{status: "Machine Unreachable"}) + + {:error, _reason} -> + send_json_response(conn, 503, %{error: "Could not create VM, Try again later"}) + end + end + + get "/v0/vms/:id" do + case Hyper.whereis(id) do + nil -> send_json_response(conn, 404, %{status: "Not Found"}) + vm -> send_json_response(conn, 200, %{status: "Found", vm: vm}) + end + end + + post "/v0/vms/:vm_id/fork" do + case Hyper.fork_vm(vm_id) do + {:ok, vm_id} -> + id = Hyper.id(vm_id) + + if id == nil do + send_json_response(conn, 503, %{status: "Machine Unreachable"}) + else + send_json_response(conn, 201, %{status: "Forked", vm: node(vm_id)}) + end + + {:error, _} -> + send_json_response(conn, 503, %{status: "Could not fork vm, try again later"}) + end + end + + post "/v0/vms/:vm_id/stop" do + case Hyper.stop_vm(vm_id) do + :ok -> + send_json_response(conn, 200, %{status: "Machine Stopped"}) + + {:error, :not_found} -> + send_json_response(conn, 404, %{status: "Machine with #{vm_id} not found"}) + + {:error, :unreachable} -> + send_json_response(conn, 404, %{status: "Machine Unreachable"}) + end + end + + put "/v0/vms/:vm_id/set_firewall" do + get_firewall = Map.get(conn.body_params, "firewall") + + case Hyper.Http.Server.set_firewall(vm_id, get_firewall) do + :ok -> + send_json_response(conn, 200, %{status: "Firewall set"}) + + :not_found -> + send_json_response(conn, 404, %{status: "Machine with #{vm_id} not found"}) + + :unreachable -> + send_json_response(conn, 404, %{status: "Machine Unreachable"}) + end + end + + get "/v0/vms/:id/usage" do + case Hyper.usage(id) do + {:ok, vm_usage} -> + send_json_response(conn, 200, %{vm_usage: vm_usage}) + + {:error, :not_found} -> + send_json_response(conn, 404, %{status: "Machine with #{id} not found"}) + end + end + + post "/v0/vms/:id/exec" do + get_argv = Map.get(conn.body_params, "argv") + get_opts = Map.get(conn.body_params, "opts") + + case Hyper.exec(id, get_argv, get_opts) do + {:ok, output} -> + %{stdout: stdout, stderr: stderr, exit_code: code} = output + + if stderr do + send_json_response(conn, 200, %{ + status: "output is stderr", + output: stderr, + exit_code: code + }) + end + + send_json_response(conn, 200, %{ + status: "output is stderr", + output: stdout, + exit_code: code + }) + + {:error, _} -> + send_json_response(conn, 503, %{ + status: "Could not execute request on Machine with #{id}, Please try again later" + }) + end + end + + # post "/v0/images" do + # conn + # |> send_resp(201, "Get vms per id ") + # end + + match _ do + send_json_response(conn, 404, "Oops! Endpoint not found") + end + + defp send_json_response(conn, status, body) do + conn + |> put_resp_content_type("application/json") + |> put_resp_header("cache-control", "store") + |> send_resp(status, Jason.encode!(body)) + end + + @impl Plug.ErrorHandler + def handle_errors(conn, %{kind: kind, reason: reason, stack: stack}) do + IO.inspect(kind, label: :kind) + IO.inspect(reason, label: :reason) + IO.inspect(stack, label: :stack) + + %VerifyRequest.IncompleteRequestError{ + message: msg + } = reason + + send_resp(conn, conn.status, msg) + end +end diff --git a/lib/hyper/http/server.ex b/lib/hyper/http/server.ex new file mode 100644 index 00000000..9257e324 --- /dev/null +++ b/lib/hyper/http/server.ex @@ -0,0 +1,83 @@ +defmodule Hyper.Http.Server do + require Logger + + def ready do + result = + case Application.get_env(:hyper, __MODULE__, [])[:ready] do + fun when is_function(fun, 0) -> fun.() + _ -> Hyper.Http.Server.Health.ready() + end + + case result do + {:ok, _} -> :ok + {:error, _} -> :error + end + end + + def list_vms(page_size, page_token \\ "") do + case Hyper.Grpc.Page.paginate( + Hyper.Cluster.Routing.all(), + page_size, + page_token, + Hyper.Grpc.Pageable.Vm + ) do + {:ok, {page, next}} -> + {:ok, + Enum.map( + page, + fn {vm_id, node} -> %{vm_id: vm_id, node: to_string(node)} end + ), next} + + {:error, bad_page_token} -> + {:error, bad_page_token} + end + end + + # use the create_vm , build the spec, servers/grpc line 43, mirror the create vm , return the fields if it doesn't work just return an unreachable machine or the error + # load image returns img_id + def create_vm(%Plug.Conn{body_params: payload} = _conn) do + %{ + "image" => image_ref, + "boot_args" => boot_args, + "type" => type + } = payload + + arch = Map.get(payload, "architecture", nil) + label = Map.get(payload, "label") + + case Hyper.Img.OciLoader.load(image_ref, label) do + {:ok, img_id} -> + spec = %Hyper.Vm.Spec{ + img_id: img_id, + type: type, + arch: arch, + boot_args: boot_args + } + + with {:ok, pid} <- Hyper.create_vm(spec), + vm_id when is_binary(vm_id) <- Hyper.id(pid), + {:ok, ipv6} <- Hyper.address(pid) do + {:created, vm_id, node(pid), ipv6} + else + nil -> {:error, :machine_unreachable} + {:error, reason} -> {:error, reason} + end + + {:error, reason} -> + {:error, reason} + end + end + + def set_firewall(vm_id, get_firewall) do + firewall = %Hyper.Vm.Firewall{ + inbound: Map.get(get_firewall, "inbound"), + outbound_blocked: Map.get(get_firewall, "outbound") + } + + Hyper.set_vm_firewall(vm_id, firewall) + rescue + e -> + Logger.error("Failed to set firewall: #{Exception.message(e)}") + {:error, :runtime_error} + end +end diff --git a/lib/hyper/http/server/health.ex b/lib/hyper/http/server/health.ex new file mode 100644 index 00000000..910bf1d4 --- /dev/null +++ b/lib/hyper/http/server/health.ex @@ -0,0 +1,63 @@ +defmodule Hyper.Http.Server.Health do + @moduledoc """ + Health checks module. `live/0` only proves a simple health endpoint check. + `ready/0` checks if the system's components are ready to do useful work + """ + + @timeout_limit 1_000 + + @spec ready() :: {:ok | :error, %{:atom => String.t()}} + def ready do + db_and_cluster_checks = checks() + + tasks = + Enum.map(db_and_cluster_checks, fn {_name, fun} -> Task.async(fn -> safe(fun) end) end) + + results = + db_and_cluster_checks + |> Enum.zip(Task.yield_many(tasks, @timeout_limit)) + |> Enum.map(fn + {{name, _}, {_task, {:ok, :up}}} -> + {name, :up} + + {{name, _}, {task, nil}} -> + Task.shutdown(task, :brutal_kill) + {name, :down} + + {{name, _}, _} -> + {name, :down} + end) + + status = if Enum.all?(results, &match?({_, :up}, &1)), do: :ok, else: :error + {status, Map.new(results, fn {name, r} -> {name, Atom.to_string(r)} end)} + end + + defp checks, do: [database: &database_up?/0, cluster: &cluster_active?/0] + + defp database_up? do + case Hyper.Img.Db.Repo.query("SELECT 1", [], timeout: @timeout_limit) do + {:ok, _} -> :up + {:error, _} -> :down + end + end + + defp cluster_active? do + safe(fn -> + alive = + Process.whereis(Hyper.Cluster) != nil and + is_pid(Process.whereis(Hyper.Cluster.Routing.name())) and + is_pid(Process.whereis(Hyper.Cluster.Budget.name())) + + if alive and is_list(Hyper.Cluster.Routing.all()) and + is_list(Hyper.Cluster.Budget.all_states()), do: :up, else: :down + end) + end + + defp safe(fun) do + fun.() + rescue + _ -> :down + catch + _, _ -> :down + end +end diff --git a/mix.exs b/mix.exs index cef90729..eb6df542 100644 --- a/mix.exs +++ b/mix.exs @@ -81,6 +81,7 @@ defmodule Hyper.MixProject do # still use their native lexers; this fills the rest in one dep. {:makeup_syntect, "~> 0.1", only: :dev, runtime: false}, {:ecto_sql, "~> 3.13"}, + {:plug_cowboy, "~> 2.7"}, {:grpc, "~> 1.1"}, {:gun, "~> 2.0"}, {:grpc_server, "~> 1.1"}, diff --git a/mix.lock b/mix.lock index 49367d78..622b1391 100644 --- a/mix.lock +++ b/mix.lock @@ -4,6 +4,7 @@ "castore": {:hex, :castore, "1.0.22", "a01978e6a5d42fa3a34143630588f92036e7d90e2309ecdd466722d1279a2213", [:mix], [], "hexpm", "c2a4d42723b4affbc1c3e15d8f6df3f7d8f1f627c84de643383634cce58493d5"}, "chatterbox": {:hex, :ts_chatterbox, "0.15.1", "5cac4d15dd7ad61fc3c4415ce4826fc563d4643dee897a558ec4ea0b1c835c9c", [:rebar3], [{:hpack, "~> 0.3.0", [hex: :hpack_erl, repo: "hexpm", optional: false]}], "hexpm", "4f75b91451338bc0da5f52f3480fa6ef6e3a2aeecfc33686d6b3d0a0948f31aa"}, "cowboy": {:hex, :cowboy, "2.21.0", "16befcb9b60e81119c2aa5864d33b1494855138c71a2d0c95e4d878d850fde71", [:make, :rebar3], [{:cowlib, ">= 2.22.0 and < 3.0.0", [hex: :cowlib, repo: "hexpm", optional: false]}, {:ranch, ">= 1.8.0 and < 3.0.0", [hex: :ranch, repo: "hexpm", optional: false]}], "hexpm", "90b4d6fe91806054538349dbeabcac86315a3fdaec4eb491f5445259668398f6"}, + "cowboy_telemetry": {:hex, :cowboy_telemetry, "0.4.0", "f239f68b588efa7707abce16a84d0d2acf3a0f50571f8bb7f56a15865aae820c", [:rebar3], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "7d98bac1ee4565d31b62d59f8823dfd8356a169e7fcbb83831b8a5397404c9de"}, "cowlib": {:hex, :cowlib, "2.22.0", "ed32663b11e0b96c4fc2e7d42cf627cd095f006e78a24d0c6b98a91f2e532cd3", [:make, :rebar3], [], "hexpm", "b1ea5995d8f1ab5086ae7afe710c2075c7872c7e1acaf45dd0db7595e900c0fc"}, "credo": {:hex, :credo, "1.7.19", "cc52129665fc7c15143d47838fda0f9cd6dac9ceced7bf4da6f85fcbfe64b12a", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "2d8bc95d5a7bb99dd2613621d4f08c6a3575c3fd4b62e6a2b48a100352a557b8"}, "ctx": {:hex, :ctx, "0.6.0", "8ff88b70e6400c4df90142e7f130625b82086077a45364a78d208ed3ed53c7fe", [:rebar3], [], "hexpm", "a14ed2d1b67723dbebbe423b28d7615eb0bdcba6ff28f2d1f1b0a7e1d4aa5fc2"}, @@ -56,6 +57,9 @@ "opentelemetry_ecto": {:hex, :opentelemetry_ecto, "1.2.0", "2382cb47ddc231f953d3b8263ed029d87fbf217915a1da82f49159d122b64865", [:mix], [{:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}, {:opentelemetry_process_propagator, "~> 0.2", [hex: :opentelemetry_process_propagator, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "70dfa2e79932e86f209df00e36c980b17a32f82d175f0068bf7ef9a96cf080cf"}, "opentelemetry_exporter": {:hex, :opentelemetry_exporter, "1.10.0", "972e142392dbfa679ec959914664adefea38399e4f56ceba5c473e1cabdbad79", [:rebar3], [{:grpcbox, ">= 0.0.0", [hex: :grpcbox, repo: "hexpm", optional: false]}, {:opentelemetry, "~> 1.7.0", [hex: :opentelemetry, repo: "hexpm", optional: false]}, {:opentelemetry_api, "~> 1.5.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}, {:tls_certificate_check, "~> 1.18", [hex: :tls_certificate_check, repo: "hexpm", optional: false]}], "hexpm", "33a116ed7304cb91783f779dec02478f887c87988077bfd72840f760b8d4b952"}, "opentelemetry_process_propagator": {:hex, :opentelemetry_process_propagator, "0.3.0", "ef5b2059403a1e2b2d2c65914e6962e56371570b8c3ab5323d7a8d3444fb7f84", [:mix, :rebar3], [{:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}], "hexpm", "7243cb6de1523c473cba5b1aefa3f85e1ff8cc75d08f367104c1e11919c8c029"}, + "plug": {:hex, :plug, "1.20.4", "8fca521b31eb586dbb91968dd9fa95be6b60fb40f9ca77b005361e06836aed75", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "96ee42c0b8b35bcb14e3e65afb85abe9bb7745a8576e8c602802bbb01e5acf72"}, + "plug_cowboy": {:hex, :plug_cowboy, "2.9.0", "87e21e0d9054ced99c36d128f49e3ea2cd8b745fffb97de50bff99706087af4f", [:mix], [{:cowboy, "~> 2.7", [hex: :cowboy, repo: "hexpm", optional: false]}, {:cowboy_telemetry, "~> 0.3", [hex: :cowboy_telemetry, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}], "hexpm", "2002bafba4f3a45b55a58e68d70211b153a7ed18d37edb1ceb6e96e7a92c422e"}, + "plug_crypto": {:hex, :plug_crypto, "2.2.1", "bd1d0358a2e2f5ffb818217e64c394f9d24ed191d862b7fa1bcce264ace2b8ea", [:mix], [], "hexpm", "4417ccbd8f85e627321cd07d2ab9c4b621f1fd883b9905af241f9b4b780b94b6"}, "postgrex": {:hex, :postgrex, "0.22.2", "4aec14df2a72722aee92492566edbeeb44e233ecb86b1915d03136297ef1385d", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "8946382ddb06294f56026ac4278b3cc212bac8a2c82ed68b4087819ed1abc53b"}, "protobuf": {:hex, :protobuf, "0.17.1", "5c058a4abbdf3c094bbdab142022b22950dd25214fcfdc624ae9bf0c60f9346f", [:mix], [{:jason, "~> 1.2", [hex: :jason, repo: "hexpm", optional: true]}], "hexpm", "76770ecda0ef057e540932f15b5a143ba8877875e88727f53429a7dc4dbf8b6c"}, "ranch": {:hex, :ranch, "2.4.0", "1552c523119cfb8dda7f171f02f664805ab08d89d2a18adfa8992676184d767a", [:make, :rebar3], [], "hexpm", "64d98b8c61d39b7b9a2e2cf92ae659b8623a69766f415ae13dc726864ec04ab9"}, diff --git a/native/suidhelper/.gitignore b/native/suidhelper/.gitignore index 0e2baff8..30752340 100644 --- a/native/suidhelper/.gitignore +++ b/native/suidhelper/.gitignore @@ -2,3 +2,4 @@ # LLVM source-based coverage drops these at the crate root during instrumented # test runs (see the xtask coverage pipeline); they are never committed. *.profraw +*.idea diff --git a/test/hyper/cfg/http_test.exs b/test/hyper/cfg/http_test.exs new file mode 100644 index 00000000..fd19e33f --- /dev/null +++ b/test/hyper/cfg/http_test.exs @@ -0,0 +1,55 @@ +defmodule Hyper.Cfg.HttpTest do + @moduledoc """ + test: TOML coercion, pass-through, plaintext default. + """ + use ExUnit.Case, async: false + + alias Hyper.Cfg.Http + alias Hyper.Cfg.Toml + + setup do + Application.delete_env(:hyper, Grpc) + Toml.put_cache(%{}) + + on_exit(fn -> + Application.delete_env(:hyper, Grpc) + Toml.reload() + end) + + :ok + end + + test "an [http_server] toml tables loads each key value pairing correctly" do + Toml.put_cache(%{ + "http_server" => %{ + "enabled" => true, + "port" => 8080, + "options" => %{"ip" => "127.0.0.2"} + } + }) + + config = Http.load() + + assert config.enabled == true + assert config.port == 8080 + + %{"ip" => ip} = config.http_server_opts + assert ip == "127.0.0.2" + end + + test "server_options adds default values when Http Config is empty" do + server_options = Http.server_options(%Http{}) + + assert server_options[:options][:ip] == {127, 0, 0, 1} + assert server_options[:options][:port] == 8081 + end + + test "config carries server options through" do + config = %Http{port: 8082, http_server_opts: [ip: {0, 0, 0, 1}]} + + opts = Http.server_options(config) + + assert opts[:options][:port] == 8082 + assert opts[:options][:ip] == {0, 0, 0, 1} + end +end diff --git a/test/hyper/http/router_test.exs b/test/hyper/http/router_test.exs new file mode 100644 index 00000000..b3932580 --- /dev/null +++ b/test/hyper/http/router_test.exs @@ -0,0 +1,125 @@ +defmodule Hyper.Http.RouterTest do + use ExUnit.Case, async: true + import Plug.Test + + alias Hyper.Http.Router + + @opts Router.init([]) + + setup do + previous = Application.get_env(:hyper, Hyper.Http.Server) + on_exit(fn -> Application.put_env(:hyper, Hyper.Http.Server, previous) end) + :ok + end + + test "Hyper System is live" do + conn = + :get + |> conn("/health") + |> Router.call(@opts) + + assert conn.state == :sent + assert conn.status == 200 + end + + test "Hyper System is ready: database and cluster are up" do + Application.put_env(:hyper, Hyper.Http.Server, + ready: fn -> {:ok, %{"database" => "up", "cluster" => "up"}} end + ) + + conn = + :get + |> conn("/ready") + |> Router.call(@opts) + + assert conn.status == 200 + + assert Jason.decode!(conn.resp_body) == %{ + "status" => "Hyper System DB and Cluster are ready" + } + end + + test "Hyper System is not ready: database is down and cluster is up" do + Application.put_env(:hyper, Hyper.Http.Server, + ready: fn -> {:error, %{"database" => "down", "cluster" => "up"}} end + ) + + conn = + :get + |> conn("/ready") + |> Router.call(@opts) + + assert conn.status == 503 + + assert Jason.decode!(conn.resp_body) == %{ + "status" => "Hyper System DB and Cluster not ready, Please try again later" + } + end + + test "Hyper System is not ready: database is up and cluster is down" do + Application.put_env(:hyper, Hyper.Http.Server, + ready: fn -> {:error, %{"database" => "up", "cluster" => "down"}} end + ) + + conn = + :get + |> conn("/ready") + |> Router.call(@opts) + + assert conn.status == 503 + + assert Jason.decode!(conn.resp_body) == %{ + "status" => "Hyper System DB and Cluster not ready, Please try again later" + } + end + + test "returns 404" do + conn = + :get + |> conn("/missing", "") + |> Router.call(@opts) + + assert conn.state == :sent + assert conn.status == 404 + end + + test "/v1/vms returns the page as JSON" do + Application.put_env(:hyper, Hyper.Http.Server, + list_vms: fn + 2, "tok" -> {:ok, [%{vm_id: "vm-1", node: "node_a"}], "next"} + _, _ -> {:ok, [], ""} + end + ) + + conn = + :get + |> conn("/v1/vms?page_size=2&page_token=tok") + |> Router.call(@opts) + + assert conn.status == 200 + + assert Jason.decode!(conn.resp_body) == %{ + "vms" => [%{"vm_id" => "vm-1", "node" => "node_a"}], + "next_page_token" => "next" + } + end + + test "/v1/vms returns 400" do + Application.put_env(:hyper, Hyper.Http.Server, + list_vms: fn + 2, "bogus_token" -> {:error, :bad_page_token} + _, _ -> {:ok, [], ""} + end + ) + + conn = + :get + |> conn("/v1/vms?page_token=bogus") + |> Router.call(@opts) + + assert conn.status == 400 + assert Jason.decode!(conn.resp_body) == %{"error" => "bad_page_token"} + end + + # test for post errors +end diff --git a/test/hyper/http/server_test.exs b/test/hyper/http/server_test.exs new file mode 100644 index 00000000..77a8953a --- /dev/null +++ b/test/hyper/http/server_test.exs @@ -0,0 +1,4 @@ +defmodule Hyper.Http.ServerTest do + use ExUnit.Case, async: true + import Plug.Test +end