wcfs.go 16.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 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 453 454 455 456 457 458 459 460 461 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 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
// Copyright (C) 2018  Nexedi SA and Contributors.
//                     Kirill Smelkov <kirr@nexedi.com>
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
// See https://www.nexedi.com/licensing for rationale and options.

// Program wcfs provides filesystem server with file data backed by wendelin.core arrays.
//
// Intro
//
// Each wendelin.core array (ZBigArray) is actually a linear file (ZBigFile)
// and array metadata like dtype, shape and strides associated with it. This
// program exposes as files only ZBigFile data and leaves rest of
// array-specific handling to client. Every ZBigFile is exposed as one separate
// file that represents whole ZBigFile's data.
//
// For a client, the primary way to access a bigfile should be to mmap
// bigfile/<bigfileX>/head/data which represents always latest bigfile data.
// Clients that want to get isolation guarantee should subscribe for
// invalidations and re-mmap invalidated regions to file with pinned bigfile revision for
// the duration of their transaction. See "Invalidation protocol" for details.
//
// In the usual situation when bigfiles are big, and there are O(1)/δt updates,
// there should be no need for any cache besides shared kernel cache of latest
// bigfile data.
//
//
// Filesystem organization
//
// Top-level structure of provided filesystem is as follows:
//
//	bigfile/
//		<oid(bigfile1)>/
//			...
//		<oid(bigfile2)>/
//			...
//		...
//
// where for a bigfileX there is bigfile/<oid(bigfileX)>/ directory, with
// oid(bigfileX) being ZODB object-id of corresponding ZBigFile object formatted with %016x.
//
// Each bigfileX/ has the following structure:
//
//	bigfile/<bigfileX>/
//		head/		; latest bigfile revision
//			...
//		@<tid1>/	; bigfile revision as of transaction <tidX>
//			...
//		@<tid2>/
//			...
//		...
//
// where head/ represents latest bigfile as stored in upstream ZODB, and
// @<tidX>/ represents bigfile as of transaction <tidX>.
//
// head/ has the following structure:
//
//	bigfile/<bigfileX>/head/
//		data		; latest bigfile data
//		at		; data is bigfile view as of this ZODB transaction
//		invalidations	; channel that describes invalidated data regions
//
// where /data represents latest bigfile data as stored in upstream ZODB. As
// there can be some lag receiving updates from the database, /at describes
// precisely ZODB state for which bigfile data is currently exposed. Whenever
// bigfile data is changed in upstream ZODB, information about the changes is
// first propagated to /invalidations, and only after that /data is
// updated. See "Invalidation protocol" for details.
//
// @<tidX>/ has the following structure:
//
//	bigfile/<bigfileX>/@<tidX>/
//		data		; bigfile data as of transaction <tidX>
//
// where /data represents bigfile data as of transaction <tidX>.
//
// bigfile/<bigfileX>/ should be created by client via mkdir. Unless explicitly
// created bigfile/<bigfileX>/ are not automatically visible in wcfs
// filesystem. Similarly bigfile/<bigfileX>/@<tidX>/ should be too created by
// client.
//
//
// Invalidation protocol
//
// In order to support isolation wcfs implements invalidation protocol that
// must be cooperatively followed by both wcfs and client.
//
// First, before client wants to mmap bigfile, it opens
// bigfile/<bigfileX>/head/invalidations and tells wcfs through it for which
// ZODB state it wants to get bigfile view. The server in turn reports for
// which ZODB state head/data is current, δ describing changed bigfile region
// between those revisions, or "wait" flag if server state is earlier compared
// to what client wants:
//
//	C: want <Cat>
//	S: have <Sat>, wait		; Sat < Cat
//	S: have <Sat>, δR(Cat,Sat)	; Sat ≥ Cat
//
// If server reply was "wait" the client does nothing and waits for next server
// message which must come without "wait" flag set. When client receives have
// message with δR(Cat,Sat) it has the guarantee from wcfs that head/data
// content is for Sat ZODB revision and won't change until client sends ack
// back to the server. The client in turn now can mmap head/data and
// @<Cat>/data to get bigfile view as of Cat:
//
//	mmap(bigfile/<bigfileX>/head/data)
//	mmap(bigfile/<bigfileX>/@<Cat>/data, δR(Cat,Sat), MAP_FIXED)  # mmaped at addresses corresponding to δR(Cat,Sat)
//
// When client completes its initial mmapping it sends ack back to the server:
//
//	C: ack
//
// From now on the server will be processing updates to bigfile coming from
// ZODB as follows:
//
//
// The filesystem server itself receives information about changed data
// from ZODB server through regular ZODB invalidation channel (as it is ZODB
// client itself). Then, before actually updating bigfile/<bigfileX>/head/data
// content in changed part, it notifies through bigfile/<bigfileX>/head/invalidations
// to clients that had opened this file (separately to each client) about the changes:
//
//	S: have <Sat>, δR(Sat_prev, Sat)
//
// where Sat_prev is ZODB revision last reported to client for this bigfile,
// and waits until they all confirm that changed file part can be updated in
// global OS cache.
//
// The client in turn can now re-mmap invalidated regions to bigfile@Cat
//
//	# mmapped at addresses corresponding to δR(Sat_prev, Sat)
//	mmap(bigfile/<bigfileX>/@<Cat>/data, δR(Sat_prev, Sat), MAP_FIXED)
//
// and must send ack back to the server when it is done:
//
//	C: ack
//
// When clients are done with bigfile/<bigfileX>/@<Cat>/data (i.e. Cat
// transaction ends and array is unmapped), the server sees number of opened
// files to bigfile/<bigfileX>/@<Cat>/data drops to zero, and automatically
// destroys bigfile/<bigfileX>/@<Cat>/ directory after reasonable timeout.
//
//
// Protection against slow or faulty clients
//
// If a client, on purpose or due to a bug or being stopped, is slow to
// respond with ack to invalidation notification, it creates a problem because
// head/data updates will be blocked and thus all other clients that try to
// work with current data will get stuck.
//
// To avoid this problem it should be possible for wcfs to stop a client with
// ptrace and change its address space in a style similar to e.g.
// VirtualAllocEx on Windows. Here is hacky example how this could be done on Linux:
//
// https://gist.github.com/rofl0r/1073739/63f0f788a4923e26fcf743dd9a8411d4916f0ac0
//
// This way there should be no possibility for a client to block wcfs
// indefinitely waiting for client's ack.
//
// Similarly for initial mmapings client could first mmap head/data, then open
// head/invalidations and tell the server that it wants Cat revision, with
// the server then remmaping blocks to get to Cat state via ptrace.
//
// However for simplicity the plan is to go first without ptrace and just kill
// a slow client on, say 30 seconds, timeout.
//
//
// Writes
//
// As each bigfile is represented by 1 synthetic file, there can be several
// write schemes:
//
// 1. mmap(MAP_PRIVATE) + writeout by client
//
// In this scheme bigfile data is mmapped in MAP_PRIVATE mode, so that local
// user changes are not automatically propagated back to the file. When there
// is a need to commit, client investigates via some OS mechanism, e.g.
// /proc/self/pagemap or something similar, which pages of this mapping it
// modified. Knowing this it knows which data it dirtied and so can write this
// data back to ZODB itself, without filesystem server providing write support.
//
// 2. mmap(MAP_SHARED, PROT_READ) + write-tracking & writeout by client
//
// In this scheme bigfile data is mmaped in MAP_SHARED mode with read-only pages
// protection. Then whenever write fault occurs, client allocates RAM from
// shmfs, copies faulted page to it, and then mmaps RAM page with RW protection
// in place of original bigfile page. Writeout implementation should be similar
// to "1", only here client already knows the pages it dirtied, and this way
// there is no need to consult /proc/self/pagemap.
//
// The advantage of this scheme over mmap(MAP_PRIVATE) is that in case
// there are several in-process mappings of the same bigfile with overlapping
// in-file ranges, changes in one mapping will be visible in another mapping.
// Contrary: whenever a MAP_PRIVATE mapping is modified, the kernel COWs
// faulted page into a page completely private to this mapping, so that other
// MAP_PRIVATE mappings of this file, including ones created from the same
// process, do not see changes made to the first mapping.
//
// Since wendelin.core needs to provide coherency in between different slices
// of the same array, this is the mode wendelin.core actually uses.
//
// 3. write to wcfs
//
// XXX we later could implement "write-directly" mode where clients would write
// data directly into the file.
package main


// Notes on OS pagecache control:
//
// the cache of snapshotted bigfile can be pre-made hot, if invalidated region
// was already in pagecache of head/data:
//
// - we can retrieve a region from pagecache of head/data with FUSE_NOTIFY_RETRIEVE.
// - we can store that retrieved data into pagecache region of @<tidX>/ with FUSE_NOTIFY_STORE.
// - we can invalidate a region from pagecache of head/data with FUSE_NOTIFY_INVAL_INODE.
//
// we have to disable FUSE_AUTO_INVAL_DATA to tell the kernel we are fully
// responsible for invalidating pagecache. If we don't, the kernel will be
// clearing whole cache of head/data on e.g. its mtime change.
//
// XXX FUSE_AUTO_INVAL_DATA does not fully prevent kernel from automatically
// invalidating pagecache - e.g. it will invalidate whole cache on file size changes:
//
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/fuse/inode.c?id=e0bc833d10#n233
//
// we can currently workaround it with using writeback mode (see !is_wb in the
// link above), but better we have proper FUSE flag for filesystem server to
// tell the kernel it is fully responsible for invalidating pagecache.

// TODO implementation organization.
// - 1 ZODB connection per 1 bigfile (each bigfile can be at its different @at,
//   because invalidations for different bigfiles can be processed with different
//   timings depending on clients). No harm here as different bigfiles use
//   completely different ZODB BTree and data objects.

import (
	"context"
	"flag"
	"log"
	"os"
	"sync"
	"syscall"

	"lab.nexedi.com/kirr/neo/go/zodb"
	"lab.nexedi.com/kirr/neo/go/zodb/btree"
	_ "lab.nexedi.com/kirr/neo/go/zodb/wks"

	"github.com/hanwen/go-fuse/fuse"
	"github.com/hanwen/go-fuse/fuse/nodefs"
	//"github.com/pkg/errors"

	//pickle "github.com/kisielk/og-rek"	// XXX should be temp here?
)

// BigFileRoot represents "/bigfile"
type BigFileRoot struct {
	nodefs.Node
	zstor zodb.IStorage

	mu  sync.Mutex
	tab map[zodb.Oid]*BigFileX
}

// BigFileX represents "/bigfile/<bigfileX>"
// XXX -> BigFileDir ?
type BigFileX struct {
	nodefs.Node
	oid  zodb.Oid
	root *BigFileRoot
}

// BigFileHead represents "/bigfile/<bigfileX>/head"
type BigFileHead struct {
	nodefs.Node
	x *BigFileX

	data *BigFile
	//at   *BigFileAt
	//inv  *BigFileInvalidations
}

// BigFile represents "/bigfile/<bigfileX>/head/data"
// XXX also @<tidX>/data ?
// XXX -> BigFileData ?
type BigFile struct {
	nodefs.Node
	parent *BigFileHead	// XXX name

	topoid	zodb.Oid	// oid of ZBigFile
	blksize int64		// ZBigFile.blksize	XXX if it is changed - invalidate all? allowed to change?

	head		zodb.Tid // current view of ZODB
	lastChange	zodb.Tid // last change to whole bigfile as of .head view
}



// ---- ctors ----	XXX to down?

func NewBigFileRoot(zstor zodb.IStorage) *BigFileRoot {
	return &BigFileRoot{
		Node:  nodefs.NewDefaultNode(),
		zstor: zstor,
		tab:   make(map[zodb.Oid]*BigFileX),
	}
}

func NewBigFileX(oid zodb.Oid, root *BigFileRoot) *BigFileX {
	bx := &BigFileX{
		Node: nodefs.NewDefaultNode(),
		oid:  oid,
		root: root,
	}

	return bx
}



func NewBigFileHead(x *BigFileX) *BigFileHead {
	f := &BigFileHead{Node: nodefs.NewDefaultNode(), x: x}
	f.data = NewBigFile(f)

	// XXX + .at

	return f
}


func NewBigFile(head *BigFileHead) *BigFile {
	return &BigFile{Node: nodefs.NewDefaultNode(), parent: head}
}





// Mkdir receives client request to create /bigfile/<bigfileX>.
func (br *BigFileRoot) Mkdir(name string, mode uint32, fctx *fuse.Context) (*nodefs.Inode, fuse.Status) {
	oid, err := zodb.ParseOid(name)
	if err != nil {
		log.Printf("/bigfile: mkdir %q: not-oid", name)
		return nil, fuse.EINVAL
	}

	// XXX ok to ignore mode?

	br.mu.Lock()

	if _, already := br.tab[oid]; already {
		return nil, fuse.Status(syscall.EEXIST)
	}

	br.mu.Unlock()

	ctx := asctx(fctx)
	_ = ctx
	return nil, fuse.ENOSYS	// XXX temp

	// xbf, err := zconn.Get(ctx, oid)
	// check err
	// check if xbf.(*ZBigFile)
/* XXX kill
	buf, _, err := br.zstor.Load(ctx, zodb.Xid{Oid: oid, At: zodb.TidMax})	// FIXME At, use serial
	if err != nil {
		switch errors.Cause(err).(type) {
		case *zodb.NoObjectError:
			return nil, fuse.EINVAL
		case *zodb.NoDataError:
			return nil, fuse.EINVAL // XXX ok?
		default:
			log.Printf("/bigfile: mkdir %q: %s", name, err)
			return nil, fuse.EIO
		}
	}

	pybf, err := zodb.PyData(buf.Data).Decode()
	if err != nil {
		log.Printf("/bigfile: mkdir %q: %s", name, err)
		return nil, fuse.EIO
	}
*/

/* XXX reenable (.zpy not yet here)
	pybf, err := br.zpy.Load(ctx, zodb.Xid{Oid: oid, At: zodb.TidMax})	// FIXME At, use serial
	if err != nil {
		switch errors.Cause(err).(type) {
		case *zodb.NoObjectError:
			// XXX log?
			return nil, fuse.EINVAL
		case *zodb.NoDataError:
			// XXX log?
			return nil, fuse.EINVAL // XXX ok?
		default:
			log.Printf("/bigfile: mkdir %q: %s", name, err)
			return nil, fuse.EIO
		}
	}

	// XXX -> pyclass.FullName() != "wendelin.bigfile.file_zodb" + ".ZBigFile"
	pybfClass := pickle.Class{Module: "wendelin.bigfile.file_zodb", Name: ".ZBigFile"}
	if pybf.PyClass() != pybfClass {
		// XXX log?
		return nil, fuse.EINVAL
	}

	// XXX other checks?


	br.mu.Lock()
	defer br.mu.Unlock()

	// XXX recheck - maybe it was already created while we were not holding br.mu

	bx := NewBigFileX(oid, br)
	br.tab[oid] = bx

	bh := NewBigFileHead(bx)

	mkdir(br, name, bx) // XXX takes treeLock - ok under br.mu ?
	mkdir(bx, "head", bh)
	mkfile(bh, "data", bh.data)
	// XXX mkfile(bh, "at", bh.at)
	// XXX mkfile(bh, "invalidations", bh.inv)

	return bx.Inode(), fuse.OK
*/
}

// XXX do we need to support rmdir? (probably no)


// module: "wendelin.bigfile.file_zodb"
//
// ZBigFile
//	.blksize	xint
//	.blktab		LOBtree{}  blk -> ZBlk*(blkdata)
//
// ZBlk0 (aliased as ZBlk)
//	str with trailing '\0' removed.
//
// ZBlk1
//	.chunktab	IOBtree{}  offset -> ZData(chunk)
//
// ZData
//	str (chunk)


// Read implements reading from /bigfile/<bigfileX>/head/data.
// XXX and from /bigfile/<bigfileX>/@<tidX>/data.
/*
func (bf *BigFile) Read(_ nodefs.File, dest []byte, off int64, _ fuse.Context) (fuse.ReadResult, fuse.Status) {
	.at
	.topoid
	// XXX
}
*/


// zodbCacheControl implements LiveCacheControl to tune ZODB to never evict
// LOBTree/LOBucket from live cache. We want to keep LOBTree/LOBucket always alive
// becuse it is essentially the index where to find ZBigFile data.
//
// For the data itself - we put it to kernel cache and always deactivate from
// ZODB right after that.
//
// TODO set it to Connection.CacheControl
type zodbCacheControl struct {}

func (cc *zodbCacheControl) WantEvict(obj zodb.IPersistent) bool {
	switch obj.(type) {
	default:
		return true

	case *btree.LOBTree:
	case *btree.LOBucket:
	}

	return false
}

// XXX option to prevent starting if wcfs was already started ?

func main() {
	log.SetPrefix("wcfs: ")

	debug := flag.Bool("d", false, "debug")
	autoexit := flag.Bool("autoexit", false, "automatically stop service when there is no client activity")
	flag.Parse()
	if len(flag.Args()) != 2 {
		log.Fatalf("Usage: %s [OPTIONS] zurl mntpt", os.Args[0])
	}
	zurl := flag.Args()[0]
	mntpt := flag.Args()[1]

	// open zodb storage
	ctx := context.Background()	// XXX + timeout?
	zstor, err := zodb.OpenStorage(ctx, zurl, &zodb.OpenOptions{ReadOnly: true})
	if err != nil {
		log.Fatal(err)
	}
	defer zstor.Close()


	// mount root
	opts := nodefs.NewOptions()
	opts.Debug = *debug

	root := nodefs.NewDefaultNode()

	server, _, err := nodefs.MountRoot(mntpt, root, opts)
	if err != nil {
		log.Fatal(err)
	}

	// add entries to /
	mkfile(root, ".wcfs", NewStaticFile([]byte(zurl)))
	mkdir(root, "bigfile", NewBigFileRoot(zstor))

	// TODO handle autoexit
	_ = autoexit

	// serve client requests
	server.Serve()	// XXX Serve returns no error
}