Subversion Repositories zfs_utils

Rev

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