Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save storage device info of the footages #330

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
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
13 changes: 7 additions & 6 deletions apps/ex_nvr/lib/ex_nvr/model/run.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@ defmodule ExNVR.Model.Run do
start_date: DateTime.t() | nil,
end_date: DateTime.t() | nil,
active: boolean(),
device_id: binary() | nil
device_id: binary() | nil,
disk_id: binary() | nil
}

@foreign_key_type :binary_id
schema "runs" do
field(:start_date, :utc_datetime_usec)
field(:end_date, :utc_datetime_usec)
field(:active, :boolean, default: false)
field :start_date, :utc_datetime_usec
field :end_date, :utc_datetime_usec
field :active, :boolean, default: false

belongs_to :device, ExNVR.Model.Device
belongs_to :device, ExNVR.Model.Device, references: :binary_id, type: :string
belongs_to :disk, ExNVR.SystemInformation.Disk, references: Ecto.UUID, type: :string
end

def deactivate_query(device_id) do
Expand Down
2 changes: 1 addition & 1 deletion apps/ex_nvr/lib/ex_nvr/pipeline/output/storage.ex
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ defmodule ExNVR.Pipeline.Output.Storage do
state.run
| end_date: Membrane.Time.to_datetime(segment.end_date),
active: not end_run?
}
},
}
end

Expand Down
18 changes: 17 additions & 1 deletion apps/ex_nvr/lib/ex_nvr/recordings.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ defmodule ExNVR.Recordings do
alias Ecto.Multi
alias ExNVR.Model.{Device, Recording, Run}
alias ExNVR.Repo
alias ExNVR.SystemInformation.Disks
alias Phoenix.PubSub

@recordings_topic "recordings"
Expand All @@ -23,9 +24,17 @@ defmodule ExNVR.Recordings do
|> Map.put(:filename, recording_path(device, params) |> Path.basename())
|> Recording.changeset()

disk_id =
device
|> maybe_get_disk_info()
|> case do
{:ok, disk} -> disk.id
_other -> nil
end

Multi.new()
|> Multi.insert(:recording, recording_changeset)
|> Multi.insert(:run, run, on_conflict: {:replace_all_except, [:start_date]})
|> Multi.insert(:run, %Run{run | disk_id: disk_id}, on_conflict: {:replace_all_except, [:start_date]})
|> Repo.transaction()
|> case do
{:ok, %{recording: recording, run: run}} ->
Expand Down Expand Up @@ -139,4 +148,11 @@ defmodule ExNVR.Recordings do
defp broadcast_recordings_event(event) do
PubSub.broadcast(ExNVR.PubSub, @recordings_topic, {event, nil})
end

defp maybe_get_disk_info(%Device{settings: %Device.Settings{storage_address: storage_address}}) do
storage_address
|> Disks.list_available_disks()
|> List.first(%{})
|> Disks.create()
end
end
42 changes: 42 additions & 0 deletions apps/ex_nvr/lib/ex_nvr/system_information/disk.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
defmodule ExNVR.SystemInformation.Disk do
@moduledoc """
A module representing a storage device: HDD, SSD, memory card, ...etc.
"""

use Ecto.Schema

alias Ecto.Changeset

@type t :: %__MODULE__{
id: binary(),
vendor: binary() | nil,
model: binary(),
serial: binary(),
type: binary() | nil,
size: integer(),
transport: binary() | nil,
hotplug: boolean() | nil,
inserted_at: DateTime.t() | nil,
updated_at: DateTime.t() | nil
}

@primary_key {:id, Ecto.UUID, autogenerate: false}
schema "storage_devices" do
field :vendor, :string
field :model, :string
field :serial, :string
field :type, :string
field :size, :integer
field :transport, :string
field :hotplug, :boolean, default: false

timestamps(type: :utc_datetime_usec)
end

@spec changeset(map()) :: Changeset.t()
def changeset(params) do
%__MODULE__{}
|> Changeset.cast(params, __MODULE__.__schema__(:fields))
|> Changeset.validate_required([:model, :serial, :size])
end
end
138 changes: 138 additions & 0 deletions apps/ex_nvr/lib/ex_nvr/system_information/disks.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
defmodule ExNVR.SystemInformation.Disks do
@moduledoc """
A module to get available disks on the machine using external utilities.

Currently only `linux` machines are supported with the use of [lsblk](https://man7.org/linux/man-pages/man8/lsblk.8.html).
"""

@manufacturers [
{~r/WESTERN.*/, "Western Digital"},
{~r/^WDC.*/, "Western Digital"},
{~r/"WD.*/, "Western Digital"},
{~r/"TOSHIBA./, "Toshiba"},
{~r/"HITACHI./, "Hitachi"},
{~r/^IC./, "Hitachi"},
{~r/^HTS./, "Hitachi"},
{~r/SANDISK./, "SanDisk"},
{~r/KINGSTON./, "Kingston Technology"},
{~r/^SONY./, "Sony"},
{~r/TRANSCEND./, "Transcend"},
{~r/SAMSUNG./, "Samsung"},
{~r/^ST(?!I\\ )./, "Seagate"},
{~r/^STI\\ ./, "SimpleTech"},
{~r/^D...-./, "IBM"},
{~r/^IBM./, "IBM"},
{~r/^FUJITSU./, "Fujitsu"},
{~r/^MP./, "Fujitsu"},
{~r/^MK./, "Toshiba"},
{~r/MAXTO./, "Maxtor"},
{~r/PIONEER./, "Pioneer"},
{~r/PHILIPS./, "Philips"},
{~r/QUANTUM./, "Quantum Technology"},
{~r/FIREBALL./, "Quantum Technology"},
{~r/^VBOX./, "VirtualBox"},
{~r/CORSAIR./, "Corsair Components"},
{~r/CRUCIAL./, "Crucial"},
{~r/ECM./, "ECM"},
{~r/INTEL./, "INTEL"},
{~r/EVO./, "Samsung"},
{~r/APPLE./, "Apple"}
]

require Logger

alias ExNVR.SystemInformation.Disk

alias ExNVR.Repo

@spec create(map() | Disk.t()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()}
def create(params) do
params
|> Disk.changeset()
|> Repo.insert()
end

def list() do
Repo.all(Disk)
end

@spec list_available_disks(binary() | nil) :: [Disk.t()]
def list_available_disks(mountpoint \\ nil) do
case :os.type() do
{:unix, :linux} ->
list_linux_disks(mountpoint)

_other ->
[]
end
end

defp list_linux_disks(mountpoint) do
with {:ok, data} <- run_lsblk_cmd(),
{:ok, data} <- Jason.decode(data) do
data
|> Map.get("blockdevices", [])
|> Enum.reject(&String.match?(&1["name"], ~r/^(loop|ram)/))
|> maybe_filter_by_mountpoint(mountpoint)
|> Enum.map(&map_linux_device_to_disk/1)
else
{:error, reason} = error ->
Logger.error(inspect(reason))
error
end
end

defp run_lsblk_cmd() do
case System.cmd("lsblk", ["-bJO"], env: [{"LC_ALL", "C"}], stderr_to_stdout: true) do
{data, 0} ->
{:ok, data}

{error, exit_status} ->
error_msg = """
lsblk failed with status: #{exit_status}
#{inspect(error)}
"""

{:error, error_msg}
end
end

defp maybe_filter_by_mountpoint(devices, nil), do: devices

defp maybe_filter_by_mountpoint(devices, mountpoint) do
Enum.filter(devices, fn device ->
device["mountpoint"] == mountpoint or
Enum.any?(device["children"] || [], &(&1["mountpoint"] == mountpoint))
end)
end

defp map_linux_device_to_disk(device) do
%{
id: device["uuid"],
vendor: get_vendor(device),
model: device["model"],
serial: device["serial"],
size: device["size"],
type: get_disk_type(device),
transport: device["tran"],
hotplug: device["hotplug"]
}
end

defp get_vendor(device) do
model = String.upcase("#{device["model"]}")
default_value = String.trim("#{device["vendor"]}")

Enum.find_value(@manufacturers, default_value, fn {pattern, manufacturer} ->
if String.match?(model, pattern), do: manufacturer
end)
end

defp get_disk_type(device) do
cond do
device["rota"] -> "HDD"
device["tran"] == "nvme" -> "NVMe"
true -> "SSD"
end
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
defmodule ExNVR.Repo.Migrations.AddDiskSystemInformation do
use Ecto.Migration

def change do
create table("storage_devices", primary_key: false) do
add :id, :uuid, primary_key: true, null: false
add :vendor, :string
add :model, :string, null: false
add :serial, :string, null: false
add :type, :string
add :size, :integer, null: false
add :transport, :string
add :hotplug, :boolean

timestamps(type: :utc_datetime_usec)
end

alter table("runs") do
add :disk_id, references("storage_devices", on_delete: :delete_all)
end
end
end
12 changes: 12 additions & 0 deletions apps/ex_nvr_web/lib/ex_nvr_web/controllers/api/disk_controller.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
defmodule ExNVRWeb.API.DiskController do
use ExNVRWeb, :controller

alias Plug.Conn
alias ExNVR.SystemInformation.Disks

def list(%Conn{} = conn, _params) do
conn
|> put_status(200)
|> json(%{disks: Disks.list()})
end
end
2 changes: 2 additions & 0 deletions apps/ex_nvr_web/lib/ex_nvr_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ defmodule ExNVRWeb.Router do
scope "/api", ExNVRWeb do
pipe_through :api

get "/system-information/disks", API.DiskController, :list

post "/users/login", API.UserSessionController, :login

scope "/devices/:device_id" do
Expand Down