summaryrefslogtreecommitdiff
path: root/ybd/cache.py
blob: c7f4f2623d852f0407dd4d56783c0e131473cde2 (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
# Copyright (C) 2014-2016 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-2 =*=

import requests

import hashlib
import json
import os
import shutil
from subprocess import call

from ybd import repos, config, utils
from ybd.repos import get_tree
from ybd.utils import log
import tempfile
import yaml
import re


def cache_key(dn):
    return dn['cache']


def cache(dn):
    if get_cache(dn):
        log(dn, "Bah! I could have cached", cache_key(dn))
        return
    tempfile.tempdir = config.config['tmp']
    tmpdir = tempfile.mkdtemp()
    cachefile = os.path.join(tmpdir, cache_key(dn))
    if dn.get('kind') == "system":
        utils.hardlink_all_files(dn['install'], dn['sandbox'])
        shutil.rmtree(dn['checkout'])
        utils.set_mtime_recursively(dn['install'])
        utils.make_deterministic_tar_archive(cachefile, dn['install'])
        shutil.move('%s.tar' % cachefile, cachefile)
    else:
        utils.set_mtime_recursively(dn['install'])
        utils.make_deterministic_gztar_archive(cachefile, dn['install'])
        shutil.move('%s.tar.gz' % cachefile, cachefile)

    unpack(dn, cachefile)
    config.config['counter'].increment()

    if config.config.get('kbas-password', 'insecure') != 'insecure' and \
            config.config.get('kbas-url') is not None:
        if dn.get('kind', 'chunk') in \
                config.config.get('kbas-upload', 'chunk'):
            with utils.timer(dn, 'upload'):
                upload(dn)


def update_manifest(dn, manifest):
    with open(manifest, "a") as m:
        if manifest.endswith('text'):
            format = '%s %s %s %s %s %s\n'
            m.write(format % (dn['name'], dn['cache'],
                              repos.gitmachine.normalize_repo_url(
                                  dn.get('repo', 'None')),
                              dn.get('ref', 'None'),
                              dn.get('unpetrify-ref', 'None'),
                              md5(get_cache(dn))))
            m.flush()
            return

        text = {'name': dn['name'],
                'summary': {'artifact': dn['cache'],
                            'repo': repos.gitmachine.normalize_repo_url(
                                dn.get('repo', None)),
                            'sha': dn.get('ref', None),
                            'ref': dn.get('unpetrify-ref', None),
                            'md5': md5(get_cache(dn))}}
        m.write(yaml.dump(text, default_flow_style=True))
        m.flush()


def unpack(dn, tmpfile):
    if dn.get('kind') != 'system':
        unpackdir = tmpfile + '.unpacked'
        os.makedirs(unpackdir)
        if call(['tar', 'xf', tmpfile, '--directory', unpackdir]):
            log(dn, 'Problem unpacking', tmpfile, exit=True)
    else:
        with open(os.devnull, "w") as fnull:
            if call(['tar', 'tvf', tmpfile], stdout=fnull, stderr=fnull):
                log(dn, 'Problem with tarfile', tmpfile, exit=True)

    try:
        path = os.path.join(config.config['artifacts'], cache_key(dn))
        shutil.move(os.path.dirname(tmpfile), path)
        if not os.path.isdir(path):
            log(dn, 'Problem creating artifact', path, exit=True)

        size = os.path.getsize(get_cache(dn))
        size = re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % size)
        checksum = md5(get_cache(dn))
        log(dn, 'Cached %s bytes %s as' % (size, checksum), cache_key(dn))
        return path
    except:
        log(dn, 'Bah! I raced on', cache_key(dn))
        shutil.rmtree(os.path.dirname(tmpfile))
        return False


def upload(dn):
    cachefile = get_cache(dn)
    url = config.config['kbas-url'] + 'upload'
    params = {"filename": dn['cache'],
              "password": config.config['kbas-password'],
              "checksum": md5(cachefile)}
    with open(cachefile, 'rb') as f:
        try:
            response = requests.post(url=url, data=params, files={"file": f})
            if response.status_code == 201:
                log(dn, 'Uploaded %s to' % dn['cache'], url)
                return
            if response.status_code == 777:
                log(dn, 'Reproduced %s at' % md5(cachefile), dn['cache'])
                config.config['reproduced'].append(
                    [md5(cachefile), dn['cache']])
                return
            if response.status_code == 405:
                # server has different md5 for this artifact
                if dn['kind'] == 'stratum' and config.config['reproduce']:
                    log('BIT-FOR-BIT',
                        'WARNING: reproduction failed for', dn['cache'])
                log(dn, 'Artifact server already has', dn['cache'])
                return
            log(dn, 'Artifact server problem:', response.status_code)
        except:
            pass
        log(dn, 'Failed to upload', dn['cache'])


def get_cache(dn):
    ''' Check if a cached artifact exists for the hashed version of d. '''

    if cache_key(dn) is False:
        return False

    cachedir = os.path.join(config.config['artifacts'], cache_key(dn))
    if os.path.isdir(cachedir):
        call(['touch', cachedir])
        artifact = os.path.join(cachedir, cache_key(dn))
        unpackdir = artifact + '.unpacked'
        if not os.path.isdir(unpackdir) and dn.get('kind') != 'system':
            tempfile.tempdir = config.config['tmp']
            tmpdir = tempfile.mkdtemp()
            if call(['tar', 'xf', artifact, '--directory', tmpdir]):
                log(dn, 'Problem unpacking', artifact)
                return False
            try:
                shutil.move(tmpdir, unpackdir)
            except:
                # corner case... if we are here ybd is multi-instance, this
                # artifact was uploaded from somewhere, and more than one
                # instance is attempting to unpack. another got there first
                pass
        return artifact

    return False


def get_remote(dn):
    ''' If a remote cached artifact exists for d, retrieve it '''
    if config.config.get('last-retry-component') == dn or dn.get('tried'):
        return False

    dn['tried'] = True  # let's not keep asking for this artifact

    if dn.get('kind', 'chunk') not in \
            config.config.get('kbas-upload', 'chunk'):
        return False

    try:
        log(dn, 'Try downloading', cache_key(dn))
        url = config.config['kbas-url'] + 'get/' + cache_key(dn)
        response = requests.get(url=url, stream=True)
    except:
        config.config.pop('kbas-url')
        log(dn, 'WARNING: remote artifact server is not working')
        return False

    if response.status_code == 200:
        try:
            tempfile.tempdir = config.config['tmp']
            tmpdir = tempfile.mkdtemp()
            cachefile = os.path.join(tmpdir, cache_key(dn))
            with open(cachefile, 'wb') as f:
                f.write(response.content)

            return unpack(dn, cachefile)

        except:
            log(dn, 'WARNING: failed downloading', cache_key(dn))

    return False


def cull(artifact_dir):
    tempfile.tempdir = config.config['tmp']
    deleted = 0

    def clear(deleted, artifact_dir):
        artifacts = utils.sorted_ls(artifact_dir)
        for artifact in artifacts:
            stat = os.statvfs(artifact_dir)
            free = stat.f_frsize * stat.f_bavail / 1000000000
            if free >= config.config.get('min-gigabytes', 10):
                log('SETUP', '%sGB is enough free space' % free)
                if deleted > 0:
                    log('SETUP', 'Culled %s items in' % deleted, artifact_dir)
                return True
            path = os.path.join(artifact_dir, artifact)
            if os.path.exists(os.path.join(path, artifact + '.unpacked')):
                path = os.path.join(path, artifact + '.unpacked')
            if os.path.exists(path) and artifact not in config.config['keys']:
                tmpdir = tempfile.mkdtemp()
                shutil.move(path, os.path.join(tmpdir, 'to-delete'))
                app.remove_dir(tmpdir)
                deleted += 1
        return False

    # cull unpacked dirs first
    if clear(deleted, artifact_dir):
        return

    # cull artifacts
    if clear(deleted, artifact_dir):
        return

    stat = os.statvfs(artifact_dir)
    free = stat.f_frsize * stat.f_bavail / 1000000000
    if free < config.config.get('min-gigabytes', 10):
        log('SETUP', '%sGB is less than min-gigabytes:' % free,
            config.config.get('min-gigabytes', 10), exit=True)


def check(artifact):
    try:
        artifact = os.path.join(config.config['artifact-dir'], artifact,
                                artifact)
        checkfile = artifact + '.md5'
        if not os.path.exists(checkfile):
            checksum = md5(artifact)
            with open(checkfile, "w") as f:
                f.write(checksum)

        return(open(checkfile).read())
    except:
        return('================================')


def md5(filename):
    # From http://stackoverflow.com/questions/3431825
    # answer by http://stackoverflow.com/users/370483/quantumsoup
    hash = hashlib.md5()
    try:
        with open(filename, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash.update(chunk)
        return hash.hexdigest()
    except:
        return None