add_test.go 6.75 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
	"testing"
Jeromy's avatar
Jeromy committed
11
	"time"
12

13
	"github.com/ipfs/go-ipfs/blockservice"
14
	"github.com/ipfs/go-ipfs/core"
Jeromy's avatar
Jeromy committed
15 16
	dag "github.com/ipfs/go-ipfs/merkledag"
	"github.com/ipfs/go-ipfs/pin/gc"
17 18
	"github.com/ipfs/go-ipfs/repo"
	"github.com/ipfs/go-ipfs/repo/config"
Steven Allen's avatar
Steven Allen committed
19
	ds2 "github.com/ipfs/go-ipfs/thirdparty/datastore2"
Jeromy's avatar
Jeromy committed
20

Hector Sanjuan's avatar
Hector Sanjuan committed
21
	blockstore "gx/ipfs/QmaG4DZ4JaqEfvPWt5nPPgoTzhc1tr1T3f4Nu9Jpdm8ymY/go-ipfs-blockstore"
22
	pi "gx/ipfs/Qmb3jLEFAQrqdVgWUajqEyuuDoavkSq1XQXz6tWdFWF995/go-ipfs-posinfo"
Steven Allen's avatar
Steven Allen committed
23
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
24 25
	files "gx/ipfs/QmceUdzxkimdYsgtX733uNgzf1DLHyBKN6ehGSp85ayppM/go-ipfs-cmdkit/files"
	blocks "gx/ipfs/Qmej7nf81hi2x2tvjRBF3mcp74sQyuDH4VMYDGd1YtXjb2/go-block-format"
26 27
)

28 29
const testPeerID = "QmTFauExutTsy4XP6JbMFcw2Wa9645HJt2bTqL6qYDCKfe"

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

func TestAddGCLive(t *testing.T) {
	r := &repo.Mock{
		C: config.Config{
			Identity: config.Identity{
54
				PeerID: testPeerID, // required by offline node
Jeromy's avatar
Jeromy committed
55 56
			},
		},
Steven Allen's avatar
Steven Allen committed
57
		D: ds2.ThreadSafeCloserMapDatastore(),
Jeromy's avatar
Jeromy committed
58 59 60 61 62 63 64
	}
	node, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})
	if err != nil {
		t.Fatal(err)
	}

	out := make(chan interface{})
65
	adder, err := NewAdder(context.Background(), node.Pinning, node.Blockstore, node.DAG)
Jeromy's avatar
Jeromy committed
66 67 68
	if err != nil {
		t.Fatal(err)
	}
69
	adder.Out = out
Jeromy's avatar
Jeromy committed
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

	dataa := ioutil.NopCloser(bytes.NewBufferString("testfileA"))
	rfa := files.NewReaderFile("a", "a", dataa, nil)

	// make two files with pipes so we can 'pause' the add for timing of the test
	piper, pipew := io.Pipe()
	hangfile := files.NewReaderFile("b", "b", piper, nil)

	datad := ioutil.NopCloser(bytes.NewBufferString("testfileD"))
	rfd := files.NewReaderFile("d", "d", datad, nil)

	slf := files.NewSliceFile("files", "files", []files.File{rfa, hangfile, rfd})

	addDone := make(chan struct{})
	go func() {
		defer close(addDone)
		defer close(out)
		err := adder.AddFile(slf)

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

	}()

	addedHashes := make(map[string]struct{})
	select {
	case o := <-out:
		addedHashes[o.(*AddedObject).Hash] = struct{}{}
	case <-addDone:
		t.Fatal("add shouldnt complete yet")
	}

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

	// 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
125 126
	o := <-out
	addedHashes[o.(*AddedObject).Hash] = struct{}{}
Jeromy's avatar
Jeromy committed
127

128
	<-gcstarted
Jeromy's avatar
Jeromy committed
129

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

Jeromy's avatar
Jeromy committed
139
	var last *cid.Cid
Jeromy's avatar
Jeromy committed
140 141
	for a := range out {
		// wait for it to finish
Jeromy's avatar
Jeromy committed
142 143 144 145 146
		c, err := cid.Decode(a.(*AddedObject).Hash)
		if err != nil {
			t.Fatal(err)
		}
		last = c
Jeromy's avatar
Jeromy committed
147 148 149 150 151
	}

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

Jeromy's avatar
Jeromy committed
152
	set := cid.NewSet()
153
	err = dag.EnumerateChildren(ctx, dag.GetLinksWithDAG(node.DAG), last, set.Visit)
Jeromy's avatar
Jeromy committed
154 155 156 157
	if err != nil {
		t.Fatal(err)
	}
}
158 159 160 161 162

func testAddWPosInfo(t *testing.T, rawLeaves bool) {
	r := &repo.Mock{
		C: config.Config{
			Identity: config.Identity{
163
				PeerID: testPeerID, // required by offline node
164 165
			},
		},
Steven Allen's avatar
Steven Allen committed
166
		D: ds2.ThreadSafeCloserMapDatastore(),
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
	}
	node, err := core.NewNode(context.Background(), &core.BuildCfg{Repo: r})
	if err != nil {
		t.Fatal(err)
	}

	bs := &testBlockstore{GCBlockstore: node.Blockstore, expectedPath: "/tmp/foo.txt", t: t}
	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)
	}
	adder.Out = make(chan interface{})
	adder.Progress = true
	adder.RawLeaves = rawLeaves
183
	adder.NoCopy = true
184 185 186 187 188 189 190 191 192 193 194 195 196 197

	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()}
	file := files.NewReaderFile("foo.txt", "/tmp/foo.txt", fileData, &fileInfo)

	go func() {
		defer close(adder.Out)
		err = adder.AddFile(file)
		if err != nil {
			t.Fatal(err)
		}
	}()
198
	for range adder.Out {
199 200
	}

201 202 203 204 205
	exp := 0
	nonOffZero := 0
	if rawLeaves {
		exp = 1
		nonOffZero = 19
206
	}
207 208 209 210
	if bs.countAtOffsetZero != exp {
		t.Fatalf("expected %d blocks with an offset at zero (one root and one leafh), got %d", exp, bs.countAtOffsetZero)
	}
	if bs.countAtOffsetNonZero != nonOffZero {
211
		// note: the exact number will depend on the size and the sharding algo. used
212
		t.Fatalf("expected %d blocks with an offset > 0, got %d", nonOffZero, bs.countAtOffsetNonZero)
213 214 215 216 217 218 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
	}
}

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 }