Subversion Repositories zfs_utils

Rev

Rev 27 | Rev 31 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
24 rodolico 1
package ZFS_Utils;
2
 
3
use strict;
4
use warnings;
5
use Exporter 'import';
6
use Data::Dumper;
7
use POSIX qw(strftime);
8
use File::Path qw(make_path);
9
 
25 rodolico 10
our @EXPORT_OK = qw(loadConfig shredFile mountDriveByLabel mountGeli logMsg runCmd makeReplicateCommands $logFileName $displayLogsOnConsole);
24 rodolico 11
 
12
 
13
our $VERSION = '0.1';
14
our $logFileName = '/tmp/zfs_utils.log'; # this can be overridden by the caller, and turned off with empty string
15
our $displayLogsOnConsole = 1;
27 rodolico 16
our $merge_stderr = 0; # if set to 1, stderr is captured in runCmd
24 rodolico 17
 
25 rodolico 18
# Execute a command and return its output.
19
# If called in scalar context, returns the full output as a single string.
20
# If called in list context, returns the output split into lines.
21
# If $merge_stderr is true (default), stderr is merged into stdout (only for scalar commands).
22
# returns empty string or empty list on failure and logs failure message.
23
sub runCmd {
27 rodolico 24
   my $cmd = \@_;
25 rodolico 25
   $merge_stderr = 1 unless defined $merge_stderr;
26
   my $output = '';
27
 
28
   if (ref $cmd eq 'ARRAY') {
29
      # Execute without a shell (safer). Note: stderr is not merged in this path.
27 rodolico 30
      logMsg( 'Running command [' . join ' ', @$cmd . ']');
25 rodolico 31
      open my $fh, '-|', @{$cmd} or do {
32
         logMsg("runCmd: failed to exec '@{$cmd}': $!");
33
         return wantarray ? () : '';
34
      };
35
      local $/ = undef;
36
      $output = <$fh>;
37
      close $fh;
38
   } else {
39
      # Scalar command runs via the shell; optionally merge stderr into stdout.
27 rodolico 40
      logMsg( "Scalar running command [$cmd]" );
25 rodolico 41
      my $c = $cmd;
42
      $c .= ' 2>&1' if $merge_stderr;
43
      $output = `$c`;
44
   }
45
 
46
   $output //= '';
47
 
48
   if (wantarray) {
49
      return $output eq '' ? () : split(/\n/, $output);
50
   } else {
51
      return $output;
52
   }
53
}
54
 
24 rodolico 55
# this calls gshred which will overwrite the file 3 times, then
56
# remove it.
57
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
58
# so assuming file is on something without COW (ramdisk, UFS, etc)
59
sub shredFile {
60
   my $filename = shift;
61
   `/usr/local/bin/gshred -u -f -s 32 $filename` if -e $filename;
62
}
63
 
64
sub logMsg {
65
    my $msg = shift;
66
    my $filename = shift // $logFileName;
67
    my $timeStampFormat = shift // '%Y-%m-%d %H:%M:%S';
68
    my $timestamp = strftime($timeStampFormat, localtime());
69
    if (defined $filename && $filename ne '' ) {
70
       open my $logfh, '>>', $filename or die "Could not open log file $filename: $!\n";
71
       print $logfh "$timestamp\t$msg\n";
72
       close $logfh;
73
    }
74
    print "$timestamp\t$msg\n" if ($displayLogsOnConsole);
75
}
76
 
77
# find a drive by it's label by scanning /dev/gpt/ for $timeout seconds.
78
# If the drive is found, mount it on mountPath and return the mountPath.
79
# If not found, return empty string.
80
sub mountDriveByLabel {
81
   my ($label, $mountPath, $timeout, $checkEvery ) = @_;
82
   unless ($label) {
83
      logMsg("mountDriveByLabel: No label provided");
84
      return '';
85
   }
86
   unless ( $label =~ /^[a-zA-Z0-9_\-]+$/ ) {
87
      logMsg("mountDriveByLabel: Invalid label '$label'");
88
      return '';
89
   }
90
 
91
   logMsg("mountDriveByLabel: Looking for drive with label '$label'");
92
   # default to /mnt/label if not provided
93
   $mountPath //= "/mnt/$label"; # this is where we'll mount it if we find it
94
   $label = "/dev/gpt/$label"; #  this is where FreeBSD puts gpt labeled drives
95
   # default to 10 minutes (600 seconds) if not provided
96
   $timeout //= 600;
97
   # default to checking every minute if not provided
98
   $checkEvery //= 60;
99
   # wait up to $timeout seconds for device to appear, checking every 10 seconds
100
   while ( $timeout > 0 ) {
101
      if ( -e "$label" ) {
102
         last;
103
      } else {
104
         sleep $checkEvery;
105
         $timeout -= $checkEvery;
106
      }
107
    }
108
    # if we found it, mount and return mount path
109
    if ( -e "$label" ) {
110
       # ensure mount point
111
       unless ( -d $mountPath || make_path($mountPath) ) {
112
         logMsg("Failed to create $mountPath: $!");
113
         return '';
114
       }
115
       # mount device (let mount detect filesystem)
116
       unless ( system('mount', $label, $mountPath) == 0 ) {
117
         logMsg("Failed to mount $label on $mountPath: $!");
118
         return '';
119
       }
120
       return $mountPath;
121
    } else {
122
       return '';
123
    }
124
}
125
 
126
## Load a YAML configuration file into a hashref.
127
## If the file does not exist, and a default hashref is provided,
128
## create the file by dumping the default to YAML, then return the default.
129
sub loadConfig {
130
    my ($filename, $default) = @_;
131
 
132
    # If no filename was provided, return default or empty hashref
133
    die "No filename provided to loadConfig\n" unless defined $filename;
134
 
135
    # If file doesn't exist but a default hashref was provided, try to
136
    # create the file by dumping the default to YAML, then return the default.
137
    unless (-e $filename) {
138
      logMsg("Config file $filename does not exist. Creating it with default values.");
139
      if ($default && ref $default eq 'HASH') {
140
         my $wrote = 0;
141
         eval {
142
               require YAML::XS;
143
               YAML::XS->import();
144
               YAML::XS::DumpFile($filename, $default);
145
               $wrote = 1;
146
               1;
147
         } or do {
148
               eval {
149
                  require YAML::Tiny;
150
                  YAML::Tiny->import();
151
                  my $yt = YAML::Tiny->new($default);
152
                  $yt->write($filename);
153
                  $wrote = 1;
154
                  1;
155
               } or do {
156
                  logMsg("No YAML writer available (YAML::XS or YAML::Tiny). Could not create $filename");
157
               };
158
         };
159
 
160
         die "Failed to write default config to $filename:$!\n" unless $wrote;
161
        }
162
 
163
        # No default provided; nothing to create
164
        return {};
165
    }
166
 
167
    my $yaml;
168
 
169
    # Try YAML::XS first, fall back to YAML::Tiny
170
    eval {
171
        require YAML::XS;
172
        YAML::XS->import();
173
        $yaml = YAML::XS::LoadFile($filename);
174
        logMsg("using YAML::XS to load $filename");
175
        1;
176
    } or do {
177
        eval {
178
            require YAML::Tiny;
179
            YAML::Tiny->import();
180
            $yaml = YAML::Tiny->read($filename);
181
            $yaml = $yaml->[0] if $yaml;  # YAML::Tiny returns an arrayref of documents
182
            logMsg("using YAML::Tiny to load $filename");
183
            1;
184
        } or do {
185
            logMsg("No YAML parser installed (YAML::XS or YAML::Tiny). Skipping config load from $filename");
186
            return ($default && ref $default eq 'HASH') ? $default : {};
187
        };
188
    };
189
    # Ensure we have a hashref
190
    die "Config file $filename did not produce a HASH.\n" unless (defined $yaml && ref $yaml eq 'HASH');
191
 
192
    return $yaml;
193
}
194
 
195
 
196
 
197
sub mountGeli {
198
   my $geliConfig = shift;
30 rodolico 199
   unless ( $geliConfig->{'localKey'} ) {
200
      logMsg "Could not find local key in configuration file\n";
24 rodolico 201
      return '';
202
   }
203
   # find the keyfile disk and mount it
204
   my $path = mountDriveByLabel( $geliConfig->{'keydiskname'} );
205
   unless ( $path ne '' and -e "$path/" . $geliConfig->{'keyfile'} ) {
206
      logMsg "Could not find or mount keyfile disk with label: " . $geliConfig->{'keydiskname'} . "\n";
207
      return '';
208
   }
209
   # create the combined geli keyfile in target location
210
   unless ( makeGeliKey( "$path/" . $geliConfig->{'keyfile'}, $geliConfig->{'localKey'}, $geliConfig->{'target'} ) ) {
211
         logMsg "Could not create geli keyfile\n";
212
         return '';
213
      }
214
   # decrypt and mount the geli disks and zfs pool
215
   my $poolname = decryptAndMountGeli( $geliConfig );
216
   return $poolname;
217
 
218
}
219
 
30 rodolico 220
# find all disks which are candidates for use with geli/zfs
221
# Grabs all disks on the system, then removes those with partitions
222
# and those already used in zpools.
223
sub findGeliDisks {
224
   logMsg("Finding available disks for GELI/ZFS use");
225
   # get all disks in system
226
   my %allDisks = map{ chomp $_ ; $_ => 1 } runCmd( "geom disk list | grep 'Geom name:' | rev | cut -d' ' -f1 | rev" );
227
   # get the disks with partitions
228
   my @temp = runCmd( "gpart show -p | grep '^=>'");  # -p prints just the disks without partitions
229
   # remove them from the list
230
   foreach my $disk ( @temp ) {
231
      $allDisks{$1} = 0 if ( $disk =~ m/^=>[\t\s0-9]+([a-z][a-z0-9]+)/ ) ;
232
   }
233
 
234
   # get disk which are currently used for zpools
235
   @temp = runCmd( "zpool status -LP | grep '/dev/'" );
236
   foreach my $disk ( @temp ) {
237
      $allDisks{$1} = 0 if  $disk =~ m|/dev/([a-z]+\d+)|;
238
   }
239
 
240
   # return only the disks which are free (value 1)
241
   return grep{ $allDisks{$_} == 1 } keys %allDisks;
242
}
243
 
24 rodolico 244
## Decrypt each GELI disk from $geliConfig->{'diskList'} using the keyfile,
245
## then import and mount the ZFS pool specified in $geliConfig->{'poolname'}.
246
##
247
## Returns the pool name on success, empty on error.
248
sub decryptAndMountGeli {
249
   my ($geliConfig) = @_;
30 rodolico 250
 
251
   # Can't continue at all if no pool name
24 rodolico 252
   die "No pool name specified in config\n" unless $geliConfig->{'poolname'};
30 rodolico 253
   # if no list of disks provided, try to find them
254
   $geliConfig->{'diskList'} //= findGeliDisks();
255
 
24 rodolico 256
   my $diskList = $geliConfig->{'diskList'};
257
   my $poolname = $geliConfig->{'poolname'};
258
   my $keyfile = $geliConfig->{'target'};
259
   unless ( -e $keyfile ) {
260
      logMsg "GELI keyfile $keyfile does not exist\n";
261
      return '';
262
   }
263
 
264
   my @decrypted_devices;
265
 
266
   # Decrypt each disk in the list
30 rodolico 267
   foreach my $disk (@{$geliConfig->{'diskList'}}) {
24 rodolico 268
      unless ( -e $disk ) {
269
         logMsg "Disk $disk does not exist\n";
270
         return '';
271
      }
272
 
273
      # Derive the decrypted device name (.eli suffix on FreeBSD)
274
      my $decrypted = $disk . '.eli';
275
 
276
      # Decrypt using geli attach with the keyfile
277
      logMsg("Decrypting $disk with keyfile $keyfile");
30 rodolico 278
      if ( my $result = system('geli', 'attach', '-k', $geliConfig->{'target'}, $disk) == 0 ) {
24 rodolico 279
         logMsg "Failed to decrypt $disk (exit $result)\n";
30 rodolico 280
         next; # ignore failed disks and continue to see if we can import the pool
24 rodolico 281
      }
282
 
283
      unless ( -e $decrypted ) {
284
         logMsg "Decrypted device $decrypted does not exist after geli attach\n";
285
         return '';
286
      }
287
      push @decrypted_devices, $decrypted;
288
   }
289
 
290
   # Import the ZFS pool
291
   logMsg("Importing ZFS pool $poolname");
292
   my @import_cmd = ('zpool', 'import');
293
   # If decrypted devices exist, add their directories to -d list
30 rodolico 294
   #foreach my $dev (@decrypted_devices) {
295
   #   my $dir = $dev;
296
   #   $dir =~ s!/[^/]+$!!;  # Remove filename to get directory
297
   #   push @import_cmd, '-d', $dir;
298
   #}
299
 
24 rodolico 300
   push @import_cmd, $poolname;
301
 
302
   my $result = system(@import_cmd);
303
   unless ( $result == 0 ) {
304
      logMsg("Failed to import zfs pool $poolname (exit $result)\n");
305
      return '';
306
   }
307
 
308
   # Mount the ZFS pool (zfs mount -a mounts all filesystems in the pool)
309
   logMsg("Mounting ZFS pool $poolname");
310
   $result = system('zfs', 'mount', '-a');
311
   unless ( $result == 0 ) {
312
      logMsg("Failed to mount zfs pool $poolname (exit $result)\n");
313
      return '';
314
   }
315
 
316
   logMsg("Successfully decrypted and mounted pool $poolname");
317
   return $poolname;
318
}
319
 
320
## Create a GELI key by XOR'ing a remote binary keyfile and a local key (hex string).
321
##
322
## Arguments:
323
##   $remote_keyfile - path to binary keyfile (32 bytes)
324
##   $localKeyHexOrPath - hex string (64 hex chars) or path to file containing hex
325
##   $target - path to write the resulting 32-byte binary key
326
##
327
## Returns true on success, dies on fatal error.
328
sub makeGeliKey {
329
   my ($remote_keyfile, $localKeyHexOrPath, $target) = @_;
330
 
331
   die "remote keyfile not provided" unless defined $remote_keyfile;
332
   die "local key not provided" unless defined $localKeyHexOrPath;
333
   die "target not provided" unless defined $target;
334
 
335
   die "Remote keyfile $remote_keyfile does not exist\n" unless -e $remote_keyfile;
336
 
337
   # Read remote binary key
338
   open my $rh, '<:raw', $remote_keyfile or die "Unable to open $remote_keyfile: $!\n";
339
   my $rbuf;
340
   my $read = read($rh, $rbuf, 32);
341
   close $rh;
342
   die "Failed to read 32 bytes from $remote_keyfile (got $read)\n" unless defined $read && $read == 32;
343
 
344
   # Get local hex string (either direct string or file contents)
345
   my $hex;
346
   if (-e $localKeyHexOrPath) {
347
      open my $lh, '<', $localKeyHexOrPath or die "Unable to open local key file $localKeyHexOrPath: $!\n";
348
      local $/ = undef;
349
      $hex = <$lh>;
350
      close $lh;
351
   } else {
352
      $hex = $localKeyHexOrPath;
353
   }
354
   # clean hex (remove whitespace/newlines and optional 0x)
355
   $hex =~ s/0x//g;
356
   $hex =~ s/[^0-9a-fA-F]//g;
357
 
358
   die "Local key must be 64 hex characters (256-bit)\n" unless length($hex) == 64;
359
 
360
   my $lbuf = pack('H*', $hex);
361
   die "Local key decoded to unexpected length " . length($lbuf) . "\n" unless length($lbuf) == 32;
362
 
363
   # XOR the two buffers
364
   my $out = '';
365
   for my $i (0 .. 31) {
366
      $out .= chr( ord(substr($rbuf, $i, 1)) ^ ord(substr($lbuf, $i, 1)) );
367
   }
368
 
369
   # Ensure target directory exists
370
   my ($vol, $dirs, $file) = ($target =~ m{^(/?)(.*/)?([^/]+)$});
371
   if ($dirs) {
372
      my $dir = $dirs;
373
      $dir =~ s{/$}{};
374
      unless (-d $dir) {
375
         require File::Path;
376
         File::Path::make_path($dir) or die "Failed to create directory $dir: $!\n";
377
      }
378
   }
379
 
380
   # Write out binary key and protect permissions
381
   open my $oh, '>:raw', $target or die "Unable to open $target for writing: $!\n";
382
   print $oh $out or die "Failed to write to $target: $!\n";
383
   close $oh;
384
   chmod 0600, $target;
385
 
386
   return 1;
387
}
388
 
25 rodolico 389
sub makeReplicateCommands {
390
   my ($sourceSnapsRef, $statusRef, $newStatusRef) = @_;
391
   $sourceSnapsRef ||= [];
392
   $statusRef     ||= [];
393
   $newStatusRef  ||= [];
394
 
395
   # parse snapshots: each line is expected to have snapshot fullname as first token: pool/fs@snap ...
396
   my %snaps_by_fs;
397
   foreach my $line (@$sourceSnapsRef) {
398
      next unless defined $line && $line =~ /\S/;
399
      my ($tok) = split /\s+/, $line;
400
      next unless $tok && $tok =~ /@/;
401
      my ($fs, $snap) = split /@/, $tok, 2;
402
      push @{ $snaps_by_fs{$fs} }, $snap;
403
   }
404
 
405
   # nothing to do
406
   return [] unless keys %snaps_by_fs;
407
 
408
   # figure root filesystem: first snapshot line's fs is the requested root
409
   my ($first_line) = grep { defined $_ && $_ =~ /\S/ } @$sourceSnapsRef;
410
   my ($root_fs) = $first_line ? (split(/\s+/, $first_line))[0] =~ /@/ ? (split(/@/, (split(/\s+/, $first_line))[0]))[0] : undef : undef;
411
   $root_fs ||= (sort keys %snaps_by_fs)[0];
412
 
413
   # helper: find last status entry for a filesystem (status lines contain full snapshot names pool/fs@snap)
414
   my %last_status_for;
415
   for my $s (@$statusRef) {
416
      next unless $s && $s =~ /@/;
417
      my ($fs, $snap) = split /@/, $s, 2;
418
      $last_status_for{$fs} = $snap;    # later entries override earlier ones -> last occurrence kept
419
   }
420
 
421
   # build per-filesystem "from" and "to"
422
   my %from_for;
423
   my %to_for;
424
   foreach my $fs (keys %snaps_by_fs) {
425
      my $arr = $snaps_by_fs{$fs};
426
      next unless @$arr;
427
      $to_for{$fs} = $arr->[-1];
428
      $from_for{$fs} = $last_status_for{$fs};    # may be undef -> full send required
429
   }
430
 
431
   # decide if we can do a single recursive send:
432
   # condition: all 'to' snapshot names are identical
433
   my %to_names = map { $_ => 1 } values %to_for;
434
   my $single_to_name = (keys %to_names == 1) ? (keys %to_names)[0] : undef;
435
 
436
   my @commands;
437
 
438
   if ($single_to_name) {
439
      # check whether any from is missing
440
      my @from_values = map { $from_for{$_} } sort keys %from_for;
441
      my $any_from_missing = grep { !defined $_ } @from_values;
442
      my %from_names = map { $_ => 1 } grep { defined $_ } @from_values;
443
      my $single_from_name = (keys %from_names == 1) ? (keys %from_names)[0] : undef;
444
 
445
      if ($any_from_missing) {
446
         # full recursive send from root
447
         push @commands, sprintf('zfs send -R %s@%s', $root_fs, $single_to_name);
448
      }
449
      elsif ($single_from_name) {
450
         # incremental recursive send
451
         push @commands, sprintf('zfs send -R -I %s@%s %s@%s',
452
                           $root_fs, $single_from_name, $root_fs, $single_to_name);
453
      }
454
      else {
455
         # from snapshots differ across children -> fall back to per-filesystem sends
456
         foreach my $fs (sort keys %to_for) {
457
            my $to  = $to_for{$fs};
458
            my $from = $from_for{$fs};
459
            if ($from) {
460
               push @commands, sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to);
461
            } else {
462
               push @commands, sprintf('zfs send %s@%s', $fs, $to);
463
            }
464
         }
465
      }
466
 
467
      # update new status: record newest snap for every filesystem
468
      foreach my $fs (keys %to_for) {
469
         push @$newStatusRef, sprintf('%s@%s', $fs, $to_for{$fs});
470
      }
471
   } else {
472
      # not all children share same newest snap -> per-filesystem sends
473
      foreach my $fs (sort keys %to_for) {
474
         my $to  = $to_for{$fs};
475
         my $from = $from_for{$fs};
476
         if ($from) {
477
            push @commands, sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to);
478
         } else {
479
            push @commands, sprintf('zfs send %s@%s', $fs, $to);
480
         }
481
         push @$newStatusRef, sprintf('%s@%s', $fs, $to);
482
      }
483
   }
484
 
485
   # return arrayref of commands (caller can iterate or join with pipes)
486
   return \@commands;
487
}
488
 
489
 
24 rodolico 490
1;