File: BackupPC_sendEmail

package info (click to toggle)
backuppc 2.1.1-2sarge2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,836 kB
  • ctags: 761
  • sloc: perl: 18,966; sh: 309; makefile: 74
file content (337 lines) | stat: -rwxr-xr-x 11,430 bytes parent folder | download
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
#!/bin/perl
#============================================================= -*-perl-*-
#
# BackupPC_sendEmail: send status emails to users and admins
#
# DESCRIPTION
#
#   BackupPC_sendEmail: send status emails to users and admins.
#   BackupPC_sendEmail is run by BackupPC_nightly, so it runs
#   once every night.
#
# 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 lib "__INSTALLDIR__/lib";
use BackupPC::Lib;
use BackupPC::FileZIO;

use Data::Dumper;
use Getopt::Std;
use DirHandle ();
use vars qw($Lang $TopDir $BinDir %Conf);

die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
$TopDir = $bpc->TopDir();
$BinDir = $bpc->BinDir();
%Conf   = $bpc->Conf();
$Lang   = $bpc->Lang();

$bpc->ChildInit();

use vars qw(%UserEmailInfo);
do "$TopDir/log/UserEmailInfo.pl";

my %opts;
if ( !getopts("t", \%opts) || @ARGV != 0 ) {
    print("usage: $0 [-t]\n");
    exit(1);
}

my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
if ( $err ) {
    print("Can't connect to server ($err)\n");
    exit(1);
}
my $reply = $bpc->ServerMesg("status hosts");
$reply = $1 if ( $reply =~ /(.*)/s );
my(%Status, %Info, %Jobs, @BgQueue, @UserQueue, @CmdQueue);
eval($reply);

###########################################################################
# Generate sysadmin warning messages
###########################################################################
my $mesg = "";

my @badHosts = ();
foreach my $host ( sort(keys(%Status)) ) {
    next if ( ($Status{$host}{reason} ne "Reason_backup_failed"
               && $Status{$host}{reason} ne "Reason_restore_failed")
           || $Status{$host}{error} =~ /^lost network connection to host/ );
    push(@badHosts, "$host ($Status{$host}{error})");
}
if ( @badHosts ) {
    my $badHosts = join("\n  - ", sort(@badHosts));
    $mesg .= <<EOF;
The following hosts had an error that is probably caused by a
misconfiguration.  Please fix these hosts:
  - $badHosts

EOF
}

#
# Report if we skipped backups because the disk was too full
#
if ( $Info{DUDailySkipHostCntPrev} > 0 ) {
    my $n = $Info{DUDailySkipHostCntPrev};
    my $m = $Conf{DfMaxUsagePct};
    $mesg .= <<EOF;
Yesterday $n hosts were skipped because the file system containing
$TopDir was too full.  The threshold in the
configuration file is $m%, while yesterday the file system was
up to $Info{DUDailyMaxPrev}% full.  Please find more space on the file system,
or reduce the number of full or incremental backups that we keep.

EOF
}

#
# Check for bogus directories (probably PCs that are no longer
# on the backup list)
#
my $d = DirHandle->new("$TopDir/pc") or die("Can't read $TopDir/pc: $!");
my @oldDirs = ();
my @files = $d->read;
$d->close;
foreach my $host ( @files ) {
    next if ( $host =~ /^\./ || defined($Status{$host}) );
    push(@oldDirs, "$TopDir/pc/$host");
}
if ( @oldDirs ) {
    my $oldDirs = join("\n  - ", sort(@oldDirs));
    $mesg .= <<EOF;
The following directories are bogus and are not being used by
BackupPC.  This typically happens when PCs are removed from the
backup list.  If you don't need any old backups from these PCs you
should remove these directories.  If there are machines on this
list that should be backed up then there is a problem with the
hosts file:
  - $oldDirs

EOF
}

if ( $mesg ne "" && $Conf{EMailAdminUserName} ne "" ) {
    $mesg = <<EOF;
To: $Conf{EMailAdminUserName}
Subject: BackupPC administrative attention needed

${mesg}Regards,
PC Backup Genie
EOF
    if ( $opts{t} ) {
        print("#" x 75, "\n");
        print $mesg;
    } else {
	SendMail($mesg);
    }
}

###########################################################################
# Generate per-host warning messages sent to each user
###########################################################################
my $Hosts = $bpc->HostInfoRead();

foreach my $host ( sort(keys(%Status)) ) {
    next if ( $Hosts->{$host}{user} eq "" );
    #
    # read any per-PC config settings (allowing per-PC email settings)
    #
    $bpc->ConfigRead($host);
    %Conf = $bpc->Conf();
    my $user = $Hosts->{$host}{user};
    next if ( time - $UserEmailInfo{$user}{lastTime}
                        < $Conf{EMailNotifyMinDays} * 24*3600 );
    next if ($Conf{XferMethod} eq "archive" );
    my @Backups = $bpc->BackupInfoRead($host);
    my $numBackups = @Backups;
    if ( $numBackups == 0 ) {
        my $subj = defined($Conf{EMailNoBackupEverSubj})
			? $Conf{EMailNoBackupEverSubj}
			: $Lang->{EMailNoBackupEverSubj};
        my $mesg = defined($Conf{EMailNoBackupEverMesg})
		        ? $Conf{EMailNoBackupEverMesg}
			: $Lang->{EMailNoBackupEverMesg};
        sendUserEmail($user, $host, $mesg, $subj, {
                            userName => user2name($user)
                        }) if ( !defined($Jobs{$host}) );
        next;
    }
    my $last = my $lastFull = my $lastIncr = 0;
    my $lastGoodOutlook = 0;
    my $lastNum = -1;
    my $numBadOutlook = 0;
    for ( my $i = 0 ; $i < @Backups ; $i++ ) {
        my $fh;
        $lastNum = $Backups[$i]{num} if ( $lastNum < $Backups[$i]{num} );
        if ( $Backups[$i]{type} eq "full" ) {
            $lastFull = $Backups[$i]{startTime}
                    if ( $lastFull < $Backups[$i]{startTime} );
        } else {
            $lastIncr = $Backups[$i]{startTime}
                    if ( $lastIncr < $Backups[$i]{startTime} );
        }
        $last = $Backups[$i]{startTime}
                    if ( $last < $Backups[$i]{startTime} );
        my $badOutlook = 0;
        my $file = "$TopDir/pc/$host/SmbLOG.$Backups[$i]{num}";
        my $comp = 0;
        if ( !-f $file ) {
            $file = "$TopDir/pc/$host/XferLOG.$Backups[$i]{num}";
            if ( !-f $file ) {
                $comp = 1;
                $file = "$TopDir/pc/$host/SmbLOG.$Backups[$i]{num}.z";
                $file = "$TopDir/pc/$host/XferLOG.$Backups[$i]{num}.z"
                                                        if ( !-f $file );
            }
        }
        next if ( !defined($fh = BackupPC::FileZIO->open($file, 0, $comp)) );
        while ( 1 ) {
            my $s = $fh->readLine();
            last if ( $s eq "" );
            if ( $s =~ /^\s*Error reading file.*\.pst : (ERRDOS - ERRlock|NT_STATUS_FILE_LOCK_CONFLICT)/
                  || $s =~ /^\s*Error reading file.*\.pst\. Got 0 bytes/ ) {
                $badOutlook = 1;
                last;
            }
        }
        $fh->close();
        $numBadOutlook += $badOutlook;
        if ( !$badOutlook ) {
            $lastGoodOutlook = $Backups[$i]{startTime}
                    if ( $lastGoodOutlook < $Backups[$i]{startTime} );
        }
    }
    if ( time - $last > $Conf{EMailNotifyOldBackupDays} * 24*3600 ) {
        my $subj = defined($Conf{EMailNoBackupRecentSubj})
			? $Conf{EMailNoBackupRecentSubj}
			: $Lang->{EMailNoBackupRecentSubj};
        my $mesg = defined($Conf{EMailNoBackupRecentMesg})
			? $Conf{EMailNoBackupRecentMesg}
			: $Lang->{EMailNoBackupRecentMesg};
        my $firstTime = sprintf("%.1f",
                        (time - $Backups[0]{startTime}) / (24*3600));
        my $days = sprintf("%.1f", (time - $last) / (24 * 3600));
        sendUserEmail($user, $host, $mesg, $subj, {
                            firstTime  => $firstTime,
                            days       => $days,
                            userName   => user2name($user),
                            numBackups => $numBackups,
                        }) if ( !defined($Jobs{$host}) );
        next;
    }
    if ( $numBadOutlook > 0
          && time - $lastGoodOutlook > $Conf{EMailNotifyOldOutlookDays}
                                             * 24 * 3600 ) {
        my($days, $howLong);
        if ( $lastGoodOutlook == 0 ) {
            $howLong = eval("qq{$Lang->{howLong_not_been_backed_up}}");
        } else {
            $days = sprintf("%.1f", (time - $lastGoodOutlook) / (24*3600));
            $howLong = eval("qq{$Lang->{howLong_not_been_backed_up_for_days_days}}");
        }
        my $subj = defined($Conf{EMailOutlookBackupSubj})
			? $Conf{EMailOutlookBackupSubj}
			: $Lang->{EMailOutlookBackupSubj};
        my $mesg = defined($Conf{EMailOutlookBackupMesg})
			? $Conf{EMailOutlookBackupMesg}
			: $Lang->{EMailOutlookBackupMesg};
        my $firstTime = sprintf("%.1f",
                        (time - $Backups[0]{startTime}) / (24*3600));
        my $lastTime = sprintf("%.1f",
                        (time - $Backups[$#Backups]{startTime}) / (24*3600));
        sendUserEmail($user, $host, $mesg, $subj, {
                            days       => $days,
                            firstTime  => $firstTime,
                            lastTime   => $lastTime,
                            numBackups => $numBackups,
                            userName   => user2name($user),
                            howLong    => $howLong,
                            serverHost => $Conf{ServerHost},
                        }) if ( !defined($Jobs{$host}) );
    }
}
if ( !$opts{t} ) {
    $Data::Dumper::Indent = 1;
    my $dumpStr = Data::Dumper->Dump(
             [\%UserEmailInfo],
             [qw(*UserEmailInfo)]);
    if ( open(HOST, ">", "$TopDir/log/UserEmailInfo.pl") ) {
	binmode(HOST);
        print(HOST $dumpStr);
        close(HOST);
    }
}

sub user2name
{
    my($user) = @_;
    my($name) = (getpwnam($user))[6];
    $name =~ s/\s.*//;
    $name = $user if ( $name eq "" );
    return $name;
}

sub sendUserEmail
{
    my($user, $host, $mesg, $subj, $vars) = @_;
    $vars->{user}   = $user;
    $vars->{host}   = $host;
    $vars->{domain} = $Conf{EMailUserDestDomain};
    $vars->{CgiURL} = $Conf{CgiURL};
    $subj =~ s/\$(\w+)/defined($vars->{$1}) ? $vars->{$1} : "\$$1"/eg;
    $vars->{subj}   = $subj;
    $mesg =~ s/\$(\w+)/defined($vars->{$1}) ? $vars->{$1} : "\$$1"/eg;
    if ( $opts{t} ) {
        print("#" x 75, "\n");
        print $mesg;
    } else {
    	SendMail($mesg);
    }
    $UserEmailInfo{$user}{lastTime} = time;
    $UserEmailInfo{$user}{lastSubj} = $subj;
    $UserEmailInfo{$user}{lastHost} = $host;
}

sub SendMail
{
    my($mesg) = @_;
    my($from) = $Conf{EMailFromUserName};
    local(*MAIL);

    $from = "-f $from" if ( $from ne "" );
    if ( !open(MAIL, "|$Conf{SendmailPath} -t $from") ) {
    	printf("Can't run sendmail ($Conf{SendmailPath}): $!\n");
	return;
    }
    print MAIL $mesg;
    close(MAIL);
}