~fusion-developers/entropy-store/818855-limit-upload-scheduler

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
"""
Object data store.

This service acts as a cache / access point for a backend object store;
currently Amazon S3 is used as the backend store, but the architecture should
be flexible enough to allow other possibilities. The system is designed to
handle objects in an immutable fashion; once an object is created, it exists in
perpetuity, and the contents will never change.

The service's functionality is two-fold; firstly, it handles requests for
retrieval of objects, servicing them from the local cache, fetching them from a
neighbour cache, or retrieving them from the backend store. Secondly, it
handles requests for storage of a new object; the object is first cached
locally to ensure local view consistency, and then queued for backend storage
in a reliable fashion.
"""
import hashlib

from zope.interface import implements

from epsilon.extime import Time

from axiom.item import Item, transacted
from axiom.attributes import text, path, timestamp, AND, inmemory
from axiom.dependency import dependsOn

from twisted.web import http
from twisted.python.components import registerAdapter

from nevow.inevow import IResource, IRequest
from nevow.static import File
from nevow.rend import NotFound
from nevow.url import URL

from entropy.ientropy import IContentStore, IContentObject
from entropy.errors import CorruptObject, NonexistentObject
from entropy.hash import getHash
from entropy.util import deferred


class ImmutableObject(Item):
    """
    An immutable object.

    Immutable objects are addressed by content hash, and consist of the object
    data as a binary blob, and object key/value metadata pairs.
    """
    implements(IContentObject)

    hash = text(allowNone=False)
    contentDigest = text(allowNone=False)
    content = path(allowNone=False)
    contentType = text(allowNone=False)
    created = timestamp(allowNone=False, defaultFactory=lambda: Time())

    @property
    def metadata(self):
        return {}

    @property
    def objectId(self):
        return u'%s:%s' % (self.hash, self.contentDigest)

    def _getDigest(self):
        fp = self.content.open()
        try:
            h = getHash(self.hash)(fp.read())
            return unicode(h.hexdigest(), 'ascii')
        finally:
            fp.close()

    def verify(self):
        digest = self._getDigest()
        if self.contentDigest != digest:
            raise CorruptObject('expected: %r actual: %r' % (self.contentDigest, digest))

    def getContent(self):
        return self.content.path.getContent()

def objectResource(obj):
    """
    Adapt L{ImmutableObject) to L{IResource}.
    """
    # XXX: Not sure if we should do this on every single resource retrieval.
    obj.verify()
    return File(obj.content.path, defaultType=obj.contentType.encode('ascii'))

registerAdapter(objectResource, ImmutableObject, IResource)


class ContentStore(Item):
    """
    Manager for stored objects.
    """
    implements(IContentStore)

    hash = text(allowNone=False, default=u'sha256')

    # IContentStore

    @deferred
    @transacted
    def storeObject(self, content, contentType, metadata={}, created=None):
        if metadata != {}:
            raise NotImplementedError('metadata not yet supported')

        contentDigest = unicode(getHash(self.hash)(content).hexdigest(), 'ascii')

        obj = self.store.findUnique(ImmutableObject,
                                    AND(ImmutableObject.hash == self.hash,
                                        ImmutableObject.contentDigest == contentDigest),
                                    default=None)
        if obj is None:
            contentFile = self.store.newFile('objects', 'immutable', '%s:%s' % (self.hash, contentDigest))
            try:
                contentFile.write(content)
                contentFile.close()
            except:
                contentFile.abort()
                raise

            obj = ImmutableObject(store=self.store,
                                  contentDigest=contentDigest,
                                  hash=self.hash,
                                  content=contentFile.finalpath,
                                  contentType=contentType)
        else:
            obj.contentType = contentType
            obj.created = created

        return obj.objectId

    def importObject(self, obj):
        """
        Import an object from elsewhere.

        @param obj: the object to import.
        @type obj: IContentObject
        """
        return self.storeObject(obj.getContent(),
                                obj.contentType,
                                obj.metadata,
                                obj.created)

    @deferred
    @transacted
    def getObject(self, objectId):
        hash, contentDigest = objectId.split(u':', 1)
        obj = self.store.findUnique(ImmutableObject,
                                    AND(ImmutableObject.hash == hash,
                                        ImmutableObject.contentDigest == contentDigest),
                                    default=None)
        if obj is None:
            raise NonexistentObject(objectId)
        return obj


class ObjectCreator(object):
    """
    Resource for storing new objects.

    @ivar contentStore: The {IContentStore} provider to create objects in.
    """
    implements(IResource)

    def __init__(self, contentStore):
        self.contentStore = contentStore

    # IResource
    def renderHTTP(self, ctx):
        req = IRequest(ctx)
        if req.method == 'GET':
            return 'PUT data here to create an object.'
        elif req.method == 'PUT':
            return self.handlePUT(req)
        else:
            req.setResponseCode(http.NOT_ALLOWED)
            req.setHeader('Content-Type', 'text/plain')
            return 'Method not allowed'

    def handlePUT(self, req):
        data = req.content.read()
        contentType = unicode(req.getHeader('Content-Type') or 'application/octet-stream', 'ascii')

        contentMD5 = req.getHeader('Content-MD5')
        if contentMD5 is not None:
            expectedHash = contentMD5.decode('base64')
            actualHash = hashlib.md5(data).digest()
            if expectedHash != actualHash:
                raise ValueError('Expected hash %r does not match actual hash %r' % (expectedHash, actualHash))

        def _cb(objectId):
            req.setHeader('Content-Type', 'text/plain')
            objectId = objectId.encode('ascii')
            return objectId

        d = self.contentStore.storeObject(data, contentType)
        return d.addCallback(_cb)


class ContentResource(Item):
    """
    Resource for accessing the content store.
    """
    implements(IResource)
    powerupInterfaces = [IResource]

    addSlash = inmemory()

    contentStore = dependsOn(ContentStore)

    def childFactory(self, name):
        """
        Hook up children.

        / is the root, nothing to see her.

        /new is how new objects are stored.

        /<objectId> is where existing objects are retrieved.
        """
        if name == '':
            return self
        elif name == 'new':
            return ObjectCreator(self.contentStore)
        else:
            try:
                obj = self.contentStore.getObject(name)
            except NonexistentObject:
                pass
            else:
                return obj
        return None

    # IResource
    def renderHTTP(self, ctx):
        """
        Nothing to see here.
        """
        return 'Entropy'

    def locateChild(self, ctx, segments):
        """
        Dispatch to L{childFactory}.
        """
        if len(segments) >= 1:
            res = self.childFactory(segments[0])
            if res is not None:
                return IResource(res), segments[1:]
        return NotFound