restic/src/restic/repository/repository.go

560 lines
14 KiB
Go
Raw Normal View History

package repository
2014-12-21 16:02:49 +00:00
import (
"bytes"
"encoding/json"
2014-12-21 16:02:49 +00:00
"errors"
"fmt"
"io"
2015-07-26 19:58:03 +00:00
"os"
2014-12-21 16:02:49 +00:00
"restic/backend"
"restic/crypto"
"restic/debug"
"restic/pack"
2014-12-21 16:02:49 +00:00
)
2015-05-09 21:59:58 +00:00
// Repository is used to access a repository in a backend.
type Repository struct {
be backend.Backend
Config Config
key *crypto.Key
keyName string
2015-10-12 20:34:12 +00:00
idx *MasterIndex
*packerManager
2014-12-21 16:02:49 +00:00
}
// New returns a new repository with backend be.
2016-03-06 12:14:06 +00:00
func New(be backend.Backend) *Repository {
repo := &Repository{
be: be,
idx: NewMasterIndex(),
2016-03-06 13:20:48 +00:00
packerManager: newPackerManager(be, nil),
}
2016-03-06 12:14:06 +00:00
return repo
2014-12-21 16:02:49 +00:00
}
2015-03-28 10:50:23 +00:00
// Find loads the list of all blobs of type t and searches for names which start
2014-12-21 16:02:49 +00:00
// with prefix. If none is found, nil and ErrNoIDPrefixFound is returned. If
// more than one is found, nil and ErrMultipleIDMatches is returned.
func (r *Repository) Find(t backend.Type, prefix string) (string, error) {
return backend.Find(r.be, t, prefix)
2014-12-21 16:02:49 +00:00
}
// PrefixLength returns the number of bytes required so that all prefixes of
// all IDs of type t are unique.
func (r *Repository) PrefixLength(t backend.Type) (int, error) {
return backend.PrefixLength(r.be, t)
2014-12-21 16:02:49 +00:00
}
// LoadAndDecrypt loads and decrypts data identified by t and id from the
// backend.
func (r *Repository) LoadAndDecrypt(t backend.Type, id backend.ID) ([]byte, error) {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.Load", "load %v with id %v", t, id.Str())
h := backend.Handle{Type: t, Name: id.String()}
buf, err := backend.LoadAll(r.be, h, nil)
2015-03-28 10:50:23 +00:00
if err != nil {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.Load", "error loading %v: %v", id.Str(), err)
2015-03-28 10:50:23 +00:00
return nil, err
}
if t != backend.Config && !backend.Hash(buf).Equal(id) {
2015-03-28 10:50:23 +00:00
return nil, errors.New("invalid data returned")
}
// decrypt
plain, err := r.Decrypt(buf)
if err != nil {
return nil, err
}
return plain, nil
}
// LoadBlob tries to load and decrypt content identified by t and id from a
2015-07-26 16:00:53 +00:00
// pack from the backend, the result is stored in plaintextBuf, which must be
// large enough to hold the complete blob.
func (r *Repository) LoadBlob(t pack.BlobType, id backend.ID, plaintextBuf []byte) ([]byte, error) {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.LoadBlob", "load %v with id %v", t, id.Str())
// lookup pack
blob, err := r.idx.Lookup(id)
if err != nil {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.LoadBlob", "id %v not found in index: %v", id.Str(), err)
return nil, err
}
plaintextBufSize := uint(cap(plaintextBuf))
if blob.PlaintextLength() > plaintextBufSize {
debug.Log("Repo.LoadBlob", "need to expand buffer: want %d bytes, got %d",
blob.PlaintextLength(), plaintextBufSize)
plaintextBuf = make([]byte, blob.PlaintextLength())
}
if blob.Type != t {
debug.Log("Repo.LoadBlob", "wrong type returned for %v: wanted %v, got %v", id.Str(), t, blob.Type)
return nil, fmt.Errorf("blob has wrong type %v (wanted: %v)", blob.Type, t)
}
debug.Log("Repo.LoadBlob", "id %v found: %v", id.Str(), blob)
// load blob from pack
h := backend.Handle{Type: backend.Data, Name: blob.PackID.String()}
ciphertextBuf := make([]byte, blob.Length)
n, err := r.be.Load(h, ciphertextBuf, int64(blob.Offset))
if err != nil {
debug.Log("Repo.LoadBlob", "error loading blob %v: %v", blob, err)
return nil, err
}
if uint(n) != blob.Length {
debug.Log("Repo.LoadBlob", "error loading blob %v: wrong length returned, want %d, got %d",
blob.Length, uint(n))
return nil, errors.New("wrong length returned")
}
// decrypt
2015-07-26 16:00:53 +00:00
plaintextBuf, err = r.decryptTo(plaintextBuf, ciphertextBuf)
if err != nil {
return nil, err
}
// check hash
2015-07-26 16:00:53 +00:00
if !backend.Hash(plaintextBuf).Equal(id) {
return nil, errors.New("invalid data returned")
}
2015-07-26 16:00:53 +00:00
return plaintextBuf, nil
}
2015-11-18 19:33:20 +00:00
// closeOrErr calls cl.Close() and sets err to the returned error value if
// itself is not yet set.
func closeOrErr(cl io.Closer, err *error) {
e := cl.Close()
if *err != nil {
return
}
*err = e
}
2015-05-04 18:39:45 +00:00
// LoadJSONUnpacked decrypts the data and afterwards calls json.Unmarshal on
// the item.
2015-11-18 19:33:20 +00:00
func (r *Repository) LoadJSONUnpacked(t backend.Type, id backend.ID, item interface{}) (err error) {
buf, err := r.LoadAndDecrypt(t, id)
if err != nil {
return err
}
return json.Unmarshal(buf, item)
}
// LoadJSONPack calls LoadBlob() to load a blob from the backend, decrypt the
// data and afterwards call json.Unmarshal on the item.
2015-11-18 19:33:20 +00:00
func (r *Repository) LoadJSONPack(t pack.BlobType, id backend.ID, item interface{}) (err error) {
buf, err := r.LoadBlob(t, id, nil)
if err != nil {
return err
}
return json.Unmarshal(buf, item)
}
// LookupBlobSize returns the size of blob id.
func (r *Repository) LookupBlobSize(id backend.ID) (uint, error) {
2015-10-12 20:34:12 +00:00
return r.idx.LookupSize(id)
}
// SaveAndEncrypt encrypts data and stores it to the backend as type t. If data
// is small enough, it will be packed together with other small blobs.
func (r *Repository) SaveAndEncrypt(t pack.BlobType, data []byte, id *backend.ID) (backend.ID, error) {
if id == nil {
// compute plaintext hash
hashedID := backend.Hash(data)
id = &hashedID
}
2015-05-09 15:41:28 +00:00
debug.Log("Repo.Save", "save id %v (%v, %d bytes)", id.Str(), t, len(data))
// get buf from the pool
2015-04-26 12:46:15 +00:00
ciphertext := getBuf()
defer freeBuf(ciphertext)
// encrypt blob
ciphertext, err := r.Encrypt(ciphertext, data)
if err != nil {
return backend.ID{}, err
}
// find suitable packer and add blob
packer, err := r.findPacker(uint(len(ciphertext)))
if err != nil {
return backend.ID{}, err
}
// save ciphertext
_, err = packer.Add(t, *id, ciphertext)
2015-10-12 20:34:12 +00:00
if err != nil {
return backend.ID{}, err
}
// if the pack is not full enough and there are less than maxPackers
// packers, put back to the list
if packer.Size() < minPackSize && r.countPacker() < maxPackers {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.Save", "pack is not full enough (%d bytes)", packer.Size())
r.insertPacker(packer)
return *id, nil
}
// else write the pack to the backend
return *id, r.savePacker(packer)
}
// SaveJSON serialises item as JSON and encrypts and saves it in a pack in the
// backend as type t.
func (r *Repository) SaveJSON(t pack.BlobType, item interface{}) (backend.ID, error) {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.SaveJSON", "save %v blob", t)
buf := getBuf()[:0]
defer freeBuf(buf)
wr := bytes.NewBuffer(buf)
enc := json.NewEncoder(wr)
err := enc.Encode(item)
if err != nil {
return backend.ID{}, fmt.Errorf("json.Encode: %v", err)
}
buf = wr.Bytes()
return r.SaveAndEncrypt(t, buf, nil)
}
// SaveJSONUnpacked serialises item as JSON and encrypts and saves it in the
// backend as type t, without a pack. It returns the storage hash.
func (r *Repository) SaveJSONUnpacked(t backend.Type, item interface{}) (backend.ID, error) {
2016-01-24 17:50:41 +00:00
debug.Log("Repo.SaveJSONUnpacked", "save new blob %v", t)
plaintext, err := json.Marshal(item)
if err != nil {
return backend.ID{}, fmt.Errorf("json.Encode: %v", err)
}
2016-01-24 17:52:11 +00:00
return r.SaveUnpacked(t, plaintext)
}
// SaveUnpacked encrypts data and stores it in the backend. Returned is the
// storage hash.
func (r *Repository) SaveUnpacked(t backend.Type, p []byte) (id backend.ID, err error) {
ciphertext := make([]byte, len(p)+crypto.Extension)
ciphertext, err = r.Encrypt(ciphertext, p)
if err != nil {
return backend.ID{}, err
}
2016-01-24 17:52:11 +00:00
id = backend.Hash(ciphertext)
2016-01-24 17:50:41 +00:00
h := backend.Handle{Type: t, Name: id.String()}
2016-01-24 17:50:41 +00:00
err = r.be.Save(h, ciphertext)
if err != nil {
2016-01-24 17:50:41 +00:00
debug.Log("Repo.SaveJSONUnpacked", "error saving blob %v: %v", h, err)
return backend.ID{}, err
}
2016-01-24 17:50:41 +00:00
debug.Log("Repo.SaveJSONUnpacked", "blob %v saved", h)
return id, nil
}
// Flush saves all remaining packs.
func (r *Repository) Flush() error {
r.pm.Lock()
defer r.pm.Unlock()
debug.Log("Repo.Flush", "manually flushing %d packs", len(r.packs))
for _, p := range r.packs {
err := r.savePacker(p)
if err != nil {
return err
}
}
r.packs = r.packs[:0]
return nil
}
// Backend returns the backend for the repository.
func (r *Repository) Backend() backend.Backend {
return r.be
}
2015-10-12 20:34:12 +00:00
// Index returns the currently used MasterIndex.
func (r *Repository) Index() *MasterIndex {
return r.idx
}
2015-05-09 11:25:52 +00:00
// SetIndex instructs the repository to use the given index.
2015-10-12 20:34:12 +00:00
func (r *Repository) SetIndex(i *MasterIndex) {
r.idx = i
}
2016-01-24 17:52:11 +00:00
// SaveIndex saves an index in the repository.
2015-10-25 16:05:54 +00:00
func SaveIndex(repo *Repository, index *Index) (backend.ID, error) {
2016-01-24 17:52:11 +00:00
buf := bytes.NewBuffer(nil)
2015-10-25 16:05:54 +00:00
2016-01-24 17:52:11 +00:00
err := index.Finalize(buf)
2015-10-25 16:05:54 +00:00
if err != nil {
return backend.ID{}, err
}
2016-01-24 17:52:11 +00:00
return repo.SaveUnpacked(backend.Index, buf.Bytes())
2015-10-25 16:05:54 +00:00
}
2015-10-12 21:59:17 +00:00
// saveIndex saves all indexes in the backend.
func (r *Repository) saveIndex(indexes ...*Index) error {
for i, idx := range indexes {
2015-10-12 20:34:12 +00:00
debug.Log("Repo.SaveIndex", "Saving index %d", i)
2015-10-25 16:05:54 +00:00
sid, err := SaveIndex(r, idx)
2015-10-12 20:34:12 +00:00
if err != nil {
return err
}
2015-02-15 23:24:58 +00:00
2015-10-12 20:34:12 +00:00
debug.Log("Repo.SaveIndex", "Saved index %d as %v", i, sid.Str())
}
2015-10-12 20:34:12 +00:00
return nil
}
2015-10-12 21:59:17 +00:00
// SaveIndex saves all new indexes in the backend.
func (r *Repository) SaveIndex() error {
return r.saveIndex(r.idx.NotFinalIndexes()...)
}
// SaveFullIndex saves all full indexes in the backend.
func (r *Repository) SaveFullIndex() error {
return r.saveIndex(r.idx.FullIndexes()...)
}
2015-07-04 16:38:32 +00:00
const loadIndexParallelism = 20
2015-10-12 20:34:12 +00:00
// LoadIndex loads all index files from the backend in parallel and stores them
// in the master index. The first error that occurred is returned.
func (r *Repository) LoadIndex() error {
2015-05-09 15:41:28 +00:00
debug.Log("Repo.LoadIndex", "Loading index")
2015-07-04 16:38:32 +00:00
errCh := make(chan error, 1)
indexes := make(chan *Index)
worker := func(id backend.ID, done <-chan struct{}) error {
2015-07-04 16:38:32 +00:00
idx, err := LoadIndex(r, id)
if err != nil {
return err
}
2015-07-04 16:38:32 +00:00
select {
case indexes <- idx:
case <-done:
}
return nil
}
go func() {
defer close(indexes)
errCh <- FilesInParallel(r.be, backend.Index, loadIndexParallelism,
ParallelWorkFuncParseID(worker))
2015-07-04 16:38:32 +00:00
}()
for idx := range indexes {
2015-10-12 20:34:12 +00:00
r.idx.Insert(idx)
2015-07-04 16:38:32 +00:00
}
if err := <-errCh; err != nil {
return err
}
2015-07-04 16:38:32 +00:00
return nil
}
2015-07-04 16:38:32 +00:00
// LoadIndex loads the index id from backend and returns it.
func LoadIndex(repo *Repository, id backend.ID) (*Index, error) {
idx, err := LoadIndexWithDecoder(repo, id, DecodeIndex)
2015-07-26 19:58:03 +00:00
if err == nil {
return idx, nil
}
if err == ErrOldIndexFormat {
fmt.Fprintf(os.Stderr, "index %v has old format\n", id.Str())
return LoadIndexWithDecoder(repo, id, DecodeOldIndex)
2015-07-26 19:58:03 +00:00
}
return nil, err
}
2015-05-04 18:39:45 +00:00
// SearchKey finds a key with the supplied password, afterwards the config is
// read and parsed.
func (r *Repository) SearchKey(password string) error {
key, err := SearchKey(r, password)
2014-12-21 17:10:19 +00:00
if err != nil {
return err
}
r.key = key.master
r.packerManager.key = key.master
r.keyName = key.Name()
2015-07-02 20:36:31 +00:00
r.Config, err = LoadConfig(r)
return err
2015-05-03 14:36:52 +00:00
}
2014-12-21 17:10:19 +00:00
2015-07-02 20:36:31 +00:00
// Init creates a new master key with the supplied password, initializes and
// saves the repository config.
func (r *Repository) Init(password string) error {
has, err := r.be.Test(backend.Config, "")
2015-05-03 15:46:18 +00:00
if err != nil {
return err
}
if has {
return errors.New("repository master key and config already initialized")
}
cfg, err := CreateConfig()
if err != nil {
return err
}
return r.init(password, cfg)
}
// init creates a new master key with the supplied password and uses it to save
// the config into the repo.
func (r *Repository) init(password string, cfg Config) error {
key, err := createMasterKey(r, password)
2015-05-03 14:36:52 +00:00
if err != nil {
return err
}
r.key = key.master
r.packerManager.key = key.master
r.keyName = key.Name()
r.Config = cfg
_, err = r.SaveJSONUnpacked(backend.Config, cfg)
2015-07-02 20:36:31 +00:00
return err
2014-12-21 17:10:19 +00:00
}
// Decrypt authenticates and decrypts ciphertext and returns the plaintext.
func (r *Repository) Decrypt(ciphertext []byte) ([]byte, error) {
return r.decryptTo(nil, ciphertext)
}
// decrypt authenticates and decrypts ciphertext and stores the result in
// plaintext.
func (r *Repository) decryptTo(plaintext, ciphertext []byte) ([]byte, error) {
if r.key == nil {
2015-05-09 11:25:52 +00:00
return nil, errors.New("key for repository not set")
2014-12-21 17:10:19 +00:00
}
return crypto.Decrypt(r.key, nil, ciphertext)
2014-12-21 17:10:19 +00:00
}
// Encrypt encrypts and authenticates the plaintext and saves the result in
// ciphertext.
func (r *Repository) Encrypt(ciphertext, plaintext []byte) ([]byte, error) {
if r.key == nil {
2015-05-09 11:25:52 +00:00
return nil, errors.New("key for repository not set")
2014-12-21 17:10:19 +00:00
}
return crypto.Encrypt(r.key, ciphertext, plaintext)
2014-12-21 17:10:19 +00:00
}
// Key returns the current master key.
func (r *Repository) Key() *crypto.Key {
return r.key
2014-12-21 17:10:19 +00:00
}
// KeyName returns the name of the current key in the backend.
func (r *Repository) KeyName() string {
return r.keyName
}
2015-03-28 10:50:23 +00:00
// Count returns the number of blobs of a given type in the backend.
func (r *Repository) Count(t backend.Type) (n uint) {
for _ = range r.be.List(t, nil) {
2015-03-28 10:50:23 +00:00
n++
2015-02-21 14:32:48 +00:00
}
2015-03-28 10:50:23 +00:00
return
2015-02-21 14:32:48 +00:00
}
func (r *Repository) list(t backend.Type, done <-chan struct{}, out chan<- backend.ID) {
defer close(out)
in := r.be.List(t, done)
var (
// disable sending on the outCh until we received a job
outCh chan<- backend.ID
// enable receiving from in
inCh = in
id backend.ID
err error
)
for {
select {
case <-done:
return
case strID, ok := <-inCh:
if !ok {
// input channel closed, we're done
return
}
id, err = backend.ParseID(strID)
if err != nil {
// ignore invalid IDs
continue
}
2014-12-21 16:02:49 +00:00
inCh = nil
outCh = out
case outCh <- id:
outCh = nil
inCh = in
}
}
2015-04-26 12:46:15 +00:00
}
// List returns a channel that yields all IDs of type t in the backend.
func (r *Repository) List(t backend.Type, done <-chan struct{}) <-chan backend.ID {
outCh := make(chan backend.ID)
go r.list(t, done, outCh)
return outCh
2014-12-21 16:02:49 +00:00
}
2016-05-08 11:51:21 +00:00
// ListPack returns the list of blobs saved in the pack id.
func (r *Repository) ListPack(id backend.ID) ([]pack.Blob, error) {
h := backend.Handle{Type: backend.Data, Name: id.String()}
rd := backend.NewReadSeeker(r.Backend(), h)
unpacker, err := pack.NewUnpacker(r.Key(), rd)
if err != nil {
return nil, err
}
return unpacker.Entries, nil
}
// Delete calls backend.Delete() if implemented, and returns an error
// otherwise.
func (r *Repository) Delete() error {
if b, ok := r.be.(backend.Deleter); ok {
2014-12-21 16:02:49 +00:00
return b.Delete()
}
return errors.New("Delete() called for backend that does not implement this method")
}
// Close closes the repository by closing the backend.
func (r *Repository) Close() error {
return r.be.Close()
2015-03-28 10:50:23 +00:00
}