__init__.py 25 KB
Newer Older
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
1
# -*- coding: utf-8 -*-
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
2 3
# Copyright (C) 2018-2019  Nexedi SA and Contributors.
#                          Kirill Smelkov <kirr@nexedi.com>
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#
# 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.

"""Module wcfs.py provides python gateway for spawning and interoperating with wcfs server

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
23
Join(zurl) joins wcfs server. If wcfs server for zurl is not yet running, it
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
24
will be automatically started if `autostart=True` parameter is passed to join.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
25 26 27
It will also be automatically started by default unless
$WENDELIN_CORE_WCFS_AUTOSTART=no is specified in environment.

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
28
WCFS represents connection to wcfs server obtained by join.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
29
FileH ... XXX
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
30
XXX
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
31 32 33

$WENDELIN_CORE_WCFS_AUTOSTART
$WENDELIN_CORE_WCFS_OPTIONS
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
34 35
"""

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
36
import os, sys, hashlib, tempfile, subprocess, time, re
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
37 38
import logging as log
from os.path import dirname
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
39
from errno import ENOENT, EEXIST
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
40

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
41
from golang import chan, select, default, func, defer
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
42
from golang import sync, context
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
43
from golang.gcompat import qq
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
44
import threading
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
45

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
46
from persistent import Persistent
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
47
from ZODB.FileStorage import FileStorage
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
48
from ZODB.utils import z64, u64, p64
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
49
from zodbtools.util import ashex, fromhex
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
50

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
51 52
from .internal import mm

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
53 54
from six import reraise

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
55

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
56
# WCFS represents filesystem-level connection to wcfs server.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
57
#
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
58
# Use join to create it.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
59 60 61
#
# The primary way to access wcfs is to open logical connection viewing on-wcfs
# data as of particular database state, and use that logical connection to
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
62
# create base-layer mappings. See .connect and Conn for details.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
63 64
#
# Raw files on wcfs can be accessed with ._path/._read/._stat/._open .
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
65
#
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
66
# WCFS logically mirrors ZODB.DB .
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
67
class WCFS(object):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
68
    # .mountpoint   path to wcfs mountpoint
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
69
    # ._fwcfs       /.wcfs/zurl opened to keep the server from going away (at least cleanly)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
70
    # ._njoin       this connection was returned for so many joins
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
71

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
72
    # XXX for-testing only?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
73
    # ._proc        wcfs process if it was opened by this WCFS | None
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
74
    pass
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
75

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
76
# Conn represents logical connection viewing data on wcfs filesystem as of
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
77 78 79 80 81 82
# particular database state.
#
# It uses /head/bigfile/* and notifications received from /head/watch to
# maintain isolated database view while at the same time sharing most of data
# cache in OS pagecache of /head/bigfile/*.
#
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
83 84 85
# Use .mmap to create new Mappings.
#
# Conn logically mirrors ZODB.Connection .
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
86
class Conn(object):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
87 88 89 90 91 92
    # ._wc          WCFS
    # .at           Tid
    # ._wlink       WatchLink watch/receive pins for created mappings

    # ._filemu      threading.Lock
    # ._filetab     {} foid -> _File
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
93
    pass
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
94 95 96

# _File represent isolated file view under Conn.
class _File(object):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
97 98
    # .wconn    Conn
    # .foid     hex of ZBigFile root object ID
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
99
    # .blksize  block size of this file
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
100
    # .headf    file object of head/file
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
101
    # .pinned   {} blk -> rev   that wcfs already sent us for this file
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
102
    # .mmaps    []_Mapping ↑blk_start    mappings of this file
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
103 104 105
    pass


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
106 107
# _Mapping represents one mapping of _File.
class _Mapping(object):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
108
    # .file         _File
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
109
    # .blk_start    offset of this mapping in file
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
110
    # .mem          mmaped memory
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
111 112 113 114 115
    pass

    # XXX property .blk_stop = blk_start + len(mem) // blksize      & assert len(mem) % blksize == 0


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
116 117 118
# connect creates new Conn viewing WCFS state as of @at.
@func(WCFS)
def connect(wc, at): # -> Conn
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
119 120 121 122 123 124 125 126 127 128 129 130
    wconn = Conn()

    # XXX support !isolated mode
    wconn._wc       = wc
    wconn.at        = at
    wconn._wlink    = WatchLink(wc)
    wconn._filemu   = threading.Lock()
    wconn._filetab  = {}

    # XXX wg.go(wconn._pinner, xxxctx)

    return wconn
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
131

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
132 133 134 135 136 137 138 139
# close releases resources associated with wconn.
# XXX what happens to file mmappings?
@func(Conn)
def close(wconn):
    # XXX stop/join pinner
    wconn._wlink.close()


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
# _pinner receives pin messages from wcfs and adjusts wconn mappings.
@func(Conn)
def _pinner(wconn, ctx):
    while 1:
        req = wconn._wlink.recvReq(ctx)
        if req is None:
            return  # XXX ok? (EOF - when wcfs closes wlink)

        # we received request to pin/unpin file block. perform it
        with wconn._filemu:
            f = wconn._filetab.get(req.foid)
            if f is None:
                1/0     # XXX we are not watching the file - why wcfs sent us this update?


            # XXX relock wconn -> f ?

            for mmap in f.mmaps:    # XXX use ↑blk_start for binary search
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
158
                if not (mmap.blk_start <= req.blk < mmap.blk_stop):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
159
                    continue    # blk ∉ mmap
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
160

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
161
                # FIXME check if virtmem did not mapped RW page into this block already
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
162
                mmap._remmapblk(req.blk, req.at)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
163

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
164
            # update f.pinned
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
165
            if req.at is None:
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
166
                f.pinned.pop(req.blk, None)     # = delete(f.pinned, req.blk)  -- unpin to @head
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
167
            else:
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
168 169 170
                f.pinned[req.blk] = req.at


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
171
# mmap creates file mapping representing file data as of wconn.at database state.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
172
@func(Conn)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
173
def mmap(wconn, foid, blk, blklen): # -> Mapping
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
174 175 176
    with wconn._filemu:
        f = wconn._filetab.get(foid)
        if f is None:
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
177 178 179 180
            f = _File()
            f.wconn     = wconn
            f.foid      = foid
            f.headf     = wconn._wc._open("head/bigfile/%s" % (ashex(foid),), "rb")
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
181
            f.blksize   = os.fstat(f.headf.fileno()).st_blksize
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
182 183
            f.pinned    = {}
            f.mmaps     = []
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
184 185 186 187 188
            wconn._filetab[foid] = f

        # XXX relock wconn -> f ?

        # create memory with head/f mapping and applied pins
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
189
        mem = mm.map_ro(f.headf.fileno(), blk*f.blksize, blklen*f.blksize)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
190
        mmap = _Mapping(f, blk_start, mem)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
191
        for blk, rev in f.pinned.items():  # XXX keep f.pinned ↑blk and use binary search?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
192
            if not (blk_start <= blk < blk_stop):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
193
                continue    # blk out of this mapping
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
194
            mmap._remmapblk(blk, rev)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
195

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
196 197
        f.mmaps.append(mmap)    # XXX keep f.mmaps ↑blk_start

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
198 199
    return mmap

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
200 201 202 203 204 205 206 207 208 209 210 211 212

# _remmapblk remmaps mapping memory for file[blk] to be viewing database as of @at state.
#
# at=None means unpin to head/ .
# NOTE this does not check wrt virtmem already mapped blk as RW     XXX ok?
@func(_Mapping)
def _remmapblk(mmap, blk, at):
    assert mmap.blk_start <= blk < mmap.blk_stop
    f = mmap.file
    if at is None:
        fsfile = f.headf
    else:
        # TODO share @rev fd until wconn is resynced?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
213
        fsfile = f.wconn._wc._open("@%s/bigfile/%s" % (ashex(at), ashex(f.foid)), "rb")
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
214
        defer(fsfile.close)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
215
        assert os.fstat(fsfile.fileno()).st_blksize == f.blksize  # FIXME assert
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
216

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
217
    mm.map_into_ro(mmap.mem[(blk-mmap.blk_start)*blksize:][:blksize], fsfile.fileno(), blk*blksize)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
218 219 220


# remmap_blk remmaps file[blk] in its place again.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
221 222 223 224 225 226
# virtmem calls this to remmap a block after RW dirty page was e.g. discarded.
@func(_Mapping)
def remmap_blk(mmap, blk):
    # XXX locking
    assert (mmap.blk_start <= blk < mmap.blk_stop)
    blkrev = mmap.pinned.get(blk, None) # rev | @head
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
227
    mmap._remmapblk(blk, blkrev)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
228

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
229

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
230 231
# unmap is removes mapping memory from address space.
# virtmem calls this when VMA is unmapped.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
232
@func(_Mapping)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
233 234 235 236
def unmap(mmap):
    # XXX locking
    mm.unmap(mmap.mem)
    mmap.mem = None
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
237

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
238 239
    mmap.file.mmaps.remove(mmap)

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
240 241 242 243

# WatchLink represents /head/watch link opened on wcfs.
#
# .sendReq()/.recvReq() provides raw IO in terms of wcfs invalidation protocol messages.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
244 245
#
# XXX safe/not-safe to access from multiple threads?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
246
class WatchLink(object):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
247 248 249 250 251 252 253 254 255 256 257 258

    def __init__(wlink, wc):
        wlink._wc = wc

        # head/watch handle.
        #
        # python/stdio lock file object on read/write, however we need both
        # read and write to be working simultaneously.
        # -> use 2 separate file objects for rx and tx.
        #
        # fdopen takes ownership of file descriptor and closes it when file
        # object is closed -> dup fd so that each file object has its own fd.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
259
        wh  = os.open(wc._path("head/watch"), os.O_RDWR)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
260
        wh2 = os.dup(wh)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
261 262
        wlink._wrx = os.fdopen(wh, 'rb')
        wlink._wtx = os.fdopen(wh2, 'wb')
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
263

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
264 265 266
        # XXX vvv -> test only?
        wlink.rx_eof = chan()   # becomes ready when wcfs closes its tx side
        wlink.fatalv = []       # fatal messages received from wcfs
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
267

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281
        # inv.protocol message IO
        wlink._acceptq  = chan() # (stream, msg)    server originated messages go here
        wlink._rxmu     = threading.Lock()
        wlink._rxtab    = {}     # stream -> rxq    server replies go via here
        wlink._accepted = set()  # of stream        streams we accepted but did not replied yet

        wlink._txmu     = threading.Lock()  # serializes writes
        wlink._txclosed = False

        serveCtx, wlink._serveCancel = context.with_cancel(context.background())
        wlink._serveWG = sync.WorkGroup(serveCtx)
        wlink._serveWG.go(wlink._serveRX)

        # this tWatchLink currently watches the following files at particular state.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
282
        # XXX back -> tWatchLink ?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
283
        wlink._watching = {}    # {} foid -> tWatch
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
284

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

    def _closeTX(wlink):
        if wlink._txclosed:
            return

        # ask wcfs to close its tx & rx sides; close(wcfs.tx) wakes up
        # _serveRX on client (= on us). The connection can be already closed by
        # wcfs - so ignore errors when sending bye.
        try:
            wlink._send(1, b'bye')
        except IOError:
            pass
        wlink._wtx.close()
        wlink._txclosed = True

    def close(wlink):
        wlink._closeTX()
        wlink._serveCancel()
        # XXX we can get stuck here if wcfs does not behave as we want.
        # XXX in particular if there is a silly - e.g. syntax or type error in
        #     test code - we currently get stuck here.
        #
        # XXX -> better pthread_kill(SIGINT) instead of relying on wcfs proper behaviour?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
308
        # XXX -> we now have `kill -QUIT` to wcfs.go on test timeout - remove ^^^ comments?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322
        try:
            wlink._serveWG.wait()
        except Exception as e:
            # canceled is expected and ok
            if e != context.canceled:
                reraise(e, None, e.__traceback__)

        wlink._wrx.close()

        # disable all established watches
        for w in wlink._watching.values():
            w.at     = z64
            w.pinned = {}
        wlink._watching = {}
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
323

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
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
    # _serveRX receives messages from ._wrx and dispatches them according to streamID.
    @func
    def _serveRX(wlink, ctx):
        # when finishing - wakeup everyone waiting for rx
        def _():
            wlink._acceptq.close()
            with wlink._rxmu:
                rxtab = wlink._rxtab
                wlink._rxtab = None     # don't allow new rxtab registers
            for rxq in rxtab.values():
                rxq.close()
        defer(_)

        while 1:
            # NOTE: .close() makes sure ._wrx.read*() will wake up
            l = wlink._wrx.readline()
            print('C: watch  : rx: %r' % l)
            if len(l) == 0:     # peer closed its tx
                wlink.rx_eof.close()
                break

            # <stream> ... \n
            stream, msg = l.split(' ', 1)
            stream = int(stream)
            msg = msg.rstrip('\n')

            if stream == 0: # control/fatal message from wcfs
                # XXX print -> receive somewhere?
                print('C: watch  : rx fatal: %r' % msg)
                wlink.fatalv.append(msg)
                continue

            reply = bool(stream % 2)
            if reply:
                with wlink._rxmu:
                    assert stream in wlink._rxtab           # XXX !test assert - recheck
                    rxq = wlink._rxtab.pop(stream)
                _, _rx = select(
                    ctx.done().recv,    # 0
                    (rxq.send, msg),    # 1
                )
                if _ == 0:
                    raise ctx.err()
            else:
                with wlink._rxmu:
                    assert stream not in wlink._accepted    # XXX !test assert - recheck
                    wlink._accepted.add(stream)
                _, _rx = select(
                    ctx.done().recv,                        # 0
                    (wlink._acceptq.send, (stream, msg)),   # 1
                )
                if _ == 0:
                    raise ctx.err()

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    # _send sends raw message via specified stream.
    #
    # multiple _send can be called in parallel - _send serializes writes.
    # XXX +ctx?
    def _send(wlink, stream, msg):
        assert '\n' not in msg
        pkt = b"%d %s\n" % (stream, msg)
        wlink._write(pkt)

    def _write(wlink, pkt):
        with wlink._txmu:
            #print('C: watch  : tx: %r' % pkt)
            wlink._wtx.write(pkt)
            wlink._wtx.flush()

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
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
    # sendReq sends client -> server request and returns server reply.
    #
    # only 1 sendReq must be used at a time.    # XXX relax?
    def sendReq(wlink, ctx, req): # -> reply | None when EOF
        rxq = wlink._sendReq(ctx, req)

        _, _rx = select(
            ctx.done().recv,    # 0
            rxq.recv,           # 1
        )
        if _ == 0:
            raise ctx.err()
        return _rx

    def _sendReq(wlink, ctx, req): # -> rxq
        stream = 1  # XXX -> dynamic

        rxq = chan()
        with wlink._rxmu:
            assert stream not in wlink._rxtab   # XXX !test assert - recheck
            wlink._rxtab[stream] = rxq

        wlink._send(stream, req)
        return rxq

    # recvReq receives client <- server request.
    #
    # multiple recvReq could be used at a time.
    def recvReq(wlink, ctx): # -> SrvReq | None when EOF
        _, _rx = select(
            ctx.done().recv,        # 0
            wlink._acceptq.recv,    # 1
        )
        if _ == 0:
            raise ctx.err()

        rx = _rx
        if rx is None:
            return rx

        stream, msg = rx
        return SrvReq(wlink, stream, msg)

# SrvReq represents 1 server-initiated wcfs request received over /head/watch link.
# XXX struct place -> ^^^ (nearby WatchLink) ?
class SrvReq(object):
    def __init__(req, wlink, stream, msg):
        req.wlink  = wlink
        req.stream = stream
        req.msg    = msg

    def reply(req, answer):
        #print('C: reply %s <- %r ...' % (req, answer))
        wlink = req.wlink
        with wlink._rxmu:
            assert req.stream in wlink._accepted

        wlink._send(req.stream, answer)

        with wlink._rxmu:
            assert req.stream in wlink._accepted
            wlink._accepted.remove(req.stream)

        # XXX also track as answered? (and don't accept with the same ID ?)

    def _parse(req): # -> (foid, blk, at|None)
        # pin <foid> #<blk> @(<at>|head)
        m = re.match(b"pin (?P<foid>[0-9a-f]{16}) #(?P<blk>[0-9]+) @(?P<at>[^ ]+)$", req.msg)
        if m is None:
            raise RuntimeError("message is not valid pin request: %s" % qq(req.msg))
        foid = fromhex(m.group('foid'))
        blk  = int(m.group('blk'))
        at   = m.group('at')
        if at == "head":
            at = None
        else:
            at = fromhex(at)

        return foid, blk, at

    @property
    def foid(req):    return req._parse()[0]
    @property
    def blk(req):     return req._parse()[1]
    @property
    def at(req):      return req._parse()[2]


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
481

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
482 483 484 485 486 487 488 489 490 491 492 493

# ---- WCFS raw file access ----

# _path returns path for object on wcfs.
# - str:        wcfs root + obj;
# - Persistent: wcfs root + (head|@<at>)/bigfile/obj
@func(WCFS)
def _path(wc, obj, at=None):
    if isinstance(obj, Persistent):
        #assert type(obj) is ZBigFile   XXX import cycle
        objtypestr = type(obj).__module__ + "." + type(obj).__name__
        assert objtypestr == "wendelin.bigfile.file_zodb.ZBigFile", objtypestr
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
494 495
        head = "head/" if at is None else ("@%s/" % ashex(at))
        obj  = "%s/bigfile/%s" % (head, ashex(obj._p_oid))
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
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
        at   = None
    assert isinstance(obj, str)
    assert at is None  # must not be used with str
    return os.path.join(wc.mountpoint, obj)

# _read reads file corresponding to obj on wcfs.
@func(WCFS)
def _read(wc, obj, at=None):
    path = wc._path(obj, at=at)
    with open(path, 'rb') as f:     # XXX -> readfile
        return f.read()

# _stat stats file corresponding to obj on wcfs.
@func(WCFS)
def _stat(wc, obj, at=None):
    path = wc._path(obj, at=at)
    return os.stat(path)

# _open opens file corresponding to obj on wcfs.
@func(WCFS)
def _open(wc, obj, mode='rb', at=None):
    path = wc._path(obj, at=at)
    return open(path, mode, 0)  # unbuffered


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
521
"""
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
522 523 524 525 526 527 528 529 530 531 532 533
    # open creates wcfs file handle, which can be mmaped to give data of ZBigFile.
    #
    # XXX more text
    #
    # All mmapings of one FileH share changes.
    # There can be several different FileH for the same (at, oid), and those
    # FileH do not share changes.
    def open(self, zfile):    # -> FileH
        #assert isinstance(zfile, ZBigFile)     # XXX import cycle

        zconn = zfile._p_jar
        # XXX ._start is probably ZODB5 only -> check ZODB4 and ZODB3
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
534
        zat   = p64(u64(zconn._storage._start)-1)    # before -> at
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
535 536
        # XXX pinned to @revX/... for now   -> TODO /head/bigfile/...

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
537 538
        path = '%s/@%s/bigfile/%s' % (self.mountpoint, ashex(zat), ashex(zfile._p_oid))
        fd = os.open(path, os.O_RDONLY)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
539 540 541 542 543 544 545 546 547 548
        return FileH(fd)


# FileH is handle to opened bigfile/X.
#
# XXX it mimics BigFileH and should be integrated into virtmem (see fileh_open_overlay)
#
# XXX it should implement wcfs invalidation protocol and remmap head/... parts
# to pinned as requested.
import mmap
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
549 550
from bigarray import pagesize           # XXX hack
from bigarray.array_ram import _VMA     # XXX hack
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
551 552 553 554
class FileH(object):
    # .fd

    def __init__(self, fd):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
555
        self.fd = fd
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
556 557 558 559 560 561

    def __del__(self):
        os.close(self.fd)

    def mmap(self, pgoffset, pglen):
        return _VMA(self.fd, pgoffset, pglen, pagesize, mmap.PROT_READ)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
562
"""
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
563 564 565 566 567 568





# ---- join/run wcfs ----
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
569

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
570 571 572 573 574 575 576 577 578 579
_wcmu = threading.Lock()
_wcregistry = {} # mntpt -> WCFS

@func(WCFS)
def __init__(wc, mountpoint, fwcfs, proc):
    wc.mountpoint = mountpoint
    wc._fwcfs     = fwcfs
    wc._njoin     = 1
    wc._proc      = proc

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
580
# close must be called to release joined connection after it is no longer needed.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
581 582 583 584 585 586 587 588
@func(WCFS)
def close(wc):
    with _wcmu:
        wc._njoin -= 1
        if wc._njoin == 0:
            # XXX unmount wcfs as well?
            wc._fwcfs.close()
            del _wcregistry[wc.mountpoint]
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
589

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
590 591 592 593 594 595 596 597 598 599 600
# _default_autostart returns default autostart setting for join.
#
# Out-of-the-box we want wcfs to be automatically started, to ease developer
# experience when wendelin.core is standalone installed. However in environments
# like SlapOS, it is more preferable to start and monitor wcfs service explicitly.
# SlapOS & co. should thus set $WENDELIN_CORE_WCFS_AUTOSTART=no.
def _default_autostart():
    autostart = os.environ.get("WENDELIN_CORE_WCFS_AUTOSTART", "yes")
    autostart = autostart.lower()
    return {"yes": True, "no": False}[autostart]

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
601 602
# join connects to wcfs server for ZODB @ zurl.
#
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
603
# If wcfs for that zurl was already started, join connects to it.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
604
# Otherwise it starts wcfs for zurl if autostart is True.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
605 606 607
#
# For the same zurl join returns the WCFS object.
def join(zurl, autostart=_default_autostart()): # -> WCFS
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
608
    mntpt = _mntpt_4zurl(zurl)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    with _wcmu:
        # check if we already have connection to wcfs server from this process
        wc = _wcregistry.get(mntpt)
        if wc is not None:
            wc._njoin += 1
            return wc

        # no. try opening .wcfs - if we succeed - wcfs is already mounted.
        try:
            f = open(mntpt + "/.wcfs/zurl")
        except IOError as e:
            if e.errno != ENOENT:
                raise
        else:
            # already have it
            wc = WCFS(mntpt, f, None)
            _wcregistry[mntpt] = wc
            return wc

        if not autostart:
            raise RuntimeError("wcfs: join %s: server not started" % zurl)

        # start wcfs with telling it to automatically exit when there is no client activity.
        optv_extra = os.environ.get("WENDELIN_CORE_WCFS_OPTIONS", "").split()
        return _start(zurl, "-autoexit", *optv_extra)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
634

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
635

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
636 637
# _start starts wcfs server for ZODB @ zurl.
#
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
638
# optv can be optionally given to pass flags to wcfs.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
639
# called under _wcmu
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
640
def _start(zurl, *optv):    # -> WCFS
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
641
    mntpt = _mntpt_4zurl(zurl)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
642 643
    log.info("wcfs: starting for %s ...", zurl)

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
644 645 646
    # XXX errctx "wcfs: start"

    # spawn wcfs and wait till filesystem-level access to it is ready
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
647
    wc = WCFS(mntpt, None, None)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
648 649 650 651 652 653 654 655 656
    wg = sync.WorkGroup(context.background())
    fsready = chan()
    def _(ctx):
        # XXX errctx "spawn"
        argv = [_wcfs_exe()] + list(optv) + [zurl, mntpt]
        proc = subprocess.Popen(argv, close_fds=True)
        while 1:
            ret = proc.poll()
            if ret is not None:
657
                raise RuntimeError("exited with %s" % ret)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
658 659 660 661 662 663 664 665 666 667 668

            _, _rx = select(
                ctx.done().recv,    # 0
                fsready.recv,       # 1
                default,            # 2
            )
            if _ == 0:
                proc.terminate()
                raise ctx.err()
            if _ == 1:
                # startup was ok - don't monitor spawned wcfs any longer
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
669
                wc._proc = proc
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
                return

            time.sleep(0.1)
    wg.go(_)

    def _(ctx):
        # XXX errctx "waitmount"
        while 1:
            try:
                f = open("%s/.wcfs/zurl" % mntpt)
            except IOError as e:
                if e.errno != ENOENT:
                    raise
            else:
                dotwcfs = f.read()
                if dotwcfs != zurl:
                    raise RuntimeError(".wcfs/zurl != zurl  (%s != %s)" % (qq(dotwcfs), qq(zurl)))

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
688
                wc._fwcfs = f
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702
                fsready.close()
                return

            _, _rx = select(
                ctx.done().recv,    # 0
                default,            # 1
            )
            if _ == 0:
                raise ctx.err()

            time.sleep(0.1)
    wg.go(_)

    wg.wait()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
703 704 705

    assert mntpt not in _wcregistry
    _wcregistry[mntpt] = wc
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
706
    return wc
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
707 708


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
709 710
# ---- misc ----

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
711 712 713 714 715
# _wcfs_exe returns path to wcfs executable.
def _wcfs_exe():
    return '%s/wcfs' % dirname(__file__)

# _mntpt_4zurl returns wcfs should-be mountpoint for ZODB @ zurl.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
716 717
#
# it also makes sure the mountpoint exists.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
718
def _mntpt_4zurl(zurl):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
719
    # XXX what if zurl is zconfig://... ? -> then we have to look inside?
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
720
    #     -> zstor_2zurl extracts zurl in canonical form and zconfig:// is not possible there.
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
721 722
    m = hashlib.sha1()
    m.update(zurl)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
723 724 725 726
    mntpt = "%s/wcfs/%s" % (tempfile.gettempdir(), m.hexdigest())
    _mkdir_p(mntpt)
    return mntpt

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
727

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
728 729 730
# zstor_2zurl converts a ZODB storage to URL to access it.
# XXX -> unexport?
def zstor_2zurl(zstor):
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
731 732 733 734 735
    # There is, sadly, no unified way to do it, as even if storages are created via
    # zodburi, after creation its uri is lost. And storages could be created not
    # only through URI but e.g. via ZConfig and manually. We want to support all
    # those cases...
    #
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
736
    # For this reason extract URL with important for wcfs use-case parameters in
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
737 738 739 740 741
    # ad-hoc way.
    if isinstance(zstor, FileStorage):
        return "file://%s" % (zstor._file_name,)

    # TODO ZEO + NEO support
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
742
    raise NotImplementedError("don't know how to extract zurl from %r" % zstor)
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
743 744


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
745 746 747 748 749 750 751 752 753
# mkdir -p.
def _mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno != EEXIST:
            raise


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
# serve starts and runs wcfs server for ZODB @ zurl.
#
# it mounts wcfs at a location that is with 1-1 correspondence with zurl.
# it then waits for wcfs to exit (either due to unmount or an error).
#
# it is an error if wcfs was already started.
#
# XXX optv
# if exec_ is True, wcfs is not spawned, but executed into.
#
# serve(zurl, exec_=False).
def serve(zurl, optv, exec_=False):
    mntpt = _mntpt_4zurl(zurl)

    # try opening .wcfs - it is an error if we can do it.
    # XXX -> option to wcfs itself?
    try:
        f = open(mntpt + "/.wcfs/zurl")
    except IOError as e:
        if e.errno != ENOENT:
            raise
    else:
        f.close()
        raise RuntimeError("wcfs: start %s: already started" % zurl)

    # seems to be ok to start
    # XXX race window if something starts after ^^^ check
    argv = [_wcfs_exe()] + list(optv) + [zurl, mntpt]
    if not exec_:
        subprocess.check_call(argv, close_fds=True)
    else:
        os.execv(argv[0], argv)


Kirill Smelkov's avatar
.  
Kirill Smelkov committed
788

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
789

Kirill Smelkov's avatar
.  
Kirill Smelkov committed
790
# if called as main just -> serve()
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
791
def main():
Kirill Smelkov's avatar
.  
Kirill Smelkov committed
792 793 794 795 796
    argv = sys.argv[1:]
    # XXX usage
    zurl = argv[-1]     # -a -b zurl    -> zurl
    optv = argv[:-1]    # -a -b zurl    -> -a -b
    serve(zurl, optv, exec_=True)