16
1

More than 1 year has passed since last update.

Elixir IEx.Helpers.runtime_info/0でシステムの状態を知る

Last updated at Posted at 2022-11-12

Elixirを実行しているシステムの状態について知りたいときは、IEx.Helpers.runtime_info/0が便利です。

  • Elixir 1.12で追加された関数、削除された関数をコード上で確認する
  • Elixirバージョンごとにノードをたてて、:application.get_key/2の結果を比較する
  • ノードは別々のDockerコンテナから起動する

論よりRUN

IExを起動します。

iex

runtime_info/0関数を呼びます。

runtime_info

:tada: 以上!

ソースコードから学ぶ

IEx.Helpers.runtime_info/0のソースコードを読んでみるとどこからどのように情報を仕入れているのかわかります。アイデアも満載です。

Elixir言語作者のJosé Valimさんが書かれたコードなので、お手本中のお手本と言えるでしょう。

System and architecture

System.version()
System.otp_release()
:erlang.system_info(:version)
:erlang.system_info(:system_architecture)
:erlang.system_info(:schedulers)
:erlang.system_info(:schedulers_online)

Memory

  • メモリの値を変換するコードがめっちゃ簡潔に綺麗に書かれています。
  • format_bytes/1からformat_bytes/2への2段階の処理が面白いです。
  • memory_unit/1を(定数にせず)あえて関数にしている発想が参考になります。
defmodule MyFormatter do
  def format_bytes(bytes) when is_integer(bytes) do
    cond do
      bytes >= memory_unit(:GB) -> format_bytes(bytes, :GB)
      bytes >= memory_unit(:MB) -> format_bytes(bytes, :MB)
      bytes >= memory_unit(:KB) -> format_bytes(bytes, :KB)
      true -> format_bytes(bytes, :B)
    end
  end

  def format_bytes(bytes, unit) when is_integer(bytes) and unit in [:GB, :MB, :KB] do
    value =
      bytes
      |> div(memory_unit(unit))
      |> round()
    "#{value} #{unit}"
  end

  def format_bytes(bytes, :B) when is_integer(bytes), do: "#{bytes} B"

  defp memory_unit(:GB), do: 1024 * 1024 * 1024
  defp memory_unit(:MB), do: 1024 * 1024
  defp memory_unit(:KB), do: 1024
end

MyFormatter.format_bytes(:erlang.memory(:total))
MyFormatter.format_bytes(:erlang.memory(:atom))
MyFormatter.format_bytes(:erlang.memory(:binary))
MyFormatter.format_bytes(:erlang.memory(:code))
MyFormatter.format_bytes(:erlang.memory(:ets))
MyFormatter.format_bytes(:erlang.memory(:processes))

Statistics / limits

:c.uptime()

:erlang.statistics(:run_queue)

print_percentage = fn min, max ->
  percentage = trunc(min / max * 100)
  IO.puts("#{min} / #{max} (#{percentage}% used)")
end

min = :erlang.system_info(:atom_count)
max = :erlang.system_info(:atom_limit)
print_percentage.(min, max)

min = :erlang.system_info(:ets_count)
max = :erlang.system_info(:ets_limit)
print_percentage.(min, max)

min = :erlang.system_info(:port_count)
max = :erlang.system_info(:port_limit)
print_percentage.(min, max)

Phoenix LiveDashboard

Phoenix LiveDashboardにも似たようなものがあります。

ご参考までに

16
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
1