Skip to content

Commit

Permalink
Update Node's geo patch with mmdb2 updates
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelmanzanera committed Dec 8, 2022
1 parent e3e5d6e commit e9132f8
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/archethic/p2p/geo_patch.ex
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ defmodule Archethic.P2P.GeoPatch do
|> List.to_string()
end

defp compute_patch(lat, lon) do
@doc """
Compute a geo patch by the coordinates
"""
@spec compute_patch(integer(), integer()) :: binary()
def compute_patch(lat, lon) do
# convert 90 and 180 to -90 and -180 to not get an out of bound index
lat = if(lat == 90, do: -90) || lat
lon = if(lon == 180, do: -180) || lon
Expand Down
32 changes: 32 additions & 0 deletions lib/archethic/p2p/geo_patch/geo_ip/maxmind_db.ex
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
defmodule Archethic.P2P.GeoPatch.GeoIP.MaxMindDB do
@moduledoc false

alias Archethic.P2P
alias Archethic.P2P.GeoPatch
alias Archethic.P2P.GeoPatch.GeoIP
alias Archethic.P2P.MemTable
alias Archethic.P2P.Node

alias MMDB2Decoder
alias MMDB2Decoder.Metadata

use GenServer
@vsn Mix.Project.config()[:version]
Expand Down Expand Up @@ -41,4 +47,30 @@ defmodule Archethic.P2P.GeoPatch.GeoIP.MaxMindDB do
{:reply, {0.0, 0.0}, {meta, tree, data}}
end
end

@impl true
def code_change(_, state = {%Metadata{build_epoch: previous_epoch}, _tree, _data, _}, _extra) do
database = File.read!(Application.app_dir(:archethic, "/priv/p2p/GEOLITE2.mmdb"))

{:ok, meta = %Metadata{build_epoch: build_epoch}, tree, data} =
MMDB2Decoder.parse_database(database)

if build_epoch > previous_epoch do
# Update the geo patch on all the nodes
Enum.each(P2P.list_nodes(), fn node = %Node{ip: ip} ->
case MMDB2Decoder.lookup(ip, meta, tree, data) do
{:ok, %{"location" => %{"latitude" => lat, "longitude" => lon}}} ->
geo_patch = GeoPatch.compute_patch(lat, lon)
MemTable.add_node(%{node | geo_patch: geo_patch})

_ ->
:skip
end
end)

{:ok, {meta, tree, data}}
else
{:ok, state}
end
end
end
Binary file modified priv/p2p/GEOLITE2.mmdb
Binary file not shown.

0 comments on commit e9132f8

Please sign in to comment.