| 1 | #!/usr/local/bin/perl | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | load_balance.pl Load balance a host or network across two or more Internet connections. | ||
| 6 | |||
| 7 | =head1 SYNOPSIS | ||
| 8 | |||
| 9 | # get status report | ||
| 10 | % sudo load_balance.pl -s | ||
| 11 | |||
| 12 | # start link monitoring and load balance across all up ISPs | ||
| 13 | % sudo load_balance.pl | ||
| 14 | |||
| 15 | # load balance across "CABLE" and "DSL" only | ||
| 16 | % sudo load_balance.pl CABLE DSL | ||
| 17 | |||
| 18 | # print out the routing and firewall commands that would | ||
| 19 | # ordinarily be executed | ||
| 20 | % load_balance.pl -d | ||
| 21 | |||
| 22 | =head1 DESCRIPTION | ||
| 23 | |||
| 24 | This script can be run on a Linux-based home router or standalone | ||
| 25 | computer to load balance your network connection among two or more | ||
| 26 | Internet Service Providers (ISPs). When aggregated across multiple | ||
| 27 | simultaneous connections, you will achieve the sum of the bandwidth of | ||
| 28 | all ISP connections. In addition, the script will continuously ping | ||
| 29 | each outgoing interface and adjust routing in the event that one or | ||
| 30 | more ISPs become unavailable. This provides failover. | ||
| 31 | |||
| 32 | The script can be called with no arguments, in which case it will mark | ||
| 33 | all known ISPs as being up and launch the "lsm" link monitor to test | ||
| 34 | each one periodically for connectivity. It can also be called with one | ||
| 35 | or more symbolic names for ISP connections, as defined in | ||
| 36 | load_balance.conf. These will be forced "up" and other ISP connections | ||
| 37 | will be forced "down". | ||
| 38 | |||
| 39 | Other command-line options allow you to view the status of your ISP | ||
| 40 | connections, kill a running lsm, and more. | ||
| 41 | |||
| 42 | Generally this script must be run as root, since it alters the routing | ||
| 43 | table and firewall rules. | ||
| 44 | |||
| 45 | For full installation and configuration instructions, please see | ||
| 46 | L<http://lstein.github.io/Net-ISP-Balance/>. | ||
| 47 | |||
| 48 | =head1 COMMAND-LINE OPTIONS | ||
| 49 | |||
| 50 | Each command-line option can be abbreviated or used in long-form. | ||
| 51 | |||
| 52 | --debug, -d Turn on debugging. In this mode, no firewall or | ||
| 53 | routing commands will be executed, but instead | ||
| 54 | will be printed to standard output for inspection. | ||
| 55 | |||
| 56 | --verbose, -v Verbose output. Echo all route and iptables commands | ||
| 57 | to STDERR before executing them. | ||
| 58 | |||
| 59 | --Version, -V Print version of Net::ISP::Balance. | ||
| 60 | |||
| 61 | --status,-s Print current status of each monitored ISP interface | ||
| 62 | to STDOUT. | ||
| 63 | |||
| 64 | --kill,-k Kill any running lsm process. | ||
| 65 | |||
| 66 | --flush,-f Flush all firewall chains and rules. If not given, then | ||
| 67 | the default is to try to keep custom iptables rules | ||
| 68 | introduced by firewall utilities such as fail2ban and | ||
| 69 | miniunpnpd. | ||
| 70 | |||
| 71 | --help,-h Print this message. | ||
| 72 | |||
| 73 | =head1 COMMON USAGE | ||
| 74 | |||
| 75 | This section describes common usage patterns. Note that | ||
| 76 | load_balance.pl must always be run as root. | ||
| 77 | |||
| 78 | =over 4 | ||
| 79 | |||
| 80 | =item Mark all ISPs as up and start link monitoring: | ||
| 81 | |||
| 82 | % sudo load_balance.pl | ||
| 83 | |||
| 84 | =item Mark just the listed ISP(s) as up. Do not start link monitoring: | ||
| 85 | |||
| 86 | % sudo load_balance.pl CABLE | ||
| 87 | |||
| 88 | =item Bring up the listed ISP service, leaving the other(s) in their current | ||
| 89 | state. This is usually done behind the scenes by lsm. | ||
| 90 | |||
| 91 | % sudo load_balance.pl up CABLE | ||
| 92 | |||
| 93 | =item Bring down the listed ISP service, leaving the other(s) in the | ||
| 94 | current state. This is usually done behind the scenes by lsm: | ||
| 95 | |||
| 96 | % sudo load_balance.pl down CABLE | ||
| 97 | |||
| 98 | =item Print current status of the defined ISPs: | ||
| 99 | |||
| 100 | % sudo load_balance.pl -s | ||
| 101 | |||
| 102 | =item Kill lsm and discontinue the link monitoring: | ||
| 103 | |||
| 104 | % sudo load_balance.pl -k | ||
| 105 | |||
| 106 | =item Print to standard output all the routing and firewall commands | ||
| 107 | that would ordinarily be issued on startup. Do not launch lsm or | ||
| 108 | actually change anything: | ||
| 109 | |||
| 110 | % sudo load_balance.pl -d | ||
| 111 | |||
| 112 | =back | ||
| 113 | |||
| 114 | =head1 FILES | ||
| 115 | |||
| 116 | This section gives locations of important files. | ||
| 117 | |||
| 118 | =head2 Debian/Ubuntu/Mint systems | ||
| 119 | |||
| 120 | /etc/network/balance.conf # Main configuration file | ||
| 121 | /etc/network/balance/firewall/ # Additional firewall rules | ||
| 122 | /etc/network/balance/routes/ # Additional routing rules | ||
| 123 | |||
| 124 | =head2 RedHat/CentOS systems | ||
| 125 | |||
| 126 | /etc/sysconfig/network-scripts/balance.conf # Main configuration file | ||
| 127 | /etc/sysconfig/network-scripts/balance/firewall/ # Additional firewall rules | ||
| 128 | /etc/sysconfig/network-scripts/balance/routes/ # Additional routing rules | ||
| 129 | |||
| 130 | =head2 Format of the balance.conf: | ||
| 131 | |||
| 132 | balance.conf is the main configuration file. It defines the interfaces | ||
| 133 | connected to the ISPs and to the LAN (if running on a router). Here is | ||
| 134 | a typical example: | ||
| 135 | |||
| 136 | #service device role ping-ip weight gateway | ||
| 137 | CABLE eth0 isp 173.194.43.95 1 default | ||
| 138 | DSL eth1 isp 173.194.43.95 1 default | ||
| 139 | LAN eth2 lan | ||
| 140 | |||
| 141 | # name=value pairs define lsm configuration variables | ||
| 142 | warn_email=fred@gmail.com | ||
| 143 | max_packet_loss=10 | ||
| 144 | min_packet_loss=5 | ||
| 145 | |||
| 146 | There are two parts of the configuration file. The first part, which | ||
| 147 | is required, is a four-column table that defines interfaces to be | ||
| 148 | monitored. | ||
| 149 | |||
| 150 | The first column is a service name that is used to bring up or down | ||
| 151 | the needed routes and firewall rules. | ||
| 152 | |||
| 153 | The second column is the name of the network interface device that | ||
| 154 | connects to that service. | ||
| 155 | |||
| 156 | The third column is either "isp" or "lan". There may be any number of | ||
| 157 | these. The script will load balance traffic across all ISPs, and will | ||
| 158 | act as a firewall between the LAN (if any) and the Internet. You do | ||
| 159 | not need to have a "lan" entry if this is a standalone host. | ||
| 160 | |||
| 161 | The fourth column (optional) is the IP address of a host that can be | ||
| 162 | periodically pinged to test the integrity of each ISP connection. If | ||
| 163 | too many pings failed, the service will be brought down and all | ||
| 164 | traffic routed through the remaining ISP(s). The service will continue | ||
| 165 | to be monitored and will be brought up when it is once again | ||
| 166 | working. Choose a host that is not likely to go offline for reasons | ||
| 167 | unrelated to your network connectivity, such as google.com, or the | ||
| 168 | ISP's web site. If this column is absent or marked "default", then the | ||
| 169 | host will default to www.google.ca. | ||
| 170 | |||
| 171 | The fifth column (optional) is a weight to assign to the service, and | ||
| 172 | is only valid for ISP rows. If weights are equal, traffic will be | ||
| 173 | apportioned evenly between the two routes. Increase a weight to favor | ||
| 174 | one ISP over the others. For example, if "CABLE" has a weight of 2 and | ||
| 175 | "DSL" has a weight of 1, then twice as much traffic will flow through | ||
| 176 | the CABLE service. If this column is omitted or marked "default", then | ||
| 177 | equal weights are assumed. | ||
| 178 | |||
| 179 | The sixth column (optional) is the IP address for the gateway host for | ||
| 180 | this service. If absent or named "default", the system will attempt | ||
| 181 | to guess the proper gateway automatically. Note the guessing algorithm | ||
| 182 | relies on the fact that the gateway is almost always the first address | ||
| 183 | in the IP range for the subnetwork. If this is not the case, then | ||
| 184 | routing through the interface won't work properly. Add the correct | ||
| 185 | gateway IP address manually to correct this. | ||
| 186 | |||
| 187 | The second (optional) part of the configuration file is a series of | ||
| 188 | name=value pairs that allow you to customize the behavior of lsm, such | ||
| 189 | as where to send email messages when a link's status changes. Please | ||
| 190 | see L<http://lsm.foobar.fi/> for the comprehensive list. | ||
| 191 | |||
| 192 | =head1 SEE ALSO | ||
| 193 | |||
| 194 | L<Net::ISP::Balance> | ||
| 195 | |||
| 196 | =head1 AUTHOR | ||
| 197 | |||
| 198 | Lincoln Stein, lincoln.stein@gmail.com | ||
| 199 | |||
| 200 | Copyright (c) 2014-2017 Lincoln D. Stein | ||
| 201 | |||
| 202 | This package and its accompanying libraries is free software; you can | ||
| 203 | redistribute it and/or modify it under the terms of the GPL (either | ||
| 204 | version 1, or at your option, any later version) or the Artistic | ||
| 205 | License 2.0. | ||
| 206 | |||
| 207 | =cut | ||
| 208 | |||
| 209 | use strict; | ||
| 210 | use Net::ISP::Balance; | ||
| 211 | use Sys::Syslog; | ||
| 212 | use Fcntl ':flock'; | ||
| 213 | use File::Spec; | ||
| 214 | use Getopt::Long qw(:config no_ignore_case); | ||
| 215 | use Carp 'croak'; | ||
| 216 | use Pod::Usage 'pod2usage'; | ||
| 217 | use constant LOCK_TIMEOUT => 30; # if two processes running simultaneously, length of time second will wait for first | ||
| 218 | |||
| 219 | my ($DEBUG,$VERBOSE,$STATUS,$KILL,$HELP,$FLUSH,$VERSION); | ||
| 220 | my $result = GetOptions('debug' => \$DEBUG, | ||
| 221 | 'verbose'=>\$VERBOSE, | ||
| 222 | 'Version'=>\$VERSION, | ||
| 223 | 'status' => \$STATUS, | ||
| 224 | 'kill' => \$KILL, | ||
| 225 | 'flush' => \$FLUSH, | ||
| 226 | 'help' => \$HELP, | ||
| 227 | ); | ||
| 228 | if (!$result || $HELP) { | ||
| 229 | pod2usage(-message => "Usage: $0", | ||
| 230 | -exitval => -1, | ||
| 231 | -verbose => 2); | ||
| 232 | exit 0; | ||
| 233 | } | ||
| 234 | if ($VERSION) { | ||
| 235 | print $Net::ISP::Balance::VERSION,"\n"; | ||
| 236 | exit 0; | ||
| 237 | } | ||
| 238 | |||
| 239 | my $lock_fh = do_lock(); | ||
| 240 | END { do_unlock($lock_fh); } | ||
| 241 | |||
| 242 | # command line arguments correspond to the ISP services (defined in the config file) | ||
| 243 | # that are "up". LAN services are assumed to be always up. | ||
| 244 | |||
| 245 | openlog('load_balance.pl','ndelay,pid','local0'); | ||
| 246 | |||
| 247 | my $bal = eval {Net::ISP::Balance->new()}; | ||
| 248 | |||
| 249 | fatal_error("Could not initialize balancer; maybe some interfaces are unavailable? Error message=$@") | ||
| 250 | unless $bal;; | ||
| 251 | |||
| 252 | $bal->echo_only($DEBUG); | ||
| 253 | $bal->verbose($VERBOSE); | ||
| 254 | $bal->keep_custom_chains(!$FLUSH); | ||
| 255 | |||
| 256 | # these two subroutines exit | ||
| 257 | do_status() if $STATUS; | ||
| 258 | do_kill_lsm() if $KILL; | ||
| 259 | |||
| 260 | my %SERVICES = map {$_=>1} $bal->isp_services; | ||
| 261 | |||
| 262 | my %LSM_STATE = (up => 'up', | ||
| 263 | down => 'down', | ||
| 264 | long_down => 'down', | ||
| 265 | long_down_to_up => 'up'); | ||
| 266 | |||
| 267 | if (exists $LSM_STATE{$ARGV[0]}) { | ||
| 268 | do_unlock($lock_fh); # to allow eventd to call us recursively | ||
| 269 | $bal->run_eventd(@ARGV); | ||
| 270 | $lock_fh = do_lock(); | ||
| 271 | if (($SERVICES{my $name = $ARGV[1]})) { | ||
| 272 | my $device = $ARGV[3] || $bal->dev($name); | ||
| 273 | syslog('warning',"$name ($device) is now in state '$ARGV[0]'."); | ||
| 274 | $bal->event($name => $LSM_STATE{$ARGV[0]}) if $LSM_STATE{$ARGV[0]}; | ||
| 275 | } | ||
| 276 | } | ||
| 277 | |||
| 278 | else { | ||
| 279 | my @up = @ARGV ? @ARGV : $bal->isp_services; | ||
| 280 | my %up_services = map {uc($_) => 1} @up; | ||
| 281 | @up = keys %up_services; # uniqueify | ||
| 282 | my @down = grep {!$up_services{$_}} $bal->isp_services; | ||
| 283 | $bal->event($_ => 'up') foreach @up; | ||
| 284 | $bal->event($_ => 'down') foreach @down; | ||
| 285 | } | ||
| 286 | |||
| 287 | if ($bal->operating_mode eq 'failover') { | ||
| 288 | my $s = $bal->preferred_service; | ||
| 289 | syslog('info',"Setting default route to service %s, device %s",$s,$bal->dev($s)); | ||
| 290 | } else { | ||
| 291 | syslog('info',"Adjusting routing tables."); | ||
| 292 | } | ||
| 293 | $bal->set_routes_and_firewall(); | ||
| 294 | kill_lsm() unless @ARGV; | ||
| 295 | start_or_reload_lsm($bal); | ||
| 296 | |||
| 297 | exit 0; | ||
| 298 | |||
| 299 | sub do_status { | ||
| 300 | my $state = $bal->event(); | ||
| 301 | my @svc = sort $bal->isp_services; | ||
| 302 | printf("%-12s %-8s %-8s %-3s\n", | ||
| 303 | 'Service', | ||
| 304 | 'Device', | ||
| 305 | 'State', | ||
| 306 | 'Routing'); | ||
| 307 | foreach (@svc) { | ||
| 308 | my $preferred = $bal->preferred_service; | ||
| 309 | my $routing = $bal->operating_mode eq 'failover' ? $_ eq $preferred | ||
| 310 | : $state->{$_} eq 'up'; | ||
| 311 | printf("%-12s %-8s %-8s %-3s\n", | ||
| 312 | $_, | ||
| 313 | $bal->dev($_), | ||
| 314 | $state->{$_}||'unknown', | ||
| 315 | $routing ? 'yes' : 'no', | ||
| 316 | |||
| 317 | ); | ||
| 318 | } | ||
| 319 | |||
| 320 | if ($< == 0) { # running as root | ||
| 321 | kill(USR1 => `cat /var/run/lsm.pid`); | ||
| 322 | print STDERR "See syslog for detailed link monitoring information from lsm.\n"; | ||
| 323 | } | ||
| 324 | exit 0; | ||
| 325 | } | ||
| 326 | |||
| 327 | sub do_kill_lsm { | ||
| 328 | kill_lsm(); | ||
| 329 | exit 0; | ||
| 330 | } | ||
| 331 | |||
| 332 | sub kill_lsm { | ||
| 333 | my $lsm_running = -e '/var/run/lsm.pid' && kill(0=>`cat /var/run/lsm.pid`); | ||
| 334 | if ($lsm_running) { | ||
| 335 | kill(TERM => `cat /var/run/lsm.pid`); | ||
| 336 | print STDERR "lsm process killed\n"; | ||
| 337 | } | ||
| 338 | } | ||
| 339 | |||
| 340 | sub start_or_reload_lsm { | ||
| 341 | my $bal = shift; | ||
| 342 | |||
| 343 | my $config_changed = write_lsm_config($bal); | ||
| 344 | my $lsm_conf = $bal->lsm_conf_file; | ||
| 345 | my $lsm_pid = -e '/var/run/lsm.pid' && `cat /var/run/lsm.pid`; | ||
| 346 | chomp($lsm_pid); | ||
| 347 | |||
| 348 | my $lsm_running = $lsm_pid && kill(0=>$lsm_pid); | ||
| 349 | |||
| 350 | if (!$lsm_running) { | ||
| 351 | print STDERR "Starting lsm link status monitoring daemon\n"; | ||
| 352 | syslog('info',"Starting lsm link status monitoring daemon"); | ||
| 353 | $bal->start_lsm(); | ||
| 354 | } | ||
| 355 | elsif ($ARGV[0] && $ARGV[0] eq 'long_down') { | ||
| 356 | print STDERR "Reloading lsm link status monitoring daemon\n"; | ||
| 357 | syslog('info',"Reloading lsm link status monitoring daemon"); | ||
| 358 | kill(HUP => $lsm_pid); | ||
| 359 | } | ||
| 360 | |||
| 361 | } | ||
| 362 | |||
| 363 | sub write_lsm_config { | ||
| 364 | my $bal = shift; | ||
| 365 | |||
| 366 | my $lsm_conf = $bal->lsm_conf_file(); | ||
| 367 | |||
| 368 | my $old_text = ''; | ||
| 369 | my $fh; | ||
| 370 | if (open $fh,$lsm_conf) { | ||
| 371 | $old_text .= $_ while <$fh>; | ||
| 372 | close $fh; | ||
| 373 | } | ||
| 374 | |||
| 375 | my $new_text = $bal->lsm_config_text(); | ||
| 376 | return if $new_text eq $old_text; | ||
| 377 | |||
| 378 | # Create config file | ||
| 379 | open $fh,'>',$lsm_conf or die "$lsm_conf: $!"; | ||
| 380 | print $fh $new_text; | ||
| 381 | close $fh or die "$lsm_conf: $!"; | ||
| 382 | |||
| 383 | return 1; | ||
| 384 | } | ||
| 385 | |||
| 386 | sub fatal_error { | ||
| 387 | my $msg = shift; | ||
| 388 | syslog('crit',$msg); | ||
| 389 | croak $msg,"\n"; | ||
| 390 | } | ||
| 391 | |||
| 392 | sub do_lock { | ||
| 393 | my $lockfile = File::Spec->catfile(File::Spec->tmpdir, | ||
| 394 | "load_balance.$>.lock"); | ||
| 395 | open (my $fh,'>>',$lockfile) or fatal_error("Can't open $lockfile for locking"); | ||
| 396 | eval { | ||
| 397 | local $SIG{ALRM} = sub { die "timeout" }; | ||
| 398 | alarm(LOCK_TIMEOUT); | ||
| 399 | flock($fh,LOCK_EX) or fatal_error("Can't lock $lockfile"); | ||
| 400 | alarm(0); | ||
| 401 | }; | ||
| 402 | fatal_error("Lock timed out") if $@ =~ /timeout/; | ||
| 403 | return $fh; | ||
| 404 | } | ||
| 405 | |||
| 406 | |||
| 407 | sub do_unlock { | ||
| 408 | my $fh = shift; | ||
| 409 | return unless $fh; | ||
| 410 | flock($fh,LOCK_UN); | ||
| 411 | my $lockfile = get_lockfile(); | ||
| 412 | unlink $lockfile; | ||
| 413 | } | ||
| 414 | |||
| 415 | sub get_lockfile { | ||
| 416 | return File::Spec->catfile(File::Spec->tmpdir, | ||
| 417 | "load_balance.$>.lock"); | ||
| 418 | } |