meta/lib/recycledcloud_web/controllers/virtual_machine_hosting_con...

59 lines
1.8 KiB
Elixir

defmodule RecycledCloudWeb.VirtualMachineHostingController do
use RecycledCloudWeb, :controller
alias RecycledCloud.OpenNebula.VM
def index(conn, _params) do
username = conn.assigns.current_user.username
vms = VM.get_by_username(username)
render(conn, "index.html", vms: vms)
end
def start(conn, %{"id" => id}) do
case VM.execute(String.to_integer(id), "resume") do
:ok ->
conn
|> put_flash(:info, "Start request sent to VMM.")
|> redirect(to: Routes.virtual_machine_hosting_path(conn, :index))
{:error, err} ->
conn
|> put_flash(:error, "Something went wrong: #{inspect(err)}")
|> redirect(to: Routes.virtual_machine_hosting_path(conn, :index))
end
end
def stop(conn, %{"id" => id}) do
case VM.execute(String.to_integer(id), "poweroff") do
:ok ->
conn
|> put_flash(:stop, "Stop request sent to VMM.")
|> redirect(to: Routes.virtual_machine_hosting_path(conn, :index))
{:error, err} ->
conn
|> put_flash(:error, "Something went wrong: #{inspect(err)}")
|> redirect(to: Routes.virtual_machine_hosting_path(conn, :index))
end
end
def show(conn, %{"id" => id}) do
case VM.get(String.to_integer(id)) do
{:error, err} ->
conn
|> put_flash(:error, "Could not fetch VM details: #{inspect(err)}")
|> redirect(to: Routes.virtual_machine_hosting_path(conn, :index))
{:ok, vm} ->
owner = vm |> Map.get(:UNAME) |> List.to_string
if owner == conn.assigns.current_user.username do
conn
|> assign(:vm, vm)
|> render("show.html")
else
conn
|> put_flash(:error, "You are not the owner of this machine.")
|> redirect(to: Routes.virtual_machine_hosting_path(conn, :index))
end
end
end
end