aboutsummaryrefslogtreecommitdiffstats
path: root/python/sandcrawler/fileset_strategies.py
blob: 2577d2b51655d32455166cb3542a212708784fe3 (plain)
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

import os
import sys
import json
import gzip
import time
import shutil
from collections import namedtuple
from typing import Optional, Tuple, Any, Dict, List

import internetarchive

from sandcrawler.html_metadata import BiblioMetadata
from sandcrawler.ia import ResourceResult, WaybackClient, SavePageNowClient, fix_transfer_encoding
from sandcrawler.fileset_types import IngestStrategy, FilesetManifestFile, FilesetPlatformItem, ArchiveStrategyResult, PlatformScopeError
from sandcrawler.misc import gen_file_metadata, gen_file_metadata_path


class FilesetIngestStrategy():

    def __init__(self):
        #self.ingest_strategy = 'unknown'
        pass

    def check_existing(self, item: FilesetPlatformItem) -> Optional[ArchiveStrategyResult]:
        raise NotImplementedError()

    def process(self, item: FilesetPlatformItem) -> ArchiveStrategyResult:
        raise NotImplementedError()


class ArchiveorgFilesetStrategy(FilesetIngestStrategy):

    def __init__(self, **kwargs):
        self.ingest_strategy = IngestStrategy.ArchiveorgFileset

        # XXX: enable cleanup when confident (eg, safe path parsing)
        self.skip_cleanup_local_files = kwargs.get('skip_cleanup_local_files', True)
        self.working_dir = os.environ.get('SANDCRAWLER_WORKING_DIR', '/tmp/sandcrawler/')
        try:
            os.mkdir(self.working_dir)
        except FileExistsError:
            pass

        self.ia_session = internetarchive.get_session()

    def check_existing(self, item: FilesetPlatformItem) -> Optional[ArchiveStrategyResult]:
        """
        use API to check for item with all the files in the manifest

        NOTE: this naive comparison is quadratic in number of files, aka O(N^2)
        """
        ia_item = self.ia_session.get_item(item.archiveorg_item_name)
        if not ia_item.exists:
            return None
        item_files = ia_item.get_files(on_the_fly=False)
        assert item.manifest
        for wanted in item.manifest:
            found = False
            for existing in item_files:
                if existing.name == wanted.path:
                    if ((existing.sha1 and existing.sha1 == wanted.sha1) or (existing.md5 and existing.md5 == wanted.md5)) and existing.name == wanted.path and existing.size == wanted.size:
                        found = True
                        wanted.status = 'exists'
                        break
                    else:
                        wanted.status = 'mismatch-existing'
                        break
            if not found:
                print(f"  item exists ({item.archiveorg_item_name}) but didn't find at least one file: {wanted.path}", file=sys.stderr)
                return None
        return ArchiveStrategyResult(
            ingest_strategy=self.ingest_strategy,
            status='success-existing',
            manifest=item.manifest,
        )

    def process(self, item: FilesetPlatformItem) -> ArchiveStrategyResult:
        """
        May require extra context to pass along to archive.org item creation.
        """
        existing = self.check_existing(item)
        if existing:
            return existing

        if item.platform_name == 'archiveorg':
            raise PlatformScopeError("should't download archive.org into itself")

        local_dir = self.working_dir + item.archiveorg_item_name
        assert local_dir.startswith('/')
        assert local_dir.count('/') > 2
        try:
            os.mkdir(local_dir)
        except FileExistsError:
            pass

        # 1. download all files locally
        assert item.manifest
        for m in item.manifest:
            # XXX: enforce safe/sane filename

            local_path = local_dir + '/' + m.path
            assert m.platform_url

            if not os.path.exists(local_path):
                print(f"  downloading {m.path}", file=sys.stderr)
                with self.ia_session.get(m.platform_url, stream=True, allow_redirects=True) as r:
                    r.raise_for_status()
                    with open(local_path + '.partial', 'wb') as f:
                        for chunk in r.iter_content(chunk_size=256*1024):
                            f.write(chunk)
                os.rename(local_path + '.partial', local_path)
                m.status = 'downloaded-local'
            else:
                m.status = 'exists-local'

            print(f"  verifying {m.path}", file=sys.stderr)
            file_meta = gen_file_metadata_path(local_path, allow_empty=True)
            assert file_meta['size_bytes'] == m.size, f"expected: {m.size} found: {file_meta['size_bytes']}"

            if m.sha1:
                assert file_meta['sha1hex'] == m.sha1
            else:
                m.sha1 = file_meta['sha1hex']

            if m.sha256:
                assert file_meta['sha256hex'] == m.sha256
            else:
                m.sha256 = file_meta['sha256hex']

            if m.md5:
                assert file_meta['md5hex'] == m.md5
            else:
                m.md5 = file_meta['md5hex']

            if m.mimetype:
                # 'magic' isn't good and parsing more detailed text file formats like text/csv
                if file_meta['mimetype'] != m.mimetype and file_meta['mimetype'] != 'text/plain':
                    # these 'tab-separated-values' from dataverse are just noise, don't log them
                    if m.mimetype != 'text/tab-separated-values':
                        print(f"  WARN: mimetype mismatch: expected {m.mimetype}, found {file_meta['mimetype']}", file=sys.stderr)
                    m.mimetype = file_meta['mimetype']
            else:
                m.mimetype = file_meta['mimetype']
            m.status = 'verified-local'

        # 2. upload all files, with metadata
        assert item.archiveorg_item_meta and item.archiveorg_item_meta['collection']
        item_files = []
        for m in item.manifest:
            local_path = local_dir + '/' + m.path
            item_files.append({
                'name': local_path,
                'remote_name': m.path,
            })

        print(f"  uploading all files to {item.archiveorg_item_name} under {item.archiveorg_item_meta.get('collection')}...", file=sys.stderr)
        internetarchive.upload(
            item.archiveorg_item_name,
            files=item_files,
            metadata=item.archiveorg_item_meta,
            checksum=True,
            queue_derive=False,
            verify=True,
        )

        for m in item.manifest:
            m.status = 'success'

        # 4. delete local directory
        if not self.skip_cleanup_local_files:
            shutil.rmtree(local_dir)

        result = ArchiveStrategyResult(
            ingest_strategy=self.ingest_strategy,
            status='success',
            manifest=item.manifest,
        )

        return result

class ArchiveorgFileStrategy(ArchiveorgFilesetStrategy):
    """
    ArchiveorgFilesetStrategy currently works fine with individual files. Just
    need to over-ride the ingest_strategy name.
    """

    def __init__(self):
        super().__init__()
        self.ingest_strategy = IngestStrategy.ArchiveorgFileset

class WebFilesetStrategy(FilesetIngestStrategy):

    def __init__(self, **kwargs):
        self.ingest_strategy = IngestStrategy.WebFileset
        self.wayback_client = WaybackClient()
        self.try_spn2 = True
        self.spn_client = SavePageNowClient(spn_cdx_retry_sec=kwargs.get('spn_cdx_retry_sec', 9.0))

        # XXX: this is copypasta, and also should be part of SPN client, not here
        self.spn2_simple_get_domains = [
            # direct PDF links
            "://arxiv.org/pdf/",
            "://europepmc.org/backend/ptpmcrender.fcgi",
            "://pdfs.semanticscholar.org/",
            "://res.mdpi.com/",

            # platform sites
            "://zenodo.org/",
            "://figshare.org/",
            "://springernature.figshare.com/",

            # popular simple cloud storage or direct links
            "://s3-eu-west-1.amazonaws.com/",
        ]

    def process(self, item: FilesetPlatformItem) -> ArchiveStrategyResult:
        """
        For each manifest item individually, run 'fetch_resource' and record stats, terminal_url, terminal_dt

        TODO:
        - full fetch_resource() method which can do SPN requests
        """

        assert item.manifest
        for m in item.manifest:
            fetch_url = m.platform_url
            if not fetch_url:
                raise NotImplementedError("require 'platform_url' for each file when doing Web fetching")

            via = "wayback"
            resource = self.wayback_client.lookup_resource(fetch_url, m.mimetype)


            if self.try_spn2 and (resource == None or (resource and resource.status == 'no-capture')):
                via = "spn2"
                force_simple_get = 0
                for domain in self.spn2_simple_get_domains:
                    if domain in fetch_url:
                        force_simple_get = 1
                        break
                resource = self.spn_client.crawl_resource(fetch_url, self.wayback_client, force_simple_get=force_simple_get)

            print("[FETCH {:>6}] {}  {}".format(
                    via,
                    (resource and resource.status),
                    (resource and resource.terminal_url) or fetch_url),
                file=sys.stderr)

            m.terminal_url = resource.terminal_url
            m.terminal_dt = resource.terminal_dt
            m.status = resource.status

            if resource.status != 'success':
                continue
            else:
                assert resource.terminal_status_code == 200

            file_meta = gen_file_metadata(resource.body)
            file_meta, html_resource = fix_transfer_encoding(file_meta, resource)

            if file_meta['size_bytes'] != m.size or (m.md5 and m.md5 != file_meta['md5hex']) or (m.sha1 and m.sha1 != file_meta['sha1hex']):
                m.status = 'mismatch'
                continue

            m.md5 = m.md5 or file_meta['md5hex']
            m.sha1 = m.sha1 or file_meta['md5hex']
            m.sha256 = m.sha256 or file_meta['sha256hex']
            m.mimetype = m.mimetype or file_meta['mimetype']

        overall_status = "success"
        for m in item.manifest:
            if m.status != 'success':
                overall_status = m.status or 'not-processed'
                break
        if not item.manifest:
            overall_status = 'empty-manifest'

        result = ArchiveStrategyResult(
            ingest_strategy=self.ingest_strategy,
            status=overall_status,
            manifest=item.manifest,
        )
        return result

class WebFileStrategy(WebFilesetStrategy):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.ingest_strategy = IngestStrategy.WebFile


FILESET_STRATEGY_HELPER_TABLE = {
    IngestStrategy.ArchiveorgFileset: ArchiveorgFilesetStrategy(),
    IngestStrategy.ArchiveorgFile: ArchiveorgFileStrategy(),
    IngestStrategy.WebFileset: WebFilesetStrategy(),
    IngestStrategy.WebFile: WebFileStrategy(),
}