]> git.proxmox.com Git - proxmox-backup.git/blobdiff - src/bin/proxmox-backup-client.rs
src/bin/proxmox-backup-client.rs: implement image/block-device upload
[proxmox-backup.git] / src / bin / proxmox-backup-client.rs
index c05d0f13478adbc47b167a01601523d886fcc8b1..545c208d7e2e13ae1000de20cca7d7ec420b7744 100644 (file)
@@ -3,7 +3,8 @@ extern crate proxmox_backup;
 use failure::*;
 //use std::os::unix::io::AsRawFd;
 use chrono::{DateTime, Local, TimeZone};
-use std::path::Path;
+use std::path::{Path, PathBuf};
+use std::collections::HashMap;
 
 use proxmox_backup::tools;
 use proxmox_backup::cli::*;
@@ -13,50 +14,154 @@ use proxmox_backup::client::*;
 use proxmox_backup::backup::*;
 //use proxmox_backup::backup::image_index::*;
 //use proxmox_backup::config::datastore;
-//use proxmox_backup::catar::encoder::*;
+//use proxmox_backup::pxar::encoder::*;
 //use proxmox_backup::backup::datastore::*;
 
 use serde_json::{json, Value};
 use hyper::Body;
 use std::sync::Arc;
 use regex::Regex;
+use xdg::BaseDirectories;
 
 use lazy_static::lazy_static;
+use futures::*;
+use tokio::sync::mpsc;
 
 lazy_static! {
-    static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+):(.+)$").unwrap();
+    static ref BACKUPSPEC_REGEX: Regex = Regex::new(r"^([a-zA-Z0-9_-]+\.(?:pxar|img)):(.+)$").unwrap();
+}
+
+
+fn record_repository(repo: &BackupRepository) {
+
+    let base = match BaseDirectories::with_prefix("proxmox-backup") {
+        Ok(v) => v,
+        _ => return,
+    };
+
+    // usually $HOME/.cache/proxmox-backup/repo-list
+    let path = match base.place_cache_file("repo-list") {
+        Ok(v) => v,
+        _ => return,
+    };
+
+    let mut data = tools::file_get_json(&path, None).unwrap_or(json!({}));
+
+    let repo = repo.to_string();
+
+    data[&repo] = json!{ data[&repo].as_i64().unwrap_or(0) + 1 };
+
+    let mut map = serde_json::map::Map::new();
+
+    loop {
+        let mut max_used = 0;
+        let mut max_repo = None;
+        for (repo, count) in data.as_object().unwrap() {
+            if map.contains_key(repo) { continue; }
+            if let Some(count) = count.as_i64() {
+                if count > max_used {
+                    max_used = count;
+                    max_repo = Some(repo);
+                }
+            }
+        }
+        if let Some(repo) = max_repo {
+            map.insert(repo.to_owned(), json!(max_used));
+        } else {
+            break;
+        }
+        if map.len() > 10 { // store max. 10 repos
+            break;
+        }
+    }
+
+    let new_data = json!(map);
+
+    let _ = tools::file_set_contents(path, new_data.to_string().as_bytes(), None);
+}
+
+fn complete_repository(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
+
+    let mut result = vec![];
+
+    let base = match BaseDirectories::with_prefix("proxmox-backup") {
+        Ok(v) => v,
+        _ => return result,
+    };
+
+    // usually $HOME/.cache/proxmox-backup/repo-list
+    let path = match base.place_cache_file("repo-list") {
+        Ok(v) => v,
+        _ => return result,
+    };
+
+    let data = tools::file_get_json(&path, None).unwrap_or(json!({}));
+
+    if let Some(map) = data.as_object() {
+        for (repo, _count) in map {
+            result.push(repo.to_owned());
+        }
+    }
+
+    result
 }
 
 fn backup_directory<P: AsRef<Path>>(
-    client: &mut HttpClient,
-    repo: &BackupRepository,
+    client: &BackupClient,
     dir_path: P,
     archive_name: &str,
-    backup_time: DateTime<Local>,
     chunk_size: Option<u64>,
+    all_file_systems: bool,
     verbose: bool,
 ) -> Result<(), Error> {
 
-    let mut param = json!({
-        "archive-name": archive_name,
-        "backup-type": "host",
-        "backup-id": &tools::nodename(),
-        "backup-time": backup_time.timestamp(),
-    });
+    if let Some(_size) = chunk_size {
+        unimplemented!();
+    }
+
+    let pxar_stream = PxarBackupStream::open(dir_path.as_ref(), all_file_systems, verbose)?;
+    let chunk_stream = ChunkStream::new(pxar_stream);
+
+    let (tx, rx) = mpsc::channel(10); // allow to buffer 10 chunks
+
+    let stream = rx
+        .map_err(Error::from)
+        .and_then(|x| x); // flatten
+
+    // spawn chunker inside a separate task so that it can run parallel
+    tokio::spawn(
+        tx.send_all(chunk_stream.then(|r| Ok(r)))
+            .map_err(|e| {}).map(|_| ())
+    );
 
-    if let Some(size) = chunk_size {
-        param["chunk-size"] = size.into();
+    client.upload_stream(archive_name, stream, "dynamic", None).wait()?;
+
+    Ok(())
+}
+
+fn backup_image<P: AsRef<Path>>(
+    client: &BackupClient,
+    image_path: P,
+    archive_name: &str,
+    image_size: u64,
+    chunk_size: Option<u64>,
+    verbose: bool,
+) -> Result<(), Error> {
+
+    if let Some(_size) = chunk_size {
+        unimplemented!();
     }
 
-    let query = tools::json_object_to_query(param)?;
+    let path = image_path.as_ref().to_owned();
 
-    let path = format!("api2/json/admin/datastore/{}/catar?{}", repo.store, query);
+    let file = tokio::fs::File::open(path).wait()?;
 
-    let stream = CaTarBackupStream::open(dir_path.as_ref(), verbose)?;
+    let stream = tokio::codec::FramedRead::new(file, tokio::codec::BytesCodec::new())
+        .map_err(Error::from);
 
-    let body = Body::wrap_stream(stream);
+    let stream = FixedChunkStream::new(stream, 4*1024*1024);
 
-    client.upload("application/x-proxmox-backup-catar", body, &path)?;
+    client.upload_stream(archive_name, stream, "fixed", Some(image_size)).wait()?;
 
     Ok(())
 }
@@ -87,6 +192,24 @@ fn backup_image(datastore: &DataStore, file: &std::fs::File, size: usize, target
 }
 */
 
+fn strip_chunked_file_expenstions(list: Vec<String>) -> Vec<String> {
+
+    let mut result = vec![];
+
+    for file in list.into_iter() {
+        if file.ends_with(".didx") {
+            result.push(file[..file.len()-5].to_owned());
+        } else if file.ends_with(".fidx") {
+            result.push(file[..file.len()-5].to_owned());
+        } else {
+            result.push(file); // should not happen
+        }
+    }
+
+    result
+}
+
+/* not used:
 fn list_backups(
     param: Value,
     _info: &ApiMethod,
@@ -94,13 +217,15 @@ fn list_backups(
 ) -> Result<Value, Error> {
 
     let repo_url = tools::required_string_param(&param, "repository")?;
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
+
+    let mut client = HttpClient::new(repo.host(), repo.user())?;
 
-    let mut client = HttpClient::new(&repo.host, &repo.user);
+    let path = format!("api2/json/admin/datastore/{}/backups", repo.store());
 
-    let path = format!("api2/json/admin/datastore/{}/backups", repo.store);
+    let result = client.get(&path, None)?;
 
-    let result = client.get(&path)?;
+    record_repository(&repo);
 
     // fixme: implement and use output formatter instead ..
     let list = result["data"].as_array().unwrap();
@@ -114,18 +239,18 @@ fn list_backups(
         let backup_dir = BackupDir::new(btype, id, epoch);
 
         let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
+        let files = strip_chunked_file_expenstions(files);
 
-        let info = BackupInfo { backup_dir, files };
-
-        for filename in info.files {
-            let path = info.backup_dir.relative_path().to_str().unwrap().to_owned();
-            println!("{} | {}/{}", info.backup_dir.backup_time().format("%c"), path, filename);
+        for filename in files {
+            let path = backup_dir.relative_path().to_str().unwrap().to_owned();
+            println!("{} | {}/{}", backup_dir.backup_time().format("%c"), path, filename);
         }
     }
 
     //Ok(result)
     Ok(Value::Null)
 }
+ */
 
 fn list_backup_groups(
     param: Value,
@@ -134,16 +259,32 @@ fn list_backup_groups(
 ) -> Result<Value, Error> {
 
     let repo_url = tools::required_string_param(&param, "repository")?;
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
+
+    let client = HttpClient::new(repo.host(), repo.user())?;
 
-    let mut client = HttpClient::new(&repo.host, &repo.user);
+    let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
 
-    let path = format!("api2/json/admin/datastore/{}/groups", repo.store);
+    let mut result = client.get(&path, None).wait()?;
 
-    let result = client.get(&path)?;
+    record_repository(&repo);
 
     // fixme: implement and use output formatter instead ..
-    let list = result["data"].as_array().unwrap();
+    let list = result["data"].as_array_mut().unwrap();
+
+    list.sort_unstable_by(|a, b| {
+        let a_id = a["backup-id"].as_str().unwrap();
+        let a_backup_type = a["backup-type"].as_str().unwrap();
+        let b_id = b["backup-id"].as_str().unwrap();
+        let b_backup_type = b["backup-type"].as_str().unwrap();
+
+        let type_order = a_backup_type.cmp(b_backup_type);
+        if type_order == std::cmp::Ordering::Equal {
+            a_id.cmp(b_id)
+        } else {
+            type_order
+        }
+    });
 
     for item in list {
 
@@ -157,12 +298,10 @@ fn list_backup_groups(
 
         let path = group.group_path().to_str().unwrap().to_owned();
 
-        let files = item["files"].as_array().unwrap().iter()
-            .map(|v| {
-                v.as_str().unwrap().to_owned()
-            }).collect();
+        let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
+        let files = strip_chunked_file_expenstions(files);
 
-        println!("{} | {} | {} | {}", path, last_backup.format("%c"),
+        println!("{:20} | {} | {:5} | {}", path, last_backup.format("%c"),
                  backup_count, tools::join(&files, ' '));
     }
 
@@ -177,22 +316,21 @@ fn list_snapshots(
 ) -> Result<Value, Error> {
 
     let repo_url = tools::required_string_param(&param, "repository")?;
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
 
     let path = tools::required_string_param(&param, "group")?;
     let group = BackupGroup::parse(path)?;
 
-    let query = tools::json_object_to_query(json!({
-        "backup-type": group.backup_type(),
-        "backup-id": group.backup_id(),
-    }))?;
+    let client = HttpClient::new(repo.host(), repo.user())?;
 
-    let mut client = HttpClient::new(&repo.host, &repo.user);
+    let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
 
-    let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store, query);
+    let result = client.get(&path, Some(json!({
+        "backup-type": group.backup_type(),
+        "backup-id": group.backup_id(),
+    }))).wait()?;
 
-    // fixme: params
-    let result = client.get(&path)?;
+    record_repository(&repo);
 
     // fixme: implement and use output formatter instead ..
     let list = result["data"].as_array().unwrap();
@@ -207,10 +345,8 @@ fn list_snapshots(
 
         let path = snapshot.relative_path().to_str().unwrap().to_owned();
 
-        let files = item["files"].as_array().unwrap().iter()
-            .map(|v| {
-                v.as_str().unwrap().to_owned()
-            }).collect();
+        let files = item["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_owned()).collect();
+        let files = strip_chunked_file_expenstions(files);
 
         println!("{} | {} | {}", path, snapshot.backup_time().format("%c"), tools::join(&files, ' '));
     }
@@ -225,22 +361,22 @@ fn forget_snapshots(
 ) -> Result<Value, Error> {
 
     let repo_url = tools::required_string_param(&param, "repository")?;
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
 
     let path = tools::required_string_param(&param, "snapshot")?;
     let snapshot = BackupDir::parse(path)?;
 
-    let query = tools::json_object_to_query(json!({
+    let mut client = HttpClient::new(repo.host(), repo.user())?;
+
+    let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
+
+    let result = client.delete(&path, Some(json!({
         "backup-type": snapshot.group().backup_type(),
         "backup-id": snapshot.group().backup_id(),
         "backup-time": snapshot.backup_time().timestamp(),
-    }))?;
-
-    let mut client = HttpClient::new(&repo.host, &repo.user);
-
-    let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store, query);
+    }))).wait()?;
 
-    let result = client.delete(&path)?;
+    record_repository(&repo);
 
     Ok(result)
 }
@@ -252,13 +388,15 @@ fn start_garbage_collection(
 ) -> Result<Value, Error> {
 
     let repo_url = tools::required_string_param(&param, "repository")?;
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
 
-    let mut client = HttpClient::new(&repo.host, &repo.user);
+    let mut client = HttpClient::new(repo.host(), repo.user())?;
 
-    let path = format!("api2/json/admin/datastore/{}/gc", repo.store);
+    let path = format!("api2/json/admin/datastore/{}/gc", repo.store());
 
-    let result = client.post(&path)?;
+    let result = client.post(&path, None).wait()?;
+
+    record_repository(&repo);
 
     Ok(result)
 }
@@ -281,7 +419,9 @@ fn create_backup(
 
     let backupspec_list = tools::required_array_param(&param, "backupspec")?;
 
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
+
+    let all_file_systems = param["all-file-systems"].as_bool().unwrap_or(false);
 
     let verbose = param["verbose"].as_bool().unwrap_or(false);
 
@@ -291,32 +431,34 @@ fn create_backup(
         verify_chunk_size(size)?;
     }
 
+    let backup_id = param["host-id"].as_str().unwrap_or(&tools::nodename());
+
     let mut upload_list = vec![];
 
+    enum BackupType { PXAR, IMAGE };
+
     for backupspec in backupspec_list {
         let (target, filename) = parse_backupspec(backupspec.as_str().unwrap())?;
 
-        let stat = match nix::sys::stat::stat(filename) {
-            Ok(s) => s,
+        use std::os::unix::fs::FileTypeExt;
+
+        let metadata = match std::fs::metadata(filename) {
+            Ok(m) => m,
             Err(err) => bail!("unable to access '{}' - {}", filename, err),
         };
+        let file_type = metadata.file_type();
 
-        if (stat.st_mode & libc::S_IFDIR) != 0 {
-
-            let target = format!("{}.catar", target);
+        if file_type.is_dir() {
 
-            upload_list.push((filename.to_owned(), target));
+            upload_list.push((BackupType::PXAR, filename.to_owned(), target.to_owned(), 0));
 
-        } else if (stat.st_mode & (libc::S_IFREG|libc::S_IFBLK)) != 0 {
-            if stat.st_size <= 0 { bail!("got strange file size '{}'", stat.st_size); }
-            let _size = stat.st_size as usize;
+        } else if file_type.is_file() || file_type.is_block_device() {
 
-            panic!("implement me");
+            let size = tools::image_size(&PathBuf::from(filename))?;
 
-            //backup_image(&datastore, &file, size, &target, chunk_size)?;
+            if size == 0 { bail!("got zero-sized file '{}'", filename); }
 
-            // let idx = datastore.open_image_reader(target)?;
-            // idx.print_info();
+            upload_list.push((BackupType::IMAGE, filename.to_owned(), target.to_owned(), size));
 
         } else {
             bail!("unsupported file type (expected a directory, file or block device)");
@@ -325,19 +467,30 @@ fn create_backup(
 
     let backup_time = Local.timestamp(Local::now().timestamp(), 0);
 
-    let mut client = HttpClient::new(&repo.host, &repo.user);
-
-    client.login()?; // login before starting backup
+    let client = HttpClient::new(repo.host(), repo.user())?;
+    record_repository(&repo);
 
     println!("Starting backup");
     println!("Client name: {}", tools::nodename());
     println!("Start Time: {}", backup_time.to_rfc3339());
 
-    for (filename, target) in upload_list {
-        println!("Upload '{}' to '{:?}' as {}", filename, repo, target);
-        backup_directory(&mut client, &repo, &filename, &target, backup_time, chunk_size_opt, verbose)?;
+    let client = client.start_backup(repo.store(), "host", &backup_id, verbose).wait()?;
+
+    for (backup_type, filename, target, size) in upload_list {
+        match backup_type {
+            BackupType::PXAR => {
+                println!("Upload directory '{}' to '{:?}' as {}", filename, repo, target);
+                backup_directory(&client, &filename, &target, chunk_size_opt, all_file_systems, verbose)?;
+            }
+            BackupType::IMAGE => {
+                println!("Upload image '{}' to '{:?}' as {}", filename, repo, target);
+                backup_image(&client, &filename, &target, size, chunk_size_opt, verbose)?;
+            }
+        }
     }
 
+    client.finish().wait()?;
+
     let end_time = Local.timestamp(Local::now().timestamp(), 0);
     let elapsed = end_time.signed_duration_since(backup_time);
     println!("Duration: {}", elapsed);
@@ -347,15 +500,19 @@ fn create_backup(
     Ok(Value::Null)
 }
 
-pub fn complete_backup_source(arg: &str) -> Vec<String> {
+fn complete_backup_source(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
 
     let mut result = vec![];
 
     let data: Vec<&str> = arg.splitn(2, ':').collect();
 
-    if data.len() != 2 { return result; }
+    if data.len() != 2 {
+        result.push(String::from("root.pxar:/"));
+        result.push(String::from("etc.pxar:/etc"));
+        return result;
+    }
 
-    let files = tools::complete_file_name(data[1]);
+    let files = tools::complete_file_name(data[1], param);
 
     for file in files {
         result.push(format!("{}:{}", data[0], file));
@@ -364,6 +521,73 @@ pub fn complete_backup_source(arg: &str) -> Vec<String> {
     result
 }
 
+fn restore(
+    param: Value,
+    _info: &ApiMethod,
+    _rpcenv: &mut RpcEnvironment,
+) -> Result<Value, Error> {
+
+    let repo_url = tools::required_string_param(&param, "repository")?;
+    let repo: BackupRepository = repo_url.parse()?;
+
+    let archive_name = tools::required_string_param(&param, "archive-name")?;
+
+    let mut client = HttpClient::new(repo.host(), repo.user())?;
+
+    record_repository(&repo);
+
+    let path = tools::required_string_param(&param, "snapshot")?;
+
+    let query;
+
+    if path.matches('/').count() == 1 {
+        let group = BackupGroup::parse(path)?;
+
+        let path = format!("api2/json/admin/datastore/{}/snapshots", repo.store());
+        let result = client.get(&path, Some(json!({
+            "backup-type": group.backup_type(),
+            "backup-id": group.backup_id(),
+        }))).wait()?;
+
+        let list = result["data"].as_array().unwrap();
+        if list.len() == 0 {
+            bail!("backup group '{}' does not contain any snapshots:", path);
+        }
+
+        query = tools::json_object_to_query(json!({
+            "backup-type": group.backup_type(),
+            "backup-id": group.backup_id(),
+            "backup-time": list[0]["backup-time"].as_i64().unwrap(),
+            "archive-name": archive_name,
+        }))?;
+    } else {
+        let snapshot = BackupDir::parse(path)?;
+
+        query = tools::json_object_to_query(json!({
+            "backup-type": snapshot.group().backup_type(),
+            "backup-id": snapshot.group().backup_id(),
+            "backup-time": snapshot.backup_time().timestamp(),
+            "archive-name": archive_name,
+        }))?;
+    }
+
+    let target = tools::required_string_param(&param, "target")?;
+
+    if archive_name.ends_with(".pxar") {
+        let path = format!("api2/json/admin/datastore/{}/pxar?{}", repo.store(), query);
+
+        println!("DOWNLOAD FILE {} to {}", path, target);
+
+        let target = PathBuf::from(target);
+        let writer = PxarDecodeWriter::new(&target, true)?;
+        client.download(&path, Box::new(writer)).wait()?;
+    } else {
+        bail!("unknown file extensions - unable to download '{}'", archive_name);
+    }
+
+    Ok(Value::Null)
+}
+
 fn prune(
     mut param: Value,
     _info: &ApiMethod,
@@ -371,19 +595,179 @@ fn prune(
 ) -> Result<Value, Error> {
 
     let repo_url = tools::required_string_param(&param, "repository")?;
-    let repo = BackupRepository::parse(repo_url)?;
+    let repo: BackupRepository = repo_url.parse()?;
 
-    let mut client = HttpClient::new(&repo.host, &repo.user);
+    let mut client = HttpClient::new(repo.host(), repo.user())?;
 
-    let path = format!("api2/json/admin/datastore/{}/prune", repo.store);
+    let path = format!("api2/json/admin/datastore/{}/prune", repo.store());
 
     param.as_object_mut().unwrap().remove("repository");
 
-    let result = client.post_json(&path, param)?;
+    let result = client.post(&path, Some(param)).wait()?;
+
+    record_repository(&repo);
 
     Ok(result)
 }
 
+// like get, but simply ignore errors and return Null instead
+fn try_get(repo: &BackupRepository, url: &str) -> Value {
+
+    let client = match HttpClient::new(repo.host(), repo.user()) {
+        Ok(v) => v,
+        _ => return Value::Null,
+    };
+
+    let mut resp = match client.get(url, None).wait() {
+        Ok(v) => v,
+        _ => return Value::Null,
+    };
+
+    if let Some(map) = resp.as_object_mut() {
+        if let Some(data) = map.remove("data") {
+            return data;
+        }
+    }
+    Value::Null
+}
+
+fn extract_repo(param: &HashMap<String, String>) -> Option<BackupRepository> {
+
+    let repo_url = match param.get("repository") {
+        Some(v) => v,
+        _ => return None,
+    };
+
+    let repo: BackupRepository = match repo_url.parse() {
+        Ok(v) => v,
+        _ => return None,
+    };
+
+    Some(repo)
+}
+
+fn complete_backup_group(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
+
+    let mut result = vec![];
+
+    let repo = match extract_repo(param) {
+        Some(v) => v,
+        _ => return result,
+    };
+
+    let path = format!("api2/json/admin/datastore/{}/groups", repo.store());
+
+    let data = try_get(&repo, &path);
+
+    if let Some(list) = data.as_array() {
+        for item in list {
+            if let (Some(backup_id), Some(backup_type)) =
+                (item["backup-id"].as_str(), item["backup-type"].as_str())
+            {
+                result.push(format!("{}/{}", backup_type, backup_id));
+            }
+        }
+    }
+
+    result
+}
+
+fn complete_group_or_snapshot(arg: &str, param: &HashMap<String, String>) -> Vec<String> {
+
+    let mut result = vec![];
+
+     let repo = match extract_repo(param) {
+        Some(v) => v,
+        _ => return result,
+    };
+
+    if arg.matches('/').count() < 2 {
+        let groups = complete_backup_group(arg, param);
+        for group in groups {
+            result.push(group.to_string());
+            result.push(format!("{}/", group));
+        }
+        return result;
+    }
+
+    let mut parts = arg.split('/');
+    let query = tools::json_object_to_query(json!({
+        "backup-type": parts.next().unwrap(),
+        "backup-id": parts.next().unwrap(),
+    })).unwrap();
+
+    let path = format!("api2/json/admin/datastore/{}/snapshots?{}", repo.store(), query);
+
+    let data = try_get(&repo, &path);
+
+    if let Some(list) = data.as_array() {
+        for item in list {
+            if let (Some(backup_id), Some(backup_type), Some(backup_time)) =
+                (item["backup-id"].as_str(), item["backup-type"].as_str(), item["backup-time"].as_i64())
+            {
+                let snapshot = BackupDir::new(backup_type, backup_id, backup_time);
+                result.push(snapshot.relative_path().to_str().unwrap().to_owned());
+            }
+        }
+    }
+
+    result
+}
+
+fn complete_archive_name(_arg: &str, param: &HashMap<String, String>) -> Vec<String> {
+
+    let mut result = vec![];
+
+    let repo = match extract_repo(param) {
+        Some(v) => v,
+        _ => return result,
+    };
+
+    let snapshot = match param.get("snapshot") {
+        Some(path) => {
+            match BackupDir::parse(path) {
+                Ok(v) => v,
+                _ => return result,
+            }
+        }
+        _ => return result,
+    };
+
+    let query = tools::json_object_to_query(json!({
+        "backup-type": snapshot.group().backup_type(),
+        "backup-id": snapshot.group().backup_id(),
+        "backup-time": snapshot.backup_time().timestamp(),
+    })).unwrap();
+
+    let path = format!("api2/json/admin/datastore/{}/files?{}", repo.store(), query);
+
+    let data = try_get(&repo, &path);
+
+    if let Some(list) = data.as_array() {
+        for item in list {
+            if let Some(filename) = item.as_str() {
+                result.push(filename.to_owned());
+            }
+        }
+    }
+
+    strip_chunked_file_expenstions(result)
+}
+
+fn complete_chunk_size(_arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
+
+    let mut result = vec![];
+
+    let mut size = 64;
+    loop {
+        result.push(size.to_string());
+        size = size * 2;
+        if size > 4096 { break; }
+    }
+
+    result
+}
+
 fn main() {
 
     let repo_url_schema: Arc<Schema> = Arc::new(
@@ -407,13 +791,16 @@ fn main() {
                 .required(
                     "backupspec",
                     ArraySchema::new(
-                        "List of backup source specifications ([<label>:<path>] ...)",
+                        "List of backup source specifications ([<label.ext>:<path>] ...)",
                         backup_source_schema,
                     ).min_length(1)
                 )
                 .optional(
                     "verbose",
                     BooleanSchema::new("Verbose output.").default(false))
+                .optional(
+                    "host-id",
+                    StringSchema::new("Use specified ID for the backup group name ('host/<id>'). The default is the system hostname."))
                 .optional(
                     "chunk-size",
                     IntegerSchema::new("Chunk size in KB. Must be a power of 2.")
@@ -423,7 +810,9 @@ fn main() {
                 )
         ))
         .arg_param(vec!["repository", "backupspec"])
-        .completion_cb("backupspec", complete_backup_source);
+        .completion_cb("repository", complete_repository)
+        .completion_cb("backupspec", complete_backup_source)
+        .completion_cb("chunk-size", complete_chunk_size);
 
     let list_cmd_def = CliCommand::new(
         ApiMethod::new(
@@ -431,7 +820,8 @@ fn main() {
             ObjectSchema::new("List backup groups.")
                 .required("repository", repo_url_schema.clone())
         ))
-        .arg_param(vec!["repository"]);
+        .arg_param(vec!["repository"])
+        .completion_cb("repository", complete_repository);
 
     let snapshots_cmd_def = CliCommand::new(
         ApiMethod::new(
@@ -440,7 +830,9 @@ fn main() {
                 .required("repository", repo_url_schema.clone())
                 .required("group", StringSchema::new("Backup group."))
         ))
-        .arg_param(vec!["repository", "group"]);
+        .arg_param(vec!["repository", "group"])
+        .completion_cb("group", complete_backup_group)
+        .completion_cb("repository", complete_repository);
 
     let forget_cmd_def = CliCommand::new(
         ApiMethod::new(
@@ -449,7 +841,9 @@ fn main() {
                 .required("repository", repo_url_schema.clone())
                 .required("snapshot", StringSchema::new("Snapshot path."))
         ))
-        .arg_param(vec!["repository", "snapshot"]);
+        .arg_param(vec!["repository", "snapshot"])
+        .completion_cb("repository", complete_repository)
+        .completion_cb("snapshot", complete_group_or_snapshot);
 
     let garbage_collect_cmd_def = CliCommand::new(
         ApiMethod::new(
@@ -457,7 +851,23 @@ fn main() {
             ObjectSchema::new("Start garbage collection for a specific repository.")
                 .required("repository", repo_url_schema.clone())
         ))
-        .arg_param(vec!["repository"]);
+        .arg_param(vec!["repository"])
+        .completion_cb("repository", complete_repository);
+
+    let restore_cmd_def = CliCommand::new(
+        ApiMethod::new(
+            restore,
+            ObjectSchema::new("Restore backup repository.")
+                .required("repository", repo_url_schema.clone())
+                .required("snapshot", StringSchema::new("Group/Snapshot path."))
+                .required("archive-name", StringSchema::new("Backup archive name."))
+                .required("target", StringSchema::new("Target directory path."))
+        ))
+        .arg_param(vec!["repository", "snapshot", "archive-name", "target"])
+        .completion_cb("repository", complete_repository)
+        .completion_cb("snapshot", complete_group_or_snapshot)
+        .completion_cb("archive-name", complete_archive_name)
+        .completion_cb("target", tools::complete_file_name);
 
     let prune_cmd_def = CliCommand::new(
         ApiMethod::new(
@@ -467,14 +877,21 @@ fn main() {
                     .required("repository", repo_url_schema.clone())
             )
         ))
-        .arg_param(vec!["repository"]);
+        .arg_param(vec!["repository"])
+        .completion_cb("repository", complete_repository);
+
     let cmd_def = CliCommandMap::new()
         .insert("backup".to_owned(), backup_cmd_def.into())
         .insert("forget".to_owned(), forget_cmd_def.into())
         .insert("garbage-collect".to_owned(), garbage_collect_cmd_def.into())
         .insert("list".to_owned(), list_cmd_def.into())
         .insert("prune".to_owned(), prune_cmd_def.into())
+        .insert("restore".to_owned(), restore_cmd_def.into())
         .insert("snapshots".to_owned(), snapshots_cmd_def.into());
 
-    run_cli_command(cmd_def.into());
+    hyper::rt::run(futures::future::lazy(move || {
+        run_cli_command(cmd_def.into());
+        Ok(())
+    }));
+
 }