#!/usr/bin/perl
# Coding assistance from Claude Code
#
# volcreate -- Create a volume, mount and set acl and quota
#
# Creates a new AFS volume on the given server and partition and mounts it
# in the file system, setting default ACLs if appropriate. It then calls
# loadmtpt to update the mount point database.
#
# Written by Neil Crellin <neilc@stanford.edu>
#        and Russ Allbery <rra@stanford.edu>
# Updated in 2025 by Adam H. Lewenberg <adamhl@stanford.edu>
# Copyright 1998, 1999, 2000, 2002, 2004, 2005, 2011, 2012, 2013, 2025
#     The Board of Trustees of the Leland Stanford Junior University
#
# This program is free software; you may redistribute it and/or modify it
# under the same terms as Perl itself.

## no critic (ProhibitParensWithBuiltins, RequireCarping)
## no critic (RequireNoMatchVarsWithUseEnglish, ProhibitDoubleSigils )

##############################################################################
# Modules and declarations
##############################################################################

use 5.024;
use strict;
use warnings;
use autodie;

use vars qw($JUSTPRINT);

use English;
use Getopt::Long::Descriptive;
use IPC::Run     qw(run);
use List::Util   qw(first);
use Readonly;

our $VERSION = '2.0 (2013-01-15)';

##############################################################################
# Site configuration
##############################################################################

# The number of KB in a MB.
Readonly my $KB_PER_MB => 1000;

# The default cutoff proportion of candidate partitions that will be
# considered for placement of a read/write volume.
Readonly my $DEFAULT_VOLCREATE_CUTOFF => 0.2;

# The cutoff proportion of candidate partitions that will be considered for
# placement of a read/write volume. This can be overridden with the -p flag.
my $VOLCREATE_CUTOFF = $DEFAULT_VOLCREATE_CUTOFF;

# Unset by default, this requires that all mount points begin with a
# particular prefix, generally to ensure that stored mount points using
# loadmtpt are all named consistently.
our $VOLCREATE_MOUNT_PREFIX;

# The path to a file containing ACL rules for volumes. See the documentation
# for its format.
our $ACLS = '/etc/afs-admin-tools/acl-rules';

# The path to a file containing a list of current AFS servers and their volume
# types. See the documentation for its format.
our $SERVERS = '/etc/afs-admin-tools/servers';

# The full path to the loadmtpt utility from afs-mountpoints. The default of
# the empty string says not to do mount point loading.
our $LOADMTPT = q{};

# The full path to fs and vos. vos may be in an sbin directory, which may
# not be on the user's path by default, so check there first.
our $FS = 'fs';
our $VOS = first { -x } qw(/usr/local/sbin/vos /usr/sbin/vos);
$VOS //= 'vos';

# The AFS cell to operate in.  Config file may override.
our $CELL = 'ir.stanford.edu';

# Default configuration file path.  May be overridden by --config on
# the command line; the load itself is deferred until after option
# parsing (see below) so that override can take effect.
my $CONFIG_FILE = '/etc/afs-admin-tools/config';

##############################################################################
# Overrides
##############################################################################

# Run an external command via IPC::Run, capturing stdout, stderr, and the
# exit code. Honors the global $JUSTPRINT variable the same way our system()
# override does: when set, the command is printed and a successful, empty
# result is returned without executing anything.
#
# Takes the command as an array reference of arguments, optionally followed
# by option key/value pairs. Returns a three-element list: (stdout, stderr,
# exit_code). Does not die on a non-zero exit code -- the caller inspects
# exit_code and decides what to do.
#
# Supported options:
#   ignore_justprint => 1   Run the command even when $JUSTPRINT is set.
#                           Use for read-only informational calls that later
#                           logic depends on (e.g. vos partinfo).
sub run_command {
    my ($cmd_ref, %opts) = @_;

    my @cmd = @{$cmd_ref};

    if ($JUSTPRINT && !$opts{ignore_justprint}) {
        print "@cmd\n";
        return (q{}, q{}, 0);
    }

    my ($stdout, $stderr) = (q{}, q{});
    run(\@cmd, \undef, \$stdout, \$stderr);

    ## no critic (ProhibitMagicNumbers)
    my $exit_code = $CHILD_ERROR >> 8;
    return ($stdout, $stderr, $exit_code);
}

# Print an error message to STDERR and exit with a non-zero status.
# The message is prefixed with "$PROGRAM_NAME: error: " and any trailing
# newline in the caller's message is stripped, so callers pass just the
# unadorned message text.
sub exit_with_error {
    my ($msg) = @_;
    chomp $msg;
    print {*STDERR} "$PROGRAM_NAME: error: $msg\n";
    exit 1;
}

##############################################################################
# AFS information
##############################################################################

# Given a list of server name and partition pairs, fully qualify each and
# return them as a list of similar pairs, ordered by whichever partition has
# the most percentage free space. If ., a list of letters, or letter ranges
# are given for the partition, pick the partition from that set that has the
# most free space.
sub find_targets {
    my @locations = @_;
    my @results;

    # Special-case the fully-qualifed case where the user gave the exact
    # server and partition.
    if (@locations == 1 && $locations[0][1] =~ /^[[:lower:]]$/xsm) {
        my ($server, $partition) = @{ $locations[0] };
        if ($server =~ /^\d+$/xsm) {
            $server = 'afssvr' . $server;
        }
        $partition =~ s{^(?:/?vicep)?}{/vicep}xsm;
        return [ $server, $partition ];
    }

    # The normal case, where we need to go looking at current server usage to
    # gather the necessary information.
    while (@locations) {
        my ($server, $part) = @{ shift @locations };

        if ($server =~ /^\d+$/xsm) {
            $server = 'afssvr' . $server;
        }

        if ($part eq q{.}) {
            $part = 'a-z';
        }

        # Read-only informational call: run unconditionally, even under
        # $JUSTPRINT, since callers of find_targets rely on the results.
        my ($partinfo_out, $partinfo_err, $partinfo_rc) = run_command(
            [$VOS, 'partinfo', '-server', $server, '-cell', $CELL],
            ignore_justprint => 1,
        );

        if ($partinfo_rc != 0) {
            exit_with_error("vos partinfo $server failed (status $partinfo_rc): $partinfo_err");
        }

        my @free;
        for my $line (split /\n/xsm, $partinfo_out) {
            # Output should look like:
            # Free space on server afssvr01.stanford.edu:7005 partition /vicepa: 1325466384 K blocks out of total 4292876288
            if ($line =~ m{^Free[ ]space[ ]on[ ].*[ ]partition[ ](/vicep[$part]):[ ](\d+)[ ]K
                           [ ]blocks[ ]out[ ]of[ ]total[ ](\d+)\s*\z}xsm) {
                push(@free, [ $1, $2, $2 / $3 ]);
            } elsif ($line =~ m{^Free[ ]space[ ]on[ ]partition[ ](?:/vicep.)}xsm) {
                next;
            } else {
                exit_with_error("vos partinfo unrecognized output: $line");
            }
        }

        if (!@free) { exit_with_error("no partition matching $part on $server") }

        # @free is a list of [ partition, free_KB, free_fraction ] triples
        # for this server.  Sort by absolute free KB (index 1), largest first,
        # then attach the server name and drop the raw KB value so each
        # result is [ server, partition, free_fraction ].
        @free = sort { $$a[1] <=> $$b[1] } @free;
        @free = reverse @free;
        push(@results, map { [ $server, $$_[0], $$_[2] ] } @free);
    }

    @results = sort { $$a[2] <=> $$b[2] } @results;
    @results = reverse @results;
    return map { [ $$_[0], $$_[1] ] } @results;
}

# Given a volume type for an unreplicated volume, look through the types file
# and find appropriate servers and partitions to use. Returns a random server
# and partition pair from the 25% that have the most percentage free space.
sub find_best_normal {
    my $type = shift;
    my @locations;
    open(my $SERVERS_FH, q{<}, $SERVERS) or exit_with_error("can't open $SERVERS: $ERRNO");
    while (my $curline = <$SERVERS_FH>) {

        if ($curline =~ /^\s* $/xsm) {
            next;
        }

        if ($curline =~ /^\s* [#]/xsm) {
            next;
        }

        my ($server, @rules) = split q{ }, $curline;
        if ($rules[0] =~ /^\[.*\]$/xsm) {
            shift @rules;
        }

        my $parts = q{};
        for my $rule (@rules) {

            my ($part, $allowed);
            if ($rule =~ /:/xsm) {
                ($part, $allowed) = split /:/xsm, $rule;
            } else {
                $part = 'a-z';
                $allowed = $rule;
            }

            if ($allowed eq $type) {
                $parts .= $part;
            }
        }

        if ($parts) {
            push(@locations, [ $server, $parts ]);
        }
    }
    close $SERVERS_FH;

    if (!@locations) {
        exit_with_error("no servers found for type $type");
    }

    my @result = find_targets @locations;
    return @{ $result[int rand(scalar(@result) * $VOLCREATE_CUTOFF)] };
}

# Given a volume type for a replicated volume and the number of replicas, look
# through the types file and find appropriate servers and partitions to use.
# Returns a list, where the first two elements are the server and partition to
# use for the read/write and the first replica and subsequent element pairs
# are the server and partition to use for the read-only replicas. Handles
# geographic dispersion.
sub find_best_replicated {
    my ($type, $replicas) = @_;
    my (@rw, @ro, %servers);
    open(my $SERVERS_FH, q{<}, $SERVERS) or exit_with_error("can't open $SERVERS: $ERRNO");
    while (my $curline = <$SERVERS_FH>) {
        next if $curline =~ /^\s* $/xsm;
        next if $curline =~ /^\s* [#]/xsm;
        my ($server, @rules) = split q{ }, $curline;
        my $site;
        if ($rules[0] =~ /^\[(.*)\]$/xsm) {
            $site = $1;
            shift @rules;
        }
        my $rwparts = q{};
        my $roparts = q{};
        for my $rule (@rules) {
            my ($part, $allowed);
            if ($rule =~ /:/xsm) {
                ($part, $allowed) = split /:/xsm, $rule;
            } else {
                $part = 'a-z';
                $allowed = $rule;
            }
            if ($allowed eq "$type-rw") {
                $rwparts .= $part;
            } elsif ($allowed eq "$type-ro") {
                $roparts .= $part;
            }
        }
        if ($rwparts) {
            $servers{$server} = $site;
            push(@rw, [ $server, $rwparts ]);
        }
        if ($roparts) {
            $servers{$server} = $site;
            push(@ro, [ $server, $roparts ]);
        }
    }
    close $SERVERS_FH;
    if (!@rw || !@ro || @ro < $replicas - 1) {
        exit_with_error("insufficient servers found for type $type");
    }
    my @locations;
    my @targets = find_targets @rw;
    push(@locations,
          $targets[int rand(scalar(@targets) * $VOLCREATE_CUTOFF)]);
    my %sites = map { $_ => 1 } values %servers;
    for my $site (keys %sites) {
        if (@locations >= $replicas) {
            last;
        }
        if ($site eq $servers{$locations[0][0]}) {
            next;
        }
        my @candidates = grep { $servers{$$_[0]} eq $site } @ro;
        if (! @candidates) {
            next;
        }
        push(@locations, (find_targets @candidates)[0]);
    }
    my $found = @locations;
    if ($found < $replicas) {
        my %locations = map { @$_ } @locations;
        @ro = grep { !$locations{$$_[0]} } @ro;
        push(@locations, (find_targets @ro)[0 .. ($replicas - $found - 1)]);
    }
    return @locations;
}

##############################################################################
# AFS operations
##############################################################################

# Create a volume, given the server, partition, volume name, and quota (MB). Dies
# on a failure to create the volume.
sub volume_create {
    my ($server, $partition, $volume, $quota_MB) = @_;

    my ($stdout, $stderr, $exit_code) = run_command([
        $VOS, 'create',
        '-server',    $server,
        '-partition', $partition,
        '-name',      $volume,
        '-maxquota',  $quota_MB * $KB_PER_MB,
        '-cell',      $CELL,
    ]);

    if ($exit_code != 0) {
        exit_with_error("Failed to create volume (status $exit_code): $stderr");
    }

    ($stdout, $stderr, $exit_code) = run_command([
        $VOS, 'backup',
        '-id',   $volume,
        '-cell', $CELL,
    ]);

    if ($exit_code != 0) {
        exit_with_error("Failed to backup volume (status $exit_code): $stderr");
    }

    return;
}

# Clone a volume, given the server, partition, and volume name to use for the
# new volume and the name of the old volume to clone.
sub volume_clone {
    my ($server, $partition, $new, $old) = @_;
    require File::Temp;
    my ($fh, $filename) = File::Temp::tempfile (undef, UNLINK => 1);

    print "Dumping volume $old\n";
    my ($stdout, $stderr, $exit_code) = run_command([
        $VOS, 'dump',
        '-id',   $old,
        '-file', $filename,
        '-cell', $CELL,
    ]);

    if ($exit_code != 0) {
        exit_with_error("failed to dump volume $old (status $exit_code): $stderr");
    }

    print "Restoring $new from ", $filename, "\n";
    ($stdout, $stderr, $exit_code) = run_command([
        $VOS, 'restore',
        '-server',    $server,
        '-partition', $partition,
        '-name',      $new,
        '-file',      $filename,
        '-cell',      $CELL,
    ]);

    if ($exit_code != 0) {
        exit_with_error("failed to restore volume $new (status $exit_code): $stderr");
    }

    close $fh;

    return;
}

# Mount the volume, chmod it to 755 since AFS creates it 777, and load the
# mount point into the database. chmod the root of the volume to 755 since
# AFS creates it 777.
sub volume_mount {
    my ($volume, $mtpt) = @_;
    ## no critic (ProhibitMagicNumbers)

    my ($stdout, $stderr, $exit_code) = run_command([
        $FS, 'mkmount',
        '-dir', $mtpt,
        '-vol', $volume,
    ]);

    if ($exit_code != 0) {
        exit_with_error("Failed to make mount point (status $exit_code): $stderr");
    }

    if ($JUSTPRINT) {
        print "chmod 755 $mtpt\n";
    } else {
        chmod(0755, $mtpt) or warn "Failed to chmod root: $ERRNO\n";
    }

    if ($LOADMTPT) {
        ($stdout, $stderr, $exit_code) = run_command([$LOADMTPT, $mtpt]);
        if ($exit_code != 0) {
            warn "Failed to load mountpoint (status $exit_code): $stderr";
        }
    }

    return;
}

# Set the ACLs of the volume appropriately. Some volumes have their own
# particular ACL conventions; take care of those here as well.
sub volume_setacls {
    my ($volume, $mtpt, @acls) = @_;

    # Find any extra ACLs that apply to this volume.
    my @extra;
    if (open(my $ACLS_FH, q{<}, $ACLS)) {
        my $found = 0;
        while (my $curline = <$ACLS_FH>) {
            next if $curline =~ /^\s+ [#]/xsm;
            next if $curline =~ /^\s* $/xsm;
            if ($curline =~ m{^/(.*)/\s*$}xsm) {
                my $regex = $1;
                $found = ($volume =~ /$regex/xsm);
            } elsif ($found && $curline =~ /^\s/xsm) {
                my ($user, $acl, $bogus) = split q{ }, $curline;
                if ($bogus || !$user || !$acl) {
                    warn "$PROGRAM_NAME: syntax error on line $INPUT_LINE_NUMBER of $ACLS\n";
                    next;
                }
                push(@extra, $user, $acl);
            }
        }
        close $ACLS_FH;
    } else {
        warn "$PROGRAM_NAME: cannot open $ACLS: $ERRNO\n";
    }

    # Append the extra ACLs that apply to this volume.
    push(@acls, @extra);

    # Actually set the ACLs. Users may include -clear or -negative in
    # @acls (see the POD); those must be passed to fs setacl as its own
    # switches, not as -acl entries.
    my @flags;
    my @entries;
    for my $arg (@acls) {
        if ($arg eq '-clear' || $arg eq '-negative') {
            push(@flags, $arg);
        } else {
            push(@entries, $arg);
        }
    }

    # fs setacl's -acl argument is mandatory and takes one or more
    # entries.  With no ACL entries to apply, there's nothing to do --
    # skip the call rather than invoke fs setacl with a bare -acl.
    if (!@entries) {
        return;
    }

    my ($stdout, $stderr, $exit_code) = run_command([
        $FS, 'setacl',
        '-path', $mtpt,
        '-acl',  @entries,
        @flags,
    ]);

    if ($exit_code != 0) {
        warn "Failed to set acls (status $exit_code): $stderr";
    }

    return;
}

# Given the volume name and then a list of server and partition pairs, create
# the replicas for a replicated volume and then release it. The list of
# server and partition pairs must include the location of the read/write
# volume for the first replica.
sub volume_replicate {
    my ($volume, @locations) = @_;
    while (@locations) {
        my ($server, $partition) = @{ shift @locations };
        my ($stdout, $stderr, $exit_code) = run_command([
            $VOS, 'addsite',
            '-server',    $server,
            '-partition', $partition,
            '-id',        $volume,
            '-cell',      $CELL,
        ]);

        if ($exit_code != 0) {
            exit_with_error("Failed to replicate volume to $server $partition (status $exit_code): $stderr");
        }
    }

    my ($stdout, $stderr, $exit_code) = run_command([
        $VOS, 'release',
        '-id',   $volume,
        '-cell', $CELL,
        '-force',
    ]);

    if ($exit_code != 0) {
        exit_with_error("Failed to release volume (status $exit_code): $stderr");
    }

    return;
}

##############################################################################
# Main routine
##############################################################################

# Trim extraneous garbage from the path.
my $fullpath = $PROGRAM_NAME;
$PROGRAM_NAME =~ s{.*/}{}xsm;

# Parse command line options. We do allow an odd number of arguments for
# ACLs, in order to allow things like -clear.
my ($opt, $usage) = describe_options(
    '%c %o [server partition] volume quota mount [acl ...]',
    [ 'cell|C=s',             'AFS cell to operate in (overrides $CELL)'             ],
    [ 'clone|c=s',            'clone from an existing volume'                        ],
    [ 'config=s',             'path to the configuration file'                       ],
    [ 'servers|s=s',          'path to servers file (overrides $SERVERS)'            ],
    [ 'type|t=s',             'volume type (looked up in the servers file)'          ],
    [ 'replicas|r=i',         'number of replicas (implies -t)', { default => 0 }    ],
    [ 'proportion|p=f',       'candidate cutoff proportion (0-1)',
        { default => $DEFAULT_VOLCREATE_CUTOFF }                                     ],
    [ 'dry-run|n',            "print what would be done; don't run it"               ],
    [ 'quiet|q',              'suppress normal output'                               ],
    [ 'manual|m',             'show the full manual page and exit'                   ],
    [ 'help|h',               'show this usage summary and exit'                     ],
    [ 'version|v',            'print version and exit'                               ],
    { getopt_conf => [ 'bundling', 'no_ignore_case', 'require_order' ] },
);

if ($opt->help) {
    print $usage->text;
    exit 0;
}
if ($opt->manual) {
    print "Feeding myself to perldoc, please wait....\n";
    exec('perldoc', '-t', $PROGRAM_NAME) or exit_with_error("Cannot fork: $ERRNO");
}
if ($opt->version) {
    print "volcreate $VERSION\n";
    exit 0;
}

my $clone    = $opt->clone;
my $type     = $opt->type;
my $replicas = $opt->replicas;
my $quiet    = $opt->quiet;
$JUSTPRINT         = $opt->dry_run;
$VOLCREATE_CUTOFF  = $opt->proportion;

# --config on the command line overrides the hardcoded default path.
# Load the config file now (deferred from top-of-file) so command-line
# --cell etc. can then override anything it sets.
if (defined $opt->config) {
    $CONFIG_FILE = $opt->config;
}
if (-f $CONFIG_FILE) {
    require $CONFIG_FILE;  ## no critic (RequireBarewordIncludes)
}

# --cell on the command line overrides both the hardcoded default and
# any $CELL set by the config file.  It also derives a mount-point
# prefix from the cell name, replacing any $VOLCREATE_MOUNT_PREFIX
# from the config file -- otherwise the config's prefix (tied to the
# default cell) would reject mount points in the requested cell.
if (defined $opt->cell) {
    $CELL = $opt->cell;
    $VOLCREATE_MOUNT_PREFIX = "/afs/.$CELL/";
}

# --servers on the command line overrides both the hardcoded default
# and any $SERVERS set by the config file.  Useful when operating on
# a non-default cell whose servers file lives at a different path.
if (defined $opt->servers) {
    $SERVERS = $opt->servers;
}

if ($replicas && !$type) { exit_with_error("-r option given without -t option") }

if ($VOLCREATE_CUTOFF > 1 || $VOLCREATE_CUTOFF < 0) {
    exit_with_error("-p value must be between 0 and 1");
}

# If quiet operation was requested, cheat by rerouting stdout to /dev/null.
if ($quiet) {
    open(STDOUT, q{>}, '/dev/null')
        or exit_with_error("cannot redirect stdout to /dev/null: $ERRNO");
}

# Fill in the various information that we need.
my ($server, $partition, $volume, $quota_MB, $mtpt, @acls);
if ($type) {
    if (@ARGV < 3) {
        exit_with_error("Usage: volcreate -t type volname quota mountpoint [acls]");
    }

    if ($type =~ /-r[wo]$/xsm) {
        exit_with_error("Type ends in -ro or -rw (maybe you meant to use the -r flag?)");
    }

    ($volume, $quota_MB, $mtpt, @acls) = @ARGV;
} else {
    if (@ARGV < 5) {
        exit_with_error("Usage: volcreate server partition volname quota mtpt [acls]");
    }

    ($server, $partition, $volume, $quota_MB, $mtpt, @acls) = @ARGV;
}

# Ensure that the mount point starts with $VOLCREATE_MOUNT_PREFIX, if set.
# This is also useful for ensuring that the arguments weren't given in the
# wrong order and no argument was missing.
if (defined($VOLCREATE_MOUNT_PREFIX) and $LOADMTPT) {
    my $prefix = $VOLCREATE_MOUNT_PREFIX;
    if ($mtpt !~ m{^\Q$prefix\E}xsm) {
        my $try = $mtpt;
        $try =~ s{^/afs/([^.])}{/afs/.$1}xsm;
        if ($try =~ m{^\Q$prefix\E}xsm) {
            $mtpt = $try;
        } else {
            exit_with_error("Mount point must begin with $prefix");
        }
    }
}

# fs mkm doesn't like trailing slashes on the mount point, and neither does
# the mount point database.
$mtpt =~ s{/+$}{}xsm;

# Make sure the parent directory of the mount point exists and the mount point
# doesn't already exist.
if (-e $mtpt) {
    exit_with_error("Mount point $mtpt already exists");
}

my $parent = $mtpt;
if ($parent =~ s{/[^/]+$}{}xsm) {
    if (! -d $parent) {
        exit_with_error("Parent directory of mount point $mtpt doesn't exist");
    }
}

# Canonify AFS server name and find the exact partition on which to create the
# read/write volume.
my @ros;
if ($type) {
    if ($replicas) {
        @ros = find_best_replicated($type, $replicas);
        ($server, $partition) = @{ $ros[0] };
    } else {
        ($server, $partition) = find_best_normal($type);
    }
} else {
    ($server, $partition) = @{ (find_targets [ $server, $partition ])[0] };
}

# Do the work of creating and mounting the read/write volume.
if ($clone) {
    volume_clone($server, $partition, $volume, $clone);
} else {
    volume_create($server, $partition, $volume, $quota_MB);
}
volume_mount($volume, $mtpt);
if (!$clone) {
    volume_setacls($volume, $mtpt, @acls);
}

# If the volume is replicated, take care of creating and releasing the
# replicas now that the ACL is set correctly.
if ($replicas && $replicas > 0) {
    volume_replicate($volume, @ros);
}
exit 0;
__END__

##############################################################################
# Documentation
##############################################################################

=for stopwords
ACL AFS Crellin acl afs-admin-tools afssvr3 afssvr14 fs -hnqv -C -s loadmtpt
afs-mountpoints partinfo pubsw rra volcreate vos pubsw.byacc19

=head1 NAME

volcreate - Create and mount a new AFS volume

=head1 SYNOPSIS

B<volcreate> [B<-hnqv>] [B<-C> I<cell>] [B<-c> I<clone-from>]
[B<--config>=I<path>] [B<-p> I<cutoff>] [B<-s> I<servers-file>] I<server>
I<part> I<volume> I<quota (MB)> I<mount> [I<acl> ...]

B<volcreate> [B<-hnqv>] [B<-C> I<cell>] [B<-c> I<clone-from>]
[B<--config>=I<path>] B<-t> I<type> [B<-p> I<cutoff>]
[B<-r> I<replicas>] [B<-s> I<servers-file>] I<volume> I<quota (MB)> I<mount> [I<acl> ...]

=head1 DESCRIPTION

B<volcreate> creates a new AFS volume on the given server and partition,
sets its quota, and mounts it in the file system at the given path,
optionally setting its ACL. It then updates the AFS mount point database
to include this new volume.

I<server> is the AFS server on which to create the volume. AFS servers
may be specified as just a number; all numeric server names will have
C<afssvr> prepended to them.

I<part> is the partition on which to create that volume. Partitions may
be specified as a simple letter, as C<vicepX>, or as C</vicepX>. More
than 26 partitions on one server is not supported. Partitions may also be
specified as C<.>, in which case a random partition on that server in the
top 20% in free space according to B<vos partinfo> is chosen, or as a
string of letters and letter ranges such as C<ace-gm>, in which case a
random partition of the set specified in the top 20% in free space is
chosen. (In this example, the set is /vicepa, /vicepc, /vicepe through
/vicepg, or /vicepm on the given sever.)  The 20% cutoff proportion can be
overridden with the B<-p> option.

Alternately, rather than giving a server and partition, B<volcreate>
accepts the B<-t> option to specify a volume type. If this option is
given, no server or partition is necessary and B<volcreate> will instead
place the volume on an appropriate server by finding a random partition in
the top 20% of the most percentage space free of the available server
partitions for that volume type. As above, the cutoff proportion can be
overridden with the B<-p> option. For more information on defining volume
types and associating them with appropriate servers and partitions, see
L<CONFIGURATION> below.

When B<-t> is given, B<-r> may also be given to specify a number of
replicas if a replicated volume is being created. When creating a
replicated volume, the read/write copy will be placed as described above,
but the read-only replicas will be placed on the I<replicas> partitions
with the most free space.

I<volume> is the name of the volume to create. I<quota> is its quota in
megabytes (B<not> in kilobytes). I<mount> is the full path to the
intended mount location of the volume (this must begin with "/afs/.ir/" so
that the mount point database remains consistent). I<acl> is any normal
ACL arguments to C<fs setacl>.

For some types of volumes, some ACLs will be set automatically. This is
governed by the F<acl-rules> file; see L<CONFIGURATION> below.

=head1 OPTIONS

=over 4

=item B<-C> I<cell>, B<--cell>=I<cell>

Operate on the named AFS cell.  This value is passed to every B<vos>
command via C<-cell>.  Overrides the built-in default and any C<$CELL>
set in F</etc/afs-admin-tools/config>.  It also derives the required
mount-point prefix from the cell name (F</afs/.>I<cell>F</>),
overriding any C<$VOLCREATE_MOUNT_PREFIX> from the config file.

=item B<-c> I<clone-from>, B<--clone>=I<clone-from>

Rather than creating a new, empty volume, clone the newly created volume
from the volume I<clone-from>. This dumps the old volume into F</tmp>, so
be careful to do this on a system with a lot of space in F</tmp> if the
volume is large. When this option is specified, the quota and ACLs
specified on the command line will be ignored, since they'll just be
copied from the old volume. (The quota must still be specified, though,
even though it's ignored. This is a wart in the interface.)

=item B<--config>=I<path>

Path to the configuration file to load, overriding the built-in default
of F</etc/afs-admin-tools/config>.  Useful when operating on a
non-default cell whose configuration lives at a different path.

=item B<-h>, B<--help>

Print a short summary of the command-line options and exit.

=item B<-m>, B<--manual>

Print this full manual page (by feeding the script to C<perldoc -t>) and
exit.

=item B<-n>, B<--dry-run>, B<--just-print>

Don't run any commands, just print out what would have been done.

=item B<-p> I<cutoff>, B<--proportion>=I<cutoff>

By default, when placing read/write volumes, the destination partition
will be chosen randomly from the top 20% of partitions ranked by the most
free space. The placement of the volume is somewhat randomized to avoid
putting lots of small volumes on the same mostly unused partition,
creating a long-term space problem when all of those volumes are used.

This option can be used to change the number of partitions selected from
for this random placement. The default is 0.2, representing that top 20%
metric. A value of 0 will always choose the partition with the most free
space. A value of 1 will cause the placement to be completely random
among all possible locations, without regard to which have the most free
space. Any other value will be the proportion of the possible locations
that will be chosen between randomly.

=item B<-q>, B<--quiet>

Run quietly. Only errors (if any) will be output.

=item B<-r> I<replicas>, B<--replicas>=I<replicas>

The number of replicas for the volume. Use of this option indicates that
the volume is replicated, and it will be replicated at a number of sites
equal to the I<replicas> value. The first replica will always be on the
same server and partition as the read/write volume; the rest will be
chosen from the servers that hold read-only replicas for that volume type.
B<-t> must be given if this option is used.

=item B<-s> I<servers-file>, B<--servers>=I<servers-file>

Path to an alternate servers file listing the AFS servers and their
volume types for the cell being operated on.  Overrides the built-in
default and any C<$SERVERS> set in F</etc/afs-admin-tools/config>.
Useful when operating on a non-default cell whose servers file lives at
a different path.

=item B<-t> I<type>, B<--type>=I<type>

Create a volume of the specified type. When this option is used, no
server or partition should be specified, and instead B<volcreate> will
find all the servers that can store that volume type and pick the server
and partition with the most percentage space free. This option is
required to use B<-r>.

=item B<-v>, B<--version>

Print out the version of B<volcreate> and quit.

=back

=head1 CONFIGURATION

=head2 General Settings

B<volcreate> loads configuration settings from
F</etc/afs-admin-tools/config> if that file exists. If it exists, it must
be Perl code suitable for loading with C<require>. This means that each
line of the configuration file should be of the form:

    our $VARIABLE = VALUE;

where C<$VARIABLE> is the configuration variable being set and C<VALUE> is
the value to set it to (which should be enclosed in quotes if it's not a
number). The file should end with:

    1;

so that Perl knows the file was loaded correctly.

The supported configuration variables are:

=over 4

=item $VOLCREATE_CUTOFF

The cutoff proportion of candidate partitions that will be considered for
placement of a read/write volume. The default is 0.2 (20%). This can be
overridden with the B<-p> flag.

=item $VOLCREATE_MOUNT_PREFIX

If set, the path at which the volume is created must start with this
string. This can be used to ensure that all registered mount points (when
B<loadmtpt> support is enabled) use a consistent naming scheme. (All of
them pointing to the read/write volume or using the fully-qualified cell
name, for example.)

If this prefix starts with F</afs/.> and the path starts with the same
prefix but without the leading period (indicating read/write paths), the
leading period will be quietly added. Otherwise, invalid arguments will
be rejected.

=item $ACLS

The path to a file containing ACL rules for volumes. See L<ACL Rules>
below for more information about its syntax. The default value is
F</etc/afs-admin-tools/acl-rules>.

=item $SERVERS

The path to a file containing a list of current AFS servers and their
volume types. See L<AFS Servers> below for more information about its
syntax. The default value is F</etc/afs-admin-tools/servers>.

=item $LOADMTPT

The full path to the B<loadmtpt> utility from afs-mountpoints. If this
variable is set, B<loadmtpt> will be invoked for each new volume created
to record its mount point in the mount point database. The default is the
empty string, which says to not run B<loadmtpt>.

=item $FS

The full path to the AFS B<fs> utility. If this variable is not set,
B<volcreate> defaults to looking for B<fs> on the user's PATH.

=item $VOS

The full path to the AFS B<vos> utility. If this variable is not set,
B<volcreate> defaults to F</usr/local/sbin/vos> or F</usr/sbin/vos> if
they exist, and otherwise looks for B<vos> on the user's PATH.

=item $CELL

The AFS cell to operate in.  Defaults to C<ir.stanford.edu>.

=back

=head2 ACL Rules

The file pointed to by the $ACLS configuration variable
(F</etc/afs-admin-tools/acl-rules> by default) contains rules specifying
the default ACLs that should be set on different types of volumes. The
format of this file should be a regular expression matching a class of
volumes, surrounded by C<//> and starting in the first column, and then
followed by whitespace-indented user/ACL pairs that apply to that class of
volumes, one per line. All matching regular expressions will contribute
their set of ACL settings to the final ACL string. Any ACLs given on the
command line of volcreate will take precedence over the ones in this file
(but the ones in this file will still be applied -- the ACLs will be
merged).

A sample entry would be:

    /^(group|dept)\./
        system:anyuser read
        system:dept-admin all

Note that the regex line must not be indented (must begin in column one),
and the ACL lines must be indented. Think of it as Python.

=head2 AFS Servers

The file pointed to by the $SERVERS configuration variable
(F</etc/afs-admin-tools/servers> by default) contains a list of AFS
servers that B<volcreate> should consider as potential hosts for new
volumes. Each line should start with an AFS server name, optionally a
location for that server in square brackets, and then optionally contain a
space-separated list of types of volumes handled by that server. Those
volume types may begin with a single letter or range of letters and a
colon, indicating that only the partition or partitions named handle that
type of volume.

Blank lines and lines beginning with C<#> are ignored.

For non-replicated volumes, the type in this file should match the type
given to B<volcreate>. For replicated volumes, the type suffixed with
C<-rw> will be used for the read/write volume and the type suffixed with
C<-ro> will be used for the replicas.

So, for example, a sample entry would be:

    afssvr11 [sweet] a-c:logs d:pubsw-ro d:web-ro

When creating replicated volumes, B<volcreate> will attempt to put at
least one replica in every distinct location that accepts the C<-ro>
version of that volume type. The names of the locations are arbitrary;
they can be any label as long as servers in the same location use the same
label.

=head1 EXAMPLES

Create the volume ls.mail.logs on afssvr14 /vicepa with a quota of 20MB
and mount it on /afs/.ir/site/leland/mail/logs:

    volcreate afssvr14 a ls.mail.logs 20 /afs/.ir/site/leland/mail/logs

Create ls.trip.nntp on afssvr3 /vicepc with a quota of 5MB and mount it on
/afs/.ir/site/leland/tripwire/nntp.Stanford.EDU. Set a default ACL only
giving system:localhosts read access and rra all access.

    volcreate 3 c ls.trip.nntp 5 \
        /afs/.ir/site/leland/tripwire/nntp.Stanford.EDU \
        -clear system:localhosts read rra all

(this should all be typed on one line). Note that C<fs setacl> flags like
B<-clear> are allowed.

Create a replicated volume with three replicas of type pubsw named
pubsw.byacc19 with a quota of 20MB and mount it at
/afs/.ir/pubsw/Languages/byacc-1.9.

    volcreate -t pubsw -r 3 pubsw.byacc19 20 \
        /afs/.ir/pubsw/Langauges/byacc-1.9

The correct ACLs for a pubsw volume will be set based on the F<acl-rules>
file.

Clone ls.trip.nntp into a new ls.trip.news volume, which will be mounted
at /afs/.ir/site/leland/tripwire/news.Stanford.EDU:

    volcreate -t logs -c ls.trip.nntp ls.trip.news 0 \
        /afs/.ir/site/leland/tripwire/news.Stanford.EDU

Note that the meaningless 0 quota value is ignored.

=head1 FILES

=over 4

=item F</etc/afs-admin-tools/servers>

The default path to a file containing a list of current AFS servers and
their volume types. The path to this file can be overridden with the
$SERVERS configuration variable.

=item F</etc/afs-admin-tools/acl-rules>

The default path to file contains rules specifying the default ACLs that
should be set on different types of volumes. The path to this file can be
overridden with the $ACLS configuration variable.

=back

=head1 AUTHORS

Neil Crellin <neilc@stanford.edu> and Russ Allbery <rra@stanford.edu>.
Updated in 2025 by Adam H. Lewenberg <adamhl@stanford.edu>.

=head1 COPYRIGHT AND LICENSE

Copyright 1998, 1999, 2000, 2002, 2004, 2005, 2011, 2025 The Board of Trustees
of the Leland Stanford Junior University.

This program is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.

=head1 SEE ALSO

L<fs_mkmount(1)>, L<fs_setquota(1)>, L<fs_setacl(1)>, L<loadmtpt(1)>,
L<vos_create(1)>, L<vos_dump(1)>, L<vos_restore(1)>

This script is part of the afs-admin-tools package. The most recent
version is available from the afs-admin-tools web page at
L<http://www.eyrie.org/~eagle/software/afs-admin-tools/>.

=cut
