Last active
October 1, 2016 03:48
-
-
Save mattvonrocketstein/580e04631af195edae0c9157f47758fe to your computer and use it in GitHub Desktop.
Demo usage of ex_slp lib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Demo usage of ex_slp_tk for OpenSLP based Elixir node clustering | |
# see the library at: https://github.com/icanhazbroccoli/ex_slp_tk | |
# | |
# To use the code below, add something like this for your application's supervisor: | |
# | |
# children = children ++ [supervisor(Discovery.Supervisor, [])] | |
# supervise(children, opts) | |
# | |
require Logger | |
defmodule Discovery.Supervisor do | |
use Supervisor | |
def start_link do | |
Supervisor.start_link(__MODULE__, [], name: __MODULE__) | |
end | |
def init([]) do | |
children = [ | |
# a periodic task for discovering other registered elixir nodes | |
worker( | |
Task, [ &Discovery.discover/0 ], | |
id: SLPNodeDiscover, | |
restart: :permanent, | |
), # a periodic task for (re)registering with the OpenSLP daemon | |
# hint: run "sudo /etc/init.d/slpd start" | |
worker( | |
Task, [&Discovery.register/0], | |
id: :SLPNodeRegister, | |
restart: :permanent) | |
] | |
supervise(children, strategy: :one_for_one) | |
end | |
end | |
defmodule Discovery do | |
# HACK: by default service-strings may be constructed with human-friendly system hostnames. | |
def normalize(service_string) do | |
{:ok, this_hostname} = :inet.gethostname() | |
normalized_string = String.replace( | |
to_string(service_string), | |
to_string(this_hostname), | |
"127.0.0.1") | |
end | |
def discover() do | |
slp_services = ExSlp.Service.discover() | |
slp_services | |
|> Enum.map( fn service_string -> | |
normalized = normalize(service_string) | |
#make sure we ignore detecting ourselves | |
should_skip = normalized == Atom.to_string(Node.self()) | |
unless(should_skip) do | |
case ExSlp.Service.connect(normalized) do | |
# in this case Node.connect() ignored a down host | |
# see http://elixir-lang.org/docs/stable/elixir/Node.html#connect/1 | |
:ignored -> | |
#Logger.info("Connection to #{inspect normalized} ignored") | |
:noop | |
# in this case the Connection failed | |
false -> | |
#Logger.info("Connection to #{inspect normalized} failed") | |
:noop | |
# in this case Connection is successful (but not necessarily new) | |
true -> | |
Logger.info("Discovery.discover: connected") | |
Logger.info("#{inspect normalized}") | |
end # case | |
end # unless | |
end) | |
Logger.info("SLP Discovery") | |
end | |
def register() do | |
{:ok, _result} = ExSlp.Service.register() | |
Logger.info("Ran registration task") | |
:timer.sleep(5000) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment