4 use anyhow
::{bail, Error}
;
10 list_subdirs_api_method
,
25 drive
::check_drive_exists
,
32 MEDIA_POOL_NAME_SCHEMA
,
39 LinuxDriveAndMediaStatus
,
41 tape
::restore
::restore_media
,
51 linux_tape_device_list
,
54 required_media_changer
,
55 update_changer_online_status
,
58 open_linux_tape_device
,
71 schema
: DRIVE_NAME_SCHEMA
,
74 schema
: MEDIA_LABEL_SCHEMA
,
79 /// Load media with specified label
81 /// Issue a media load request to the associated changer device.
82 pub async
fn load_media(drive
: String
, label_text
: String
) -> Result
<(), Error
> {
84 let (config
, _digest
) = config
::drive
::config()?
;
86 tokio
::task
::spawn_blocking(move || {
87 let (mut changer
, _
) = required_media_changer(&config
, &drive
)?
;
88 changer
.load_media(&label_text
)
96 schema
: DRIVE_NAME_SCHEMA
,
99 description
: "Source slot number.",
105 /// Load media from the specified slot
107 /// Issue a media load request to the associated changer device.
108 pub async
fn load_slot(drive
: String
, source_slot
: u64) -> Result
<(), Error
> {
110 let (config
, _digest
) = config
::drive
::config()?
;
112 tokio
::task
::spawn_blocking(move || {
113 let (mut changer
, _
) = required_media_changer(&config
, &drive
)?
;
114 changer
.load_media_from_slot(source_slot
)
122 schema
: DRIVE_NAME_SCHEMA
,
125 schema
: MEDIA_LABEL_SCHEMA
,
130 description
: "The import-export slot number the media was transfered to.",
135 /// Export media with specified label
136 pub async
fn export_media(drive
: String
, label_text
: String
) -> Result
<u64, Error
> {
138 let (config
, _digest
) = config
::drive
::config()?
;
140 tokio
::task
::spawn_blocking(move || {
141 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
142 match changer
.export_media(&label_text
)?
{
143 Some(slot
) => Ok(slot
),
144 None
=> bail
!("media '{}' is not online (via changer '{}')", label_text
, changer_name
),
153 schema
: DRIVE_NAME_SCHEMA
,
156 description
: "Target slot number. If omitted, defaults to the slot that the drive was loaded from.",
163 /// Unload media via changer
166 target_slot
: Option
<u64>,
168 ) -> Result
<(), Error
> {
170 let (config
, _digest
) = config
::drive
::config()?
;
172 tokio
::task
::spawn_blocking(move || {
173 let (mut changer
, _
) = required_media_changer(&config
, &drive
)?
;
174 changer
.unload_media(target_slot
)
183 description
: "The list of autodetected tape drives.",
186 type: TapeDeviceInfo
,
191 pub fn scan_drives(_param
: Value
) -> Result
<Vec
<TapeDeviceInfo
>, Error
> {
193 let list
= linux_tape_device_list();
202 schema
: DRIVE_NAME_SCHEMA
,
205 description
: "Use fast erase.",
220 rpcenv
: &mut dyn RpcEnvironment
,
221 ) -> Result
<Value
, Error
> {
223 let (config
, _digest
) = config
::drive
::config()?
;
225 check_drive_exists(&config
, &drive
)?
; // early check before starting worker
227 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
229 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
231 let upid_str
= WorkerTask
::new_thread(
237 let mut drive
= open_drive(&config
, &drive
)?
;
238 drive
.erase_media(fast
.unwrap_or(true))?
;
250 schema
: DRIVE_NAME_SCHEMA
,
261 rpcenv
: &mut dyn RpcEnvironment
,
262 ) -> Result
<Value
, Error
> {
264 let (config
, _digest
) = config
::drive
::config()?
;
266 check_drive_exists(&config
, &drive
)?
; // early check before starting worker
268 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
270 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
272 let upid_str
= WorkerTask
::new_thread(
278 let mut drive
= open_drive(&config
, &drive
)?
;
291 schema
: DRIVE_NAME_SCHEMA
,
296 /// Eject/Unload drive media
297 pub async
fn eject_media(drive
: String
) -> Result
<(), Error
> {
299 let (config
, _digest
) = config
::drive
::config()?
;
301 tokio
::task
::spawn_blocking(move || {
302 if let Some((mut changer
, _
)) = media_changer(&config
, &drive
)?
{
303 changer
.unload_media(None
)?
;
305 let mut drive
= open_drive(&config
, &drive
)?
;
306 drive
.eject_media()?
;
316 schema
: DRIVE_NAME_SCHEMA
,
319 schema
: MEDIA_LABEL_SCHEMA
,
322 schema
: MEDIA_POOL_NAME_SCHEMA
,
333 /// Write a new media label to the media in 'drive'. The media is
334 /// assigned to the specified 'pool', or else to the free media pool.
336 /// Note: The media need to be empty (you may want to erase it first).
339 pool
: Option
<String
>,
341 rpcenv
: &mut dyn RpcEnvironment
,
342 ) -> Result
<Value
, Error
> {
344 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
346 if let Some(ref pool
) = pool
{
347 let (pool_config
, _digest
) = config
::media_pool
::config()?
;
349 if pool_config
.sections
.get(pool
).is_none() {
350 bail
!("no such pool ('{}')", pool
);
354 let (config
, _digest
) = config
::drive
::config()?
;
356 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
358 let upid_str
= WorkerTask
::new_thread(
365 let mut drive
= open_drive(&config
, &drive
)?
;
369 match drive
.read_next_file() {
370 Ok(Some(_file
)) => bail
!("media is not empty (erase first)"),
371 Ok(None
) => { /* EOF mark at BOT, assume tape is empty */ }
,
373 if err
.is_errno(nix
::errno
::Errno
::ENOSPC
) || err
.is_errno(nix
::errno
::Errno
::EIO
) {
374 /* assume tape is empty */
376 bail
!("media read error - {}", err
);
381 let ctime
= proxmox
::tools
::time
::epoch_i64();
382 let label
= MediaLabel
{
383 label_text
: label_text
.to_string(),
384 uuid
: Uuid
::generate(),
388 write_media_label(worker
, &mut drive
, label
, pool
)
395 fn write_media_label(
396 worker
: Arc
<WorkerTask
>,
397 drive
: &mut Box
<dyn TapeDriver
>,
399 pool
: Option
<String
>,
400 ) -> Result
<(), Error
> {
402 drive
.label_tape(&label
)?
;
404 let mut media_set_label
= None
;
406 if let Some(ref pool
) = pool
{
407 // assign media to pool by writing special media set label
408 worker
.log(format
!("Label media '{}' for pool '{}'", label
.label_text
, pool
));
409 let set
= MediaSetLabel
::with_data(&pool
, [0u8; 16].into(), 0, label
.ctime
);
411 drive
.write_media_set_label(&set
)?
;
412 media_set_label
= Some(set
);
414 worker
.log(format
!("Label media '{}' (no pool assignment)", label
.label_text
));
417 let media_id
= MediaId { label, media_set_label }
;
419 let status_path
= Path
::new(TAPE_STATUS_DIR
);
421 // Create the media catalog
422 MediaCatalog
::overwrite(status_path
, &media_id
, false)?
;
424 let mut inventory
= Inventory
::load(status_path
)?
;
425 inventory
.store(media_id
.clone(), false)?
;
429 match drive
.read_label() {
431 if info
.label
.uuid
!= media_id
.label
.uuid
{
432 bail
!("verify label failed - got wrong label uuid");
434 if let Some(ref pool
) = pool
{
435 match info
.media_set_label
{
437 if set
.uuid
!= [0u8; 16].into() {
438 bail
!("verify media set label failed - got wrong set uuid");
440 if &set
.pool
!= pool
{
441 bail
!("verify media set label failed - got wrong pool");
445 bail
!("verify media set label failed (missing set label)");
450 Ok(None
) => bail
!("verify label failed (got empty media)"),
451 Err(err
) => bail
!("verify label failed - {}", err
),
463 schema
: DRIVE_NAME_SCHEMA
,
466 description
: "Inventorize media",
476 pub async
fn read_label(
478 inventorize
: Option
<bool
>,
479 ) -> Result
<MediaIdFlat
, Error
> {
481 let (config
, _digest
) = config
::drive
::config()?
;
483 tokio
::task
::spawn_blocking(move || {
484 let mut drive
= open_drive(&config
, &drive
)?
;
486 let media_id
= drive
.read_label()?
;
488 let media_id
= match media_id
{
490 let mut flat
= MediaIdFlat
{
491 uuid
: media_id
.label
.uuid
.to_string(),
492 label_text
: media_id
.label
.label_text
.clone(),
493 ctime
: media_id
.label
.ctime
,
494 media_set_ctime
: None
,
495 media_set_uuid
: None
,
499 if let Some(ref set
) = media_id
.media_set_label
{
500 flat
.pool
= Some(set
.pool
.clone());
501 flat
.seq_nr
= Some(set
.seq_nr
);
502 flat
.media_set_uuid
= Some(set
.uuid
.to_string());
503 flat
.media_set_ctime
= Some(set
.ctime
);
506 if let Some(true) = inventorize
{
507 let state_path
= Path
::new(TAPE_STATUS_DIR
);
508 let mut inventory
= Inventory
::load(state_path
)?
;
509 inventory
.store(media_id
, false)?
;
515 bail
!("Media is empty (no label).");
527 schema
: DRIVE_NAME_SCHEMA
,
538 rpcenv
: &mut dyn RpcEnvironment
,
539 ) -> Result
<Value
, Error
> {
541 let (config
, _digest
) = config
::drive
::config()?
;
543 check_drive_exists(&config
, &drive
)?
; // early check before starting worker
545 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
547 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
549 let upid_str
= WorkerTask
::new_thread(
556 let (mut changer
, _changer_name
) = required_media_changer(&config
, &drive
)?
;
558 worker
.log("Starting drive clean");
560 changer
.clean_drive()?
;
562 worker
.log("Drive cleaned sucessfully");
574 schema
: DRIVE_NAME_SCHEMA
,
579 description
: "The list of media labels with associated media Uuid (if any).",
586 /// List known media labels (Changer Inventory)
588 /// Note: Only useful for drives with associated changer device.
590 /// This method queries the changer to get a list of media labels.
592 /// Note: This updates the media online status.
593 pub async
fn inventory(
595 ) -> Result
<Vec
<LabelUuidMap
>, Error
> {
597 let (config
, _digest
) = config
::drive
::config()?
;
599 tokio
::task
::spawn_blocking(move || {
600 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
602 let label_text_list
= changer
.online_media_label_texts()?
;
604 let state_path
= Path
::new(TAPE_STATUS_DIR
);
606 let mut inventory
= Inventory
::load(state_path
)?
;
608 update_changer_online_status(
615 let mut list
= Vec
::new();
617 for label_text
in label_text_list
.iter() {
618 if label_text
.starts_with("CLN") {
619 // skip cleaning unit
623 let label_text
= label_text
.to_string();
625 if let Some(media_id
) = inventory
.find_media_by_label_text(&label_text
) {
626 list
.push(LabelUuidMap { label_text, uuid: Some(media_id.label.uuid.to_string()) }
);
628 list
.push(LabelUuidMap { label_text, uuid: None }
);
640 schema
: DRIVE_NAME_SCHEMA
,
643 description
: "Load all tapes and try read labels (even if already inventoried)",
655 /// Note: Only useful for drives with associated changer device.
657 /// This method queries the changer to get a list of media labels. It
658 /// then loads any unknown media into the drive, reads the label, and
659 /// store the result to the media database.
661 /// Note: This updates the media online status.
662 pub fn update_inventory(
664 read_all_labels
: Option
<bool
>,
665 rpcenv
: &mut dyn RpcEnvironment
,
666 ) -> Result
<Value
, Error
> {
668 let (config
, _digest
) = config
::drive
::config()?
;
670 check_drive_exists(&config
, &drive
)?
; // early check before starting worker
672 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
674 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
676 let upid_str
= WorkerTask
::new_thread(
683 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
685 let label_text_list
= changer
.online_media_label_texts()?
;
686 if label_text_list
.is_empty() {
687 worker
.log(format
!("changer device does not list any media labels"));
690 let state_path
= Path
::new(TAPE_STATUS_DIR
);
692 let mut inventory
= Inventory
::load(state_path
)?
;
694 update_changer_online_status(&config
, &mut inventory
, &changer_name
, &label_text_list
)?
;
696 for label_text
in label_text_list
.iter() {
697 if label_text
.starts_with("CLN") {
698 worker
.log(format
!("skip cleaning unit '{}'", label_text
));
702 let label_text
= label_text
.to_string();
704 if !read_all_labels
.unwrap_or(false) {
705 if let Some(_
) = inventory
.find_media_by_label_text(&label_text
) {
706 worker
.log(format
!("media '{}' already inventoried", label_text
));
711 if let Err(err
) = changer
.load_media(&label_text
) {
712 worker
.warn(format
!("unable to load media '{}' - {}", label_text
, err
));
716 let mut drive
= open_drive(&config
, &drive
)?
;
717 match drive
.read_label() {
719 worker
.warn(format
!("unable to read label form media '{}' - {}", label_text
, err
));
722 worker
.log(format
!("media '{}' is empty", label_text
));
724 Ok(Some(media_id
)) => {
725 if label_text
!= media_id
.label
.label_text
{
726 worker
.warn(format
!("label text missmatch ({} != {})", label_text
, media_id
.label
.label_text
));
729 worker
.log(format
!("inventorize media '{}' with uuid '{}'", label_text
, media_id
.label
.uuid
));
730 inventory
.store(media_id
, false)?
;
733 changer
.unload_media(None
)?
;
747 schema
: DRIVE_NAME_SCHEMA
,
750 schema
: MEDIA_POOL_NAME_SCHEMA
,
759 /// Label media with barcodes from changer device
760 pub fn barcode_label_media(
762 pool
: Option
<String
>,
763 rpcenv
: &mut dyn RpcEnvironment
,
764 ) -> Result
<Value
, Error
> {
766 if let Some(ref pool
) = pool
{
767 let (pool_config
, _digest
) = config
::media_pool
::config()?
;
769 if pool_config
.sections
.get(pool
).is_none() {
770 bail
!("no such pool ('{}')", pool
);
774 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
776 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
778 let upid_str
= WorkerTask
::new_thread(
779 "barcode-label-media",
784 barcode_label_media_worker(worker
, drive
, pool
)
791 fn barcode_label_media_worker(
792 worker
: Arc
<WorkerTask
>,
794 pool
: Option
<String
>,
795 ) -> Result
<(), Error
> {
797 let (config
, _digest
) = config
::drive
::config()?
;
799 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
801 let label_text_list
= changer
.online_media_label_texts()?
;
803 let state_path
= Path
::new(TAPE_STATUS_DIR
);
805 let mut inventory
= Inventory
::load(state_path
)?
;
807 update_changer_online_status(&config
, &mut inventory
, &changer_name
, &label_text_list
)?
;
809 if label_text_list
.is_empty() {
810 bail
!("changer device does not list any media labels");
813 for label_text
in label_text_list
{
814 if label_text
.starts_with("CLN") { continue; }
817 if inventory
.find_media_by_label_text(&label_text
).is_some() {
818 worker
.log(format
!("media '{}' already inventoried (already labeled)", label_text
));
822 worker
.log(format
!("checking/loading media '{}'", label_text
));
824 if let Err(err
) = changer
.load_media(&label_text
) {
825 worker
.warn(format
!("unable to load media '{}' - {}", label_text
, err
));
829 let mut drive
= open_drive(&config
, &drive
)?
;
832 match drive
.read_next_file() {
834 worker
.log(format
!("media '{}' is not empty (erase first)", label_text
));
837 Ok(None
) => { /* EOF mark at BOT, assume tape is empty */ }
,
839 if err
.is_errno(nix
::errno
::Errno
::ENOSPC
) || err
.is_errno(nix
::errno
::Errno
::EIO
) {
840 /* assume tape is empty */
842 worker
.warn(format
!("media '{}' read error (maybe not empty - erase first)", label_text
));
848 let ctime
= proxmox
::tools
::time
::epoch_i64();
849 let label
= MediaLabel
{
850 label_text
: label_text
.to_string(),
851 uuid
: Uuid
::generate(),
855 write_media_label(worker
.clone(), &mut drive
, label
, pool
.clone())?
865 schema
: DRIVE_NAME_SCHEMA
,
870 description
: "A List of medium auxiliary memory attributes.",
877 /// Read Cartridge Memory (Medium auxiliary memory attributes)
878 pub fn cartridge_memory(drive
: String
) -> Result
<Vec
<MamAttribute
>, Error
> {
880 let (config
, _digest
) = config
::drive
::config()?
;
882 let drive_config
: LinuxTapeDrive
= config
.lookup("linux", &drive
)?
;
883 let mut handle
= drive_config
.open()?
;
885 handle
.cartridge_memory()
892 schema
: DRIVE_NAME_SCHEMA
,
897 type: LinuxDriveAndMediaStatus
,
900 /// Get drive/media status
901 pub fn status(drive
: String
) -> Result
<LinuxDriveAndMediaStatus
, Error
> {
903 let (config
, _digest
) = config
::drive
::config()?
;
905 let drive_config
: LinuxTapeDrive
= config
.lookup("linux", &drive
)?
;
907 // Note: use open_linux_tape_device, because this also works if no medium loaded
908 let file
= open_linux_tape_device(&drive_config
.path
)?
;
910 let mut handle
= LinuxTapeHandle
::new(file
);
912 handle
.get_drive_and_media_status()
919 schema
: DRIVE_NAME_SCHEMA
,
922 description
: "Force overriding existing index.",
927 description
: "Verbose mode - log all found chunks.",
937 /// Scan media and record content
938 pub fn catalog_media(
941 verbose
: Option
<bool
>,
942 rpcenv
: &mut dyn RpcEnvironment
,
943 ) -> Result
<Value
, Error
> {
945 let verbose
= verbose
.unwrap_or(false);
946 let force
= force
.unwrap_or(false);
948 let (config
, _digest
) = config
::drive
::config()?
;
950 check_drive_exists(&config
, &drive
)?
; // early check before starting worker
952 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
954 let to_stdout
= if rpcenv
.env_type() == RpcEnvironmentType
::CLI { true }
else { false }
;
956 let upid_str
= WorkerTask
::new_thread(
963 let mut drive
= open_drive(&config
, &drive
)?
;
967 let media_id
= match drive
.read_label()?
{
970 "found media label: {}",
971 serde_json
::to_string_pretty(&serde_json
::to_value(&media_id
)?
)?
975 None
=> bail
!("media is empty (no media label found)"),
978 let status_path
= Path
::new(TAPE_STATUS_DIR
);
980 let mut inventory
= Inventory
::load(status_path
)?
;
981 inventory
.store(media_id
.clone(), false)?
;
983 let pool
= match media_id
.media_set_label
{
985 worker
.log("media is empty");
986 MediaCatalog
::destroy(status_path
, &media_id
.label
.uuid
)?
;
990 if set
.uuid
.as_ref() == [0u8;16] { // media is empty
991 worker
.log("media is empty");
992 MediaCatalog
::destroy(status_path
, &media_id
.label
.uuid
)?
;
999 let _lock
= MediaPool
::lock(status_path
, &pool
)?
;
1001 if MediaCatalog
::exists(status_path
, &media_id
.label
.uuid
) {
1003 bail
!("media catalog exists (please use --force to overwrite)");
1007 restore_media(&worker
, &mut drive
, &media_id
, None
, verbose
)?
;
1018 pub const SUBDIRS
: SubdirMap
= &sorted
!([
1020 "barcode-label-media",
1022 .put(&API_METHOD_BARCODE_LABEL_MEDIA
)
1027 .put(&API_METHOD_CATALOG_MEDIA
)
1032 .put(&API_METHOD_CLEAN_DRIVE
)
1037 .put(&API_METHOD_EJECT_MEDIA
)
1042 .put(&API_METHOD_ERASE_MEDIA
)
1047 .get(&API_METHOD_INVENTORY
)
1048 .put(&API_METHOD_UPDATE_INVENTORY
)
1053 .put(&API_METHOD_LABEL_MEDIA
)
1058 .put(&API_METHOD_LOAD_SLOT
)
1063 .put(&API_METHOD_CARTRIDGE_MEMORY
)
1068 .get(&API_METHOD_READ_LABEL
)
1073 .put(&API_METHOD_REWIND
)
1078 .get(&API_METHOD_SCAN_DRIVES
)
1083 .get(&API_METHOD_STATUS
)
1088 .put(&API_METHOD_UNLOAD
)
1092 pub const ROUTER
: Router
= Router
::new()
1093 .get(&list_subdirs_api_method
!(SUBDIRS
))