flatfs.go 8.58 KB
Newer Older
Tommi Virtanen's avatar
Tommi Virtanen committed
1 2 3 4 5 6 7 8 9 10
// 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"
	"io/ioutil"
	"os"
	"path"
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

	getDir ShardFunc
Jeromy's avatar
Jeromy committed
32 33 34

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

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

39 40 41
type ShardFunc func(string) string

func New(path string, getDir ShardFunc, sync bool) (*Datastore, error) {
Tommi Virtanen's avatar
Tommi Virtanen committed
42
	fs := &Datastore{
43 44 45
		path:   path,
		getDir: getDir,
		sync:   sync,
Tommi Virtanen's avatar
Tommi Virtanen committed
46 47 48 49
	}
	return fs, nil
}

50 51 52 53 54 55 56 57 58 59 60 61 62 63
func Prefix(prefixLen int) ShardFunc {
	padding := strings.Repeat("_", prefixLen)
	return func(noslash string) string {
		return (noslash + padding)[:prefixLen]
	}
}

func Suffix(suffixLen int) ShardFunc {
	padding := strings.Repeat("_", suffixLen)
	return func(noslash string) string {
		str := padding + noslash
		return str[len(str)-suffixLen:]
	}
}
Tommi Virtanen's avatar
Tommi Virtanen committed
64

65 66 67 68 69 70 71 72 73
func NextToLast(suffixLen int) ShardFunc {
	padding := strings.Repeat("_", suffixLen+1)
	return func(noslash string) string {
		str := padding + noslash
		offset := len(str) - suffixLen - 1
		return str[offset : offset+suffixLen]
	}
}

Tommi Virtanen's avatar
Tommi Virtanen committed
74
func (fs *Datastore) encode(key datastore.Key) (dir, file string) {
75
	noslash := key.String()[1:]
76
	dir = path.Join(fs.path, fs.getDir(noslash))
77
	file = path.Join(dir, noslash+extension)
Tommi Virtanen's avatar
Tommi Virtanen committed
78 79 80
	return dir, file
}

81 82 83 84 85
func (fs *Datastore) decode(file string) (key datastore.Key, ok bool) {
	if path.Ext(file) != extension {
		return datastore.Key{}, false
	}
	name := file[:len(file)-len(extension)]
Jeromy's avatar
Jeromy committed
86
	return datastore.NewKey(name), true
87 88
}

89 90
func (fs *Datastore) makeDir(dir string) error {
	if err := fs.makeDirNoSync(dir); err != nil {
Jeromy's avatar
Jeromy committed
91
		return err
92 93 94 95 96 97
	}

	// 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
98 99 100 101
	if fs.sync {
		if err := syncDir(fs.path); err != nil {
			return err
		}
102 103 104 105
	}
	return nil
}

106
func (fs *Datastore) makeDirNoSync(dir string) error {
Jeromy's avatar
Jeromy committed
107 108 109 110 111 112 113 114 115 116
	if err := os.Mkdir(dir, 0777); err != nil {
		// 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
117
var putMaxRetries = 6
118

Tommi Virtanen's avatar
Tommi Virtanen committed
119 120 121 122 123 124
func (fs *Datastore) Put(key datastore.Key, value interface{}) error {
	val, ok := value.([]byte)
	if !ok {
		return datastore.ErrInvalidType
	}

125
	var err error
Jeromy's avatar
Jeromy committed
126
	for i := 1; i <= putMaxRetries; i++ {
127 128
		err = fs.doPut(key, val)
		if err == nil {
Jeromy's avatar
Jeromy committed
129
			break
130 131 132
		}

		if !strings.Contains(err.Error(), "too many open files") {
Jeromy's avatar
Jeromy committed
133
			break
134 135
		}

Or Rikon's avatar
Or Rikon committed
136
		log.Errorf("too many open files, retrying in %dms", 100*i)
Jeromy's avatar
Jeromy committed
137
		time.Sleep(time.Millisecond * 100 * time.Duration(i))
138 139 140 141 142
	}
	return err
}

func (fs *Datastore) doPut(key datastore.Key, val []byte) error {
Tommi Virtanen's avatar
Tommi Virtanen committed
143
	dir, path := fs.encode(key)
144
	if err := fs.makeDir(dir); err != nil {
145
		return err
Tommi Virtanen's avatar
Tommi Virtanen committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
	}

	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
168
	if fs.sync {
169
		if err := syncFile(tmp); err != nil {
Jeromy's avatar
Jeromy committed
170 171
			return err
		}
172
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
173 174 175 176 177
	if err := tmp.Close(); err != nil {
		return err
	}
	closed = true

178
	err = osrename.Rename(tmp.Name(), path)
Tommi Virtanen's avatar
Tommi Virtanen committed
179 180 181 182 183
	if err != nil {
		return err
	}
	removed = true

Jeromy's avatar
Jeromy committed
184 185 186 187
	if fs.sync {
		if err := syncDir(dir); err != nil {
			return err
		}
188
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
189 190 191
	return nil
}

Jeromy's avatar
Jeromy committed
192 193 194 195 196 197 198 199 200 201
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)
202
		if err := fs.makeDirNoSync(dir); err != nil {
Jeromy's avatar
Jeromy committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
			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
237
		if fs.sync {
238
			if err := syncFile(fi); err != nil {
Jeromy's avatar
Jeromy committed
239 240
				return err
			}
Jeromy's avatar
Jeromy committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
		}

		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
262 263 264 265 266
	if fs.sync {
		for _, dir := range dirsToSync {
			if err := syncDir(dir); err != nil {
				return err
			}
Jeromy's avatar
Jeromy committed
267 268
		}

Jeromy's avatar
Jeromy committed
269 270 271 272
		// sync top flatfs dir
		if err := syncDir(fs.path); err != nil {
			return err
		}
Jeromy's avatar
Jeromy committed
273 274 275 276 277
	}

	return nil
}

Tommi Virtanen's avatar
Tommi Virtanen committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291
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
292 293 294 295 296 297 298 299 300
	_, 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
301 302 303
}

func (fs *Datastore) Delete(key datastore.Key) error {
Tommi Virtanen's avatar
Tommi Virtanen committed
304 305 306 307 308 309 310 311 312
	_, 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
313 314 315
}

func (fs *Datastore) Query(q query.Query) (query.Results, error) {
316 317 318 319 320 321 322 323 324 325 326
	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")
	}

327
	reschan := make(chan query.Result, query.KeysOnlyBufSize)
Jeromy's avatar
Jeromy committed
328 329
	go func() {
		defer close(reschan)
330
		err := fs.walkTopLevel(fs.path, reschan)
Jeromy's avatar
Jeromy committed
331
		if err != nil {
332
			reschan <- query.Result{Error: errors.New("walk failed: " + err.Error())}
333
		}
Jeromy's avatar
Jeromy committed
334 335
	}()
	return query.ResultsWithChan(q, reschan), nil
Tommi Virtanen's avatar
Tommi Virtanen committed
336 337
}

338 339 340 341 342
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
343
	defer dir.Close()
344 345 346 347 348
	names, err := dir.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, dir := range names {
Kevin Atkinson's avatar
Kevin Atkinson committed
349 350 351 352 353

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

354 355 356 357
		err = fs.walk(filepath.Join(path, dir), reschan)
		if err != nil {
			return err
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
358

359 360 361 362 363 364 365 366 367
	}
	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
368
	defer dir.Close()
369 370 371 372 373 374 375 376 377 378

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

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
	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 {
			log.Warning("failed to decode entry in flatfs")
			continue
		}

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

Jeromy's avatar
Jeromy committed
404 405 406 407
func (fs *Datastore) Close() error {
	return nil
}

Jeromy's avatar
Jeromy committed
408
type flatfsBatch struct {
Jeromy's avatar
Jeromy committed
409 410 411 412 413 414
	puts    map[datastore.Key]interface{}
	deletes map[datastore.Key]struct{}

	ds *Datastore
}

Jeromy's avatar
Jeromy committed
415
func (fs *Datastore) Batch() (datastore.Batch, error) {
Jeromy's avatar
Jeromy committed
416
	return &flatfsBatch{
Jeromy's avatar
Jeromy committed
417 418 419
		puts:    make(map[datastore.Key]interface{}),
		deletes: make(map[datastore.Key]struct{}),
		ds:      fs,
Jeromy's avatar
Jeromy committed
420
	}, nil
Jeromy's avatar
Jeromy committed
421 422
}

Jeromy's avatar
Jeromy committed
423
func (bt *flatfsBatch) Put(key datastore.Key, val interface{}) error {
Jeromy's avatar
Jeromy committed
424 425 426 427
	bt.puts[key] = val
	return nil
}

Jeromy's avatar
Jeromy committed
428
func (bt *flatfsBatch) Delete(key datastore.Key) error {
Jeromy's avatar
Jeromy committed
429 430 431 432
	bt.deletes[key] = struct{}{}
	return nil
}

Jeromy's avatar
Jeromy committed
433
func (bt *flatfsBatch) Commit() error {
Jeromy's avatar
Jeromy committed
434 435 436 437 438 439 440 441 442 443 444 445 446
	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
447 448 449
var _ datastore.ThreadSafeDatastore = (*Datastore)(nil)

func (*Datastore) IsThreadSafe() {}