1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
|
#!/bin/perl
#============================================================= -*-perl-*-
#
# BackupPC: Main program for PC backups.
#
# DESCRIPTION
#
# BackupPC reads the configuration and status information from
# $TopDir/conf. It then runs and manages all the backup activity.
#
# As specified by $Conf{WakeupSchedule}, BackupPC wakes up periodically
# to queue backups on all the PCs. This is a four step process:
# 1) For each host and DHCP address backup requests are queued on the
# background command queue.
# 2) For each PC, BackupPC_dump is forked. Several of these may
# be run in parallel, based on the configuration.
# 3) For each complete, good, backup, BackupPC_link is forked.
# Only one of these tasks runs at a time.
# 4) In the background BackupPC_trashClean is run to remove any expired
# backups. Once each night, BackupPC_nightly is run to complete some
# additional administrative tasks (pool cleaning etc).
#
# BackupPC also listens for connections on a unix domain socket and
# the tcp port $Conf{ServerPort}, which are used by various
# sub-programs and the CGI script BackupPC_Admin for status reporting
# and user-initiated backup or backup cancel requests.
#
# AUTHOR
# Craig Barratt <cbarratt@users.sourceforge.net>
#
# COPYRIGHT
# Copyright (C) 2001-2003 Craig Barratt
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#========================================================================
#
# Version 2.1.1, released 13 Mar 2005.
#
# See http://backuppc.sourceforge.net.
#
#========================================================================
use strict;
no utf8;
use vars qw(%Status %Info $Hosts);
use lib "__INSTALLDIR__/lib";
use BackupPC::Lib;
use BackupPC::FileZIO;
use File::Path;
use Data::Dumper;
use Getopt::Std;
use Socket;
use Carp;
use Digest::MD5;
use POSIX qw(setsid);
###########################################################################
# Handle command line options
###########################################################################
my %opts;
if ( !getopts("d", \%opts) || @ARGV != 0 ) {
print("usage: $0 [-d]\n");
exit(1);
}
###########################################################################
# Initialize major data structures and variables
###########################################################################
#
# Get an instance of BackupPC::Lib and get some shortcuts.
#
die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
my $TopDir = $bpc->TopDir();
my $BinDir = $bpc->BinDir();
my %Conf = $bpc->Conf();
#
# Verify we are running as the correct user
#
if ( $Conf{BackupPCUserVerify}
&& $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
}
#
# %Status maintain status information about each host.
# It is a hash of hashes, whose first index is the host.
#
%Status = ();
#
# %Info is a hash giving general information about BackupPC status.
#
%Info = ();
#
# Read old status
#
if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
die "couldn't parse $TopDir/log/status.pl: $@" if $@;
die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
die "couldn't run $TopDir/log/status.pl";
}
#
# %Jobs maintains information about currently running jobs.
# It is a hash of hashes, whose first index is the host.
#
my %Jobs = ();
#
# There are three command queues:
# - @UserQueue is a queue of user initiated backup requests.
# - @BgQueue is a queue of automatically scheduled backup requests.
# - @CmdQueue is a queue of administrative jobs, including tasks
# like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
# Each queue is an array of hashes. Each hash stores information
# about the command request.
#
my @UserQueue = ();
my @CmdQueue = ();
my @BgQueue = ();
#
# To quickly lookup if a given host is on a given queue, we keep
# a hash of flags for each queue type.
#
my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
#
# One or more clients can connect to the server to get status information
# or request/cancel backups etc. The %Clients hash maintains information
# about each of these socket connections. The hash key is an incrementing
# number stored in $ClientConnCnt. Each entry is a hash that contains
# various information about the client connection.
#
my %Clients = ();
my $ClientConnCnt;
#
# Read file descriptor mask used by select(). Every file descriptor
# on which we expect to read (or accept) has the corresponding bit
# set.
#
my $FDread = '';
#
# Unix seconds when we next wakeup. A value of zero forces the scheduler
# to compute the next wakeup time.
#
my $NextWakeup = 0;
#
# Name of signal saved by catch_signal
#
my $SigName = "";
#
# Misc variables
#
my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
my($BackupPCNightlyJobs, $BackupPCNightlyLock);
#
# Complete the rest of the initialization
#
Main_Initialize();
###########################################################################
# Main loop
###########################################################################
while ( 1 )
{
#
# Check if we can/should run BackupPC_nightly
#
Main_TryToRun_nightly();
#
# Check if we can run a new command from @CmdQueue.
#
Main_TryToRun_CmdQueue();
#
# Check if we can run a new command from @UserQueue or @BgQueue.
#
Main_TryToRun_Bg_or_User_Queue();
#
# Do a select() to wait for the next interesting thing to happen
# (timeout, signal, someone sends a message, child dies etc).
#
my $fdRead = Main_Select();
#
# Process a signal if we received one.
#
if ( $SigName ) {
Main_Process_Signal();
$fdRead = undef;
}
#
# Check if a timeout has occurred.
#
Main_Check_Timeout();
#
# Check for, and process, any messages (output) from our jobs
#
Main_Check_Job_Messages($fdRead);
#
# Check for, and process, any output from our clients. Also checks
# for new connections to our SERVER_UNIX and SERVER_INET sockets.
#
Main_Check_Client_Messages($fdRead);
}
############################################################################
# Main_Initialize()
#
# Main initialization routine. Called once at statup.
############################################################################
sub Main_Initialize
{
umask($Conf{UmaskMode});
#
# Check for another running process, check that PASSWD is set and
# verify executables are configured correctly.
#
if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
print(STDERR $bpc->timeStamp,
"Another BackupPC is running (pid $Info{pid}); quitting...\n");
exit(1);
}
foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
SendmailPath SshPath) ) {
next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
print(STDERR $bpc->timeStamp,
"\$Conf{$progName} = '$Conf{$progName}' is not a"
. " valid executable program\n");
exit(1);
}
if ( $opts{d} ) {
#
# daemonize by forking
#
my $pid;
defined($pid = fork) or die "Can't fork: $!"; exit if $pid; # parent exits
POSIX::setsid();
defined($pid = fork) or die "Can't fork: $!"; exit if $pid; # parent exits
chdir ("/") or die ("Cannot chdir to /: $!\n");
close(STDIN); open (STDIN , ">/dev/null") or die ("Cannot open /dev/null as stdin\n");
# STDOUT and STDERR are handled in LogFileOpen() right below,
# otherwise we would have to reopen them too.
#close(STDOUT); open (STDOUT, ">/dev/null") or die ("Cannot open /dev/null as stdout\n");
#close(STDERR); open (STDERR, ">/dev/null") or die ("Cannot open /dev/null as stderr\n");
}
#
# Open the LOG file and redirect STDOUT, STDERR etc
#
LogFileOpen();
#
# Read the hosts file (force a read).
#
exit(1) if ( !HostsUpdate(1) );
#
# Clean up %ENV for taint checking
#
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
$ENV{PATH} = $Conf{MyPath};
#
# Initialize server sockets
#
ServerSocketInit();
#
# Catch various signals
#
foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
$SIG{$sig} = \&catch_signal;
}
#
# Report that we started, and update %Info.
#
print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
$Info{ConfigModTime} = $bpc->ConfigMTime();
$Info{pid} = $$;
$Info{startTime} = time;
$Info{ConfigLTime} = time;
$Info{Version} = $bpc->{Version};
#
# Update the status left over form the last time BackupPC ran.
# Requeue any pending links.
#
foreach my $host ( sort(keys(%$Hosts)) ) {
if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
#
# should we restart it? skip it for now.
#
$Status{$host}{state} = "Status_idle";
} elsif ( $Status{$host}{state} eq "Status_link_pending"
|| $Status{$host}{state} eq "Status_link_running" ) {
QueueLink($host);
} else {
$Status{$host}{state} = "Status_idle";
}
$Status{$host}{activeJob} = 0;
}
foreach my $host ( sort(keys(%Status)) ) {
next if ( defined($Hosts->{$host}) );
delete($Status{$host});
}
#
# Write out our initial status and save our PID
#
StatusWrite();
if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
print(PID $$);
close(PID);
}
#
# For unknown reasons there is a very infrequent error about not
# being able to coerce GLOBs inside the XS Data::Dumper. I've
# only seen this on a particular platform and perl version.
# For now the workaround appears to be use the perl version of
# XS Data::Dumper.
#
$Data::Dumper::Useqq = 1;
}
############################################################################
# Main_TryToRun_nightly()
#
# Checks to see if we can/should run BackupPC_nightly or
# BackupPC_trashClean. If so we push the appropriate command onto
# @CmdQueue.
############################################################################
sub Main_TryToRun_nightly
{
#
# Check if we should run BackupPC_nightly or BackupPC_trashClean.
# BackupPC_nightly is run when the current job queue is empty.
# BackupPC_trashClean is run in the background always.
#
my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
#
# This should only happen once at startup, but just in case this
# code will re-start BackupPC_trashClean if it quits
#
unshift(@CmdQueue, {
host => $bpc->trashJob,
user => "BackupPC",
reqTime => time,
cmd => ["$BinDir/BackupPC_trashClean"],
});
$CmdQueueOn{$bpc->trashJob} = 1;
}
if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
#
# Queue multiple nightly jobs based on the configuration
#
$Conf{MaxBackupPCNightlyJobs} = 1
if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
$Conf{BackupPCNightlyPeriod} = 1
if ( $Conf{BackupPCNightlyPeriod} <= 0 );
#
# Decide what subset of the 16 top-level directories 0..9a..f
# we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
# If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
# time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
# 0..7 one night and 89a-f the next night. And so on.
#
# $Info{NightlyPhase} counts which night, from 0 to
# $Conf{BackupPCNightlyPeriod} - 1.
#
my $start = int($Info{NightlyPhase} * 16
/ $Conf{BackupPCNightlyPeriod});
my $end = int(($Info{NightlyPhase} + 1) * 16
/ $Conf{BackupPCNightlyPeriod});
$end = $start + 1 if ( $end <= $start );
$Info{NightlyPhase}++;
$Info{NightlyPhase} = 0 if ( $end >= 16 );
#
# Zero out the data we expect to get from BackupPC_nightly.
# In the future if we want to split BackupPC_nightly over
# more than one night we will only zero out the portion
# that we are running right now.
#
for my $p ( qw(pool cpool) ) {
for ( my $i = $start ; $i < $end ; $i++ ) {
$Info{pool}{$p}[$i]{FileCnt} = 0;
$Info{pool}{$p}[$i]{DirCnt} = 0;
$Info{pool}{$p}[$i]{Kb} = 0;
$Info{pool}{$p}[$i]{Kb2} = 0;
$Info{pool}{$p}[$i]{KbRm} = 0;
$Info{pool}{$p}[$i]{FileCntRm} = 0;
$Info{pool}{$p}[$i]{FileCntRep} = 0;
$Info{pool}{$p}[$i]{FileRepMax} = 0;
$Info{pool}{$p}[$i]{FileCntRename} = 0;
$Info{pool}{$p}[$i]{FileLinkMax} = 0;
$Info{pool}{$p}[$i]{Time} = 0;
}
}
print(LOG $bpc->timeStamp,
sprintf("Running %d BackupPC_nightly jobs from %d..%d"
. " (out of 0..15)\n",
$Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
#
# Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
# The granularity on start and end is now 0..256.
#
$start *= 16;
$end *= 16;
my $start0 = $start;
for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
#
# The first nightly job gets the -m option (does email, log aging).
# All jobs get the start and end options from 0..255 telling
# them which parts of the pool to traverse.
#
my $cmd = ["$BinDir/BackupPC_nightly"];
push(@$cmd, "-m") if ( $i == 0 );
push(@$cmd, $start);
$start = $start0 + int(($end - $start0)
* ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
push(@$cmd, $start - 1);
my $job = $bpc->adminJob($i);
unshift(@CmdQueue, {
host => $job,
user => "BackupPC",
reqTime => time,
cmd => $cmd,
});
$CmdQueueOn{$job} = 1;
}
$RunNightlyWhenIdle = 2;
}
}
############################################################################
# Main_TryToRun_CmdQueue()
#
# Decide if we can run a new command from the @CmdQueue.
# We only run one of these at a time. The @CmdQueue is
# used to run BackupPC_link (for the corresponding host),
# BackupPC_trashClean, and BackupPC_nightly using a fake
# host name of $bpc->adminJob.
############################################################################
sub Main_TryToRun_CmdQueue
{
my($req, $host);
while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
|| @CmdQueue > 0 && $RunNightlyWhenIdle == 2
&& $bpc->isAdminJob($CmdQueue[0]->{host})
) {
local(*FH);
$req = pop(@CmdQueue);
$host = $req->{host};
if ( defined($Jobs{$host}) ) {
print(LOG $bpc->timeStamp,
"Botch on admin job for $host: already in use!!\n");
#
# This could happen during normal opertion: a user could
# request a backup while a BackupPC_link is queued from
# a previous backup. But it is unlikely. Just put this
# request back on the end of the queue.
#
unshift(@CmdQueue, $req);
return;
}
$CmdQueueOn{$host} = 0;
my $cmd = $req->{cmd};
my $pid = open(FH, "-|");
if ( !defined($pid) ) {
print(LOG $bpc->timeStamp,
"can't fork for $host, request by $req->{user}\n");
close(FH);
next;
}
if ( !$pid ) {
setpgrp 0,0;
exec(@$cmd);
print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
exit(0);
}
$Jobs{$host}{pid} = $pid;
$Jobs{$host}{fh} = *FH;
$Jobs{$host}{fn} = fileno(FH);
vec($FDread, $Jobs{$host}{fn}, 1) = 1;
$Jobs{$host}{startTime} = time;
$Jobs{$host}{reqTime} = $req->{reqTime};
$cmd = $bpc->execCmd2ShellCmd(@$cmd);
$Jobs{$host}{cmd} = $cmd;
$Jobs{$host}{user} = $req->{user};
$Jobs{$host}{type} = $Status{$host}{type};
$Status{$host}{state} = "Status_link_running";
$Status{$host}{activeJob} = 1;
$Status{$host}{endTime} = time;
$CmdJob = $host if ( $host ne $bpc->trashJob );
$cmd =~ s/$BinDir\///g;
print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
if ( $cmd =~ /^BackupPC_nightly\s/ ) {
$BackupPCNightlyJobs++;
$BackupPCNightlyLock++;
}
}
}
############################################################################
# Main_TryToRun_Bg_or_User_Queue()
#
# Decide if we can run any new backup requests from @BgQueue
# or @UserQueue. Several of these can be run at the same time
# based on %Conf settings. Jobs from @UserQueue take priority,
# and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
# simultaneous jobs can run from @UserQueue. After @UserQueue
# is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
# run from @BgQueue.
############################################################################
sub Main_TryToRun_Bg_or_User_Queue
{
my($req, $host);
while ( $RunNightlyWhenIdle == 0 ) {
local(*FH);
my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
my $nJobs = keys(%Jobs);
#
# CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
#
$nJobs -= $BackupPCNightlyJobs if ( $CmdJob ne "" );
$nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
&& @UserQueue > 0 ) {
$req = pop(@UserQueue);
if ( defined($Jobs{$req->{host}}) ) {
push(@deferUserQueue, $req);
next;
}
push(@args, $req->{doFull} ? "-f" : "-i")
if (( !$req->{restore} ) && ( !$req->{archive} ));
$UserQueueOn{$req->{host}} = 0;
} elsif ( $nJobs < $Conf{MaxBackups}
&& (@CmdQueue + $nJobs)
<= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
&& @BgQueue > 0 ) {
my $du;
if ( time - $Info{DUlastValueTime} >= 60 ) {
#
# Update our notion of disk usage no more than
# once every minute
#
$du = $bpc->CheckFileSystemUsage($TopDir);
$Info{DUlastValue} = $du;
$Info{DUlastValueTime} = time;
} else {
#
# if we recently checked it then just use the old value
#
$du = $Info{DUlastValue};
}
if ( $Info{DUDailyMaxReset} ) {
$Info{DUDailyMaxStartTime} = time;
$Info{DUDailyMaxReset} = 0;
$Info{DUDailyMax} = 0;
}
if ( $du > $Info{DUDailyMax} ) {
$Info{DUDailyMax} = $du;
$Info{DUDailyMaxTime} = time;
}
if ( $du > $Conf{DfMaxUsagePct} ) {
my $nSkip = @BgQueue + @deferBgQueue;
print(LOG $bpc->timeStamp,
"Disk too full ($du%); skipping $nSkip hosts\n");
$Info{DUDailySkipHostCnt} += $nSkip;
@BgQueue = ();
@deferBgQueue = ();
%BgQueueOn = ();
next;
}
$req = pop(@BgQueue);
if ( defined($Jobs{$req->{host}}) ) {
push(@deferBgQueue, $req);
next;
}
$BgQueueOn{$req->{host}} = 0;
} else {
while ( @deferBgQueue ) {
push(@BgQueue, pop(@deferBgQueue));
}
while ( @deferUserQueue ) {
push(@UserQueue, pop(@deferUserQueue));
}
last;
}
$host = $req->{host};
my $user = $req->{user};
if ( $req->{restore} ) {
$progName = "BackupPC_restore";
$type = "restore";
push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
} elsif ( $req->{archive} ) {
$progName = "BackupPC_archive";
$type = "archive";
push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
} else {
$progName = "BackupPC_dump";
$type = "backup";
push(@args, "-d") if ( $req->{dhcp} );
push(@args, "-e") if ( $req->{dumpExpire} );
push(@args, $host);
}
my $pid = open(FH, "-|");
if ( !defined($pid) ) {
print(LOG $bpc->timeStamp,
"can't fork to run $progName for $host, request by $user\n");
close(FH);
next;
}
if ( !$pid ) {
setpgrp 0,0;
exec("$BinDir/$progName", @args);
print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
exit(0);
}
$Jobs{$host}{pid} = $pid;
$Jobs{$host}{fh} = *FH;
$Jobs{$host}{fn} = fileno(FH);
$Jobs{$host}{dhcp} = $req->{dhcp};
vec($FDread, $Jobs{$host}{fn}, 1) = 1;
$Jobs{$host}{startTime} = time;
$Jobs{$host}{reqTime} = $req->{reqTime};
$Jobs{$host}{userReq} = $req->{userReq};
$Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
$Jobs{$host}{user} = $user;
$Jobs{$host}{type} = $type;
$Status{$host}{userReq} = $req->{userReq}
if ( defined($Hosts->{$host}) );
if ( !$req->{dhcp} ) {
$Status{$host}{state} = "Status_".$type."_starting";
$Status{$host}{activeJob} = 1;
$Status{$host}{startTime} = time;
$Status{$host}{endTime} = "";
}
}
}
############################################################################
# Main_Select()
#
# If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
# and then do a select() to wait for the next thing to happen
# (timeout, signal, someone sends a message, child dies etc).
############################################################################
sub Main_Select
{
if ( $NextWakeup <= 0 ) {
#
# Figure out when to next wakeup based on $Conf{WakeupSchedule}.
#
my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
= localtime(time);
my($currHours) = $hour + $min / 60 + $sec / 3600;
if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
ServerReload("Re-read config file because mtime changed");
}
my $delta = -1;
foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
next if ( $t < 0 || $t > 24 );
my $tomorrow = $t + 24;
if ( $delta < 0
|| ($tomorrow - $currHours > 0
&& $delta > $tomorrow - $currHours) ) {
$delta = $tomorrow - $currHours;
$FirstWakeup = $t == $Conf{WakeupSchedule}[0];
}
if ( $delta < 0
|| ($t - $currHours > 0 && $delta > $t - $currHours) ) {
$delta = $t - $currHours;
$FirstWakeup = $t == $Conf{WakeupSchedule}[0];
}
}
$NextWakeup = time + $delta * 3600;
$Info{nextWakeup} = $NextWakeup;
print(LOG $bpc->timeStamp, "Next wakeup is ",
$bpc->timeStamp($NextWakeup, 1), "\n");
}
#
# Call select(), waiting until either a signal, a timeout,
# any output from our jobs, or any messages from clients
# connected via tcp.
# select() is where we (hopefully) spend most of our time blocked...
#
my $timeout = $NextWakeup - time;
$timeout = 1 if ( $timeout <= 0 );
my $ein = $FDread;
select(my $rout = $FDread, undef, $ein, $timeout);
return $rout;
}
############################################################################
# Main_Process_Signal()
#
# Signal handler.
############################################################################
sub Main_Process_Signal
{
#
# Process signals
#
if ( $SigName eq "HUP" ) {
ServerReload("Re-read config file because of a SIG_HUP");
} elsif ( $SigName ) {
ServerShutdown("Got signal $SigName... cleaning up");
}
$SigName = "";
}
############################################################################
# Main_Check_Timeout()
#
# Check if a timeout has occured, and if so, queue all the PCs for backups.
# Also does log file aging on the first timeout after midnight.
############################################################################
sub Main_Check_Timeout
{
#
# Process timeouts
#
return if ( time < $NextWakeup || $NextWakeup <= 0 );
$NextWakeup = 0;
if ( $FirstWakeup ) {
#
# This is the first wakeup after midnight. Do log file aging
# and various house keeping.
#
$FirstWakeup = 0;
printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
. " %d skipped hosts\n",
$bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
$Info{DUDailySkipHostCnt});
$Info{DUDailyMaxReset} = 1;
$Info{DUDailyMaxPrev} = $Info{DUDailyMax};
$Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
$Info{DUDailySkipHostCnt} = 0;
my $lastLog = $Conf{MaxOldLogFiles} - 1;
if ( -f "$TopDir/log/LOG.$lastLog" ) {
print(LOG $bpc->timeStamp,
"Removing $TopDir/log/LOG.$lastLog\n");
unlink("$TopDir/log/LOG.$lastLog");
}
if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
print(LOG $bpc->timeStamp,
"Removing $TopDir/log/LOG.$lastLog.z\n");
unlink("$TopDir/log/LOG.$lastLog.z");
}
print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
. "LOG.1 -> ... -> LOG.$lastLog\n");
close(STDERR); # dup of LOG
close(STDOUT); # dup of LOG
close(LOG);
for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
my $j = $i + 1;
rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
if ( -f "$TopDir/log/LOG.$i" );
rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
if ( -f "$TopDir/log/LOG.$i.z" );
}
#
# Compress the log file LOG -> LOG.0.z (if enabled).
# Otherwise, just rename LOG -> LOG.0.
#
BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
"$TopDir/log/LOG.0.z",
"$TopDir/log/LOG.0",
$Conf{CompressLevel}, 1);
LogFileOpen();
#
# Remember to run nightly script after current jobs are done
#
$RunNightlyWhenIdle = 1;
}
#
# Write out the current status and then queue all the PCs
#
HostsUpdate(0);
StatusWrite();
%BgQueueOn = () if ( @BgQueue == 0 );
%UserQueueOn = () if ( @UserQueue == 0 );
%CmdQueueOn = () if ( @CmdQueue == 0 );
QueueAllPCs();
}
############################################################################
# Main_Check_Job_Messages($fdRead)
#
# Check if select() says we have bytes waiting from any of our jobs.
# Handle each of the messages when complete (newline terminated).
############################################################################
sub Main_Check_Job_Messages
{
my($fdRead) = @_;
foreach my $host ( keys(%Jobs) ) {
next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
my $mesg;
#
# do a last check to make sure there is something to read so
# we are absolutely sure we won't block.
#
vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
if ( !select($readMask, undef, undef, 0.0) ) {
print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
. " nothing to read from $host. Debug dump:\n");
my($dump) = Data::Dumper->new(
[ \%Clients, \%Jobs, \$FDread, \$fdRead],
[qw(*Clients, *Jobs *FDread, *fdRead)]);
$dump->Indent(1);
print(LOG $dump->Dump);
next;
}
my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
$Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
#
# Process any complete lines of output from this jobs.
# Any output to STDOUT or STDERR from the children is processed here.
#
while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
$mesg = $1;
$Jobs{$host}{mesg} = $2;
if ( $Jobs{$host}{dhcp} ) {
if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
my $newHost = $bpc->uriUnesc($2);
if ( defined($Jobs{$newHost}) ) {
print(LOG $bpc->timeStamp,
"Backup on $newHost is already running\n");
kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
$nbytes = 0;
last;
}
$Jobs{$host}{dhcpHostIP} = $host;
$Status{$newHost}{dhcpHostIP} = $host;
$Jobs{$newHost} = $Jobs{$host};
delete($Jobs{$host});
$host = $newHost;
$Status{$host}{state} = "Status_backup_starting";
$Status{$host}{activeJob} = 1;
$Status{$host}{startTime} = $Jobs{$host}{startTime};
$Status{$host}{endTime} = "";
$Jobs{$host}{dhcp} = 0;
} else {
print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
}
} elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
$Jobs{$host}{type} = $1;
$Jobs{$host}{shareName} = $2;
print(LOG $bpc->timeStamp,
"Started $1 backup on $host (pid=$Jobs{$host}{pid}",
$Jobs{$host}{dhcpHostIP}
? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
", share=$Jobs{$host}{shareName})\n");
$Status{$host}{state} = "Status_backup_in_progress";
$Status{$host}{reason} = "";
$Status{$host}{type} = $1;
$Status{$host}{startTime} = time;
$Status{$host}{deadCnt} = 0;
$Status{$host}{aliveCnt}++;
$Status{$host}{dhcpCheckCnt}--
if ( $Status{$host}{dhcpCheckCnt} > 0 );
} elsif ( $mesg =~ /^xferPids (.*)/ ) {
$Jobs{$host}{xferPid} = $1;
} elsif ( $mesg =~ /^started_restore/ ) {
$Jobs{$host}{type} = "restore";
print(LOG $bpc->timeStamp,
"Started restore on $host"
. " (pid=$Jobs{$host}{pid})\n");
$Status{$host}{state} = "Status_restore_in_progress";
$Status{$host}{reason} = "";
$Status{$host}{type} = "restore";
$Status{$host}{startTime} = time;
$Status{$host}{deadCnt} = 0;
$Status{$host}{aliveCnt}++;
} elsif ( $mesg =~ /^started_archive/ ) {
$Jobs{$host}{type} = "archive";
print(LOG $bpc->timeStamp,
"Started archive on $host"
. " (pid=$Jobs{$host}{pid})\n");
$Status{$host}{state} = "Status_archive_in_progress";
$Status{$host}{reason} = "";
$Status{$host}{type} = "archive";
$Status{$host}{startTime} = time;
$Status{$host}{deadCnt} = 0;
$Status{$host}{aliveCnt}++;
} elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
$Status{$host}{reason} = "Reason_backup_done";
delete($Status{$host}{error});
delete($Status{$host}{errorTime});
$Status{$host}{endTime} = time;
$Status{$host}{lastGoodBackupTime} = time;
} elsif ( $mesg =~ /^backups disabled/ ) {
print(LOG $bpc->timeStamp,
"Ignoring old backup error on $host\n");
$Status{$host}{reason} = "Reason_backup_done";
delete($Status{$host}{error});
delete($Status{$host}{errorTime});
$Status{$host}{endTime} = time;
} elsif ( $mesg =~ /^restore complete/ ) {
print(LOG $bpc->timeStamp, "Finished restore on $host\n");
$Status{$host}{reason} = "Reason_restore_done";
delete($Status{$host}{error});
delete($Status{$host}{errorTime});
$Status{$host}{endTime} = time;
} elsif ( $mesg =~ /^archive complete/ ) {
print(LOG $bpc->timeStamp, "Finished archive on $host\n");
$Status{$host}{reason} = "Reason_archive_done";
delete($Status{$host}{error});
delete($Status{$host}{errorTime});
$Status{$host}{endTime} = time;
} elsif ( $mesg =~ /^nothing to do/ ) {
if ( $Status{$host}{reason} ne "Reason_backup_failed"
&& $Status{$host}{reason} ne "Reason_restore_failed" ) {
$Status{$host}{state} = "Status_idle";
$Status{$host}{reason} = "Reason_nothing_to_do";
$Status{$host}{startTime} = time;
}
$Status{$host}{dhcpCheckCnt}--
if ( $Status{$host}{dhcpCheckCnt} > 0 );
} elsif ( $mesg =~ /^no ping response/
|| $mesg =~ /^ping too slow/
|| $mesg =~ /^host not found/ ) {
$Status{$host}{state} = "Status_idle";
if ( $Status{$host}{userReq}
|| $Status{$host}{reason} ne "Reason_backup_failed"
|| $Status{$host}{error} =~ /^aborted by user/ ) {
$Status{$host}{reason} = "Reason_no_ping";
$Status{$host}{error} = $mesg;
$Status{$host}{startTime} = time;
}
$Status{$host}{deadCnt}++;
if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
$Status{$host}{aliveCnt} = 0;
}
} elsif ( $mesg =~ /^dump failed: (.*)/ ) {
$Status{$host}{state} = "Status_idle";
$Status{$host}{error} = $1;
$Status{$host}{errorTime} = time;
$Status{$host}{endTime} = time;
if ( $Status{$host}{reason}
eq "Reason_backup_canceled_by_user" ) {
print(LOG $bpc->timeStamp,
"Backup canceled on $host ($1)\n");
} else {
$Status{$host}{reason} = "Reason_backup_failed";
print(LOG $bpc->timeStamp,
"Backup failed on $host ($1)\n");
}
} elsif ( $mesg =~ /^restore failed: (.*)/ ) {
$Status{$host}{state} = "Status_idle";
$Status{$host}{error} = $1;
$Status{$host}{errorTime} = time;
$Status{$host}{endTime} = time;
if ( $Status{$host}{reason}
eq "Reason_restore_canceled_by_user" ) {
print(LOG $bpc->timeStamp,
"Restore canceled on $host ($1)\n");
} else {
$Status{$host}{reason} = "Reason_restore_failed";
print(LOG $bpc->timeStamp,
"Restore failed on $host ($1)\n");
}
} elsif ( $mesg =~ /^archive failed: (.*)/ ) {
$Status{$host}{state} = "Status_idle";
$Status{$host}{error} = $1;
$Status{$host}{errorTime} = time;
$Status{$host}{endTime} = time;
if ( $Status{$host}{reason}
eq "Reason_archive_canceled_by_user" ) {
print(LOG $bpc->timeStamp,
"Archive canceled on $host ($1)\n");
} else {
$Status{$host}{reason} = "Reason_archive_failed";
print(LOG $bpc->timeStamp,
"Archive failed on $host ($1)\n");
}
} elsif ( $mesg =~ /^log\s+(.*)/ ) {
print(LOG $bpc->timeStamp, "$1\n");
} elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
my $chunk = int($1 / 16);
my @f = split(/,/, $2);
$Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
$Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
$Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
$Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
$Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
$Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
$Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
$Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
$Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
$Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
$Info{pool}{$f[0]}[$chunk]{Time} = time;
} elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
$BackupPCNightlyLock--;
if ( $BackupPCNightlyLock == 0 ) {
#
# This means the last BackupPC_nightly is done with
# the pool clean, so it's to start running regular
# backups again.
#
$RunNightlyWhenIdle = 0;
}
} elsif ( $mesg =~ /^processState\s+(.+)/ ) {
$Jobs{$host}{processState} = $1;
} elsif ( $mesg =~ /^link\s+(.+)/ ) {
my($h) = $1;
$Status{$h}{needLink} = 1;
} else {
print(LOG $bpc->timeStamp, "$host: $mesg\n");
}
}
#
# shut down the client connection if we read EOF
#
if ( $nbytes <= 0 ) {
close($Jobs{$host}{fh});
vec($FDread, $Jobs{$host}{fn}, 1) = 0;
if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
my $cmd = $Jobs{$host}{cmd};
$cmd =~ s/$BinDir\///g;
print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
$Status{$host}{state} = "Status_idle";
$Status{$host}{endTime} = time;
if ( $cmd =~ /^BackupPC_nightly\s/ ) {
$BackupPCNightlyJobs--;
#print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
# . " have $BackupPCNightlyJobs running\n");
if ( $BackupPCNightlyJobs <= 0 ) {
$BackupPCNightlyJobs = 0;
$RunNightlyWhenIdle = 0;
$CmdJob = "";
#
# Combine the 16 per-directory results
#
for my $p ( qw(pool cpool) ) {
$Info{"${p}FileCnt"} = 0;
$Info{"${p}DirCnt"} = 0;
$Info{"${p}Kb"} = 0;
$Info{"${p}Kb2"} = 0;
$Info{"${p}KbRm"} = 0;
$Info{"${p}FileCntRm"} = 0;
$Info{"${p}FileCntRep"} = 0;
$Info{"${p}FileRepMax"} = 0;
$Info{"${p}FileCntRename"} = 0;
$Info{"${p}FileLinkMax"} = 0;
$Info{"${p}Time"} = 0;
for ( my $i = 0 ; $i < 16 ; $i++ ) {
$Info{"${p}FileCnt"}
+= $Info{pool}{$p}[$i]{FileCnt};
$Info{"${p}DirCnt"}
+= $Info{pool}{$p}[$i]{DirCnt};
$Info{"${p}Kb"}
+= $Info{pool}{$p}[$i]{Kb};
$Info{"${p}Kb2"}
+= $Info{pool}{$p}[$i]{Kb2};
$Info{"${p}KbRm"}
+= $Info{pool}{$p}[$i]{KbRm};
$Info{"${p}FileCntRm"}
+= $Info{pool}{$p}[$i]{FileCntRm};
$Info{"${p}FileCntRep"}
+= $Info{pool}{$p}[$i]{FileCntRep};
$Info{"${p}FileRepMax"}
= $Info{pool}{$p}[$i]{FileRepMax}
if ( $Info{"${p}FileRepMax"} <
$Info{pool}{$p}[$i]{FileRepMax} );
$Info{"${p}FileCntRename"}
+= $Info{pool}{$p}[$i]{FileCntRename};
$Info{"${p}FileLinkMax"}
= $Info{pool}{$p}[$i]{FileLinkMax}
if ( $Info{"${p}FileLinkMax"} <
$Info{pool}{$p}[$i]{FileLinkMax} );
$Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
if ( $Info{"${p}Time"} <
$Info{pool}{$p}[$i]{Time} );
}
printf(LOG "%s%s nightly clean removed %d files of"
. " size %.2fGB\n",
$bpc->timeStamp, ucfirst($p),
$Info{"${p}FileCntRm"},
$Info{"${p}KbRm"} / (1000 * 1024));
printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
. "%d max chain, %d max links), %d directories\n",
$bpc->timeStamp, ucfirst($p),
$Info{"${p}Kb"} / (1000 * 1024),
$Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
$Info{"${p}FileRepMax"},
$Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
}
}
} else {
$CmdJob = "";
}
} else {
#
# Queue BackupPC_link to complete the backup
# processing for this host.
#
if ( defined($Status{$host})
&& ($Status{$host}{reason} eq "Reason_backup_done"
|| $Status{$host}{needLink}) ) {
QueueLink($host);
} elsif ( defined($Status{$host}) ) {
$Status{$host}{state} = "Status_idle";
}
}
delete($Jobs{$host});
$Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
}
}
#
# When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
# do a pass over %Status updating the deadCnt and aliveCnt for
# DHCP hosts. The reason we need to do this later is we can't
# be sure whether a DHCP host is alive or dead until we have passed
# over all the DHCP pool.
#
return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
foreach my $host ( keys(%Status) ) {
next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
$Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
$Status{$host}{dhcpCheckCnt} = 0;
if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
$Status{$host}{aliveCnt} = 0;
}
}
}
############################################################################
# Main_Check_Client_Messages($fdRead)
#
# Check for, and process, any output from our clients. Also checks
# for new connections to our SERVER_UNIX and SERVER_INET sockets.
############################################################################
sub Main_Check_Client_Messages
{
my($fdRead) = @_;
foreach my $client ( keys(%Clients) ) {
next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
my($mesg, $host);
#
# do a last check to make sure there is something to read so
# we are absolutely sure we won't block.
#
vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
if ( !select($readMask, undef, undef, 0.0) ) {
print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
. " nothing to read from $client. Debug dump:\n");
my($dump) = Data::Dumper->new(
[ \%Clients, \%Jobs, \$FDread, \$fdRead],
[qw(*Clients, *Jobs *FDread, *fdRead)]);
$dump->Indent(1);
print(LOG $dump->Dump);
next;
}
my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
$Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
#
# Process any complete lines received from this client.
#
while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
my($reply);
my $cmd = $1;
$Clients{$client}{mesg} = $2;
#
# Authenticate the message by checking the MD5 digest
#
my $md5 = Digest::MD5->new;
if ( $cmd !~ /^(.{22}) (.*)/
|| ($md5->add($Clients{$client}{seed}
. $Clients{$client}{mesgCnt}
. $Conf{ServerMesgSecret} . $2),
$md5->b64digest ne $1) ) {
print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
. " client '$Clients{$client}{clientName}':"
. " shutting down client connection\n");
$nbytes = 0;
last;
}
$Clients{$client}{mesgCnt}++;
$cmd = $2;
if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
$host = $1;
my $user = $2;
my $backoff = $3;
$host = $bpc->uriUnesc($host);
if ( $CmdJob ne $host && defined($Status{$host})
&& defined($Jobs{$host}) ) {
print(LOG $bpc->timeStamp,
"Stopping current $Jobs{$host}{type} of $host,"
. " request by $user (backoff=$backoff)\n");
kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
#
# Don't close the pipe now; wait until the child
# really exits later. Otherwise close() will
# block until the child has exited.
# old code:
##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
##close($Jobs{$host}{fh});
##delete($Jobs{$host});
$Status{$host}{state} = "Status_idle";
if ( $Jobs{$host}{type} eq "restore" ) {
$Status{$host}{reason}
= "Reason_restore_canceled_by_user";
} elsif ( $Jobs{$host}{type} eq "archive" ) {
$Status{$host}{reason}
= "Reason_archive_canceled_by_user";
} else {
$Status{$host}{reason}
= "Reason_backup_canceled_by_user";
}
$Status{$host}{activeJob} = 0;
$Status{$host}{startTime} = time;
$reply = "ok: $Jobs{$host}{type} of $host canceled";
} elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
print(LOG $bpc->timeStamp,
"Stopping pending backup of $host,"
. " request by $user (backoff=$backoff)\n");
@BgQueue = grep($_->{host} ne $host, @BgQueue);
@UserQueue = grep($_->{host} ne $host, @UserQueue);
$BgQueueOn{$host} = $UserQueueOn{$host} = 0;
$reply = "ok: pending backup of $host canceled";
} else {
print(LOG $bpc->timeStamp,
"Nothing to do for stop backup of $host,"
. " request by $user (backoff=$backoff)\n");
$reply = "ok: no backup was pending or running";
}
if ( defined($Status{$host}) && $backoff ne "" ) {
if ( $backoff > 0 ) {
$Status{$host}{backoffTime} = time + $backoff * 3600;
} else {
delete($Status{$host}{backoffTime});
}
}
} elsif ( $cmd =~ /^backup all$/ ) {
QueueAllPCs();
} elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
$RunNightlyWhenIdle = 1;
} elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
my $hostIP = $1;
$host = $2;
my $user = $3;
my $doFull = $4;
$host = $bpc->uriUnesc($host);
$hostIP = $bpc->uriUnesc($hostIP);
if ( !defined($Status{$host}) ) {
print(LOG $bpc->timeStamp,
"User $user requested backup of unknown host"
. " $host\n");
$reply = "error: unknown host $host";
} elsif ( defined($Jobs{$host})
&& $Jobs{$host}{type} ne "restore" ) {
print(LOG $bpc->timeStamp,
"User $user requested backup of $host,"
. " but one is currently running\n");
$reply = "error: backup of $host is already running";
} else {
print(LOG $bpc->timeStamp,
"User $user requested backup of $host"
. " ($hostIP)\n");
if ( $BgQueueOn{$hostIP} ) {
@BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
$BgQueueOn{$hostIP} = 0;
}
if ( $UserQueueOn{$hostIP} ) {
@UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
$UserQueueOn{$hostIP} = 0;
}
unshift(@UserQueue, {
host => $hostIP,
user => $user,
reqTime => time,
doFull => $doFull,
userReq => 1,
dhcp => $hostIP eq $host ? 0 : 1,
});
$UserQueueOn{$hostIP} = 1;
$reply = "ok: requested backup of $host";
}
} elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
my $user = $1;
my $archivehost = $2;
my $reqFileName = $3;
$host = $bpc->uriUnesc($archivehost);
if ( !defined($Status{$host}) ) {
print(LOG $bpc->timeStamp,
"User $user requested archive of unknown archive host"
. " $host");
$reply = "archive error: unknown archive host $host";
} else {
print(LOG $bpc->timeStamp,
"User $user requested archive on $host"
. " ($host)\n");
if ( defined($Jobs{$host}) ) {
$reply = "Archive currently running on $host, please try later";
} else {
unshift(@UserQueue, {
host => $host,
hostIP => $user,
reqFileName => $reqFileName,
reqTime => time,
dhcp => 0,
archive => 1,
userReq => 1,
});
$UserQueueOn{$host} = 1;
$reply = "ok: requested archive on $host";
}
}
} elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
my $hostIP = $1;
$host = $2;
my $user = $3;
my $reqFileName = $4;
$host = $bpc->uriUnesc($host);
$hostIP = $bpc->uriUnesc($hostIP);
if ( !defined($Status{$host}) ) {
print(LOG $bpc->timeStamp,
"User $user requested restore to unknown host"
. " $host");
$reply = "restore error: unknown host $host";
} else {
print(LOG $bpc->timeStamp,
"User $user requested restore to $host"
. " ($hostIP)\n");
unshift(@UserQueue, {
host => $host,
hostIP => $hostIP,
reqFileName => $reqFileName,
reqTime => time,
dhcp => 0,
restore => 1,
userReq => 1,
});
$UserQueueOn{$host} = 1;
if ( defined($Jobs{$host}) ) {
$reply = "ok: requested restore of $host, but a"
. " job is currently running,"
. " so this request will start later";
} else {
$reply = "ok: requested restore of $host";
}
}
} elsif ( $cmd =~ /^status\s*(.*)/ ) {
my($args) = $1;
my($dump, @values, @names);
foreach my $type ( split(/\s+/, $args) ) {
if ( $type =~ /^queues/ ) {
push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
push(@names, qw(*BgQueue *UserQueue *CmdQueue));
} elsif ( $type =~ /^jobs/ ) {
push(@values, \%Jobs);
push(@names, qw(*Jobs));
} elsif ( $type =~ /^queueLen/ ) {
push(@values, {
BgQueue => scalar(@BgQueue),
UserQueue => scalar(@UserQueue),
CmdQueue => scalar(@CmdQueue),
});
push(@names, qw(*QueueLen));
} elsif ( $type =~ /^info/ ) {
push(@values, \%Info);
push(@names, qw(*Info));
} elsif ( $type =~ /^hosts/ ) {
push(@values, \%Status);
push(@names, qw(*Status));
} elsif ( $type =~ /^host\((.*)\)/ ) {
my $h = $bpc->uriUnesc($1);
if ( defined($Status{$h}) ) {
push(@values, {
%{$Status{$h}},
BgQueueOn => $BgQueueOn{$h},
UserQueueOn => $UserQueueOn{$h},
CmdQueueOn => $CmdQueueOn{$h},
});
push(@names, qw(*StatusHost));
} else {
print(LOG $bpc->timeStamp,
"Unknown host $h for status request\n");
}
} else {
print(LOG $bpc->timeStamp,
"Unknown status request $type\n");
}
}
$dump = Data::Dumper->new(\@values, \@names);
$dump->Indent(0);
$reply = $dump->Dump;
} elsif ( $cmd =~ /^link\s+(.+)/ ) {
my($host) = $1;
$host = $bpc->uriUnesc($host);
QueueLink($host);
} elsif ( $cmd =~ /^log\s+(.*)/ ) {
print(LOG $bpc->timeStamp, "$1\n");
} elsif ( $cmd =~ /^server\s+(\w+)/ ) {
my($type) = $1;
if ( $type eq 'reload' ) {
ServerReload("Reloading config/host files via CGI request");
} elsif ( $type eq 'shutdown' ) {
$reply = "Shutting down...\n";
syswrite($Clients{$client}{fh}, $reply, length($reply));
ServerShutdown("Server shutting down...");
}
} elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
$nbytes = 0;
last;
} else {
print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
$reply = "error: bad command $cmd";
}
#
# send a reply to the client, at a minimum "ok\n".
#
$reply = "ok" if ( $reply eq "" );
$reply .= "\n";
syswrite($Clients{$client}{fh}, $reply, length($reply));
}
#
# Detect possible denial-of-service attack from sending a huge line
# (ie: never terminated). 32K seems to be plenty big enough as
# a limit.
#
if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
print(LOG $bpc->timeStamp, "Line too long from client"
. " '$Clients{$client}{clientName}':"
. " shutting down client connection\n");
$nbytes = 0;
}
#
# Shut down the client connection if we read EOF
#
if ( $nbytes <= 0 ) {
close($Clients{$client}{fh});
vec($FDread, $Clients{$client}{fn}, 1) = 0;
delete($Clients{$client});
}
}
#
# Accept any new connections on each of our listen sockets
#
if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
local(*CLIENT);
my $paddr = accept(CLIENT, SERVER_UNIX);
$ClientConnCnt++;
$Clients{$ClientConnCnt}{clientName} = "unix socket";
$Clients{$ClientConnCnt}{mesg} = "";
$Clients{$ClientConnCnt}{fh} = *CLIENT;
$Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
#
# Generate and send unique seed for MD5 digests to avoid
# replay attacks. See BackupPC::Lib::ServerMesg().
#
my $seed = time . ",$ClientConnCnt,$$,0\n";
$Clients{$ClientConnCnt}{seed} = $seed;
$Clients{$ClientConnCnt}{mesgCnt} = 0;
syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
}
if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
local(*CLIENT);
my $paddr = accept(CLIENT, SERVER_INET);
my($port,$iaddr) = sockaddr_in($paddr);
my $name = gethostbyaddr($iaddr, AF_INET);
$ClientConnCnt++;
$Clients{$ClientConnCnt}{mesg} = "";
$Clients{$ClientConnCnt}{fh} = *CLIENT;
$Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
$Clients{$ClientConnCnt}{clientName} = "$name:$port";
vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
#
# Generate and send unique seed for MD5 digests to avoid
# replay attacks. See BackupPC::Lib::ServerMesg().
#
my $seed = time . ",$ClientConnCnt,$$,$port\n";
$Clients{$ClientConnCnt}{seed} = $seed;
$Clients{$ClientConnCnt}{mesgCnt} = 0;
syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
}
}
###########################################################################
# Miscellaneous subroutines
###########################################################################
#
# Write the current status to $TopDir/log/status.pl
#
sub StatusWrite
{
my($dump) = Data::Dumper->new(
[ \%Info, \%Status],
[qw(*Info *Status)]);
$dump->Indent(1);
if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
print(STATUS $dump->Dump);
close(STATUS);
}
}
#
# Compare function for host sort. Hosts with errors go first,
# sorted with the oldest errors first. The remaining hosts
# are sorted so that those with the oldest backups go first.
#
sub HostSortCompare
{
#
# Hosts with errors go before hosts without errors
#
return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
#
# Hosts with no errors go after hosts with errors
#
return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
#
# hosts with the older last good backups sort earlier
#
my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
return $r if ( $r );
#
# Finally, just sort based on host name
#
return $a cmp $b;
}
#
# Queue all the hosts for backup. This means queuing all the fixed
# ip hosts and all the dhcp address ranges. We also additionally
# queue the dhcp hosts with a -e flag to check for expired dumps.
#
sub QueueAllPCs
{
foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
delete($Status{$host}{backoffTime})
if ( defined($Status{$host}{backoffTime})
&& $Status{$host}{backoffTime} < time );
next if ( defined($Jobs{$host})
|| $BgQueueOn{$host}
|| $UserQueueOn{$host}
|| $CmdQueueOn{$host} );
if ( $Hosts->{$host}{dhcp} ) {
$Status{$host}{dhcpCheckCnt}++;
if ( $RunNightlyWhenIdle ) {
#
# Once per night queue a check for DHCP hosts that just
# checks for expired dumps. We need to do this to handle
# the case when a DHCP host has not been on the network for
# a long time, and some of the old dumps need to be expired.
# Normally expiry checks are done by BackupPC_dump only
# after the DHCP hosts has been detected on the network.
#
unshift(@BgQueue,
{host => $host, user => "BackupPC", reqTime => time,
dhcp => 0, dumpExpire => 1});
$BgQueueOn{$host} = 1;
}
} else {
#
# this is a fixed ip host: queue it
#
unshift(@BgQueue,
{host => $host, user => "BackupPC", reqTime => time,
dhcp => $Hosts->{$host}{dhcp}});
$BgQueueOn{$host} = 1;
}
}
foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
my $ipAddr = "$dhcp->{ipAddrBase}.$i";
next if ( defined($Jobs{$ipAddr})
|| $BgQueueOn{$ipAddr}
|| $UserQueueOn{$ipAddr}
|| $CmdQueueOn{$ipAddr} );
#
# this is a potential dhcp ip address (we don't know the
# host name yet): queue it
#
unshift(@BgQueue,
{host => $ipAddr, user => "BackupPC", reqTime => time,
dhcp => 1});
$BgQueueOn{$ipAddr} = 1;
}
}
}
#
# Queue a BackupPC_link for the given host
#
sub QueueLink
{
my($host) = @_;
return if ( $CmdQueueOn{$host} );
$Status{$host}{state} = "Status_link_pending";
$Status{$host}{needLink} = 0;
unshift(@CmdQueue, {
host => $host,
user => "BackupPC",
reqTime => time,
cmd => ["$BinDir/BackupPC_link", $host],
});
$CmdQueueOn{$host} = 1;
}
#
# Read the hosts file, and update Status if any hosts have been
# added or deleted. We also track the mtime so the only need to
# update the hosts file on changes.
#
# This function is called at startup, SIGHUP, and on each wakeup.
# It returns 1 on success and undef on failure.
#
sub HostsUpdate
{
my($force) = @_;
my $newHosts;
#
# Nothing to do if we already have the current hosts file
#
return 1 if ( !$force && defined($Hosts)
&& $Info{HostsModTime} == $bpc->HostsMTime() );
if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
return;
}
print(LOG $bpc->timeStamp, "Reading hosts file\n");
$Hosts = $newHosts;
$Info{HostsModTime} = $bpc->HostsMTime();
#
# Now update %Status in case any hosts have been added or deleted
#
foreach my $host ( sort(keys(%$Hosts)) ) {
next if ( defined($Status{$host}) );
$Status{$host}{state} = "Status_idle";
print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
}
foreach my $host ( sort(keys(%Status)) ) {
next if ( $host eq $bpc->trashJob
|| $bpc->isAdminJob($host)
|| defined($Hosts->{$host})
|| defined($Jobs{$host})
|| $BgQueueOn{$host}
|| $UserQueueOn{$host}
|| $CmdQueueOn{$host} );
print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
delete($Status{$host});
}
return 1;
}
#
# Remember the signal name for later processing
#
sub catch_signal
{
if ( $SigName ) {
$SigName = shift;
foreach my $host ( keys(%Jobs) ) {
kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
}
#
# In case we are inside the exit handler, reopen the log file
#
close(LOG);
LogFileOpen();
print(LOG "Fatal error: unhandled signal $SigName\n");
unlink("$TopDir/log/BackupPC.pid");
confess("Got new signal $SigName... quitting\n");
} else {
$SigName = shift;
}
}
#
# Open the log file and point STDOUT and STDERR there too
#
sub LogFileOpen
{
mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
open(LOG, ">>$TopDir/log/LOG")
|| die("Can't create LOG file $TopDir/log/LOG");
close(STDOUT);
close(STDERR);
open(STDOUT, ">&LOG");
open(STDERR, ">&LOG");
select(LOG); $| = 1;
select(STDERR); $| = 1;
select(STDOUT); $| = 1;
}
#
# Initialize the unix-domain and internet-domain sockets that
# we listen to for client connections (from the CGI script and
# some of the BackupPC sub-programs).
#
sub ServerSocketInit
{
if ( !defined(fileno(SERVER_UNIX)) ) {
#
# one-time only: initialize unix-domain socket
#
if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
exit(1);
}
my $sockFile = "$TopDir/log/BackupPC.sock";
unlink($sockFile);
if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
exit(1);
}
if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
exit(1);
}
vec($FDread, fileno(SERVER_UNIX), 1) = 1;
}
return if ( $ServerInetPort == $Conf{ServerPort} );
if ( $ServerInetPort > 0 ) {
vec($FDread, fileno(SERVER_INET), 1) = 0;
close(SERVER_INET);
$ServerInetPort = -1;
}
if ( $Conf{ServerPort} > 0 ) {
#
# Setup a socket to listen on $Conf{ServerPort}
#
my $proto = getprotobyname('tcp');
if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
exit(1);
}
if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
exit(1);
}
if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
exit(1);
}
if ( !listen(SERVER_INET, SOMAXCONN) ) {
print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
exit(1);
}
vec($FDread, fileno(SERVER_INET), 1) = 1;
$ServerInetPort = $Conf{ServerPort};
}
}
#
# Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
# or when the command "server reload" is received.
#
sub ServerReload
{
my($mesg) = @_;
$mesg = $bpc->ConfigRead() || $mesg;
print(LOG $bpc->timeStamp, "$mesg\n");
$Info{ConfigModTime} = $bpc->ConfigMTime();
%Conf = $bpc->Conf();
umask($Conf{UmaskMode});
ServerSocketInit();
HostsUpdate(0);
$NextWakeup = 0;
$Info{ConfigLTime} = time;
}
#
# Gracefully shutdown the server. Used by Main_Process_Signal when
# $SigName ne "" && $SigName ne "HUP" or when the command
# "server shutdown" is received.
#
sub ServerShutdown
{
my($mesg) = @_;
print(LOG $bpc->timeStamp, "$mesg\n");
if ( keys(%Jobs) ) {
foreach my $host ( keys(%Jobs) ) {
kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
}
sleep(1);
foreach my $host ( keys(%Jobs) ) {
kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
}
%Jobs = ();
}
delete($Info{pid});
StatusWrite();
unlink("$TopDir/log/BackupPC.pid");
exit(1);
}
|