Subversion Repositories zfs_utils

Rev

Rev 25 | Rev 30 | 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;
199
   unless ( -e $geliConfig->{'localKey'} ) {
200
      logMsg "Could not find local key file: " . $geliConfig->{'localKey'} . "\n";
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
 
220
## Decrypt each GELI disk from $geliConfig->{'diskList'} using the keyfile,
221
## then import and mount the ZFS pool specified in $geliConfig->{'poolname'}.
222
##
223
## Returns the pool name on success, empty on error.
224
sub decryptAndMountGeli {
225
   my ($geliConfig) = @_;
226
   # these are configuration sanity checks, so die if they fail
227
   die "No disk list found in GELI config\n" unless $geliConfig->{'diskList'};
228
   die "No pool name specified in config\n" unless $geliConfig->{'poolname'};
229
 
230
   my $diskList = $geliConfig->{'diskList'};
231
   my $poolname = $geliConfig->{'poolname'};
232
   my $keyfile = $geliConfig->{'target'};
233
   unless ( -e $keyfile ) {
234
      logMsg "GELI keyfile $keyfile does not exist\n";
235
      return '';
236
   }
237
 
238
   my @decrypted_devices;
239
 
240
   # Decrypt each disk in the list
241
   foreach my $disk (@{$diskList}) {
242
      unless ( -e $disk ) {
243
         logMsg "Disk $disk does not exist\n";
244
         return '';
245
      }
246
 
247
      # Derive the decrypted device name (.eli suffix on FreeBSD)
248
      my $decrypted = $disk . '.eli';
249
 
250
      # Decrypt using geli attach with the keyfile
251
      logMsg("Decrypting $disk with keyfile $keyfile");
252
      if ( my $result = system('geli', 'attach', '-k', $keyfile, $disk) == 0 ) {
253
         logMsg "Failed to decrypt $disk (exit $result)\n";
254
         return '';
255
      }
256
 
257
      unless ( -e $decrypted ) {
258
         logMsg "Decrypted device $decrypted does not exist after geli attach\n";
259
         return '';
260
      }
261
      push @decrypted_devices, $decrypted;
262
   }
263
 
264
   # Import the ZFS pool
265
   logMsg("Importing ZFS pool $poolname");
266
   my @import_cmd = ('zpool', 'import');
267
   # If decrypted devices exist, add their directories to -d list
268
   foreach my $dev (@decrypted_devices) {
269
      my $dir = $dev;
270
      $dir =~ s!/[^/]+$!!;  # Remove filename to get directory
271
      push @import_cmd, '-d', $dir;
272
   }
273
   push @import_cmd, $poolname;
274
 
275
   my $result = system(@import_cmd);
276
   unless ( $result == 0 ) {
277
      logMsg("Failed to import zfs pool $poolname (exit $result)\n");
278
      return '';
279
   }
280
 
281
   # Mount the ZFS pool (zfs mount -a mounts all filesystems in the pool)
282
   logMsg("Mounting ZFS pool $poolname");
283
   $result = system('zfs', 'mount', '-a');
284
   unless ( $result == 0 ) {
285
      logMsg("Failed to mount zfs pool $poolname (exit $result)\n");
286
      return '';
287
   }
288
 
289
   logMsg("Successfully decrypted and mounted pool $poolname");
290
   return $poolname;
291
}
292
 
293
## Create a GELI key by XOR'ing a remote binary keyfile and a local key (hex string).
294
##
295
## Arguments:
296
##   $remote_keyfile - path to binary keyfile (32 bytes)
297
##   $localKeyHexOrPath - hex string (64 hex chars) or path to file containing hex
298
##   $target - path to write the resulting 32-byte binary key
299
##
300
## Returns true on success, dies on fatal error.
301
sub makeGeliKey {
302
   my ($remote_keyfile, $localKeyHexOrPath, $target) = @_;
303
 
304
   die "remote keyfile not provided" unless defined $remote_keyfile;
305
   die "local key not provided" unless defined $localKeyHexOrPath;
306
   die "target not provided" unless defined $target;
307
 
308
   die "Remote keyfile $remote_keyfile does not exist\n" unless -e $remote_keyfile;
309
 
310
   # Read remote binary key
311
   open my $rh, '<:raw', $remote_keyfile or die "Unable to open $remote_keyfile: $!\n";
312
   my $rbuf;
313
   my $read = read($rh, $rbuf, 32);
314
   close $rh;
315
   die "Failed to read 32 bytes from $remote_keyfile (got $read)\n" unless defined $read && $read == 32;
316
 
317
   # Get local hex string (either direct string or file contents)
318
   my $hex;
319
   if (-e $localKeyHexOrPath) {
320
      open my $lh, '<', $localKeyHexOrPath or die "Unable to open local key file $localKeyHexOrPath: $!\n";
321
      local $/ = undef;
322
      $hex = <$lh>;
323
      close $lh;
324
   } else {
325
      $hex = $localKeyHexOrPath;
326
   }
327
   # clean hex (remove whitespace/newlines and optional 0x)
328
   $hex =~ s/0x//g;
329
   $hex =~ s/[^0-9a-fA-F]//g;
330
 
331
   die "Local key must be 64 hex characters (256-bit)\n" unless length($hex) == 64;
332
 
333
   my $lbuf = pack('H*', $hex);
334
   die "Local key decoded to unexpected length " . length($lbuf) . "\n" unless length($lbuf) == 32;
335
 
336
   # XOR the two buffers
337
   my $out = '';
338
   for my $i (0 .. 31) {
339
      $out .= chr( ord(substr($rbuf, $i, 1)) ^ ord(substr($lbuf, $i, 1)) );
340
   }
341
 
342
   # Ensure target directory exists
343
   my ($vol, $dirs, $file) = ($target =~ m{^(/?)(.*/)?([^/]+)$});
344
   if ($dirs) {
345
      my $dir = $dirs;
346
      $dir =~ s{/$}{};
347
      unless (-d $dir) {
348
         require File::Path;
349
         File::Path::make_path($dir) or die "Failed to create directory $dir: $!\n";
350
      }
351
   }
352
 
353
   # Write out binary key and protect permissions
354
   open my $oh, '>:raw', $target or die "Unable to open $target for writing: $!\n";
355
   print $oh $out or die "Failed to write to $target: $!\n";
356
   close $oh;
357
   chmod 0600, $target;
358
 
359
   return 1;
360
}
361
 
25 rodolico 362
sub makeReplicateCommands {
363
   my ($sourceSnapsRef, $statusRef, $newStatusRef) = @_;
364
   $sourceSnapsRef ||= [];
365
   $statusRef     ||= [];
366
   $newStatusRef  ||= [];
367
 
368
   # parse snapshots: each line is expected to have snapshot fullname as first token: pool/fs@snap ...
369
   my %snaps_by_fs;
370
   foreach my $line (@$sourceSnapsRef) {
371
      next unless defined $line && $line =~ /\S/;
372
      my ($tok) = split /\s+/, $line;
373
      next unless $tok && $tok =~ /@/;
374
      my ($fs, $snap) = split /@/, $tok, 2;
375
      push @{ $snaps_by_fs{$fs} }, $snap;
376
   }
377
 
378
   # nothing to do
379
   return [] unless keys %snaps_by_fs;
380
 
381
   # figure root filesystem: first snapshot line's fs is the requested root
382
   my ($first_line) = grep { defined $_ && $_ =~ /\S/ } @$sourceSnapsRef;
383
   my ($root_fs) = $first_line ? (split(/\s+/, $first_line))[0] =~ /@/ ? (split(/@/, (split(/\s+/, $first_line))[0]))[0] : undef : undef;
384
   $root_fs ||= (sort keys %snaps_by_fs)[0];
385
 
386
   # helper: find last status entry for a filesystem (status lines contain full snapshot names pool/fs@snap)
387
   my %last_status_for;
388
   for my $s (@$statusRef) {
389
      next unless $s && $s =~ /@/;
390
      my ($fs, $snap) = split /@/, $s, 2;
391
      $last_status_for{$fs} = $snap;    # later entries override earlier ones -> last occurrence kept
392
   }
393
 
394
   # build per-filesystem "from" and "to"
395
   my %from_for;
396
   my %to_for;
397
   foreach my $fs (keys %snaps_by_fs) {
398
      my $arr = $snaps_by_fs{$fs};
399
      next unless @$arr;
400
      $to_for{$fs} = $arr->[-1];
401
      $from_for{$fs} = $last_status_for{$fs};    # may be undef -> full send required
402
   }
403
 
404
   # decide if we can do a single recursive send:
405
   # condition: all 'to' snapshot names are identical
406
   my %to_names = map { $_ => 1 } values %to_for;
407
   my $single_to_name = (keys %to_names == 1) ? (keys %to_names)[0] : undef;
408
 
409
   my @commands;
410
 
411
   if ($single_to_name) {
412
      # check whether any from is missing
413
      my @from_values = map { $from_for{$_} } sort keys %from_for;
414
      my $any_from_missing = grep { !defined $_ } @from_values;
415
      my %from_names = map { $_ => 1 } grep { defined $_ } @from_values;
416
      my $single_from_name = (keys %from_names == 1) ? (keys %from_names)[0] : undef;
417
 
418
      if ($any_from_missing) {
419
         # full recursive send from root
420
         push @commands, sprintf('zfs send -R %s@%s', $root_fs, $single_to_name);
421
      }
422
      elsif ($single_from_name) {
423
         # incremental recursive send
424
         push @commands, sprintf('zfs send -R -I %s@%s %s@%s',
425
                           $root_fs, $single_from_name, $root_fs, $single_to_name);
426
      }
427
      else {
428
         # from snapshots differ across children -> fall back to per-filesystem sends
429
         foreach my $fs (sort keys %to_for) {
430
            my $to  = $to_for{$fs};
431
            my $from = $from_for{$fs};
432
            if ($from) {
433
               push @commands, sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to);
434
            } else {
435
               push @commands, sprintf('zfs send %s@%s', $fs, $to);
436
            }
437
         }
438
      }
439
 
440
      # update new status: record newest snap for every filesystem
441
      foreach my $fs (keys %to_for) {
442
         push @$newStatusRef, sprintf('%s@%s', $fs, $to_for{$fs});
443
      }
444
   } else {
445
      # not all children share same newest snap -> per-filesystem sends
446
      foreach my $fs (sort keys %to_for) {
447
         my $to  = $to_for{$fs};
448
         my $from = $from_for{$fs};
449
         if ($from) {
450
            push @commands, sprintf('zfs send -I %s@%s %s@%s', $fs, $from, $fs, $to);
451
         } else {
452
            push @commands, sprintf('zfs send %s@%s', $fs, $to);
453
         }
454
         push @$newStatusRef, sprintf('%s@%s', $fs, $to);
455
      }
456
   }
457
 
458
   # return arrayref of commands (caller can iterate or join with pipes)
459
   return \@commands;
460
}
461
 
462
 
24 rodolico 463
1;