├── lib ├── pogo.ex └── pogo │ └── dynamic_supervisor.ex ├── test ├── test_helper.exs ├── support │ ├── pogo │ │ └── worker.ex │ └── assert_async.ex └── pogo │ └── dynamic_supervisor_test.exs ├── .formatter.exs ├── CHANGELOG.md ├── test_app ├── lib │ └── test_app │ │ └── application.ex └── mix.exs ├── .gitignore ├── test_app_with_children ├── mix.exs └── lib │ └── test_app_with_children │ └── application.ex ├── .github └── workflows │ └── build.yml ├── mix.exs ├── README.md ├── mix.lock └── LICENSE /lib/pogo.ex: -------------------------------------------------------------------------------- 1 | defmodule Pogo do 2 | @moduledoc false 3 | end 4 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | :ok = LocalCluster.start() 2 | 3 | ExUnit.start() 4 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: [ 4 | "{mix,.formatter}.exs", 5 | "{config,lib,test,test_app,test_app_with_children}/**/*.{ex,exs}" 6 | ] 7 | ] 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.3.0 4 | 5 | * Accept list of children to be started when supervisor starts. https://github.com/team-telnyx/pogo/pull/1 6 | 7 | ## 0.2.0 8 | 9 | * Rework internal process lifecycle to improve reliability of process termination. 10 | 11 | ## 0.1.0 12 | 13 | Initial release. 14 | -------------------------------------------------------------------------------- /test/support/pogo/worker.ex: -------------------------------------------------------------------------------- 1 | defmodule Pogo.Worker do 2 | @moduledoc false 3 | 4 | use GenServer 5 | 6 | def child_spec(id) do 7 | %{ 8 | id: {__MODULE__, id}, 9 | start: {__MODULE__, :start_link, [id]} 10 | } 11 | end 12 | 13 | def start_link(id) do 14 | GenServer.start_link(__MODULE__, id) 15 | end 16 | 17 | def get_id(pid) do 18 | GenServer.call(pid, :id) 19 | end 20 | 21 | @impl true 22 | def init(id) do 23 | {:ok, id} 24 | end 25 | 26 | @impl true 27 | def handle_call(:id, _from, id) do 28 | {:reply, id, id} 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /test_app/lib/test_app/application.ex: -------------------------------------------------------------------------------- 1 | defmodule TestApp.Application do 2 | # See https://hexdocs.pm/elixir/Application.html 3 | # for more information on OTP Applications 4 | @moduledoc false 5 | 6 | use Application 7 | 8 | @impl true 9 | def start(_type, _args) do 10 | children = [ 11 | {Pogo.DynamicSupervisor, 12 | name: PogoTest.DistributedSupervisor, scope: :test, sync_interval: 100} 13 | ] 14 | 15 | # See https://hexdocs.pm/elixir/Supervisor.html 16 | # for other strategies and supported options 17 | opts = [strategy: :one_for_one, name: TestApp.Supervisor] 18 | Supervisor.start_link(children, opts) 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | pogo-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /test_app/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule TestApp.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :test_app, 7 | version: "0.1.0", 8 | elixir: "~> 1.11", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps() 11 | ] 12 | end 13 | 14 | # Run "mix help compile.app" to learn about applications. 15 | def application do 16 | [ 17 | extra_applications: [:logger], 18 | mod: {TestApp.Application, []} 19 | ] 20 | end 21 | 22 | # Run "mix help deps" to learn about dependencies. 23 | defp deps do 24 | [ 25 | # {:dep_from_hexpm, "~> 0.3.0"}, 26 | # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} 27 | ] 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test_app_with_children/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule TestAppWithChildren.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :test_app_with_children, 7 | version: "0.1.0", 8 | elixir: "~> 1.11", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps() 11 | ] 12 | end 13 | 14 | # Run "mix help compile.app" to learn about applications. 15 | def application do 16 | [ 17 | extra_applications: [:logger], 18 | mod: {TestAppWithChildren.Application, []} 19 | ] 20 | end 21 | 22 | # Run "mix help deps" to learn about dependencies. 23 | defp deps do 24 | [ 25 | # {:dep_from_hexpm, "~> 0.3.0"}, 26 | # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} 27 | ] 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test_app_with_children/lib/test_app_with_children/application.ex: -------------------------------------------------------------------------------- 1 | defmodule TestAppWithChildren.Application do 2 | # See https://hexdocs.pm/elixir/Application.html 3 | # for more information on OTP Applications 4 | @moduledoc false 5 | 6 | use Application 7 | 8 | @impl true 9 | def start(_type, _args) do 10 | children = [ 11 | {Pogo.DynamicSupervisor, 12 | name: PogoTest.DistributedSupervisor, 13 | scope: :test, 14 | sync_interval: 100, 15 | children: [ 16 | Pogo.Worker.child_spec(1), 17 | Pogo.Worker.child_spec(2), 18 | {Pogo.Worker, 3} 19 | ]} 20 | ] 21 | 22 | # See https://hexdocs.pm/elixir/Supervisor.html 23 | # for other strategies and supported options 24 | opts = [strategy: :one_for_one, name: TestAppWithChildren.Supervisor] 25 | Supervisor.start_link(children, opts) 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and test 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | name: "mix test (otp-${{matrix.otp}}, elixir-${{matrix.elixir}})" 15 | runs-on: ubuntu-latest 16 | 17 | env: 18 | MIX_ENV: test 19 | 20 | strategy: 21 | matrix: 22 | include: 23 | - elixir: 1.12.3 24 | otp: 24.3 25 | 26 | - elixir: 1.13.4 27 | otp: 24.3 28 | 29 | - elixir: 1.13.4 30 | otp: 25.3 31 | 32 | - elixir: 1.14.3 33 | otp: 24.3 34 | 35 | - elixir: 1.14.3 36 | otp: 25.3 37 | 38 | steps: 39 | - name: Checkout 40 | uses: actions/checkout@v3 41 | 42 | - name: Set up Elixir 43 | uses: erlef/setup-beam@v1 44 | with: 45 | otp-version: ${{matrix.otp}} 46 | elixir-version: ${{matrix.elixir}} 47 | 48 | - name: Install dependencies 49 | run: mix deps.get 50 | 51 | - name: Start EPMD 52 | run: epmd -daemon 53 | 54 | - name: Run credo check 55 | run: mix credo 56 | 57 | - name: Run tests 58 | run: mix test 59 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Pogo.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :pogo, 7 | version: "0.3.0", 8 | elixir: "~> 1.11", 9 | elixirc_paths: elixirc_paths(Mix.env()), 10 | start_permanent: Mix.env() == :prod, 11 | deps: deps(), 12 | package: package(), 13 | source_url: "https://github.com/team-telnyx/pogo", 14 | description: description(), 15 | name: "Pogo", 16 | docs: docs(), 17 | aliases: [ 18 | test: "test --no-start" 19 | ] 20 | ] 21 | end 22 | 23 | # Run "mix help compile.app" to learn about applications. 24 | def application do 25 | [ 26 | extra_applications: [:logger] 27 | ] 28 | end 29 | 30 | # Run "mix help deps" to learn about dependencies. 31 | defp deps do 32 | [ 33 | {:libring, "~> 1.6.0"}, 34 | {:local_cluster, "~> 1.2.1", only: [:test]}, 35 | {:test_app, path: "test_app", only: [:test]}, 36 | {:test_app_with_children, path: "test_app_with_children", only: [:test]}, 37 | {:ex_doc, "~> 0.29", only: [:dev], runtime: false}, 38 | {:credo, "~> 1.7", only: [:dev, :test], runtime: false} 39 | ] 40 | end 41 | 42 | defp description do 43 | """ 44 | Distributed supervisor for clustered Elixir applications 45 | """ 46 | end 47 | 48 | defp package do 49 | [ 50 | maintainers: ["Michał Szajbe "], 51 | licenses: ["LGPL-3.0-or-later"], 52 | links: %{"GitHub" => "https://github.com/team-telnyx/pogo"}, 53 | files: ~w"lib mix.exs README.md LICENSE" 54 | ] 55 | end 56 | 57 | defp docs do 58 | [ 59 | main: "readme", 60 | extras: ["README.md", "LICENSE"] 61 | ] 62 | end 63 | 64 | defp elixirc_paths(:test), do: ["lib", "test/support"] 65 | defp elixirc_paths(_), do: ["lib"] 66 | end 67 | -------------------------------------------------------------------------------- /test/support/assert_async.ex: -------------------------------------------------------------------------------- 1 | defmodule AssertAsync do 2 | @moduledoc """ 3 | Helper macro for making assertions on async actions. This is particularly 4 | useful for testing GenServers and other processes that may be synchronously 5 | processing messages. The macro will retry an assertion until it passes 6 | or times out. 7 | 8 | ## Example 9 | 10 | defmodule Foo do 11 | use GenServer 12 | 13 | def init(opts) do 14 | {:ok, state, {:continue, :sleep}} 15 | end 16 | 17 | def handle_continue(:sleep, state) do 18 | Process.sleep(2_000) 19 | {:noreply, state} 20 | end 21 | 22 | def handle_call(:bar, _, state) do 23 | Map.get(state, :bar) 24 | end 25 | end 26 | 27 | iex> import AssertAsync 28 | iex {:ok, pid} = GenServer.start_link(Foo, %{bar: 42}) 29 | iex> assert_async do 30 | ...> assert GenServer.call(pid, :bar) == 42 31 | ...> end 32 | 33 | ## Configuration 34 | 35 | * `sleep` - Time in milliseconds to wait before next retry. Defaults to `200`. 36 | * `max_tries` - Number of attempts to make before flunking assertion. Defaults to `10`. 37 | * `debug` - Boolean for producing `DEBUG` messages on failing iterations. Defaults `false`. 38 | """ 39 | 40 | defmodule Impl do 41 | @moduledoc false 42 | require Logger 43 | 44 | @defaults %{ 45 | sleep: 200, 46 | max_tries: 10, 47 | debug: false 48 | } 49 | 50 | def assert(function, opts) do 51 | state = Map.merge(@defaults, Map.new(opts)) 52 | do_assert(function, state) 53 | end 54 | 55 | defp do_assert(function, %{max_tries: 1}) do 56 | function.() 57 | end 58 | 59 | defp do_assert(function, %{max_tries: max_tries} = opts) do 60 | function.() 61 | rescue 62 | e in ExUnit.AssertionError -> 63 | if opts.debug do 64 | Logger.debug(fn -> 65 | "AssertAsync(remaining #{max_tries - 1}): #{ExUnit.AssertionError.message(e)}" 66 | end) 67 | end 68 | 69 | Process.sleep(opts.sleep) 70 | do_assert(function, %{opts | max_tries: max_tries - 1}) 71 | end 72 | end 73 | 74 | defmacro assert_async(opts \\ [], do: do_block) do 75 | quote do 76 | AssertAsync.Impl.assert(fn -> unquote(do_block) end, unquote(opts)) 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pogo 2 | 3 | Pogo is a distributed supervisor for clustered Elixir applications. 4 | 5 | It uses battle-tested distributed named process groups (`:pg`) under the hood to maintain cluster-wide state and coordinate work between local supervisors running on different nodes. 6 | 7 | Features of distributed supervisor: 8 | 9 | * automatically chooses a node to locally supervise child process 10 | * a child process running in the cluster can be started or stopped using any local supervisor 11 | * ensures a child is started only once in the cluster (as long as its child spec is unique) 12 | * redistibutes children when cluster topology changes 13 | 14 | You can read more in an [introductory article](https://szajbus.dev/elixir/2023/05/22/pogo-distributed-supervisor-for-elixir.html). 15 | 16 | ## Installation 17 | 18 | The package can be installed by adding `pogo` to your list of dependencies in `mix.exs`: 19 | 20 | ```elixir 21 | def deps do 22 | [ 23 | {:pogo, "~> 0.3.0"} 24 | ] 25 | end 26 | ``` 27 | 28 | ## Documentation 29 | 30 | Full documentation can be found at [hexdocs.pm/pogo](https://hexdocs.pm/pogo). 31 | 32 | ## Example usage 33 | 34 | Let's imagine we have an application running on multiple nodes that needs to monitor some external services and we want each of these services to be monitored only once. 35 | 36 | Start `Pogo.DynamicSupervisor` under application's supervision tree, locally on each node. All these local supervisors will form a distributed supervisor named `MyApp.DistributedSupervisor`. 37 | 38 | ```elixir 39 | defmodule MyApp.Application do 40 | use Application 41 | 42 | @impl true 43 | def start(_type, _args) do 44 | children = [ 45 | {Pogo.DynamicSupervisor, [name: MyApp.DistributedSupervisor, scope: :my_app]} 46 | ] 47 | 48 | Supervisor.start_link(children, strategy: :one_for_one) 49 | end 50 | end 51 | ``` 52 | 53 | Now request service monitor processes to be started as children of our distributed supervisor. It can be done on any of the nodes or even on all of them, the distributed supervisor will determine which of the local ones will actually start each child. 54 | 55 | ```elixir 56 | for service_ip <- ["10.0.0.1", "10.0.0.2", "10.0.0.3"] do 57 | Pogo.DynamicSupervisor.start_child( 58 | MyApp.DistributedSupervisor, 59 | %{ 60 | id: {MyApp.ServiceMonitor, service_ip}, 61 | start: {MyApp.ServiceMonitor, :start_link, [ip: service_ip]} 62 | } 63 | ) 64 | end 65 | ``` 66 | 67 | We can list locally and globally supervised child processes. 68 | 69 | ```elixir 70 | Pogo.DynamicSupervisor.which_children(MyApp.DistributedSupervisor, :local) 71 | # [{MyApp.ServiceMonitor, "10.0.0.2"}, #PID<0.2010.0>, :worker, [MyApp.ServiceMonitor]] 72 | 73 | Pogo.DynamicSupervisor.which_children(MyApp.DistributedSupervisor, :global) 74 | # [ 75 | # {MyApp.ServiceMonitor, "10.0.0.2"}, #PID<0.2010.0>, :worker, [MyApp.ServiceMonitor], 76 | # {MyApp.ServiceMonitor, "10.0.0.1"}, #PID<4461.199.10>, :worker, [MyApp.ServiceMonitor], 77 | # {MyApp.ServiceMonitor, "10.0.0.3"}, #PID<306.320.94>, :worker, [MyApp.ServiceMonitor] 78 | # ] 79 | ``` 80 | 81 | To request a child to be terminated, its id needs to be provided. The request can be made on any of the nodes irrespective of whether the child is supervised locally or not. 82 | 83 | ```elixir 84 | Pogo.DynamicSupervisor.terminate_child( 85 | MyApp.DistributedSupervisor, 86 | {MyApp.ServiceMonitor, "10.0.0.3"} 87 | ) 88 | ``` 89 | 90 | ## Acknowledgments 91 | 92 | Original version of this library was developed by [Guilherme Balena Versiani](https://github.com/balena). 93 | 94 | ## License 95 | 96 | GNU Lesser General Public License v3.0, see [`LICENSE`](LICENSE) for details. 97 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "assert_eventually": {:hex, :assert_eventually, "1.0.0", "f1539f28ba3ffa99a712433c77723c7103986932aa341d05eee94c333a920d15", [:mix], [{:ex_doc, ">= 0.0.0", [hex: :ex_doc, repo: "hexpm", optional: true]}], "hexpm", "c658ac4103c8bd82d0cf72a2fdb77477ba3fbc6b15228c5c801003d239625c69"}, 3 | "bunt": {:hex, :bunt, "0.2.1", "e2d4792f7bc0ced7583ab54922808919518d0e57ee162901a16a1b6664ef3b14", [:mix], [], "hexpm", "a330bfb4245239787b15005e66ae6845c9cd524a288f0d141c148b02603777a5"}, 4 | "credo": {:hex, :credo, "1.7.0", "6119bee47272e85995598ee04f2ebbed3e947678dee048d10b5feca139435f75", [:mix], [{:bunt, "~> 0.2.1", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2.8", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "6839fcf63d1f0d1c0f450abc8564a57c43d644077ab96f2934563e68b8a769d7"}, 5 | "earmark_parser": {:hex, :earmark_parser, "1.4.31", "a93921cdc6b9b869f519213d5bc79d9e218ba768d7270d46fdcf1c01bacff9e2", [:mix], [], "hexpm", "317d367ee0335ef037a87e46c91a2269fef6306413f731e8ec11fc45a7efd059"}, 6 | "ex_doc": {:hex, :ex_doc, "0.29.3", "f07444bcafb302db86e4f02d8bbcd82f2e881a0dcf4f3e4740e4b8128b9353f7", [:mix], [{:earmark_parser, "~> 1.4.31", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "3dc6787d7b08801ec3b51e9bd26be5e8826fbf1a17e92d1ebc252e1a1c75bfe1"}, 7 | "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, 8 | "global_flags": {:hex, :global_flags, "1.0.0", "ee6b864979a1fb38d1fbc67838565644baf632212bce864adca21042df036433", [:rebar3], [], "hexpm", "85d944cecd0f8f96b20ce70b5b16ebccedfcd25e744376b131e89ce61ba93176"}, 9 | "jason": {:hex, :jason, "1.4.0", "e855647bc964a44e2f67df589ccf49105ae039d4179db7f6271dfd3843dc27e6", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "79a3791085b2a0f743ca04cec0f7be26443738779d09302e01318f97bdb82121"}, 10 | "libring": {:hex, :libring, "1.6.0", "d5dca4bcb1765f862ab59f175b403e356dec493f565670e0bacc4b35e109ce0d", [:mix], [], "hexpm", "5e91ece396af4bce99953d49ee0b02f698cd38326d93cd068361038167484319"}, 11 | "local_cluster": {:hex, :local_cluster, "1.2.1", "8eab3b8a387680f0872eacfb1a8bd5a91cb1d4d61256eec6a655b07ac7030c73", [:mix], [{:global_flags, "~> 1.0", [hex: :global_flags, repo: "hexpm", optional: false]}], "hexpm", "aae80c9bc92c911cb0be085fdeea2a9f5b88f81b6bec2ff1fec244bb0acc232c"}, 12 | "makeup": {:hex, :makeup, "1.1.0", "6b67c8bc2882a6b6a445859952a602afc1a41c2e08379ca057c0f525366fc3ca", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "0a45ed501f4a8897f580eabf99a2e5234ea3e75a4373c8a52824f6e873be57a6"}, 13 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.0", "f8c570a0d33f8039513fbccaf7108c5d750f47d8defd44088371191b76492b0b", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "28b2cbdc13960a46ae9a8858c4bebdec3c9a6d7b4b9e7f4ed1502f8159f338e7"}, 14 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.1", "3fcb7f09eb9d98dc4d208f49cc955a34218fc41ff6b84df7c75b3e6e533cc65f", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "174d0809e98a4ef0b3309256cbf97101c6ec01c4ab0b23e926a9e17df2077cbb"}, 15 | "nimble_parsec": {:hex, :nimble_parsec, "1.2.3", "244836e6e3f1200c7f30cb56733fd808744eca61fd182f731eac4af635cc6d0b", [:mix], [], "hexpm", "c8d789e39b9131acf7b99291e93dae60ab48ef14a7ee9d58c6964f59efb570b0"}, 16 | } 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /test/pogo/dynamic_supervisor_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Pogo.DynamicSupervisorTest do 2 | use ExUnit.Case 3 | import AssertAsync 4 | 5 | @supervisor PogoTest.DistributedSupervisor 6 | 7 | setup do 8 | on_exit(fn -> 9 | # these tests are flaky in CI, sleep below is a naive attempt 10 | # to give nodes enough time to shutdown after the test 11 | :timer.sleep(1000) 12 | end) 13 | 14 | :ok 15 | end 16 | 17 | test "starts child on a single node in the cluster" do 18 | [node1, node2] = start_nodes(:test_app, "foo", 2) 19 | 20 | child_spec = Pogo.Worker.child_spec(1) 21 | 22 | start_child(node1, child_spec) 23 | start_child(node2, child_spec) 24 | 25 | assert_async do 26 | assert %{ 27 | ^node1 => [], 28 | ^node2 => [{{Pogo.Worker, 1}, _, :worker, _}] 29 | } = local_children([node1, node2]) 30 | end 31 | end 32 | 33 | test "terminates child running in the cluster" do 34 | [node1, node2] = nodes = start_nodes(:test_app, "foo", 2) 35 | 36 | [child_spec1, _child_spec2, child_spec3] = 37 | for id <- 1..3 do 38 | child_spec = Pogo.Worker.child_spec(id) 39 | start_child(node1, child_spec) 40 | child_spec 41 | end 42 | 43 | assert_async do 44 | assert %{ 45 | ^node1 => [ 46 | {{Pogo.Worker, 2}, _, :worker, _} 47 | ], 48 | ^node2 => [ 49 | {{Pogo.Worker, 1}, _, :worker, _}, 50 | {{Pogo.Worker, 3}, _, :worker, _} 51 | ] 52 | } = local_children(nodes) 53 | end 54 | 55 | # terminate using node1 even though the process is running on node2 56 | terminate_child(node1, child_spec1) 57 | 58 | assert_async do 59 | assert %{ 60 | ^node1 => [ 61 | {{Pogo.Worker, 2}, _, :worker, _} 62 | ], 63 | ^node2 => [ 64 | {{Pogo.Worker, 3}, _, :worker, _} 65 | ] 66 | } = local_children(nodes) 67 | end 68 | 69 | # terminate using node2 even though the process was started using node1 70 | terminate_child(node2, child_spec3) 71 | 72 | assert_async do 73 | assert %{ 74 | ^node1 => [ 75 | {{Pogo.Worker, 2}, _, :worker, _} 76 | ], 77 | ^node2 => [] 78 | } = local_children(nodes) 79 | end 80 | end 81 | 82 | test "keeps track of new pid when child process crashes and gets restarted" do 83 | [node] = start_nodes(:test_app, "foo", 1) 84 | 85 | child_spec = Pogo.Worker.child_spec(1) 86 | start_child(node, child_spec) 87 | 88 | :timer.sleep(1000) 89 | 90 | [{{Pogo.Worker, 1}, pid, :worker, _}] = global_children(node) 91 | 92 | # kill child process, it will get restarted by local supervisor 93 | Process.exit(pid, :brutal_kill) 94 | 95 | assert_async do 96 | assert [{{Pogo.Worker, 1}, new_pid, :worker, _}] = global_children(node) 97 | assert new_pid != pid 98 | end 99 | end 100 | 101 | test "moves children between nodes when cluster topology changes" do 102 | [node1] = start_nodes(:test_app, "foo", 1) 103 | 104 | start_child(node1, Pogo.Worker.child_spec(1)) 105 | start_child(node1, Pogo.Worker.child_spec(2)) 106 | 107 | assert_async do 108 | assert %{ 109 | ^node1 => [ 110 | {{Pogo.Worker, 1}, _, :worker, _}, 111 | {{Pogo.Worker, 2}, _, :worker, _} 112 | ] 113 | } = local_children([node1]) 114 | end 115 | 116 | [node2] = start_nodes(:test_app, "bar", 1) 117 | 118 | assert_async do 119 | assert %{ 120 | ^node1 => [{{Pogo.Worker, 2}, _, :worker, _}], 121 | ^node2 => [{{Pogo.Worker, 1}, _, :worker, _}] 122 | } = local_children([node1, node2]) 123 | end 124 | 125 | stop_nodes([node2]) 126 | 127 | assert_async do 128 | assert %{ 129 | ^node1 => [ 130 | {{Pogo.Worker, 1}, _, :worker, _}, 131 | {{Pogo.Worker, 2}, _, :worker, _} 132 | ] 133 | } = local_children([node1]) 134 | end 135 | end 136 | 137 | test "starts process on another node when the node it was scheduled on goes down" do 138 | [node1, node2, node3] = start_nodes(:test_app, "foo", 3) 139 | 140 | start_child(node2, Pogo.Worker.child_spec(1)) 141 | 142 | assert_async do 143 | assert %{ 144 | ^node1 => [], 145 | ^node2 => [ 146 | {{Pogo.Worker, 1}, _, :worker, _} 147 | ], 148 | ^node3 => [] 149 | } = local_children([node1, node2, node3]) 150 | end 151 | 152 | stop_nodes([node2]) 153 | 154 | assert_async do 155 | assert %{ 156 | ^node1 => [], 157 | ^node3 => [ 158 | {{Pogo.Worker, 1}, _, :worker, _} 159 | ] 160 | } = local_children([node1, node3]) 161 | end 162 | end 163 | 164 | test "starts distributed supervisor with initial list of children" do 165 | [node1, node2, node3] = start_nodes(:test_app_with_children, "foo", 3) 166 | 167 | assert_async do 168 | assert %{ 169 | ^node1 => [{{Pogo.Worker, 2}, _, :worker, _}], 170 | ^node2 => [ 171 | {{Pogo.Worker, 1}, _, :worker, _}, 172 | {{Pogo.Worker, 3}, _, :worker, _} 173 | ], 174 | ^node3 => [] 175 | } = local_children([node1, node2, node3]) 176 | end 177 | end 178 | 179 | test "initial list of children is automatically started after supervisor crash" do 180 | [node] = start_nodes(:test_app_with_children, "foo", 1) 181 | 182 | assert_async do 183 | assert %{ 184 | ^node => [ 185 | {{Pogo.Worker, 1}, _, :worker, _}, 186 | {{Pogo.Worker, 2}, _, :worker, _}, 187 | {{Pogo.Worker, 3}, _, :worker, _} 188 | ] 189 | } = local_children([node]) 190 | end 191 | 192 | # kill supervisor 193 | pid = :rpc.call(node, Process, :whereis, [PogoTest.DistributedSupervisor]) 194 | :rpc.call(node, Process, :exit, [pid, :brutal_kill]) 195 | 196 | assert_async do 197 | assert %{ 198 | ^node => [ 199 | {{Pogo.Worker, 1}, _, :worker, _}, 200 | {{Pogo.Worker, 2}, _, :worker, _}, 201 | {{Pogo.Worker, 3}, _, :worker, _} 202 | ] 203 | } = local_children([node]) 204 | end 205 | end 206 | 207 | @tag chaos: true 208 | test "chaos" do 209 | # start nodes 210 | nodes = start_nodes(:test_app, "foo", 10) 211 | 212 | # start children 213 | specs = for id <- 1..60, do: Pogo.Worker.child_spec(id) 214 | for spec <- specs, do: start_child(Enum.random(nodes), spec) 215 | 216 | :timer.sleep(1000) 217 | 218 | # stop some nodes 219 | nodes_to_stop = Enum.shuffle(nodes) |> Enum.take(5) 220 | stop_nodes(nodes_to_stop) 221 | nodes = nodes -- nodes_to_stop 222 | 223 | :timer.sleep(1000) 224 | 225 | # terminate some children 226 | specs_to_terminate = Enum.shuffle(specs) |> Enum.take(45) 227 | for spec <- specs_to_terminate, do: terminate_child(Enum.random(nodes), spec) 228 | specs = specs -- specs_to_terminate 229 | 230 | # start some more children 231 | specs_to_start = for id <- 61..120, do: Pogo.Worker.child_spec(id) 232 | for spec <- specs_to_start, do: start_child(Enum.random(nodes), spec) 233 | specs = specs ++ specs_to_start 234 | 235 | :timer.sleep(1000) 236 | 237 | # start some more nodes 238 | nodes = nodes ++ start_nodes(:test_app, "bar", 10) 239 | 240 | :timer.sleep(1000) 241 | 242 | # terminate some children 243 | specs_to_terminate = Enum.shuffle(specs) |> Enum.take(30) 244 | for spec <- specs_to_terminate, do: terminate_child(Enum.random(nodes), spec) 245 | specs = specs -- specs_to_terminate 246 | 247 | # start some more children 248 | specs_to_start = for id <- 121..150, do: Pogo.Worker.child_spec(id) 249 | for spec <- specs_to_start, do: start_child(Enum.random(nodes), spec) 250 | specs = specs ++ specs_to_start 251 | 252 | :timer.sleep(3000) 253 | 254 | node = Enum.random(nodes) 255 | all_nodes = Enum.sort(nodes) 256 | 257 | children = 258 | for {id, pid, :worker, _} <- global_children(node), into: %{} do 259 | {id, pid} 260 | end 261 | 262 | # assert that all scheduled children are running in the cluster 263 | for %{id: id} <- specs do 264 | pid = Map.get(children, id) 265 | assert is_pid(pid) 266 | assert :rpc.call(node(pid), Process, :alive?, [pid]) 267 | end 268 | 269 | # assert that terminated children are not running in the cluster 270 | assert Enum.count(specs) == Enum.count(children) 271 | 272 | ####################### 273 | ### test ugly internals 274 | ####################### 275 | 276 | pg_state = 277 | for group <- :rpc.call(node, :pg, :which_groups, [:test]), into: %{} do 278 | members = :rpc.call(node, :pg, :get_members, [:test, group]) 279 | {group, members} 280 | end 281 | 282 | groups = 283 | for {group, members} <- pg_state, into: %{} do 284 | nodes = Enum.map(members, &node(&1)) 285 | {group, nodes} 286 | end 287 | 288 | # assert all nodes are participating 289 | participating_nodes = for {{:member, node}, _} <- groups, do: node 290 | assert Enum.sort(participating_nodes) == all_nodes 291 | 292 | # assert all child specs are tracked by all nodes 293 | for spec <- specs do 294 | tracking_nodes = Map.get(groups, {:spec, spec}, []) 295 | assert Enum.sort(tracking_nodes) == all_nodes 296 | end 297 | 298 | # assert no dangling start_child or terminate_child requests 299 | refute groups 300 | |> Enum.any?(fn 301 | {{:start_child, _}, _} -> true 302 | {{:terminate_child, _}, _} -> true 303 | _ -> false 304 | end) 305 | 306 | # assert no dangling terminating markings 307 | refute groups 308 | |> Enum.any?(fn 309 | {{:terminating, _}, _} -> true 310 | _ -> false 311 | end) 312 | end 313 | 314 | describe "which_children/1" do 315 | test "returns children running on the node when called with :local" do 316 | [node1, node2] = nodes = start_nodes(:test_app, "foo", 2) 317 | 318 | start_child(node1, Pogo.Worker.child_spec(1)) 319 | start_child(node1, Pogo.Worker.child_spec(2)) 320 | 321 | assert_async do 322 | assert [ 323 | {{Pogo.Worker, 2}, _, :worker, _} 324 | ] = 325 | :rpc.call(node1, Pogo.DynamicSupervisor, :which_children, [@supervisor, :local]) 326 | end 327 | 328 | assert_async do 329 | assert [ 330 | {{Pogo.Worker, 1}, _, :worker, _} 331 | ] = 332 | :rpc.call(node2, Pogo.DynamicSupervisor, :which_children, [@supervisor, :local]) 333 | end 334 | 335 | %{ 336 | ^node1 => [{{Pogo.Worker, 2}, pid2, :worker, _}], 337 | ^node2 => [{{Pogo.Worker, 1}, pid1, :worker, _}] 338 | } = local_children(nodes) 339 | 340 | assert Pogo.Worker.get_id(pid1) == 1 341 | assert Pogo.Worker.get_id(pid2) == 2 342 | end 343 | 344 | test "returns all children running in cluster when called with :global" do 345 | [node1, node2] = start_nodes(:test_app, "foo", 2) 346 | 347 | start_child(node1, Pogo.Worker.child_spec(1)) 348 | start_child(node1, Pogo.Worker.child_spec(2)) 349 | 350 | assert_async do 351 | assert [ 352 | {{Pogo.Worker, 1}, _, :worker, _}, 353 | {{Pogo.Worker, 2}, _, :worker, _} 354 | ] = 355 | :rpc.call(node1, Pogo.DynamicSupervisor, :which_children, [@supervisor, :global]) 356 | |> Enum.sort() 357 | end 358 | 359 | assert_async do 360 | assert [ 361 | {{Pogo.Worker, 1}, _, :worker, _}, 362 | {{Pogo.Worker, 2}, _, :worker, _} 363 | ] = 364 | :rpc.call(node2, Pogo.DynamicSupervisor, :which_children, [@supervisor, :global]) 365 | |> Enum.sort() 366 | end 367 | 368 | assert global_children(node1) == global_children(node2) 369 | 370 | [ 371 | {{Pogo.Worker, 1}, pid1, :worker, _}, 372 | {{Pogo.Worker, 2}, pid2, :worker, _} 373 | ] = global_children(node1) 374 | 375 | assert Pogo.Worker.get_id(pid1) == 1 376 | assert Pogo.Worker.get_id(pid2) == 2 377 | end 378 | end 379 | 380 | defp start_nodes(app, prefix, n) do 381 | LocalCluster.start_nodes(prefix, n, 382 | applications: [app], 383 | files: ["test/support/pogo/worker.ex"] 384 | ) 385 | end 386 | 387 | defp stop_nodes(nodes) do 388 | LocalCluster.stop_nodes(nodes) 389 | end 390 | 391 | defp start_child(node, child_spec) do 392 | :rpc.call(node, Pogo.DynamicSupervisor, :start_child, [@supervisor, child_spec]) 393 | end 394 | 395 | defp terminate_child(node, %{id: id}) do 396 | :rpc.call(node, Pogo.DynamicSupervisor, :terminate_child, [@supervisor, id]) 397 | end 398 | 399 | defp local_children(nodes) do 400 | for node <- nodes, into: %{} do 401 | local_children = 402 | :rpc.call(node, Pogo.DynamicSupervisor, :which_children, [@supervisor, :local]) 403 | 404 | {node, Enum.sort(local_children)} 405 | end 406 | end 407 | 408 | defp global_children(node) do 409 | :rpc.call(node, Pogo.DynamicSupervisor, :which_children, [@supervisor, :global]) 410 | |> Enum.sort() 411 | end 412 | end 413 | -------------------------------------------------------------------------------- /lib/pogo/dynamic_supervisor.ex: -------------------------------------------------------------------------------- 1 | defmodule Pogo.DynamicSupervisor do 2 | @moduledoc """ 3 | Dynamic Supervisor that distributes processes among nodes in the cluster. 4 | 5 | Uses process groups (via `:pg`) under the hood to maintain cluster-wide 6 | state and coordinate work between supervisor processes running in the 7 | cluster. Supervisors are organized into independent scopes. 8 | 9 | When a supervisor receives a request to start a child process via 10 | `start_child/2`, instead of starting it immediately, it propagates that 11 | request via process groups to supervisors running on other nodes. 12 | Termination of child processes via `terminate_child/2` works in the same 13 | way. 14 | 15 | Each supervisor periodically synchronizes its local state by processing 16 | the start and terminate requests, and updates child process information 17 | in cluster-wide state. 18 | 19 | Supervisor processes running on different nodes, but operating within the 20 | same scope, form a hash ring. When processing requests to start child 21 | processes, supervisors use consistent hashing to determine if they should 22 | accept the request or not, guaranteeing that there will be exactly one 23 | supervisor accepting the request and actually starting the child process 24 | locally. 25 | 26 | Cluster topology changes, with supervisors being added or removed, are 27 | likely to affect the distribution of child processes - some child processes 28 | may get rescheduled to supervisors running on different nodes. 29 | """ 30 | 31 | use GenServer, type: :supervisor 32 | 33 | @type option :: {:name, Supervised.name()} 34 | @type init_option :: 35 | Supervisor.init_option() 36 | | {:scope, term} 37 | | {:sync_interval, pos_integer()} 38 | | {:children, [Supervisor.child_spec()]} 39 | 40 | @sync_interval 5_000 41 | 42 | defstruct [:scope, :supervisor, :sync_interval] 43 | 44 | @doc """ 45 | Starts local supervisor and joins cluster-wide scoped process group. 46 | 47 | ## Options 48 | 49 | All options accepted by `Supervisor.init/2` are also accepted here, except for 50 | `:strategy` which is always `:one_for_one`. Additionally the following options 51 | can be specified. 52 | 53 | * `scope` - scope to join, supervisors only cooperate with other supervisors 54 | operating within the same scope 55 | * `sync_interval` - interval in milliseconds, how often the supervisor should 56 | synchronize its local state with the cluster by processing requests to 57 | start and terminate child processes, defaults to `5_000` 58 | * `children` - list of child specifications to automatially start in the cluster 59 | 60 | Children specified at startup are handled in the same way as children started 61 | dynamically. The only difference is that when `Pogo.DynamicSupervisor` runs under 62 | a supervision tree and is restarted, it will automatically restart all these 63 | children as well. 64 | """ 65 | @spec start_link([option | init_option]) :: GenServer.on_start() 66 | def start_link(opts) do 67 | {name, opts} = Keyword.pop(opts, :name, __MODULE__) 68 | GenServer.start_link(__MODULE__, opts, name: name) 69 | end 70 | 71 | @doc """ 72 | Requests a child process to be started under one of the supervisors in the cluster. 73 | """ 74 | @spec start_child(Supervisor.supervisor(), Supervisor.child_spec() | {module, term} | module) :: 75 | :ok | {:error, any} 76 | def start_child(supervisor, child_spec) do 77 | child_spec = Supervisor.child_spec(child_spec, []) 78 | 79 | case validate_child(child_spec) do 80 | :ok -> GenServer.cast(supervisor, {:start_child, child_spec}) 81 | error -> {:error, error} 82 | end 83 | end 84 | 85 | @doc """ 86 | Requests a child process running under one of the supervisors in the cluster 87 | to be terminated. 88 | """ 89 | @spec terminate_child(Supervisor.supervisor(), term) :: :ok 90 | def terminate_child(supervisor, id) do 91 | GenServer.cast(supervisor, {:terminate_child, id}) 92 | end 93 | 94 | @doc """ 95 | Returns a list with information about locally or globally supervised children. 96 | """ 97 | @spec which_children(Supervisor.supervisor(), :global | :local) :: [ 98 | {term | :undefined, Supervisor.child() | :restarting, :worker | :supervisor, 99 | [module] | :dynamic} 100 | ] 101 | def which_children(supervisor, scope) do 102 | GenServer.call(supervisor, {:which_children, scope}) 103 | end 104 | 105 | @impl true 106 | def init(opts) do 107 | scope = Keyword.fetch!(opts, :scope) 108 | {sync_interval, opts} = Keyword.pop(opts, :sync_interval, @sync_interval) 109 | {children, opts} = Keyword.pop(opts, :children, []) 110 | 111 | opts = Keyword.put(opts, :strategy, :one_for_one) 112 | 113 | :pg.start_link(scope) 114 | :ok = :pg.join(scope, {:member, Node.self()}, self()) 115 | 116 | {:ok, supervisor} = Supervisor.start_link([], opts) 117 | 118 | state = %__MODULE__{ 119 | scope: scope, 120 | supervisor: supervisor, 121 | sync_interval: sync_interval 122 | } 123 | 124 | Process.send_after(self(), :sync, sync_interval) 125 | 126 | {:ok, state, {:continue, {:start_children, children}}} 127 | end 128 | 129 | @impl true 130 | def handle_continue({:start_children, children}, %{scope: scope} = state) do 131 | for child_spec <- children do 132 | child_spec = Supervisor.child_spec(child_spec, []) 133 | :ok = validate_child(child_spec) 134 | make_request(scope, {:start_child, child_spec}) 135 | end 136 | 137 | {:noreply, state} 138 | end 139 | 140 | @impl true 141 | def handle_call({:which_children, :local}, _from, %{supervisor: supervisor} = state) do 142 | {:reply, Supervisor.which_children(supervisor), state} 143 | end 144 | 145 | def handle_call({:which_children, :global}, _from, %{scope: scope} = state) do 146 | groups = :pg.which_groups(scope) 147 | 148 | children = 149 | for {:pid, id} <- groups, reduce: [] do 150 | acc -> 151 | case to_child(scope, id) do 152 | nil -> acc 153 | child -> [child | acc] 154 | end 155 | end 156 | 157 | {:reply, children, state} 158 | end 159 | 160 | @impl true 161 | def handle_cast({:start_child, child_spec}, %{scope: scope} = state) do 162 | make_request(scope, {:start_child, child_spec}) 163 | {:noreply, state} 164 | end 165 | 166 | def handle_cast({:terminate_child, id}, %{scope: scope} = state) do 167 | make_request(scope, {:terminate_child, id}) 168 | {:noreply, state} 169 | end 170 | 171 | @impl true 172 | def handle_info( 173 | :sync, 174 | %{scope: scope, supervisor: supervisor, sync_interval: sync_interval} = state 175 | ) do 176 | ring = node_ring(scope) 177 | 178 | process_start_child_requests(scope, supervisor, ring) 179 | process_terminate_child_requests(scope, supervisor, ring) 180 | distribute_children(scope, supervisor, ring) 181 | sync_local_children(scope, supervisor) 182 | sync_specs(scope) 183 | cleanup(scope) 184 | 185 | Process.send_after(self(), :sync, sync_interval) 186 | 187 | {:noreply, state} 188 | end 189 | 190 | defp node_ring(scope) do 191 | groups = :pg.which_groups(scope) 192 | 193 | # build a consistent hash ring of existing nodes to distribute 194 | # child processes among them 195 | for {:member, node} <- groups, reduce: HashRing.new() do 196 | acc -> HashRing.add_node(acc, node) 197 | end 198 | end 199 | 200 | defp assign_child(scope, id, ring) do 201 | assigned_node = HashRing.key_to_node(ring, id) 202 | 203 | assigned_supervisor = 204 | case :pg.get_members(scope, {:member, assigned_node}) do 205 | [supervisor | _] -> supervisor 206 | _ -> nil 207 | end 208 | 209 | {assigned_node, assigned_supervisor} 210 | end 211 | 212 | defp process_start_child_requests(scope, supervisor, ring) do 213 | for {:start_child, %{id: id} = child_spec} = request <- :pg.which_groups(scope) do 214 | {assigned_node, assigned_supervisor} = assign_child(scope, id, ring) 215 | 216 | cond do 217 | assigned_node == Node.self() -> 218 | unless supervising?(scope, child_spec) do 219 | {:ok, pid} = Supervisor.start_child(supervisor, child_spec) 220 | 221 | track_supervisor(scope, child_spec) 222 | track_pid(scope, child_spec, pid) 223 | track_spec(scope, child_spec) 224 | end 225 | 226 | complete_request(scope, request) 227 | 228 | tracks_spec?(scope, child_spec, assigned_supervisor) -> 229 | complete_request(scope, request) 230 | 231 | true -> 232 | :noop 233 | end 234 | end 235 | end 236 | 237 | defp process_terminate_child_requests(scope, supervisor, ring) do 238 | for {:terminate_child, id} = request <- :pg.which_groups(scope) do 239 | {assigned_node, assigned_supervisor} = assign_child(scope, id, ring) 240 | child_spec = get_child_spec(scope, id) 241 | 242 | cond do 243 | assigned_node == Node.self() -> 244 | start_terminate(scope, id) 245 | 246 | if child_spec && supervising?(scope, child_spec) do 247 | Supervisor.terminate_child(supervisor, id) 248 | Supervisor.delete_child(supervisor, id) 249 | 250 | untrack_supervisor(scope, child_spec) 251 | untrack_spec(scope, child_spec) 252 | end 253 | 254 | complete_request(scope, request) 255 | 256 | is_nil(child_spec) || !tracks_spec?(scope, child_spec, assigned_supervisor) -> 257 | # complete request only after assigned supervisor untracks the spec 258 | complete_request(scope, request) 259 | 260 | true -> 261 | :noop 262 | end 263 | end 264 | end 265 | 266 | defp distribute_children(scope, supervisor, ring) do 267 | self_node = Node.self() 268 | 269 | for {:spec, %{id: id} = child_spec} <- :pg.which_groups(scope) do 270 | {assigned_node, assigned_supervisor} = assign_child(scope, id, ring) 271 | 272 | case assigned_node do 273 | ^self_node -> 274 | # child is assigned to current node 275 | # start it here, if it's not started yet and it's not being terminated 276 | 277 | unless terminating?(scope, id) || supervising?(scope, child_spec) do 278 | {:ok, pid} = Supervisor.start_child(supervisor, child_spec) 279 | 280 | track_supervisor(scope, child_spec) 281 | track_pid(scope, child_spec, pid) 282 | track_spec(scope, child_spec) 283 | end 284 | 285 | _ -> 286 | # child is assigned to a different node 287 | # terminate it here, but only if it's already started there 288 | 289 | if supervising?(scope, child_spec) && 290 | tracks_spec?(scope, child_spec, assigned_supervisor) do 291 | Supervisor.terminate_child(supervisor, id) 292 | Supervisor.delete_child(supervisor, id) 293 | 294 | untrack_supervisor(scope, child_spec) 295 | end 296 | end 297 | end 298 | end 299 | 300 | defp sync_specs(scope) do 301 | for {:spec, %{id: id} = child_spec} <- :pg.which_groups(scope) do 302 | cond do 303 | terminating?(scope, id) -> 304 | # untrack spec if child is being terminated 305 | untrack_spec(scope, child_spec) 306 | 307 | alive?(scope, child_spec) -> 308 | # track spec only after it is started by its assigned supervisor 309 | track_spec(scope, child_spec) 310 | 311 | true -> 312 | :noop 313 | end 314 | end 315 | end 316 | 317 | defp sync_local_children(scope, supervisor) do 318 | # go through all processes supervised by the local supervisor 319 | # to sync its state with cluster supervisor 320 | for {id, pid, _, _} <- Supervisor.which_children(supervisor) do 321 | case pid do 322 | :undefined -> 323 | # restart supervised child process that is not running 324 | with {:ok, pid} when is_pid(pid) <- Supervisor.restart_child(supervisor, id) do 325 | join_once(scope, {:pid, id}, pid) 326 | end 327 | 328 | pid when is_pid(pid) -> 329 | # ensure that we track new pids of child processes that may have 330 | # crashed and been restarted by local supervisor 331 | join_once(scope, {:pid, id}, pid) 332 | 333 | _ -> 334 | :noop 335 | end 336 | end 337 | end 338 | 339 | defp cleanup(scope) do 340 | # clean up terminating children if they have been untracked by all supervisors 341 | for {:terminating, id} <- :pg.which_groups(scope), 342 | :error == fetch_child_spec(scope, id) do 343 | finish_terminate(scope, id) 344 | end 345 | end 346 | 347 | defp make_request(scope, request) do 348 | join_once(scope, request, self()) 349 | end 350 | 351 | defp complete_request(scope, request) do 352 | :pg.leave(scope, request, self()) 353 | end 354 | 355 | defp supervising?(scope, %{id: id}) do 356 | self() in :pg.get_members(scope, {:supervisor, id}) 357 | end 358 | 359 | defp track_supervisor(scope, %{id: id}) do 360 | :pg.join(scope, {:supervisor, id}, self()) 361 | end 362 | 363 | defp untrack_supervisor(scope, %{id: id}) do 364 | :pg.leave(scope, {:supervisor, id}, self()) 365 | end 366 | 367 | defp track_pid(scope, %{id: id}, pid) do 368 | :pg.join(scope, {:pid, id}, pid) 369 | end 370 | 371 | defp track_spec(scope, child_spec) do 372 | join_once(scope, {:spec, child_spec}, self()) 373 | end 374 | 375 | defp untrack_spec(scope, child_spec) do 376 | :pg.leave(scope, {:spec, child_spec}, self()) 377 | end 378 | 379 | defp tracks_spec?(scope, child_spec, supervisor) do 380 | supervisor in :pg.get_members(scope, {:spec, child_spec}) 381 | end 382 | 383 | defp alive?(scope, child_spec) do 384 | :pg.get_members(scope, {:pid, child_spec.id}) != [] 385 | end 386 | 387 | defp start_terminate(scope, id) do 388 | join_once(scope, {:terminating, id}, self()) 389 | end 390 | 391 | defp finish_terminate(scope, id) do 392 | :pg.leave(scope, {:terminating, id}, self()) 393 | end 394 | 395 | defp terminating?(scope, id) do 396 | :pg.get_members(scope, {:terminating, id}) != [] 397 | end 398 | 399 | defp join_once(scope, group, pid) do 400 | unless pid in :pg.get_members(scope, group) do 401 | :pg.join(scope, group, pid) 402 | end 403 | end 404 | 405 | defp to_child(scope, id) do 406 | with [pid | _] <- :pg.get_members(scope, {:pid, id}), 407 | {:ok, %{start: {mod, _, _}} = child_spec} <- fetch_child_spec(scope, id) do 408 | type = Map.get(child_spec, :type, :worker) 409 | modules = Map.get(child_spec, :modules, [mod]) 410 | 411 | {id, pid, type, modules} 412 | else 413 | _ -> nil 414 | end 415 | end 416 | 417 | defp fetch_child_spec(scope, id) do 418 | groups = :pg.which_groups(scope) 419 | 420 | Enum.find_value(groups, :error, fn 421 | {:spec, %{id: ^id} = child_spec} -> 422 | {:ok, child_spec} 423 | 424 | _ -> 425 | false 426 | end) 427 | end 428 | 429 | defp get_child_spec(scope, id) do 430 | case fetch_child_spec(scope, id) do 431 | {:ok, child_spec} -> child_spec 432 | :error -> nil 433 | end 434 | end 435 | 436 | defp validate_child(%{id: _, start: {mod, _, _} = start} = child) do 437 | restart = Map.get(child, :restart, :permanent) 438 | type = Map.get(child, :type, :worker) 439 | modules = Map.get(child, :modules, [mod]) 440 | 441 | shutdown = 442 | case type do 443 | :worker -> Map.get(child, :shutdown, 5_000) 444 | :supervisor -> Map.get(child, :shutdown, :infinity) 445 | end 446 | 447 | validate_child(start, restart, shutdown, type, modules) 448 | end 449 | 450 | defp validate_child(other) do 451 | {:invalid_child_spec, other} 452 | end 453 | 454 | defp validate_child(start, restart, shutdown, type, modules) do 455 | with :ok <- validate_start(start), 456 | :ok <- validate_restart(restart), 457 | :ok <- validate_shutdown(shutdown), 458 | :ok <- validate_type(type) do 459 | validate_modules(modules) 460 | end 461 | end 462 | 463 | defp validate_start({m, f, args}) when is_atom(m) and is_atom(f) and is_list(args), do: :ok 464 | defp validate_start(mfa), do: {:invalid_mfa, mfa} 465 | 466 | defp validate_type(type) when type in [:supervisor, :worker], do: :ok 467 | defp validate_type(type), do: {:invalid_child_type, type} 468 | 469 | defp validate_restart(restart) when restart in [:permanent, :temporary, :transient], do: :ok 470 | defp validate_restart(restart), do: {:invalid_restart_type, restart} 471 | 472 | defp validate_shutdown(shutdown) when is_integer(shutdown) and shutdown > 0, do: :ok 473 | defp validate_shutdown(shutdown) when shutdown in [:infinity, :brutal_kill], do: :ok 474 | defp validate_shutdown(shutdown), do: {:invalid_shutdown, shutdown} 475 | 476 | defp validate_modules(:dynamic), do: :ok 477 | 478 | defp validate_modules(mods) do 479 | if is_list(mods) and Enum.all?(mods, &is_atom/1) do 480 | :ok 481 | else 482 | {:invalid_modules, mods} 483 | end 484 | end 485 | end 486 | --------------------------------------------------------------------------------