Subversion Repositories zfs_utils

Rev

Rev 34 | Rev 37 | Go to most recent revision | 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
37
# Copyright 2024 Daily Data Inc. <rodo@dailydata.net>
38
 
39
# currently used for sneakernet scripts, but plans to expand to other ZFS related tasks
40
# functions include:
41
#   runCmd: execute a command and return its output
42
#   shredFile: securely delete a file using gshred
43
#   logMsg: log messages to a log file and optionally to console
44
#   mountDriveByLabel: find and mount a drive by its GPT label
45
#   loadConfig: load a YAML configuration file into a hashref
46
#   mountGeli: decrypt and mount a GELI encrypted ZFS pool
47
#   makeGeliKey: create a GELI key by XOR'ing a remote binary keyfile and a local hex key
48
#   decryptAndMountGeli: decrypt GELI disks and mount the ZFS pool
49
#   findGeliDisks: find available disks for GELI/ZFS use
50
#   makeReplicateCommands: create zfs send commands for replication based on snapshot lists
51
 
52
 
53
# Exported functions and variables
54
 
35 rodolico 55
our @EXPORT_OK = qw(loadConfig shredFile mountDriveByLabel mountGeli logMsg runCmd makeReplicateCommands sendReport $logFileName $displayLogsOnConsole);
24 rodolico 56
 
57
 
34 rodolico 58
our $VERSION = '0.2';
24 rodolico 59
our $logFileName = '/tmp/zfs_utils.log'; # this can be overridden by the caller, and turned off with empty string
34 rodolico 60
our $displayLogsOnConsole = 1; # if non-zero, log messages are also printed to console
27 rodolico 61
our $merge_stderr = 0; # if set to 1, stderr is captured in runCmd
24 rodolico 62
 
25 rodolico 63
# Execute a command and return its output.
64
# If called in scalar context, returns the full output as a single string.
65
# If called in list context, returns the output split into lines.
66
# If $merge_stderr is true (default), stderr is merged into stdout (only for scalar commands).
34 rodolico 67
# returns undef on failure and logs failure message.
25 rodolico 68
sub runCmd {
33 rodolico 69
   my $cmd = join( ' ', @_ );
25 rodolico 70
   $merge_stderr = 1 unless defined $merge_stderr;
71
   my $output = '';
72
 
34 rodolico 73
   logMsg( "Running command [$cmd]" );
74
   $cmd .= ' 2>&1' if $merge_stderr;
75
   $output = `$cmd`;
76
   if ($? == -1) {
77
      logMsg( "failed to execute: $!");
78
      return ''
79
   }
80
   elsif ($? & 127) { # fatal error, exit program
81
      logMsg( sprintf( "child died with signal %d, %s coredump\n", ($? & 127),  ($? & 128) ? 'with' : 'without' ) );
82
      die;
83
   }
84
   else {
85
      logMsg( sprintf( "child exited with value %d\n", $? >> 8 ) );
86
   }
25 rodolico 87
   $output //= '';
88
 
89
   if (wantarray) {
90
      return $output eq '' ? () : split(/\n/, $output);
91
   } else {
92
      return $output;
93
   }
94
}
95
 
24 rodolico 96
# this calls gshred which will overwrite the file 3 times, then
97
# remove it.
98
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
99
# so assuming file is on something without COW (ramdisk, UFS, etc)
100
sub shredFile {
101
   my $filename = shift;
102
   `/usr/local/bin/gshred -u -f -s 32 $filename` if -e $filename;
103
}
104
 
105
sub logMsg {
106
    my $msg = shift;
107
    my $filename = shift // $logFileName;
108
    my $timeStampFormat = shift // '%Y-%m-%d %H:%M:%S';
109
    my $timestamp = strftime($timeStampFormat, localtime());
110
    if (defined $filename && $filename ne '' ) {
111
       open my $logfh, '>>', $filename or die "Could not open log file $filename: $!\n";
112
       print $logfh "$timestamp\t$msg\n";
113
       close $logfh;
114
    }
115
    print "$timestamp\t$msg\n" if ($displayLogsOnConsole);
116
}
117
 
35 rodolico 118
# find a drive by it's label by scanning /dev/gpt/
119
# driveInfo is a hashref with the following keys:
120
# label - the GPT label of the drive (required)
121
# filesystem - the filesystem type (default: ufs)
122
# mountPath - where to mount the drive (default: /mnt/label)
123
# timeout - how long to wait for the drive (default: 600 seconds)
124
# check_interval - how often to check for the drive (default: 15 seconds)
24 rodolico 125
# If the drive is found, mount it on mountPath and return the mountPath.
126
# If not found, return empty string.
127
sub mountDriveByLabel {
35 rodolico 128
   my ( $driveInfo ) = @_;
129
   unless ($driveInfo->{label}) {
130
      logMsg("mountDriveByLabel: No drive label provided");
24 rodolico 131
      return '';
132
   }
35 rodolico 133
   unless ( $driveInfo->{label} =~ /^[a-zA-Z0-9_\-]+$/ ) {
134
      logMsg("mountDriveByLabel: Invalid label '$driveInfo->{label}'");
24 rodolico 135
      return '';
136
   }
137
 
35 rodolico 138
   logMsg("mountDriveByLabel: Looking for drive with label '$driveInfo->{label}'");
24 rodolico 139
   # default to /mnt/label if not provided
35 rodolico 140
   $driveInfo->{mountPath} //= "/mnt/$driveInfo->{label}"; # this is where we'll mount it if we find it
141
   $driveInfo->{filesystem} //= 'ufs'; # default to mounting ufs
34 rodolico 142
   # The location for the label depends on filesystem. Only providing access to ufs and msdos here for safety.
143
   # gpt labeled drives for ufs are in /dev/gpt/, for msdosfs in /dev/msdosfs/
35 rodolico 144
   $driveInfo->{mountPath} = $driveInfo->{filesystem} eq 'msdos' ? "/dev/msdosfs/$driveInfo->{label}" : "/dev/gpt/$driveInfo->{label}"; 
31 rodolico 145
   # drive already mounted, just return the path
35 rodolico 146
   return $driveInfo->{mountPath} if ( runCmd( "mount | grep '$driveInfo->{mountPath}'" ) );
24 rodolico 147
   # default to 10 minutes (600 seconds) if not provided
35 rodolico 148
   $driveInfo->{timeout} //= 600;
24 rodolico 149
   # default to checking every minute if not provided
35 rodolico 150
   $driveInfo->{check_interval} //= 15;
24 rodolico 151
   # wait up to $timeout seconds for device to appear, checking every 10 seconds
35 rodolico 152
   while ( $driveInfo->{timeout} > 0 ) {
153
      if ( -e "$driveInfo->{label}" ) {
24 rodolico 154
         last;
155
      } else {
35 rodolico 156
         sleep $driveInfo->{check_interval};
157
         $driveInfo->{timeout} -= $driveInfo->{check_interval};
158
         print "Waiting for drive labeled $driveInfo->{label}\n";
24 rodolico 159
      }
160
    }
161
    # if we found it, mount and return mount path
35 rodolico 162
    if ( -e "$driveInfo->{label}" ) {
24 rodolico 163
       # ensure mount point
35 rodolico 164
       unless ( -d $driveInfo->{mountPath} || make_path($driveInfo->{mountPath}) ) {
165
         logMsg("Failed to create $driveInfo->{mountPath}: $!");
24 rodolico 166
         return '';
167
       }
168
       # mount device (let mount detect filesystem)
35 rodolico 169
       unless ( runCmd( "mount -t $driveInfo->{filesystem} $driveInfo->{label} $driveInfo->{mountPath}" ) ) {
170
         logMsg("Failed to mount $driveInfo->{label} on $driveInfo->{mountPath}: $!");
24 rodolico 171
         return '';
172
       }
35 rodolico 173
       return $driveInfo->{mountPath};
24 rodolico 174
    } else {
175
       return '';
176
    }
177
}
178
 
179
## Load a YAML configuration file into a hashref.
180
## If the file does not exist, and a default hashref is provided,
181
## create the file by dumping the default to YAML, then return the default.
182
sub loadConfig {
183
    my ($filename, $default) = @_;
184
 
185
    # If no filename was provided, return default or empty hashref
186
    die "No filename provided to loadConfig\n" unless defined $filename;
187
 
188
    # If file doesn't exist but a default hashref was provided, try to
189
    # create the file by dumping the default to YAML, then return the default.
190
    unless (-e $filename) {
191
      logMsg("Config file $filename does not exist. Creating it with default values.");
192
      if ($default && ref $default eq 'HASH') {
193
         my $wrote = 0;
194
         eval {
195
               require YAML::XS;
196
               YAML::XS->import();
197
               YAML::XS::DumpFile($filename, $default);
198
               $wrote = 1;
199
               1;
200
         } or do {
201
               eval {
202
                  require YAML::Tiny;
203
                  YAML::Tiny->import();
204
                  my $yt = YAML::Tiny->new($default);
205
                  $yt->write($filename);
206
                  $wrote = 1;
207
                  1;
208
               } or do {
209
                  logMsg("No YAML writer available (YAML::XS or YAML::Tiny). Could not create $filename");
210
               };
211
         };
212
 
213
         die "Failed to write default config to $filename:$!\n" unless $wrote;
214
        }
215
 
216
        # No default provided; nothing to create
217
        return {};
218
    }
219
 
220
    my $yaml;
221
 
222
    # Try YAML::XS first, fall back to YAML::Tiny
223
    eval {
224
        require YAML::XS;
225
        YAML::XS->import();
226
        $yaml = YAML::XS::LoadFile($filename);
227
        logMsg("using YAML::XS to load $filename");
228
        1;
229
    } or do {
230
        eval {
231
            require YAML::Tiny;
232
            YAML::Tiny->import();
233
            $yaml = YAML::Tiny->read($filename);
234
            $yaml = $yaml->[0] if $yaml;  # YAML::Tiny returns an arrayref of documents
235
            logMsg("using YAML::Tiny to load $filename");
236
            1;
237
        } or do {
238
            logMsg("No YAML parser installed (YAML::XS or YAML::Tiny). Skipping config load from $filename");
239
            return ($default && ref $default eq 'HASH') ? $default : {};
240
        };
241
    };
242
    # Ensure we have a hashref
243
    die "Config file $filename did not produce a HASH.\n" unless (defined $yaml && ref $yaml eq 'HASH');
244
 
245
    return $yaml;
246
}
247
 
248
 
249
 
250
sub mountGeli {
251
   my $geliConfig = shift;
30 rodolico 252
   unless ( $geliConfig->{'localKey'} ) {
253
      logMsg "Could not find local key in configuration file\n";
24 rodolico 254
      return '';
255
   }
256
   # find the keyfile disk and mount it
257
   my $path = mountDriveByLabel( $geliConfig->{'keydiskname'} );
258
   unless ( $path ne '' and -e "$path/" . $geliConfig->{'keyfile'} ) {
259
      logMsg "Could not find or mount keyfile disk with label: " . $geliConfig->{'keydiskname'} . "\n";
260
      return '';
261
   }
262
   # create the combined geli keyfile in target location
263
   unless ( makeGeliKey( "$path/" . $geliConfig->{'keyfile'}, $geliConfig->{'localKey'}, $geliConfig->{'target'} ) ) {
264
         logMsg "Could not create geli keyfile\n";
265
         return '';
266
      }
267
   # decrypt and mount the geli disks and zfs pool
268
   my $poolname = decryptAndMountGeli( $geliConfig );
269
   return $poolname;
270
 
271
}
272
 
30 rodolico 273
# find all disks which are candidates for use with geli/zfs
274
# Grabs all disks on the system, then removes those with partitions
275
# and those already used in zpools.
276
sub findGeliDisks {
277
   logMsg("Finding available disks for GELI/ZFS use");
278
   # get all disks in system
279
   my %allDisks = map{ chomp $_ ; $_ => 1 } runCmd( "geom disk list | grep 'Geom name:' | rev | cut -d' ' -f1 | rev" );
280
   # get the disks with partitions
281
   my @temp = runCmd( "gpart show -p | grep '^=>'");  # -p prints just the disks without partitions
282
   # remove them from the list
283
   foreach my $disk ( @temp ) {
284
      $allDisks{$1} = 0 if ( $disk =~ m/^=>[\t\s0-9]+([a-z][a-z0-9]+)/ ) ;
285
   }
286
 
287
   # get disk which are currently used for zpools
288
   @temp = runCmd( "zpool status -LP | grep '/dev/'" );
289
   foreach my $disk ( @temp ) {
290
      $allDisks{$1} = 0 if  $disk =~ m|/dev/([a-z]+\d+)|;
291
   }
292
 
293
   # return only the disks which are free (value 1)
294
   return grep{ $allDisks{$_} == 1 } keys %allDisks;
295
}
296
 
24 rodolico 297
## Decrypt each GELI disk from $geliConfig->{'diskList'} using the keyfile,
298
## then import and mount the ZFS pool specified in $geliConfig->{'poolname'}.
299
##
300
## Returns the pool name on success, empty on error.
301
sub decryptAndMountGeli {
302
   my ($geliConfig) = @_;
30 rodolico 303
 
304
   # Can't continue at all if no pool name
24 rodolico 305
   die "No pool name specified in config\n" unless $geliConfig->{'poolname'};
30 rodolico 306
   # if no list of disks provided, try to find them
307
   $geliConfig->{'diskList'} //= findGeliDisks();
308
 
24 rodolico 309
   my $diskList = $geliConfig->{'diskList'};
310
   my $poolname = $geliConfig->{'poolname'};
311
   my $keyfile = $geliConfig->{'target'};
312
   unless ( -e $keyfile ) {
313
      logMsg "GELI keyfile $keyfile does not exist\n";
314
      return '';
315
   }
316
 
317
   my @decrypted_devices;
318
 
319
   # Decrypt each disk in the list
30 rodolico 320
   foreach my $disk (@{$geliConfig->{'diskList'}}) {
24 rodolico 321
      unless ( -e $disk ) {
322
         logMsg "Disk $disk does not exist\n";
323
         return '';
324
      }
325
 
326
      # Derive the decrypted device name (.eli suffix on FreeBSD)
327
      my $decrypted = $disk . '.eli';
328
 
329
      # Decrypt using geli attach with the keyfile
330
      logMsg("Decrypting $disk with keyfile $keyfile");
30 rodolico 331
      if ( my $result = system('geli', 'attach', '-k', $geliConfig->{'target'}, $disk) == 0 ) {
24 rodolico 332
         logMsg "Failed to decrypt $disk (exit $result)\n";
30 rodolico 333
         next; # ignore failed disks and continue to see if we can import the pool
24 rodolico 334
      }
335
 
336
      unless ( -e $decrypted ) {
337
         logMsg "Decrypted device $decrypted does not exist after geli attach\n";
338
         return '';
339
      }
340
      push @decrypted_devices, $decrypted;
341
   }
342
 
343
   # Import the ZFS pool
344
   logMsg("Importing ZFS pool $poolname");
345
   my @import_cmd = ('zpool', 'import');
346
   # If decrypted devices exist, add their directories to -d list
30 rodolico 347
   #foreach my $dev (@decrypted_devices) {
348
   #   my $dir = $dev;
349
   #   $dir =~ s!/[^/]+$!!;  # Remove filename to get directory
350
   #   push @import_cmd, '-d', $dir;
351
   #}
352
 
24 rodolico 353
   push @import_cmd, $poolname;
354
 
355
   my $result = system(@import_cmd);
356
   unless ( $result == 0 ) {
357
      logMsg("Failed to import zfs pool $poolname (exit $result)\n");
358
      return '';
359
   }
360
 
361
   # Mount the ZFS pool (zfs mount -a mounts all filesystems in the pool)
362
   logMsg("Mounting ZFS pool $poolname");
363
   $result = system('zfs', 'mount', '-a');
364
   unless ( $result == 0 ) {
365
      logMsg("Failed to mount zfs pool $poolname (exit $result)\n");
366
      return '';
367
   }
368
 
369
   logMsg("Successfully decrypted and mounted pool $poolname");
370
   return $poolname;
371
}
372
 
373
## Create a GELI key by XOR'ing a remote binary keyfile and a local key (hex string).
374
##
375
## Arguments:
376
##   $remote_keyfile - path to binary keyfile (32 bytes)
377
##   $localKeyHexOrPath - hex string (64 hex chars) or path to file containing hex
378
##   $target - path to write the resulting 32-byte binary key
379
##
380
## Returns true on success, dies on fatal error.
381
sub makeGeliKey {
382
   my ($remote_keyfile, $localKeyHexOrPath, $target) = @_;
383
 
384
   die "remote keyfile not provided" unless defined $remote_keyfile;
385
   die "local key not provided" unless defined $localKeyHexOrPath;
386
   die "target not provided" unless defined $target;
387
 
388
   die "Remote keyfile $remote_keyfile does not exist\n" unless -e $remote_keyfile;
389
 
390
   # Read remote binary key
391
   open my $rh, '<:raw', $remote_keyfile or die "Unable to open $remote_keyfile: $!\n";
392
   my $rbuf;
393
   my $read = read($rh, $rbuf, 32);
394
   close $rh;
395
   die "Failed to read 32 bytes from $remote_keyfile (got $read)\n" unless defined $read && $read == 32;
396
 
397
   # Get local hex string (either direct string or file contents)
398
   my $hex;
399
   if (-e $localKeyHexOrPath) {
400
      open my $lh, '<', $localKeyHexOrPath or die "Unable to open local key file $localKeyHexOrPath: $!\n";
401
      local $/ = undef;
402
      $hex = <$lh>;
403
      close $lh;
404
   } else {
405
      $hex = $localKeyHexOrPath;
406
   }
407
   # clean hex (remove whitespace/newlines and optional 0x)
408
   $hex =~ s/0x//g;
409
   $hex =~ s/[^0-9a-fA-F]//g;
410
 
411
   die "Local key must be 64 hex characters (256-bit)\n" unless length($hex) == 64;
412
 
413
   my $lbuf = pack('H*', $hex);
414
   die "Local key decoded to unexpected length " . length($lbuf) . "\n" unless length($lbuf) == 32;
415
 
416
   # XOR the two buffers
417
   my $out = '';
418
   for my $i (0 .. 31) {
419
      $out .= chr( ord(substr($rbuf, $i, 1)) ^ ord(substr($lbuf, $i, 1)) );
420
   }
421
 
422
   # Ensure target directory exists
423
   my ($vol, $dirs, $file) = ($target =~ m{^(/?)(.*/)?([^/]+)$});
424
   if ($dirs) {
425
      my $dir = $dirs;
426
      $dir =~ s{/$}{};
427
      unless (-d $dir) {
428
         require File::Path;
429
         File::Path::make_path($dir) or die "Failed to create directory $dir: $!\n";
430
      }
431
   }
432
 
433
   # Write out binary key and protect permissions
434
   open my $oh, '>:raw', $target or die "Unable to open $target for writing: $!\n";
435
   print $oh $out or die "Failed to write to $target: $!\n";
436
   close $oh;
437
   chmod 0600, $target;
438
 
439
   return 1;
440
}
441
 
25 rodolico 442
sub makeReplicateCommands {
443
   my ($sourceSnapsRef, $statusRef, $newStatusRef) = @_;
444
   $sourceSnapsRef ||= [];
445
   $statusRef     ||= [];
446
   $newStatusRef  ||= [];
447
 
448
   # parse snapshots: each line is expected to have snapshot fullname as first token: pool/fs@snap ...
449
   my %snaps_by_fs;
450
   foreach my $line (@$sourceSnapsRef) {
451
      next unless defined $line && $line =~ /\S/;
452
      my ($tok) = split /\s+/, $line;
453
      next unless $tok && $tok =~ /@/;
454
      my ($fs, $snap) = split /@/, $tok, 2;
455
      push @{ $snaps_by_fs{$fs} }, $snap;
456
   }
457
 
458
   # nothing to do
459
   return [] unless keys %snaps_by_fs;
460
 
461
   # figure root filesystem: first snapshot line's fs is the requested root
462
   my ($first_line) = grep { defined $_ && $_ =~ /\S/ } @$sourceSnapsRef;
463
   my ($root_fs) = $first_line ? (split(/\s+/, $first_line))[0] =~ /@/ ? (split(/@/, (split(/\s+/, $first_line))[0]))[0] : undef : undef;
464
   $root_fs ||= (sort keys %snaps_by_fs)[0];
465
 
466
   # helper: find last status entry for a filesystem (status lines contain full snapshot names pool/fs@snap)
467
   my %last_status_for;
468
   for my $s (@$statusRef) {
469
      next unless $s && $s =~ /@/;
470
      my ($fs, $snap) = split /@/, $s, 2;
471
      $last_status_for{$fs} = $snap;    # later entries override earlier ones -> last occurrence kept
472
   }
473
 
474
   # build per-filesystem "from" and "to"
475
   my %from_for;
476
   my %to_for;
477
   foreach my $fs (keys %snaps_by_fs) {
478
      my $arr = $snaps_by_fs{$fs};
479
      next unless @$arr;
480
      $to_for{$fs} = $arr->[-1];
481
      $from_for{$fs} = $last_status_for{$fs};    # may be undef -> full send required
482
   }
483
 
484
   # decide if we can do a single recursive send:
485
   # condition: all 'to' snapshot names are identical
486
   my %to_names = map { $_ => 1 } values %to_for;
487
   my $single_to_name = (keys %to_names == 1) ? (keys %to_names)[0] : undef;
488
 
31 rodolico 489
   my %commands;
25 rodolico 490
 
491
   if ($single_to_name) {
492
      # check whether any from is missing
493
      my @from_values = map { $from_for{$_} } sort keys %from_for;
494
      my $any_from_missing = grep { !defined $_ } @from_values;
495
      my %from_names = map { $_ => 1 } grep { defined $_ } @from_values;
496
      my $single_from_name = (keys %from_names == 1) ? (keys %from_names)[0] : undef;
497
 
498
      if ($any_from_missing) {
499
         # full recursive send from root
31 rodolico 500
         $commands{'root_fs'} = sprintf('zfs send -R %s@%s', $root_fs, $single_to_name);
25 rodolico 501
      }
502
      elsif ($single_from_name) {
31 rodolico 503
         # incremental recursive send, but don't do it if they are the same
504
         $commands{$root_fs} = sprintf('zfs send -R -I %s@%s %s@%s',
505
                           $root_fs, $single_from_name, $root_fs, $single_to_name)
506
                           unless $single_from_name eq $single_to_name;
25 rodolico 507
      }
508
      else {
509
         # from snapshots differ across children -> fall back to per-filesystem sends
510
         foreach my $fs (sort keys %to_for) {
511
            my $to  = $to_for{$fs};
512
            my $from = $from_for{$fs};
513
            if ($from) {
31 rodolico 514
               # if from and to are different, add it
515
               $commands{$fs} = sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to)
516
                  unless $from eq $to;
25 rodolico 517
            } else {
31 rodolico 518
               $commands{$fs} = sprintf('zfs send %s@%s', $fs, $to);
25 rodolico 519
            }
520
         }
521
      }
522
 
523
      # update new status: record newest snap for every filesystem
524
      foreach my $fs (keys %to_for) {
525
         push @$newStatusRef, sprintf('%s@%s', $fs, $to_for{$fs});
526
      }
527
   } else {
528
      # not all children share same newest snap -> per-filesystem sends
529
      foreach my $fs (sort keys %to_for) {
530
         my $to  = $to_for{$fs};
531
         my $from = $from_for{$fs};
532
         if ($from) {
31 rodolico 533
            $commands{$fs} = sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to);
25 rodolico 534
         } else {
31 rodolico 535
            $commands{$fs} = sprintf('zfs send %s@%s', $fs, $to);
25 rodolico 536
         }
537
         push @$newStatusRef, sprintf('%s@%s', $fs, $to);
538
      }
539
   }
540
 
541
   # return arrayref of commands (caller can iterate or join with pipes)
31 rodolico 542
   return \%commands;
25 rodolico 543
}
544
 
35 rodolico 545
# Send report via email and/or copy to target drive.
546
# $reportConfig is a hashref with optional keys:
547
#   email - email address to send report to
548
#   targetDrive - hashref with keys:
549
#       label - GPT or msdosfs label of the target drive
550
#       mount_point - optional mount point to use (if not provided, /mnt/label is used)
551
# $subject is the email subject
552
# $logFile is the path to the log file to send/copy
553
sub sendReport {
554
   my ( $reportConfig, $subject, $logFile ) = @_;
555
   return unless defined $reportConfig;
556
   if ( defined $reportConfig->{email} && $reportConfig->{email} ne '' ) {
557
      sendEmailReport( $reportConfig->{email}, $subject, $logFile );
558
   }
559
   if ( defined $reportConfig->{targetDrive} ) {
560
      my $mountPoint = mountDriveByLabel( $reportConfig->{targetDrive}->{label}, $reportConfig->{targetDrive}->{mount_point}, 300 );
561
      if ( defined $mountPoint ) {
562
         copyReportToDrive( $logFile, $mountPoint );
563
         `umount $mountPoint`;
564
         rmdir $mountPoint;
565
      } else {
566
         logMsg( "Warning: could not mount report target drive with label '$reportConfig->{targetDrive}->{label}'" );
567
      }
568
   }
569
}
25 rodolico 570
 
35 rodolico 571
# Copy the report log file to the specified mount point.
572
# $logFile is the path to the log file to copy.
573
# $mountPoint is the mount point of the target drive.
574
# Does nothing if log file or mount point are invalid.
575
sub copyReportToDrive {
576
   my ( $logFile, $mountPoint ) = @_;
577
   return unless defined $logFile && -e $logFile;
578
   return unless defined $mountPoint && -d $mountPoint;
579
 
580
   my $targetFile = "$mountPoint/" . ( split( /\//, $logFile ) )[-1];
581
   logMsg( "Copying report log file $logFile to drive at $mountPoint" );
582
   unless ( copy( $logFile, $targetFile ) ) {
583
      logMsg( "Could not copy report log file to target drive: $!" );
584
   }
585
}
586
 
587
# Send an email report with the contents of the log file.
588
# $to is the recipient email address.
589
# $subject is the email subject.
590
# $logFile is the path to the log file to send.
591
# Does nothing if any parameter is invalid.
592
sub sendEmailReport {
593
   my ( $to, $subject, $logFile ) = @_;
594
   return unless defined $to && $to ne '';
595
   return unless defined $subject && $subject ne '';
596
   return unless defined $logFile && -e $logFile;
597
 
598
   logMsg( "Sending email report to $to with subject '$subject'" );
599
   open my $mailfh, '|-', '/usr/sbin/sendmail -t' or do {
600
      logMsg( "Could not open sendmail: $!" );
601
      return;
602
   };
603
   print $mailfh "To: $to\n";
604
   print $mailfh "Subject: $subject\n";
605
   print $mailfh "MIME-Version: 1.0\n";
606
   print $mailfh "Content-Type: text/plain; charset=\"utf-8\"\n";
607
   print $mailfh "\n"; # end of headers
608
 
609
   open my $logfh, '<', $logFile or do {
610
      logMsg( "Could not open log file $logFile for reading: $!" );
611
      close $mailfh;
612
      return;
613
   };
614
   while ( my $line = <$logfh> ) {
615
      print $mailfh $line;
616
   }
617
   close $logfh;
618
   close $mailfh;
619
}  
620
 
24 rodolico 621
1;