add_test.go 7 KB
Newer Older
1 2 3
package coreunix

import (
Jeromy's avatar
Jeromy committed
4
	"bytes"
5
	"context"
Jeromy's avatar
Jeromy committed
6 7
	"io"
	"io/ioutil"
8 9
	"math/rand"
	"os"
10
	"path/filepath"
11
	"testing"
Jeromy's avatar
Jeromy committed
12
	"time"
13

14
	"github.com/ipfs/go-ipfs/core"
15
	coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
Jeromy's avatar
Jeromy committed
16
	"github.com/ipfs/go-ipfs/pin/gc"
17
	"github.com/ipfs/go-ipfs/repo"
18

Steven Allen's avatar
Steven Allen committed
19
	"gx/ipfs/QmPoh3SrQzFBWtdGK6qmHDV4EanKR6kYPj4DD3J2NLoEmZ/go-blockservice"
Steven Allen's avatar
Steven Allen committed
20 21
	pi "gx/ipfs/QmR6YMs8EkXQLXNwQKxLnQp2VBZSepoEJ8KCZAyanJHhJu/go-ipfs-posinfo"
	cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
22
	blockstore "gx/ipfs/QmS2aqUZLJp8kF1ihE5rvDGE5LvmKDPnx32w9Z1BW9xLV5/go-ipfs-blockstore"
Steven Allen's avatar
Steven Allen committed
23
	blocks "gx/ipfs/QmWoXtvgC8inqFkAATB7cp2Dax7XBi9VDvSg9RCCZufmRk/go-block-format"
24
	files "gx/ipfs/QmXWZCd8jfaHmt4UDSnjKmGcrQMw95bDGWqEeVLVJjoANX/go-ipfs-files"
Steven Allen's avatar
Steven Allen committed
25 26
	config "gx/ipfs/QmYyzmMnhNTtoXx5ttgUaRdHHckYnQWjPL98hgLAR2QLDD/go-ipfs-config"
	dag "gx/ipfs/QmdV35UHnL1FM52baPkeUo6u7Fxm2CRUkPTLRPxeF8a4Ap/go-merkledag"
27 28
	datastore "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore"
	syncds "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/sync"
29 30
)

31 32
const testPeerID = "QmTFauExutTsy4XP6JbMFcw2Wa9645HJt2bTqL6qYDCKfe"

33 34 35 36
func TestAddRecursive(t *testing.T) {
	r := &repo.Mock{
		C: config.Config{
			Identity: config.Identity{
37
				PeerID: testPeerID, // required by offline node
38 39
			},
		},
40
		D: syncds.MutexWrap(datastore.NewMapDatastore()),
41
	}
42
	node, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})
43 44 45
	if err != nil {
		t.Fatal(err)
	}
camelmasa's avatar
camelmasa committed
46
	if k, err := AddR(node, "test/data"); err != nil {
47 48
		t.Fatal(err)
	} else if k != "QmWCCga8AbTyfAQ7pTnGT6JgmRMAB3Qp8ZmTEFi5q5o8jC" {
Jeromy's avatar
Jeromy committed
49
		t.Fatal("keys do not match: ", k)
50 51
	}
}
Jeromy's avatar
Jeromy committed
52 53 54 55 56

func TestAddGCLive(t *testing.T) {
	r := &repo.Mock{
		C: config.Config{
			Identity: config.Identity{
57
				PeerID: testPeerID, // required by offline node
Jeromy's avatar
Jeromy committed
58 59
			},
		},
60
		D: syncds.MutexWrap(datastore.NewMapDatastore()),
Jeromy's avatar
Jeromy committed
61 62 63 64 65 66 67
	}
	node, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})
	if err != nil {
		t.Fatal(err)
	}

	out := make(chan interface{})
68
	adder, err := NewAdder(context.Background(), node.Pinning, node.Blockstore, node.DAG)
Jeromy's avatar
Jeromy committed
69 70 71
	if err != nil {
		t.Fatal(err)
	}
72
	adder.Out = out
Jeromy's avatar
Jeromy committed
73

74
	rfa := files.FileFrom([]byte("testfileA"))
Jeromy's avatar
Jeromy committed
75 76 77

	// make two files with pipes so we can 'pause' the add for timing of the test
	piper, pipew := io.Pipe()
78
	hangfile := files.FileFrom(piper)
Jeromy's avatar
Jeromy committed
79

80
	rfd := files.FileFrom([]byte("testfileD"))
Jeromy's avatar
Jeromy committed
81

82 83 84 85
	slf := files.DirFrom(map[string]files.Node{
		"a": rfa,
		"b": hangfile,
		"d": rfd,
Łukasz Magiera's avatar
Łukasz Magiera committed
86
	})
Jeromy's avatar
Jeromy committed
87 88 89 90 91

	addDone := make(chan struct{})
	go func() {
		defer close(addDone)
		defer close(out)
92
		_, err := adder.AddAllAndPin(slf)
Jeromy's avatar
Jeromy committed
93 94 95 96 97 98 99 100 101 102

		if err != nil {
			t.Fatal(err)
		}

	}()

	addedHashes := make(map[string]struct{})
	select {
	case o := <-out:
103
		addedHashes[o.(*coreiface.AddEvent).Hash] = struct{}{}
Jeromy's avatar
Jeromy committed
104 105 106 107
	case <-addDone:
		t.Fatal("add shouldnt complete yet")
	}

108
	var gcout <-chan gc.Result
Jeromy's avatar
Jeromy committed
109 110 111
	gcstarted := make(chan struct{})
	go func() {
		defer close(gcstarted)
112
		gcout = gc.GC(context.Background(), node.Blockstore, node.Repo.Datastore(), node.Pinning, nil)
Jeromy's avatar
Jeromy committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
	}()

	// gc shouldnt start until we let the add finish its current file.
	pipew.Write([]byte("some data for file b"))

	select {
	case <-gcstarted:
		t.Fatal("gc shouldnt have started yet")
	default:
	}

	time.Sleep(time.Millisecond * 100) // make sure gc gets to requesting lock

	// finish write and unblock gc
	pipew.Close()

	// receive next object from adder
130
	o := <-out
131
	addedHashes[o.(*coreiface.AddEvent).Hash] = struct{}{}
Jeromy's avatar
Jeromy committed
132

133
	<-gcstarted
Jeromy's avatar
Jeromy committed
134

135 136 137 138 139
	for r := range gcout {
		if r.Error != nil {
			t.Fatal(err)
		}
		if _, ok := addedHashes[r.KeyRemoved.String()]; ok {
Jeromy's avatar
Jeromy committed
140 141 142 143
			t.Fatal("gc'ed a hash we just added")
		}
	}

144
	var last cid.Cid
Jeromy's avatar
Jeromy committed
145 146
	for a := range out {
		// wait for it to finish
147
		c, err := cid.Decode(a.(*coreiface.AddEvent).Hash)
Jeromy's avatar
Jeromy committed
148 149 150 151
		if err != nil {
			t.Fatal(err)
		}
		last = c
Jeromy's avatar
Jeromy committed
152 153 154 155 156
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()

Jeromy's avatar
Jeromy committed
157
	set := cid.NewSet()
158
	err = dag.EnumerateChildren(ctx, dag.GetLinksWithDAG(node.DAG), last, set.Visit)
Jeromy's avatar
Jeromy committed
159 160 161 162
	if err != nil {
		t.Fatal(err)
	}
}
163 164 165 166 167

func testAddWPosInfo(t *testing.T, rawLeaves bool) {
	r := &repo.Mock{
		C: config.Config{
			Identity: config.Identity{
168
				PeerID: testPeerID, // required by offline node
169 170
			},
		},
171
		D: syncds.MutexWrap(datastore.NewMapDatastore()),
172 173 174 175 176 177
	}
	node, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})
	if err != nil {
		t.Fatal(err)
	}

178
	bs := &testBlockstore{GCBlockstore: node.Blockstore, expectedPath: filepath.Join(os.TempDir(), "foo.txt"), t: t}
179 180 181 182 183 184
	bserv := blockservice.New(bs, node.Exchange)
	dserv := dag.NewDAGService(bserv)
	adder, err := NewAdder(context.Background(), node.Pinning, bs, dserv)
	if err != nil {
		t.Fatal(err)
	}
185 186
	out := make(chan interface{})
	adder.Out = out
187 188
	adder.Progress = true
	adder.RawLeaves = rawLeaves
189
	adder.NoCopy = true
190 191 192 193 194

	data := make([]byte, 5*1024*1024)
	rand.New(rand.NewSource(2)).Read(data) // Rand.Read never returns an error
	fileData := ioutil.NopCloser(bytes.NewBuffer(data))
	fileInfo := dummyFileInfo{"foo.txt", int64(len(data)), time.Now()}
195
	file, _ := files.NewReaderPathFile(filepath.Join(os.TempDir(), "foo.txt"), fileData, &fileInfo)
196 197 198

	go func() {
		defer close(adder.Out)
199
		_, err = adder.AddAllAndPin(file)
200 201 202 203
		if err != nil {
			t.Fatal(err)
		}
	}()
204
	for range out {
205 206
	}

207 208 209 210 211
	exp := 0
	nonOffZero := 0
	if rawLeaves {
		exp = 1
		nonOffZero = 19
212
	}
213
	if bs.countAtOffsetZero != exp {
214
		t.Fatalf("expected %d blocks with an offset at zero (one root and one leaf), got %d", exp, bs.countAtOffsetZero)
215 216
	}
	if bs.countAtOffsetNonZero != nonOffZero {
217
		// note: the exact number will depend on the size and the sharding algo. used
218
		t.Fatalf("expected %d blocks with an offset > 0, got %d", nonOffZero, bs.countAtOffsetNonZero)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	}
}

func TestAddWPosInfo(t *testing.T) {
	testAddWPosInfo(t, false)
}

func TestAddWPosInfoAndRawLeafs(t *testing.T) {
	testAddWPosInfo(t, true)
}

type testBlockstore struct {
	blockstore.GCBlockstore
	expectedPath         string
	t                    *testing.T
	countAtOffsetZero    int
	countAtOffsetNonZero int
}

func (bs *testBlockstore) Put(block blocks.Block) error {
	bs.CheckForPosInfo(block)
	return bs.GCBlockstore.Put(block)
}

func (bs *testBlockstore) PutMany(blocks []blocks.Block) error {
	for _, blk := range blocks {
		bs.CheckForPosInfo(blk)
	}
	return bs.GCBlockstore.PutMany(blocks)
}

func (bs *testBlockstore) CheckForPosInfo(block blocks.Block) error {
	fsn, ok := block.(*pi.FilestoreNode)
	if ok {
		posInfo := fsn.PosInfo
		if posInfo.FullPath != bs.expectedPath {
			bs.t.Fatal("PosInfo does not have the expected path")
		}
		if posInfo.Offset == 0 {
			bs.countAtOffsetZero += 1
		} else {
			bs.countAtOffsetNonZero += 1
		}
	}
	return nil
}

type dummyFileInfo struct {
	name    string
	size    int64
	modTime time.Time
}

func (fi *dummyFileInfo) Name() string       { return fi.name }
func (fi *dummyFileInfo) Size() int64        { return fi.size }
func (fi *dummyFileInfo) Mode() os.FileMode  { return 0 }
func (fi *dummyFileInfo) ModTime() time.Time { return fi.modTime }
func (fi *dummyFileInfo) IsDir() bool        { return false }
func (fi *dummyFileInfo) Sys() interface{}   { return nil }