flatfs.go 9.49 KB
Newer Older
Tommi Virtanen's avatar
Tommi Virtanen committed
1 2 3 4 5 6 7
// Package flatfs is a Datastore implementation that stores all
// objects in a two-level directory structure in the local file
// system, regardless of the hierarchy of the keys.
package flatfs

import (
	"errors"
8
	"fmt"
Tommi Virtanen's avatar
Tommi Virtanen committed
9 10
	"io/ioutil"
	"os"
Jeromy's avatar
Jeromy committed
11
	"path/filepath"
Tommi Virtanen's avatar
Tommi Virtanen committed
12
	"strings"
13
	"time"
Tommi Virtanen's avatar
Tommi Virtanen committed
14

Jeromy's avatar
Jeromy committed
15 16
	"github.com/ipfs/go-datastore"
	"github.com/ipfs/go-datastore/query"
Jakub Sztandera's avatar
Jakub Sztandera committed
17
	"github.com/jbenet/go-os-rename"
18

Jakub Sztandera's avatar
Jakub Sztandera committed
19
	logging "github.com/ipfs/go-log"
Tommi Virtanen's avatar
Tommi Virtanen committed
20 21
)

22 23
var log = logging.Logger("flatfs")

Tommi Virtanen's avatar
Tommi Virtanen committed
24
const (
25
	extension = ".data"
Tommi Virtanen's avatar
Tommi Virtanen committed
26 27 28 29
)

type Datastore struct {
	path string
30

31 32
	shardStr string
	getDir   ShardFunc
Jeromy's avatar
Jeromy committed
33 34 35

	// sychronize all writes and directory changes for added safety
	sync bool
Tommi Virtanen's avatar
Tommi Virtanen committed
36 37
}

38 39
type ShardFunc func(string) string

40 41
var _ datastore.Datastore = (*Datastore)(nil)

Kevin Atkinson's avatar
Kevin Atkinson committed
42
var (
43 44
	ErrDatastoreExists       = errors.New("datastore already exist")
	ErrDatastoreDoesNotExist = errors.New("datastore directory does not exist")
45
	ErrShardingFileMissing   = fmt.Errorf("%s file not found in datastore", SHARDING_FN)
Kevin Atkinson's avatar
Kevin Atkinson committed
46
)
47

48
func Create(path string, fun *ShardIdV1) error {
49

kpcyrd's avatar
kpcyrd committed
50
	err := os.Mkdir(path, 0755)
51 52
	if err != nil && !os.IsExist(err) {
		return err
Tommi Virtanen's avatar
Tommi Virtanen committed
53 54
	}

55 56
	dsFun, err := ReadShardFunc(path)
	switch err {
Kevin Atkinson's avatar
Kevin Atkinson committed
57
	case ErrShardingFileMissing:
58 59 60 61 62
		isEmpty, err := DirIsEmpty(path)
		if err != nil {
			return err
		}
		if !isEmpty {
63
			return fmt.Errorf("directory missing %s file: %s", SHARDING_FN, path)
64 65 66
		}

		err = WriteShardFunc(path, fun)
67 68 69
		if err != nil {
			return err
		}
70 71
		err = WriteReadme(path, fun)
		return err
72
	case nil:
73
		if fun.String() != dsFun.String() {
74
			return fmt.Errorf("specified shard func '%s' does not match repo shard func '%s'",
75
				fun.String(), dsFun.String())
76
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
77
		return ErrDatastoreExists
78
	default:
79
		return err
80
	}
81 82 83 84 85
}

func Open(path string, sync bool) (*Datastore, error) {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
Kevin Atkinson's avatar
Kevin Atkinson committed
86
		return nil, ErrDatastoreDoesNotExist
87 88 89 90
	} else if err != nil {
		return nil, err
	}

91
	shardId, err := ReadShardFunc(path)
92
	if err != nil {
93
		return nil, err
94 95
	}

96
	fs := &Datastore{
97 98 99 100
		path:     path,
		shardStr: shardId.String(),
		getDir:   shardId.Func(),
		sync:     sync,
101
	}
102 103 104
	return fs, nil
}

105
// convenience method
106
func CreateOrOpen(path string, fun *ShardIdV1, sync bool) (*Datastore, error) {
107
	err := Create(path, fun)
Kevin Atkinson's avatar
Kevin Atkinson committed
108
	if err != nil && err != ErrDatastoreExists {
109 110 111 112 113
		return nil, err
	}
	return Open(path, sync)
}

114 115
func (fs *Datastore) ShardStr() string {
	return fs.shardStr
116 117
}

Tommi Virtanen's avatar
Tommi Virtanen committed
118
func (fs *Datastore) encode(key datastore.Key) (dir, file string) {
119
	noslash := key.String()[1:]
Jeromy's avatar
Jeromy committed
120 121
	dir = filepath.Join(fs.path, fs.getDir(noslash))
	file = filepath.Join(dir, noslash+extension)
Tommi Virtanen's avatar
Tommi Virtanen committed
122 123 124
	return dir, file
}

125
func (fs *Datastore) decode(file string) (key datastore.Key, ok bool) {
Jeromy's avatar
Jeromy committed
126
	if filepath.Ext(file) != extension {
127 128 129
		return datastore.Key{}, false
	}
	name := file[:len(file)-len(extension)]
Jeromy's avatar
Jeromy committed
130
	return datastore.NewKey(name), true
131 132
}

133 134
func (fs *Datastore) makeDir(dir string) error {
	if err := fs.makeDirNoSync(dir); err != nil {
Jeromy's avatar
Jeromy committed
135
		return err
136 137 138 139 140 141
	}

	// In theory, if we create a new prefix dir and add a file to
	// it, the creation of the prefix dir itself might not be
	// durable yet. Sync the root dir after a successful mkdir of
	// a prefix dir, just to be paranoid.
Jeromy's avatar
Jeromy committed
142 143 144 145
	if fs.sync {
		if err := syncDir(fs.path); err != nil {
			return err
		}
146 147 148 149
	}
	return nil
}

150
func (fs *Datastore) makeDirNoSync(dir string) error {
kpcyrd's avatar
kpcyrd committed
151
	if err := os.Mkdir(dir, 0755); err != nil {
Jeromy's avatar
Jeromy committed
152 153 154 155 156 157 158 159 160
		// EEXIST is safe to ignore here, that just means the prefix
		// directory already existed.
		if !os.IsExist(err) {
			return err
		}
	}
	return nil
}

Jeromy's avatar
Jeromy committed
161
var putMaxRetries = 6
162

Tommi Virtanen's avatar
Tommi Virtanen committed
163 164 165 166 167 168
func (fs *Datastore) Put(key datastore.Key, value interface{}) error {
	val, ok := value.([]byte)
	if !ok {
		return datastore.ErrInvalidType
	}

169
	var err error
Jeromy's avatar
Jeromy committed
170
	for i := 1; i <= putMaxRetries; i++ {
171 172
		err = fs.doPut(key, val)
		if err == nil {
Jeromy's avatar
Jeromy committed
173
			break
174 175 176
		}

		if !strings.Contains(err.Error(), "too many open files") {
Jeromy's avatar
Jeromy committed
177
			break
178 179
		}

Or Rikon's avatar
Or Rikon committed
180
		log.Errorf("too many open files, retrying in %dms", 100*i)
Jeromy's avatar
Jeromy committed
181
		time.Sleep(time.Millisecond * 100 * time.Duration(i))
182 183 184 185 186
	}
	return err
}

func (fs *Datastore) doPut(key datastore.Key, val []byte) error {
Tommi Virtanen's avatar
Tommi Virtanen committed
187
	dir, path := fs.encode(key)
188
	if err := fs.makeDir(dir); err != nil {
189
		return err
Tommi Virtanen's avatar
Tommi Virtanen committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
	}

	tmp, err := ioutil.TempFile(dir, "put-")
	if err != nil {
		return err
	}
	closed := false
	removed := false
	defer func() {
		if !closed {
			// silence errcheck
			_ = tmp.Close()
		}
		if !removed {
			// silence errcheck
			_ = os.Remove(tmp.Name())
		}
	}()

	if _, err := tmp.Write(val); err != nil {
		return err
	}
Jeromy's avatar
Jeromy committed
212
	if fs.sync {
213
		if err := syncFile(tmp); err != nil {
Jeromy's avatar
Jeromy committed
214 215
			return err
		}
216
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
217 218 219 220 221
	if err := tmp.Close(); err != nil {
		return err
	}
	closed = true

222
	err = osrename.Rename(tmp.Name(), path)
Tommi Virtanen's avatar
Tommi Virtanen committed
223 224 225 226 227
	if err != nil {
		return err
	}
	removed = true

Jeromy's avatar
Jeromy committed
228 229 230 231
	if fs.sync {
		if err := syncDir(dir); err != nil {
			return err
		}
232
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
233 234 235
	return nil
}

Jeromy's avatar
Jeromy committed
236 237 238 239 240 241 242 243 244 245
func (fs *Datastore) putMany(data map[datastore.Key]interface{}) error {
	var dirsToSync []string
	files := make(map[*os.File]string)

	for key, value := range data {
		val, ok := value.([]byte)
		if !ok {
			return datastore.ErrInvalidType
		}
		dir, path := fs.encode(key)
246
		if err := fs.makeDirNoSync(dir); err != nil {
Jeromy's avatar
Jeromy committed
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 278 279 280
			return err
		}
		dirsToSync = append(dirsToSync, dir)

		tmp, err := ioutil.TempFile(dir, "put-")
		if err != nil {
			return err
		}

		if _, err := tmp.Write(val); err != nil {
			return err
		}

		files[tmp] = path
	}

	ops := make(map[*os.File]int)

	defer func() {
		for fi, _ := range files {
			val, _ := ops[fi]
			switch val {
			case 0:
				_ = fi.Close()
				fallthrough
			case 1:
				_ = os.Remove(fi.Name())
			}
		}
	}()

	// Now we sync everything
	// sync and close files
	for fi, _ := range files {
Jeromy's avatar
Jeromy committed
281
		if fs.sync {
282
			if err := syncFile(fi); err != nil {
Jeromy's avatar
Jeromy committed
283 284
				return err
			}
Jeromy's avatar
Jeromy committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
		}

		if err := fi.Close(); err != nil {
			return err
		}

		// signify closed
		ops[fi] = 1
	}

	// move files to their proper places
	for fi, path := range files {
		if err := osrename.Rename(fi.Name(), path); err != nil {
			return err
		}

		// signify removed
		ops[fi] = 2
	}

	// now sync the dirs for those files
Jeromy's avatar
Jeromy committed
306 307 308 309 310
	if fs.sync {
		for _, dir := range dirsToSync {
			if err := syncDir(dir); err != nil {
				return err
			}
Jeromy's avatar
Jeromy committed
311 312
		}

Jeromy's avatar
Jeromy committed
313 314 315 316
		// sync top flatfs dir
		if err := syncDir(fs.path); err != nil {
			return err
		}
Jeromy's avatar
Jeromy committed
317 318 319 320 321
	}

	return nil
}

Tommi Virtanen's avatar
Tommi Virtanen committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335
func (fs *Datastore) Get(key datastore.Key) (value interface{}, err error) {
	_, path := fs.encode(key)
	data, err := ioutil.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, datastore.ErrNotFound
		}
		// no specific error to return, so just pass it through
		return nil, err
	}
	return data, nil
}

func (fs *Datastore) Has(key datastore.Key) (exists bool, err error) {
Tommi Virtanen's avatar
Tommi Virtanen committed
336 337 338 339 340 341 342 343 344
	_, path := fs.encode(key)
	switch _, err := os.Stat(path); {
	case err == nil:
		return true, nil
	case os.IsNotExist(err):
		return false, nil
	default:
		return false, err
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
345 346 347
}

func (fs *Datastore) Delete(key datastore.Key) error {
Tommi Virtanen's avatar
Tommi Virtanen committed
348 349 350 351 352 353 354 355 356
	_, path := fs.encode(key)
	switch err := os.Remove(path); {
	case err == nil:
		return nil
	case os.IsNotExist(err):
		return datastore.ErrNotFound
	default:
		return err
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
357 358 359
}

func (fs *Datastore) Query(q query.Query) (query.Results, error) {
360 361 362 363 364 365 366 367 368 369 370
	if (q.Prefix != "" && q.Prefix != "/") ||
		len(q.Filters) > 0 ||
		len(q.Orders) > 0 ||
		q.Limit > 0 ||
		q.Offset > 0 ||
		!q.KeysOnly {
		// TODO this is overly simplistic, but the only caller is
		// `ipfs refs local` for now, and this gets us moving.
		return nil, errors.New("flatfs only supports listing all keys in random order")
	}

371
	reschan := make(chan query.Result, query.KeysOnlyBufSize)
Jeromy's avatar
Jeromy committed
372 373
	go func() {
		defer close(reschan)
374
		err := fs.walkTopLevel(fs.path, reschan)
Jeromy's avatar
Jeromy committed
375
		if err != nil {
376
			reschan <- query.Result{Error: errors.New("walk failed: " + err.Error())}
377
		}
Jeromy's avatar
Jeromy committed
378 379
	}()
	return query.ResultsWithChan(q, reschan), nil
Tommi Virtanen's avatar
Tommi Virtanen committed
380 381
}

382 383 384 385 386
func (fs *Datastore) walkTopLevel(path string, reschan chan query.Result) error {
	dir, err := os.Open(path)
	if err != nil {
		return err
	}
Kevin Atkinson's avatar
Kevin Atkinson committed
387
	defer dir.Close()
388 389 390 391 392
	names, err := dir.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, dir := range names {
Kevin Atkinson's avatar
Kevin Atkinson committed
393 394 395 396 397

		if len(dir) == 0 || dir[0] == '.' {
			continue
		}

398 399 400 401
		err = fs.walk(filepath.Join(path, dir), reschan)
		if err != nil {
			return err
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
402

403 404 405 406 407 408 409 410 411
	}
	return nil
}

func (fs *Datastore) walk(path string, reschan chan query.Result) error {
	dir, err := os.Open(path)
	if err != nil {
		return err
	}
Kevin Atkinson's avatar
Kevin Atkinson committed
412
	defer dir.Close()
413 414 415 416 417 418 419 420 421 422

	// ignore non-directories
	fileInfo, err := dir.Stat()
	if err != nil {
		return err
	}
	if !fileInfo.IsDir() {
		return nil
	}

423 424 425 426 427 428 429 430 431 432 433 434
	names, err := dir.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, fn := range names {

		if len(fn) == 0 || fn[0] == '.' {
			continue
		}

		key, ok := fs.decode(fn)
		if !ok {
435
			log.Warningf("failed to decode flatfs entry: %s", fn)
436 437 438 439 440 441 442 443 444 445 446 447
			continue
		}

		reschan <- query.Result{
			Entry: query.Entry{
				Key: key.String(),
			},
		}
	}
	return nil
}

Jeromy's avatar
Jeromy committed
448 449 450 451
func (fs *Datastore) Close() error {
	return nil
}

Jeromy's avatar
Jeromy committed
452
type flatfsBatch struct {
Jeromy's avatar
Jeromy committed
453 454 455 456 457 458
	puts    map[datastore.Key]interface{}
	deletes map[datastore.Key]struct{}

	ds *Datastore
}

Jeromy's avatar
Jeromy committed
459
func (fs *Datastore) Batch() (datastore.Batch, error) {
Jeromy's avatar
Jeromy committed
460
	return &flatfsBatch{
Jeromy's avatar
Jeromy committed
461 462 463
		puts:    make(map[datastore.Key]interface{}),
		deletes: make(map[datastore.Key]struct{}),
		ds:      fs,
Jeromy's avatar
Jeromy committed
464
	}, nil
Jeromy's avatar
Jeromy committed
465 466
}

Jeromy's avatar
Jeromy committed
467
func (bt *flatfsBatch) Put(key datastore.Key, val interface{}) error {
Jeromy's avatar
Jeromy committed
468 469 470 471
	bt.puts[key] = val
	return nil
}

Jeromy's avatar
Jeromy committed
472
func (bt *flatfsBatch) Delete(key datastore.Key) error {
Jeromy's avatar
Jeromy committed
473 474 475 476
	bt.deletes[key] = struct{}{}
	return nil
}

Jeromy's avatar
Jeromy committed
477
func (bt *flatfsBatch) Commit() error {
Jeromy's avatar
Jeromy committed
478 479 480 481 482 483 484 485 486 487 488 489 490
	if err := bt.ds.putMany(bt.puts); err != nil {
		return err
	}

	for k, _ := range bt.deletes {
		if err := bt.ds.Delete(k); err != nil {
			return err
		}
	}

	return nil
}

Tommi Virtanen's avatar
Tommi Virtanen committed
491 492 493
var _ datastore.ThreadSafeDatastore = (*Datastore)(nil)

func (*Datastore) IsThreadSafe() {}