1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/*
This file is part of Yama.

Yama is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Yama is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Yama.  If not, see <https://www.gnu.org/licenses/>.
*/


use std::fs::File;
use std::io;
use std::io::{Read, Write};
use std::path::Path;
use std::sync::Arc;

use anyhow::{anyhow, bail, Context};
use clap::crate_version;
use log::warn;

use crate::chunking::{RecursiveChunker, RecursiveUnchunker, SENSIBLE_THRESHOLD};
use crate::definitions::{PointerData, RecursiveChunkRef, RootTreeNode, TreeNode};
use crate::pile::compression::{CompressionSettings, RawPileCompressor};
use crate::pile::integrity::RawPileIntegrityChecker;
use crate::pile::local_sqlitebloblogs::SqliteBloblogPile;
use crate::pile::{Pile, PileDescriptor, PileStorage, RawPile};
use crate::tree::{integrate_node_in_place, merge_uid_or_gid_tables};
use crate::utils::get_number_of_workers;

pub fn init(dir: &Path) -> anyhow::Result<()> {
    let yama_toml = dir.join("yama.toml");
    if yama_toml.exists() {
        bail!("yama.toml already exists. Cannot create yama pile here.");
    }

    /*
    let pile_db = sled::open(dir.join("pile.sled"))?;
    pile_db.flush()?;
     */

    let mut file = File::create(yama_toml)?;

    let desc = PileDescriptor {
        yama_version: crate_version!().to_owned(),
        storage: PileStorage::SqliteIndexedBloblog,
        compression: Some(12),
    };

    file.write_all(&toml::to_vec(&desc)?)?;

    Ok(())
}

pub fn load_pile_descriptor(dir: &Path) -> anyhow::Result<PileDescriptor> {
    let yama_toml = dir.join("yama.toml");
    if !yama_toml.exists() {
        bail!("yama.toml does not exist here. Is this an existing pile?");
    }

    let mut file = File::open(yama_toml)?;
    let mut buf = Vec::new();
    file.read_to_end(&mut buf)?;
    Ok(toml::from_slice(&buf)?)
}

pub fn open_pile(dir: &Path, desc: &PileDescriptor) -> anyhow::Result<Pile<Box<dyn RawPile>>> {
    let num_compressors = get_number_of_workers("YAMA_COMPRESSORS");
    let num_decompressors = get_number_of_workers("YAMA_DECOMPRESSORS");

    match desc.storage {
        PileStorage::RemoteOnly => {
            bail!("This is a remote-only pile. No local storage allowed.");
        }
        PileStorage::SqliteIndexedBloblog => {
            let blob_raw_pile = RawPileIntegrityChecker::new(SqliteBloblogPile::open(dir)?);
            let raw_pile: Box<dyn RawPile> = match desc.compression {
                None => Box::new(blob_raw_pile),
                Some(comp_level) => {
                    let mut dictionary = Vec::new();
                    let dict_path = dir.join("important_zstd.dict");
                    File::open(dict_path)
                        .context("You need important_zstd.dict in your pile folder.")?
                        .read_to_end(&mut dictionary)?;

                    let (compressed_pile, _handles) = RawPileCompressor::new(
                        blob_raw_pile,
                        CompressionSettings {
                            dictionary: Arc::new(dictionary),
                            level: comp_level as i32,
                            num_compressors: num_compressors as u32,
                            num_decompressors: num_decompressors as u32,
                        },
                    )?;

                    Box::new(compressed_pile)
                }
            };
            Ok(Pile::new(raw_pile))
        }
    }
}

pub fn store_tree_node<RP: RawPile>(
    pile: &Pile<RP>,
    root_tree_node: &RootTreeNode,
) -> anyhow::Result<RecursiveChunkRef> {
    let serialised = serde_bare::to_vec(root_tree_node)?;
    let mut chunker = RecursiveChunker::new(SENSIBLE_THRESHOLD, pile);
    io::copy(&mut (&serialised[..]), &mut chunker)?;
    let chunk_ref = chunker.finish()?;
    Ok(chunk_ref)
}

pub fn retrieve_tree_node<RP: RawPile>(
    pile: &Pile<RP>,
    chunk_ref: RecursiveChunkRef,
) -> anyhow::Result<RootTreeNode> {
    let mut serialised = Vec::new();
    let mut unchunker = RecursiveUnchunker::new(pile, chunk_ref);
    io::copy(&mut unchunker, &mut serialised)?;
    Ok(serde_bare::from_slice(&serialised)?)
    /*
    let unchunker = RecursiveUnchunker::new(pile, chunk_ref);
    Ok(serde_bare::from_reader(unchunker)?)
     */
}

pub fn fully_integrate_pointer_node<RP: RawPile>(
    pile: &Pile<RP>,
    tree_node: &mut TreeNode,
    pointer: &mut PointerData,
) -> anyhow::Result<()> {
    if let Some(parent_name) = &pointer.parent_pointer {
        let mut parent = pile
            .read_pointer(parent_name.as_str())?
            .ok_or_else(|| anyhow!("Parent pointer {:?} not found.", parent_name))?;
        let mut parent_node = retrieve_tree_node(pile, parent.chunk_ref.clone())?.node;

        fully_integrate_pointer_node(pile, &mut parent_node, &mut parent)?;
        integrate_node_in_place(tree_node, &mut parent_node)?;

        // merge in the UID and GID tables when integrating.
        if !merge_uid_or_gid_tables(&mut pointer.uid_lookup, &parent.uid_lookup) {
            warn!(
                "Overlap when merging parent:{:?}'s UID table into child.",
                parent_name
            );
        }
        if !merge_uid_or_gid_tables(&mut pointer.gid_lookup, &parent.gid_lookup) {
            warn!(
                "Overlap when merging parent:{:?}'s GID table into child.",
                parent_name
            );
        }

        pointer.parent_pointer = None;
    }
    Ok(())
}

pub fn fully_load_pointer<RP: RawPile>(
    pile: &Pile<RP>,
    pointer_name: &str,
) -> anyhow::Result<(PointerData, RootTreeNode)> {
    let mut pointer_data = pile
        .read_pointer(pointer_name)?
        .ok_or_else(|| anyhow!("Pointer {:?} not found.", pointer_name))?;
    let mut root_node = retrieve_tree_node(pile, pointer_data.chunk_ref.clone())?;

    fully_integrate_pointer_node(pile, &mut root_node.node, &mut pointer_data)?;

    Ok((pointer_data, root_node))
}