File size: 8,140 Bytes
bbff072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Command-line access to NYARION's POSIX regular-file image engine."""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import sys

import pagefs
from . import __version__

INPUT_LIMIT = 1024 * 1024


def _json(value):
    print(json.dumps(value, sort_keys=True, ensure_ascii=True, indent=2))


def _read(path, limit=INPUT_LIMIT):
    if path == '-':
        data = sys.stdin.buffer.read(limit + 1)
    else:
        with open(path, 'rb') as stream:
            data = stream.read(limit + 1)
    if len(data) > limit:
        raise ValueError(f'input exceeds {limit} byte command limit')
    return data


def _write(path, data):
    """Exclusive creation keeps output paths from replacing an image or input."""
    if path == '-':
        sys.stdout.buffer.write(data)
        sys.stdout.buffer.flush()
        return
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600)
    with os.fdopen(descriptor, 'wb') as stream:
        stream.write(data)
        stream.flush()
        os.fsync(stream.fileno())


def _pairs(items):
    obj = {}
    for key, value in items:
        if key in obj:
            raise ValueError(f'duplicate JSON key: {key!r}')
        obj[key] = value
    return obj


def _transaction(path):
    try:
        obj = json.loads(_read(path).decode('utf8'), object_pairs_hook=_pairs,
                         parse_constant=lambda value: (_ for _ in ()).throw(ValueError('invalid JSON constant')))
    except (UnicodeError, RecursionError) as exc:
        raise ValueError('transaction must be bounded UTF-8 JSON') from exc
    if not isinstance(obj, dict) or set(obj) != {'token', 'changes'}:
        raise ValueError('transaction fields must be exactly token and changes')
    pagefs.token_key(obj['token'])
    changes = obj['changes']
    if not isinstance(changes, dict) or not changes:
        raise ValueError('transaction changes must be a nonempty map')
    decoded = {}
    for key, entry in changes.items():
        pagefs.path_key(key)
        if entry is None:
            decoded[key] = None
        elif isinstance(entry, dict) and set(entry) == {'base64'}:
            decoded[key] = pagefs.unb64(entry['base64'])
        else:
            raise ValueError('each change must be null or an object containing only base64')
    return decoded, obj['token']


def _snapshot(store):
    files = []
    for path in store.files():
        data = store.get(path)
        files.append({'path': path, 'base64': base64.b64encode(data).decode('ascii'),
                      'length': len(data), 'sha256': hashlib.sha256(data).hexdigest()})
    # Receipt enumeration is a release-local export interface. Each value is
    # retrieved through the public query function after recovery validation.
    receipts = [{'token': token, **store.query(token)} for token in sorted(store._tokens)]
    body = {'export_format': 1, 'engine_format': pagefs.FORMAT, 'volume': store.volume,
            'epoch': store.epoch, 'files': files, 'receipts': receipts}
    body['snapshot_sha256'] = hashlib.sha256(pagefs.canonical(body)).hexdigest()
    return body


def parser():
    result = argparse.ArgumentParser(
        prog='nyarion',
        description='NYARION regular-file storage engine. Requires Python 3 and POSIX; this is not a mounted filesystem.')
    result.add_argument('--version', action='version', version='NYARION ' + __version__)
    commands = result.add_subparsers(dest='command', required=True)
    init = commands.add_parser('init', help='exclusively create an empty image')
    init.add_argument('image')
    init.add_argument('--pool-blocks', type=int, default=pagefs.DEFAULT_POOL_BLOCKS,
                      help='number of 4 KiB physical arena blocks, including replicas')
    put = commands.add_parser('put', help='durably replace one complete logical file value')
    put.add_argument('image'); put.add_argument('key'); put.add_argument('--token', required=True)
    data = put.add_mutually_exclusive_group(required=True)
    data.add_argument('--file', metavar='PATH', help='input bytes; - reads stdin')
    data.add_argument('--text', help='UTF-8 text value')
    get = commands.add_parser('get', help='read a logical value as raw bytes')
    get.add_argument('image'); get.add_argument('key')
    get.add_argument('--output', default='-', help='new output file; default is stdout')
    ls = commands.add_parser('ls', aliases=['list'], help='list logical keys as JSON')
    ls.add_argument('image')
    delete = commands.add_parser('delete', help='durably remove one logical key')
    delete.add_argument('image'); delete.add_argument('key'); delete.add_argument('--token', required=True)
    tx = commands.add_parser('transact', help='apply one atomic JSON transaction')
    tx.add_argument('image'); tx.add_argument('transaction', help='UTF-8 JSON path, or - for stdin')
    for command, help_text in (
        ('checkpoint', 'materialize and publish the complete outstanding prefix'),
        ('inspect', 'inspect recovered metadata without repairing'),
        ('plan', 'show an exact checkpoint publication summary without writing'),
        ('verify', 'validate recovery and report a logical snapshot digest without repairing'),
        ('repair', 'open writable, restore available mirror redundancy, and inspect'),
    ):
        cmd = commands.add_parser(command, help=help_text); cmd.add_argument('image')
    query = commands.add_parser('query', help='query a durable retry receipt')
    query.add_argument('image'); query.add_argument('token')
    export = commands.add_parser('export', help='export bytes and receipt metadata as audit JSON')
    export.add_argument('image'); export.add_argument('--output', default='-', help='new output file; default is stdout')
    return result


def main(argv=None):
    args = parser().parse_args(argv)
    try:
        command = args.command
        if command == 'init':
            with pagefs.PageStore.create(args.image, pool_blocks=args.pool_blocks) as store:
                _json(store.inspect())
            return 0
        if command == 'put':
            value = args.text.encode('utf8') if args.text is not None else _read(args.file)
            changes, token = {args.key: value}, args.token
        elif command == 'delete':
            changes, token = {args.key: None}, args.token
        elif command == 'transact':
            changes, token = _transaction(args.transaction)
        writable = command in ('put', 'delete', 'transact', 'checkpoint', 'repair')
        with pagefs.PageStore(args.image, writable=writable) as store:
            if command in ('put', 'delete', 'transact'):
                epoch = store.transact(changes, token)
                _json({'epoch': epoch, 'receipt': store.query(token)})
            elif command == 'get':
                _write(args.output, store.get(args.key))
            elif command in ('ls', 'list'):
                _json(store.files())
            elif command == 'checkpoint':
                _json({'checkpoint_epoch': store.checkpoint(), 'state': store.inspect()})
            elif command in ('inspect', 'repair'):
                _json(store.inspect())
            elif command == 'plan':
                _json(store.checkpoint_plan())
            elif command == 'query':
                _json(store.query(args.token))
            elif command in ('verify', 'export'):
                snapshot = _snapshot(store)
                if command == 'export':
                    _write(args.output, (json.dumps(snapshot, sort_keys=True, ensure_ascii=True, indent=2) + '\n').encode('ascii'))
                else:
                    _json({'valid': True, 'epoch': store.epoch, 'files': len(snapshot['files']),
                           'receipts': len(snapshot['receipts']), 'snapshot_sha256': snapshot['snapshot_sha256']})
        return 0
    except (pagefs.StoreError, OSError, ValueError, TypeError) as exc:
        print('nyarion: ' + str(exc), file=sys.stderr)
        return 2


if __name__ == '__main__':
    raise SystemExit(main())