Community discussions

MikroTik App
 
MaxHardwood
just joined
Topic Author
Posts: 1
Joined: Sun Aug 22, 2021 3:48 pm

ECMP with multiple DHCP Clients

Sun Aug 22, 2021 4:24 pm

ECMP requires you to know the gateways, unfortunately RouterOS doesn't provide an alias for DHCP provided gateways to configure routes with.
My use case is two different ISPs providing DHCP WAN connections for load balancing and failover. I'm doing this for all of my traffic on the network so I'm not using any routing marks or mangling.

# ECMP DHCP Gateway Routes
# Uses comments to identify routes and DHCP Clients
# DHCP Clients require comment "ECMP" or "ECMP Count: #"
# Routes require comment "ECMP-Main"
# Required Policies: Read, Write, Test


:local dhcpGateways

# DHCP Clients
# Only handle clients with a comment containing "ECMP"
:foreach dhcpClient in=[/ip dhcp-client find where status=bound and gateway!=nil and comment~".*ECMP.*"] do={
    :local client [/ip dhcp-client get $dhcpClient]
    :local comment ($client->"comment")
    
# Unequal load balancing using "ECMP Count: 3" in the comment
    :if ($comment~".*ECMP Count.*") do={
# Add the found number to 0 to convert from str to int, repeat as many times as found
        :for from=1 to=( ([:pick $comment ([:find $comment : ]+1) [:len $comment]]) + 0 ) counter=i do={
            :set dhcpGateways (($client->"gateway"),$dhcpGateways)
        }
# No comment containing "Count", only add once
    } else {
        :set dhcpGateways (($client->"gateway"),$dhcpGateways)
    }
}

# Routes
# Only handle routes with the commet "ECMP-Main"
:foreach route in=[/ip route find where comment="ECMP-Main"] do={
    :local routeGateways [/ip route get $route gateway]
    :local newGateways

# Compare the current gateways before working
    :if ($routeGateways != $dhcpGateways) do={
        :foreach gateway in=$dhcpGateways do={
            :if ([ping $gateway count=1]=1) do={
                :set newGateways "$newGateways,$gateway"
            }
        }

        /ip route set $route gateway=$newGateways

# Log changes
        :log warning message="ECMP routes have changed!"
        :log info message=("ECMP Previous route: " . [:tostr $routeGateways])
        :log info message="ECMP New routes: $newGateways"
    }
}

To use this I add a comment to the DHCP Clients with "ECMP", and for unequal routes I do "ECMP Count: 2" or however many times I want that gateway to be added to the route.
I create a route for 0.0.0.0/0 and give it a comment of "ECMP-Main". You could configure this route however you wish as the script only updates the gateways without modify anything else of the route. I run this every 30 seconds but it only does work when there are changes.

Figured this may be handy for somebody else

Who is online

Users browsing this forum: Rhydu and 14 guests