File: filereceiver.py

package info (click to toggle)
gr-satellites 5.8.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,836 kB
  • sloc: python: 29,546; cpp: 5,448; ansic: 1,247; sh: 118; makefile: 24
file content (328 lines) | stat: -rw-r--r-- 9,297 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright 2020 Daniel Estevez <daniel@destevez.net>
#
# This file is part of gr-satellites
#
# SPDX-License-Identifier: GPL-3.0-or-later
#

import pathlib


class File:
    """
    Class to hold housekeeping data about a file being received
    """
    def __init__(self, path):
        """
        Builds a new file, initializing housekeeping data

        Args:
            path: path of the file (pathlib.Path)
        """
        self.path = path
        mode = 'r+b' if path.exists() else 'wb'
        self.f = open(path, mode)
        self.broken = False
        self.expected_seq = 0
        self.write_pointer = 0
        self.size = None
        self.chunks = None


class FileReceiver:
    """
    Class to reassemble files transmitted in chunks

    This implements the generic framework. Specific protocols should
    inherit from this class and implement some functions
    """
    def __init__(self, path, verbose=False):
        """
        Builds a new FileReceiver

        Args:
            path: directory where files should be stored (str or pathlib.Path)
            verbose: verbose reporting of events (bool)
        """
        self._files = dict()
        self._current_file = None
        self._next_fid = 0
        self._path = pathlib.Path(path)
        self._verbose = verbose
        self._name = 'FileReceiver'

    def file_id(self, chunk):
        """
        Returns the file ID of a given chunk

        If the file cannot be identified from a chunk, it should
        return None.

        The default implementation returns chunk.file_id if available
        else None

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        """
        return getattr(chunk, 'file_id', None)

    def chunk_sequence(self, chunk):
        """
        Returns the sequence number of a given chunk

        The sequence number should increase from 0. If the chunk number
        cannot be identified from a chunk, or if chunk_offset is used
        instead, it should return None.

        The default implementation returns chunk.sequence if available
        else None

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        """
        return getattr(chunk, 'sequence', None)

    def chunk_size(self):
        """
        Returns the size of a chunk if all chunks (except possibly
        the last one) have the same fixed size, None if not
        """
        return None

    def chunk_offset(self, chunk):
        """
        Returns the offset in bytes of a given chunk within the file

        This should return None if it is not possible to determine
        the chunk offset from the chunk.

        The default implementation first returns chunk.offset if available.
        If not, it tries to use chunk_sequence() and chunk_size() to
        determine the offset.

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        """
        off = getattr(chunk, 'offset', None)
        if off is not None:
            return off
        s = self.chunk_size()
        i = self.chunk_sequence(chunk)
        if s is not None and i is not None:
            return s * i
        else:
            return None

    def chunk_data(self, chunk):
        """
        Returns the file data in a given chunk

        The default implementation returns chunk.data.

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        Returns:
            bytes
        """
        return chunk.data

    def file_chunks(self, chunk):
        """
        Returns the total number of chunks in the file

        The default implementation returns chunk.chunks if available
        else None

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        """
        return getattr(chunk, 'chunks', None)

    def file_size(self, chunk):
        """
        Returns the total number of bytes in the file

        The default implementation returns chunk.filesize if available
        else None

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        """
        return getattr(chunk, 'filesize', None)

    def is_last_chunk(self, chunk):
        """
        Returns whether this is the last chunk in the file

        The default implementation returns None

        Args:
            chunk: a file chunk (parsed by parse_chunk())
        Returns:
            True if this is is the last chunk, False if this is not
            the last chunk, None if it is unknown whether this is the
            last chunk.
        """
        return None

    def parse_chunk(self, chunk):
        """
        Parses the chunk into an object which is easier to handle

        The default implementation does nothing.
        A return of None means the chunk is invalid and should not
        be processed.

        Args:
            chunk: a file chunk (bytes)
        """
        return chunk

    def filename(self, fid):
        """
        Generates a filename based on the file id

        The default implementation uses the file id as filename

        Args:
           fid: file id (usually int)
        """
        return str(fid)

    def on_completion(self, f):
        """
        Function to be called on file completion

        The user should overload this function if some action
        needs to be done after a file is complete

        Args:
            f: the file just completed (File)
        """

    def _new_file(self, fid):
        """
        Creates a new file

        Args:
            fid: file id of the new file (usually int)
        Returns:
            the new file
        """
        f = File(self._path / self.filename(fid))
        self._files[fid] = f
        return f

    def _fill_file_data(self, f, chunk):
        """
        Tries to fill some file data from the chunk

        Args:
            f: a File
            chunk: a file chunk (parsed by parse_chunk())
        """
        if f.size is None:
            f.size = self.file_size(chunk)
        if f.chunks is None:
            f.chunks = self.file_chunks(chunk)

    def log(self, message):
        if self._verbose:
            print(f'{self._name}: {message}')

    def push_chunk(self, chunk):
        """
        Processes a new chunk

        The user should call this function whenever a new chunk
        is received.

        Args:
            chunk: the file chunk (bytes)
        """
        chunk = self.parse_chunk(chunk)
        if chunk is None:
            return

        # Find file
        # TODO: logic about new file when file_id == None
        fid = self.file_id(chunk)
        if fid is None:
            fid = self._current_file
        if fid is None:
            fid = self._next_fid
            self._next_fid += 1
        try:
            f = self._files[fid]
        except KeyError:
            self.log(f'new file {fid}')
            f = self._new_file(fid)

        seq = self.chunk_sequence(chunk)

        # Detect a new file if sequence has decreased
        if (self.file_id(chunk) is None
                and seq is not None
                and seq < f.expected_seq):
            # f is finished
            self.log(f'file {fid} is finished')
            fid = self._next_fid
            self._next_fid += 1
            f = self._new_file(fid)
            self.log(f'receiving new file {fid}')
        self._current_file = fid

        self._fill_file_data(f, chunk)

        if seq is not None:
            self.log(f'received sequence {seq} for file {fid}')

        if f.broken:
            # File is broken, nothing can be done with the chunk
            return

        # Try to determine offset
        offset = self.chunk_offset(chunk)
        if seq is None and offset is not None:
            self.log(f'received offset {offset} for file {fid}')
        if offset is None:
            # Check sequence continuity
            if seq is None:
                raise Exception(
                    'FileReceiver unable to compute chunk_offset() '
                    'nor chunk_sequence()')
            if seq != f.expected_seq:
                self.log(f'received sequence {seq} != expected sequence '
                         f'{f.expected_seq}. File reception is broken.')
                f.broken = True
                return
            offset = f.write_pointer

        data = self.chunk_data(chunk)
        new_write_pointer = offset + len(data)

        # check offset within size
        if f.size is not None and new_write_pointer > f.size:
            self.log(f'invalid offset {offset} (chunk size is {len(data)}, '
                     f'file size is {f.size})')
            return

        # write chunk at offset
        f.f.seek(offset)
        f.f.write(data)
        f.f.flush()

        # update pointers
        f.write_pointer = new_write_pointer
        f.expected_seq = seq + 1 if seq is not None else None

        # check if file is complete
        if ((f.size is not None and f.write_pointer >= f.size)
                or (f.chunks is not None and f.expected_seq >= f.chunks)
                or self.is_last_chunk(chunk)):
            self.log(f'file {fid} complete')
            self.on_completion(f)
            self._current_file = None