model.py 10.1 KB
Newer Older
1
2
3
4
import llfuse
import time
import os
import stat
5
import copy
6
import logging
7
8
9

import settings

10
11

class FuseIO():
12
13
14
15
16
17
18
19
20
21
22
23
    def __init__(self, mode, inode, attr=None):
        self._inode = inode
        if attr:
            self._attr = attr
        else:
            self._attr = self._construct_attr(mode)

    def _construct_attr(self, mode):
        attr = llfuse.EntryAttributes()
        attr.st_mode = mode
        attr.st_nlink = 1
        attr.st_size = 0
24

25
26
        # attr.generation = 0
        # attr.st_rdev = 0
27

28
29
30
31
32
        # attr.attr_timeout = 300
        # attr.entry_timeout = 300
        attr.st_atime_ns = int(time.time())
        attr.st_mtime_ns = int(time.time())
        attr.st_ctime_ns = int(time.time())
33

34
35
        # attr.st_blksize = 512
        # attr.st_blocks = 1
36

37
38
        attr.st_gid = os.getgid()
        attr.st_uid = os.getuid()
39

40
        return attr
41
42

    def get_inode(self):
43
44
        if self._inode == -1:
            raise Exception("Special File")
45
        else:
46
47
48
49
            return self._inode

    def set_inode(self, inode):
        self._inode = inode
50

51
    def get_attr(self):
52
53
54
55
56
        if self._inode == -1:
            if hasattr(self, "_name"):
                raise Exception(self._name + ": Special File")
            raise Exception("Special File")
        self._attr.st_ino = self._inode
57
58
        return self._attr

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
    def add_nlink(self):
        self._attr.st_nlink += 1

    def deepcopy_and_register(self, placeholder, obj):
        """ Make a generic deepcopy and register an inode.
        The placeholder and obj parameter make no sense here and are
        for signature compability with FuseDir.
        """
        if self._inode != -1:
            raise Exception("Cannot create a deep copy of an real file.")
        pcopy = copy.copy(self)
        # TODO
        # https://bitbucket.org/nikratio/python-llfuse/issues/95/copying-of-llfuseentryattributes-fails
        # pcopy._attr = copy.copy(self._attr)
        pcopy._attr = self._construct_attr(self._attr.st_mode)
        self._data.pin_inode(pcopy)
        return pcopy

    def is_special(self):
        return False


class Node:
    def __init__(self, parent, name, data, root=False):
        self._parent = parent
        if root:
            self._parent = self
        self._name = name
        self._data = data
        self._children = {}
        self._specials = []

91
    def get_parent(self):
Gerion Entrup's avatar
Gerion Entrup committed
92
        return self._parent
93

94
95
96
97
98
    def get_root(self):
        parent = self
        while parent is not parent.get_parent():
            parent = parent.get_parent()
        return parent
99

100
101
    def get_name(self):
        return self._name
102

103
104
105
    def add_special(self, special):
        self._specials.append(special)
        return special
Gerion Entrup's avatar
Gerion Entrup committed
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
    def add_fuseio(self, fuseio, filename):
        if filename in self._children:
            raise Exception("File with filename {} already exists".format(
                filename))
        self._children[filename] = fuseio
        return fuseio

    def is_leaf(self):
        return len(self._children) == 0 and len(self._specials) == 0

    def get_children(self):
        return self._children

    def get_specials(self):
        return self._specials


class Special(Node):
    def __init__(self, query, functions, where, session,
                 parent, name, data, fileattr):
        super().__init__(parent, name, data)
        self._query = query
        self._functions = functions
        self._session = session
        self._where = where
        self._fileattr = fileattr
133
        self.logger = logging.getLogger('sqlfuse.special')
134
135
136
137
138
139
140
141
142
143
144
145
146
147

    def __repr__(self):
        return ''.join(["Special(query=", repr(self._query),
                        ", functions=",   repr(self._functions),
                        ", where=",       repr(self._where),
                        ", session=",     repr(self._session),
                        ", parent=",      self._parent.get_name(),
                        ", name=",        self._name,
                        ", data=",        repr(self._data),
                        ", fileattr=",    repr(self._fileattr),
                        ")"])

    def query_name(self, qname):
        query = self._functions.parse_name(qname, self._query)
148
        self.logger.debug("query by name '{}': {}".format(qname, str(query)))
149
150
151
152
153
        if query is None:
            return None
        return self._session.execute(query).first()

    def query_all(self):
154
        self.logger.debug("query all: {}".format(str(self._query)))
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        return self._session.execute(self._query)

    def is_special(self):
        return True

    def get_fileattr(self, row):
        return self._fileattr(row)

    def get_obj_fname(self, row):
        return self._functions.gen_name(row)

    def apply_where(self, placeholder, obj):
        for pwhere in self._where:
            if pwhere.ph_obj == placeholder:
169
170
171
172
173
174
                if self.logger.isEnabledFor(logging.DEBUG):
                    self.logger.debug("apply where clause with function '{}', \
attribute {}, object items: {}".format('.'.join([str(pwhere.function.__self__),
                                                pwhere.function.__name__]),
                                       pwhere.attribute,
                                       obj.items()))
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
                try:
                    attr = getattr(obj, pwhere.attribute)
                except AttributeError:
                    raise Exception("Applying where fails: " + str(obj) +
                                    " has not the wanted attribute " +
                                    pwhere.attribute)
                self._query = self._query.where(pwhere.function(attr))


class FuseDir(FuseIO, Node):
    def __init__(self, mode, inode, parent, name, data, root=False):
        if mode is None:
            mode = settings.default_mode_dir
        FuseIO.__init__(self, stat.S_IFDIR | mode, inode)
        Node.__init__(self, parent, name, data, root=root)
        self._attr.st_size = 4096
        self._sorted_filenames = []
        if root:
            self._attr.st_nlink = 2

    def __repr__(self):
        return ''.join(["FuseDir(mode=", oct(self._attr.st_mode),
                        ", inode=",      str(self._inode),
                        ", parent=",     self._parent.get_name(),
                        ", name=",       self._name,
                        ")"])

    def construct_from_query(self, special, row):
        name = special.get_obj_fname(row)
        if name in self._children:
            return None, None

        if special.is_leaf():
            (gid, path) = special.get_fileattr(row)
            f = FuseFile(None, -1, self, gid, path, self._data)
        else:
            f = FuseDir(None, -1, self, name, self._data)
            for (fname, child) in special.get_children().items():
                f.add_fuseio(child.deepcopy_and_register(special.get_name(),
                                                         row),
                             fname)
216
217
218
219
            for s_special in special.get_specials():
                s_special = copy.copy(s_special)
                s_special.apply_where(special.get_name(), row)
                f.add_special(s_special)
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
        self._data.pin_inode(f)
        self.add_fuseio(f, name)
        return name, f

    def deepcopy_and_register(self, placeholder, obj):
        pcopy = FuseIO.deepcopy_and_register(self, placeholder, obj)
        pcopy._children = {}
        pcopy._sorted_filenames = []
        pcopy._specials = []
        for (fname, child) in self._children.items():
            pcopy.add_fuseio(child.deepcopy_and_register(placeholder, obj),
                             fname)
        for special in self._specials:
            special = copy.copy(special)
            special.apply_where(placeholder, obj)
            pcopy.add_special(special)
        return pcopy
237

238
    def query_name(self, filename):
Gerion Entrup's avatar
Gerion Entrup committed
239
240
241
        if filename == '.':
            return self.get_attr()
        if filename == '..':
242
            return self.get_parent().get_attr()
Gerion Entrup's avatar
Gerion Entrup committed
243
        if filename in self._children:
244
245
246
247
248
249
            return self._children[filename].get_attr()
        for special in self._specials:
            res = special.query_name(filename)
            if res is not None:
                name, f = self.construct_from_query(special, res)
                return f.get_attr()
Gerion Entrup's avatar
Gerion Entrup committed
250
251

    def add_fuseio(self, fuseio, filename):
252
253
254
255
256
257
        Node.add_fuseio(self, fuseio, filename)
        self._sorted_filenames.append(filename)
        fuseio.add_nlink()
        if isinstance(fuseio, FuseDir):
            self.add_nlink()
        return fuseio
258
259
260
261
262

    def opendir(self):
        pass

    def readdir(self, offset):
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        for child in self._sorted_filenames[offset:]:
            yield (child, self._children[child].get_attr())
        for special in self._specials:
            nlen = len(self._sorted_filenames)
            res = special.query_all()
            for row in res:
                name, f = self.construct_from_query(special, row)
                if name is not None and offset <= nlen:
                        yield(name, f.get_attr())


class FuseFile(FuseIO, Node):
    def __init__(self, mode, inode, parent, gid, path, data):
        if mode is None:
            mode = settings.default_mode_file
        FuseIO.__init__(self, stat.S_IFREG | mode, inode)
        Node.__init__(self, parent, None, data)
        self._gid = gid
281
        self._path = path
282
283
284
285
286
287
288
289
290
        self._attr.st_size = os.path.getsize(path)

    def __repr__(self):
        return ''.join(["FuseFile(mode=", oct(self._attr.st_mode),
                        ", inode=",       str(self._inode),
                        ", parent=",      self._parent.get_name(),
                        ", gid=",         str(self._gid),
                        ", path=",        self._path,
                        ")"])
291
292
293
294
295
296

    def open(self):
        self._file = open(self._path, 'rb')

    def close(self):
        self._file.close()
297

298
299
300
301
    def get_name(self):
        return str(self._gid)

    def read(self, offset, size):
302
303
304
        self._file.seek(offset)
        return self._file.read(size)

305
306
307
308
309
    def add_fuseio(self, fuseio, filename):
        raise Exception("FuseFile has to be a leaf.")

    def add_special(self, special):
        raise Exception("FuseFile has to be a leaf.")