Amanda::Changer modules list
Amanda modules list
List of All Modules
All Amanda Releases



Amanda::Changer -- interface to changer scripts


    use Amanda::Changer;
    my $chg = Amanda::Changer->new(); # loads the default changer; OR
    $chg = Amanda::Changer->new("somechanger"); # references a defined changer in amanda.conf
        label => "TAPE-012",
        mode => "write",
        res_cb => sub {
            my ($err, $reservation) = @_;
            if ($err) {
                die $err->{message};
            $dev = $reservation->{'device'};
            # use device..
    # later..
    $reservation->release(finished_cb => $start_next_volume);
    # later..


All operations in the module return immediately, and take as an argument a callback function which will indicate completion of the changer operation -- a kind of continuation. The caller should run a main loop (see Amanda::MainLoop) to allow the interactions with the changer script to continue.

A new object is created with the new function as follows:

  my $chg = Amanda::Changer->new($changer_name,
                                 tapelist       => $tapelist,
                                 labelstr       => $labelstr,
                                 autolabel      => $autolabel,
                                 meta_autolabel => $meta_autolabel);

to create a named changer (a name provided by the user, either specifying a changer directly or specifying a changer definition), or

  my $chg = Amanda::Changer->new(undef,
                                 tapelist       => $tapelist,
                                 labelstr       => $labelstr,
                                 autolabel      => $autolabel,
                                 meta_autolabel => $meta_autolabel);

to run the default changer. This function handles the many ways a user can configure a changer.

If there is a problem creating the new object, then the resulting object will be a fatal Error object (described below). Thus the usual recipe for creating a new changer is

  my $chg = Amanda::Changer->new($changer_name);
  if ($chg->isa("Amanda::Changer::Error")) {
    die("Error creating changer $changer_name: $chg");

tapelist must be an Amanda::Tapelist object. It is required if you want to use $chg->volume_is_labelable(), $chg->make_new_tape_label(), $chg->make_new_meta_label(), $res->make_new_tape_label() or $res->make_new_meta_label(). labelstr must be like getconf($CNF_LABELSTR), that value is used if labelstr is not set. autolabel must be like getconf($CNF_AUTOLABEL), that value is used if autolabel is not set. meta_autolabel must be like getconf($CNF_META_AUTOLABEL), that value is used if meta_autolabel is not set. =head2 MEMBER VARIABLES

Note that these variables are not set until after the subclass constructor is finished.


Gives the name of the changer. This name will make sense to the user, but will not necessarily form a valid changer specification. It should be used to describe the changer in messages to the user.


All changer callbacks take an error object as the first parameter. If no error occurred, then this parameter is undef and the remaining parameters are defined.

A res_cb $cb is called back as:

 $cb->($error, undef);

in the event of an error, or

 $cb->(undef, $reservation);

with a successful reservation. res_cb must always be specified. A finished_cb $cb is called back as


in the event of an error, or


on success. A finished_cb may be omitted if no notification of completion is required.

Other callback types are defined below.


When a callback is made with an error, it is an object of type Amanda::Changer::Error. When interpolated into a string, this object turns into a simple error message. However, it has some additional methods that can be used to determine how to respond to the error. First, the error message is available explicitly as $err->message. The error type is available as $err->{'type'}, although checks for particular error types should use the TYPE methods instead, as perl is better able to detect typos with this syntax:

  if ($err->failed) { ... }

The error types are:

  fatal      Changer is no longer useable
  failed     Operation failed, but the changer is OK

The API may add other error types in the future (for example, to indicate that a required resource is already reserved).

Errors of the type fatal indicate that the changer should not be used any longer, and in most cases the caller should terminate abnormally. For example, configuration or hardware errors are generally fatal.

If an operation fails, but the changer remains viable, then the error type is failed. The reason for the failure is usually clear to the user from the message, but for callers who may need to distinguish, $err->{'reason'} has one of the following values:

  notfound          The requested volume was not found
  invalid           The caller's request was invalid (e.g., bad slot)
  notimpl           The requested operation is not supported
  volinuse          The requested volume or slot is already in use
  driveinuse        All drives are in use
  unknown           Unknown reason
  empty             The slot is empty

Like types, checks for particular reasons should use the methods, to avoid undetected typos:

  if ($err->failed and $err->notimpl) { ... }

Other reasons may be added in the future, so a caller should check for the reasons it expects, and treat any other failures as of unknown cause.

When the desired slot cannot be loaded because it is already in use, the volinuse error comes with an extra parameter, slot, giving the slot in question. This parameter is not defined for other cases.


Changers maintain a global concept of a "current" slot, for compatibility with Amanda algorithms such as the taperscan. However, it is not compatible with concurrent use of the same changer, and may be inefficient for some changers, so new algorithms should avoid using it, preferring instead to load the correct tape immediately (with load), and to progress from tape to tape using the relative_slot parameter to load.



To terminate a changer object.


The most common operation with a tape changer is to load a volume. The load method is heavily overloaded to support a number of different ways to specify a volume.

In general, the method takes a res_cb giving a callback that will receive the reservation. If set_current is specified and true, then the changer's current slot should be updated to correspond to $slot. If not, then the changer should not update its current slot (but some changers will anyway - specifically, chg-compat).

The load method always read the label if it succeed to load a volume.

The optional mode describes the intended use of the volume by the caller, and should be one of "read" (the default) or "write". Changers managing WORM media may use this parameter to provide a fresh volume for writing, but to search for already-written volumes when reading.

The load method has a number of permutations:

  $chg->load(res_cb => $cb,
             label => $label,
             mode => $mode,
             set_current => $sc)

Load and reserve a volume with the given label. This may leverage any barcodes or other indices that the changer has available.

Note that the changer tries to load the requested volume, but it's a mean world out there, and you may not get what you want, so check the label on the loaded volume before getting started.

  $chg->load(res_cb => $cb,
             slot => $slot,
             mode => $mode,
             set_current => $sc)

Load and reserve the volume in the given slot. $slot is a string specifying the slot to load, provided by the user or from some other invocation of this changer. Note that slots are not necessarily numeric, so performing arithmetic on this value is an error.

If the slot does not exist, res_cb will be called with a notfound error. Empty slots are considered empty.

  $chg->load(res_cb => $cb,
             relative_slot => "current",
             mode => $mode)

Reserve the volume in the "current" slot. This is used by the traditional taperscan algorithm to begin its search.

  $chg->load(res_cb => $cb,
             relative_slot => "next",
             slot => $slot,
             except_slots => { %except_slots },
             mode => $mode,
             set_current => $sc)

Reserve the volume that follows the given slot or, if slot is omitted, the volume that follows the current slot. This will skip empty slots as if they were not present in the changer.

The optional except_slots argument specifies a hash of slots that should not be loaded. Keys are slot names, and the hash values are ignored. This is useful as a termination condition when scanning all of the slots in a changer: keep a hash of all slots already loaded, and pass that hash in except_slots. When the load operation returns a notfound error, the scan is complete.


  $chg->info(info_cb => $cb,
             info => [ $key1, $key2, .. ])

Query the changer for miscellaneous information. Any number of keys may be specified. The info_cb is called with $error as the first argument, much like a res_cb, but the remaining arguments form a hash giving values for all of the requested keys that are supported by the changer. The preamble to such a callback is usually

  info_cb => sub {
    my ($error, %results) = @_;
    # ..

Supported keys are:


The total number of slots in the changer device. If this key is not present or -1, then the device cannot determine its slot count (for example, an archival device that names slots by timestamp could potentially run until the heat-death of the universe).


A string describing the name and model of the changer device.


If true, then this changer implements searching (loading by label) with something more efficient than a sequential scan through the volumes. This information affects some taperscan algorithms and recovery programs, which may choose to do their own manual scan instead of invoking many potentially slow searches.


  $chg->reset(finished_cb => $cb)

Reset the changer to a "base" state. This will generally reset the "current" slot to something the user would think of as the "first" tape, unload any loaded drives, etc. It is an error to call this while any reservations are outstanding.


  $chg->clean(finished_cb => $cb,
              drive => $drivename)

Clean a drive, if the changer supports it. Drivename can be omitted for devices with only one drive, or can be an arbitrary string from the user (e.g., an amtape argument). Note that some changers cannot detect the completion of a cleaning cycle; in this case, the user will just need to delay further Amanda activities until the cleaning is complete.


  $chg->eject(finished_cb => $cb,
              drive => $drivename)

Eject the volume in a drive, if the changer supports it. Drivename is as specified to clean. If possible, applications should prefer to eject a reserved volume when finished with it ($res->release(eject => 1)), to ensure that the correct volume is ejected from a multi-drive changer.


  $chg->update(finished_cb => $cb,
               user_msg_fn => $fn,
               changed => $changed)

The user has changed something -- loading or unloading tapes, reconfiguring the changer, etc. -- that may have invalidated the database. $changed is a changer-specific string indicating what has changed; if it is omitted, the changer will check everything.

Since updates can take a long time, and users often want to know what's going on, the update method will call user_msg_fn, if specified, with user-oriented messages appropriate to the changer.


  $chg->inventory(inventory_cb => $cb)

The inventory_cb is called with an error object as the first parameter, or undef if no error occurs. The second parameter is an arrayref containing an ordered list of information about the slots in the changer. The order never change, but some entries can be added or removed.

Each slot is represented by a hash with the following keys:


  $chg->make_new_tape_label(barcode => $barcode,
                            slot    => $slot,
                            meta    => $meta);

To devise a new name for a volume using the barcode and meta arguments. This will return undef if no label could be created.



To devise a new meta name for a meta volume. This will return undef if no label could be created.



Return True if the changer have the inventory method.


  $chg->volume_is_labelable($device_status, $f_type, $label);

Return 1 if the volume is labelable acording to the autolabel setting.


The slot name


Set to 1 if it is the current slot.


Set to SLOT_FULL if the slot is full, SLOT_EMPTY if the slot is empty (no volume in slot), SLOT_UNKNOWN if the changer doesn't know if the slot is full or not (but it can know), or undef if the changer can't know if the slot is full or not. A changer that doesn't keep state must set it to undef, like chg-single. These constants are available in the :constants export tag.

A blank or erased volume is not the same as an empty slot.


The device status after the open or read_label, undef if device status is unknown.


The file header type as returned by read_label, only if device_status is DEVICE_STATUS_SUCCESS.


The label on the volume in this slot, can be set by barcode or by read_label if f_type is Amanda::Header::F_TAPESTART.

barcode (optional)

The barcode for the volume in this slot, if barcodes are available.


Set to 1 if this slot is reserved, either by this process or another process. This is only set for exclusive reservations, meaning that loading the slot would result in an volinuse error. Devices which can support concurrent access will never set this flag.

loaded_in (optional)

For changers which have distinct user-visible drives, this gives the drive currently accessing the volume in this slot.

import_export (optional)

Set to 1 if this is an import-export slot -- a slot in which the user can easily add or remove volumes. This information may be useful for operations to bulk-import newly-inserted tapes or bulk-export a set of tapes.


  $chg->move(finished_cb => $cb,
             from_slot => $from,
             to_slot => $to)

Move a volume between two slots in the changer. These slots are provided by the user, and have meaning for the changer.




This is the changer object.


This is the fully configured device for the reserved volume. The device is not started.


This is the name of this slot. It is an arbitrary string which will have some meaning to the changer's load() method. It is safe to access this field after the reservation has been released.


If this changer supports barcodes, then this is the barcode of the reserved volume. This can be helpful for labeling tapes using their barcode.

$label = $res->make_new_tape_label()

To devise a new name for a volume. This will return undef if no label could be created.

$meta = $res->make_new_meta_label()

To devise a new meta name for a meta volume. This will return undef if no label could be created.

$res->release(finished_cb => $cb, eject => $eject)

This is how an Amanda application indicates that it no longer needs the reserved volume. The callback is called after any related operations are complete -- possibly immediately. Some drives and changers have a notion of "ejecting" a volume, and some don't. In particular, a manual changer can cause the tape drive to eject the tape, while a tape robot can move a tape back to storage, leaving the drive empty. If the eject parameter is given and true, it indicates that Amanda is done with the volume and has reason to believe the user is done with the volume, too -- for example, when a tape has been written completely.

A reservation will be released automatically when the object is destroyed, but in this case no finished_cb is given, so the release operation may not complete before the process exits. Wherever possible, reservations should be explicitly released.

$res->set_label(finished_cb => $cb, label => $label)

This is how Amanda indicates to the changer that the volume in the device has been (re-)labeled. Changers can keep a database of volume labels by slot or by barcode, or just ignore this function and call $cb immediately. Note that the reservation must still be held when this function is called.


Amanda::Changer implements some methods and attributes to help subclass implementers.


Implementing the info method can be tricky, because it can potentially request a number of keys that require asynchronous access. The info implementation in this class may make the process a bit easier.

First, if the method info_setup is defined, info calls it, passing it a finished_cb and the list of desired keys, info. This method is useful to gather information that is useful for several info keys.

Next, for each requested key, info calls

  $self->info_key($key, %params)

including a regular info_cb callback. The info method will wait for all info_key invocations to finish, then collect the results or errors that occur.


To create a new error object, use $self->make_error($type, $cb, %args). This method will create a new Amanda::Changer::Error object and optionally invoke a callback with it. If $type is fatal, then $chg->{'fatal_error'} is made a reference to the new error object. The callback $cb (which should be made using make_cb() from Amanda::MainLoop) is called with the new error object. The %args are added to the new error object. In use, this looks something like:

  if (!$success) {
    return $self->make_error("failed", $params{'res_cb'},
            reason => "notfound",
            message => "Volume '$label' not found");

This method can also be called as a class method, e.g., from a constructor. In this case, it returns the resulting error object, which should be fatal.

  if (!$config_ok) {
    return Amanda::Changer->make_error("fatal", undef,
            message => "config error");

For cases where a number of errors have occurred, it is helpful to make a "combined" error. The method make_combined_error takes care of this operation, given a callback and an array of tuples [ $description, $err ] for each error. This method uses some heuristics to figure out the appropriate type and reason for the combined error.

  if ($left_err and $right_err) {
    return $self->make_combined_error($params{'finished_cb'},
        [ [ "from the left", $left_err ],
          [ "from the right", $right_err ] ]);

Any additional keyword arguments to make_combined_error are put into the combined error; this is useful to set the slot attribute.

The method $self->check_error($cb) is a useful method for subclasses to avoid doing anything after a fatal error. This method checks $self->{'fatal_error'}. If the error is defined, the method calls $cb and returns true. The usual recipe is

  sub load {
    my $self = shift;
    my %params = @_;
    return if $self->check_error($params{'res_cb'});
    # ...


Amanda::Changer-new> calls subclass constructors with two parameters: a configuration object and a changer specification. The changer specification is the string that led to creation of this changer device. The configuration object is of type Amanda::Changer::Config, and can be treated as a hashref with the following keys:

  name                  -- name of the changer section (or "default")
  is_global             -- true if this changer is the default changer
  tapedev               -- tapedev parameter
  tpchanger             -- tpchanger parameter
  changerdev            -- changerdev parameter
  changerfile           -- changerfile parameter
  properties            -- all properties for this changer
  device_properties     -- device properties from this changer

The four parameters are just as supplied by the user, either in the global config or in a changer section. Changer authors are cautioned not to try to override any of these parameters as previous changers have done (e.g., changerfile specifying both configuration and state files). Use properties instead.

The properties and device_properties parameters are in the format provided by Amanda::Config. If is_global is true, then device_properties will include any device properties specified globally, as well as properties culled from the global tapetype.

The configure_device method generally takes care of the intricacies of handling device properties. Pass it a newly opened device and it will apply the relevant properties, returning undef on success or an error message on failure.

The get_property method is a shortcut method to get the value of a changer property, ignoring its the priority and other attributes. In a list context, it returns all values for the property; in a scalar context, it returns the first value specified.

Many properties are boolean, and Amanda has a habit of accepting a number of different ways of writing boolean values. The method $config->get_boolean_property($prop, $default) will parse such a property, returning 0 or 1 if the property is specified, $default if it is not specified, or undef if the property cannot be parsed.


Many changer subclasses need to track state across invocations and between different processes, and to ensure that the state is read and written atomically. The with_locked_state provides this functionality by locking a statefile, only unlocking it after any changes have been written back to it. Subclasses can use this method both for mutual exclusion (ensuring that only one changer operation is in progress at any time) and for atomic state storage.

The with_locked_state method works like synchronized (in Amanda::MainLoop), but with some extra arguments:

  $self->with_locked_state($filename, $some_cb, sub {
    # note: $some_cb shadows outer $some_cb; see Amanda::MainLoop::synchronized
    my ($state, $some_cb) = @_;
    # ... and eventually:

The callback $some_cb is assumed to take a changer error as its first argument, and if there are any errors locking the statefile, they will be reported directly to this callback. Otherwise, a wrapped version of $some_cb is passed to the inner sub. When this wrapper is invoked, the state will be written to disk and unlocked before the original callback is invoked.

The state itself begins as an empty hashref, but subclasses can add arbitrary keys to the hash. Serialization is currently handled with Data::Dumper.


The validate_params method is useful to make sure that the proper parameters are present for a particular method, dying if not. Call it like this:

  $self->validate_params("load", \%params);

The method currently only supports the "load" method, but can be expanded to cover other methods.


The Amanda Wiki (http://wiki.zmanda.com) has a higher-level description of the changer model implemented by this package.

See amanda-changers(7) for user-level documentation of the changer implementations.


This page was automatically generated Tue Feb 21 19:14:01 2012 from the Amanda source tree, and documents the most recent development version of Amanda. For documentation specific to the version of Amanda on your system, use the 'perldoc' command.