~launchpad-pqm/launchpad/devel

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
# Copyright 2009-2010 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

__metaclass__ = type

import os
import errno
import hashlib
import shutil
import tempfile

from zope.component import getUtility

from canonical.launchpad.webapp.interfaces import (
        IStoreSelector, MAIN_STORE, DEFAULT_FLAVOR)
from lp.services.database import write_transaction

__all__ = [
    'DigestMismatchError',
    'LibrarianStorage',
    'LibraryFileUpload',
    'DuplicateFileIDError',
    'WrongDatabaseError',
    # _relFileLocation needed by other modules in this package.
    # Listed here to keep the import fascist happy
    '_relFileLocation',
    '_sameFile',
    ]


class DigestMismatchError(Exception):
    """The given digest doesn't match the SHA-1 digest of the file."""


class DuplicateFileIDError(Exception):
    """Given File ID already exists."""


class WrongDatabaseError(Exception):
    """The client's database name doesn't match our database."""

    def __init__(self, clientDatabaseName, serverDatabaseName):
        Exception.__init__(self, clientDatabaseName, serverDatabaseName)
        self.clientDatabaseName = clientDatabaseName
        self.serverDatabaseName = serverDatabaseName


class LibrarianStorage:
    """Blob storage.

    This manages the actual storage of files on disk and the record of those
    in the database; it has nothing to do with the network interface to those
    files.
    """

    def __init__(self, directory, library):
        self.directory = directory
        self.library = library
        self.incoming = os.path.join(self.directory, 'incoming')
        try:
            os.mkdir(self.incoming)
        except OSError, e:
            if e.errno != errno.EEXIST:
                raise

    def hasFile(self, fileid):
        return os.access(self._fileLocation(fileid), os.F_OK)

    def _fileLocation(self, fileid):
        return os.path.join(self.directory, _relFileLocation(str(fileid)))

    def startAddFile(self, filename, size):
        return LibraryFileUpload(self, filename, size)

    def getFileAlias(self, aliasid, token, path):
        return self.library.getAlias(aliasid, token, path)


class LibraryFileUpload(object):
    """A file upload from a client."""
    srcDigest = None
    mimetype = 'unknown/unknown'
    contentID = None
    aliasID = None
    expires = None
    databaseName = None
    debugID = None

    def __init__(self, storage, filename, size):
        self.storage = storage
        self.filename = filename
        self.size = size
        self.debugLog = []

        # Create temporary file
        tmpfile, tmpfilepath = tempfile.mkstemp(dir=self.storage.incoming)
        self.tmpfile = os.fdopen(tmpfile, 'w')
        self.tmpfilepath = tmpfilepath
        self.shaDigester = hashlib.sha1()
        self.md5Digester = hashlib.md5()

    def append(self, data):
        self.tmpfile.write(data)
        self.shaDigester.update(data)
        self.md5Digester.update(data)

    @write_transaction
    def store(self):
        self.debugLog.append('storing %r, size %r'
                             % (self.filename, self.size))
        self.tmpfile.close()

        # Verify the digest matches what the client sent us
        dstDigest = self.shaDigester.hexdigest()
        if self.srcDigest is not None and dstDigest != self.srcDigest:
            # XXX: Andrew Bennetts 2004-09-20: Write test that checks that
            # the file really is removed or renamed, and can't possibly be
            # left in limbo
            os.remove(self.tmpfilepath)
            raise DigestMismatchError(self.srcDigest, dstDigest)

        try:
            # If the client told us the name of the database it's using,
            # check that it matches.
            if self.databaseName is not None:
                store = getUtility(IStoreSelector).get(
                        MAIN_STORE, DEFAULT_FLAVOR)
                result = store.execute("SELECT current_database()")
                databaseName = result.get_one()[0]
                if self.databaseName != databaseName:
                    raise WrongDatabaseError(self.databaseName, databaseName)

            self.debugLog.append(
                'database name %r ok' % (self.databaseName, ))
            # If we haven't got a contentID, we need to create one and return
            # it to the client.
            if self.contentID is None:
                contentID = self.storage.library.add(
                        dstDigest, self.size, self.md5Digester.hexdigest())
                aliasID = self.storage.library.addAlias(
                        contentID, self.filename, self.mimetype, self.expires)
                self.debugLog.append('created contentID: %r, aliasID: %r.'
                                     % (contentID, aliasID))
            else:
                contentID = self.contentID
                aliasID = None
                self.debugLog.append('received contentID: %r' % (contentID, ))

        except:
            # Abort transaction and re-raise
            self.debugLog.append('failed to get contentID/aliasID, aborting')
            raise

        # Move file to final location
        try:
            self._move(contentID)
        except:
            # Abort DB transaction
            self.debugLog.append('failed to move file, aborting')

            # Remove file
            os.remove(self.tmpfilepath)

            # Re-raise
            raise

        # Commit any DB changes
        self.debugLog.append('committed')

        # Return the IDs if we created them, or None otherwise
        return contentID, aliasID

    def _move(self, fileID):
        location = self.storage._fileLocation(fileID)
        if os.path.exists(location):
            raise DuplicateFileIDError(fileID)
        try:
            os.makedirs(os.path.dirname(location))
        except OSError, e:
            # If the directory already exists, that's ok.
            if e.errno != errno.EEXIST:
                raise
        shutil.move(self.tmpfilepath, location)


def _sameFile(path1, path2):
    file1 = open(path1, 'rb')
    file2 = open(path2, 'rb')

    blk = 1024 * 64
    chunksIter = iter(lambda: (file1.read(blk), file2.read(blk)), ('', ''))
    for chunk1, chunk2 in chunksIter:
        if chunk1 != chunk2:
            return False
    return True


def _relFileLocation(file_id):
    """Return the relative location for the given file_id.

    The relative location is obtained by converting file_id into a 8-digit hex
    and then splitting it across four path segments.
    """
    h = "%08x" % int(file_id)
    return '%s/%s/%s/%s' % (h[:2], h[2:4], h[4:6], h[6:])