Skip to content
Draft
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
29 changes: 29 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -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
Comment on lines +2 to +4

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// 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"
]
}
]
}
2 changes: 2 additions & 0 deletions docs/cookbook/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ cred = { cert = "/etc/hyper/tls/cert.pem", key = "/etc/hyper/tls/key.pem" }
```
<!-- tabs close -->

# add server config here

## Telemetry Configuration

You can configure telemetry with Hyper by adding this section to your
Expand Down
2 changes: 1 addition & 1 deletion lib/hyper/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
96 changes: 96 additions & 0 deletions lib/hyper/cfg/http.ex
Original file line number Diff line number Diff line change
@@ -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
22 changes: 22 additions & 0 deletions lib/hyper/http.ex
Original file line number Diff line number Diff line change
@@ -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
57 changes: 57 additions & 0 deletions lib/hyper/http/plugs/verify_request.ex
Original file line number Diff line number Diff line change
@@ -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
Loading