export.go 4.96 KB
Newer Older
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
// Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package localstore

import (
	"archive/tar"
	"context"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"sync"

acud's avatar
acud committed
28
	"github.com/ethersphere/bee/pkg/postage"
29
	"github.com/ethersphere/bee/pkg/shed"
30 31
	"github.com/ethersphere/bee/pkg/storage"
	"github.com/ethersphere/bee/pkg/swarm"
32 33 34 35 36 37 38
)

const (
	// filename in tar archive that holds the information
	// about exported data format version
	exportVersionFilename = ".swarm-export-version"
	// current export format version
39
	currentExportVersion = "3"
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
)

// Export writes a tar structured data to the writer of
// all chunks in the retrieval data index. It returns the
// number of chunks exported.
func (db *DB) Export(w io.Writer) (count int64, err error) {
	tw := tar.NewWriter(w)
	defer tw.Close()

	if err := tw.WriteHeader(&tar.Header{
		Name: exportVersionFilename,
		Mode: 0644,
		Size: int64(len(currentExportVersion)),
	}); err != nil {
		return 0, err
	}
	if _, err := tw.Write([]byte(currentExportVersion)); err != nil {
		return 0, err
	}

	err = db.retrievalDataIndex.Iterate(func(item shed.Item) (stop bool, err error) {

		hdr := &tar.Header{
			Name: hex.EncodeToString(item.Address),
			Mode: 0644,
acud's avatar
acud committed
65
			Size: int64(postage.StampSize + len(item.Data)),
66 67 68 69 70
		}

		if err := tw.WriteHeader(hdr); err != nil {
			return false, err
		}
acud's avatar
acud committed
71 72 73
		if _, err := tw.Write(item.BatchID); err != nil {
			return false, err
		}
74 75 76 77 78 79
		if _, err := tw.Write(item.Index); err != nil {
			return false, err
		}
		if _, err := tw.Write(item.Timestamp); err != nil {
			return false, err
		}
acud's avatar
acud committed
80 81 82
		if _, err := tw.Write(item.Sig); err != nil {
			return false, err
		}
83 84 85 86 87 88 89 90 91 92 93 94 95
		if _, err := tw.Write(item.Data); err != nil {
			return false, err
		}
		count++
		return false, nil
	}, nil)

	return count, err
}

// Import reads a tar structured data from the reader and
// stores chunks in the database. It returns the number of
// chunks imported.
96
func (db *DB) Import(ctx context.Context, r io.Reader) (count int64, err error) {
97 98 99 100 101 102 103 104 105
	tr := tar.NewReader(r)

	errC := make(chan error)
	doneC := make(chan struct{})
	tokenPool := make(chan struct{}, 100)
	var wg sync.WaitGroup
	go func() {
		var (
			firstFile = true
106

107
			// if exportVersionFilename file is not present
108 109
			// assume current version
			version = currentExportVersion
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
		)
		for {
			hdr, err := tr.Next()
			if err != nil {
				if err == io.EOF {
					break
				}
				select {
				case errC <- err:
				case <-ctx.Done():
				}
			}
			if firstFile {
				firstFile = false
				if hdr.Name == exportVersionFilename {
					data, err := ioutil.ReadAll(tr)
					if err != nil {
						select {
						case errC <- err:
						case <-ctx.Done():
						}
					}
					version = string(data)
					continue
				}
			}

			if len(hdr.Name) != 64 {
138
				db.logger.Warningf("localstore export: ignoring non-chunk file: %s", hdr.Name)
139 140 141 142 143
				continue
			}

			keybytes, err := hex.DecodeString(hdr.Name)
			if err != nil {
144
				db.logger.Warningf("localstore export: ignoring invalid chunk file %s: %v", hdr.Name, err)
145 146 147
				continue
			}

acud's avatar
acud committed
148 149 150 151 152 153 154 155 156
			rawdata, err := ioutil.ReadAll(tr)
			if err != nil {
				select {
				case errC <- err:
				case <-ctx.Done():
				}
			}
			stamp := new(postage.Stamp)
			err = stamp.UnmarshalBinary(rawdata[:postage.StampSize])
157 158 159 160 161 162
			if err != nil {
				select {
				case errC <- err:
				case <-ctx.Done():
				}
			}
acud's avatar
acud committed
163
			data := rawdata[postage.StampSize:]
164
			key := swarm.NewAddress(keybytes)
165

166
			var ch swarm.Chunk
167 168
			switch version {
			case currentExportVersion:
acud's avatar
acud committed
169
				ch = swarm.NewChunk(key, data).WithStamp(stamp)
170 171 172 173 174 175 176 177 178 179
			default:
				select {
				case errC <- fmt.Errorf("unsupported export data version %q", version):
				case <-ctx.Done():
				}
			}
			tokenPool <- struct{}{}
			wg.Add(1)

			go func() {
180
				_, err := db.Put(ctx, storage.ModePutUpload, ch)
181 182 183 184 185 186
				select {
				case errC <- err:
				case <-ctx.Done():
					wg.Done()
					<-tokenPool
				default:
187
					_, err := db.Put(ctx, storage.ModePutUpload, ch)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
					if err != nil {
						errC <- err
					}
					wg.Done()
					<-tokenPool
				}
			}()

			count++
		}
		wg.Wait()
		close(doneC)
	}()

	// wait for all chunks to be stored
	for {
		select {
		case err := <-errC:
			if err != nil {
				return count, err
			}
		case <-ctx.Done():
			return count, ctx.Err()
		default:
			select {
			case <-doneC:
				return count, nil
			default:
			}
		}
	}
}