1## This Source Code Form is subject to the terms of the Mozilla Public
2## License, v. 2.0. If a copy of the MPL was not distributed with this
3## file, You can obtain one at https://mozilla.org/MPL/2.0/.
4##
5## Copyright (c) 2007-2021 VMware, Inc. or its affiliates.  All rights reserved.
6
7defmodule RabbitMQ.CLI.Diagnostics.Commands.CheckVirtualHostsCommand do
8  @moduledoc """
9  Exits with a non-zero code if the target node reports any vhost down.
10
11  This command is meant to be used in health checks.
12  """
13
14  import RabbitMQ.CLI.Core.Platform, only: [line_separator: 0]
15
16  @behaviour RabbitMQ.CLI.CommandBehaviour
17
18  use RabbitMQ.CLI.Core.AcceptsDefaultSwitchesAndTimeout
19  use RabbitMQ.CLI.Core.MergesNoDefaults
20  use RabbitMQ.CLI.Core.AcceptsNoPositionalArguments
21  use RabbitMQ.CLI.Core.RequiresRabbitAppRunning
22
23  def run([], %{node: node_name, timeout: timeout}) do
24    :rabbit_misc.rpc_call(node_name, :rabbit_vhost_sup_sup, :check, [], timeout)
25  end
26
27  def output([], %{formatter: "json"}) do
28    {:ok, %{"result" => "ok"}}
29  end
30
31  def output([], %{silent: true}) do
32    {:ok, :check_passed}
33  end
34
35  def output([], %{formatter: "erlang"}) do
36    {:ok, :check_passed}
37  end
38
39  def output([], %{node: node_name}) do
40    {:ok, "Node #{node_name} reported all vhosts as running"}
41  end
42
43  def output(vhosts, %{formatter: "erlang"} = _opts) when is_list(vhosts) do
44    {:error, :check_failed, {:down_vhosts, vhosts}}
45  end
46
47  def output(vhosts, %{formatter: "json"} = _opts) when is_list(vhosts) do
48    {:error, :check_failed, %{"result" => "error", "down_vhosts" => vhosts}}
49  end
50
51  def output(vhosts, %{silent: true} = _opts) when is_list(vhosts) do
52    {:error, :check_failed}
53  end
54
55  def output(vhosts, %{node: node_name}) when is_list(vhosts) do
56    lines = Enum.join(vhosts, line_separator())
57    {:error, "Some virtual hosts on node #{node_name} are down:\n#{lines}"}
58  end
59
60  use RabbitMQ.CLI.DefaultOutput
61
62  def description(), do: "Health check that checks if all vhosts are running in the target node"
63
64  def help_section(), do: :observability_and_health_checks
65
66  def usage, do: "check_virtual_hosts"
67
68  def banner([], %{node: node_name}) do
69    "Checking if all vhosts are running on node #{node_name} ..."
70  end
71end
72