1 use std
::panic
::UnwindSafe
;
4 use std
::collections
::HashMap
;
6 use anyhow
::{bail, format_err, Error}
;
12 list_subdirs_api_method
,
16 section_config
::SectionConfigData
,
26 UPID_SCHEMA
, CHANGER_NAME_SCHEMA
, DRIVE_NAME_SCHEMA
, MEDIA_LABEL_SCHEMA
, MEDIA_POOL_NAME_SCHEMA
,
27 Authid
, DriveListEntry
, LtoTapeDrive
, MediaIdFlat
, LabelUuidMap
, MamAttribute
,
28 LtoDriveAndMediaStatus
, Lp17VolumeStatistics
,
31 use pbs_api_types
::{PRIV_TAPE_AUDIT, PRIV_TAPE_READ, PRIV_TAPE_WRITE}
;
32 use pbs_config
::CachedUserInfo
;
35 sg_tape
::tape_alert_flags_critical
,
36 linux_list_drives
::{lto_tape_device_list, lookup_device_identification, open_lto_tape_device}
,
38 use pbs_tools
::{task_log, task_warn}
;
39 use proxmox_rest_server
::WorkerTask
;
42 api2
::tape
::restore
::{
53 lock_unassigned_media_pool
,
63 required_media_changer
,
66 set_tape_device_state
,
67 get_tape_device_state
,
69 changer
::update_changer_online_status
,
73 fn run_drive_worker
<F
>(
74 rpcenv
: &dyn RpcEnvironment
,
77 job_id
: Option
<String
>,
79 ) -> Result
<String
, Error
>
84 + FnOnce(Arc
<WorkerTask
>, SectionConfigData
) -> Result
<(), Error
>,
86 // early check/lock before starting worker
87 let (config
, _digest
) = pbs_config
::drive
::config()?
;
88 let lock_guard
= lock_tape_device(&config
, &drive
)?
;
90 let auth_id
= rpcenv
.get_auth_id().unwrap();
91 let to_stdout
= rpcenv
.env_type() == RpcEnvironmentType
::CLI
;
93 WorkerTask
::new_thread(worker_type
, job_id
, auth_id
, to_stdout
, move |worker
| {
94 let _lock_guard
= lock_guard
;
95 set_tape_device_state(&drive
, &worker
.upid().to_string())
96 .map_err(|err
| format_err
!("could not set tape device state: {}", err
))?
;
98 let result
= f(worker
, config
);
99 set_tape_device_state(&drive
, "")
100 .map_err(|err
| format_err
!("could not unset tape device state: {}", err
))?
;
105 async
fn run_drive_blocking_task
<F
, R
>(drive
: String
, state
: String
, f
: F
) -> Result
<R
, Error
>
107 F
: Send
+ '
static + FnOnce(SectionConfigData
) -> Result
<R
, Error
>,
110 // early check/lock before starting worker
111 let (config
, _digest
) = pbs_config
::drive
::config()?
;
112 let lock_guard
= lock_tape_device(&config
, &drive
)?
;
113 tokio
::task
::spawn_blocking(move || {
114 let _lock_guard
= lock_guard
;
115 set_tape_device_state(&drive
, &state
)
116 .map_err(|err
| format_err
!("could not set tape device state: {}", err
))?
;
117 let result
= f(config
);
118 set_tape_device_state(&drive
, "")
119 .map_err(|err
| format_err
!("could not unset tape device state: {}", err
))?
;
129 schema
: DRIVE_NAME_SCHEMA
,
132 schema
: MEDIA_LABEL_SCHEMA
,
140 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
143 /// Load media with specified label
145 /// Issue a media load request to the associated changer device.
149 rpcenv
: &mut dyn RpcEnvironment
,
150 ) -> Result
<Value
, Error
> {
151 let job_id
= format
!("{}:{}", drive
, label_text
);
153 let upid_str
= run_drive_worker(
158 move |worker
, config
| {
159 task_log
!(worker
, "loading media '{}' into drive '{}'", label_text
, drive
);
160 let (mut changer
, _
) = required_media_changer(&config
, &drive
)?
;
161 changer
.load_media(&label_text
)?
;
173 schema
: DRIVE_NAME_SCHEMA
,
176 description
: "Source slot number.",
182 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
185 /// Load media from the specified slot
187 /// Issue a media load request to the associated changer device.
188 pub async
fn load_slot(drive
: String
, source_slot
: u64) -> Result
<(), Error
> {
189 run_drive_blocking_task(
191 format
!("load from slot {}", source_slot
),
193 let (mut changer
, _
) = required_media_changer(&config
, &drive
)?
;
194 changer
.load_media_from_slot(source_slot
)?
;
205 schema
: DRIVE_NAME_SCHEMA
,
208 schema
: MEDIA_LABEL_SCHEMA
,
213 description
: "The import-export slot number the media was transferred to.",
218 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
221 /// Export media with specified label
222 pub async
fn export_media(drive
: String
, label_text
: String
) -> Result
<u64, Error
> {
223 run_drive_blocking_task(
225 format
!("export media {}", label_text
),
227 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
228 match changer
.export_media(&label_text
)?
{
229 Some(slot
) => Ok(slot
),
231 "media '{}' is not online (via changer '{}')",
245 schema
: DRIVE_NAME_SCHEMA
,
248 description
: "Target slot number. If omitted, defaults to the slot that the drive was loaded from.",
258 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
261 /// Unload media via changer
264 target_slot
: Option
<u64>,
265 rpcenv
: &mut dyn RpcEnvironment
,
266 ) -> Result
<Value
, Error
> {
267 let upid_str
= run_drive_worker(
272 move |worker
, config
| {
273 task_log
!(worker
, "unloading media from drive '{}'", drive
);
275 let (mut changer
, _
) = required_media_changer(&config
, &drive
)?
;
276 changer
.unload_media(target_slot
)?
;
288 schema
: DRIVE_NAME_SCHEMA
,
291 description
: "Use fast erase.",
297 schema
: MEDIA_LABEL_SCHEMA
,
306 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_WRITE
, false),
309 /// Format media. Check for label-text if given (cancels if wrong media).
313 label_text
: Option
<String
>,
314 rpcenv
: &mut dyn RpcEnvironment
,
315 ) -> Result
<Value
, Error
> {
316 let upid_str
= run_drive_worker(
321 move |worker
, config
| {
322 if let Some(ref label
) = label_text
{
323 task_log
!(worker
, "try to load media '{}'", label
);
324 if let Some((mut changer
, _
)) = media_changer(&config
, &drive
)?
{
325 changer
.load_media(label
)?
;
329 let mut handle
= open_drive(&config
, &drive
)?
;
331 match handle
.read_label() {
333 if let Some(label
) = label_text
{
334 bail
!("expected label '{}', found unrelated data", label
);
336 /* assume drive contains no or unrelated data */
337 task_log
!(worker
, "unable to read media label: {}", err
);
338 task_log
!(worker
, "format anyways");
339 handle
.format_media(fast
.unwrap_or(true))?
;
342 if let Some(label
) = label_text
{
343 bail
!("expected label '{}', found empty tape", label
);
345 task_log
!(worker
, "found empty media - format anyways");
346 handle
.format_media(fast
.unwrap_or(true))?
;
348 Ok((Some(media_id
), _key_config
)) => {
349 if let Some(label_text
) = label_text
{
350 if media_id
.label
.label_text
!= label_text
{
352 "expected label '{}', found '{}', aborting",
354 media_id
.label
.label_text
361 "found media '{}' with uuid '{}'",
362 media_id
.label
.label_text
, media_id
.label
.uuid
,
365 let status_path
= Path
::new(TAPE_STATUS_DIR
);
366 let mut inventory
= Inventory
::new(status_path
);
368 if let Some(MediaSetLabel { ref pool, ref uuid, ..}
) = media_id
.media_set_label
{
369 let _pool_lock
= lock_media_pool(status_path
, pool
)?
;
370 let _media_set_lock
= lock_media_set(status_path
, uuid
, None
)?
;
371 MediaCatalog
::destroy(status_path
, &media_id
.label
.uuid
)?
;
372 inventory
.remove_media(&media_id
.label
.uuid
)?
;
374 let _lock
= lock_unassigned_media_pool(status_path
)?
;
375 MediaCatalog
::destroy(status_path
, &media_id
.label
.uuid
)?
;
376 inventory
.remove_media(&media_id
.label
.uuid
)?
;
379 handle
.format_media(fast
.unwrap_or(true))?
;
394 schema
: DRIVE_NAME_SCHEMA
,
402 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
408 rpcenv
: &mut dyn RpcEnvironment
,
409 ) -> Result
<Value
, Error
> {
410 let upid_str
= run_drive_worker(
415 move |_worker
, config
| {
416 let mut drive
= open_drive(&config
, &drive
)?
;
429 schema
: DRIVE_NAME_SCHEMA
,
437 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
440 /// Eject/Unload drive media
443 rpcenv
: &mut dyn RpcEnvironment
,
444 ) -> Result
<Value
, Error
> {
445 let upid_str
= run_drive_worker(
450 move |_worker
, config
| {
451 if let Some((mut changer
, _
)) = media_changer(&config
, &drive
)?
{
452 changer
.unload_media(None
)?
;
454 let mut drive
= open_drive(&config
, &drive
)?
;
455 drive
.eject_media()?
;
468 schema
: DRIVE_NAME_SCHEMA
,
471 schema
: MEDIA_LABEL_SCHEMA
,
474 schema
: MEDIA_POOL_NAME_SCHEMA
,
483 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_WRITE
, false),
488 /// Write a new media label to the media in 'drive'. The media is
489 /// assigned to the specified 'pool', or else to the free media pool.
491 /// Note: The media need to be empty (you may want to format it first).
494 pool
: Option
<String
>,
496 rpcenv
: &mut dyn RpcEnvironment
,
497 ) -> Result
<Value
, Error
> {
498 if let Some(ref pool
) = pool
{
499 let (pool_config
, _digest
) = pbs_config
::media_pool
::config()?
;
501 if pool_config
.sections
.get(pool
).is_none() {
502 bail
!("no such pool ('{}')", pool
);
505 let upid_str
= run_drive_worker(
510 move |worker
, config
| {
511 let mut drive
= open_drive(&config
, &drive
)?
;
515 match drive
.read_next_file() {
516 Ok(_reader
) => bail
!("media is not empty (format it first)"),
517 Err(BlockReadError
::EndOfFile
) => { /* EOF mark at BOT, assume tape is empty */ }
,
518 Err(BlockReadError
::EndOfStream
) => { /* tape is empty */ }
,
520 bail
!("media read error - {}", err
);
524 let ctime
= proxmox
::tools
::time
::epoch_i64();
525 let label
= MediaLabel
{
526 label_text
: label_text
.to_string(),
527 uuid
: Uuid
::generate(),
531 write_media_label(worker
, &mut drive
, label
, pool
)
538 fn write_media_label(
539 worker
: Arc
<WorkerTask
>,
540 drive
: &mut Box
<dyn TapeDriver
>,
542 pool
: Option
<String
>,
543 ) -> Result
<(), Error
> {
545 drive
.label_tape(&label
)?
;
547 let status_path
= Path
::new(TAPE_STATUS_DIR
);
549 let media_id
= if let Some(ref pool
) = pool
{
550 // assign media to pool by writing special media set label
551 task_log
!(worker
, "Label media '{}' for pool '{}'", label
.label_text
, pool
);
552 let set
= MediaSetLabel
::with_data(&pool
, [0u8; 16].into(), 0, label
.ctime
, None
);
554 drive
.write_media_set_label(&set
, None
)?
;
556 let media_id
= MediaId { label, media_set_label: Some(set) }
;
558 // Create the media catalog
559 MediaCatalog
::overwrite(status_path
, &media_id
, false)?
;
561 let mut inventory
= Inventory
::new(status_path
);
562 inventory
.store(media_id
.clone(), false)?
;
566 task_log
!(worker
, "Label media '{}' (no pool assignment)", label
.label_text
);
568 let media_id
= MediaId { label, media_set_label: None }
;
570 // Create the media catalog
571 MediaCatalog
::overwrite(status_path
, &media_id
, false)?
;
573 let mut inventory
= Inventory
::new(status_path
);
574 inventory
.store(media_id
.clone(), false)?
;
581 match drive
.read_label() {
582 Ok((Some(info
), _
)) => {
583 if info
.label
.uuid
!= media_id
.label
.uuid
{
584 bail
!("verify label failed - got wrong label uuid");
586 if let Some(ref pool
) = pool
{
587 match info
.media_set_label
{
589 if set
.uuid
!= [0u8; 16].into() {
590 bail
!("verify media set label failed - got wrong set uuid");
592 if &set
.pool
!= pool
{
593 bail
!("verify media set label failed - got wrong pool");
597 bail
!("verify media set label failed (missing set label)");
602 Ok((None
, _
)) => bail
!("verify label failed (got empty media)"),
603 Err(err
) => bail
!("verify label failed - {}", err
),
616 schema
: DRIVE_NAME_SCHEMA
,
619 description
: "Encryption key password.",
624 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
627 /// Try to restore a tape encryption key
628 pub async
fn restore_key(
631 ) -> Result
<(), Error
> {
632 run_drive_blocking_task(
634 "restore key".to_string(),
636 let mut drive
= open_drive(&config
, &drive
)?
;
638 let (_media_id
, key_config
) = drive
.read_label()?
;
640 if let Some(key_config
) = key_config
{
641 let password_fn
= || { Ok(password.as_bytes().to_vec()) }
;
642 let (key
, ..) = key_config
.decrypt(&password_fn
)?
;
643 pbs_config
::tape_encryption_keys
::insert_key(key
, key_config
, true)?
;
645 bail
!("media does not contain any encryption key configuration");
658 schema
: DRIVE_NAME_SCHEMA
,
661 description
: "Inventorize media",
670 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
673 /// Read media label (optionally inventorize media)
674 pub async
fn read_label(
676 inventorize
: Option
<bool
>,
677 ) -> Result
<MediaIdFlat
, Error
> {
678 run_drive_blocking_task(
680 "reading label".to_string(),
682 let mut drive
= open_drive(&config
, &drive
)?
;
684 let (media_id
, _key_config
) = drive
.read_label()?
;
686 let media_id
= match media_id
{
688 let mut flat
= MediaIdFlat
{
689 uuid
: media_id
.label
.uuid
.clone(),
690 label_text
: media_id
.label
.label_text
.clone(),
691 ctime
: media_id
.label
.ctime
,
692 media_set_ctime
: None
,
693 media_set_uuid
: None
,
694 encryption_key_fingerprint
: None
,
698 if let Some(ref set
) = media_id
.media_set_label
{
699 flat
.pool
= Some(set
.pool
.clone());
700 flat
.seq_nr
= Some(set
.seq_nr
);
701 flat
.media_set_uuid
= Some(set
.uuid
.clone());
702 flat
.media_set_ctime
= Some(set
.ctime
);
703 flat
.encryption_key_fingerprint
= set
704 .encryption_key_fingerprint
706 .map(|fp
| pbs_tools
::format
::as_fingerprint(fp
.bytes()));
708 let encrypt_fingerprint
= set
.encryption_key_fingerprint
.clone()
709 .map(|fp
| (fp
, set
.uuid
.clone()));
711 if let Err(err
) = drive
.set_encryption(encrypt_fingerprint
) {
712 // try, but ignore errors. just log to stderr
713 eprintln
!("unable to load encryption key: {}", err
);
717 if let Some(true) = inventorize
{
718 let state_path
= Path
::new(TAPE_STATUS_DIR
);
719 let mut inventory
= Inventory
::new(state_path
);
721 if let Some(MediaSetLabel { ref pool, ref uuid, ..}
) = media_id
.media_set_label
{
722 let _pool_lock
= lock_media_pool(state_path
, pool
)?
;
723 let _lock
= lock_media_set(state_path
, uuid
, None
)?
;
724 MediaCatalog
::destroy_unrelated_catalog(state_path
, &media_id
)?
;
725 inventory
.store(media_id
, false)?
;
727 let _lock
= lock_unassigned_media_pool(state_path
)?
;
728 MediaCatalog
::destroy(state_path
, &media_id
.label
.uuid
)?
;
729 inventory
.store(media_id
, false)?
;
736 bail
!("Media is empty (no label).");
750 schema
: DRIVE_NAME_SCHEMA
,
758 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
764 rpcenv
: &mut dyn RpcEnvironment
,
765 ) -> Result
<Value
, Error
> {
766 let upid_str
= run_drive_worker(
771 move |worker
, config
| {
772 let (mut changer
, _changer_name
) = required_media_changer(&config
, &drive
)?
;
774 task_log
!(worker
, "Starting drive clean");
776 changer
.clean_drive()?
;
778 if let Ok(drive_config
) = config
.lookup
::<LtoTapeDrive
>("lto", &drive
) {
779 // Note: clean_drive unloads the cleaning media, so we cannot use drive_config.open
780 let mut handle
= LtoTapeHandle
::new(open_lto_tape_device(&drive_config
.path
)?
)?
;
782 // test for critical tape alert flags
783 if let Ok(alert_flags
) = handle
.tape_alert_flags() {
784 if !alert_flags
.is_empty() {
785 task_log
!(worker
, "TapeAlertFlags: {:?}", alert_flags
);
786 if tape_alert_flags_critical(alert_flags
) {
787 bail
!("found critical tape alert flags: {:?}", alert_flags
);
792 // test wearout (max. 50 mounts)
793 if let Ok(volume_stats
) = handle
.volume_statistics() {
794 task_log
!(worker
, "Volume mounts: {}", volume_stats
.volume_mounts
);
795 let wearout
= volume_stats
.volume_mounts
* 2; // (*100.0/50.0);
796 task_log
!(worker
, "Cleaning tape wearout: {}%", wearout
);
800 task_log
!(worker
, "Drive cleaned successfully");
813 schema
: DRIVE_NAME_SCHEMA
,
818 description
: "The list of media labels with associated media Uuid (if any).",
825 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
828 /// List known media labels (Changer Inventory)
830 /// Note: Only useful for drives with associated changer device.
832 /// This method queries the changer to get a list of media labels.
834 /// Note: This updates the media online status.
835 pub async
fn inventory(
837 ) -> Result
<Vec
<LabelUuidMap
>, Error
> {
838 run_drive_blocking_task(
840 "inventorize".to_string(),
842 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
844 let label_text_list
= changer
.online_media_label_texts()?
;
846 let state_path
= Path
::new(TAPE_STATUS_DIR
);
848 let mut inventory
= Inventory
::load(state_path
)?
;
850 update_changer_online_status(
857 let mut list
= Vec
::new();
859 for label_text
in label_text_list
.iter() {
860 if label_text
.starts_with("CLN") {
861 // skip cleaning unit
865 let label_text
= label_text
.to_string();
867 if let Some(media_id
) = inventory
.find_media_by_label_text(&label_text
) {
868 list
.push(LabelUuidMap { label_text, uuid: Some(media_id.label.uuid.clone()) }
);
870 list
.push(LabelUuidMap { label_text, uuid: None }
);
884 schema
: DRIVE_NAME_SCHEMA
,
887 description
: "Load all tapes and try read labels (even if already inventoried)",
897 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
902 /// Note: Only useful for drives with associated changer device.
904 /// This method queries the changer to get a list of media labels. It
905 /// then loads any unknown media into the drive, reads the label, and
906 /// store the result to the media database.
908 /// Note: This updates the media online status.
909 pub fn update_inventory(
911 read_all_labels
: Option
<bool
>,
912 rpcenv
: &mut dyn RpcEnvironment
,
913 ) -> Result
<Value
, Error
> {
914 let upid_str
= run_drive_worker(
919 move |worker
, config
| {
920 let (mut changer
, changer_name
) = required_media_changer(&config
, &drive
)?
;
922 let label_text_list
= changer
.online_media_label_texts()?
;
923 if label_text_list
.is_empty() {
924 task_log
!(worker
, "changer device does not list any media labels");
927 let state_path
= Path
::new(TAPE_STATUS_DIR
);
929 let mut inventory
= Inventory
::load(state_path
)?
;
931 update_changer_online_status(&config
, &mut inventory
, &changer_name
, &label_text_list
)?
;
933 for label_text
in label_text_list
.iter() {
934 if label_text
.starts_with("CLN") {
935 task_log
!(worker
, "skip cleaning unit '{}'", label_text
);
939 let label_text
= label_text
.to_string();
941 if !read_all_labels
.unwrap_or(false) && inventory
.find_media_by_label_text(&label_text
).is_some() {
942 task_log
!(worker
, "media '{}' already inventoried", label_text
);
946 if let Err(err
) = changer
.load_media(&label_text
) {
947 task_warn
!(worker
, "unable to load media '{}' - {}", label_text
, err
);
951 let mut drive
= open_drive(&config
, &drive
)?
;
952 match drive
.read_label() {
954 task_warn
!(worker
, "unable to read label form media '{}' - {}", label_text
, err
);
957 task_log
!(worker
, "media '{}' is empty", label_text
);
959 Ok((Some(media_id
), _key_config
)) => {
960 if label_text
!= media_id
.label
.label_text
{
961 task_warn
!(worker
, "label text mismatch ({} != {})", label_text
, media_id
.label
.label_text
);
964 task_log
!(worker
, "inventorize media '{}' with uuid '{}'", label_text
, media_id
.label
.uuid
);
966 if let Some(MediaSetLabel { ref pool, ref uuid, ..}
) = media_id
.media_set_label
{
967 let _pool_lock
= lock_media_pool(state_path
, pool
)?
;
968 let _lock
= lock_media_set(state_path
, uuid
, None
)?
;
969 MediaCatalog
::destroy_unrelated_catalog(state_path
, &media_id
)?
;
970 inventory
.store(media_id
, false)?
;
972 let _lock
= lock_unassigned_media_pool(state_path
)?
;
973 MediaCatalog
::destroy(state_path
, &media_id
.label
.uuid
)?
;
974 inventory
.store(media_id
, false)?
;
978 changer
.unload_media(None
)?
;
992 schema
: DRIVE_NAME_SCHEMA
,
995 schema
: MEDIA_POOL_NAME_SCHEMA
,
1001 schema
: UPID_SCHEMA
,
1004 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_WRITE
, false),
1007 /// Label media with barcodes from changer device
1008 pub fn barcode_label_media(
1010 pool
: Option
<String
>,
1011 rpcenv
: &mut dyn RpcEnvironment
,
1012 ) -> Result
<Value
, Error
> {
1013 if let Some(ref pool
) = pool
{
1014 let (pool_config
, _digest
) = pbs_config
::media_pool
::config()?
;
1016 if pool_config
.sections
.get(pool
).is_none() {
1017 bail
!("no such pool ('{}')", pool
);
1021 let upid_str
= run_drive_worker(
1024 "barcode-label-media",
1025 Some(drive
.clone()),
1026 move |worker
, config
| barcode_label_media_worker(worker
, drive
, &config
, pool
),
1032 fn barcode_label_media_worker(
1033 worker
: Arc
<WorkerTask
>,
1035 drive_config
: &SectionConfigData
,
1036 pool
: Option
<String
>,
1037 ) -> Result
<(), Error
> {
1038 let (mut changer
, changer_name
) = required_media_changer(drive_config
, &drive
)?
;
1040 let mut label_text_list
= changer
.online_media_label_texts()?
;
1042 // make sure we label them in the right order
1043 label_text_list
.sort();
1045 let state_path
= Path
::new(TAPE_STATUS_DIR
);
1047 let mut inventory
= Inventory
::load(state_path
)?
;
1049 update_changer_online_status(drive_config
, &mut inventory
, &changer_name
, &label_text_list
)?
;
1051 if label_text_list
.is_empty() {
1052 bail
!("changer device does not list any media labels");
1055 for label_text
in label_text_list
{
1056 if label_text
.starts_with("CLN") { continue; }
1058 inventory
.reload()?
;
1059 if inventory
.find_media_by_label_text(&label_text
).is_some() {
1060 task_log
!(worker
, "media '{}' already inventoried (already labeled)", label_text
);
1064 task_log
!(worker
, "checking/loading media '{}'", label_text
);
1066 if let Err(err
) = changer
.load_media(&label_text
) {
1067 task_warn
!(worker
, "unable to load media '{}' - {}", label_text
, err
);
1071 let mut drive
= open_drive(drive_config
, &drive
)?
;
1074 match drive
.read_next_file() {
1076 task_log
!(worker
, "media '{}' is not empty (format it first)", label_text
);
1079 Err(BlockReadError
::EndOfFile
) => { /* EOF mark at BOT, assume tape is empty */ }
,
1080 Err(BlockReadError
::EndOfStream
) => { /* tape is empty */ }
,
1082 task_warn
!(worker
, "media '{}' read error (maybe not empty - format it first)", label_text
);
1087 let ctime
= proxmox
::tools
::time
::epoch_i64();
1088 let label
= MediaLabel
{
1089 label_text
: label_text
.to_string(),
1090 uuid
: Uuid
::generate(),
1094 write_media_label(worker
.clone(), &mut drive
, label
, pool
.clone())?
1104 schema
: DRIVE_NAME_SCHEMA
,
1109 description
: "A List of medium auxiliary memory attributes.",
1116 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_AUDIT
, false),
1119 /// Read Cartridge Memory (Medium auxiliary memory attributes)
1120 pub async
fn cartridge_memory(drive
: String
) -> Result
<Vec
<MamAttribute
>, Error
> {
1121 run_drive_blocking_task(
1123 "reading cartridge memory".to_string(),
1125 let drive_config
: LtoTapeDrive
= config
.lookup("lto", &drive
)?
;
1126 let mut handle
= open_lto_tape_drive(&drive_config
)?
;
1128 handle
.cartridge_memory()
1138 schema
: DRIVE_NAME_SCHEMA
,
1143 type: Lp17VolumeStatistics
,
1146 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_AUDIT
, false),
1149 /// Read Volume Statistics (SCSI log page 17h)
1150 pub async
fn volume_statistics(drive
: String
) -> Result
<Lp17VolumeStatistics
, Error
> {
1151 run_drive_blocking_task(
1153 "reading volume statistics".to_string(),
1155 let drive_config
: LtoTapeDrive
= config
.lookup("lto", &drive
)?
;
1156 let mut handle
= open_lto_tape_drive(&drive_config
)?
;
1158 handle
.volume_statistics()
1168 schema
: DRIVE_NAME_SCHEMA
,
1173 type: LtoDriveAndMediaStatus
,
1176 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_AUDIT
, false),
1179 /// Get drive/media status
1180 pub async
fn status(drive
: String
) -> Result
<LtoDriveAndMediaStatus
, Error
> {
1181 run_drive_blocking_task(
1183 "reading drive status".to_string(),
1185 let drive_config
: LtoTapeDrive
= config
.lookup("lto", &drive
)?
;
1187 // Note: use open_lto_tape_device, because this also works if no medium loaded
1188 let file
= open_lto_tape_device(&drive_config
.path
)?
;
1190 let mut handle
= LtoTapeHandle
::new(file
)?
;
1192 handle
.get_drive_and_media_status()
1202 schema
: DRIVE_NAME_SCHEMA
,
1205 description
: "Force overriding existing index.",
1210 description
: "Re-read the whole tape to reconstruct the catalog instead of restoring saved versions.",
1215 description
: "Verbose mode - log all found chunks.",
1222 schema
: UPID_SCHEMA
,
1225 permission
: &Permission
::Privilege(&["tape", "device", "{drive}"], PRIV_TAPE_READ
, false),
1228 /// Scan media and record content
1229 pub fn catalog_media(
1231 force
: Option
<bool
>,
1233 verbose
: Option
<bool
>,
1234 rpcenv
: &mut dyn RpcEnvironment
,
1235 ) -> Result
<Value
, Error
> {
1236 let verbose
= verbose
.unwrap_or(false);
1237 let force
= force
.unwrap_or(false);
1238 let scan
= scan
.unwrap_or(false);
1240 let upid_str
= run_drive_worker(
1244 Some(drive
.clone()),
1245 move |worker
, config
| {
1246 let mut drive
= open_drive(&config
, &drive
)?
;
1250 let media_id
= match drive
.read_label()?
{
1251 (Some(media_id
), key_config
) => {
1254 "found media label: {}",
1255 serde_json
::to_string_pretty(&serde_json
::to_value(&media_id
)?
)?
1257 if key_config
.is_some() {
1260 "encryption key config: {}",
1261 serde_json
::to_string_pretty(&serde_json
::to_value(&key_config
)?
)?
1266 (None
, _
) => bail
!("media is empty (no media label found)"),
1269 let status_path
= Path
::new(TAPE_STATUS_DIR
);
1271 let mut inventory
= Inventory
::new(status_path
);
1273 let (_media_set_lock
, media_set_uuid
) = match media_id
.media_set_label
{
1275 task_log
!(worker
, "media is empty");
1276 let _lock
= lock_unassigned_media_pool(status_path
)?
;
1277 MediaCatalog
::destroy(status_path
, &media_id
.label
.uuid
)?
;
1278 inventory
.store(media_id
.clone(), false)?
;
1282 if set
.uuid
.as_ref() == [0u8;16] { // media is empty
1283 task_log
!(worker
, "media is empty");
1284 let _lock
= lock_unassigned_media_pool(status_path
)?
;
1285 MediaCatalog
::destroy(status_path
, &media_id
.label
.uuid
)?
;
1286 inventory
.store(media_id
.clone(), false)?
;
1289 let encrypt_fingerprint
= set
.encryption_key_fingerprint
.clone()
1290 .map(|fp
| (fp
, set
.uuid
.clone()));
1292 drive
.set_encryption(encrypt_fingerprint
)?
;
1294 let _pool_lock
= lock_media_pool(status_path
, &set
.pool
)?
;
1295 let media_set_lock
= lock_media_set(status_path
, &set
.uuid
, None
)?
;
1297 MediaCatalog
::destroy_unrelated_catalog(status_path
, &media_id
)?
;
1299 inventory
.store(media_id
.clone(), false)?
;
1301 (media_set_lock
, &set
.uuid
)
1305 if MediaCatalog
::exists(status_path
, &media_id
.label
.uuid
) && !force
{
1306 bail
!("media catalog exists (please use --force to overwrite)");
1310 let media_set
= inventory
.compute_media_set_members(media_set_uuid
)?
;
1312 if fast_catalog_restore(&worker
, &mut drive
, &media_set
, &media_id
.label
.uuid
)?
{
1316 task_log
!(worker
, "no catalog found");
1319 task_log
!(worker
, "scanning entire media to reconstruct catalog");
1322 drive
.read_label()?
; // skip over labels - we already read them above
1324 let mut checked_chunks
= HashMap
::new();
1325 restore_media(worker
, &mut drive
, &media_id
, None
, &mut checked_chunks
, verbose
)?
;
1338 schema
: CHANGER_NAME_SCHEMA
,
1344 description
: "The list of configured drives with model information.",
1347 type: DriveListEntry
,
1351 description
: "List configured tape drives filtered by Tape.Audit privileges",
1352 permission
: &Permission
::Anybody
,
1357 changer
: Option
<String
>,
1359 rpcenv
: &mut dyn RpcEnvironment
,
1360 ) -> Result
<Vec
<DriveListEntry
>, Error
> {
1361 let auth_id
: Authid
= rpcenv
.get_auth_id().unwrap().parse()?
;
1362 let user_info
= CachedUserInfo
::new()?
;
1364 let (config
, _
) = pbs_config
::drive
::config()?
;
1366 let lto_drives
= lto_tape_device_list();
1368 let drive_list
: Vec
<LtoTapeDrive
> = config
.convert_to_typed_array("lto")?
;
1370 let mut list
= Vec
::new();
1372 for drive
in drive_list
{
1373 if changer
.is_some() && drive
.changer
!= changer
{
1377 let privs
= user_info
.lookup_privs(&auth_id
, &["tape", "drive", &drive
.name
]);
1378 if (privs
& PRIV_TAPE_AUDIT
) == 0 {
1382 let info
= lookup_device_identification(<o_drives
, &drive
.path
);
1383 let state
= get_tape_device_state(&config
, &drive
.name
)?
;
1384 let entry
= DriveListEntry { config: drive, info, state }
;
1392 pub const SUBDIRS
: SubdirMap
= &sorted
!([
1394 "barcode-label-media",
1396 .post(&API_METHOD_BARCODE_LABEL_MEDIA
)
1401 .post(&API_METHOD_CATALOG_MEDIA
)
1406 .put(&API_METHOD_CLEAN_DRIVE
)
1411 .post(&API_METHOD_EJECT_MEDIA
)
1416 .post(&API_METHOD_FORMAT_MEDIA
)
1421 .put(&API_METHOD_EXPORT_MEDIA
)
1426 .get(&API_METHOD_INVENTORY
)
1427 .put(&API_METHOD_UPDATE_INVENTORY
)
1432 .post(&API_METHOD_LABEL_MEDIA
)
1437 .post(&API_METHOD_LOAD_MEDIA
)
1442 .post(&API_METHOD_LOAD_SLOT
)
1447 .get(&API_METHOD_CARTRIDGE_MEMORY
)
1450 "volume-statistics",
1452 .get(&API_METHOD_VOLUME_STATISTICS
)
1457 .get(&API_METHOD_READ_LABEL
)
1462 .post(&API_METHOD_RESTORE_KEY
)
1467 .post(&API_METHOD_REWIND
)
1472 .get(&API_METHOD_STATUS
)
1477 .post(&API_METHOD_UNLOAD
)
1481 const ITEM_ROUTER
: Router
= Router
::new()
1482 .get(&list_subdirs_api_method
!(SUBDIRS
))
1485 pub const ROUTER
: Router
= Router
::new()
1486 .get(&API_METHOD_LIST_DRIVES
)
1487 .match_all("drive", &ITEM_ROUTER
);