blib/script/load_balance.pl untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 34 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 284 CC 13 SCAR 22.0
CC
13
Cov
0%
do_status
30.0
lsm_running
12.0
write_lsm_config
12.0
CRAP 9.0
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 my $lsm_pid_path = Net::ISP::Balance->lsm_pid_path();
219  
220 my ($DEBUG,$VERBOSE,$STATUS,$KILL,$HELP,$FLUSH,$VERSION);
221 my $result = GetOptions('debug' => \$DEBUG,
222 'verbose'=>\$VERBOSE,
223 'Version'=>\$VERSION,
224 'status' => \$STATUS,
225 'kill' => \$KILL,
226 'flush' => \$FLUSH,
227 'help' => \$HELP,
228 );
229 if (!$result || $HELP) {
230 pod2usage(-message => "Usage: $0",
231 -exitval => -1,
232 -verbose => 2);
233 exit 0;
234 }
235 if ($VERSION) {
236 print $Net::ISP::Balance::VERSION,"\n";
237 exit 0;
238 }
239  
240 my $lock_fh = do_lock();
241 END { do_unlock($lock_fh); }
242  
243 # command line arguments correspond to the ISP services (defined in the config file)
244 # that are "up". LAN services are assumed to be always up.
245  
246 openlog('load_balance.pl','ndelay,pid','local0');
247  
248 my $bal = eval {Net::ISP::Balance->new()};
249  
250 fatal_error("Could not initialize balancer; maybe some interfaces are unavailable? Error message=$@")
251 unless $bal;;
252  
253 $bal->echo_only($DEBUG);
254 $bal->verbose($VERBOSE);
255 $bal->keep_custom_chains(!$FLUSH);
256  
257 # these two subroutines exit
258 do_status() if $STATUS;
259 do_kill_lsm() if $KILL;
260  
261 my %SERVICES = map {$_=>1} $bal->isp_services;
262  
263 my %LSM_STATE = (up => 'up',
264 down => 'down',
265 long_down => 'down',
266 long_down_to_up => 'up');
267  
268 if (exists $LSM_STATE{$ARGV[0]}) {
269 do_unlock($lock_fh); # to allow eventd to call us recursively
270 $bal->run_eventd(@ARGV);
271 $lock_fh = do_lock();
272 if (($SERVICES{my $name = $ARGV[1]})) {
273 my $device = $ARGV[3] || $bal->dev($name);
274 syslog('warning',"$name ($device) is now in state '$ARGV[0]'.");
275 $bal->event($name => $LSM_STATE{$ARGV[0]}) if $LSM_STATE{$ARGV[0]};
276 }
277 }
278  
279 else {
280 my @up = @ARGV ? @ARGV : $bal->isp_services;
281 my %up_services = map {uc($_) => 1} @up;
282 @up = keys %up_services; # uniqueify
283 my @down = grep {!$up_services{$_}} $bal->isp_services;
284 $bal->event($_ => 'up') foreach @up;
285 $bal->event($_ => 'down') foreach @down;
286 }
287  
288 if ($bal->operating_mode eq 'failover') {
289 my $s = $bal->preferred_service;
290 syslog('info',"Setting default route to service %s, device %s",$s,$bal->dev($s));
291 } else {
292 syslog('info',"Adjusting routing tables.");
293 }
294 $bal->set_routes_and_firewall();
295 kill_lsm() unless @ARGV;
296 start_or_reload_lsm($bal);
297  
298 exit 0;
299  
300 sub do_status {
301 my $state = $bal->event();
302 my @svc = sort $bal->isp_services;
303 printf("%-12s %-12s %-12s %-3s\n",
304 'Service',
305 'Device',
306 'State',
307 'Routing');
308 foreach (@svc) {
309 my $preferred = $bal->preferred_service;
310 my $routing = $bal->operating_mode eq 'failover' ? $_ eq $preferred
311 : $state->{$_} eq 'up';
312 printf("%-12s %-12s %-12s %-3s\n",
313 $_,
314 $bal->vdev($_),
315 $state->{$_}||'unknown',
316 $routing ? 'yes' : 'no',
317  
318 );
319 }
320  
321 my $pid = lsm_pid();
322 my $lsm_running = $pid && lsm_running($pid) ? "running ($pid)" : 'not running';
323 print "\nLink monitoring daemon (lsm) process: $lsm_running\n";
324  
325 if ($< == 0 && $pid) { # running as root
326 kill(USR1 => $pid);
327 print STDERR "See syslog for detailed link monitoring information from lsm.\n";
328 }
329 exit 0;
330 }
331  
332 sub lsm_running {
333 my $pid = shift;
334 $pid ||= lsm_pid();
335 return unless $pid;
336 return kill(0=>$pid) if $< == 0; # running as root so we can try signaling
337 # otherwise we check whether this pid is listed in /proc
338 return -e "/proc/$pid";
339 }
340  
341 sub lsm_pid {
342 -e $lsm_pid_path or return;
343 open my $fh,$lsm_pid_path or return;
344 chomp (my $pid = <$fh>);
345 close $fh;
346 return $pid;
347 }
348  
349 sub do_kill_lsm {
350 kill_lsm();
351 exit 0;
352 }
353  
354 sub kill_lsm {
355 my $pid = lsm_pid();
356 my $lsm_running = $pid && kill(0=>$pid);
357 if ($lsm_running) {
358 kill(TERM => $pid);
359 print STDERR "foolsm process killed\n";
360 syslog('warning',"foolsm process killed");
361 }
362 unlink $lsm_pid_path;
363 }
364  
365 sub start_or_reload_lsm {
366 my $bal = shift;
367  
368 my $config_changed = write_lsm_config($bal);
369 my $lsm_pid = lsm_pid();
370  
371 if (!lsm_running($lsm_pid)) {
372 print STDERR "Starting foolsm link status monitoring daemon\n";
373 syslog('info',"Starting foolsm link status monitoring daemon");
374 $bal->start_lsm();
375 }
376 }
377  
378 sub write_lsm_config {
379 my $bal = shift;
380  
381 my $lsm_conf = $bal->lsm_conf_file();
382  
383 my $old_text = '';
384 my $fh;
385 if (open $fh,$lsm_conf) {
386 $old_text .= $_ while <$fh>;
387 close $fh;
388 }
389  
390 my $new_text = $bal->lsm_config_text();
391 return if $new_text eq $old_text;
392
393 # Create config file
394 open $fh,'>',$lsm_conf or die "$lsm_conf: $!";
395 print $fh $new_text;
396 close $fh or die "$lsm_conf: $!";
397
398 return 1;
399 }
400  
401 sub fatal_error {
402 my $msg = shift;
403 syslog('crit',$msg);
404 croak $msg,"\n";
405 }
406  
407 sub do_lock {
408 my $lockfile = File::Spec->catfile(File::Spec->tmpdir,
409 "load_balance.$>.lock");
410 open (my $fh,'>>',$lockfile) or fatal_error("Can't open $lockfile for locking");
411 eval {
412 local $SIG{ALRM} = sub { die "timeout" };
413 alarm(LOCK_TIMEOUT);
414 flock($fh,LOCK_EX) or fatal_error("Can't lock $lockfile");
415 alarm(0);
416 };
417 fatal_error("Lock timed out") if $@ =~ /timeout/;
418 return $fh;
419 }
420  
421  
422 sub do_unlock {
423 my $fh = shift;
424 return unless $fh;
425 flock($fh,LOCK_UN);
426 my $lockfile = get_lockfile();
427 unlink $lockfile;
428 }
429  
430 sub get_lockfile {
431 return File::Spec->catfile(File::Spec->tmpdir,
432 "load_balance.$>.lock");
433 }