Subversion Repositories zfs_utils

Rev

Rev 51 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
34 rodolico 1
# Simplified BSD License (FreeBSD License)
2
#
3
# Copyright (c) 2025, Daily Data Inc.
4
# All rights reserved.
5
#
6
# Redistribution and use in source and binary forms, with or without
7
# modification, are permitted provided that the following conditions are met:
8
#
9
# 1. Redistributions of source code must retain the above copyright notice, this
10
#    list of conditions and the following disclaimer.
11
#
12
# 2. Redistributions in binary form must reproduce the above copyright notice,
13
#    this list of conditions and the following disclaimer in the documentation
14
#    and/or other materials provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
20
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
 
24 rodolico 27
package ZFS_Utils;
28
 
29
use strict;
30
use warnings;
31
use Exporter 'import';
32
use Data::Dumper;
33
use POSIX qw(strftime);
34
use File::Path qw(make_path);
35
 
34 rodolico 36
# library of ZFS related utility functions
48 rodolico 37
# Copyright 2025 Daily Data Inc. <rodo@dailydata.net>
34 rodolico 38
 
39
# currently used for sneakernet scripts, but plans to expand to other ZFS related tasks
40
# functions include:
48 rodolico 41
#   runCmd: execute a command and return its output (captures exit status in $lastRunError;
42
#           supports optional stderr merge via $merge_stderr)
43
#   shredFile: securely delete a file using gshred (note: not effective on ZFS due to COW)
60 rodolico 44
#   logMsg: timestamped logging to a file and optionally to console; respects $verboseLoggingLevel
48 rodolico 45
#   loadConfig: load a YAML configuration file into a hashref; will create the file from a
46
#           provided default hashref if the file does not exist (uses YAML::XS or YAML::Tiny)
47
#   mountDriveByLabel: find and mount a drive by its GPT label (supports ufs/msdos; waits
48
#           for device and creates mountpoint)
49
#   unmountDriveByLabel: unmount a drive found by GPT label and remove the mountpoint if empty
50
#   mountGeli: high level orchestrator to decrypt multiple GELI devices and import/mount a ZFS pool
51
#   decryptAndMountGeli: attach GELI devices, optionally build a combined key, import the pool
52
#           and mount ZFS datasets
53
#   makeGeliKey: create a GELI key by XOR'ing a remote binary keyfile and a local 256-bit hex key;
54
#           writes a 32-byte binary key file with mode 0600
55
#   findGeliDisks: discover candidate disks suitable for GELI on the host
60 rodolico 56
#   makeReplicateCommands: build zfs send/receive command lists from snapshot lists and prior status;
57
#           intelligently determines recursive vs per-filesystem sends and incremental vs full sends
58
#           based on snapshot availability; filters snapshots by matching parent path + dataset name
59
#           to avoid false matches with similarly-named datasets in different locations
48 rodolico 60
#   sendReport: helper to deliver replication reports (email/file) — exported for scripts to implement
61
#   fatalError: helper to log a fatal condition and die (convenience wrapper)
62
#   getDirectoryList: utility to list directory contents with optional filters
63
#   cleanDirectory: safe directory cleaning utility used by snapshot pruning helpers
51 rodolico 64
#   exported package variables: $logFileName, $displayLogsOnConsole, $lastRunError, $verboseLoggingLevel
65
#
48 rodolico 66
# v1.0 RWR 20251215
67
# This is the initial, tested release
51 rodolico 68
#
69
# v1.0.1 RWR 20251215
70
# Added verbose logging control to logMsg calls, controlled by $verboseLoggingLevel
60 rodolico 71
#
72
# v1.1.0 RWR 20251217
73
# Added added version variable $VERSION
74
# Added more logging of source/target snapshots in doSourceReplication for debugging.
75
# max verbosity is now 5 instead of 3.
76
# optimized makeReplicateCommands to avoid unnecessary copies of large arrays and increase reliability
77
# when processing snapshots with inconsistent naming in child datasets.
34 rodolico 78
 
79
# Exported functions and variables
80
 
51 rodolico 81
our @EXPORT_OK = qw(loadConfig shredFile mountDriveByLabel unmountDriveByLabel mountGeli logMsg runCmd makeReplicateCommands sendReport fatalError getDirectoryList cleanDirectory $logFileName $displayLogsOnConsole $lastRunError $verboseLoggingLevel);
24 rodolico 82
 
60 rodolico 83
our $VERSION = '1.1.0';
24 rodolico 84
 
48 rodolico 85
# these are variables which affect the flow of the program and are exported so they can be modified by the caller
24 rodolico 86
our $logFileName = '/tmp/zfs_utils.log'; # this can be overridden by the caller, and turned off with empty string
34 rodolico 87
our $displayLogsOnConsole = 1; # if non-zero, log messages are also printed to console
27 rodolico 88
our $merge_stderr = 0; # if set to 1, stderr is captured in runCmd
37 rodolico 89
our $lastRunError = 0; # tracks the last error code from runCmd
51 rodolico 90
our $verboseLoggingLevel = 0; # if non-zero, logMsg will include more verbose output
24 rodolico 91
 
25 rodolico 92
# Execute a command and return its output.
93
# If called in scalar context, returns the full output as a single string.
94
# If called in list context, returns the output split into lines.
95
# If $merge_stderr is true (default), stderr is merged into stdout (only for scalar commands).
34 rodolico 96
# returns undef on failure and logs failure message.
25 rodolico 97
sub runCmd {
33 rodolico 98
   my $cmd = join( ' ', @_ );
25 rodolico 99
   $merge_stderr = 1 unless defined $merge_stderr;
100
   my $output = '';
101
 
51 rodolico 102
   logMsg( "Running command [$cmd]" ) if $verboseLoggingLevel >= 2;
34 rodolico 103
   $cmd .= ' 2>&1' if $merge_stderr;
104
   $output = `$cmd`;
37 rodolico 105
   $lastRunError = $?;
106
   if ( $lastRunError ) {
107
      if ($? == -1) {
108
         logMsg( "failed to execute: $!");
109
         return '';
110
      } elsif ($? & 127) { # fatal error, exit program
111
         logMsg( sprintf( "child died with signal %d, %s coredump\n", ($? & 127),  ($? & 128) ? 'with' : 'without' ) );
112
         die;
113
      } elsif ($? >> 8) { # it had some return code other than 0
114
         logMsg( sprintf( "child exited with value %d\n", $? >> 8 ) );
115
      }
34 rodolico 116
   }
25 rodolico 117
   $output //= '';
118
 
119
   if (wantarray) {
120
      return $output eq '' ? () : split(/\n/, $output);
121
   } else {
122
      return $output;
123
   }
124
}
125
 
24 rodolico 126
# this calls gshred which will overwrite the file 3 times, then
127
# remove it.
128
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
129
# so assuming file is on something without COW (ramdisk, UFS, etc)
130
sub shredFile {
131
   my $filename = shift;
132
   `/usr/local/bin/gshred -u -f -s 32 $filename` if -e $filename;
133
}
134
 
135
sub logMsg {
136
    my $msg = shift;
137
    my $filename = shift // $logFileName;
138
    my $timeStampFormat = shift // '%Y-%m-%d %H:%M:%S';
139
    my $timestamp = strftime($timeStampFormat, localtime());
140
    if (defined $filename && $filename ne '' ) {
141
       open my $logfh, '>>', $filename or die "Could not open log file $filename: $!\n";
142
       print $logfh "$timestamp\t$msg\n";
143
       close $logfh;
144
    }
145
    print "$timestamp\t$msg\n" if ($displayLogsOnConsole);
146
}
147
 
35 rodolico 148
# find a drive by it's label by scanning /dev/gpt/
149
# driveInfo is a hashref with the following keys:
150
# label - the GPT label of the drive (required)
151
# filesystem - the filesystem type (default: ufs)
152
# mountPath - where to mount the drive (default: /mnt/label)
153
# timeout - how long to wait for the drive (default: 600 seconds)
154
# check_interval - how often to check for the drive (default: 15 seconds)
24 rodolico 155
# If the drive is found, mount it on mountPath and return the mountPath.
156
# If not found, return empty string.
157
sub mountDriveByLabel {
35 rodolico 158
   my ( $driveInfo ) = @_;
159
   unless ($driveInfo->{label}) {
160
      logMsg("mountDriveByLabel: No drive label provided");
24 rodolico 161
      return '';
162
   }
35 rodolico 163
   unless ( $driveInfo->{label} =~ /^[a-zA-Z0-9_\-]+$/ ) {
164
      logMsg("mountDriveByLabel: Invalid label '$driveInfo->{label}'");
24 rodolico 165
      return '';
166
   }
167
 
51 rodolico 168
   logMsg("mountDriveByLabel: Looking for drive with label '$driveInfo->{label}'") if $verboseLoggingLevel >= 1;
24 rodolico 169
   # default to /mnt/label if not provided
35 rodolico 170
   $driveInfo->{mountPath} //= "/mnt/$driveInfo->{label}"; # this is where we'll mount it if we find it
46 rodolico 171
   $driveInfo->{fstype} //= 'ufs'; # default to mounting ufs
34 rodolico 172
   # The location for the label depends on filesystem. Only providing access to ufs and msdos here for safety.
173
   # gpt labeled drives for ufs are in /dev/gpt/, for msdosfs in /dev/msdosfs/
46 rodolico 174
   my $labelPath = $driveInfo->{fstype} eq 'msdos' ? "/dev/msdosfs/$driveInfo->{label}" : "/dev/gpt/$driveInfo->{label}"; 
31 rodolico 175
   # drive already mounted, just return the path
37 rodolico 176
   my $output = runCmd( "mount | grep '$driveInfo->{mountPath}'" );
177
   return $driveInfo->{mountPath} if ( $lastRunError == 0 ); # grep found it for us
24 rodolico 178
   # default to 10 minutes (600 seconds) if not provided
35 rodolico 179
   $driveInfo->{timeout} //= 600;
24 rodolico 180
   # default to checking every minute if not provided
35 rodolico 181
   $driveInfo->{check_interval} //= 15;
24 rodolico 182
   # wait up to $timeout seconds for device to appear, checking every 10 seconds
35 rodolico 183
   while ( $driveInfo->{timeout} > 0 ) {
46 rodolico 184
      if ( -e "$labelPath" ) {
24 rodolico 185
         last;
186
      } else {
46 rodolico 187
         print "Waiting for drive labeled $driveInfo->{label}, looking in $labelPath\n";
35 rodolico 188
         sleep $driveInfo->{check_interval};
189
         $driveInfo->{timeout} -= $driveInfo->{check_interval};
24 rodolico 190
      }
191
    }
192
    # if we found it, mount and return mount path
46 rodolico 193
    if ( -e "$labelPath" ) {
24 rodolico 194
       # ensure mount point
35 rodolico 195
       unless ( -d $driveInfo->{mountPath} || make_path($driveInfo->{mountPath}) ) {
196
         logMsg("Failed to create $driveInfo->{mountPath}: $!");
24 rodolico 197
         return '';
198
       }
37 rodolico 199
       # mount device
46 rodolico 200
       runCmd( "mount -t $driveInfo->{fstype} $labelPath $driveInfo->{mountPath}" );
37 rodolico 201
       if ( $lastRunError ) {
51 rodolico 202
         logMsg("Failed to mount $labelPath on $driveInfo->{mountPath}: $!") if $verboseLoggingLevel >= 0;
24 rodolico 203
         return '';
204
       }
35 rodolico 205
       return $driveInfo->{mountPath};
24 rodolico 206
    } else {
207
       return '';
208
    }
209
}
210
 
42 rodolico 211
# finds and unmounts a drive defined by $driveInfo.
212
# on success, removes the mount point if empty.
213
sub unmountDriveByLabel {
214
   my ( $driveInfo ) = @_;
215
   unless ($driveInfo->{label}) {
216
      logMsg("unmountDriveByLabel: No drive label provided");
217
      return '';
218
   }
219
   unless ( $driveInfo->{label} =~ /^[a-zA-Z0-9_\-]+$/ ) {
220
      logMsg("unmountDriveByLabel: Invalid label '$driveInfo->{label}'");
221
      return '';
222
   }
223
 
51 rodolico 224
   logMsg("unmountDriveByLabel: Looking for drive with label '$driveInfo->{label}'") if $verboseLoggingLevel >= 1;
42 rodolico 225
   # default to /mnt/label if not provided
226
   $driveInfo->{mountPath} //= "/mnt/$driveInfo->{label}"; # this is where we'll mount it if we find it
227
 
228
   runCmd( "mount | grep '$driveInfo->{mountPath}'" );
229
   if ( $lastRunError ) {
51 rodolico 230
     logMsg("Drive with label '$driveInfo->{label}' is not mounted") if $verboseLoggingLevel >= 2;
42 rodolico 231
     return '';
232
   }
233
 
234
   # unmount device
235
   runCmd( "umount $driveInfo->{mountPath}" );
236
   if ( $lastRunError ) {
237
     logMsg("Failed to unmount $driveInfo->{mountPath}: $!");
238
     return '';
239
   }
240
 
241
   # and remove the directory if empty (find command will return empty string or one filename)
242
   rmdir $driveInfo->{mountPath} unless runCmd( "find $driveInfo->{mountPath} -mindepth 1 -print -quit");
243
   return $driveInfo->{mountPath};
244
}
245
 
24 rodolico 246
## Load a YAML configuration file into a hashref.
247
## If the file does not exist, and a default hashref is provided,
248
## create the file by dumping the default to YAML, then return the default.
249
sub loadConfig {
250
    my ($filename, $default) = @_;
251
 
252
    # If no filename was provided, return default or empty hashref
253
    die "No filename provided to loadConfig\n" unless defined $filename;
254
 
255
    # If file doesn't exist but a default hashref was provided, try to
256
    # create the file by dumping the default to YAML, then return the default.
257
    unless (-e $filename) {
258
      logMsg("Config file $filename does not exist. Creating it with default values.");
259
      if ($default && ref $default eq 'HASH') {
260
         my $wrote = 0;
261
         eval {
262
               require YAML::XS;
263
               YAML::XS->import();
264
               YAML::XS::DumpFile($filename, $default);
265
               $wrote = 1;
266
               1;
267
         } or do {
268
               eval {
269
                  require YAML::Tiny;
270
                  YAML::Tiny->import();
271
                  my $yt = YAML::Tiny->new($default);
272
                  $yt->write($filename);
273
                  $wrote = 1;
274
                  1;
275
               } or do {
276
                  logMsg("No YAML writer available (YAML::XS or YAML::Tiny). Could not create $filename");
277
               };
278
         };
279
         die "Failed to write default config to $filename:$!\n" unless $wrote;
42 rodolico 280
      } # if default
281
      # No default provided; nothing to create
282
      return {};
283
   } # unless -e $filename
24 rodolico 284
 
42 rodolico 285
   my $yaml;
24 rodolico 286
 
42 rodolico 287
   # Try YAML::XS first, fall back to YAML::Tiny
288
   eval {
289
      require YAML::XS;
290
      YAML::XS->import();
291
      $yaml = YAML::XS::LoadFile($filename);
51 rodolico 292
      logMsg("using YAML::XS to load $filename") if $verboseLoggingLevel >= 3;
42 rodolico 293
      1;
294
   } or do {
295
      eval {
296
         require YAML::Tiny;
297
         YAML::Tiny->import();
298
         $yaml = YAML::Tiny->read($filename);
299
         $yaml = $yaml->[0] if $yaml;  # YAML::Tiny returns an arrayref of documents
51 rodolico 300
         logMsg("using YAML::Tiny to load $filename") if $verboseLoggingLevel >= 3;
42 rodolico 301
         1;
302
      } or do {
303
         logMsg("No YAML parser installed (YAML::XS or YAML::Tiny). Skipping config load from $filename");
304
         return ($default && ref $default eq 'HASH') ? $default : {};
305
      };
306
   };
307
   # Ensure we have a hashref
308
   die "Config file $filename did not produce a HASH.\n" unless (defined $yaml && ref $yaml eq 'HASH');
24 rodolico 309
 
42 rodolico 310
   return $yaml;
24 rodolico 311
}
312
 
313
 
48 rodolico 314
## Mount a GELI-encrypted ZFS pool (high-level orchestration).
315
##
316
## Arguments:
317
##   $geliConfig - HASHREF containing GELI/ZFS mounting configuration. Expected keys include:
318
##       poolname        - name of the zpool to import
319
##       secureKey       - HASHREF with { label, keyfile, path } describing the keyfile disk
320
##       target          - path where the combined keyfile will be written
321
##       diskList        - OPTIONAL arrayref of disk device names (eg: ['ada0','ada1'])
322
##
323
## Behavior:
324
##   - Mounts the keyfile disk (using mountDriveByLabel), builds the combined key (makeGeliKey),
325
##     then calls decryptAndMountGeli to attach geli devices and import/mount the zpool.
326
##
327
## Returns:
328
##   Pool name (string) on success, empty string on error.
24 rodolico 329
sub mountGeli {
330
   my $geliConfig = shift;
38 rodolico 331
 
51 rodolico 332
   logMsg( "geli config detected, attempting to mount geli disks" ) if $verboseLoggingLevel >= 0;
38 rodolico 333
   # Can't continue at all if no pool name
334
   unless ( $geliConfig->{'poolname'} ) {
335
      logMsg "Could not find pool name in configuration file\n";
24 rodolico 336
      return '';
337
   }
338
   # find the keyfile disk and mount it
39 rodolico 339
   $geliConfig->{secureKey}->{path} = mountDriveByLabel( $geliConfig->{secureKey} );
340
   unless ( $geliConfig->{secureKey}->{path} ) {
38 rodolico 341
      logMsg "Could not find or mount keyfile disk with label: " . $geliConfig->{secureKey}->{label};
24 rodolico 342
      return '';
343
   }
344
   # create the combined geli keyfile in target location
38 rodolico 345
   unless ( makeGeliKey( $geliConfig ) ) {
24 rodolico 346
         logMsg "Could not create geli keyfile\n";
347
         return '';
348
      }
349
   # decrypt and mount the geli disks and zfs pool
350
   my $poolname = decryptAndMountGeli( $geliConfig );
351
   return $poolname;
352
 
353
}
354
 
48 rodolico 355
## Discover disks suitable for GELI/ZFS use on the host.
356
##
357
## Returns an array of device names (eg: qw( ada0 ada1 )) that appear free for use.
358
## The routine collects all disks, excludes disks with existing partitions and those
359
## referenced by active zpools.
30 rodolico 360
sub findGeliDisks {
51 rodolico 361
   logMsg("Finding available disks for GELI/ZFS use") if $verboseLoggingLevel >= 2;
30 rodolico 362
   # get all disks in system
363
   my %allDisks = map{ chomp $_ ; $_ => 1 } runCmd( "geom disk list | grep 'Geom name:' | rev | cut -d' ' -f1 | rev" );
364
   # get the disks with partitions
365
   my @temp = runCmd( "gpart show -p | grep '^=>'");  # -p prints just the disks without partitions
366
   # remove them from the list
367
   foreach my $disk ( @temp ) {
368
      $allDisks{$1} = 0 if ( $disk =~ m/^=>[\t\s0-9]+([a-z][a-z0-9]+)/ ) ;
369
   }
370
 
371
   # get disk which are currently used for zpools
372
   @temp = runCmd( "zpool status -LP | grep '/dev/'" );
373
   foreach my $disk ( @temp ) {
374
      $allDisks{$1} = 0 if  $disk =~ m|/dev/([a-z]+\d+)|;
375
   }
376
 
377
   # return only the disks which are free (value 1)
378
   return grep{ $allDisks{$_} == 1 } keys %allDisks;
379
}
380
 
48 rodolico 381
## Decrypt GELI-encrypted disks and import/mount the ZFS pool.
24 rodolico 382
##
48 rodolico 383
## Arguments:
384
##   $geliConfig - HASHREF expected to contain:
385
##       poolname - zpool name to import
386
##       target   - path to the combined GELI keyfile created by makeGeliKey
387
##       diskList - OPTIONAL arrayref of disk device names (if omitted, findGeliDisks() is used)
388
##
389
## Behavior:
390
##   - Ensures the pool is not already imported
391
##   - Attaches (geli attach) each supplied disk using the keyfile
392
##   - Attempts to import the specified pool and runs `zfs mount -a` to mount datasets
393
##
394
## Returns:
395
##   Pool name (string) on success; empty string on failure.
24 rodolico 396
sub decryptAndMountGeli {
38 rodolico 397
   my ($geliConfig) = shift;
30 rodolico 398
 
399
   # if no list of disks provided, try to find them
39 rodolico 400
   $geliConfig->{'diskList'} //= [ findGeliDisks() ];
30 rodolico 401
 
24 rodolico 402
   my $diskList = $geliConfig->{'diskList'};
403
   my $poolname = $geliConfig->{'poolname'};
404
   my $keyfile = $geliConfig->{'target'};
46 rodolico 405
 
406
   # check if the pool already attached (grep returns 0 on found, something else on not)
407
   runCmd( "zpool list -H -o name | grep $poolname" );
408
   return $poolname unless $lastRunError;
409
 
24 rodolico 410
   unless ( -e $keyfile ) {
411
      logMsg "GELI keyfile $keyfile does not exist\n";
412
      return '';
413
   }
414
 
415
   my @decrypted_devices;
416
 
417
   # Decrypt each disk in the list
30 rodolico 418
   foreach my $disk (@{$geliConfig->{'diskList'}}) {
39 rodolico 419
      $disk = '/dev/' . $disk unless $disk =~ m|/dev|;
24 rodolico 420
      unless ( -e $disk ) {
421
         logMsg "Disk $disk does not exist\n";
422
         return '';
423
      }
424
 
425
      # Derive the decrypted device name (.eli suffix on FreeBSD)
426
      my $decrypted = $disk . '.eli';
427
 
428
      # Decrypt using geli attach with the keyfile
51 rodolico 429
      logMsg("Decrypting $disk with keyfile $keyfile") if $verboseLoggingLevel >= 2;
41 rodolico 430
      runCmd("geli attach -p -k $geliConfig->{target} $disk");
431
      if ( $lastRunError) {
51 rodolico 432
         logMsg "Failed to decrypt $disk (exit $lastRunError)\n" if $verboseLoggingLevel >= 3;
30 rodolico 433
         next; # ignore failed disks and continue to see if we can import the pool
24 rodolico 434
      }
435
 
436
      unless ( -e $decrypted ) {
51 rodolico 437
         logMsg "Decrypted device $decrypted does not exist after geli attach\n" if $verboseLoggingLevel >= 0;
24 rodolico 438
         return '';
439
      }
440
      push @decrypted_devices, $decrypted;
441
   }
442
 
443
   # Import the ZFS pool
51 rodolico 444
   logMsg("Importing ZFS pool $poolname") if $verboseLoggingLevel >= 0;
24 rodolico 445
   my @import_cmd = ('zpool', 'import');
30 rodolico 446
 
24 rodolico 447
   push @import_cmd, $poolname;
448
 
40 rodolico 449
   runCmd("zpool import $poolname" );
450
   unless ( $lastRunError == 0 ) {
451
      logMsg("Failed to import zfs pool $poolname (exit $lastRunError)\n");
24 rodolico 452
      return '';
453
   }
454
 
455
   # Mount the ZFS pool (zfs mount -a mounts all filesystems in the pool)
51 rodolico 456
   logMsg("Mounting ZFS pool $poolname") if $verboseLoggingLevel >= 1;
40 rodolico 457
   runCmd('zfs mount -a');
458
   unless ( $lastRunError == 0 ) {
459
      logMsg("Failed to mount zfs pool $poolname (exit $lastRunError)\n");
24 rodolico 460
      return '';
461
   }
51 rodolico 462
 
463
   logMsg("Successfully decrypted and mounted pool $poolname") if $verboseLoggingLevel >= 2;
24 rodolico 464
   return $poolname;
465
}
466
 
467
## Create a GELI key by XOR'ing a remote binary keyfile and a local key (hex string).
468
##
48 rodolico 469
## Expected input (via $geliConfig HASHREF):
470
##   $geliConfig->{secureKey}->{path} - directory where the remote keyfile resides
471
##   $geliConfig->{secureKey}->{keyfile} - filename of the remote 32-byte binary key
472
##   $geliConfig->{localKey} - 64-hex char string OR path to a file containing the hex
473
##   $geliConfig->{target} - path to write the resulting 32-byte binary key
24 rodolico 474
##
48 rodolico 475
## Behavior:
476
##   - Reads 32 bytes from the remote binary key
477
##   - Reads/cleans the 64-hex local key and converts it to 32 bytes
478
##   - XORs the two 32-byte buffers and writes the 32-byte result to $target with mode 0600
479
##
480
## Returns: 1 on success. Dies on unrecoverable errors.
24 rodolico 481
sub makeGeliKey {
38 rodolico 482
   my ( $geliConfig ) = @_;
24 rodolico 483
 
38 rodolico 484
   $geliConfig->{secureKey}->{keyfile} //= '';
485
   $geliConfig->{localKey} //= '';
486
   $geliConfig->{target} //= '';
24 rodolico 487
 
38 rodolico 488
   if ( $geliConfig->{target} && -f $geliConfig->{target} ) {
51 rodolico 489
      logMsg "GELI target keyfile $geliConfig->{target} already exists. Not overwriting.\n" if $verboseLoggingLevel >= 2;
38 rodolico 490
      return 1;
491
   }
24 rodolico 492
 
38 rodolico 493
   my $remote_keyfile = "$geliConfig->{secureKey}->{path}/$geliConfig->{secureKey}->{keyfile}";
494
   my $localKeyHexOrPath = $geliConfig->{localKey};
495
   my $target = $geliConfig->{target};
40 rodolico 496
 
38 rodolico 497
   if ( $geliConfig->{secureKey}->{keyfile} && $geliConfig->{localKey} ) {
498
      # we have what we need to proceed
499
 
500
      if ( -f $remote_keyfile ) {
51 rodolico 501
         logMsg "Creating GELI keyfile at $geliConfig->{target} using remote keyfile " . $geliConfig->{secureKey}->{keyfile} . " and local key\n" 
502
            if $verboseLoggingLevel >= 2;
38 rodolico 503
      } else {
504
         die "Remote keyfile " . $geliConfig->{secureKey}->{keyfile} . " does not exist\n";
505
      }
506
   }
507
 
24 rodolico 508
   # Read remote binary key
509
   open my $rh, '<:raw', $remote_keyfile or die "Unable to open $remote_keyfile: $!\n";
510
   my $rbuf;
511
   my $read = read($rh, $rbuf, 32);
512
   close $rh;
513
   die "Failed to read 32 bytes from $remote_keyfile (got $read)\n" unless defined $read && $read == 32;
514
 
515
   # Get local hex string (either direct string or file contents)
516
   my $hex;
517
   if (-e $localKeyHexOrPath) {
518
      open my $lh, '<', $localKeyHexOrPath or die "Unable to open local key file $localKeyHexOrPath: $!\n";
519
      local $/ = undef;
520
      $hex = <$lh>;
521
      close $lh;
522
   } else {
523
      $hex = $localKeyHexOrPath;
524
   }
525
   # clean hex (remove whitespace/newlines and optional 0x)
526
   $hex =~ s/0x//g;
527
   $hex =~ s/[^0-9a-fA-F]//g;
528
 
529
   die "Local key must be 64 hex characters (256-bit)\n" unless length($hex) == 64;
530
 
531
   my $lbuf = pack('H*', $hex);
532
   die "Local key decoded to unexpected length " . length($lbuf) . "\n" unless length($lbuf) == 32;
533
 
534
   # XOR the two buffers
535
   my $out = '';
536
   for my $i (0 .. 31) {
537
      $out .= chr( ord(substr($rbuf, $i, 1)) ^ ord(substr($lbuf, $i, 1)) );
538
   }
539
 
540
   # Ensure target directory exists
541
   my ($vol, $dirs, $file) = ($target =~ m{^(/?)(.*/)?([^/]+)$});
542
   if ($dirs) {
543
      my $dir = $dirs;
544
      $dir =~ s{/$}{};
545
      unless (-d $dir) {
546
         require File::Path;
547
         File::Path::make_path($dir) or die "Failed to create directory $dir: $!\n";
548
      }
549
   }
550
 
551
   # Write out binary key and protect permissions
552
   open my $oh, '>:raw', $target or die "Unable to open $target for writing: $!\n";
553
   print $oh $out or die "Failed to write to $target: $!\n";
554
   close $oh;
555
   chmod 0600, $target;
556
 
557
   return 1;
558
}
559
 
42 rodolico 560
# make a bunch of replicate commands and return them to the caller as a list
44 rodolico 561
# $sourceSnapsRef - list of snapshots on source machine
562
# $targetSnapsRef - list of snapshots on target machine
563
# $dataset - The name of the dataset we are working on (same on both source and target)
564
# $sourceParent - The parent dataset of $dataset on source
565
# $targetParent - The parent dataset of $dataset on target
566
# $newStatusRef - A place to put the updated $targetSnapsRef
567
# returns hashref of commands to execute, of form
568
#    {$dataset} = "zfs send command"
569
# where $dataset above can be a child of $dataset
25 rodolico 570
sub makeReplicateCommands {
44 rodolico 571
   my ( $sourceSnapsRef, $targetSnapsRef, $dataset, $sourceParent, $targetParent, $newStatusRef ) = @_;
60 rodolico 572
 
573
   # Ensure all array refs are defined (use empty arrays if not provided)
25 rodolico 574
   $sourceSnapsRef ||= [];
44 rodolico 575
   $targetSnapsRef     ||= [];
25 rodolico 576
   $newStatusRef  ||= [];
60 rodolico 577
 
578
   # Normalize parent paths: ensure they end with '/' unless empty
579
   # This makes path construction consistent later (e.g., "pool/" + "dataset")
44 rodolico 580
   $sourceParent //= '';
581
   $sourceParent .= '/' unless $sourceParent eq '' or substr($sourceParent, -1) eq '/';
582
   $targetParent //= '';
583
   $targetParent .= '/' unless $targetParent eq '' or substr($targetParent, -1) eq '/';
25 rodolico 584
 
44 rodolico 585
 
60 rodolico 586
   logMsg( "makeReplicateCommands: dataset=[$dataset] sourceParent=[$sourceParent] targetParent=[$targetParent]" ) if $verboseLoggingLevel >= 4;
587
   logMsg( "makeReplicateCommands: source snapshots count=" . scalar(@$sourceSnapsRef) . ", target snapshots count=" . scalar(@$targetSnapsRef) ) if $verboseLoggingLevel >= 4;
588
   if ($verboseLoggingLevel >= 5) {
589
      logMsg( "makeReplicateCommands: RAW target snapshots BEFORE filtering:" );
590
      foreach my $snap (@$targetSnapsRef) {
591
         logMsg( "  [$snap]" );
592
      }
593
      logMsg( "makeReplicateCommands: RAW source snapshots BEFORE filtering:" );
594
      foreach my $snap (@$sourceSnapsRef) {
595
         logMsg( "  [$snap]" );
596
      }
597
   }
598
 
599
   my %commands; # Hash to store generated zfs send commands, keyed by filesystem name
600
 
44 rodolico 601
   fatalError( "No dataset defined in makeReplicateCommands, can not continue") unless $dataset;
602
 
60 rodolico 603
   # Filter snapshot lists to only include snapshots matching our dataset and its children
604
   # The dataset should match as a full path component (not substring)
605
   # Then strip the parent path prefix from each snapshot name
606
   # Example: "storage/mydata@snap1" becomes "mydata@snap1" when sourceParent="storage/"
607
   # This allows us to work with relative paths and handle different parent paths on source/target
608
   # Match: storage/mydata@snap, storage/mydata/child@snap
609
   # Don't match: storage/mydataset@snap (if dataset is "mydata")
610
   # Don't match: storage/otherparent/mydata@snap (different parent path)
611
   my $targetSnaps = [ map{ s/^$targetParent//r } grep{ /^\Q$targetParent$dataset\E(?:\/|@)/ } @$targetSnapsRef ];
612
   my $sourceSnaps = [ map{ s/^$sourceParent//r } grep{ /^\Q$sourceParent$dataset\E(?:\/|@)/ } @$sourceSnapsRef ];
44 rodolico 613
 
60 rodolico 614
   logMsg( "makeReplicateCommands: filtered source snapshots count=" . scalar(@$sourceSnaps) . ", filtered target snapshots count=" . scalar(@$targetSnaps) ) if $verboseLoggingLevel >= 4;
615
   logMsg( "makeReplicateCommands: filtered source snapshots: " . join(', ', sort @$sourceSnaps) ) if $verboseLoggingLevel >= 5;
616
   logMsg( "makeReplicateCommands: filtered target snapshots: " . join(', ', sort @$targetSnaps) ) if $verboseLoggingLevel >= 5;
44 rodolico 617
 
60 rodolico 618
   # Parse source snapshots to build a hash indexed by filesystem
619
   # Input lines may have format: "pool/fs@snapshot extra data"
620
   # We extract just the first token (pool/fs@snapshot) and split it into filesystem and snapshot name
621
   # Result: %snaps_by_fs = { "pool/fs" => ["snap1", "snap2", ...] }
622
   # This groups all snapshots by their parent filesystem
25 rodolico 623
   my %snaps_by_fs;
44 rodolico 624
   foreach my $line (@$sourceSnaps) {
60 rodolico 625
      next unless defined $line && $line =~ /\S/;  # Skip empty lines
626
      my ($tok) = split /\s+/, $line;              # Get first token
627
      next unless $tok && $tok =~ /@/;             # Must contain @ separator
628
      my ($fs, $snap) = split /@/, $tok, 2;        # Split into filesystem and snapshot name
629
      push @{ $snaps_by_fs{$fs} }, $snap;          # Add snapshot to this filesystem's list
25 rodolico 630
   }
631
 
60 rodolico 632
   logMsg( "makeReplicateCommands: parsed filesystems: " . join(', ', sort keys %snaps_by_fs) ) if $verboseLoggingLevel >= 4;
633
 
634
   # If no snapshots were found, return empty array (nothing to replicate)
25 rodolico 635
   return [] unless keys %snaps_by_fs;
636
 
60 rodolico 637
   # Determine the root filesystem for recursive operations
638
   # We try to get it from the first non-empty snapshot line, otherwise use first sorted key
639
   # The root filesystem is used when we can do a single recursive send instead of multiple sends
44 rodolico 640
   my ($first_line) = grep { defined $_ && $_ =~ /\S/ } @$sourceSnaps;
25 rodolico 641
   my ($root_fs) = $first_line ? (split(/\s+/, $first_line))[0] =~ /@/ ? (split(/@/, (split(/\s+/, $first_line))[0]))[0] : undef : undef;
642
   $root_fs ||= (sort keys %snaps_by_fs)[0];
643
 
60 rodolico 644
   # Build a hash of the most recent snapshot on target for each filesystem
645
   # This tells us what's already been replicated, so we can do incremental sends
646
   # If a filesystem isn't in this hash, we need to do a full (non-incremental) send
647
   # Note: If multiple snapshots exist for a filesystem, we keep only the last one
648
   # (later entries override earlier ones in the hash assignment)
25 rodolico 649
   my %last_status_for;
44 rodolico 650
   for my $s (@$targetSnaps) {
25 rodolico 651
      next unless $s && $s =~ /@/;
652
      my ($fs, $snap) = split /@/, $s, 2;
653
      $last_status_for{$fs} = $snap;    # later entries override earlier ones -> last occurrence kept
654
   }
655
 
60 rodolico 656
   if ($verboseLoggingLevel >= 4) {
657
      logMsg( "makeReplicateCommands: last status snapshots:" );
658
      for my $fs (sort keys %last_status_for) {
659
         logMsg( "  $fs => $last_status_for{$fs}" );
660
      }
661
   }
662
 
663
   # Build "from" and "to" snapshot mappings for each filesystem
664
   # "to" = the newest snapshot on source (what we want to send)
665
   # "from" = the last replicated snapshot on target (what we're sending from)
666
   # If "from" is undef, this filesystem hasn't been replicated before -> full send needed
667
   # Example: from="daily-2025-12-15" to="daily-2025-12-17" -> incremental send
668
   #          from=undef to="daily-2025-12-17" -> full send
669
   # NOTE: The "from" snapshot must exist in the source's snapshot list for incremental send
670
   #       If it doesn't exist in source, we need to find a common snapshot or do full send
25 rodolico 671
   my %from_for;
672
   my %to_for;
673
   foreach my $fs (keys %snaps_by_fs) {
60 rodolico 674
      my $arr = $snaps_by_fs{$fs};              # Get all snapshots for this filesystem
675
      next unless @$arr;                        # Skip if no snapshots
676
      $to_for{$fs} = $arr->[-1];                # Last element = newest snapshot to send
677
 
678
      # Check if the target's last status snapshot exists in the source list
679
      # If it does, we can do incremental send from that point
680
      # If it doesn't, the target may have a snapshot the source doesn't have anymore
681
      my $target_last = $last_status_for{$fs};
682
      if (defined $target_last && grep { $_ eq $target_last } @$arr) {
683
         $from_for{$fs} = $target_last;         # Use target's last snapshot as "from"
684
      } else {
685
         # Target's snapshot doesn't exist in source list - need full send
686
         $from_for{$fs} = undef;
687
      }
25 rodolico 688
   }
689
 
60 rodolico 690
   if ($verboseLoggingLevel >= 4) {
691
      logMsg( "makeReplicateCommands: from/to mapping:" );
692
      for my $fs (sort keys %to_for) {
693
         my $from = $from_for{$fs} // '(none - full send)';
694
         my $send_type = defined $from_for{$fs} ? 'incremental' : 'full';
695
         logMsg( "  $fs: from=$from to=$to_for{$fs} [$send_type]" );
696
      }
697
   }
698
 
699
   # Optimization check: Can we do a single recursive send?
700
   # Recursive sends are more efficient when replicating entire filesystem hierarchies
701
   # Condition: all filesystems must be sending to the same-named snapshot
702
   # Example: If pool/data@daily-2025-12-17 and pool/data/child@daily-2025-12-17 exist,
703
   #          we can do "zfs send -R pool/data@daily-2025-12-17" instead of two separate sends
704
   my %to_names = map { $_ => 1 } values %to_for;  # Get unique "to" snapshot names
25 rodolico 705
   my $single_to_name = (keys %to_names == 1) ? (keys %to_names)[0] : undef;
60 rodolico 706
 
707
   logMsg( "makeReplicateCommands: single_to_name=" . ($single_to_name // '(none - varied snapshots)') ) if $verboseLoggingLevel >= 4;
25 rodolico 708
 
709
   if ($single_to_name) {
60 rodolico 710
      # All filesystems are targeting the same snapshot name
711
      # Now check if we can use incremental recursive send or need full send
25 rodolico 712
      my @from_values = map { $from_for{$_} } sort keys %from_for;
60 rodolico 713
      my $any_from_missing = grep { !defined $_ } @from_values;  # Any filesystem not yet replicated?
714
      my %from_names = map { $_ => 1 } grep { defined $_ } @from_values;  # Unique "from" names
25 rodolico 715
      my $single_from_name = (keys %from_names == 1) ? (keys %from_names)[0] : undef;
716
 
60 rodolico 717
      logMsg( "makeReplicateCommands: single_from_name=" . ($single_from_name // '(none)') . ", any_from_missing=$any_from_missing" ) if $verboseLoggingLevel >= 4;
718
 
25 rodolico 719
      if ($any_from_missing) {
60 rodolico 720
         # At least one filesystem has never been replicated (from=undef)
721
         # Check if the ROOT filesystem has been replicated - if not, must do full recursive send
722
         # If only children are missing, we can still do per-filesystem sends with incrementals where possible
723
         if (!defined $from_for{$root_fs}) {
724
            # Root filesystem has never been replicated - must do full recursive send
725
            # Command: zfs send -R pool/dataset@snapshot
726
            logMsg( "makeReplicateCommands: generating full recursive send (root filesystem has no prior snapshot)" ) if $verboseLoggingLevel >= 4;
727
            $commands{$root_fs} = sprintf('zfs send -R %s%s@%s', $sourceParent, $root_fs, $single_to_name);
728
         } else {
729
            # Root has been replicated, but some children haven't - do per-filesystem sends
730
            # This allows incremental sends for filesystems that have prior snapshots
731
            logMsg( "makeReplicateCommands: root replicated but some children missing - using per-filesystem sends" ) if $verboseLoggingLevel >= 4;
732
            foreach my $fs (sort keys %to_for) {
733
               my $to  = $to_for{$fs};
734
               my $from = $from_for{$fs};
735
               if ($from) {
736
                  # Incremental send for this filesystem
737
                  $commands{$fs} = sprintf('zfs send -I %s%s@%s %s%s@%s', $sourceParent, $fs, $from, $sourceParent, $fs, $to)
738
                     unless $from eq $to;
739
               } else {
740
                  # Full send for this filesystem (never replicated before)
741
                  logMsg( "makeReplicateCommands: $fs - full send (no prior snapshot)" ) if $verboseLoggingLevel >= 4;
742
                  $commands{$fs} = sprintf('zfs send %s%s@%s', $sourceParent, $fs, $to);
743
               }
744
            }
745
         }
25 rodolico 746
      }
747
      elsif ($single_from_name) {
60 rodolico 748
         # All filesystems have been replicated AND they all have the same "from" snapshot
749
         # Perfect case for incremental recursive send
750
         # Command: zfs send -R -I pool/dataset@old pool/dataset@new
751
         if ($single_from_name eq $single_to_name) {
752
            # Source and target are already identical - nothing to send
753
            logMsg( "makeReplicateCommands: from and to snapshots are identical ($single_from_name) - no send needed" ) if $verboseLoggingLevel >= 4;
754
         } else {
755
            logMsg( "makeReplicateCommands: generating incremental recursive send from $single_from_name to $single_to_name" ) if $verboseLoggingLevel >= 4;
756
            $commands{$root_fs} = sprintf('zfs send -R -I %s%s@%s %s%s@%s',
757
                           $sourceParent, $root_fs, $single_from_name, $sourceParent, $root_fs, $single_to_name);
758
         }
25 rodolico 759
      }
760
      else {
60 rodolico 761
         # Filesystems have different "from" snapshots - can't use single recursive send
762
         # Fall back to individual per-filesystem sends
763
         logMsg( "makeReplicateCommands: from snapshots differ across children - using per-filesystem sends" ) if $verboseLoggingLevel >= 4;
25 rodolico 764
         foreach my $fs (sort keys %to_for) {
765
            my $to  = $to_for{$fs};
766
            my $from = $from_for{$fs};
767
            if ($from) {
60 rodolico 768
               # Incremental send: send all intermediate snapshots from "from" to "to"
769
               # Skip if from and to are identical (already up to date)
44 rodolico 770
               $commands{$fs} = sprintf('zfs send -I %s%s@%s %s%s@%s', $sourceParent, $fs, $from, $sourceParent, $fs, $to)
31 rodolico 771
                  unless $from eq $to;
25 rodolico 772
            } else {
60 rodolico 773
               # Full send: no prior snapshot on target, send everything
44 rodolico 774
               $commands{$fs} = sprintf('zfs send %s%s@%s', $sourceParent, $fs, $to);
25 rodolico 775
            }
776
         }
777
      }
778
 
60 rodolico 779
      # Update the status array with the new target snapshots
780
      # This will be written to the status file for tracking what's been replicated
781
      # Format: targetParent/filesystem@snapshot
25 rodolico 782
      foreach my $fs (keys %to_for) {
44 rodolico 783
         push @$newStatusRef, sprintf('%s%s@%s', $targetParent, $fs, $to_for{$fs});
25 rodolico 784
      }
60 rodolico 785
      logMsg( "makeReplicateCommands: added " . scalar(keys %to_for) . " entries to new status" ) if $verboseLoggingLevel >= 4;
25 rodolico 786
   } else {
60 rodolico 787
      # Filesystems have different "to" snapshot names - can't use recursive send
788
      # Must send each filesystem individually
789
      # This handles cases like:
790
      #   - Parent: pool/data@daily-2025-12-17
791
      #   - Child:  pool/data/child@hourly-2025-12-17-14
792
      # Each filesystem can still do incremental sends to its own target snapshot
793
      logMsg( "makeReplicateCommands: varied 'to' snapshots - using per-filesystem sends (each may be incremental)" ) if $verboseLoggingLevel >= 4;
25 rodolico 794
      foreach my $fs (sort keys %to_for) {
795
         my $to  = $to_for{$fs};
796
         my $from = $from_for{$fs};
797
         if ($from) {
60 rodolico 798
            # Incremental send for this filesystem to its specific target snapshot
799
            # Command: zfs send -I pool/fs@old pool/fs@new
800
            # Note: "old" and "new" are specific to this filesystem, not necessarily matching parent
801
            logMsg( "makeReplicateCommands: $fs - incremental send from $from to $to" ) if $verboseLoggingLevel >= 4;
44 rodolico 802
            $commands{$fs} = sprintf('zfs send -I %s%s@%s %s%s@%s', $sourceParent, $fs, $from, $sourceParent, $fs, $to);
25 rodolico 803
         } else {
60 rodolico 804
            # Full send for this filesystem (never replicated before, or target snap not in source)
805
            # Command: zfs send pool/fs@snapshot
806
            logMsg( "makeReplicateCommands: $fs - full send to $to (no common snapshot)" ) if $verboseLoggingLevel >= 4;
44 rodolico 807
            $commands{$fs} = sprintf('zfs send %s%s@%s', $sourceParent, $fs, $to);
25 rodolico 808
         }
60 rodolico 809
         # Add to status tracking
44 rodolico 810
         push @$newStatusRef, sprintf('%s%s@%s', $targetParent, $fs, $to);
25 rodolico 811
      }
60 rodolico 812
      logMsg( "makeReplicateCommands: added " . scalar(keys %to_for) . " entries to new status" ) if $verboseLoggingLevel >= 4;
25 rodolico 813
   }
814
 
60 rodolico 815
   logMsg( "makeReplicateCommands: generated " . scalar(keys %commands) . " commands" ) if $verboseLoggingLevel >= 4;
816
 
817
   # Return hash reference of commands: { "filesystem" => "zfs send command" }
818
   # Caller will typically pipe these to "zfs receive" on target
31 rodolico 819
   return \%commands;
25 rodolico 820
}
821
 
35 rodolico 822
# Send report via email and/or copy to target drive.
823
# $reportConfig is a hashref with optional keys:
824
#   email - email address to send report to
825
#   targetDrive - hashref with keys:
826
#       label - GPT or msdosfs label of the target drive
827
#       mount_point - optional mount point to use (if not provided, /mnt/label is used)
828
# $subject is the email subject
42 rodolico 829
# $message is the message to include in the email body
830
# $logFile is the path to the log file to include in the report
35 rodolico 831
sub sendReport {
42 rodolico 832
   my ( $reportConfig, $message, $logFile ) = @_;
35 rodolico 833
   return unless defined $reportConfig;
42 rodolico 834
   $logFile //= $reportConfig->{logFile};
51 rodolico 835
   logMsg( "Beginning sendReport" ) if $verboseLoggingLevel >= 0;
37 rodolico 836
   # if targetDrive defined and there is a valid label for it, try to mount it and write the report there
837
   if ( defined $reportConfig->{targetDrive} && defined $reportConfig->{targetDrive}->{label} && $reportConfig->{targetDrive}->{label} ) {
51 rodolico 838
      logMsg( "Saving report to disk with label $reportConfig->{targetDrive}->{label}" ) if $verboseLoggingLevel >= 2;
46 rodolico 839
      if ( $reportConfig->{targetDrive}->{mountPath} = mountDriveByLabel( $reportConfig->{targetDrive} ) ) {
840
         copyReportToDrive( $logFile, $reportConfig->{targetDrive}->{mountPath} );
841
         unmountDriveByLabel( $reportConfig->{targetDrive} );
35 rodolico 842
      } else {
51 rodolico 843
         logMsg( "Warning: could not mount report target drive with label '$reportConfig->{targetDrive}->{label}'" ) if $verboseLoggingLevel >= 1;
35 rodolico 844
      }
845
   }
42 rodolico 846
   # if they have set an e-mail address, try to e-mail the report
847
   if ( defined $reportConfig->{email} && $reportConfig->{email} ne '' ) {
51 rodolico 848
      logMsg( "Sending report via e-mail to $reportConfig->{email}" ) if $verboseLoggingLevel >= 1;
42 rodolico 849
      $reportConfig->{subject} //= 'Replication Report from ' . `hostname`;
850
      sendEmailReport( $reportConfig->{email}, $reportConfig->{subject}, $message, $logFile );
851
   }
35 rodolico 852
}
25 rodolico 853
 
48 rodolico 854
## Copy the report log file to a mounted target drive.
855
##
856
## Arguments:
857
##   $logFile    - path to the log file to copy (must exist)
858
##   $mountPoint - mount point of the target drive (must be a directory)
859
##
860
## Behavior:
861
##   - Copies the log file into the root of $mountPoint using File::Copy::copy
862
##   - Logs success/failure via logMsg
35 rodolico 863
sub copyReportToDrive {
864
   my ( $logFile, $mountPoint ) = @_;
865
   return unless defined $logFile && -e $logFile;
866
   return unless defined $mountPoint && -d $mountPoint;
867
 
868
   my $targetFile = "$mountPoint/" . ( split( /\//, $logFile ) )[-1];
51 rodolico 869
   logMsg( "Copying report log file $logFile to drive at $mountPoint" ) if $verboseLoggingLevel >= 2;
46 rodolico 870
   use File::Copy;
35 rodolico 871
   unless ( copy( $logFile, $targetFile ) ) {
51 rodolico 872
      logMsg( "Could not copy report log file to target drive: $!" ) if $verboseLoggingLevel >= 0;
35 rodolico 873
   }
874
}
875
 
48 rodolico 876
## Send an email report with an attached log body.
877
##
878
## Arguments:
879
##   $to      - recipient email address (string)
880
##   $subject - subject line (string)
881
##   $message - optional message body (string)
882
##   $logFile - optional path to log file whose contents will be appended to the email body
883
##
884
## Behavior:
885
##   - Opens /usr/sbin/sendmail -t and writes a simple plain-text email including the
886
##     supplied message and the contents of $logFile (if present).
887
##   - Logs failures to open sendmail or read the log file.
35 rodolico 888
sub sendEmailReport {
42 rodolico 889
   my ( $to, $subject, $message, $logFile ) = @_;
35 rodolico 890
   return unless defined $to && $to ne '';
37 rodolico 891
   $subject //= 'Sneakernet Replication Report from ' . `hostname`;
42 rodolico 892
   $message //= '';
37 rodolico 893
   $logFile //= '';
35 rodolico 894
 
51 rodolico 895
   logMsg( "Sending email report to $to with subject '$subject'" ) if $verboseLoggingLevel >= 2;
35 rodolico 896
   open my $mailfh, '|-', '/usr/sbin/sendmail -t' or do {
51 rodolico 897
      logMsg( "Could not open sendmail: $!" ) if $verboseLoggingLevel >= 0;
35 rodolico 898
      return;
899
   };
900
   print $mailfh "To: $to\n";
901
   print $mailfh "Subject: $subject\n";
902
   print $mailfh "MIME-Version: 1.0\n";
903
   print $mailfh "Content-Type: text/plain; charset=\"utf-8\"\n";
904
   print $mailfh "\n"; # end of headers
37 rodolico 905
 
42 rodolico 906
   print $mailfh "$message\n";
907
   print $mailfh "\nLog contents:\n\n";
37 rodolico 908
   if ( -e $logFile && open my $logfh, '<', $logFile ) {
909
      while ( my $line = <$logfh> ) {
910
         print $mailfh $line;
911
      }
912
      close $logfh;
913
   } else {
51 rodolico 914
      logMsg( "Could not open log file [$logFile] for reading: $!" ) if $verboseLoggingLevel >= 0;
35 rodolico 915
   };
37 rodolico 916
 
35 rodolico 917
   close $mailfh;
918
}  
919
 
48 rodolico 920
## Return list of regular files in a directory (non-recursive).
921
##
922
## Arguments:
923
##   $dirname - directory to scan
924
##
925
## Returns: ARRAYREF of full-path filenames on success, 0 on error (matching prior behavior).
42 rodolico 926
sub getDirectoryList {
927
   my $dirname = shift;
928
   opendir( my $dh, $dirname ) || return 0;
929
   # get all file names, but leave directories alone
930
   my @files = map{ $dirname . "/$_" } grep { -f "$dirname/$_" } readdir($dh);
931
   closedir $dh;
932
   return \@files;
933
}
934
 
48 rodolico 935
## Remove all regular files from the specified directory (non-recursive).
936
##
937
## Arguments:
938
##   $dirname - directory to clean
939
##
940
## Behavior:
941
##   - Calls getDirectoryList to obtain files and unlinks each file. Directories are left untouched.
942
##   - Logs the cleanup operation via logMsg.
943
##
944
## Returns: 1 on completion. Note: individual unlink failures are currently reported via warn.
42 rodolico 945
sub cleanDirectory {
946
   my $dirname = shift;
51 rodolico 947
   logMsg( "Cleaning up $dirname of all files" ) if $verboseLoggingLevel >= 2;
42 rodolico 948
   my $files = getDirectoryList( $dirname );
949
   # clean up a directory
950
   foreach my $file (@$files) {
951
      unlink $file or warn "Could not unlink $file: #!\n";
952
   }
953
   return 1;
954
}
955
 
48 rodolico 956
## Handle a fatal error: log, optionally run a cleanup routine, then die.
957
##
958
## Arguments:
959
##   $message        - string message describing the fatal condition
960
##   $config         - OPTIONAL configuration HASHREF (passed to cleanupRoutine)
961
##   $cleanupRoutine - OPTIONAL CODE ref to run prior to dying; will be called as
962
##                     $cleanupRoutine->($config, $message)
963
##
964
## Behavior:
965
##   - Logs the fatal message via logMsg, runs the cleanup code if provided (errors in the cleanup
966
##     are logged), then terminates the process via die.
42 rodolico 967
sub fatalError {
968
   my ( $message, $config, $cleanupRoutine ) = @_;
51 rodolico 969
   logMsg( "FATAL ERROR: $message" ) if $verboseLoggingLevel >= 0;
42 rodolico 970
   if ( defined $cleanupRoutine && ref $cleanupRoutine eq 'CODE' ) {
51 rodolico 971
      logMsg( "Running cleanup routine before fatal error" ) if $verboseLoggingLevel >= 2;
42 rodolico 972
      eval {
973
         $cleanupRoutine->( $config, $message );
974
         1;
975
      } or do {
51 rodolico 976
         logMsg( "Cleanup routine failed: $@" ) if $verboseLoggingLevel >= 0;
42 rodolico 977
      };
978
   }
979
   die;
980
}
981
 
982
 
24 rodolico 983
1;