Subversion Repositories zfs_utils

Rev

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

Rev Author Line No. Line
24 rodolico 1
#! /usr/bin/env perl
2
 
34 rodolico 3
# Simplified BSD License (FreeBSD License)
4
#
5
# Copyright (c) 2025, Daily Data Inc.
6
# All rights reserved.
7
#
8
# Redistribution and use in source and binary forms, with or without
9
# modification, are permitted provided that the following conditions are met:
10
#
11
# 1. Redistributions of source code must retain the above copyright notice, this
12
#    list of conditions and the following disclaimer.
13
#
14
# 2. Redistributions in binary form must reproduce the above copyright notice,
15
#    this list of conditions and the following disclaimer in the documentation
16
#    and/or other materials provided with the distribution.
17
#
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 
29
# sneakernet.pl
30
# Script to perform sneakernet replication of ZFS datasets between two servers
31
# using an external transport drive.
32
# Uses ZFS send/receive to replicate datasets to/from the transport drive.
33
# Optionally uses symmetric encryption to encrypt datasets during transport.
34
# On the target server, can optionally use GELI to encrypt the datasets on disk.
35
# Requires a configuration file in YAML format next to the script.
36
# Author: R. W. Rodlico <rodo@dailydata.net>
37
# Created: December 2025
48 rodolico 38
#
34 rodolico 39
# Revision History:
48 rodolico 40
# Version: 0.1 RWR 2025-12-10
41
# Development version
42
#
43
# Version: 1.0 RWR 2025-12-15
44
# Tested and ready for initial release
51 rodolico 45
#
46
# Version: 1.0.1 RWR 2025-12-15
47
# Added verbose logging control to logMsg calls, controlled by ZFS_Utils::$verboseLoggingLevel
34 rodolico 48
 
48 rodolico 49
 
24 rodolico 50
use strict;
51
use warnings;
52
 
51 rodolico 53
our $VERSION = '1.0.1';
34 rodolico 54
 
46 rodolico 55
use File::Basename;
24 rodolico 56
use FindBin;
57
use lib "$FindBin::Bin/..";
27 rodolico 58
use Data::Dumper;
51 rodolico 59
use ZFS_Utils qw(loadConfig shredFile logMsg makeReplicateCommands mountDriveByLabel unmountDriveByLabel mountGeli runCmd sendReport fatalError getDirectoryList cleanDirectory $logFileName $displayLogsOnConsole $verboseLoggingLevel);
44 rodolico 60
use Getopt::Long qw(GetOptions);
61
Getopt::Long::Configure ("bundling");
24 rodolico 62
 
35 rodolico 63
my $scriptDirectory = $FindBin::RealBin;
64
my $scriptFullPath = "$scriptDirectory/" . $FindBin::Script;
65
 
24 rodolico 66
# display all log messages on console in addition to the log file
67
$displayLogsOnConsole = 1;
68
 
35 rodolico 69
my $configFileName = "$scriptFullPath.conf.yaml";
24 rodolico 70
 
71
my $config = {
44 rodolico 72
   'dryrun' => 0,
73
   'verbosity' => 1,
24 rodolico 74
   # file created on source server to track last copyed dataset
35 rodolico 75
   'status_file' => "$scriptFullPath.status",
76
   'log_file' => "$scriptFullPath.log",
24 rodolico 77
   #information about source server
37 rodolico 78
   'source' => {
24 rodolico 79
      'hostname' => '', # used to see if we are on source
34 rodolico 80
      'poolname' => 'pool', # name of the ZFS pool to export
81
      # if set, will generate a report via email or by storing on a drive
82
      'report' => {
83
         'email' => 'tech@example.org',
84
         'subject' => 'AG Transport Report',
85
         'targetDrive' => {
35 rodolico 86
            'fstype' => '', # filesystem type of the report drive
87
            # How often to check for the disk (seconds), message displayed every interval
88
            'check_interval' => 15,
34 rodolico 89
            'label' => '',
90
            'mount_point' => '',
91
         }
92
      }
24 rodolico 93
   },
94
   #information about target server
37 rodolico 95
   'target' => {
24 rodolico 96
      'hostname' => '', # used to see if we are on target
34 rodolico 97
      'poolname' => 'backup', # name of the ZFS pool to import
42 rodolico 98
      'shutdown_after_replication' => 0, # if set to 1, will shutdown the server after replication
24 rodolico 99
      # if this is set, the dataset uses GELI, so we must decrypt and
100
      # mount it first
101
      'geli' => {
35 rodolico 102
         'secureKey ' => {
103
            'label' => 'replica', # the GPT label of the key disk
104
            'fstype' => 'ufs', # filesystem type of the key disk
105
            'check_interval' => 15,
106
            'wait_timeout' => 300,
107
            'keyfile' => 'geli.key', # the name of the key file on the secureKey disk
108
         },
24 rodolico 109
         'localKey' => 'e98c660cccdae1226550484d62caa2b72f60632ae0c607528aba1ac9e7bfbc9c', # hex representation of the local key part
110
         'target' => '/media/geli.key', # location to create the combined keyfile
34 rodolico 111
         'poolname' => 'backup', # name of the ZFS pool to import
24 rodolico 112
         'diskList' => [ 
34 rodolico 113
            'da0',
114
            'da1'
24 rodolico 115
            ], # list of disks to try to mount the dataset from
34 rodolico 116
      },
117
      'report' => {
118
         'email' => '',
119
         'subject' => '',
120
         'targetDrive' => {
35 rodolico 121
            'fstype' => 'msdos', # filesystem type of the report drive
122
            'label' => 'sneakernet',
123
            'mount_point' => '',
34 rodolico 124
         }
24 rodolico 125
      }
126
   },
127
   'transport' => {
128
      # this is the GPT label of the sneakernet disk
37 rodolico 129
      'label' => 'sneakernet',
35 rodolico 130
      # this is the file system type. Not needed if ufs
131
      'fstype' => 'ufs',
24 rodolico 132
      # where we want to mount it
133
      'mount_point' => '/mnt/sneakernet',
134
      # amount of time to wait for the disk to appear
135
      'timeout' => 600,
35 rodolico 136
      # How often to check for the disk (seconds), message displayed every interval
137
      'check_interval' => 15,
24 rodolico 138
      # if set, all files will be encrypted with this key/IV during transport
139
      'encryption' => {
140
         'key'    => '', # openssl rand 32 | xxd -p | tr -d '\n' > test.key
141
         'IV'     => '00000000000000000000000000000000',
142
      },
143
   },
144
   'datasets' => {
34 rodolico 145
      'dataset1' => {
42 rodolico 146
         'source' => 'pool', # the parent of the dataset on the source
147
         'target' => 'backup', # the parent of the dataset on the target
148
         'dataset' => 'dataset1', # the dataset name
24 rodolico 149
      },
150
      'files_share'  => {
42 rodolico 151
         'source' => 'pool',
152
         'target' => 'backup',
43 rodolico 153
         'dataset' => 'files_share',
24 rodolico 154
      },
155
   }
156
};
157
 
48 rodolico 158
## Read the status file and return its lines as an ARRAYREF.
159
##
160
## Arguments:
161
##   $filename - path to the status file (string)
162
##
163
## Behavior:
164
##   - If the file exists and is readable, reads all lines, chomps newlines and returns an ARRAYREF
165
##     containing the lines (each line generally holds a fully qualified snapshot name).
166
##   - If the file does not exist or cannot be opened, logs a message and returns an empty ARRAYREF.
167
##
168
## Returns: ARRAYREF of lines (possibly empty).
30 rodolico 169
sub getStatusFile {
170
   my $filename = shift;
171
   # read in history/status file
34 rodolico 172
   my @lines = ();
30 rodolico 173
   if ( -e $filename && open my $fh, '<', $filename ) {
174
      chomp( @lines = <$fh> );
175
      close $fh;
51 rodolico 176
      logMsg("Read status file '$filename' with contents:\n" . join( "\n", @lines ) . "\n") if $verboseLoggingLevel >= 3;
30 rodolico 177
   } else {
51 rodolico 178
      logMsg("Error: could not read status file '$filename', assuming a fresh start: $!") if $verboseLoggingLevel >= 2;
30 rodolico 179
   }
180
   return \@lines;
181
}
24 rodolico 182
 
48 rodolico 183
## Write the status list to disk safely.
184
##
185
## Arguments:
186
##   $filename   - path to the status file to write
187
##   $statusList - ARRAYREF of lines to write into the file
188
##
189
## Behavior:
190
##   - If an existing file is present, renames it to `$filename.bak` as a simple backup.
191
##   - Writes the provided lines to `$filename` (one per line).
192
##   - Logs the written contents. Dies on failure to backup or write the file.
30 rodolico 193
sub writeStatusFile {
194
   my ( $filename, $statusList ) = @_;
195
   # backup existing status file
196
   if ( -e $filename ) {
51 rodolico 197
      rename( $filename, "$filename.bak" ) 
198
         or fatalError("Error: could not backup existing status file '$filename': $!");
30 rodolico 199
   }
200
   # write new status file
201
   if ( open my $fh, '>', $filename ) {
202
      foreach my $line ( @$statusList ) {
203
         print $fh "$line\n";
204
      }
205
      close $fh;
51 rodolico 206
      logMsg("Wrote status file '$filename' with contents:\n" . join( "\n", @$statusList ) . "\n") if $verboseLoggingLevel >= 3;
30 rodolico 207
   } else {
51 rodolico 208
      fatalError("Error: could not write status file '$filename': $!");
30 rodolico 209
   }
210
}
211
 
48 rodolico 212
## Convert a path-like dataset name into a filename-safe string.
213
##
214
## Examples:
215
##   'pool/fs/sub' => 'pool.fs.sub' (default)
216
##
217
## Arguments:
218
##   $string       - input string to convert
219
##   $delimiter    - input delimiter to split on (default: '/')
220
##   $substitution - output separator to join with (default: '.')
221
##
222
## Returns: a joined string suitable for use as a filename.
46 rodolico 223
sub dirnameToFileName {
224
   my ( $string, $delimiter, $substitution ) = @_;
225
   $delimiter //= '/';
226
   $substitution //= '.';
227
   my @parts = split( /\Q$delimiter\E/, $string );
228
   return join( $substitution, @parts );
31 rodolico 229
}
230
 
48 rodolico 231
## Perform replication for all configured datasets on the source server.
232
##
233
## Arguments:
234
##   $config     - configuration HASHREF (loaded from YAML). Must contain `datasets` and `transport` entries.
235
##   $statusList - ARRAYREF of previously replicated snapshot full names (used to compute incremental sends)
236
##
237
## Behavior:
238
##   - Iterates over datasets defined in `$config->{datasets}`.
239
##   - For each dataset, enumerates available snapshots on the source and calls
240
##     `makeReplicateCommands` to produce zfs send commands.
241
##   - Commands are optionally piped through `openssl enc` when `transport.encryption.key` is set.
242
##   - The output is written to files on the transport mount point (one file per dataset snapshot set).
243
##   - Respects `$config->{dryrun}`: no commands are executed when dryrun is enabled.
244
##
245
## Returns: ARRAYREF `$newStatus` containing updated status lines (latest snapshots per dataset).
30 rodolico 246
sub doSourceReplication {
247
   my ($config, $statusList) = @_;
248
   my $newStatus = [];
249
   foreach my $dataset ( sort keys %{$config->{datasets}} ) {
51 rodolico 250
      logMsg("Processing dataset '$dataset'") if $verboseLoggingLevel >= 1;
31 rodolico 251
      # get list of all snapshots on dataset
44 rodolico 252
      my $sourceList;
253
      if ( -e "$scriptDirectory/test.status") {
254
         $sourceList = getStatusFile( "$scriptDirectory/test.status" );
255
      } else {
46 rodolico 256
         $sourceList = [ runCmd( "zfs list -rt snap -H -o name $config->{datasets}->{$dataset}->{source}" ) ];
44 rodolico 257
      }
258
 
30 rodolico 259
      # process dataset here
44 rodolico 260
      my $commands = makeReplicateCommands( 
261
                        $sourceList,
262
                        $statusList,
263
                        $dataset,
264
                        $config->{datasets}->{$dataset}->{source},
265
                        $config->{datasets}->{$dataset}->{target},
266
                        $newStatus
267
                     );
31 rodolico 268
      if ( %$commands ) {
269
         foreach my $cmd ( keys %$commands ) {
270
            my $command = $commands->{$cmd};
43 rodolico 271
            my $outputFile = $cmd;
48 rodolico 272
            my $outfile = dirnameToFileName( $cmd );
45 rodolico 273
            $command .= " | openssl enc -aes-256-cbc -K $config->{transport}->{encryption}->{key} -iv $config->{transport}->{encryption}->{IV} " if $config->{transport}->{encryption}->{key};
48 rodolico 274
            $command .= " > $config->{transport}->{mount_point}/$outfile";
51 rodolico 275
            logMsg("Running command: $command") if $verboseLoggingLevel >= 2;
44 rodolico 276
            runCmd(  $command  ) unless $config->{dryrun};
31 rodolico 277
         }
278
      } else {
51 rodolico 279
         logMsg( "Nothing to do for $dataset" ) if $verboseLoggingLevel >= 1;
30 rodolico 280
      }
281
   }
282
   return $newStatus;
283
}
284
 
48 rodolico 285
## Perform cleanup and final reporting after replication.
286
##
287
## Arguments:
288
##   $config  - configuration HASHREF (required)
289
##   $message - OPTIONAL message to include in the report
290
##
291
## Behavior:
292
##   - Logs disk usage for the transport mount and zpool list for diagnostics.
293
##   - Ensures the report subject and message are populated, then attempts to unmount
294
##     the transport drive and send the report (via `sendReport`).
295
##   - If `shutdown_after_replication` is set in the running role's config, attempts
296
##     to shut down the machine (honors `$config->{dryrun}`).
42 rodolico 297
sub cleanup{
298
   my ( $config, $message ) = @_;
299
   # add disk space utilization information on transport to the log
51 rodolico 300
   logMsg( "Disk space utilization on transport disk:\n" . runCmd( "df -h $config->{transport}->{mount_point}" ) . "\n" )
301
      if $verboseLoggingLevel >= 1;
42 rodolico 302
   # add information about the server (zpools) to the log
303
   my $servername = `hostname -s`;
304
   chomp $servername;
51 rodolico 305
   logMsg( "Zpools on server $servername:\n" . join( "\n", runCmd( "zpool list" ) ) . "\n" ) if $verboseLoggingLevel >= 1;
42 rodolico 306
   $config->{$config->{runningAs}}->{report}->{subject} //= "Replication Report for $config->{runningAs} server $servername";
307
   $message //= "Replication completed on $config->{runningAs} server $servername.";
308
   # unmount the sneakernet drive
44 rodolico 309
   unmountDriveByLabel( $config->{transport} ) unless $config->{dryrun};
42 rodolico 310
   sendReport( $config->{$config->{runningAs}}->{report}, $message, $config->{log_file} );
311
   # If they have requested shutdown, do it now
312
   if ( $config->{$config->{runningAs}}->{shutdown_after_replication} ) {
51 rodolico 313
      logMsg( "Shutting down target server as per configuration" ) if $verboseLoggingLevel >= 0;
44 rodolico 314
      runCmd( "shutdown -p now" ) unless $config->{dryrun};
33 rodolico 315
   }
42 rodolico 316
}
33 rodolico 317
 
48 rodolico 318
## Update the target zfs datasets from files on the transport drive.
319
##
320
## Arguments:
321
##   $config - configuration HASHREF containing `transport` and `datasets` entries.
322
##
323
## Behavior:
324
##   - Reads all regular files from the transport mount point (via `getDirectoryList`).
325
##   - For each file, determines the intended target dataset based on the filename and
326
##     the `datasets` mapping in the config, optionally decrypts via `openssl enc -d`,
327
##     and pipes the stream into `zfs receive -F` to update the target dataset.
328
##   - Uses `runCmd` to execute the receive commands and logs the executed command string.
42 rodolico 329
sub updateTarget {
330
   my $config = shift;
331
   my $files = getDirectoryList( $config->{transport}->{mount_point});
332
   foreach my $filename ( @$files ) {
46 rodolico 333
      my $targetDataset = basename( $filename );
334
      my ($dataset) = split( /\Q\.\E/, $targetDataset ); # grab only the first element of a string which has internal delimiters
335
      $targetDataset = $config->{datasets}->{$dataset}->{target} . '/' . dirnameToFileName( $targetDataset, '.', '/' );
336
      my $command = "cat $filename";
337
      $command .= " | openssl enc -aes-256-cbc -d -K $config->{transport}->{encryption}->{key} -iv $config->{transport}->{encryption}->{IV} " if $config->{transport}->{encryption}->{key};
338
      $command .= " | zfs receive -F $targetDataset";
51 rodolico 339
      logMsg( $command ) if $verboseLoggingLevel >= 2;
46 rodolico 340
      runCmd( $command );
42 rodolico 341
   }
31 rodolico 342
}
30 rodolico 343
 
344
##################### main program starts here #####################
345
# Example to create a random key for encryption/decryption:
24 rodolico 346
# generate a random key with
347
# openssl rand 32 | xxd -p | tr -d '\n' > test.key
348
 
349
# If a YAML config file exists next to the script, load and merge it
350
$config = loadConfig($configFileName, $config );
42 rodolico 351
exit 1 unless keys %$config;
27 rodolico 352
 
44 rodolico 353
# parse CLI options
354
GetOptions( $config,
355
   'dryrun|n',
356
   'verbose|v+',
357
   'version|V',
358
   'help|h',
359
) or do { print "Invalid options\n"; exit 2 };
360
if (defined ($config->{help})) {
361
   print "Usage: $FindBin::Script [--dryrun] [--verbose] [--help]\n";
362
   print "  --dryrun, -n   Run in dry-run mode (no writes)\n";
363
   print "  --verbose, -v  Run in verbose mode (more v's mean more verbose)\n";
364
   print "  --version, -V  Display version number\n";
365
   exit 0;
366
} elsif (defined $config->{version}) {
367
   print "$FindBin::Script v$VERSION\n";
368
   exit 0;
369
}
370
 
51 rodolico 371
# set some defaults in library from config
372
$verboseLoggingLevel = $config->{verbose} // 0;
373
# status file path
35 rodolico 374
$config->{'status_file'} //= "$scriptFullPath.status";
375
# set log file name for sub logMsg in ZFS_Utils, and remove the old log if it exists
376
# Log file is only valid for one run
377
$logFileName = $config->{'log_file'} //= "$scriptFullPath.log";
378
# log only for one run
379
unlink ( $logFileName ) if -f $logFileName;
24 rodolico 380
 
42 rodolico 381
fatalError( "Invalid config file: missing source and/or target server", $config, \&cleanup )
37 rodolico 382
    unless (defined $config->{source} && defined $config->{target});
24 rodolico 383
 
384
my $servername = `hostname -s`;
385
chomp $servername;
42 rodolico 386
$config->{runningAs} = $servername eq $config->{source}->{hostname} ? 'source' :
37 rodolico 387
                $servername eq $config->{target}->{hostname} ? 'target' : 'unknown';
388
 
42 rodolico 389
# mount the transport drive, fatal error if we can not find it
46 rodolico 390
fatalError( "Unable to mount tranport drive with label $config->{transport}->{label}", $config, \&cleanup )
391
   unless $config->{transport}->{mount_point} =  mountDriveByLabel( $config->{transport} );
42 rodolico 392
 
44 rodolico 393
# main program logic
42 rodolico 394
if ( $config->{runningAs} eq 'source' ) {
51 rodolico 395
    logMsg "Running as source server" if $verboseLoggingLevel >= 1;
33 rodolico 396
    # remove all files from transport disk, but leave all subdirectories alone
42 rodolico 397
   fatalError( "Failed to clean transport directory $config->{transport}->{mount_point}", $config, \&cleanup )
44 rodolico 398
      unless $config->{dryrun} or cleanDirectory( $config->{transport}->{mount_point} );
30 rodolico 399
    my $statusList = getStatusFile($config->{status_file});
37 rodolico 400
    $statusList = doSourceReplication($config, $statusList); 
44 rodolico 401
    writeStatusFile($config->{status_file}, $statusList) unless $config->{dryrun};
42 rodolico 402
} elsif ( $config->{runningAs} eq 'target' ) {
51 rodolico 403
    logMsg "Running as target server" if $verboseLoggingLevel >= 1;
37 rodolico 404
    mountGeli( $config->{target}->{geli} ) if ( defined $config->{target}->{geli} );
46 rodolico 405
    umountDiskByLabel( $config->{target}->{geli}->{secureKey} )
406
       unless $config->{target}->{geli}->{secureKey}->{label} eq $config->{transport}->{label};
407
    print "Please insert device labeled REPORT\n" if $config->{target}->{report}->{targetDrive}->{label};
42 rodolico 408
    updateTarget( $config );
24 rodolico 409
} else {
37 rodolico 410
    fatalError( "This server ($servername) is neither source nor target server as per config\n" );
24 rodolico 411
}
412
 
42 rodolico 413
cleanup( $config );
35 rodolico 414
 
25 rodolico 415
1;