storages.py 9.16 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of CubicWeb.
#
# CubicWeb is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
11
# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
12
13
14
15
16
17
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
18
"""custom storages for the system source"""
19

20
21
from os import unlink, path as osp

22
23
from yams.schema import role_name

24
from cubicweb import Binary, ValidationError
25
from cubicweb.server import hook
26
27

def set_attribute_storage(repo, etype, attr, storage):
28
    repo.system_source.set_storage(etype, attr, storage)
29

30
def unset_attribute_storage(repo, etype, attr):
31
    repo.system_source.unset_storage(etype, attr)
32
33

class Storage(object):
34
35
36
    """abstract storage

    * If `source_callback` is true (by default), the callback will be run during
37
      query result process of fetched attribute's value and should have the
38
39
      following prototype::

40
        callback(self, source, session, value)
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

      where `value` is the value actually stored in the backend. None values
      will be skipped (eg callback won't be called).

    * if `source_callback` is false, the callback will be run during sql
      generation when some attribute with a custom storage is accessed and
      should have the following prototype::

        callback(self, generator, relation, linkedvar)

      where `generator` is the sql generator, `relation` the current rql syntax
      tree relation and linkedvar the principal syntax tree variable holding the
      attribute.
    """
    is_source_callback = True

    def callback(self, *args):
        """see docstring for prototype, which vary according to is_source_callback
59
60
61
62
63
64
65
66
67
68
69
70
        """
        raise NotImplementedError()

    def entity_added(self, entity, attr):
        """an entity using this storage for attr has been added"""
        raise NotImplementedError()
    def entity_updated(self, entity, attr):
        """an entity using this storage for attr has been updatded"""
        raise NotImplementedError()
    def entity_deleted(self, entity, attr):
        """an entity using this storage for attr has been deleted"""
        raise NotImplementedError()
71
72
73
    def migrate_entity(self, entity, attribute):
        """migrate an entity attribute to the storage"""
        raise NotImplementedError()
74
75
76
77

# TODO
# * make it configurable without code
# * better file path attribution
Sylvain Thénault's avatar
Sylvain Thénault committed
78
# * handle backup/restore
79

80
81
82
83
84
85
def uniquify_path(dirpath, basename):
    """return a unique file name for `basename` in `dirpath`, or None
    if all attemps failed.

    XXX subject to race condition.
    """
86
    path = osp.join(dirpath, basename.replace(osp.sep, '-'))
87
88
89
90
91
92
93
94
95
    if not osp.isfile(path):
        return path
    base, ext = osp.splitext(path)
    for i in xrange(1, 256):
        path = '%s%s%s' % (base, i, ext)
        if not osp.isfile(path):
            return path
    return None

Sylvain Thénault's avatar
Sylvain Thénault committed
96

97
98
class BytesFileSystemStorage(Storage):
    """store Bytes attribute value on the file system"""
99
    def __init__(self, defaultdir, fsencoding='utf-8'):
100
        self.default_directory = defaultdir
101
        self.fsencoding = fsencoding
102

103
    def callback(self, source, session, value):
104
105
106
        """sql generator callback when some attribute with a custom storage is
        accessed
        """
107
108
        fpath = source.binary_to_str(value)
        try:
109
            return Binary(file(fpath, 'rb').read())
110
111
112
        except OSError, ex:
            source.critical("can't open %s: %s", value, ex)
            return None
113
114
115

    def entity_added(self, entity, attr):
        """an entity using this storage for attr has been added"""
116
        if entity._cw.transaction_data.get('fs_importing'):
117
            binary = Binary(file(entity[attr].getvalue(), 'rb').read())
118
119
120
121
122
        else:
            binary = entity.pop(attr)
            fpath = self.new_fs_path(entity, attr)
            # bytes storage used to store file's path
            entity[attr] = Binary(fpath)
123
            file(fpath, 'wb').write(binary.getvalue())
124
            hook.set_operation(entity._cw, 'bfss_added', fpath, AddFileOp)
125
        return binary
126
127
128

    def entity_updated(self, entity, attr):
        """an entity using this storage for attr has been updatded"""
129
        # get the name of the previous file containing the value
130
        oldpath = self.current_fs_path(entity, attr)
131
        if entity._cw.transaction_data.get('fs_importing'):
132
133
134
            # If we are importing from the filesystem, the file already exists.
            # We do not need to create it but we need to fetch the content of
            # the file as the actual content of the attribute
135
            fpath = entity[attr].getvalue()
136
            binary = Binary(file(fpath, 'rb').read())
137
        else:
138
139
140
141
142
143
144
145
146
            # We must store the content of the attributes
            # into a file to stay consistent with the behaviour of entity_add.
            # Moreover, the BytesFileSystemStorage expects to be able to
            # retrieve the current value of the attribute at anytime by reading
            # the file on disk. To be able to rollback things, use a new file
            # and keep the old one that will be removed on commit if everything
            # went ok.
            #
            # fetch the current attribute value in memory
147
            binary = entity.pop(attr)
148
            # Get filename for it
149
            fpath = self.new_fs_path(entity, attr)
150
151
152
153
154
155
            assert not osp.exists(fpath)
            # write attribute value on disk
            file(fpath, 'wb').write(binary.getvalue())
            # Mark the new file as added during the transaction.
            # The file will be removed on rollback
            hook.set_operation(entity._cw, 'bfss_added', fpath, AddFileOp)
156
        if oldpath != fpath:
157
            # register the new location for the file.
158
            entity[attr] = Binary(fpath)
159
160
            # Mark the old file as useless so the file will be removed at
            # commit.
161
162
            hook.set_operation(entity._cw, 'bfss_deleted', oldpath,
                               DeleteFileOp)
163
        return binary
164
165
166

    def entity_deleted(self, entity, attr):
        """an entity using this storage for attr has been deleted"""
167
168
        fpath = self.current_fs_path(entity, attr)
        hook.set_operation(entity._cw, 'bfss_deleted', fpath, DeleteFileOp)
169
170

    def new_fs_path(self, entity, attr):
171
172
173
174
175
        # We try to get some hint about how to name the file using attribute's
        # name metadata, so we use the real file name and extension when
        # available. Keeping the extension is useful for example in the case of
        # PIL processing that use filename extension to detect content-type, as
        # well as providing more understandable file names on the fs.
176
        basename = [str(entity.eid), attr]
177
        name = entity.cw_attr_metadata(attr, 'name')
178
        if name is not None:
179
            basename.append(name.encode(self.fsencoding))
180
181
182
        fspath = uniquify_path(self.default_directory, '_'.join(basename))
        if fspath is None:
            msg = entity._cw._('failed to uniquify path (%s, %s)') % (
183
                self.default_directory, '_'.join(basename))
184
            raise ValidationError(entity.eid, {role_name(attr, 'subject'): msg})
185
186
187
        return fspath

    def current_fs_path(self, entity, attr):
188
189
190
        sysource = entity._cw.pool.source('system')
        cu = sysource.doexec(entity._cw,
                             'SELECT cw_%s FROM cw_%s WHERE cw_eid=%s' % (
191
                             attr, entity.__regid__, entity.eid))
192
193
194
195
        rawvalue = cu.fetchone()[0]
        if rawvalue is None: # no previous value
            return self.new_fs_path(entity, attr)
        return sysource._process_value(rawvalue, cu.description[0],
196
                                       binarywrap=str)
197

198
199
200
201
202
203
204
205
206
207
    def migrate_entity(self, entity, attribute):
        """migrate an entity attribute to the storage"""
        entity.edited_attributes = set()
        self.entity_added(entity, attribute)
        session = entity._cw
        source = session.repo.system_source
        attrs = source.preprocess_entity(entity)
        sql = source.sqlgen.update('cw_' + entity.__regid__, attrs,
                                   ['cw_eid'])
        source.doexec(session, sql, attrs)
208

209
210

class AddFileOp(hook.Operation):
211
    def rollback_event(self):
212
213
214
215
216
        for filepath in self.session.transaction_data.pop('bfss_added'):
            try:
                unlink(filepath)
            except Exception, ex:
                self.error('cant remove %s: %s' % (filepath, ex))
217

218
class DeleteFileOp(hook.Operation):
219
    def commit_event(self):
220
221
222
223
224
        for filepath in self.session.transaction_data.pop('bfss_deleted'):
            try:
                unlink(filepath)
            except Exception, ex:
                self.error('cant remove %s: %s' % (filepath, ex))