flatfs.go 26.4 KB
Newer Older
Tommi Virtanen's avatar
Tommi Virtanen committed
1 2 3 4 5 6
// 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 (
7
	"encoding/json"
Tommi Virtanen's avatar
Tommi Virtanen committed
8
	"errors"
9
	"fmt"
Tommi Virtanen's avatar
Tommi Virtanen committed
10
	"io/ioutil"
11 12
	"math"
	"math/rand"
Tommi Virtanen's avatar
Tommi Virtanen committed
13
	"os"
Jeromy's avatar
Jeromy committed
14
	"path/filepath"
Tommi Virtanen's avatar
Tommi Virtanen committed
15
	"strings"
16 17
	"sync"
	"sync/atomic"
18
	"time"
Tommi Virtanen's avatar
Tommi Virtanen committed
19

Jeromy's avatar
Jeromy committed
20 21
	"github.com/ipfs/go-datastore"
	"github.com/ipfs/go-datastore/query"
Steven Allen's avatar
Steven Allen committed
22
	"github.com/jbenet/goprocess"
23

Jakub Sztandera's avatar
Jakub Sztandera committed
24
	logging "github.com/ipfs/go-log"
Tommi Virtanen's avatar
Tommi Virtanen committed
25 26
)

27 28
var log = logging.Logger("flatfs")

Tommi Virtanen's avatar
Tommi Virtanen committed
29
const (
30
	extension                  = ".data"
31
	diskUsageMessageTimeout    = 5 * time.Second
32
	diskUsageCheckpointPercent = 1.0
33
	diskUsageCheckpointTimeout = 2 * time.Second
Tommi Virtanen's avatar
Tommi Virtanen committed
34 35
)

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
var (
	// DiskUsageFile is the name of the file to cache the size of the
	// datastore in disk
	DiskUsageFile = "diskUsage.cache"
	// DiskUsageFilesAverage is the maximum number of files per folder
	// to stat in order to calculate the size of the datastore.
	// The size of the rest of the files in a folder will be assumed
	// to be the average of the values obtained. This includes
	// regular files and directories.
	DiskUsageFilesAverage = 2000
	// DiskUsageCalcTimeout is the maximum time to spend
	// calculating the DiskUsage upon a start when no
	// DiskUsageFile is present.
	// If this period did not suffice to read the size of the datastore,
	// the remaining sizes will be stimated.
	DiskUsageCalcTimeout = 5 * time.Minute
)

const (
	opPut = iota
	opDelete
	opRename
)

60 61 62
type initAccuracy string

const (
63
	unknownA  initAccuracy = "unknown"
64 65 66 67 68 69
	exactA    initAccuracy = "initial-exact"
	approxA   initAccuracy = "initial-approximate"
	timedoutA initAccuracy = "initial-timed-out"
)

func combineAccuracy(a, b initAccuracy) initAccuracy {
70 71 72
	if a == unknownA || b == unknownA {
		return unknownA
	}
73 74 75 76 77 78 79 80 81
	if a == timedoutA || b == timedoutA {
		return timedoutA
	}
	if a == approxA || b == approxA {
		return approxA
	}
	if a == exactA && b == exactA {
		return exactA
	}
82 83 84 85 86 87 88
	if a == "" {
		return b
	}
	if b == "" {
		return a
	}
	return unknownA
89 90
}

91 92 93 94 95 96
var _ datastore.Datastore = (*Datastore)(nil)

var (
	ErrDatastoreExists       = errors.New("datastore already exists")
	ErrDatastoreDoesNotExist = errors.New("datastore directory does not exist")
	ErrShardingFileMissing   = fmt.Errorf("%s file not found in datastore", SHARDING_FN)
Steven Allen's avatar
Steven Allen committed
97
	ErrClosed                = errors.New("datastore closed")
98
	ErrInvalidKey            = errors.New("key not supported by flatfs")
99 100 101 102 103 104 105 106 107 108
)

func init() {
	rand.Seed(time.Now().UTC().UnixNano())
}

// Datastore implements the go-datastore Interface.
// Note this datastore cannot guarantee order of concurrent
// write operations to the same key. See the explanation in
// Put().
Tommi Virtanen's avatar
Tommi Virtanen committed
109
type Datastore struct {
110 111 112 113 114
	// atmoic operations should always be used with diskUsage.
	// Must be first in struct to ensure correct alignment
	// (see https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
	diskUsage int64

115 116
	path     string
	tempPath string
117

118 119
	shardStr string
	getDir   ShardFunc
Jeromy's avatar
Jeromy committed
120 121 122

	// sychronize all writes and directory changes for added safety
	sync bool
123

124 125 126
	// these values should only be used during internalization or
	// inside the checkpoint loop
	dirty       bool
127
	storedValue diskUsageValue
128

Steven Allen's avatar
Steven Allen committed
129
	// Used to trigger a checkpoint.
Kevin Atkinson's avatar
Kevin Atkinson committed
130 131
	checkpointCh chan struct{}
	done         chan struct{}
132

Steven Allen's avatar
Steven Allen committed
133 134 135
	shutdownLock sync.RWMutex
	shutdown     bool

136 137 138
	// opMap handles concurrent write operations (put/delete)
	// to the same key
	opMap *opMap
Tommi Virtanen's avatar
Tommi Virtanen committed
139 140
}

141
type diskUsageValue struct {
142 143
	DiskUsage int64        `json:"diskUsage"`
	Accuracy  initAccuracy `json:"accuracy"`
144 145
}

146 147
type ShardFunc func(string) string

148
type opT int
149

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
// op wraps useful arguments of write operations
type op struct {
	typ  opT           // operation type
	key  datastore.Key // datastore key. Mandatory.
	tmp  string        // temp file path
	path string        // file path
	v    []byte        // value
}

type opMap struct {
	ops sync.Map
}

type opResult struct {
	mu      sync.RWMutex
	success bool

	opMap *opMap
	name  string
}

// Returns nil if there's nothing to do.
func (m *opMap) Begin(name string) *opResult {
	for {
		myOp := &opResult{opMap: m, name: name}
		myOp.mu.Lock()
		opIface, loaded := m.ops.LoadOrStore(name, myOp)
		if !loaded { // no one else doing ops with this key
			return myOp
		}

		op := opIface.(*opResult)
		// someone else doing ops with this key, wait for
		// the result
		op.mu.RLock()
		if op.success {
			return nil
		}

		// if we are here, we will retry the operation
	}
}

func (o *opResult) Finish(ok bool) {
	o.success = ok
	o.opMap.ops.Delete(o.name)
	o.mu.Unlock()
}
198

199
func Create(path string, fun *ShardIdV1) error {
kpcyrd's avatar
kpcyrd committed
200
	err := os.Mkdir(path, 0755)
201 202
	if err != nil && !os.IsExist(err) {
		return err
Tommi Virtanen's avatar
Tommi Virtanen committed
203 204
	}

205 206
	dsFun, err := ReadShardFunc(path)
	switch err {
Kevin Atkinson's avatar
Kevin Atkinson committed
207
	case ErrShardingFileMissing:
208 209 210 211 212
		isEmpty, err := DirIsEmpty(path)
		if err != nil {
			return err
		}
		if !isEmpty {
213
			return fmt.Errorf("directory missing %s file: %s", SHARDING_FN, path)
214 215 216
		}

		err = WriteShardFunc(path, fun)
217 218 219
		if err != nil {
			return err
		}
220 221
		err = WriteReadme(path, fun)
		return err
222
	case nil:
223
		if fun.String() != dsFun.String() {
224
			return fmt.Errorf("specified shard func '%s' does not match repo shard func '%s'",
225
				fun.String(), dsFun.String())
226
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
227
		return ErrDatastoreExists
228
	default:
229
		return err
230
	}
231 232
}

233
func Open(path string, syncFiles bool) (*Datastore, error) {
234 235
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
Kevin Atkinson's avatar
Kevin Atkinson committed
236
		return nil, ErrDatastoreDoesNotExist
237 238 239 240
	} else if err != nil {
		return nil, err
	}

241 242 243 244 245 246 247 248 249 250 251
	tempPath := filepath.Join(path, ".temp")
	err = os.RemoveAll(tempPath)
	if err != nil && !os.IsNotExist(err) {
		return nil, fmt.Errorf("failed to remove temporary directory: %w", err)
	}

	err = os.Mkdir(tempPath, 0755)
	if err != nil {
		return nil, fmt.Errorf("failed to create temporary directory: %w", err)
	}

252
	shardId, err := ReadShardFunc(path)
253
	if err != nil {
254
		return nil, err
255 256
	}

257
	fs := &Datastore{
Steven Allen's avatar
Steven Allen committed
258
		path:         path,
259
		tempPath:     tempPath,
Steven Allen's avatar
Steven Allen committed
260 261 262 263 264 265 266
		shardStr:     shardId.String(),
		getDir:       shardId.Func(),
		sync:         syncFiles,
		checkpointCh: make(chan struct{}, 1),
		done:         make(chan struct{}),
		diskUsage:    0,
		opMap:        new(opMap),
267 268 269 270 271 272 273 274 275 276 277
	}

	// This sets diskUsage to the correct value
	// It might be slow, but allowing it to happen
	// while the datastore is usable might
	// cause diskUsage to not be accurate.
	err = fs.calculateDiskUsage()
	if err != nil {
		// Cannot stat() all
		// elements in the datastore.
		return nil, err
278
	}
279

Kevin Atkinson's avatar
Kevin Atkinson committed
280
	go fs.checkpointLoop()
281 282 283
	return fs, nil
}

284
// convenience method
285
func CreateOrOpen(path string, fun *ShardIdV1, sync bool) (*Datastore, error) {
286
	err := Create(path, fun)
Kevin Atkinson's avatar
Kevin Atkinson committed
287
	if err != nil && err != ErrDatastoreExists {
288 289 290 291 292
		return nil, err
	}
	return Open(path, sync)
}

293 294
func (fs *Datastore) ShardStr() string {
	return fs.shardStr
295 296
}

Tommi Virtanen's avatar
Tommi Virtanen committed
297
func (fs *Datastore) encode(key datastore.Key) (dir, file string) {
298
	noslash := key.String()[1:]
Jeromy's avatar
Jeromy committed
299 300
	dir = filepath.Join(fs.path, fs.getDir(noslash))
	file = filepath.Join(dir, noslash+extension)
Tommi Virtanen's avatar
Tommi Virtanen committed
301 302 303
	return dir, file
}

304
func (fs *Datastore) decode(file string) (key datastore.Key, ok bool) {
305 306 307 308 309 310
	if !strings.HasSuffix(file, extension) {
		// We expect random files like "put-". Log when we encounter
		// others.
		if !strings.HasPrefix(file, "put-") {
			log.Warnw("failed to decode flatfs filename", "file", file)
		}
311 312 313
		return datastore.Key{}, false
	}
	name := file[:len(file)-len(extension)]
Jeromy's avatar
Jeromy committed
314
	return datastore.NewKey(name), true
315 316
}

317 318
func (fs *Datastore) makeDir(dir string) error {
	if err := fs.makeDirNoSync(dir); err != nil {
Jeromy's avatar
Jeromy committed
319
		return err
320 321 322 323 324 325
	}

	// 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
326 327 328 329
	if fs.sync {
		if err := syncDir(fs.path); err != nil {
			return err
		}
330 331 332 333
	}
	return nil
}

334
func (fs *Datastore) makeDirNoSync(dir string) error {
kpcyrd's avatar
kpcyrd committed
335
	if err := os.Mkdir(dir, 0755); err != nil {
Jeromy's avatar
Jeromy committed
336 337 338 339 340
		// EEXIST is safe to ignore here, that just means the prefix
		// directory already existed.
		if !os.IsExist(err) {
			return err
		}
341
		return nil
Jeromy's avatar
Jeromy committed
342
	}
343 344 345

	// Track DiskUsage of this NEW folder
	fs.updateDiskUsage(dir, true)
Jeromy's avatar
Jeromy committed
346 347 348
	return nil
}

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
// This function always runs under an opLock. Therefore, only one thread is
// touching the affected files.
func (fs *Datastore) renameAndUpdateDiskUsage(tmpPath, path string) error {
	fi, err := os.Stat(path)

	// Destination exists, we need to discount it from diskUsage
	if fs != nil && err == nil {
		atomic.AddInt64(&fs.diskUsage, -fi.Size())
	} else if !os.IsNotExist(err) {
		return err
	}

	// Rename and add new file's diskUsage. If the rename fails,
	// it will either a) Re-add the size of an existing file, which
	// was sustracted before b) Add 0 if there is no existing file.
364
	err = os.Rename(tmpPath, path)
365 366 367 368
	fs.updateDiskUsage(path, true)
	return err
}

Jeromy's avatar
Jeromy committed
369
var putMaxRetries = 6
370

371 372 373 374 375 376 377 378 379 380
// Put stores a key/value in the datastore.
//
// Note, that we do not guarantee order of write operations (Put or Delete)
// to the same key in this datastore.
//
// For example. i.e. in the case of two concurrent Put, we only guarantee
// that one of them will come through, but cannot assure which one even if
// one arrived slightly later than the other. In the case of a
// concurrent Put and a Delete operation, we cannot guarantee which one
// will win.
381
func (fs *Datastore) Put(key datastore.Key, value []byte) error {
382
	if !keyIsValid(key) {
383
		return fmt.Errorf("when putting '%q': %w", key, ErrInvalidKey)
384 385
	}

Steven Allen's avatar
Steven Allen committed
386 387 388 389 390 391
	fs.shutdownLock.RLock()
	defer fs.shutdownLock.RUnlock()
	if fs.shutdown {
		return ErrClosed
	}

392
	var err error
Jeromy's avatar
Jeromy committed
393
	for i := 1; i <= putMaxRetries; i++ {
394 395 396
		err = fs.doWriteOp(&op{
			typ: opPut,
			key: key,
397
			v:   value,
398
		})
399
		if err == nil {
Jeromy's avatar
Jeromy committed
400
			break
401 402 403
		}

		if !strings.Contains(err.Error(), "too many open files") {
Jeromy's avatar
Jeromy committed
404
			break
405 406
		}

Or Rikon's avatar
Or Rikon committed
407
		log.Errorf("too many open files, retrying in %dms", 100*i)
Jeromy's avatar
Jeromy committed
408
		time.Sleep(time.Millisecond * 100 * time.Duration(i))
409 410 411 412
	}
	return err
}

Adin Schmahmann's avatar
Adin Schmahmann committed
413 414 415 416 417 418 419 420 421 422
func (fs *Datastore) Sync(prefix datastore.Key) error {
	fs.shutdownLock.RLock()
	defer fs.shutdownLock.RUnlock()
	if fs.shutdown {
		return ErrClosed
	}

	return nil
}

423 424 425 426 427 428 429 430 431 432 433 434 435
func (fs *Datastore) doOp(oper *op) error {
	switch oper.typ {
	case opPut:
		return fs.doPut(oper.key, oper.v)
	case opDelete:
		return fs.doDelete(oper.key)
	case opRename:
		return fs.renameAndUpdateDiskUsage(oper.tmp, oper.path)
	default:
		panic("bad operation, this is a bug")
	}
}

436 437
// doWrite optimizes out write operations (put/delete) to the same
// key by queueing them and succeeding all queued
438
// operations if one of them does. In such case,
439
// we assume that the first succeeding operation
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
// on that key was the last one to happen after
// all successful others.
func (fs *Datastore) doWriteOp(oper *op) error {
	keyStr := oper.key.String()

	opRes := fs.opMap.Begin(keyStr)
	if opRes == nil { // nothing to do, a concurrent op succeeded
		return nil
	}

	// Do the operation
	err := fs.doOp(oper)

	// Finish it. If no error, it will signal other operations
	// waiting on this result to succeed. Otherwise, they will
	// retry.
	opRes.Finish(err == nil)
	return err
}

460
func (fs *Datastore) doPut(key datastore.Key, val []byte) error {
461

Tommi Virtanen's avatar
Tommi Virtanen committed
462
	dir, path := fs.encode(key)
463
	if err := fs.makeDir(dir); err != nil {
464
		return err
Tommi Virtanen's avatar
Tommi Virtanen committed
465 466
	}

467
	tmp, err := fs.tempFile()
Tommi Virtanen's avatar
Tommi Virtanen committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
	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
487
	if fs.sync {
488
		if err := syncFile(tmp); err != nil {
Jeromy's avatar
Jeromy committed
489 490
			return err
		}
491
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
492 493 494 495 496
	if err := tmp.Close(); err != nil {
		return err
	}
	closed = true

497
	err = fs.renameAndUpdateDiskUsage(tmp.Name(), path)
Tommi Virtanen's avatar
Tommi Virtanen committed
498 499 500 501 502
	if err != nil {
		return err
	}
	removed = true

Jeromy's avatar
Jeromy committed
503 504 505 506
	if fs.sync {
		if err := syncDir(dir); err != nil {
			return err
		}
507
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
508 509 510
	return nil
}

511
func (fs *Datastore) putMany(data map[datastore.Key][]byte) error {
Steven Allen's avatar
Steven Allen committed
512 513 514 515 516 517
	fs.shutdownLock.RLock()
	defer fs.shutdownLock.RUnlock()
	if fs.shutdown {
		return ErrClosed
	}

Jeromy's avatar
Jeromy committed
518 519
	var dirsToSync []string

520 521 522 523 524
	files := make(map[*os.File]*op, len(data))
	ops := make(map[*os.File]int, len(data))

	defer func() {
		for fi := range files {
Steven Allen's avatar
Steven Allen committed
525
			val := ops[fi]
526 527 528 529 530 531 532
			switch val {
			case 0:
				_ = fi.Close()
				fallthrough
			case 1:
				_ = os.Remove(fi.Name())
			}
Jeromy's avatar
Jeromy committed
533
		}
534 535 536
	}()

	for key, value := range data {
Jeromy's avatar
Jeromy committed
537
		dir, path := fs.encode(key)
538
		if err := fs.makeDirNoSync(dir); err != nil {
Jeromy's avatar
Jeromy committed
539 540 541 542
			return err
		}
		dirsToSync = append(dirsToSync, dir)

543
		tmp, err := fs.tempFile()
Jeromy's avatar
Jeromy committed
544 545 546 547
		if err != nil {
			return err
		}

548
		if _, err := tmp.Write(value); err != nil {
Jeromy's avatar
Jeromy committed
549 550 551
			return err
		}

552 553 554 555 556 557
		files[tmp] = &op{
			typ:  opRename,
			path: path,
			tmp:  tmp.Name(),
			key:  key,
		}
Jeromy's avatar
Jeromy committed
558 559 560 561
	}

	// Now we sync everything
	// sync and close files
562
	for fi := range files {
Jeromy's avatar
Jeromy committed
563
		if fs.sync {
564
			if err := syncFile(fi); err != nil {
Jeromy's avatar
Jeromy committed
565 566
				return err
			}
Jeromy's avatar
Jeromy committed
567 568 569 570 571 572 573 574 575 576 577
		}

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

		// signify closed
		ops[fi] = 1
	}

	// move files to their proper places
578
	for fi, op := range files {
579 580 581 582
		err := fs.doWriteOp(op)
		if err != nil {
			return err
		}
Jeromy's avatar
Jeromy committed
583 584 585 586 587
		// signify removed
		ops[fi] = 2
	}

	// now sync the dirs for those files
Jeromy's avatar
Jeromy committed
588 589 590 591 592
	if fs.sync {
		for _, dir := range dirsToSync {
			if err := syncDir(dir); err != nil {
				return err
			}
Jeromy's avatar
Jeromy committed
593 594
		}

Jeromy's avatar
Jeromy committed
595 596 597 598
		// sync top flatfs dir
		if err := syncDir(fs.path); err != nil {
			return err
		}
Jeromy's avatar
Jeromy committed
599 600 601 602 603
	}

	return nil
}

604
func (fs *Datastore) Get(key datastore.Key) (value []byte, err error) {
605 606 607 608 609
	// Can't exist in datastore.
	if !keyIsValid(key) {
		return nil, datastore.ErrNotFound
	}

Tommi Virtanen's avatar
Tommi Virtanen committed
610 611 612 613 614 615 616 617 618 619 620 621 622
	_, 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) {
623 624 625 626 627
	// Can't exist in datastore.
	if !keyIsValid(key) {
		return false, nil
	}

Tommi Virtanen's avatar
Tommi Virtanen committed
628 629 630 631 632 633 634 635 636
	_, 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
637 638
}

Steven Allen's avatar
Steven Allen committed
639
func (fs *Datastore) GetSize(key datastore.Key) (size int, err error) {
640 641 642 643 644
	// Can't exist in datastore.
	if !keyIsValid(key) {
		return -1, datastore.ErrNotFound
	}

Steven Allen's avatar
Steven Allen committed
645 646 647 648 649 650 651 652 653 654 655
	_, path := fs.encode(key)
	switch s, err := os.Stat(path); {
	case err == nil:
		return int(s.Size()), nil
	case os.IsNotExist(err):
		return -1, datastore.ErrNotFound
	default:
		return -1, err
	}
}

656 657 658
// Delete removes a key/value from the Datastore. Please read
// the Put() explanation about the handling of concurrent write
// operations to the same key.
Tommi Virtanen's avatar
Tommi Virtanen committed
659
func (fs *Datastore) Delete(key datastore.Key) error {
660 661 662 663 664
	// Can't exist in datastore.
	if !keyIsValid(key) {
		return nil
	}

Steven Allen's avatar
Steven Allen committed
665 666 667 668 669 670
	fs.shutdownLock.RLock()
	defer fs.shutdownLock.RUnlock()
	if fs.shutdown {
		return ErrClosed
	}

671 672 673 674 675 676 677 678 679 680
	return fs.doWriteOp(&op{
		typ: opDelete,
		key: key,
		v:   nil,
	})
}

// This function always runs within an opLock for the given
// key, and not concurrently.
func (fs *Datastore) doDelete(key datastore.Key) error {
Tommi Virtanen's avatar
Tommi Virtanen committed
681
	_, path := fs.encode(key)
682 683 684

	fSize := fileSize(path)

Tommi Virtanen's avatar
Tommi Virtanen committed
685 686
	switch err := os.Remove(path); {
	case err == nil:
687 688
		atomic.AddInt64(&fs.diskUsage, -fSize)
		fs.checkpointDiskUsage()
Tommi Virtanen's avatar
Tommi Virtanen committed
689 690
		return nil
	case os.IsNotExist(err):
Steven Allen's avatar
Steven Allen committed
691
		return nil
Tommi Virtanen's avatar
Tommi Virtanen committed
692 693 694
	default:
		return err
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
695 696 697
}

func (fs *Datastore) Query(q query.Query) (query.Results, error) {
Steven Allen's avatar
Steven Allen committed
698
	prefix := datastore.NewKey(q.Prefix).String()
699 700 701 702
	if prefix != "/" {
		// This datastore can't include keys with multiple components.
		// Therefore, it's always correct to return an empty result when
		// the user requests a filter by prefix.
703 704 705 706 707
		log.Warnw(
			"flatfs was queried with a key prefix but flatfs only supports keys at the root",
			"prefix", q.Prefix,
			"query", q,
		)
708 709
		return query.ResultsWithEntries(q, nil), nil
	}
710

Steven Allen's avatar
Steven Allen committed
711 712 713 714 715 716 717
	// Replicates the logic in ResultsWithChan but actually respects calls
	// to `Close`.
	b := query.NewResultBuilder(q)
	b.Process.Go(func(p goprocess.Process) {
		err := fs.walkTopLevel(fs.path, b)
		if err == nil {
			return
718
		}
Steven Allen's avatar
Steven Allen committed
719 720 721 722 723
		select {
		case b.Output <- query.Result{Error: errors.New("walk failed: " + err.Error())}:
		case <-p.Closing():
		}
	})
Steven Allen's avatar
Steven Allen committed
724
	go b.Process.CloseAfterChildren() //nolint
Steven Allen's avatar
Steven Allen committed
725

726 727 728
	// We don't apply _any_ of the query logic ourselves so we'll leave it
	// all up to the naive query engine.
	return query.NaiveQueryApply(q, b.Results()), nil
Tommi Virtanen's avatar
Tommi Virtanen committed
729 730
}

Steven Allen's avatar
Steven Allen committed
731
func (fs *Datastore) walkTopLevel(path string, result *query.ResultBuilder) error {
732 733 734 735
	dir, err := os.Open(path)
	if err != nil {
		return err
	}
Kevin Atkinson's avatar
Kevin Atkinson committed
736
	defer dir.Close()
737 738 739 740 741
	names, err := dir.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, dir := range names {
Kevin Atkinson's avatar
Kevin Atkinson committed
742 743 744 745
		if len(dir) == 0 || dir[0] == '.' {
			continue
		}

Steven Allen's avatar
Steven Allen committed
746
		err = fs.walk(filepath.Join(path, dir), result)
747 748 749
		if err != nil {
			return err
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
750

Steven Allen's avatar
Steven Allen committed
751 752 753 754 755 756
		// Are we closing?
		select {
		case <-result.Process.Closing():
			return nil
		default:
		}
757 758 759 760
	}
	return nil
}

761
// folderSize estimates the diskUsage of a folder by reading
762 763
// up to DiskUsageFilesAverage entries in it and assuming any
// other files will have an average size.
764
func folderSize(path string, deadline time.Time) (int64, initAccuracy, error) {
765 766 767 768
	var du int64

	folder, err := os.Open(path)
	if err != nil {
769
		return 0, "", err
770 771 772 773 774
	}
	defer folder.Close()

	stat, err := folder.Stat()
	if err != nil {
775
		return 0, "", err
776 777 778 779
	}

	files, err := folder.Readdirnames(-1)
	if err != nil {
780
		return 0, "", err
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
	}

	totalFiles := len(files)
	i := 0
	filesProcessed := 0
	maxFiles := DiskUsageFilesAverage
	if maxFiles <= 0 {
		maxFiles = totalFiles
	}

	// randomize file order
	// https://stackoverflow.com/a/42776696
	for i := len(files) - 1; i > 0; i-- {
		j := rand.Intn(i + 1)
		files[i], files[j] = files[j], files[i]
	}

798
	accuracy := exactA
799
	for {
800 801 802
		// Do not process any files after deadline is over
		if time.Now().After(deadline) {
			accuracy = timedoutA
803 804 805
			break
		}

806 807 808 809
		if i >= totalFiles || filesProcessed >= maxFiles {
			if filesProcessed >= maxFiles {
				accuracy = approxA
			}
810 811 812 813 814 815 816 817
			break
		}

		// Stat the file
		fname := files[i]
		subpath := filepath.Join(path, fname)
		st, err := os.Stat(subpath)
		if err != nil {
818
			return 0, "", err
819 820 821 822
		}

		// Find folder size recursively
		if st.IsDir() {
823
			du2, acc, err := folderSize(filepath.Join(subpath), deadline)
824
			if err != nil {
825
				return 0, "", err
826
			}
827
			accuracy = combineAccuracy(acc, accuracy)
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
			du += du2
			filesProcessed++
		} else { // in any other case, add the file size
			du += st.Size()
			filesProcessed++
		}

		i++
	}

	nonProcessed := totalFiles - filesProcessed

	// Avg is total size in this folder up to now / total files processed
	// it includes folders ant not folders
	avg := 0.0
	if filesProcessed > 0 {
		avg = float64(du) / float64(filesProcessed)
	}
	duEstimation := int64(avg * float64(nonProcessed))
	du += duEstimation
	du += stat.Size()
	//fmt.Println(path, "total:", totalFiles, "totalStat:", i, "totalFile:", filesProcessed, "left:", nonProcessed, "avg:", int(avg), "est:", int(duEstimation), "du:", du)
850
	return du, accuracy, nil
851 852 853 854
}

// calculateDiskUsage tries to read the DiskUsageFile for a cached
// diskUsage value, otherwise walks the datastore files.
855
// it is only safe to call in Open()
856 857 858
func (fs *Datastore) calculateDiskUsage() error {
	// Try to obtain a previously stored value from disk
	if persDu := fs.readDiskUsageFile(); persDu > 0 {
859
		fs.diskUsage = persDu
860 861 862
		return nil
	}

863 864 865 866 867 868 869
	msgDone := make(chan struct{}, 1) // prevent race condition
	msgTimer := time.AfterFunc(diskUsageMessageTimeout, func() {
		fmt.Printf("Calculating datastore size. This might take %s at most and will happen only once\n",
			DiskUsageCalcTimeout.String())
		msgDone <- struct{}{}
	})
	defer msgTimer.Stop()
870
	deadline := time.Now().Add(DiskUsageCalcTimeout)
871
	du, accuracy, err := folderSize(fs.path, deadline)
872 873 874
	if err != nil {
		return err
	}
875 876 877
	if !msgTimer.Stop() {
		<-msgDone
	}
878
	if accuracy == timedoutA {
879 880 881 882 883 884 885
		fmt.Println("WARN: It took to long to calculate the datastore size")
		fmt.Printf("WARN: The total size (%d) is an estimation. You can fix errors by\n", du)
		fmt.Printf("WARN: replacing the %s file with the right disk usage in bytes and\n",
			filepath.Join(fs.path, DiskUsageFile))
		fmt.Println("WARN: re-opening the datastore")
	}

886
	fs.storedValue.Accuracy = accuracy
887
	fs.diskUsage = du
888
	fs.writeDiskUsageFile(du, true)
889

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
	return nil
}

func fileSize(path string) int64 {
	fi, err := os.Stat(path)
	if err != nil {
		return 0
	}
	return fi.Size()
}

// updateDiskUsage reads the size of path and atomically
// increases or decreases the diskUsage variable.
// setting add to false will subtract from disk usage.
func (fs *Datastore) updateDiskUsage(path string, add bool) {
	fsize := fileSize(path)
	if !add {
		fsize = -fsize
	}

	if fsize != 0 {
911 912
		atomic.AddInt64(&fs.diskUsage, fsize)
		fs.checkpointDiskUsage()
913 914 915
	}
}

916
func (fs *Datastore) checkpointDiskUsage() {
917
	select {
Kevin Atkinson's avatar
Kevin Atkinson committed
918
	case fs.checkpointCh <- struct{}{}:
Kevin Atkinson's avatar
Tweaks.  
Kevin Atkinson committed
919
		// msg sent
920 921
	default:
		// checkpoint request already pending
922 923 924
	}
}

925
func (fs *Datastore) checkpointLoop() {
Steven Allen's avatar
Steven Allen committed
926 927
	defer close(fs.done)

928 929
	timerActive := true
	timer := time.NewTimer(0)
Kevin Atkinson's avatar
Tweaks.  
Kevin Atkinson committed
930
	defer timer.Stop()
931
	for {
932 933 934
		select {
		case _, more := <-fs.checkpointCh:
			du := atomic.LoadInt64(&fs.diskUsage)
Kevin Atkinson's avatar
Tweaks.  
Kevin Atkinson committed
935
			fs.dirty = true
936
			if !more { // shutting down
937
				fs.writeDiskUsageFile(du, true)
938
				if fs.dirty {
Steven Allen's avatar
Steven Allen committed
939
					log.Error("could not store final value of disk usage to file, future estimates may be inaccurate")
940
				}
941 942 943 944 945
				return
			}
			// If the difference between the checkpointed disk usage and
			// current one is larger than than `diskUsageCheckpointPercent`
			// of the checkpointed: store it.
946
			newDu := float64(du)
947
			lastCheckpointDu := float64(fs.storedValue.DiskUsage)
948
			diff := math.Abs(newDu - lastCheckpointDu)
949 950
			if lastCheckpointDu*diskUsageCheckpointPercent < diff*100.0 {
				fs.writeDiskUsageFile(du, false)
951
			}
952 953 954 955
			// Otherwise insure the value will be written to disk after
			// `diskUsageCheckpointTimeout`
			if fs.dirty && !timerActive {
				timer.Reset(diskUsageCheckpointTimeout)
Kevin Atkinson's avatar
Kevin Atkinson committed
956
				timerActive = true
957 958 959 960 961
			}
		case <-timer.C:
			timerActive = false
			if fs.dirty {
				du := atomic.LoadInt64(&fs.diskUsage)
962
				fs.writeDiskUsageFile(du, false)
963
			}
964
		}
965
	}
966 967
}

968
func (fs *Datastore) writeDiskUsageFile(du int64, doSync bool) {
969
	tmp, err := fs.tempFile()
970
	if err != nil {
Steven Allen's avatar
Steven Allen committed
971
		log.Warnw("could not write disk usage", "error", err)
972 973 974
		return
	}

975 976 977 978 979 980 981
	removed := false
	defer func() {
		if !removed {
			// silence errcheck
			_ = os.Remove(tmp.Name())
		}
	}()
982

983 984
	toWrite := fs.storedValue
	toWrite.DiskUsage = du
985
	encoder := json.NewEncoder(tmp)
986
	if err := encoder.Encode(&toWrite); err != nil {
Steven Allen's avatar
Steven Allen committed
987
		log.Warnw("cound not write disk usage", "error", err)
988 989
		return
	}
990

991 992
	if doSync {
		if err := tmp.Sync(); err != nil {
Steven Allen's avatar
Steven Allen committed
993
			log.Warnw("cound not sync", "error", err, "file", DiskUsageFile)
994 995 996 997
			return
		}
	}

998
	if err := tmp.Close(); err != nil {
Steven Allen's avatar
Steven Allen committed
999
		log.Warnw("cound not write disk usage", "error", err)
1000 1001 1002
		return
	}

1003
	if err := os.Rename(tmp.Name(), filepath.Join(fs.path, DiskUsageFile)); err != nil {
Steven Allen's avatar
Steven Allen committed
1004
		log.Warnw("cound not write disk usage", "error", err)
1005
		return
1006
	}
1007
	removed = true
1008

1009
	fs.storedValue = toWrite
1010
	fs.dirty = false
1011 1012
}

1013
// readDiskUsageFile is only safe to call in Open()
1014 1015 1016 1017 1018 1019
func (fs *Datastore) readDiskUsageFile() int64 {
	fpath := filepath.Join(fs.path, DiskUsageFile)
	duB, err := ioutil.ReadFile(fpath)
	if err != nil {
		return 0
	}
1020
	err = json.Unmarshal(duB, &fs.storedValue)
1021 1022 1023
	if err != nil {
		return 0
	}
1024
	return fs.storedValue.DiskUsage
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
}

// DiskUsage implements the PersistentDatastore interface
// and returns the current disk usage in bytes used by
// this datastore.
//
// The size is approximative and may slightly differ from
// the real disk values.
func (fs *Datastore) DiskUsage() (uint64, error) {
	// it may differ from real disk values if
	// the filesystem has allocated for blocks
	// for a directory because it has many files in it
	// we don't account for "resized" directories.
	// In a large datastore, the differences should be
	// are negligible though.

	du := atomic.LoadInt64(&fs.diskUsage)
	return uint64(du), nil
}

1045 1046 1047 1048
// Accuracy returns a string representing the accuracy of the
// DiskUsage() result, the value returned is implementation defined
// and for informational purposes only
func (fs *Datastore) Accuracy() string {
1049
	return string(fs.storedValue.Accuracy)
1050 1051
}

1052 1053 1054 1055 1056
func (fs *Datastore) tempFile() (*os.File, error) {
	file, err := ioutil.TempFile(fs.tempPath, "temp-")
	return file, err
}

1057
func (fs *Datastore) walk(path string, qrb *query.ResultBuilder) error {
1058 1059
	dir, err := os.Open(path)
	if err != nil {
1060 1061 1062 1063
		if os.IsNotExist(err) {
			// not an error if the file disappeared
			return nil
		}
1064 1065
		return err
	}
Kevin Atkinson's avatar
Kevin Atkinson committed
1066
	defer dir.Close()
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

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

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
	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 {
1089
			// not a block.
1090 1091 1092
			continue
		}

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
		var result query.Result
		result.Key = key.String()
		if !qrb.Query.KeysOnly {
			value, err := ioutil.ReadFile(filepath.Join(path, fn))
			if err != nil {
				result.Error = err
			} else {
				// NOTE: Don't set the value/size on error. We
				// don't want to return partial values.
				result.Value = value
				result.Size = len(value)
			}
		} else if qrb.Query.ReturnsSizes {
			var stat os.FileInfo
			stat, err := os.Stat(filepath.Join(path, fn))
			if err != nil {
				result.Error = err
			} else {
				result.Size = int(stat.Size())
			}
		}

Steven Allen's avatar
Steven Allen committed
1115
		select {
1116 1117
		case qrb.Output <- result:
		case <-qrb.Process.Closing():
Steven Allen's avatar
Steven Allen committed
1118
			return nil
1119 1120 1121 1122 1123
		}
	}
	return nil
}

1124 1125 1126
// Deactivate closes background maintenance threads, most write
// operations will fail but readonly operations will continue to
// function
Steven Allen's avatar
Steven Allen committed
1127
func (fs *Datastore) deactivate() {
Steven Allen's avatar
Steven Allen committed
1128 1129 1130
	fs.shutdownLock.Lock()
	defer fs.shutdownLock.Unlock()
	if fs.shutdown {
Steven Allen's avatar
Steven Allen committed
1131
		return
1132
	}
Steven Allen's avatar
Steven Allen committed
1133 1134 1135
	fs.shutdown = true
	close(fs.checkpointCh)
	<-fs.done
Jeromy's avatar
Jeromy committed
1136 1137
}

1138
func (fs *Datastore) Close() error {
Steven Allen's avatar
Steven Allen committed
1139 1140
	fs.deactivate()
	return nil
1141 1142
}

Jeromy's avatar
Jeromy committed
1143
type flatfsBatch struct {
1144
	puts    map[datastore.Key][]byte
Jeromy's avatar
Jeromy committed
1145 1146 1147 1148 1149
	deletes map[datastore.Key]struct{}

	ds *Datastore
}

Jeromy's avatar
Jeromy committed
1150
func (fs *Datastore) Batch() (datastore.Batch, error) {
Jeromy's avatar
Jeromy committed
1151
	return &flatfsBatch{
1152
		puts:    make(map[datastore.Key][]byte),
Jeromy's avatar
Jeromy committed
1153 1154
		deletes: make(map[datastore.Key]struct{}),
		ds:      fs,
Jeromy's avatar
Jeromy committed
1155
	}, nil
Jeromy's avatar
Jeromy committed
1156 1157
}

1158
func (bt *flatfsBatch) Put(key datastore.Key, val []byte) error {
1159
	if !keyIsValid(key) {
1160
		return fmt.Errorf("when putting '%q': %w", key, ErrInvalidKey)
1161
	}
Jeromy's avatar
Jeromy committed
1162 1163 1164 1165
	bt.puts[key] = val
	return nil
}

Jeromy's avatar
Jeromy committed
1166
func (bt *flatfsBatch) Delete(key datastore.Key) error {
1167 1168 1169
	if keyIsValid(key) {
		bt.deletes[key] = struct{}{}
	} // otherwise, delete is a no-op anyways.
Jeromy's avatar
Jeromy committed
1170 1171 1172
	return nil
}

Jeromy's avatar
Jeromy committed
1173
func (bt *flatfsBatch) Commit() error {
Jeromy's avatar
Jeromy committed
1174 1175 1176 1177
	if err := bt.ds.putMany(bt.puts); err != nil {
		return err
	}

Steven Allen's avatar
Steven Allen committed
1178
	for k := range bt.deletes {
Jeromy's avatar
Jeromy committed
1179 1180 1181 1182 1183 1184 1185
		if err := bt.ds.Delete(k); err != nil {
			return err
		}
	}

	return nil
}