1 // Note: This is only for test an debug
6 use anyhow
::{bail, format_err, Error}
;
7 use serde
::{Serialize, Deserialize}
;
10 fs
::{replace_file, CreateOptions}
,
13 use pbs_datastore
::key_derivation
::KeyConfig
;
34 PROXMOX_BACKUP_MEDIA_SET_LABEL_MAGIC_1_0
,
45 /// This needs to lock the drive
46 pub fn open_virtual_tape_drive(config
: &VirtualTapeDrive
) -> Result
<VirtualTapeHandle
, Error
> {
48 let mut lock_path
= std
::path
::PathBuf
::from(&config
.path
);
49 lock_path
.push(".drive.lck");
51 let options
= CreateOptions
::new();
52 let timeout
= std
::time
::Duration
::new(10, 0);
53 let lock
= proxmox
::tools
::fs
::open_file_locked(&lock_path
, timeout
, true, options
)?
;
55 Ok(VirtualTapeHandle
{
57 drive_name
: config
.name
.clone(),
58 max_size
: config
.max_size
.unwrap_or(64*1024*1024),
59 path
: std
::path
::PathBuf
::from(&config
.path
),
61 }).map_err(|err
: Error
| format_err
!("open drive '{}' ({}) failed - {}", config
.name
, config
.path
, err
))
64 #[derive(Serialize,Deserialize)]
65 struct VirtualTapeStatus
{
70 #[derive(Serialize,Deserialize)]
71 struct VirtualDriveStatus
{
72 current_tape
: Option
<VirtualTapeStatus
>,
75 #[derive(Serialize,Deserialize)]
80 pub struct VirtualTapeHandle
{
82 path
: std
::path
::PathBuf
,
87 impl VirtualTapeHandle
{
89 fn status_file_path(&self) -> std
::path
::PathBuf
{
90 let mut path
= self.path
.clone();
91 path
.push("drive-status.json");
95 fn tape_index_path(&self, tape_name
: &str) -> std
::path
::PathBuf
{
96 let mut path
= self.path
.clone();
97 path
.push(format
!("tape-{}.json", tape_name
));
101 fn tape_file_path(&self, tape_name
: &str, pos
: usize) -> std
::path
::PathBuf
{
102 let mut path
= self.path
.clone();
103 path
.push(format
!("tapefile-{}-{}.json", pos
, tape_name
));
107 fn load_tape_index(&self, tape_name
: &str) -> Result
<TapeIndex
, Error
> {
108 let path
= self.tape_index_path(tape_name
);
109 let raw
= proxmox
::tools
::fs
::file_get_contents(&path
)?
;
111 return Ok(TapeIndex { files: 0 }
);
113 let data
: TapeIndex
= serde_json
::from_slice(&raw
)?
;
117 fn store_tape_index(&self, tape_name
: &str, index
: &TapeIndex
) -> Result
<(), Error
> {
118 let path
= self.tape_index_path(tape_name
);
119 let raw
= serde_json
::to_string_pretty(&serde_json
::to_value(index
)?
)?
;
121 let options
= CreateOptions
::new();
122 replace_file(&path
, raw
.as_bytes(), options
)?
;
126 fn truncate_tape(&self, tape_name
: &str, pos
: usize) -> Result
<usize, Error
> {
127 let mut index
= self.load_tape_index(tape_name
)?
;
129 if index
.files
<= pos
{
130 return Ok(index
.files
)
133 for i
in pos
..index
.files
{
134 let path
= self.tape_file_path(tape_name
, i
);
135 let _
= std
::fs
::remove_file(path
);
140 self.store_tape_index(tape_name
, &index
)?
;
145 fn load_status(&self) -> Result
<VirtualDriveStatus
, Error
> {
146 let path
= self.status_file_path();
148 let default = serde_json
::to_value(VirtualDriveStatus
{
152 let data
= proxmox
::tools
::fs
::file_get_json(&path
, Some(default))?
;
153 let status
: VirtualDriveStatus
= serde_json
::from_value(data
)?
;
157 fn store_status(&self, status
: &VirtualDriveStatus
) -> Result
<(), Error
> {
158 let path
= self.status_file_path();
159 let raw
= serde_json
::to_string_pretty(&serde_json
::to_value(status
)?
)?
;
161 let options
= CreateOptions
::new();
162 replace_file(&path
, raw
.as_bytes(), options
)?
;
166 fn online_media_label_texts(&self) -> Result
<Vec
<String
>, Error
> {
167 let mut list
= Vec
::new();
168 for entry
in std
::fs
::read_dir(&self.path
)?
{
170 let path
= entry
.path();
171 if path
.is_file() && path
.extension() == Some(std
::ffi
::OsStr
::new("json")) {
172 if let Some(name
) = path
.file_stem() {
173 if let Some(name
) = name
.to_str() {
174 if let Some(label
) = name
.strip_prefix("tape-") {
175 list
.push(label
.to_string());
185 fn forward_space_count_files(&mut self, count
: usize) -> Result
<(), Error
> {
186 let mut status
= self.load_status()?
;
187 match status
.current_tape
{
188 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
190 let index
= self.load_tape_index(name
)
191 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
193 let new_pos
= *pos
+ count
;
194 if new_pos
<= index
.files
{
197 bail
!("forward_space_count_files failed: move beyond EOT");
200 self.store_status(&status
)
201 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
205 None
=> bail
!("drive is empty (no tape loaded)."),
209 // Note: behavior differs from LTO, because we always position at
211 fn backward_space_count_files(&mut self, count
: usize) -> Result
<(), Error
> {
212 let mut status
= self.load_status()?
;
213 match status
.current_tape
{
214 Some(VirtualTapeStatus { ref mut pos, .. }
) => {
219 bail
!("backward_space_count_files failed: move before BOT");
222 self.store_status(&status
)
223 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
227 None
=> bail
!("drive is empty (no tape loaded)."),
233 impl TapeDriver
for VirtualTapeHandle
{
235 fn sync(&mut self) -> Result
<(), Error
> {
236 Ok(()) // do nothing for now
239 fn current_file_number(&mut self) -> Result
<u64, Error
> {
240 let status
= self.load_status()
241 .map_err(|err
| format_err
!("current_file_number failed: {}", err
.to_string()))?
;
243 match status
.current_tape
{
244 Some(VirtualTapeStatus { pos, .. }
) => { Ok(pos as u64)}
,
245 None
=> bail
!("current_file_number failed: drive is empty (no tape loaded)."),
249 /// Move to last file
250 fn move_to_last_file(&mut self) -> Result
<(), Error
> {
252 self.move_to_eom(false)?
;
254 if self.current_file_number()?
== 0 {
255 bail
!("move_to_last_file failed - media contains no data");
258 self.backward_space_count_files(1)?
;
263 fn move_to_file(&mut self, file
: u64) -> Result
<(), Error
> {
264 let mut status
= self.load_status()?
;
265 match status
.current_tape
{
266 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
268 let index
= self.load_tape_index(name
)
269 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
271 if file
as usize > index
.files
{
272 bail
!("invalid file nr");
275 *pos
= file
as usize;
277 self.store_status(&status
)
278 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
282 None
=> bail
!("drive is empty (no tape loaded)."),
286 fn read_next_file(&mut self) -> Result
<Box
<dyn TapeRead
>, BlockReadError
> {
287 let mut status
= self.load_status()
288 .map_err(|err
| BlockReadError
::Error(io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string())))?
;
290 match status
.current_tape
{
291 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
293 let index
= self.load_tape_index(name
)
294 .map_err(|err
| BlockReadError
::Error(io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string())))?
;
296 if *pos
>= index
.files
{
297 return Err(BlockReadError
::EndOfStream
);
300 let path
= self.tape_file_path(name
, *pos
);
301 let file
= std
::fs
::OpenOptions
::new()
306 self.store_status(&status
)
307 .map_err(|err
| BlockReadError
::Error(io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string())))?
;
309 let reader
= EmulateTapeReader
::new(file
);
310 let reader
= BlockedReader
::open(reader
)?
;
314 return Err(BlockReadError
::Error(proxmox
::io_format_err
!("drive is empty (no tape loaded).")));
319 fn write_file(&mut self) -> Result
<Box
<dyn TapeWrite
>, io
::Error
> {
320 let mut status
= self.load_status()
321 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
323 match status
.current_tape
{
324 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
326 let mut index
= self.load_tape_index(name
)
327 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
329 for i
in *pos
..index
.files
{
330 let path
= self.tape_file_path(name
, i
);
331 let _
= std
::fs
::remove_file(path
);
334 let mut used_space
= 0;
336 let path
= self.tape_file_path(name
, i
);
337 used_space
+= path
.metadata()?
.len() as usize;
340 index
.files
= *pos
+ 1;
342 self.store_tape_index(name
, &index
)
343 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
345 let path
= self.tape_file_path(name
, *pos
);
346 let file
= std
::fs
::OpenOptions
::new()
354 self.store_status(&status
)
355 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
357 let mut free_space
= 0;
358 if used_space
< self.max_size
{
359 free_space
= self.max_size
- used_space
;
362 let writer
= EmulateTapeWriter
::new(file
, free_space
);
363 let writer
= Box
::new(BlockedWriter
::new(writer
));
367 None
=> proxmox
::io_bail
!("drive is empty (no tape loaded)."),
371 fn move_to_eom(&mut self, _write_missing_eof
: bool
) -> Result
<(), Error
> {
372 let mut status
= self.load_status()?
;
373 match status
.current_tape
{
374 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
376 let index
= self.load_tape_index(name
)
377 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
381 self.store_status(&status
)
382 .map_err(|err
| io
::Error
::new(io
::ErrorKind
::Other
, err
.to_string()))?
;
386 None
=> bail
!("drive is empty (no tape loaded)."),
390 fn rewind(&mut self) -> Result
<(), Error
> {
391 let mut status
= self.load_status()?
;
392 match status
.current_tape
{
393 Some(ref mut tape_status
) => {
395 self.store_status(&status
)?
;
398 None
=> bail
!("drive is empty (no tape loaded)."),
402 fn format_media(&mut self, _fast
: bool
) -> Result
<(), Error
> {
403 let mut status
= self.load_status()?
;
404 match status
.current_tape
{
405 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
406 *pos
= self.truncate_tape(name
, 0)?
;
407 self.store_status(&status
)?
;
410 None
=> bail
!("drive is empty (no tape loaded)."),
414 fn write_media_set_label(
416 media_set_label
: &MediaSetLabel
,
417 key_config
: Option
<&KeyConfig
>,
418 ) -> Result
<(), Error
> {
420 self.set_encryption(None
)?
;
422 if key_config
.is_some() {
423 bail
!("encryption is not implemented - internal error");
426 let mut status
= self.load_status()?
;
427 match status
.current_tape
{
428 Some(VirtualTapeStatus { ref name, ref mut pos }
) => {
429 *pos
= self.truncate_tape(name
, 1)?
;
431 self.store_status(&status
)?
;
434 bail
!("media is empty (no label).");
437 bail
!("write_media_set_label: truncate failed - got wrong pos '{}'", pos
);
440 let raw
= serde_json
::to_string_pretty(&serde_json
::to_value(media_set_label
)?
)?
;
441 let header
= MediaContentHeader
::new(PROXMOX_BACKUP_MEDIA_SET_LABEL_MAGIC_1_0
, raw
.len() as u32);
444 let mut writer
= self.write_file()?
;
445 writer
.write_header(&header
, raw
.as_bytes())?
;
446 writer
.finish(false)?
;
451 None
=> bail
!("drive is empty (no tape loaded)."),
455 fn eject_media(&mut self) -> Result
<(), Error
> {
456 let status
= VirtualDriveStatus
{
459 self.store_status(&status
)
463 impl MediaChange
for VirtualTapeHandle
{
465 fn drive_number(&self) -> u64 {
469 fn drive_name(&self) -> &str {
473 fn status(&mut self) -> Result
<MtxStatus
, Error
> {
475 let drive_status
= self.load_status()?
;
477 let mut drives
= Vec
::new();
479 if let Some(current_tape
) = &drive_status
.current_tape
{
480 drives
.push(DriveStatus
{
482 status
: ElementStatus
::VolumeTag(current_tape
.name
.clone()),
483 drive_serial_number
: None
,
490 // This implementation is lame, because we do not have fixed
491 // slot-assignment here.
493 let mut slots
= Vec
::new();
494 let label_texts
= self.online_media_label_texts()?
;
495 let max_slots
= ((label_texts
.len() + 7)/8) * 8;
497 for i
in 0..max_slots
{
498 let status
= if let Some(label_text
) = label_texts
.get(i
) {
499 ElementStatus
::VolumeTag(label_text
.clone())
503 slots
.push(StorageElementStatus
{
504 import_export
: false,
506 element_address
: (i
+ 1) as u16,
510 Ok(MtxStatus { drives, slots, transports: Vec::new() }
)
513 fn transfer_media(&mut self, _from
: u64, _to
: u64) -> Result
<MtxStatus
, Error
> {
514 bail
!("media transfer is not implemented!");
517 fn export_media(&mut self, _label_text
: &str) -> Result
<Option
<u64>, Error
> {
518 bail
!("media export is not implemented!");
521 fn load_media_from_slot(&mut self, slot
: u64) -> Result
<MtxStatus
, Error
> {
523 bail
!("invalid slot ID {}", slot
);
526 let label_texts
= self.online_media_label_texts()?
;
528 if slot
> label_texts
.len() as u64 {
529 bail
!("slot {} is empty", slot
);
532 self.load_media(&label_texts
[slot
as usize - 1])
535 /// Try to load media
537 /// We automatically create an empty virtual tape here (if it does
538 /// not exist already)
539 fn load_media(&mut self, label
: &str) -> Result
<MtxStatus
, Error
> {
540 let name
= format
!("tape-{}.json", label
);
541 let mut path
= self.path
.clone();
544 eprintln
!("unable to find tape {} - creating file {:?}", label
, path
);
545 let index
= TapeIndex { files: 0 }
;
546 self.store_tape_index(label
, &index
)?
;
549 let status
= VirtualDriveStatus
{
550 current_tape
: Some(VirtualTapeStatus
{
551 name
: label
.to_string(),
555 self.store_status(&status
)?
;
560 fn unload_media(&mut self, _target_slot
: Option
<u64>) -> Result
<MtxStatus
, Error
> {
561 // Note: we currently simply ignore target_slot
566 fn clean_drive(&mut self) -> Result
<MtxStatus
, Error
> {
572 impl MediaChange
for VirtualTapeDrive
{
574 fn drive_number(&self) -> u64 {
578 fn drive_name(&self) -> &str {
582 fn status(&mut self) -> Result
<MtxStatus
, Error
> {
583 let mut handle
= open_virtual_tape_drive(self)?
;
587 fn transfer_media(&mut self, from
: u64, to
: u64) -> Result
<MtxStatus
, Error
> {
588 let mut handle
= open_virtual_tape_drive(self)?
;
589 handle
.transfer_media(from
, to
)
592 fn export_media(&mut self, label_text
: &str) -> Result
<Option
<u64>, Error
> {
593 let mut handle
= open_virtual_tape_drive(self)?
;
594 handle
.export_media(label_text
)
597 fn load_media_from_slot(&mut self, slot
: u64) -> Result
<MtxStatus
, Error
> {
598 let mut handle
= open_virtual_tape_drive(self)?
;
599 handle
.load_media_from_slot(slot
)
602 fn load_media(&mut self, label_text
: &str) -> Result
<MtxStatus
, Error
> {
603 let mut handle
= open_virtual_tape_drive(self)?
;
604 handle
.load_media(label_text
)
607 fn unload_media(&mut self, target_slot
: Option
<u64>) -> Result
<MtxStatus
, Error
> {
608 let mut handle
= open_virtual_tape_drive(self)?
;
609 handle
.unload_media(target_slot
)
612 fn online_media_label_texts(&mut self) -> Result
<Vec
<String
>, Error
> {
613 let handle
= open_virtual_tape_drive(self)?
;
614 handle
.online_media_label_texts()
617 fn clean_drive(&mut self) -> Result
<MtxStatus
, Error
> {
618 let mut handle
= open_virtual_tape_drive(self)?
;