Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/sugar_network/node/sync.py
blob: f5b946c69dcc712f0f1bfe130c9d6721bda69f7b (plain)
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
# Copyright (C) 2012-2013 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import gzip
import zlib
import json
import logging
from cStringIO import StringIO
from types import GeneratorType
from os.path import exists, join, dirname, basename, splitext

from sugar_network import toolkit
from sugar_network.toolkit import coroutine, enforce


# Filename suffix to use for sneakernet synchronization files
_SNEAKERNET_SUFFIX = '.sneakernet'

# Leave at leat n bytes in fs whle calling `encode_to_file()`
_SNEAKERNET_RESERVED_SIZE = 1024 * 1024

_logger = logging.getLogger('node.sync')


def decode(stream):
    packet = _PacketsIterator(stream)
    while True:
        packet.next()
        if packet.name == 'last':
            break
        yield packet


def encode(packets, **header):
    return _encode(None, packets, False, header, _EncodingStatus())


def limited_encode(limit, packets, **header):
    return _encode(limit, packets, False, header, _EncodingStatus())


def package_decode(stream):
    stream = _GzipStream(stream)
    package_props = json.loads(stream.readline())

    for packet in decode(stream):
        packet.props.update(package_props)
        yield packet


def package_encode(packets, **header):
    # XXX Only for small amount of data
    # TODO Support real streaming
    buf = StringIO()
    zipfile = gzip.GzipFile(mode='wb', fileobj=buf)

    header['filename'] = toolkit.uuid() + _SNEAKERNET_SUFFIX
    json.dump(header, zipfile)
    zipfile.write('\n')

    for chunk in _encode(None, packets, False, None, _EncodingStatus()):
        zipfile.write(chunk)
    zipfile.close()

    yield buf.getvalue()


def sneakernet_decode(root, node=None, session=None):
    for root, __, files in os.walk(root):
        for filename in files:
            if not filename.endswith(_SNEAKERNET_SUFFIX):
                continue
            zipfile = gzip.open(join(root, filename), 'rb')
            try:
                package_props = json.loads(zipfile.readline())

                if node is not None and package_props.get('src') == node:
                    if package_props.get('session') == session:
                        _logger.debug('Skip session %r sneakernet package',
                                zipfile.name)
                    else:
                        _logger.debug('Remove outdate %r sneakernet package',
                                zipfile.name)
                        os.unlink(zipfile.name)
                    continue

                for packet in decode(zipfile):
                    packet.props.update(package_props)
                    yield packet
            finally:
                zipfile.close()


def sneakernet_encode(packets, root=None, limit=None, path=None, **header):
    if path is None:
        if not exists(root):
            os.makedirs(root)
        filename = toolkit.uuid() + _SNEAKERNET_SUFFIX
        path = toolkit.unique_filename(root, filename)
    else:
        filename = splitext(basename(path))[0] + _SNEAKERNET_SUFFIX
    if 'filename' not in header:
        header['filename'] = filename

    if limit <= 0:
        stat = os.statvfs(dirname(path))
        limit = stat.f_bfree * stat.f_frsize - _SNEAKERNET_RESERVED_SIZE

    _logger.debug('Creating %r sneakernet package, limit=%s header=%r',
            path, limit, header)

    status = _EncodingStatus()
    with file(path, 'wb') as package:
        zipfile = gzip.GzipFile(fileobj=package)
        try:
            json.dump(header, zipfile)
            zipfile.write('\n')

            pos = None
            encoder = _encode(limit, packets, True, None, status)
            while True:
                try:
                    chunk = encoder.send(pos)
                    zipfile.write(chunk)
                    pos = zipfile.fileobj.tell()
                    coroutine.dispatch()
                except StopIteration:
                    break

        except Exception:
            _logger.debug('Emergency removing %r package', path)
            package.close()
            os.unlink(path)
            raise
        else:
            zipfile.close()
            package.flush()
            os.fsync(package.fileno())

    return not status.aborted


class _EncodingStatus(object):

    aborted = False


def _encode(limit, packets, download_blobs, header, status):
    for packet, props, content in packets:
        if status.aborted:
            break

        if props is None:
            props = {}
        if header:
            props.update(header)
        props['packet'] = packet
        pos = (yield json.dumps(props) + '\n') or 0

        if content is None:
            continue

        content = iter(content)
        try:
            record = next(content)

            while True:
                blob = None
                blob_size = 0
                if 'blob' in record:
                    blob = record.pop('blob')
                    blob_size = record['blob_size']

                dump = json.dumps(record) + '\n'
                if not status.aborted and limit is not None and \
                        pos + len(dump) + blob_size > limit:
                    status.aborted = True
                    if not isinstance(content, GeneratorType):
                        raise StopIteration()
                    record = content.throw(StopIteration())
                    continue
                pos = (yield dump) or 0

                if blob is not None:
                    for chunk in blob:
                        pos = (yield chunk) or 0
                        blob_size -= len(chunk)
                    enforce(blob_size == 0, EOFError,
                            'File size is not the same as declared')

                record = next(content)
        except StopIteration:
            pass

    yield json.dumps({'packet': 'last'}) + '\n'


class _PacketsIterator(object):

    def __init__(self, stream):
        if not hasattr(stream, 'readline'):
            stream.readline = lambda: toolkit.readline(stream)
        if hasattr(stream, 'seek'):
            self._seek = stream.seek
        self._stream = stream
        self.props = {}
        self._name = None
        self._shift = True

    @property
    def name(self):
        return self._name

    def next(self):
        if self._shift:
            for __ in self:
                pass
        if self._name is None:
            raise EOFError()
        self._shift = True

    def __repr__(self):
        return '<SyncPacket %r>' % self.props

    def __getitem__(self, key):
        return self.props.get(key)

    def __iter__(self):
        blob = None
        while True:
            if blob is not None and blob.size_to_read:
                self._seek(blob.size_to_read, 1)
                blob = None
            record = self._stream.readline()
            if not record:
                self._name = None
                raise EOFError()
            record = json.loads(record)
            if 'packet' in record:
                self._name = record['packet'] or ''
                self.props = record
                self._shift = False
                break
            blob_size = record.get('blob_size')
            if blob_size:
                blob = record['blob'] = _Blob(self._stream, blob_size)
            yield record

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        pass

    # pylint: disable-msg=E0202
    def _seek(self, distance, where):
        while distance:
            chunk = self._stream.read(min(distance, toolkit.BUFFER_SIZE))
            distance -= len(chunk)


class _Blob(object):

    def __init__(self, stream, size):
        self._stream = stream
        self.size_to_read = size

    def read(self, size=toolkit.BUFFER_SIZE):
        chunk = self._stream.read(min(size, self.size_to_read))
        self.size_to_read -= len(chunk)
        return chunk


class _GzipStream(object):

    def __init__(self, stream):
        self._stream = stream
        self._zip = zlib.decompressobj(16 + zlib.MAX_WBITS)
        self._buffer = bytearray()

    def read(self, size):
        while True:
            if size <= len(self._buffer):
                result = self._buffer[:size]
                self._buffer = self._buffer[size:]
                return bytes(result)
            chunk = self._stream.read(size)
            if not chunk:
                result, self._buffer = self._buffer, bytearray()
                return result
            self._buffer += self._zip.decompress(chunk)

    def readline(self):
        return toolkit.readline(self)