sql.go 70.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * JuiceFS, Copyright (C) 2020 Juicedata, Inc.
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package meta

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
24
	"io"
25
	"runtime"
26
	"sort"
27 28
	"strings"
	"sync"
D
Davies Liu 已提交
29
	"sync/atomic"
30 31 32 33
	"syscall"
	"time"

	_ "github.com/go-sql-driver/mysql"
34
	"github.com/juicedata/juicefs/pkg/utils"
35
	_ "github.com/lib/pq"
36 37 38 39 40 41 42 43 44 45 46 47 48
	"github.com/mattn/go-sqlite3"
	_ "github.com/mattn/go-sqlite3"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

type setting struct {
	Name  string `xorm:"pk"`
	Value string `xorm:"varchar(4096) notnull"`
}

type counter struct {
	Name  string `xorm:"pk"`
D
Davies Liu 已提交
49
	Value int64  `xorm:"notnull"`
50 51 52 53 54 55 56 57 58 59
}

type edge struct {
	Parent Ino    `xorm:"unique(edge) notnull"`
	Name   string `xorm:"unique(edge) notnull"`
	Inode  Ino    `xorm:"notnull"`
	Type   uint8  `xorm:"notnull"`
}

type node struct {
60 61 62 63 64 65 66 67 68 69 70
	Inode  Ino    `xorm:"pk"`
	Type   uint8  `xorm:"notnull"`
	Flags  uint8  `xorm:"notnull"`
	Mode   uint16 `xorm:"notnull"`
	Uid    uint32 `xorm:"notnull"`
	Gid    uint32 `xorm:"notnull"`
	Atime  int64  `xorm:"notnull"`
	Mtime  int64  `xorm:"notnull"`
	Ctime  int64  `xorm:"notnull"`
	Nlink  uint32 `xorm:"notnull"`
	Length uint64 `xorm:"notnull"`
71 72 73 74
	Rdev   uint32
	Parent Ino
}

75 76 77 78 79
type namedNode struct {
	node `xorm:"extends"`
	Name string
}

80 81 82 83 84
type chunk struct {
	Inode  Ino    `xorm:"unique(chunk) notnull"`
	Indx   uint32 `xorm:"unique(chunk) notnull"`
	Slices []byte `xorm:"blob notnull"`
}
D
Davies Liu 已提交
85
type chunkRef struct {
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	Chunkid uint64 `xorm:"pk"`
	Size    uint32 `xorm:"notnull"`
	Refs    int    `xorm:"notnull"`
}
type symlink struct {
	Inode  Ino    `xorm:"pk"`
	Target string `xorm:"varchar(4096) notnull"`
}

type xattr struct {
	Inode Ino    `xorm:"unique(name) notnull"`
	Name  string `xorm:"unique(name) notnull"`
	Value []byte `xorm:"blob notnull"`
}

D
Davies Liu 已提交
101 102 103
type flock struct {
	Inode Ino    `xorm:"notnull unique(flock)"`
	Sid   uint64 `xorm:"notnull unique(flock)"`
D
Davies Liu 已提交
104
	Owner int64  `xorm:"notnull unique(flock)"`
D
Davies Liu 已提交
105 106 107
	Ltype byte   `xorm:"notnull"`
}

108 109 110
type plock struct {
	Inode   Ino    `xorm:"notnull unique(plock)"`
	Sid     uint64 `xorm:"notnull unique(plock)"`
D
Davies Liu 已提交
111
	Owner   int64  `xorm:"notnull unique(plock)"`
112 113 114
	Records []byte `xorm:"blob notnull"`
}

115
type session struct {
116 117
	Sid       uint64 `xorm:"pk"`
	Heartbeat int64  `xorm:"notnull"`
118
	Info      []byte `xorm:"blob"`
119 120 121 122 123 124 125 126
}

type sustained struct {
	Sid   uint64 `xorm:"unique(sustained) notnull"`
	Inode Ino    `xorm:"unique(sustained) notnull"`
}

type delfile struct {
127 128 129
	Inode  Ino    `xorm:"pk notnull"`
	Length uint64 `xorm:"notnull"`
	Expire int64  `xorm:"notnull"`
130 131 132 133 134 135 136 137 138
}

type freeID struct {
	next  uint64
	maxid uint64
}
type dbMeta struct {
	sync.Mutex
	conf   *Config
D
Davies Liu 已提交
139
	fmt    Format
140 141 142
	engine *xorm.Engine

	sid          uint64
143
	of           *openfiles
144
	root         Ino
145 146 147 148 149
	removedFiles map[Ino]bool
	compacting   map[uint64]bool
	deleting     chan int
	symlinks     *sync.Map
	msgCallbacks *msgCallbacks
D
Davies Liu 已提交
150 151
	newSpace     int64
	newInodes    int64
D
Davies Liu 已提交
152 153
	usedSpace    int64
	usedInodes   int64
154
	umounting    bool
155 156 157 158 159 160

	freeMu     sync.Mutex
	freeInodes freeID
	freeChunks freeID
}

161 162 163 164 165 166 167 168 169 170 171
func init() {
	Register("mysql", newSQLMeta)
	Register("sqlite3", newSQLMeta)
	Register("postgres", newSQLMeta)
}

func newSQLMeta(driver, addr string, conf *Config) (Meta, error) {
	if driver == "postgres" {
		addr = driver + "://" + addr
	}
	engine, err := xorm.NewEngine(driver, addr)
172 173 174
	if err != nil {
		return nil, fmt.Errorf("unable to use data source %s: %s", driver, err)
	}
175
	start := time.Now()
176 177 178
	if err = engine.Ping(); err != nil {
		return nil, fmt.Errorf("ping database: %s", err)
	}
179 180 181
	if time.Since(start) > time.Millisecond {
		logger.Warnf("The latency to database is too high: %s", time.Since(start))
	}
182

183
	engine.SetTableMapper(names.NewPrefixMapper(engine.GetTableMapper(), "jfs_"))
184 185 186 187 188 189
	if conf.Retries == 0 {
		conf.Retries = 30
	}
	m := &dbMeta{
		conf:         conf,
		engine:       engine,
190
		of:           newOpenFiles(conf.OpenCache),
191 192
		removedFiles: make(map[Ino]bool),
		compacting:   make(map[uint64]bool),
193
		deleting:     make(chan int, conf.MaxDeletes),
194 195 196 197 198
		symlinks:     &sync.Map{},
		msgCallbacks: &msgCallbacks{
			callbacks: make(map[uint32]MsgCallback),
		},
	}
199 200 201 202 203 204 205 206 207 208
	m.root = 1
	m.root, err = lookupSubdir(m, conf.Subdir)
	return m, err
}

func (m *dbMeta) checkRoot(inode Ino) Ino {
	if inode == 1 {
		return m.root
	}
	return inode
209 210
}

211 212 213 214
func (m *dbMeta) Name() string {
	return m.engine.DriverName()
}

D
Davies Liu 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
func (m *dbMeta) updateCollate() {
	if r, err := m.engine.Query("show create table jfs_edge"); err != nil {
		logger.Fatalf("show table jfs_edge: %s", err.Error())
	} else {
		createTable := string(r[0]["Create Table"])
		// the default collate is case-insensitive
		if !strings.Contains(createTable, "SET utf8mb4 COLLATE utf8mb4_bin") {
			_, err := m.engine.Exec("alter table jfs_edge modify name varchar (255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL")
			if err != nil && strings.Contains(err.Error(), "Error 1071: Specified key was too long; max key length is 767 bytes") {
				// MySQL 5.6 supports key length up to 767 bytes, so reduce the length of name to 190 chars
				_, err = m.engine.Exec("alter table jfs_edge modify name varchar (190) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL")
			}
			if err != nil {
				logger.Fatalf("update collate: %s", err)
			}
		}
	}
}

234
func (m *dbMeta) Init(format Format, force bool) error {
235 236
	if err := m.engine.Sync2(new(setting), new(counter)); err != nil {
		logger.Fatalf("create table setting, counter: %s", err)
237
	}
238 239
	if err := m.engine.Sync2(new(node), new(edge), new(symlink), new(xattr)); err != nil {
		logger.Fatalf("create table node, edge, symlink, xattr: %s", err)
240
	}
D
Davies Liu 已提交
241
	if err := m.engine.Sync2(new(chunk), new(chunkRef)); err != nil {
242
		logger.Fatalf("create table chunk, chunk_ref: %s", err)
243
	}
244 245
	if err := m.engine.Sync2(new(session), new(sustained), new(delfile)); err != nil {
		logger.Fatalf("create table session, sustaind, delfile: %s", err)
246
	}
247 248
	if err := m.engine.Sync2(new(flock), new(plock)); err != nil {
		logger.Fatalf("create table flock, plock: %s", err)
D
Davies Liu 已提交
249
	}
S
Sandy Xu 已提交
250
	if m.engine.DriverName() == "mysql" {
D
Davies Liu 已提交
251
		m.updateCollate()
S
Sandy Xu 已提交
252
	}
253

254 255
	var s = setting{Name: "format"}
	ok, err := m.engine.Get(&s)
256 257 258
	if err != nil {
		return err
	}
259 260 261 262 263 264 265

	if ok {
		var old Format
		err = json.Unmarshal([]byte(s.Value), &old)
		if err != nil {
			return fmt.Errorf("json: %s", err)
		}
266 267 268 269 270
		if force {
			old.SecretKey = "removed"
			logger.Warnf("Existing volume will be overwrited: %+v", old)
		} else {
			format.UUID = old.UUID
D
Davies Liu 已提交
271
			// these can be safely updated.
272 273
			old.AccessKey = format.AccessKey
			old.SecretKey = format.SecretKey
D
Davies Liu 已提交
274 275
			old.Capacity = format.Capacity
			old.Inodes = format.Inodes
276
			if format != old {
277 278 279 280 281 282 283 284 285
				old.SecretKey = ""
				format.SecretKey = ""
				return fmt.Errorf("cannot update format from %+v to %+v", old, format)
			}
		}
	}

	data, err := json.MarshalIndent(format, "", "")
	if err != nil {
286
		return fmt.Errorf("json: %s", err)
287 288
	}

D
Davies Liu 已提交
289
	m.fmt = format
290
	return m.txn(func(s *xorm.Session) error {
291 292 293 294 295
		if ok {
			_, err = s.Update(&setting{"format", string(data)}, &setting{Name: "format"})
			return err
		}

D
Davies Liu 已提交
296
		var set = &setting{"format", string(data)}
297
		now := time.Now()
D
Davies Liu 已提交
298
		var root = &node{
299 300 301
			Inode:  1,
			Type:   TypeDirectory,
			Mode:   0777,
302 303 304
			Atime:  now.UnixNano() / 1000,
			Mtime:  now.UnixNano() / 1000,
			Ctime:  now.UnixNano() / 1000,
305 306 307 308
			Nlink:  2,
			Length: 4 << 10,
			Parent: 1,
		}
D
Davies Liu 已提交
309 310 311 312 313 314 315 316 317
		var cs = []counter{
			{"nextInode", 2}, // 1 is root
			{"nextChunk", 1},
			{"nextSession", 1},
			{"usedSpace", 0},
			{"totalInodes", 0},
			{"nextCleanupSlices", 0},
		}
		return mustInsert(s, set, root, &cs)
318 319 320 321
	})
}

func (m *dbMeta) Load() (*Format, error) {
322 323
	var s = setting{Name: "format"}
	ok, err := m.engine.Get(&s)
324 325 326 327
	if err == nil && !ok {
		err = fmt.Errorf("database is not formatted")
	}
	if err != nil {
328 329 330
		return nil, err
	}

D
Davies Liu 已提交
331
	err = json.Unmarshal([]byte(s.Value), &m.fmt)
332 333 334
	if err != nil {
		return nil, fmt.Errorf("json: %s", err)
	}
D
Davies Liu 已提交
335
	return &m.fmt, nil
336 337 338
}

func (m *dbMeta) NewSession() error {
339 340 341 342
	go m.refreshUsage()
	if m.conf.ReadOnly {
		return nil
	}
343 344 345
	if err := m.engine.Sync2(new(session)); err != nil { // old client has no info field
		return err
	}
S
Sandy Xu 已提交
346
	if m.engine.DriverName() == "mysql" {
D
Davies Liu 已提交
347
		m.updateCollate()
S
Sandy Xu 已提交
348
	}
D
Davies Liu 已提交
349 350 351 352
	// update the owner from uint64 to int64
	if err := m.engine.Sync2(new(flock), new(plock)); err != nil {
		logger.Fatalf("update table flock, plock: %s", err)
	}
353

354
	info := newSessionInfo()
355 356 357 358 359
	info.MountPoint = m.conf.MountPoint
	data, err := json.Marshal(info)
	if err != nil {
		return fmt.Errorf("json: %s", err)
	}
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	var v uint64
	for {
		v, err = m.incrCounter("nextSession", 1)
		if err != nil {
			return fmt.Errorf("create session: %s", err)
		}
		err = m.txn(func(s *xorm.Session) error {
			return mustInsert(s, &session{v, time.Now().Unix(), data})
		})
		if err == nil {
			break
		}
		if strings.Contains(err.Error(), "UNIQUE constraint failed") {
			logger.Warnf("session id %d is already used", v)
			continue
		}
		if err != nil {
			return fmt.Errorf("insert new session: %s", err)
		}
379 380 381 382 383 384 385
	}
	m.sid = v
	logger.Debugf("session is %d", m.sid)

	go m.refreshSession()
	go m.cleanupDeletedFiles()
	go m.cleanupSlices()
D
Davies Liu 已提交
386
	go m.flushStats()
387 388 389
	return nil
}

390
func (m *dbMeta) CloseSession() error {
391 392 393
	if m.conf.ReadOnly {
		return nil
	}
394 395 396 397 398 399 400
	m.Lock()
	m.umounting = true
	m.Unlock()
	m.cleanStaleSession(m.sid, true)
	return nil
}

D
Davies Liu 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
func (m *dbMeta) refreshUsage() {
	for {
		var c = counter{Name: "usedSpace"}
		_, err := m.engine.Get(&c)
		if err == nil {
			atomic.StoreInt64(&m.usedSpace, c.Value)
		}
		c = counter{Name: "totalInodes"}
		_, err = m.engine.Get(&c)
		if err == nil {
			atomic.StoreInt64(&m.usedInodes, c.Value)
		}
		time.Sleep(time.Second * 10)
	}
}

func (r *dbMeta) checkQuota(size, inodes int64) bool {
	if size > 0 && r.fmt.Capacity > 0 && atomic.LoadInt64(&r.usedSpace)+atomic.LoadInt64(&r.newSpace)+size > int64(r.fmt.Capacity) {
		return true
	}
	return inodes > 0 && r.fmt.Inodes > 0 && atomic.LoadInt64(&r.usedInodes)+atomic.LoadInt64(&r.newInodes)+inodes > int64(r.fmt.Inodes)
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
func (m *dbMeta) getSession(row *session, detail bool) (*Session, error) {
	var s Session
	if row.Info == nil { // legacy client has no info
		row.Info = []byte("{}")
	}
	if err := json.Unmarshal(row.Info, &s); err != nil {
		return nil, fmt.Errorf("corrupted session info; json error: %s", err)
	}
	s.Sid = row.Sid
	s.Heartbeat = time.Unix(row.Heartbeat, 0)
	if detail {
		var (
			srows []sustained
			frows []flock
			prows []plock
		)
		if err := m.engine.Find(&srows, &sustained{Sid: s.Sid}); err != nil {
			return nil, fmt.Errorf("find sustained %d: %s", s.Sid, err)
		}
		s.Sustained = make([]Ino, 0, len(srows))
		for _, srow := range srows {
			s.Sustained = append(s.Sustained, srow.Inode)
		}

		if err := m.engine.Find(&frows, &flock{Sid: s.Sid}); err != nil {
			return nil, fmt.Errorf("find flock %d: %s", s.Sid, err)
		}
		s.Flocks = make([]Flock, 0, len(frows))
		for _, frow := range frows {
D
Davies Liu 已提交
453
			s.Flocks = append(s.Flocks, Flock{frow.Inode, uint64(frow.Owner), string(frow.Ltype)})
454 455 456 457 458 459 460
		}

		if err := m.engine.Find(&prows, &plock{Sid: s.Sid}); err != nil {
			return nil, fmt.Errorf("find plock %d: %s", s.Sid, err)
		}
		s.Plocks = make([]Plock, 0, len(prows))
		for _, prow := range prows {
D
Davies Liu 已提交
461
			s.Plocks = append(s.Plocks, Plock{prow.Inode, uint64(prow.Owner), prow.Records})
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
		}
	}
	return &s, nil
}

func (m *dbMeta) GetSession(sid uint64) (*Session, error) {
	row := session{Sid: sid}
	ok, err := m.engine.Get(&row)
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, fmt.Errorf("session not found: %d", sid)
	}
	return m.getSession(&row, true)
}

func (m *dbMeta) ListSessions() ([]*Session, error) {
	var rows []session
	err := m.engine.Find(&rows)
	if err != nil {
		return nil, err
	}
	sessions := make([]*Session, 0, len(rows))
	for _, row := range rows {
		s, err := m.getSession(&row, false)
		if err != nil {
			logger.Errorf("get session: %s", err)
			continue
		}
		sessions = append(sessions, s)
	}
	return sessions, nil
}

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
func (m *dbMeta) OnMsg(mtype uint32, cb MsgCallback) {
	m.msgCallbacks.Lock()
	defer m.msgCallbacks.Unlock()
	m.msgCallbacks.callbacks[mtype] = cb
}

func (m *dbMeta) newMsg(mid uint32, args ...interface{}) error {
	m.msgCallbacks.Lock()
	cb, ok := m.msgCallbacks.callbacks[mid]
	m.msgCallbacks.Unlock()
	if ok {
		return cb(args...)
	}
	return fmt.Errorf("message %d is not supported", mid)
}

D
Davies Liu 已提交
513 514
func (m *dbMeta) incrCounter(name string, batch int64) (uint64, error) {
	var v int64
515
	err := m.txn(func(s *xorm.Session) error {
516 517
		var c = counter{Name: name}
		_, err := s.Get(&c)
518 519 520
		if err != nil {
			return err
		}
521 522
		v = c.Value + batch
		_, err = s.Cols("value").Update(&counter{Value: v}, &counter{Name: name})
523 524
		return err
	})
D
Davies Liu 已提交
525
	return uint64(v), err
526 527 528 529 530
}

func (m *dbMeta) nextInode() (Ino, error) {
	m.freeMu.Lock()
	defer m.freeMu.Unlock()
531 532 533 534 535 536 537
	if m.freeInodes.next >= m.freeInodes.maxid {
		v, err := m.incrCounter("nextInode", 100)
		if err != nil {
			return 0, err
		}
		m.freeInodes.next = v - 100
		m.freeInodes.maxid = v
538
	}
539 540 541
	n := m.freeInodes.next
	m.freeInodes.next++
	return Ino(n), nil
542 543
}

D
Davies Liu 已提交
544 545 546 547 548 549 550 551
func mustInsert(s *xorm.Session, beans ...interface{}) error {
	inserted, err := s.Insert(beans...)
	if err == nil && int(inserted) < len(beans) {
		err = fmt.Errorf("%d records not inserted: %+v", len(beans)-int(inserted), beans)
	}
	return err
}

D
Davies Liu 已提交
552 553 554 555
func (m *dbMeta) shouldRetry(err error) bool {
	if err == nil {
		return false
	}
556 557 558
	if _, ok := err.(syscall.Errno); ok {
		return false
	}
D
Davies Liu 已提交
559 560 561 562 563 564 565 566
	// TODO: add other retryable errors here
	msg := err.Error()
	switch m.engine.DriverName() {
	case "sqlite3":
		return errors.Is(err, sqlite3.ErrBusy) || strings.Contains(msg, "database is locked")
	case "mysql":
		// MySQL, MariaDB or TiDB
		return strings.Contains(msg, "try restarting transaction") || strings.Contains(msg, "try again later")
567 568
	case "postgres":
		return strings.Contains(msg, "current transaction is aborted") || strings.Contains(msg, "deadlock detected")
D
Davies Liu 已提交
569 570 571 572 573
	default:
		return false
	}
}

574
func (m *dbMeta) txn(f func(s *xorm.Session) error) error {
D
Davies Liu 已提交
575 576 577
	if m.conf.ReadOnly {
		return syscall.EROFS
	}
578 579 580 581 582
	start := time.Now()
	defer func() { txDist.Observe(time.Since(start).Seconds()) }()
	var err error
	for i := 0; i < 50; i++ {
		_, err = m.engine.Transaction(func(s *xorm.Session) (interface{}, error) {
583
			s.ForUpdate()
584 585
			return nil, f(s)
		})
D
Davies Liu 已提交
586
		if m.shouldRetry(err) {
587
			txRestart.Add(1)
D
Davies Liu 已提交
588
			logger.Debugf("conflicted transaction, restart it (tried %d): %s", i+1, err)
S
satoru 已提交
589
			time.Sleep(time.Millisecond * time.Duration(i*i))
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
			continue
		}
		break
	}
	return err
}

func (m *dbMeta) parseAttr(n *node, attr *Attr) {
	if attr == nil {
		return
	}
	attr.Typ = n.Type
	attr.Mode = n.Mode
	attr.Flags = n.Flags
	attr.Uid = n.Uid
	attr.Gid = n.Gid
606 607 608 609 610 611
	attr.Atime = n.Atime / 1e6
	attr.Atimensec = uint32(n.Atime % 1e6 * 1000)
	attr.Mtime = n.Mtime / 1e6
	attr.Mtimensec = uint32(n.Mtime % 1e6 * 1000)
	attr.Ctime = n.Ctime / 1e6
	attr.Ctimensec = uint32(n.Ctime % 1e6 * 1000)
612 613
	attr.Nlink = n.Nlink
	attr.Length = n.Length
S
satoru 已提交
614 615
	attr.Rdev = n.Rdev
	attr.Parent = n.Parent
616 617 618
	attr.Full = true
}

D
Davies Liu 已提交
619
func (m *dbMeta) updateStats(space int64, inodes int64) {
D
Davies Liu 已提交
620 621
	atomic.AddInt64(&m.newSpace, space)
	atomic.AddInt64(&m.newInodes, inodes)
D
Davies Liu 已提交
622 623 624
}

func (m *dbMeta) flushStats() {
D
Davies Liu 已提交
625 626 627 628
	var inttype = "BIGINT"
	if m.engine.DriverName() == "mysql" {
		inttype = "SIGNED"
	}
D
Davies Liu 已提交
629
	for {
D
Davies Liu 已提交
630 631
		newSpace := atomic.SwapInt64(&m.newSpace, 0)
		newInodes := atomic.SwapInt64(&m.newInodes, 0)
D
Davies Liu 已提交
632 633
		if newSpace != 0 || newInodes != 0 {
			err := m.txn(func(s *xorm.Session) error {
D
Davies Liu 已提交
634
				_, err := s.Exec("UPDATE jfs_counter SET value=value+ CAST((CASE name WHEN 'usedSpace' THEN ? ELSE ? END) AS "+inttype+") WHERE name='usedSpace' OR name='totalInodes' ", newSpace, newInodes)
D
Davies Liu 已提交
635 636
				return err
			})
D
Davies Liu 已提交
637
			if err != nil && !strings.Contains(err.Error(), "attempt to write a readonly database") {
D
Davies Liu 已提交
638 639 640 641 642 643 644 645
				logger.Warnf("update stats: %s", err)
				m.updateStats(newSpace, newInodes)
			}
		}
		time.Sleep(time.Second)
	}
}

646
func (m *dbMeta) StatFS(ctx Context, totalspace, availspace, iused, iavail *uint64) syscall.Errno {
647
	defer timeit(time.Now())
D
Davies Liu 已提交
648 649
	usedSpace := atomic.LoadInt64(&m.newSpace)
	inodes := atomic.LoadInt64(&m.newInodes)
650 651
	var c = counter{Name: "usedSpace"}
	_, err := m.engine.Get(&c)
652 653
	if err != nil {
		logger.Warnf("get used space: %s", err)
D
Davies Liu 已提交
654 655 656 657 658
	} else {
		usedSpace += c.Value
	}
	if usedSpace < 0 {
		usedSpace = 0
659
	}
D
Davies Liu 已提交
660
	usedSpace = ((usedSpace >> 16) + 1) << 16 // aligned to 64K
D
Davies Liu 已提交
661 662 663 664 665 666 667 668 669 670
	if m.fmt.Capacity > 0 {
		*totalspace = m.fmt.Capacity
		if *totalspace < uint64(usedSpace) {
			*totalspace = uint64(usedSpace)
		}
	} else {
		*totalspace = 1 << 50
		for *totalspace*8 < uint64(usedSpace)*10 {
			*totalspace *= 2
		}
671
	}
D
Davies Liu 已提交
672

D
Davies Liu 已提交
673
	*availspace = *totalspace - uint64(usedSpace)
674 675
	c = counter{Name: "totalInodes"}
	_, err = m.engine.Get(&c)
676 677
	if err != nil {
		logger.Warnf("get total inodes: %s", err)
D
Davies Liu 已提交
678 679 680 681 682
	} else {
		inodes += c.Value
	}
	if inodes < 0 {
		inodes = 0
683
	}
D
Davies Liu 已提交
684
	*iused = uint64(inodes)
D
Davies Liu 已提交
685 686 687 688 689 690 691 692
	if m.fmt.Inodes > 0 {
		if *iused > m.fmt.Inodes {
			*iavail = 0
		} else {
			*iavail = m.fmt.Inodes - *iused
		}
	} else {
		*iavail = 10 << 20
693 694 695
		for *iused*10 > (*iused+*iavail)*8 {
			*iavail *= 2
		}
D
Davies Liu 已提交
696
	}
697 698 699 700
	return 0
}

func (m *dbMeta) Lookup(ctx Context, parent Ino, name string, inode *Ino, attr *Attr) syscall.Errno {
701 702 703
	if inode == nil || attr == nil {
		return syscall.EINVAL
	}
704
	defer timeit(time.Now())
705
	parent = m.checkRoot(parent)
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
	if name == ".." {
		if parent == m.root {
			name = "."
		} else {
			if st := m.GetAttr(ctx, parent, attr); st != 0 {
				return st
			}
			if attr.Typ != TypeDirectory {
				return syscall.ENOTDIR
			}
			*inode = attr.Parent
			return m.GetAttr(ctx, *inode, attr)
		}
	}
	if name == "." {
		st := m.GetAttr(ctx, parent, attr)
		if st != 0 {
			return st
		}
		if attr.Typ != TypeDirectory {
			return syscall.ENOTDIR
		}
		*inode = parent
		return 0
	}
731 732 733 734 735 736
	dbSession := m.engine.Table(&edge{})
	if attr != nil {
		dbSession = dbSession.Join("INNER", &node{}, "jfs_edge.inode=jfs_node.inode")
	}
	nn := namedNode{node: node{Parent: parent}, Name: name}
	exist, err := dbSession.Select("*").Get(&nn)
737 738 739
	if err != nil {
		return errno(err)
	}
740
	if !exist {
741 742 743
		if m.conf.CaseInsensi {
			// TODO: in SQL
			if e := m.resolveCase(ctx, parent, name); e != nil {
744 745
				*inode = e.Inode
				return m.GetAttr(ctx, *inode, attr)
746 747 748 749
			}
		}
		return syscall.ENOENT
	}
750 751
	*inode = nn.Inode
	m.parseAttr(&nn.node, attr)
752 753 754
	return 0
}

755 756 757 758
func (r *dbMeta) Resolve(ctx Context, parent Ino, path string, inode *Ino, attr *Attr) syscall.Errno {
	return syscall.ENOTSUP
}

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
func (m *dbMeta) Access(ctx Context, inode Ino, mmask uint8, attr *Attr) syscall.Errno {
	if ctx.Uid() == 0 {
		return 0
	}

	if attr == nil || !attr.Full {
		if attr == nil {
			attr = &Attr{}
		}
		err := m.GetAttr(ctx, inode, attr)
		if err != 0 {
			return err
		}
	}

	mode := accessMode(attr, ctx.Uid(), ctx.Gid())
	if mode&mmask != mmask {
		logger.Debugf("Access inode %d %o, mode %o, request mode %o", inode, attr.Mode, mode, mmask)
		return syscall.EACCES
	}
	return 0
}

func (m *dbMeta) GetAttr(ctx Context, inode Ino, attr *Attr) syscall.Errno {
783
	inode = m.checkRoot(inode)
784 785 786
	if m.conf.OpenCache > 0 && m.of.Check(inode, attr) {
		return 0
	}
787
	defer timeit(time.Now())
788 789
	var n = node{Inode: inode}
	ok, err := m.engine.Get(&n)
790 791 792 793 794 795 796 797 798 799 800 801 802 803
	if err != nil && inode == 1 {
		err = nil
		n.Type = TypeDirectory
		n.Mode = 0777
		n.Nlink = 2
		n.Length = 4 << 10
	}
	if err != nil {
		return errno(err)
	}
	if !ok {
		return syscall.ENOENT
	}
	m.parseAttr(&n, attr)
804
	m.of.Update(inode, attr)
805 806 807 808
	return 0
}

func (m *dbMeta) SetAttr(ctx Context, inode Ino, set uint16, sugidclearmode uint8, attr *Attr) syscall.Errno {
809
	defer timeit(time.Now())
810
	inode = m.checkRoot(inode)
811
	defer func() { m.of.InvalidateChunk(inode, 0xFFFFFFFE) }()
812
	return errno(m.txn(func(s *xorm.Session) error {
813 814
		var cur = node{Inode: inode}
		ok, err := s.Get(&cur)
815 816 817 818 819 820 821 822 823 824 825
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if (set&(SetAttrUID|SetAttrGID)) != 0 && (set&SetAttrMode) != 0 {
			attr.Mode |= (cur.Mode & 06000)
		}
		var changed bool
		if (cur.Mode&06000) != 0 && (set&(SetAttrUID|SetAttrGID)) != 0 {
826 827
			if ctx.Uid() != 0 || (cur.Mode>>3)&1 != 0 {
				// clear SUID and SGID
828
				cur.Mode &= 01777
829 830 831 832 833
				attr.Mode &= 01777
			} else {
				// keep SGID if the file is non-group-executable
				cur.Mode &= 03777
				attr.Mode &= 03777
834
			}
835
			changed = true
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
		}
		if set&SetAttrUID != 0 && cur.Uid != attr.Uid {
			cur.Uid = attr.Uid
			changed = true
		}
		if set&SetAttrGID != 0 && cur.Gid != attr.Gid {
			cur.Gid = attr.Gid
			changed = true
		}
		if set&SetAttrMode != 0 {
			if ctx.Uid() != 0 && (attr.Mode&02000) != 0 {
				if ctx.Gid() != cur.Gid {
					attr.Mode &= 05777
				}
			}
			if attr.Mode != cur.Mode {
				cur.Mode = attr.Mode
				changed = true
			}
		}
856 857 858
		now := time.Now().UnixNano() / 1e3
		if set&SetAttrAtime != 0 {
			cur.Atime = attr.Atime*1e6 + int64(attr.Atimensec)/1e3
859 860 861 862 863 864
			changed = true
		}
		if set&SetAttrAtimeNow != 0 {
			cur.Atime = now
			changed = true
		}
865 866
		if set&SetAttrMtime != 0 {
			cur.Mtime = attr.Mtime*1e6 + int64(attr.Mtimensec)/1e3
867 868 869 870 871 872 873 874 875 876
			changed = true
		}
		if set&SetAttrMtimeNow != 0 {
			cur.Mtime = now
			changed = true
		}
		m.parseAttr(&cur, attr)
		if !changed {
			return nil
		}
877
		cur.Ctime = now
D
Davies Liu 已提交
878
		_, err = s.Cols("mode", "uid", "gid", "atime", "mtime", "ctime").Update(&cur, &node{Inode: inode})
879 880 881 882 883 884 885 886 887 888
		if err == nil {
			m.parseAttr(&cur, attr)
		}
		return err
	}))
}

func (m *dbMeta) appendSlice(s *xorm.Session, inode Ino, indx uint32, buf []byte) error {
	var r sql.Result
	var err error
889 890
	driver := m.engine.DriverName()
	if driver == "sqlite3" || driver == "postgres" {
891 892 893 894 895 896
		r, err = s.Exec("update jfs_chunk set slices=slices || ? where inode=? AND indx=?", buf, inode, indx)
	} else {
		r, err = s.Exec("update jfs_chunk set slices=concat(slices, ?) where inode=? AND indx=?", buf, inode, indx)
	}
	if err == nil {
		if n, _ := r.RowsAffected(); n == 0 {
D
Davies Liu 已提交
897
			err = mustInsert(s, &chunk{inode, indx, buf})
898 899 900 901 902 903
		}
	}
	return err
}

func (m *dbMeta) Truncate(ctx Context, inode Ino, flags uint8, length uint64, attr *Attr) syscall.Errno {
904
	defer timeit(time.Now())
D
Davies Liu 已提交
905 906 907 908 909
	f := m.of.find(inode)
	if f != nil {
		f.Lock()
		defer f.Unlock()
	}
910
	defer func() { m.of.InvalidateChunk(inode, 0xFFFFFFFF) }()
D
Davies Liu 已提交
911 912
	var newSpace int64
	err := m.txn(func(s *xorm.Session) error {
913 914
		var n = node{Inode: inode}
		ok, err := s.Get(&n)
915 916 917 918 919 920 921 922 923 924 925 926 927
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if n.Type != TypeFile {
			return syscall.EPERM
		}
		if length == n.Length {
			m.parseAttr(&n, attr)
			return nil
		}
928 929 930 931 932 933 934 935 936 937 938 939 940 941
		newSpace = align4K(length) - align4K(n.Length)
		if newSpace > 0 && m.checkQuota(newSpace, 0) {
			return syscall.ENOSPC
		}
		var c chunk
		var zeroChunks []uint32
		var left, right = n.Length, length
		if left > right {
			right, left = left, right
		}
		if right/ChunkSize-left/ChunkSize > 1 {
			rows, err := s.Where("inode = ? AND indx > ? AND indx < ?", inode, left/ChunkSize, right/ChunkSize).Cols("indx").Rows(&c)
			if err != nil {
				return err
942
			}
943 944 945
			for rows.Next() {
				if err = rows.Scan(&c); err != nil {
					rows.Close()
946 947
					return err
				}
948
				zeroChunks = append(zeroChunks, c.Indx)
949
			}
950 951
			rows.Close()
		}
952

953 954 955 956 957 958 959 960 961 962
		l := uint32(right - left)
		if right > (left/ChunkSize+1)*ChunkSize {
			l = ChunkSize - uint32(left%ChunkSize)
		}
		if err = m.appendSlice(s, inode, uint32(left/ChunkSize), marshalSlice(uint32(left%ChunkSize), 0, 0, 0, l)); err != nil {
			return err
		}
		buf := marshalSlice(0, 0, 0, 0, ChunkSize)
		for _, indx := range zeroChunks {
			if err = m.appendSlice(s, inode, indx, buf); err != nil {
963 964
				return err
			}
965 966 967 968
		}
		if right > (left/ChunkSize+1)*ChunkSize && right%ChunkSize > 0 {
			if err = m.appendSlice(s, inode, uint32(right/ChunkSize), marshalSlice(0, 0, 0, 0, uint32(right%ChunkSize))); err != nil {
				return err
969 970 971
			}
		}
		n.Length = length
972
		now := time.Now().UnixNano() / 1e3
D
Davies Liu 已提交
973 974
		n.Mtime = now
		n.Ctime = now
975
		if _, err = s.Cols("length", "mtime", "ctime").Update(&n, &node{Inode: n.Inode}); err != nil {
976 977
			return err
		}
D
Davies Liu 已提交
978
		m.parseAttr(&n, attr)
979
		return nil
D
Davies Liu 已提交
980 981 982 983 984
	})
	if err == nil {
		m.updateStats(newSpace, 0)
	}
	return errno(err)
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
}

func (m *dbMeta) Fallocate(ctx Context, inode Ino, mode uint8, off uint64, size uint64) syscall.Errno {
	if mode&fallocCollapesRange != 0 && mode != fallocCollapesRange {
		return syscall.EINVAL
	}
	if mode&fallocInsertRange != 0 && mode != fallocInsertRange {
		return syscall.EINVAL
	}
	if mode == fallocInsertRange || mode == fallocCollapesRange {
		return syscall.ENOTSUP
	}
	if mode&fallocPunchHole != 0 && mode&fallocKeepSize == 0 {
		return syscall.EINVAL
	}
	if size == 0 {
		return syscall.EINVAL
	}
1003
	defer timeit(time.Now())
D
Davies Liu 已提交
1004 1005 1006 1007 1008
	f := m.of.find(inode)
	if f != nil {
		f.Lock()
		defer f.Unlock()
	}
1009
	defer func() { m.of.InvalidateChunk(inode, 0xFFFFFFFF) }()
D
Davies Liu 已提交
1010 1011
	var newSpace int64
	err := m.txn(func(s *xorm.Session) error {
1012 1013
		var n = node{Inode: inode}
		ok, err := s.Get(&n)
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if n.Type == TypeFIFO {
			return syscall.EPIPE
		}
		if n.Type != TypeFile {
			return syscall.EPERM
		}
		length := n.Length
		if off+size > n.Length {
			if mode&fallocKeepSize == 0 {
				length = off + size
			}
		}

		old := n.Length
D
Davies Liu 已提交
1034
		newSpace = align4K(length) - align4K(n.Length)
D
Davies Liu 已提交
1035 1036 1037
		if m.checkQuota(newSpace, 0) {
			return syscall.ENOSPC
		}
D
Davies Liu 已提交
1038
		now := time.Now().UnixNano() / 1e3
1039
		n.Length = length
D
Davies Liu 已提交
1040 1041 1042
		n.Mtime = now
		n.Ctime = now
		if _, err := s.Cols("length", "mtime", "ctime").Update(&n, &node{Inode: inode}); err != nil {
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
			return err
		}
		if mode&(fallocZeroRange|fallocPunchHole) != 0 {
			if off+size > old {
				size = old - off
			}
			for size > 0 {
				indx := uint32(off / ChunkSize)
				coff := off % ChunkSize
				l := size
				if coff+size > ChunkSize {
					l = ChunkSize - coff
				}
				err = m.appendSlice(s, inode, indx, marshalSlice(uint32(coff), 0, 0, 0, uint32(l)))
				if err != nil {
					return err
				}
				off += l
				size -= l
			}
		}
D
Davies Liu 已提交
1064 1065 1066 1067 1068 1069
		return nil
	})
	if err == nil {
		m.updateStats(newSpace, 0)
	}
	return errno(err)
1070 1071 1072 1073 1074 1075 1076
}

func (m *dbMeta) ReadLink(ctx Context, inode Ino, path *[]byte) syscall.Errno {
	if target, ok := m.symlinks.Load(inode); ok {
		*path = target.([]byte)
		return 0
	}
1077
	defer timeit(time.Now())
1078 1079
	var l = symlink{Inode: inode}
	ok, err := m.engine.Get(&l)
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	if err != nil {
		return errno(err)
	}
	if !ok {
		return syscall.ENOENT
	}
	*path = []byte(l.Target)
	m.symlinks.Store(inode, []byte(l.Target))
	return 0
}

func (m *dbMeta) Symlink(ctx Context, parent Ino, name string, path string, inode *Ino, attr *Attr) syscall.Errno {
1092
	defer timeit(time.Now())
1093 1094 1095 1096
	return m.mknod(ctx, parent, name, TypeSymlink, 0644, 022, 0, path, inode, attr)
}

func (m *dbMeta) Mknod(ctx Context, parent Ino, name string, _type uint8, mode, cumask uint16, rdev uint32, inode *Ino, attr *Attr) syscall.Errno {
1097
	defer timeit(time.Now())
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
	return m.mknod(ctx, parent, name, _type, mode, cumask, rdev, "", inode, attr)
}

func (m *dbMeta) resolveCase(ctx Context, parent Ino, name string) *Entry {
	// TODO in SQL
	var entries []*Entry
	_ = m.Readdir(ctx, parent, 0, &entries)
	for _, e := range entries {
		n := string(e.Name)
		if strings.EqualFold(name, n) {
			return e
		}
	}
	return nil
}

func (m *dbMeta) mknod(ctx Context, parent Ino, name string, _type uint8, mode, cumask uint16, rdev uint32, path string, inode *Ino, attr *Attr) syscall.Errno {
D
Davies Liu 已提交
1115 1116 1117
	if m.checkQuota(4<<10, 1) {
		return syscall.ENOSPC
	}
1118
	parent = m.checkRoot(parent)
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
	ino, err := m.nextInode()
	if err != nil {
		return errno(err)
	}
	var n node
	n.Inode = ino
	n.Type = _type
	n.Mode = mode & ^cumask
	n.Uid = ctx.Uid()
	n.Gid = ctx.Gid()
	if _type == TypeDirectory {
		n.Nlink = 2
		n.Length = 4 << 10
	} else {
		n.Nlink = 1
		if _type == TypeSymlink {
			n.Length = uint64(len(path))
		} else {
			n.Length = 0
			n.Rdev = rdev
		}
	}
	n.Parent = parent
	if inode != nil {
		*inode = ino
	}

D
Davies Liu 已提交
1146
	err = m.txn(func(s *xorm.Session) error {
1147 1148
		var pn = node{Inode: parent}
		ok, err := s.Get(&pn)
1149 1150 1151 1152 1153 1154 1155 1156 1157
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if pn.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
1158 1159
		var e = edge{Parent: parent, Name: name}
		ok, err = s.Get(&e)
1160 1161 1162
		if err != nil {
			return err
		}
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
		var foundIno Ino
		var foundType uint8
		if ok {
			foundType, foundIno = e.Type, e.Inode
		} else if m.conf.CaseInsensi {
			if entry := m.resolveCase(ctx, parent, name); entry != nil {
				foundType, foundIno = entry.Attr.Typ, entry.Inode
			}
		}
		if foundIno != 0 {
			if _type == TypeFile && attr != nil {
				foundNode := node{Inode: foundIno}
				ok, err = s.Get(&foundNode)
				if err != nil {
					return err
				} else if ok {
					m.parseAttr(&foundNode, attr)
				} else {
					*attr = Attr{Typ: foundType, Parent: parent} // corrupt entry
				}
				if inode != nil {
					*inode = foundIno
				}
			}
1187 1188 1189
			return syscall.EEXIST
		}

1190
		now := time.Now().UnixNano() / 1e3
1191 1192 1193 1194
		if _type == TypeDirectory {
			pn.Nlink++
		}
		pn.Mtime = now
1195
		pn.Ctime = now
1196 1197
		n.Atime = now
		n.Mtime = now
1198
		n.Ctime = now
1199
		if pn.Mode&02000 != 0 || ctx.Value(CtxKey("behavior")) == "Hadoop" || runtime.GOOS == "darwin" {
1200
			n.Gid = pn.Gid
1201 1202 1203
			if _type == TypeDirectory && runtime.GOOS == "linux" {
				n.Mode |= pn.Mode & 02000
			}
1204 1205
		}

D
Davies Liu 已提交
1206
		if err = mustInsert(s, &edge{parent, name, ino, _type}, &n); err != nil {
1207 1208
			return err
		}
D
Davies Liu 已提交
1209
		if _, err := s.Cols("nlink", "mtime", "ctime").Update(&pn, &node{Inode: pn.Inode}); err != nil {
1210 1211 1212
			return err
		}
		if _type == TypeSymlink {
D
Davies Liu 已提交
1213
			if err = mustInsert(s, &symlink{Inode: ino, Target: path}); err != nil {
1214 1215 1216
				return err
			}
		}
D
Davies Liu 已提交
1217
		m.parseAttr(&n, attr)
D
Davies Liu 已提交
1218
		return nil
D
Davies Liu 已提交
1219 1220 1221 1222 1223
	})
	if err == nil {
		m.updateStats(align4K(0), 1)
	}
	return errno(err)
1224 1225 1226
}

func (m *dbMeta) Mkdir(ctx Context, parent Ino, name string, mode uint16, cumask uint16, copysgid uint8, inode *Ino, attr *Attr) syscall.Errno {
1227 1228
	defer timeit(time.Now())
	return m.mknod(ctx, parent, name, TypeDirectory, mode, cumask, 0, "", inode, attr)
1229 1230
}

1231
func (m *dbMeta) Create(ctx Context, parent Ino, name string, mode uint16, cumask uint16, flags uint32, inode *Ino, attr *Attr) syscall.Errno {
1232
	defer timeit(time.Now())
1233 1234 1235
	if attr == nil {
		attr = &Attr{}
	}
1236
	err := m.mknod(ctx, parent, name, TypeFile, mode, cumask, 0, "", inode, attr)
1237 1238 1239
	if err == syscall.EEXIST && (flags&syscall.O_EXCL) == 0 && attr.Typ == TypeFile {
		err = 0
	}
1240
	if err == 0 && inode != nil {
1241
		m.of.Open(*inode, attr)
1242 1243 1244 1245 1246
	}
	return err
}

func (m *dbMeta) Unlink(ctx Context, parent Ino, name string) syscall.Errno {
1247
	defer timeit(time.Now())
1248
	parent = m.checkRoot(parent)
D
Davies Liu 已提交
1249
	var newSpace, newInode int64
1250 1251
	var n node
	var opened bool
D
Davies Liu 已提交
1252
	err := m.txn(func(s *xorm.Session) error {
1253 1254
		var pn = node{Inode: parent}
		ok, err := s.Get(&pn)
1255 1256 1257 1258 1259 1260 1261 1262 1263
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if pn.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
1264 1265
		var e = edge{Parent: parent, Name: name}
		ok, err = s.Get(&e)
1266 1267 1268 1269 1270 1271
		if err != nil {
			return err
		}
		if !ok && m.conf.CaseInsensi {
			if ee := m.resolveCase(ctx, parent, name); ee != nil {
				ok = true
S
Sandy Xu 已提交
1272
				e.Name = string(ee.Name)
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
				e.Inode = ee.Inode
				e.Type = ee.Attr.Typ
			}
		}
		if !ok {
			return syscall.ENOENT
		}
		if e.Type == TypeDirectory {
			return syscall.EPERM
		}

1284
		n = node{Inode: e.Inode}
1285
		ok, err = s.Get(&n)
1286 1287 1288
		if err != nil {
			return err
		}
D
Davies Liu 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		now := time.Now().UnixNano() / 1e3
		opened = false
		if ok {
			if ctx.Uid() != 0 && pn.Mode&01000 != 0 && ctx.Uid() != pn.Uid && ctx.Uid() != n.Uid {
				return syscall.EACCES
			}
			n.Nlink--
			n.Ctime = now
			if n.Type == TypeFile && n.Nlink == 0 {
				opened = m.of.IsOpen(e.Inode)
			}
		} else {
			logger.Warnf("no attribute for inode %d (%d, %s)", e.Inode, parent, name)
1302
		}
1303
		defer func() { m.of.InvalidateChunk(e.Inode, 0xFFFFFFFE) }()
1304 1305

		pn.Mtime = now
1306
		pn.Ctime = now
1307

S
Sandy Xu 已提交
1308
		if _, err := s.Delete(&edge{Parent: parent, Name: e.Name}); err != nil {
1309 1310 1311 1312 1313
			return err
		}
		if _, err := s.Delete(&xattr{Inode: e.Inode}); err != nil {
			return err
		}
D
Davies Liu 已提交
1314
		if _, err = s.Cols("mtime", "ctime").Update(&pn, &node{Inode: pn.Inode}); err != nil {
1315 1316 1317 1318
			return err
		}

		if n.Nlink > 0 {
D
Davies Liu 已提交
1319
			if _, err := s.Cols("nlink", "ctime").Update(&n, &node{Inode: e.Inode}); err != nil {
1320 1321 1322 1323 1324 1325
				return err
			}
		} else {
			switch e.Type {
			case TypeFile:
				if opened {
D
Davies Liu 已提交
1326
					if err = mustInsert(s, sustained{m.sid, e.Inode}); err != nil {
1327 1328
						return err
					}
1329
					if _, err := s.Cols("nlink", "ctime").Update(&n, &node{Inode: e.Inode}); err != nil {
1330 1331 1332
						return err
					}
				} else {
D
Davies Liu 已提交
1333
					if err = mustInsert(s, delfile{e.Inode, n.Length, time.Now().Unix()}); err != nil {
1334 1335 1336 1337 1338
						return err
					}
					if _, err := s.Delete(&node{Inode: e.Inode}); err != nil {
						return err
					}
D
Davies Liu 已提交
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
					newSpace, newInode = -align4K(n.Length), -1
				}
			case TypeSymlink:
				if _, err := s.Delete(&symlink{Inode: e.Inode}); err != nil {
					return err
				}
				fallthrough
			default:
				if _, err := s.Delete(&node{Inode: e.Inode}); err != nil {
					return err
1349
				}
D
Davies Liu 已提交
1350
				newSpace, newInode = -align4K(0), -1
1351 1352
			}
		}
1353 1354 1355 1356
		return err
	})
	if err == nil {
		if n.Type == TypeFile && n.Nlink == 0 {
1357 1358
			if opened {
				m.Lock()
1359
				m.removedFiles[Ino(n.Inode)] = true
1360 1361
				m.Unlock()
			} else {
1362
				go m.deleteFile(n.Inode, n.Length)
1363 1364
			}
		}
D
Davies Liu 已提交
1365 1366 1367
		m.updateStats(newSpace, newInode)
	}
	return errno(err)
1368 1369 1370 1371 1372 1373 1374 1375 1376
}

func (m *dbMeta) Rmdir(ctx Context, parent Ino, name string) syscall.Errno {
	if name == "." {
		return syscall.EINVAL
	}
	if name == ".." {
		return syscall.ENOTEMPTY
	}
1377
	defer timeit(time.Now())
1378
	parent = m.checkRoot(parent)
D
Davies Liu 已提交
1379
	err := m.txn(func(s *xorm.Session) error {
1380 1381
		var pn = node{Inode: parent}
		ok, err := s.Get(&pn)
1382 1383 1384 1385 1386 1387 1388 1389 1390
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if pn.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
1391 1392
		var e = edge{Parent: parent, Name: name}
		ok, err = s.Get(&e)
1393 1394 1395 1396 1397 1398 1399
		if err != nil {
			return err
		}
		if !ok && m.conf.CaseInsensi {
			if ee := m.resolveCase(ctx, parent, name); ee != nil {
				ok = true
				e.Inode = ee.Inode
S
Sandy Xu 已提交
1400
				e.Name = string(ee.Name)
1401 1402 1403 1404 1405 1406 1407 1408 1409
				e.Type = ee.Attr.Typ
			}
		}
		if !ok {
			return syscall.ENOENT
		}
		if e.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
1410 1411 1412 1413 1414 1415
		if ctx.Uid() != 0 && pn.Mode&01000 != 0 && ctx.Uid() != pn.Uid {
			var n = node{Inode: e.Inode}
			ok, err = s.Get(&n)
			if err != nil {
				return err
			}
D
Davies Liu 已提交
1416
			if ok && ctx.Uid() != n.Uid {
1417
				return syscall.EACCES
D
Davies Liu 已提交
1418 1419
			} else if !ok {
				logger.Warnf("no attribute for inode %d (%d, %s)", e.Inode, parent, name)
1420 1421
			}
		}
1422
		exist, err := s.Exist(&edge{Parent: e.Inode})
1423 1424 1425
		if err != nil {
			return err
		}
1426
		if exist {
1427 1428 1429
			return syscall.ENOTEMPTY
		}

1430
		now := time.Now().UnixNano() / 1e3
1431 1432
		pn.Nlink--
		pn.Mtime = now
1433
		pn.Ctime = now
S
Sandy Xu 已提交
1434
		if _, err := s.Delete(&edge{Parent: parent, Name: e.Name}); err != nil {
1435 1436 1437 1438 1439 1440 1441 1442
			return err
		}
		if _, err := s.Delete(&node{Inode: e.Inode}); err != nil {
			return err
		}
		if _, err := s.Delete(&xattr{Inode: e.Inode}); err != nil {
			return err
		}
D
Davies Liu 已提交
1443
		_, err = s.Cols("nlink", "mtime", "ctime").Update(&pn, &node{Inode: pn.Inode})
1444
		return err
D
Davies Liu 已提交
1445 1446 1447 1448 1449
	})
	if err == nil {
		m.updateStats(-align4K(0), -1)
	}
	return errno(err)
1450 1451
}

S
Sandy Xu 已提交
1452 1453 1454 1455 1456 1457 1458 1459
func (m *dbMeta) Rename(ctx Context, parentSrc Ino, nameSrc string, parentDst Ino, nameDst string, flags uint32, inode *Ino, attr *Attr) syscall.Errno {
	switch flags {
	case 0, RenameNoReplace, RenameExchange:
	case RenameWhiteout, RenameNoReplace | RenameWhiteout:
		return syscall.ENOTSUP
	default:
		return syscall.EINVAL
	}
1460
	defer timeit(time.Now())
S
Sandy Xu 已提交
1461
	exchange := flags == RenameExchange
1462 1463
	parentSrc = m.checkRoot(parentSrc)
	parentDst = m.checkRoot(parentDst)
1464 1465 1466
	var opened bool
	var dino Ino
	var dn node
D
Davies Liu 已提交
1467 1468
	var newSpace, newInode int64
	err := m.txn(func(s *xorm.Session) error {
1469
		var se = edge{Parent: parentSrc, Name: nameSrc}
S
Sandy Xu 已提交
1470
		ok, err := s.Get(&se)
1471 1472 1473 1474 1475 1476 1477
		if err != nil {
			return err
		}
		if !ok && m.conf.CaseInsensi {
			if e := m.resolveCase(ctx, parentSrc, nameSrc); e != nil {
				ok = true
				se.Inode = e.Inode
S
Sandy Xu 已提交
1478
				se.Type = e.Attr.Typ
S
Sandy Xu 已提交
1479
				se.Name = string(e.Name)
1480 1481 1482 1483 1484
			}
		}
		if !ok {
			return syscall.ENOENT
		}
S
Sandy Xu 已提交
1485
		if parentSrc == parentDst && se.Name == nameDst {
1486 1487 1488 1489 1490
			if inode != nil {
				*inode = Ino(se.Inode)
			}
			return nil
		}
S
Sandy Xu 已提交
1491 1492
		var spn = node{Inode: parentSrc}
		ok, err = s.Get(&spn)
1493 1494 1495 1496 1497 1498
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
S
Sandy Xu 已提交
1499 1500 1501
		if spn.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
1502 1503
		var dpn = node{Inode: parentDst}
		ok, err = s.Get(&dpn)
1504 1505 1506 1507 1508 1509 1510 1511 1512
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if dpn.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
S
Sandy Xu 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521
		var sn = node{Inode: se.Inode}
		ok, err = s.Get(&sn)
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}

1522 1523
		var de = edge{Parent: parentDst, Name: nameDst}
		ok, err = s.Get(&de)
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
		if err != nil {
			return err
		}
		if !ok && m.conf.CaseInsensi {
			if e := m.resolveCase(ctx, parentDst, nameDst); e != nil {
				ok = true
				de.Inode = e.Inode
				de.Type = e.Attr.Typ
				de.Name = string(e.Name)
			}
		}
S
Sandy Xu 已提交
1535
		now := time.Now().UnixNano() / 1e3
1536 1537
		opened = false
		dn = node{Inode: de.Inode}
1538
		if ok {
S
Sandy Xu 已提交
1539
			if flags == RenameNoReplace {
1540 1541
				return syscall.EEXIST
			}
S
Sandy Xu 已提交
1542
			dino = Ino(de.Inode)
1543 1544 1545 1546 1547
			ok, err := s.Get(&dn)
			if err != nil {
				return err
			}
			if !ok {
S
Sandy Xu 已提交
1548
				return syscall.ENOENT // corrupt entry
1549
			}
S
Sandy Xu 已提交
1550
			if exchange {
炽天 已提交
1551
				dn.Parent = parentSrc
S
Sandy Xu 已提交
1552 1553 1554 1555
				dn.Ctime = now
				if de.Type == TypeDirectory && parentSrc != parentDst {
					dpn.Nlink--
					spn.Nlink++
1556 1557
				}
			} else {
S
Sandy Xu 已提交
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
				if de.Type == TypeDirectory {
					exist, err := s.Exist(&edge{Parent: de.Inode})
					if err != nil {
						return err
					}
					if exist {
						return syscall.ENOTEMPTY
					}
				} else {
					dn.Nlink--
					if dn.Nlink > 0 {
						dn.Ctime = now
					} else if de.Type == TypeFile {
						opened = m.of.IsOpen(dn.Inode)
					}
1573 1574
				}
			}
1575 1576 1577
			if ctx.Uid() != 0 && dpn.Mode&01000 != 0 && ctx.Uid() != dpn.Uid && ctx.Uid() != dn.Uid {
				return syscall.EACCES
			}
S
Sandy Xu 已提交
1578 1579 1580 1581 1582
		} else {
			if exchange {
				return syscall.ENOENT
			}
			dino = 0
1583 1584 1585
		}
		if ctx.Uid() != 0 && spn.Mode&01000 != 0 && ctx.Uid() != spn.Uid && ctx.Uid() != sn.Uid {
			return syscall.EACCES
1586 1587 1588
		}

		spn.Mtime = now
1589
		spn.Ctime = now
1590
		dpn.Mtime = now
1591
		dpn.Ctime = now
1592
		sn.Parent = parentDst
1593
		sn.Ctime = now
S
Sandy Xu 已提交
1594
		if se.Type == TypeDirectory && parentSrc != parentDst {
1595 1596 1597
			spn.Nlink--
			dpn.Nlink++
		}
1598 1599 1600
		if inode != nil {
			*inode = sn.Inode
		}
1601 1602
		m.parseAttr(&sn, attr)

S
Sandy Xu 已提交
1603 1604 1605 1606 1607 1608 1609
		if exchange {
			if _, err := s.Cols("inode", "type").Update(&de, &edge{Parent: parentSrc, Name: se.Name}); err != nil {
				return err
			}
			if _, err := s.Cols("inode", "type").Update(&se, &edge{Parent: parentDst, Name: de.Name}); err != nil {
				return err
			}
炽天 已提交
1610
			if _, err := s.Cols("ctime", "parent").Update(dn, &node{Inode: dino}); err != nil {
S
Sandy Xu 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
				return err
			}
		} else {
			if n, err := s.Delete(&edge{Parent: parentSrc, Name: se.Name}); err != nil {
				return err
			} else if n != 1 {
				return fmt.Errorf("delete src failed")
			}
			if dino > 0 {
				if de.Type != TypeDirectory && dn.Nlink > 0 {
					if _, err := s.Update(dn, &node{Inode: dino}); err != nil {
						return err
					}
				} else {
					if de.Type == TypeFile {
						if opened {
							if _, err := s.Cols("nlink", "ctime").Update(&dn, &node{Inode: dino}); err != nil {
								return err
							}
							if err = mustInsert(s, sustained{m.sid, dino}); err != nil {
								return err
							}
						} else {
							if err = mustInsert(s, delfile{dino, dn.Length, time.Now().Unix()}); err != nil {
								return err
							}
							if _, err := s.Delete(&node{Inode: dino}); err != nil {
								return err
							}
							newSpace, newInode = -align4K(dn.Length), -1
1641 1642
						}
					} else {
S
Sandy Xu 已提交
1643 1644 1645 1646 1647 1648
						if de.Type == TypeDirectory {
							dn.Nlink--
						} else if de.Type == TypeSymlink {
							if _, err := s.Delete(&symlink{Inode: dino}); err != nil {
								return err
							}
1649
						}
S
Sandy Xu 已提交
1650
						if _, err := s.Delete(&node{Inode: dino}); err != nil {
1651 1652
							return err
						}
S
Sandy Xu 已提交
1653
						newSpace, newInode = -align4K(0), -1
D
Davies Liu 已提交
1654
					}
S
Sandy Xu 已提交
1655
					if _, err := s.Delete(xattr{Inode: dino}); err != nil {
D
Davies Liu 已提交
1656 1657
						return err
					}
1658
				}
S
Sandy Xu 已提交
1659
				if _, err := s.Delete(&edge{Parent: parentDst, Name: de.Name}); err != nil {
1660 1661 1662
					return err
				}
			}
S
Sandy Xu 已提交
1663
			if err = mustInsert(s, &edge{parentDst, de.Name, se.Inode, se.Type}); err != nil {
1664 1665 1666
				return err
			}
		}
1667 1668 1669 1670
		if parentDst != parentSrc {
			if _, err := s.Cols("nlink", "mtime", "ctime").Update(&spn, &node{Inode: parentSrc}); err != nil {
				return err
			}
S
Sandy Xu 已提交
1671
		}
炽天 已提交
1672
		if _, err := s.Cols("ctime", "parent").Update(&sn, &node{Inode: sn.Inode}); err != nil {
1673 1674
			return err
		}
1675 1676
		if _, err := s.Cols("nlink", "mtime", "ctime").Update(&dpn, &node{Inode: parentDst}); err != nil {
			return err
1677
		}
1678 1679
		return err
	})
S
Sandy Xu 已提交
1680
	if err == nil && !exchange {
1681
		if dino > 0 && dn.Type == TypeFile && dn.Nlink == 0 {
1682 1683 1684 1685 1686 1687 1688 1689
			if opened {
				m.Lock()
				m.removedFiles[dino] = true
				m.Unlock()
			} else {
				go m.deleteFile(dino, dn.Length)
			}
		}
D
Davies Liu 已提交
1690 1691 1692
		m.updateStats(newSpace, newInode)
	}
	return errno(err)
1693 1694 1695
}

func (m *dbMeta) Link(ctx Context, inode, parent Ino, name string, attr *Attr) syscall.Errno {
1696
	defer timeit(time.Now())
1697
	parent = m.checkRoot(parent)
1698
	defer func() { m.of.InvalidateChunk(inode, 0xFFFFFFFE) }()
1699
	return errno(m.txn(func(s *xorm.Session) error {
1700 1701
		var pn = node{Inode: parent}
		ok, err := s.Get(&pn)
1702 1703 1704 1705 1706 1707 1708 1709 1710
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if pn.Type != TypeDirectory {
			return syscall.ENOTDIR
		}
1711 1712
		var e = edge{Parent: parent, Name: name}
		ok, err = s.Get(&e)
1713 1714 1715 1716 1717 1718 1719
		if err != nil {
			return err
		}
		if ok || !ok && m.conf.CaseInsensi && m.resolveCase(ctx, parent, name) != nil {
			return syscall.EEXIST
		}

1720 1721
		var n = node{Inode: inode}
		ok, err = s.Get(&n)
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if n.Type == TypeDirectory {
			return syscall.EPERM
		}

1732
		now := time.Now().UnixNano() / 1e3
1733
		pn.Mtime = now
1734
		pn.Ctime = now
1735
		n.Nlink++
1736
		n.Ctime = now
1737

D
Davies Liu 已提交
1738
		if err = mustInsert(s, &edge{Parent: parent, Name: name, Inode: inode, Type: n.Type}); err != nil {
1739 1740
			return err
		}
D
Davies Liu 已提交
1741
		if _, err := s.Cols("mtime", "ctime").Update(&pn, &node{Inode: parent}); err != nil {
1742 1743
			return err
		}
D
Davies Liu 已提交
1744
		if _, err := s.Cols("nlink", "ctime").Update(&n, node{Inode: inode}); err != nil {
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
			return err
		}
		if err == nil {
			m.parseAttr(&n, attr)
		}
		return err
	}))
}

func (m *dbMeta) Readdir(ctx Context, inode Ino, plus uint8, entries *[]*Entry) syscall.Errno {
1755
	inode = m.checkRoot(inode)
1756 1757 1758 1759 1760
	var attr Attr
	eno := m.GetAttr(ctx, inode, &attr)
	if eno != 0 {
		return eno
	}
1761 1762 1763
	if inode == m.root {
		attr.Parent = m.root
	}
1764 1765 1766 1767 1768
	var pattr Attr
	eno = m.GetAttr(ctx, attr.Parent, &pattr)
	if eno != 0 {
		return eno
	}
1769
	defer timeit(time.Now())
1770 1771 1772
	dbSession := m.engine.Table(&edge{})
	if plus != 0 {
		dbSession = dbSession.Join("INNER", &node{}, "jfs_edge.inode=jfs_node.inode")
1773
	}
1774 1775
	var nodes []namedNode
	if err := dbSession.Find(&nodes, &edge{Parent: inode}); err != nil {
1776 1777
		return errno(err)
	}
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789

	*entries = make([]*Entry, 0, 2+len(nodes))
	*entries = append(*entries, &Entry{
		Inode: inode,
		Name:  []byte("."),
		Attr:  &attr,
	})
	*entries = append(*entries, &Entry{
		Inode: attr.Parent,
		Name:  []byte(".."),
		Attr:  &pattr,
	})
1790 1791 1792 1793 1794
	for _, n := range nodes {
		entry := &Entry{
			Inode: n.Inode,
			Name:  []byte(n.Name),
			Attr:  &Attr{},
1795
		}
1796 1797 1798 1799 1800 1801
		if plus != 0 {
			m.parseAttr(&n.node, entry.Attr)
		} else {
			entry.Attr.Typ = n.Type
		}
		*entries = append(*entries, entry)
1802 1803 1804 1805
	}
	return 0
}

1806
func (m *dbMeta) cleanStaleSession(sid uint64, sync bool) {
D
Davies Liu 已提交
1807 1808
	// release locks
	_, _ = m.engine.Delete(flock{Sid: sid})
1809
	_, _ = m.engine.Delete(plock{Sid: sid})
D
Davies Liu 已提交
1810

1811 1812
	var s = sustained{Sid: sid}
	rows, err := m.engine.Rows(&s)
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
	if err != nil {
		logger.Warnf("scan stale session %d: %s", sid, err)
		return
	}

	var inodes []Ino
	for rows.Next() {
		if rows.Scan(&s) == nil {
			inodes = append(inodes, s.Inode)
		}
	}
	rows.Close()

S
satoru 已提交
1826
	done := true
1827
	for _, inode := range inodes {
1828
		if err := m.deleteInode(inode, sync); err != nil {
1829 1830 1831 1832
			logger.Errorf("Failed to delete inode %d: %s", inode, err)
			done = false
		} else {
			_ = m.txn(func(ses *xorm.Session) error {
D
Davies Liu 已提交
1833
				_, err = ses.Delete(&sustained{Sid: sid, Inode: inode})
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
				return err
			})
		}
	}
	if done {
		_ = m.txn(func(ses *xorm.Session) error {
			_, err = ses.Delete(&session{Sid: sid})
			logger.Infof("cleanup session %d: %s", sid, err)
			return err
		})
	}
}

func (m *dbMeta) cleanStaleSessions() {
	var s session
1849
	rows, err := m.engine.Where("Heartbeat < ?", time.Now().Add(time.Minute*-5).Unix()).Rows(&s)
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
	if err != nil {
		logger.Warnf("scan stale sessions: %s", err)
		return
	}
	var ids []uint64
	for rows.Next() {
		if rows.Scan(&s) == nil {
			ids = append(ids, s.Sid)
		}
	}
	rows.Close()
	for _, sid := range ids {
1862
		m.cleanStaleSession(sid, false)
1863 1864 1865 1866 1867 1868
	}
}

func (m *dbMeta) refreshSession() {
	for {
		time.Sleep(time.Minute)
1869 1870 1871 1872 1873
		m.Lock()
		if m.umounting {
			m.Unlock()
			return
		}
1874
		_ = m.txn(func(ses *xorm.Session) error {
1875
			n, err := ses.Cols("Heartbeat").Update(&session{Heartbeat: time.Now().Unix()}, &session{Sid: m.sid})
1876 1877 1878 1879
			if err == nil && n == 0 {
				err = fmt.Errorf("no session found matching sid: %d", m.sid)
			}
			if err != nil {
1880 1881 1882 1883
				logger.Errorf("update session: %s", err)
			}
			return err
		})
1884
		m.Unlock()
1885 1886 1887
		if _, err := m.Load(); err != nil {
			logger.Warnf("reload setting: %s", err)
		}
1888 1889 1890 1891
		go m.cleanStaleSessions()
	}
}

1892
func (m *dbMeta) deleteInode(inode Ino, sync bool) error {
1893
	var n = node{Inode: inode}
D
Davies Liu 已提交
1894
	var newSpace int64
1895
	err := m.txn(func(s *xorm.Session) error {
1896
		ok, err := s.Get(&n)
1897 1898 1899 1900 1901 1902
		if err != nil {
			return err
		}
		if !ok {
			return nil
		}
D
Davies Liu 已提交
1903
		if err = mustInsert(s, &delfile{inode, n.Length, time.Now().Unix()}); err != nil {
1904 1905
			return err
		}
D
Davies Liu 已提交
1906 1907
		newSpace = -align4K(n.Length)
		_, err = s.Delete(&node{Inode: inode})
1908 1909 1910
		return err
	})
	if err == nil {
D
Davies Liu 已提交
1911
		m.updateStats(newSpace, -1)
1912 1913 1914 1915 1916
		if sync {
			m.deleteFile(inode, n.Length)
		} else {
			go m.deleteFile(inode, n.Length)
		}
1917 1918 1919 1920
	}
	return err
}

D
Davies Liu 已提交
1921
func (m *dbMeta) Open(ctx Context, inode Ino, flags uint32, attr *Attr) syscall.Errno {
1922 1923 1924 1925 1926 1927
	if m.conf.ReadOnly && flags&(syscall.O_WRONLY|syscall.O_RDWR|syscall.O_TRUNC|syscall.O_APPEND) != 0 {
		return syscall.EROFS
	}
	if m.conf.OpenCache > 0 && m.of.OpenCheck(inode, attr) {
		return 0
	}
1928
	var err syscall.Errno
1929
	if attr != nil && !attr.Full {
1930 1931 1932
		err = m.GetAttr(ctx, inode, attr)
	}
	if err == 0 {
1933
		m.of.Open(inode, attr)
1934 1935 1936 1937 1938
	}
	return 0
}

func (m *dbMeta) Close(ctx Context, inode Ino) syscall.Errno {
1939 1940 1941
	if m.of.Close(inode) {
		m.Lock()
		defer m.Unlock()
1942 1943 1944
		if m.removedFiles[inode] {
			delete(m.removedFiles, inode)
			go func() {
1945
				if err := m.deleteInode(inode, false); err == nil {
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
					_ = m.txn(func(ses *xorm.Session) error {
						_, err := ses.Delete(&sustained{m.sid, inode})
						return err
					})
				}
			}()
		}
	}
	return 0
}

func (m *dbMeta) Read(ctx Context, inode Ino, indx uint32, chunks *[]Slice) syscall.Errno {
D
Davies Liu 已提交
1958 1959 1960 1961 1962
	f := m.of.find(inode)
	if f != nil {
		f.RLock()
		defer f.RUnlock()
	}
1963 1964 1965 1966
	if cs, ok := m.of.ReadChunk(inode, indx); ok {
		*chunks = cs
		return 0
	}
1967
	defer timeit(time.Now())
1968 1969 1970 1971 1972 1973
	var c chunk
	_, err := m.engine.Where("inode=? and indx=?", inode, indx).Get(&c)
	if err != nil {
		return errno(err)
	}
	ss := readSliceBuf(c.Slices)
D
Davies Liu 已提交
1974 1975 1976
	if ss == nil {
		return syscall.EIO
	}
1977
	*chunks = buildSlice(ss)
1978
	m.of.CacheChunk(inode, indx, *chunks)
D
Davies Liu 已提交
1979
	if !m.conf.ReadOnly && (len(c.Slices)/sliceBytes >= 5 || len(*chunks) >= 5) {
1980 1981 1982 1983 1984 1985 1986 1987
		go m.compactChunk(inode, indx, false)
	}
	return 0
}

func (m *dbMeta) NewChunk(ctx Context, inode Ino, indx uint32, offset uint32, chunkid *uint64) syscall.Errno {
	m.freeMu.Lock()
	defer m.freeMu.Unlock()
1988 1989 1990 1991 1992 1993 1994
	if m.freeChunks.next >= m.freeChunks.maxid {
		v, err := m.incrCounter("nextChunk", 1000)
		if err != nil {
			return errno(err)
		}
		m.freeChunks.next = v - 1000
		m.freeChunks.maxid = v
1995
	}
1996 1997 1998
	*chunkid = m.freeChunks.next
	m.freeChunks.next++
	return 0
1999 2000
}

2001 2002 2003 2004 2005
func (m *dbMeta) InvalidateChunkCache(ctx Context, inode Ino, indx uint32) syscall.Errno {
	m.of.InvalidateChunk(inode, indx)
	return 0
}

2006
func (m *dbMeta) Write(ctx Context, inode Ino, indx uint32, off uint32, slice Slice) syscall.Errno {
2007
	defer timeit(time.Now())
D
Davies Liu 已提交
2008 2009 2010 2011 2012
	f := m.of.find(inode)
	if f != nil {
		f.Lock()
		defer f.Unlock()
	}
2013
	defer func() { m.of.InvalidateChunk(inode, indx) }()
D
Davies Liu 已提交
2014
	var newSpace int64
2015
	var needCompact bool
D
Davies Liu 已提交
2016
	err := m.txn(func(s *xorm.Session) error {
2017 2018
		var n = node{Inode: inode}
		ok, err := s.Get(&n)
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
		if err != nil {
			return err
		}
		if !ok {
			return syscall.ENOENT
		}
		if n.Type != TypeFile {
			return syscall.EPERM
		}
		newleng := uint64(indx)*ChunkSize + uint64(off) + uint64(slice.Len)
		if newleng > n.Length {
D
Davies Liu 已提交
2030
			newSpace = align4K(newleng) - align4K(n.Length)
2031 2032
			n.Length = newleng
		}
D
Davies Liu 已提交
2033 2034 2035
		if m.checkQuota(newSpace, 0) {
			return syscall.ENOSPC
		}
2036
		now := time.Now().UnixNano() / 1e3
2037
		n.Mtime = now
2038
		n.Ctime = now
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050

		var ck chunk
		ok, err = s.Where("Inode = ? and Indx = ?", inode, indx).Get(&ck)
		if err != nil {
			return err
		}
		buf := marshalSlice(off, slice.Chunkid, slice.Size, slice.Off, slice.Len)
		if ok {
			if err := m.appendSlice(s, inode, indx, buf); err != nil {
				return err
			}
		} else {
D
Davies Liu 已提交
2051
			if err = mustInsert(s, &chunk{inode, indx, buf}); err != nil {
2052 2053 2054
				return err
			}
		}
D
Davies Liu 已提交
2055
		if err = mustInsert(s, chunkRef{slice.Chunkid, slice.Size, 1}); err != nil {
2056 2057
			return err
		}
D
Davies Liu 已提交
2058
		_, err = s.Cols("length", "mtime", "ctime").Update(&n, &node{Inode: inode})
2059 2060
		if err == nil {
			needCompact = (len(ck.Slices)/sliceBytes)%100 == 99
2061 2062
		}
		return err
D
Davies Liu 已提交
2063 2064
	})
	if err == nil {
2065 2066 2067
		if needCompact {
			go m.compactChunk(inode, indx, false)
		}
D
Davies Liu 已提交
2068 2069 2070
		m.updateStats(newSpace, 0)
	}
	return errno(err)
2071 2072 2073
}

func (m *dbMeta) CopyFileRange(ctx Context, fin Ino, offIn uint64, fout Ino, offOut uint64, size uint64, flags uint32, copied *uint64) syscall.Errno {
2074
	defer timeit(time.Now())
D
Davies Liu 已提交
2075 2076 2077 2078 2079
	f := m.of.find(fout)
	if f != nil {
		f.Lock()
		defer f.Unlock()
	}
D
Davies Liu 已提交
2080
	var newSpace int64
2081
	defer func() { m.of.InvalidateChunk(fout, 0xFFFFFFFF) }()
D
Davies Liu 已提交
2082
	err := m.txn(func(s *xorm.Session) error {
2083 2084
		var nin, nout = node{Inode: fin}, node{Inode: fout}
		ok, err := s.Get(&nin)
2085 2086 2087
		if err != nil {
			return err
		}
2088
		ok2, err2 := s.Get(&nout)
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
		if err2 != nil {
			return err2
		}
		if !ok || !ok2 {
			return syscall.ENOENT
		}
		if nin.Type != TypeFile {
			return syscall.EINVAL
		}
		if offIn >= nin.Length {
			*copied = 0
			return nil
		}
		if offIn+size > nin.Length {
			size = nin.Length - offIn
		}
		if nout.Type != TypeFile {
			return syscall.EINVAL
		}

		newleng := offOut + size
		if newleng > nout.Length {
D
Davies Liu 已提交
2111
			newSpace = align4K(newleng) - align4K(nout.Length)
2112 2113
			nout.Length = newleng
		}
D
Davies Liu 已提交
2114 2115 2116
		if m.checkQuota(newSpace, 0) {
			return syscall.ENOSPC
		}
2117
		now := time.Now().UnixNano() / 1e3
2118
		nout.Mtime = now
2119
		nout.Ctime = now
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142

		var c chunk
		rows, err := s.Where("inode = ? AND indx >= ? AND indx <= ?", fin, offIn/ChunkSize, (offIn+size)/ChunkSize).Rows(&c)
		if err != nil {
			return err
		}
		chunks := make(map[uint32][]*slice)
		for rows.Next() {
			err = rows.Scan(&c)
			if err != nil {
				rows.Close()
				return err
			}
			chunks[c.Indx] = readSliceBuf(c.Slices)
		}
		rows.Close()

		ses := s
		updateSlices := func(indx uint32, buf []byte, s *Slice) error {
			if err := m.appendSlice(ses, fout, indx, buf); err != nil {
				return err
			}
			if s.Chunkid > 0 {
D
Davies Liu 已提交
2143
				if _, err := ses.Exec("update jfs_chunk_ref set refs=refs+1 where chunkid = ? AND size = ?", s.Chunkid, s.Size); err != nil {
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
					return err
				}
			}
			return nil
		}
		coff := uint64(offIn/ChunkSize) * ChunkSize
		for coff < offIn+size {
			if coff%ChunkSize != 0 {
				panic("coff")
			}
			// Add a zero chunk for hole
			ss := append([]*slice{{len: ChunkSize}}, chunks[uint32(coff/ChunkSize)]...)
			cs := buildSlice(ss)
			for _, s := range cs {
				pos := coff
				coff += uint64(s.Len)
				if pos < offIn+size && pos+uint64(s.Len) > offIn {
					if pos < offIn {
						dec := offIn - pos
						s.Off += uint32(dec)
						pos += dec
						s.Len -= uint32(dec)
					}
					if pos+uint64(s.Len) > offIn+size {
						dec := pos + uint64(s.Len) - (offIn + size)
						s.Len -= uint32(dec)
					}
					doff := pos - offIn + offOut
					indx := uint32(doff / ChunkSize)
					dpos := uint32(doff % ChunkSize)
					if dpos+s.Len > ChunkSize {
						if err := updateSlices(indx, marshalSlice(dpos, s.Chunkid, s.Size, s.Off, ChunkSize-dpos), &s); err != nil {
							return err
						}
						skip := ChunkSize - dpos
						if err := updateSlices(indx+1, marshalSlice(0, s.Chunkid, s.Size, s.Off+skip, s.Len-skip), &s); err != nil {
							return err
						}
					} else {
						if err := updateSlices(indx, marshalSlice(dpos, s.Chunkid, s.Size, s.Off, s.Len), &s); err != nil {
							return err
						}
					}
				}
			}
		}
D
Davies Liu 已提交
2190
		if _, err := s.Cols("length", "mtime", "ctime").Update(&nout, &node{Inode: fout}); err != nil {
2191 2192
			return err
		}
D
Davies Liu 已提交
2193 2194 2195 2196 2197 2198 2199
		*copied = size
		return nil
	})
	if err == nil {
		m.updateStats(newSpace, 0)
	}
	return errno(err)
2200 2201 2202 2203 2204 2205
}

func (m *dbMeta) cleanupDeletedFiles() {
	for {
		time.Sleep(time.Minute)
		var d delfile
2206
		rows, err := m.engine.Where("expire < ?", time.Now().Add(-time.Hour).Unix()).Rows(&d)
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
		if err != nil {
			continue
		}
		var fs []delfile
		for rows.Next() {
			if rows.Scan(&d) == nil {
				fs = append(fs, d)
			}
		}
		rows.Close()
		for _, f := range fs {
			logger.Debugf("cleanup chunks of inode %d with %d bytes", f.Inode, f.Length)
2219
			m.deleteFile(f.Inode, f.Length)
2220 2221 2222 2223 2224 2225 2226 2227 2228
		}
	}
}

func (m *dbMeta) cleanupSlices() {
	for {
		time.Sleep(time.Hour)

		// once per hour
2229 2230
		var c = counter{Name: "nextCleanupSlices"}
		_, err := m.engine.Get(&c)
2231 2232 2233 2234
		if err != nil {
			continue
		}
		now := time.Now().Unix()
D
Davies Liu 已提交
2235
		if c.Value+3600 > now {
2236 2237 2238
			continue
		}
		_ = m.txn(func(ses *xorm.Session) error {
D
Davies Liu 已提交
2239
			_, err := ses.Update(&counter{Value: now}, counter{Name: "nextCleanupSlices"})
2240 2241 2242
			return err
		})

D
Davies Liu 已提交
2243
		var ck chunkRef
2244 2245 2246 2247
		rows, err := m.engine.Where("refs <= 0").Rows(&ck)
		if err != nil {
			continue
		}
D
Davies Liu 已提交
2248
		var cks []chunkRef
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
		for rows.Next() {
			if rows.Scan(&ck) == nil {
				cks = append(cks, ck)
			}
		}
		rows.Close()
		for _, ck := range cks {
			if ck.Refs <= 0 {
				m.deleteSlice(ck.Chunkid, ck.Size)
			}
		}
	}
}

func (m *dbMeta) deleteSlice(chunkid uint64, size uint32) {
2264 2265 2266
	if m.conf.MaxDeletes == 0 {
		return
	}
2267 2268 2269 2270 2271 2272 2273
	m.deleting <- 1
	defer func() { <-m.deleting }()
	err := m.newMsg(DeleteChunk, chunkid, size)
	if err != nil {
		logger.Warnf("delete chunk %d (%d bytes): %s", chunkid, size, err)
	} else {
		err = m.txn(func(ses *xorm.Session) error {
D
Davies Liu 已提交
2274
			_, err = ses.Exec("delete from jfs_chunk_ref where chunkid=?", chunkid)
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
			return err
		})
		if err != nil {
			logger.Errorf("delete slice %d: %s", chunkid, err)
		}
	}
}

func (m *dbMeta) deleteChunk(inode Ino, indx uint32) error {
	var c chunk
	var ss []*slice
	err := m.txn(func(ses *xorm.Session) error {
		ok, err := ses.Where("inode = ? AND indx = ?", inode, indx).Get(&c)
		if err != nil {
			return err
		}
		if !ok {
			return nil
		}
		ss = readSliceBuf(c.Slices)
		for _, s := range ss {
D
Davies Liu 已提交
2296
			_, err = ses.Exec("update jfs_chunk_ref set refs=refs-1 where chunkid=? AND size=?", s.chunkid, s.size)
2297 2298 2299 2300
			if err != nil {
				return err
			}
		}
W
Wjie 已提交
2301
		n, err := ses.Delete(chunk{Inode: c.Inode, Indx: c.Indx})
2302 2303 2304
		if err == nil && n == 0 {
			err = fmt.Errorf("chunk %d:%d changed, try restarting transaction", inode, indx)
		}
2305 2306 2307 2308 2309 2310
		return err
	})
	if err != nil {
		return fmt.Errorf("delete slice from chunk %s fail: %s, retry later", inode, err)
	}
	for _, s := range ss {
2311 2312 2313 2314 2315
		var ref = chunkRef{Chunkid: s.chunkid}
		ok, err := m.engine.Get(&ref)
		if err == nil && ok && ref.Refs <= 0 {
			m.deleteSlice(s.chunkid, s.size)
		}
2316 2317 2318 2319 2320
	}
	return nil
}

func (m *dbMeta) deleteFile(inode Ino, length uint64) {
2321 2322
	var c = chunk{Inode: inode}
	rows, err := m.engine.Rows(&c)
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
	if err != nil {
		return
	}
	var indexes []uint32
	for rows.Next() {
		if rows.Scan(&c) == nil {
			indexes = append(indexes, c.Indx)
		}
	}
	rows.Close()
	for _, indx := range indexes {
		err = m.deleteChunk(inode, indx)
		if err != nil {
W
Wjie 已提交
2336
			logger.Debugf("deleteChunk inode %d index %d error: %s", inode, indx, err)
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
			return
		}
	}
	_, _ = m.engine.Delete(delfile{Inode: inode})
}

func (m *dbMeta) compactChunk(inode Ino, indx uint32, force bool) {
	if !force {
		// avoid too many or duplicated compaction
		m.Lock()
		k := uint64(inode) + (uint64(indx) << 32)
		if len(m.compacting) > 10 || m.compacting[k] {
			m.Unlock()
			return
		}
		m.compacting[k] = true
		m.Unlock()
		defer func() {
			m.Lock()
			delete(m.compacting, k)
			m.Unlock()
		}()
	}

	var c chunk
	_, err := m.engine.Where("inode=? and indx=?", inode, indx).Get(&c)
	if err != nil {
		return
	}

D
Davies Liu 已提交
2367 2368 2369 2370 2371
	ss := readSliceBuf(c.Slices)
	skipped := skipSome(ss)
	ss = ss[skipped:]
	pos, size, chunks := compactChunk(ss)
	if len(ss) < 2 || size == 0 {
2372 2373 2374 2375 2376 2377 2378 2379
		return
	}

	var chunkid uint64
	st := m.NewChunk(Background, 0, 0, 0, &chunkid)
	if st != 0 {
		return
	}
2380
	logger.Debugf("compact %d:%d: skipped %d slices (%d bytes) %d slices (%d bytes)", inode, indx, skipped, pos, len(ss), size)
2381 2382
	err = m.newMsg(CompactChunk, chunks, chunkid)
	if err != nil {
2383 2384 2385
		if !strings.Contains(err.Error(), "not exist") && !strings.Contains(err.Error(), "not found") {
			logger.Warnf("compact %d %d with %d slices: %s", inode, indx, len(ss), err)
		}
2386 2387
		return
	}
2388
	err = m.txn(func(ses *xorm.Session) error {
2389
		var c2 = chunk{Inode: inode}
2390
		_, err := ses.Where("indx=?", indx).Get(&c2)
2391 2392 2393 2394 2395 2396 2397 2398
		if err != nil {
			return err
		}
		if len(c2.Slices) < len(c.Slices) || !bytes.Equal(c.Slices, c2.Slices[:len(c.Slices)]) {
			logger.Infof("chunk %d:%d was changed %d -> %d", inode, indx, len(c.Slices), len(c2.Slices))
			return syscall.EINVAL
		}

2399
		c2.Slices = append(append(c2.Slices[:skipped*sliceBytes], marshalSlice(pos, chunkid, size, 0, size)...), c2.Slices[len(c.Slices):]...)
2400
		if _, err := ses.Where("Inode = ? AND indx = ?", inode, indx).Update(c2); err != nil {
2401 2402 2403
			return err
		}
		// create the key to tracking it
2404
		if err = mustInsert(ses, chunkRef{chunkid, size, 1}); err != nil {
2405 2406 2407
			return err
		}
		for _, s := range ss {
D
Davies Liu 已提交
2408
			if _, err := ses.Exec("update jfs_chunk_ref set refs=refs-1 where chunkid=? and size=?", s.chunkid, s.size); err != nil {
2409 2410 2411 2412 2413 2414 2415
				return err
			}
		}
		return nil
	})
	// there could be false-negative that the compaction is successful, double-check
	if err != nil {
D
Davies Liu 已提交
2416
		var c = chunkRef{Chunkid: chunkid}
2417
		ok, e := m.engine.Get(&c)
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
		if e == nil {
			if ok {
				err = nil
			} else {
				logger.Infof("compacted chunk %d was not used", chunkid)
				err = syscall.EINVAL
			}
		}
	}

	if errno, ok := err.(syscall.Errno); ok && errno == syscall.EINVAL {
		logger.Infof("compaction for %d:%d is wasted, delete slice %d (%d bytes)", inode, indx, chunkid, size)
		m.deleteSlice(chunkid, size)
	} else if err == nil {
2432
		m.of.InvalidateChunk(inode, indx)
2433
		for _, s := range ss {
D
Davies Liu 已提交
2434
			var ref = chunkRef{Chunkid: s.chunkid}
2435
			ok, err := m.engine.Get(&ref)
2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
			if err == nil && ok && ref.Refs <= 0 {
				m.deleteSlice(s.chunkid, s.size)
			}
		}
	} else {
		logger.Warnf("compact %d %d: %s", inode, indx, err)
	}
	go func() {
		// wait for the current compaction to finish
		time.Sleep(time.Millisecond * 10)
		m.compactChunk(inode, indx, force)
	}()
}

2450 2451 2452 2453 2454 2455
func dup(b []byte) []byte {
	r := make([]byte, len(b))
	copy(r, b)
	return r
}

2456 2457 2458 2459 2460 2461 2462 2463 2464
func (m *dbMeta) CompactAll(ctx Context) syscall.Errno {
	var c chunk
	rows, err := m.engine.Where("length(slices) >= ?", sliceBytes*2).Cols("inode", "indx").Rows(&c)
	if err != nil {
		return errno(err)
	}
	var cs []chunk
	for rows.Next() {
		if rows.Scan(&c) == nil {
2465
			c.Slices = dup(c.Slices)
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
			cs = append(cs, c)
		}
	}
	rows.Close()

	for _, c := range cs {
		logger.Debugf("compact chunk %d:%d (%d slices)", c.Inode, c.Indx, len(c.Slices)/sliceBytes)
		m.compactChunk(c.Inode, c.Indx, true)
	}
	return 0
}

2478
func (m *dbMeta) ListSlices(ctx Context, slices *[]Slice, delete bool, showProgress func()) syscall.Errno {
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
	var c chunk
	rows, err := m.engine.Rows(&c)
	if err != nil {
		return errno(err)
	}
	defer rows.Close()

	*slices = nil
	for rows.Next() {
		err = rows.Scan(&c)
		if err != nil {
			return errno(err)
		}
		ss := readSliceBuf(c.Slices)
		for _, s := range ss {
			if s.chunkid > 0 {
				*slices = append(*slices, Slice{Chunkid: s.chunkid, Size: s.size})
2496 2497 2498
				if showProgress != nil {
					showProgress()
				}
2499 2500 2501 2502 2503 2504 2505
			}
		}
	}
	return 0
}

func (m *dbMeta) GetXattr(ctx Context, inode Ino, name string, vbuff *[]byte) syscall.Errno {
2506
	defer timeit(time.Now())
2507
	inode = m.checkRoot(inode)
2508 2509
	var x = xattr{Inode: inode, Name: name}
	ok, err := m.engine.Get(&x)
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
	if err != nil {
		return errno(err)
	}
	if !ok {
		return ENOATTR
	}
	*vbuff = x.Value
	return 0
}

func (m *dbMeta) ListXattr(ctx Context, inode Ino, names *[]byte) syscall.Errno {
2521
	defer timeit(time.Now())
2522
	inode = m.checkRoot(inode)
2523
	var x = xattr{Inode: inode}
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
	rows, err := m.engine.Where("inode = ?", inode).Rows(&x)
	if err != nil {
		return errno(err)
	}
	defer rows.Close()
	*names = nil
	for rows.Next() {
		err = rows.Scan(&x)
		if err != nil {
			return errno(err)
		}
		*names = append(*names, []byte(x.Name)...)
		*names = append(*names, 0)
	}
	return 0
}

S
Sandy Xu 已提交
2541
func (m *dbMeta) SetXattr(ctx Context, inode Ino, name string, value []byte, flags uint32) syscall.Errno {
2542 2543 2544
	if name == "" {
		return syscall.EINVAL
	}
2545
	defer timeit(time.Now())
2546
	inode = m.checkRoot(inode)
2547 2548
	return errno(m.txn(func(s *xorm.Session) error {
		var x = xattr{inode, name, value}
2549 2550 2551 2552 2553 2554 2555
		var err error
		var n int64
		switch flags {
		case XattrCreate:
			n, err = s.Insert(&x)
			if err != nil || n == 0 {
				err = syscall.EEXIST
2556
			}
2557 2558 2559 2560 2561 2562
		case XattrReplace:
			n, err = s.Update(&x, &xattr{inode, name, nil})
			if err == nil && n == 0 {
				err = ENOATTR
			}
		default:
2563 2564 2565 2566 2567 2568 2569 2570
			n, err = s.Insert(&x)
			if err != nil || n == 0 {
				if m.engine.DriverName() == "postgres" {
					// cleanup failed session
					_ = s.Rollback()
				}
				_, err = s.Update(&x, &xattr{inode, name, nil})
			}
2571 2572 2573 2574 2575 2576 2577 2578 2579
		}
		return err
	}))
}

func (m *dbMeta) RemoveXattr(ctx Context, inode Ino, name string) syscall.Errno {
	if name == "" {
		return syscall.EINVAL
	}
2580
	defer timeit(time.Now())
2581
	inode = m.checkRoot(inode)
2582 2583
	return errno(m.txn(func(s *xorm.Session) error {
		n, err := s.Delete(&xattr{Inode: inode, Name: name})
2584 2585 2586 2587 2588 2589
		if err != nil {
			return err
		} else if n == 0 {
			return ENOATTR
		} else {
			return nil
2590 2591 2592
		}
	}))
}
2593

2594
func (m *dbMeta) dumpEntry(inode Ino) (*DumpedEntry, error) {
2595
	e := &DumpedEntry{}
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
	return e, m.txn(func(s *xorm.Session) error {
		n := &node{Inode: inode}
		ok, err := m.engine.Get(n)
		if err != nil {
			return err
		}
		if !ok {
			return fmt.Errorf("inode %d not found", inode)
		}
		attr := &Attr{}
		m.parseAttr(n, attr)
		e.Attr = dumpAttr(attr)
2608
		e.Attr.Inode = inode
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631

		var rows []xattr
		if err = m.engine.Find(&rows, &xattr{Inode: inode}); err != nil {
			return err
		}
		if len(rows) > 0 {
			xattrs := make([]*DumpedXattr, 0, len(rows))
			for _, x := range rows {
				xattrs = append(xattrs, &DumpedXattr{x.Name, string(x.Value)})
			}
			sort.Slice(xattrs, func(i, j int) bool { return xattrs[i].Name < xattrs[j].Name })
			e.Xattrs = xattrs
		}

		if attr.Typ == TypeFile {
			for indx := uint32(0); uint64(indx)*ChunkSize < attr.Length; indx++ {
				c := &chunk{Inode: inode, Indx: indx}
				if _, err = m.engine.Get(c); err != nil {
					return err
				}
				ss := readSliceBuf(c.Slices)
				slices := make([]*DumpedSlice, 0, len(ss))
				for _, s := range ss {
2632
					slices = append(slices, &DumpedSlice{Pos: s.pos, Chunkid: s.chunkid, Off: s.size, Len: s.off, Size: s.len})
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
				}
				e.Chunks = append(e.Chunks, &DumpedChunk{indx, slices})
			}
		} else if attr.Typ == TypeSymlink {
			l := &symlink{Inode: inode}
			ok, err = m.engine.Get(l)
			if err != nil {
				return err
			}
			if !ok {
				return fmt.Errorf("no link target for inode %d", inode)
			}
			e.Symlink = l.Target
		}

		return nil
	})
}

2652
func (m *dbMeta) dumpDir(inode Ino, showProgress func(totalIncr, currentIncr int64)) (map[string]*DumpedEntry, error) {
2653 2654 2655 2656
	var edges []edge
	if err := m.engine.Find(&edges, &edge{Parent: inode}); err != nil {
		return nil, err
	}
2657 2658 2659
	if showProgress != nil {
		showProgress(int64(len(edges)), 0)
	}
2660
	entries := make(map[string]*DumpedEntry)
2661
	for _, e := range edges {
2662
		entry, err := m.dumpEntry(e.Inode)
2663 2664 2665 2666
		if err != nil {
			return nil, err
		}
		if e.Type == TypeDirectory {
2667
			if entry.Entries, err = m.dumpDir(e.Inode, showProgress); err != nil {
2668 2669 2670
				return nil, err
			}
		}
2671
		entries[e.Name] = entry
2672 2673 2674
		if showProgress != nil {
			showProgress(0, 1)
		}
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
	}
	return entries, nil
}

func (m *dbMeta) DumpMeta(w io.Writer) error {
	var drows []delfile
	if err := m.engine.Find(&drows); err != nil {
		return err
	}
	dels := make([]*DumpedDelFile, 0, len(drows))
	for _, row := range drows {
		dels = append(dels, &DumpedDelFile{row.Inode, row.Length, row.Expire})
	}

2689
	tree, err := m.dumpEntry(m.root)
2690 2691 2692
	if err != nil {
		return err
	}
2693

S
Sandy Xu 已提交
2694 2695 2696
	var total int64 = 1 // root
	progress, bar := utils.NewDynProgressBar("Dump dir progress: ", false)
	bar.Increment()
2697 2698 2699 2700 2701
	if tree.Entries, err = m.dumpDir(m.root, func(totalIncr, currentIncr int64) {
		total += totalIncr
		bar.SetTotal(total, false)
		bar.IncrInt64(currentIncr)
	}); err != nil {
2702 2703
		return err
	}
S
Sandy Xu 已提交
2704 2705 2706 2707 2708
	if bar.Current() != total {
		logger.Warnf("Dumped %d / total %d, some entries are not dumped", bar.Current(), total)
	}
	bar.SetTotal(0, true)
	progress.Wait()
2709 2710 2711

	format, err := m.Load()
	if err != nil {
2712
		return err
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
	}

	var crows []counter
	if err = m.engine.Find(&crows); err != nil {
		return err
	}
	counters := &DumpedCounters{}
	for _, row := range crows {
		switch row.Name {
		case "usedSpace":
			counters.UsedSpace = row.Value
		case "totalInodes":
			counters.UsedInodes = row.Value
		case "nextInode":
			counters.NextInode = row.Value
		case "nextChunk":
			counters.NextChunk = row.Value
		case "nextSession":
			counters.NextSession = row.Value
		}
	}

	var srows []sustained
	if err = m.engine.Find(&srows); err != nil {
		return err
	}
	ss := make(map[uint64][]Ino)
	for _, row := range srows {
		ss[row.Sid] = append(ss[row.Sid], row.Inode)
	}
	sessions := make([]*DumpedSustained, 0, len(ss))
	for k, v := range ss {
		sessions = append(sessions, &DumpedSustained{k, v})
	}

2748
	dm := DumpedMeta{
2749 2750 2751 2752 2753 2754
		format,
		counters,
		sessions,
		dels,
		tree,
	}
2755
	return dm.writeJSON(w)
2756 2757 2758
}

func (m *dbMeta) loadEntry(e *DumpedEntry, cs *DumpedCounters, refs map[uint64]*chunkRef) error {
2759 2760
	inode := e.Attr.Inode
	logger.Debugf("Loading entry inode %d name %s", inode, e.Name)
2761 2762
	attr := e.Attr
	n := &node{
2763
		Inode:  inode,
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
		Type:   typeFromString(attr.Type),
		Mode:   attr.Mode,
		Uid:    attr.Uid,
		Gid:    attr.Gid,
		Atime:  attr.Atime*1e6 + int64(attr.Atimensec)/1e3,
		Mtime:  attr.Mtime*1e6 + int64(attr.Atimensec)/1e3,
		Ctime:  attr.Ctime*1e6 + int64(attr.Atimensec)/1e3,
		Nlink:  attr.Nlink,
		Rdev:   attr.Rdev,
		Parent: e.Parent,
	} // Length not set
	var beans []interface{}
	if n.Type == TypeFile {
		n.Length = attr.Length
		chunks := make([]*chunk, 0, len(e.Chunks))
		for _, c := range e.Chunks {
			if len(c.Slices) == 0 {
				continue
			}
			slices := make([]byte, 0, sliceBytes*len(c.Slices))
			for _, s := range c.Slices {
				slices = append(slices, marshalSlice(s.Pos, s.Chunkid, s.Size, s.Off, s.Len)...)
				if refs[s.Chunkid] == nil {
					refs[s.Chunkid] = &chunkRef{s.Chunkid, s.Size, 1}
				} else {
					refs[s.Chunkid].Refs++
				}
				if cs.NextChunk <= int64(s.Chunkid) {
					cs.NextChunk = int64(s.Chunkid) + 1
				}
			}
2795
			chunks = append(chunks, &chunk{inode, c.Index, slices})
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
		}
		if len(chunks) > 0 {
			beans = append(beans, chunks)
		}
	} else if n.Type == TypeDirectory {
		n.Length = 4 << 10
		if len(e.Entries) > 0 {
			edges := make([]*edge, 0, len(e.Entries))
			for _, c := range e.Entries {
				edges = append(edges, &edge{
2806
					Parent: inode,
2807
					Name:   c.Name,
2808
					Inode:  c.Attr.Inode,
2809 2810 2811 2812 2813 2814 2815
					Type:   typeFromString(c.Attr.Type),
				})
			}
			beans = append(beans, edges)
		}
	} else if n.Type == TypeSymlink {
		n.Length = uint64(len(e.Symlink))
2816
		beans = append(beans, &symlink{inode, e.Symlink})
2817
	}
2818
	if inode > 1 {
2819 2820 2821
		cs.UsedSpace += align4K(n.Length)
		cs.UsedInodes += 1
	}
2822 2823
	if cs.NextInode <= int64(inode) {
		cs.NextInode = int64(inode) + 1
2824 2825 2826 2827 2828
	}

	if len(e.Xattrs) > 0 {
		xattrs := make([]*xattr, 0, len(e.Xattrs))
		for _, x := range e.Xattrs {
2829
			xattrs = append(xattrs, &xattr{inode, x.Name, []byte(x.Value)})
2830 2831 2832 2833 2834 2835 2836 2837 2838
		}
		beans = append(beans, xattrs)
	}
	beans = append(beans, n)
	s := m.engine.NewSession()
	defer s.Close()
	return mustInsert(s, beans...)
}

2839
func (m *dbMeta) LoadMeta(r io.Reader) error {
2840 2841 2842 2843 2844
	tables, err := m.engine.DBMetas()
	if err != nil {
		return err
	}
	if len(tables) > 0 {
2845
		return fmt.Errorf("Database %s is not empty", m.Name())
2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
	}
	if err = m.engine.Sync2(new(setting), new(counter)); err != nil {
		return fmt.Errorf("create table setting, counter: %s", err)
	}
	if err = m.engine.Sync2(new(node), new(edge), new(symlink), new(xattr)); err != nil {
		return fmt.Errorf("create table node, edge, symlink, xattr: %s", err)
	}
	if err = m.engine.Sync2(new(chunk), new(chunkRef)); err != nil {
		return fmt.Errorf("create table chunk, chunk_ref: %s", err)
	}
	if err = m.engine.Sync2(new(session), new(sustained), new(delfile)); err != nil {
		return fmt.Errorf("create table session, sustaind, delfile: %s", err)
	}
	if err = m.engine.Sync2(new(flock), new(plock)); err != nil {
		return fmt.Errorf("create table flock, plock: %s", err)
	}

2863
	dec := json.NewDecoder(r)
2864
	dm := &DumpedMeta{}
2865
	if err = dec.Decode(dm); err != nil {
2866 2867 2868 2869 2870 2871 2872
		return err
	}
	format, err := json.MarshalIndent(dm.Setting, "", "")
	if err != nil {
		return err
	}

S
Sandy Xu 已提交
2873 2874
	var total int64 = 1 // root
	progress, bar := utils.NewDynProgressBar("CollectEntry progress: ", false)
2875
	dm.FSTree.Attr.Inode = 1
2876
	entries := make(map[Ino]*DumpedEntry)
2877 2878 2879 2880 2881
	if err = collectEntry(dm.FSTree, entries, func(totalIncr, currentIncr int64) {
		total += totalIncr
		bar.SetTotal(total, false)
		bar.IncrInt64(currentIncr)
	}); err != nil {
2882 2883
		return err
	}
S
Sandy Xu 已提交
2884 2885 2886 2887 2888
	if bar.Current() != total {
		logger.Warnf("Collected %d / total %d, some entries are not collected", bar.Current(), total)
	}
	bar.SetTotal(0, true)
	progress.Wait()
2889

2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
	counters := &DumpedCounters{
		NextInode:   2,
		NextChunk:   1,
		NextSession: 1,
	}
	refs := make(map[uint64]*chunkRef)
	for _, entry := range entries {
		if err = m.loadEntry(entry, counters, refs); err != nil {
			return err
		}
	}
	logger.Infof("Dumped counters: %+v", *dm.Counters)
	logger.Infof("Loaded counters: %+v", *counters)

	beans := make([]interface{}, 0, 4) // setting, counter, delfile, chunkRef
	beans = append(beans, &setting{"format", string(format)})
	cs := make([]*counter, 0, 6)
	cs = append(cs, &counter{"usedSpace", counters.UsedSpace})
	cs = append(cs, &counter{"totalInodes", counters.UsedInodes})
	cs = append(cs, &counter{"nextInode", counters.NextInode})
	cs = append(cs, &counter{"nextChunk", counters.NextChunk})
	cs = append(cs, &counter{"nextSession", counters.NextSession})
2912
	cs = append(cs, &counter{"nextCleanupSlices", 0})
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
	beans = append(beans, cs)
	if len(dm.DelFiles) > 0 {
		dels := make([]*delfile, 0, len(dm.DelFiles))
		for _, d := range dm.DelFiles {
			dels = append(dels, &delfile{d.Inode, d.Length, d.Expire})
		}
		beans = append(beans, dels)
	}
	if len(refs) > 0 {
		cks := make([]*chunkRef, 0, len(refs))
		for _, v := range refs {
			cks = append(cks, v)
		}
		beans = append(beans, cks)
	}
	s := m.engine.NewSession()
	defer s.Close()
	return mustInsert(s, beans...)
}