source: rtems-source-builder/source-builder/sb/download.py @ 0a916c3

4.11
Last change on this file since 0a916c3 was f179dc6, checked in by Chris Johns <chrisj@…>, on 06/08/17 at 06:03:15

sb: Backport from master the '--rsb-file=' option.

Upates #3033.

  • Property mode set to 100644
File size: 23.5 KB
Line 
1#
2# RTEMS Tools Project (http://www.rtems.org/)
3# Copyright 2010-2016 Chris Johns (chrisj@rtems.org)
4# All rights reserved.
5#
6# This file is part of the RTEMS Tools package in 'rtems-tools'.
7#
8# Permission to use, copy, modify, and/or distribute this software for any
9# purpose with or without fee is hereby granted, provided that the above
10# copyright notice and this permission notice appear in all copies.
11#
12# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20#
21# This code builds a package given a config file. It only builds to be
22# installed not to be package unless you run a packager around this.
23#
24
25from __future__ import print_function
26
27import hashlib
28import os
29import re
30import stat
31import sys
32try:
33    import urllib.request as urllib_request
34    import urllib.parse as urllib_parse
35except ImportError:
36    import urllib2 as urllib_request
37    import urlparse as urllib_parse
38
39import cvs
40import error
41import git
42import log
43import path
44import sources
45import version
46
47def _do_download(opts):
48    download = True
49    if opts.dry_run():
50        download = False
51        wa = opts.with_arg('download')
52        if wa is not None:
53            if wa[0] == 'with_download' and wa[1] == 'yes':
54                download = True
55    return download
56
57def _humanize_bytes(bytes, precision = 1):
58    abbrevs = (
59        (1 << 50, 'PB'),
60        (1 << 40, 'TB'),
61        (1 << 30, 'GB'),
62        (1 << 20, 'MB'),
63        (1 << 10, 'kB'),
64        (1, ' bytes')
65    )
66    if bytes == 1:
67        return '1 byte'
68    for factor, suffix in abbrevs:
69        if bytes >= factor:
70            break
71    return '%.*f%s' % (precision, float(bytes) / factor, suffix)
72
73def _sensible_url(url, used = 0):
74    space = 200
75    if len(url) > space:
76        size = int(space - 14)
77        url = url[:size] + '...<see log>'
78    return url
79
80def _hash_check(file_, absfile, macros, remove = True):
81    failed = False
82    hash = sources.get_hash(file_.lower(), macros)
83    if hash is not None:
84        hash = hash.split()
85        if len(hash) != 2:
86            raise error.internal('invalid hash format: %s' % (file_))
87        try:
88            hashlib_algorithms = hashlib.algorithms
89        except:
90            hashlib_algorithms = ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']
91        if hash[0] not in hashlib_algorithms:
92            raise error.general('invalid hash algorithm for %s: %s' % (file_, hash[0]))
93        hasher = None
94        _in = None
95        try:
96            hasher = hashlib.new(hash[0])
97            _in = open(path.host(absfile), 'rb')
98            hasher.update(_in.read())
99        except IOError as err:
100            log.notice('hash: %s: read error: %s' % (file_, str(err)))
101            failed = True
102        except:
103            msg = 'hash: %s: error' % (file_)
104            log.stderr(msg)
105            log.notice(msg)
106            if _in is not None:
107                _in.close()
108            raise
109        if _in is not None:
110            _in.close()
111        log.output('checksums: %s: %s => %s' % (file_, hasher.hexdigest(), hash[1]))
112        if hasher.hexdigest() != hash[1]:
113            log.warning('checksum error: %s' % (file_))
114            failed = True
115        if failed and remove:
116            log.warning('removing: %s' % (file_))
117            if path.exists(absfile):
118                try:
119                    os.remove(path.host(absfile))
120                except IOError as err:
121                    raise error.general('hash: %s: remove: %s' % (absfile, str(err)))
122                except:
123                    raise error.general('hash: %s: remove error' % (file_))
124        if hasher is not None:
125            del hasher
126    else:
127        if version.released():
128            raise error.general('%s: no hash found in released RSB' % (file_))
129        log.warning('%s: no hash found' % (file_))
130    return not failed
131
132def _local_path(source, pathkey, config):
133    for p in config.define(pathkey).split(':'):
134        local_prefix = path.abspath(p)
135        local = path.join(local_prefix, source['file'])
136        if source['local'] is None:
137            source['local_prefix'] = local_prefix
138            source['local'] = local
139        if path.exists(local):
140            source['local_prefix'] = local_prefix
141            source['local'] = local
142            _hash_check(source['file'], local, config.macros)
143            break
144
145def _http_parser(source, pathkey, config, opts):
146    #
147    # If the file has not been overrided attempt to recover a possible file name.
148    #
149    if 'file-override' not in source['options']:
150        #
151        # Hack for gitweb.cgi patch downloads. We rewrite the various fields.
152        #
153        if 'gitweb.cgi' in source['url']:
154            url = source['url']
155            if '?' not in url:
156                raise error.general('invalid gitweb.cgi request: %s' % (url))
157            req = url.split('?')[1]
158            if len(req) == 0:
159                raise error.general('invalid gitweb.cgi request: %s' % (url))
160            #
161            # The gitweb.cgi request should have:
162            #    p=<what>
163            #    a=patch
164            #    h=<hash>
165            # so extract the p and h parts to make the local name.
166            #
167            p = None
168            a = None
169            h = None
170            for r in req.split(';'):
171                if '=' not in r:
172                    raise error.general('invalid gitweb.cgi path: %s' % (url))
173                rs = r.split('=')
174                if rs[0] == 'p':
175                    p = rs[1].replace('.', '-')
176                elif rs[0] == 'a':
177                    a = rs[1]
178                elif rs[0] == 'h':
179                    h = rs[1]
180            if p is None or h is None:
181                raise error.general('gitweb.cgi path missing p or h: %s' % (url))
182            source['file'] = '%s-%s.patch' % (p, h)
183        #
184        # Check the source file name for any extra request query data and remove if
185        # found. Some hosts do not like file names containing them.
186        #
187        if '?' in source['file']:
188            qmark = source['file'].find('?')
189            source['file'] = source['file'][:qmark]
190    #
191    # Check local path
192    #
193    _local_path(source, pathkey, config)
194    #
195    # Is the file compressed ?
196    #
197    esl = source['ext'].split('.')
198    if esl[-1:][0] == 'gz':
199        source['compressed-type'] = 'gzip'
200        source['compressed'] = '%{__gzip} -dc'
201    elif esl[-1:][0] == 'bz2':
202        source['compressed-type'] = 'bzip2'
203        source['compressed'] = '%{__bzip2} -dc'
204    elif esl[-1:][0] == 'zip':
205        source['compressed-type'] = 'zip'
206        source['compressed'] = '%{__unzip} -u'
207    elif esl[-1:][0] == 'xz':
208        source['compressed-type'] = 'xz'
209        source['compressed'] = '%{__xz} -dc'
210
211def _patchworks_parser(source, pathkey, config, opts):
212    #
213    # Check local path
214    #
215    _local_path(source, pathkey, config)
216    source['url'] = 'http%s' % (source['path'][2:])
217
218def _git_parser(source, pathkey, config, opts):
219    #
220    # Check local path
221    #
222    _local_path(source, pathkey, config)
223    #
224    # Symlink.
225    #
226    us = source['url'].split('?')
227    source['path'] = path.dirname(us[0])
228    source['file'] = path.basename(us[0])
229    source['name'], source['ext'] = path.splitext(source['file'])
230    if len(us) > 1:
231        source['args'] = us[1:]
232    source['local'] = \
233        path.join(source['local_prefix'], 'git', source['file'])
234    source['symlink'] = source['local']
235
236def _cvs_parser(source, pathkey, config, opts):
237    #
238    # Check local path
239    #
240    _local_path(source, pathkey, config)
241    #
242    # Symlink.
243    #
244    if not source['url'].startswith('cvs://'):
245        raise error.general('invalid cvs path: %s' % (source['url']))
246    us = source['url'].split('?')
247    try:
248        url = us[0]
249        source['file'] = url[url[6:].index(':') + 7:]
250        source['cvsroot'] = ':%s:' % (url[6:url[6:].index('/') + 6:])
251    except:
252        raise error.general('invalid cvs path: %s' % (source['url']))
253    for a in us[1:]:
254        _as = a.split('=')
255        if _as[0] == 'module':
256            if len(_as) != 2:
257                raise error.general('invalid cvs module: %s' % (a))
258            source['module'] = _as[1]
259        elif _as[0] == 'src-prefix':
260            if len(_as) != 2:
261                raise error.general('invalid cvs src-prefix: %s' % (a))
262            source['src_prefix'] = _as[1]
263        elif _as[0] == 'tag':
264            if len(_as) != 2:
265                raise error.general('invalid cvs tag: %s' % (a))
266            source['tag'] = _as[1]
267        elif _as[0] == 'date':
268            if len(_as) != 2:
269                raise error.general('invalid cvs date: %s' % (a))
270            source['date'] = _as[1]
271    if 'date' in source and 'tag' in source:
272        raise error.general('cvs URL cannot have a date and tag: %s' % (source['url']))
273    # Do here to ensure an ordered path, the URL can include options in any order
274    if 'module' in source:
275        source['file'] += '_%s' % (source['module'])
276    if 'tag' in source:
277        source['file'] += '_%s' % (source['tag'])
278    if 'date' in source:
279        source['file'] += '_%s' % (source['date'])
280    for c in '/@#%.-':
281        source['file'] = source['file'].replace(c, '_')
282    source['local'] = path.join(source['local_prefix'], 'cvs', source['file'])
283    if 'src_prefix' in source:
284        source['symlink'] = path.join(source['local'], source['src_prefix'])
285    else:
286        source['symlink'] = source['local']
287
288def _file_parser(source, pathkey, config, opts):
289    #
290    # Check local path
291    #
292    _local_path(source, pathkey, config)
293    #
294    # Get the paths sorted.
295    #
296    source['file'] = source['url'][6:]
297
298parsers = { 'http': _http_parser,
299            'ftp':  _http_parser,
300            'pw':   _patchworks_parser,
301            'git':  _git_parser,
302            'cvs':  _cvs_parser,
303            'file': _file_parser }
304
305def set_release_path(release_path, macros):
306    if release_path is None:
307        release_path = '%{rtems_release_url}/%{rsb_version}/sources'
308    macros.define('release_path', release_path)
309
310def parse_url(url, pathkey, config, opts, file_override = None):
311    #
312    # Split the source up into the parts we need.
313    #
314    source = {}
315    source['url'] = url
316    source['options'] = []
317    colon = url.find(':')
318    if url[colon + 1:colon + 3] != '//':
319        raise error.general('malforned URL (no protocol prefix): %s' % (url))
320    source['path'] = url[:colon + 3] + path.dirname(url[colon + 3:])
321    if file_override is None:
322        source['file'] = path.basename(url)
323    else:
324        bad_chars = [c for c in ['/', '\\', '?', '*'] if c in file_override]
325        if len(bad_chars) > 0:
326            raise error.general('bad characters in file name: %s' % (file_override))
327
328        log.output('download: file-override: %s' % (file_override))
329        source['file'] = file_override
330        source['options'] += ['file-override']
331    source['name'], source['ext'] = path.splitext(source['file'])
332    if source['name'].endswith('.tar'):
333        source['name'] = source['name'][:-4]
334        source['ext'] = '.tar' + source['ext']
335    #
336    # Get the file. Checks the local source directory first.
337    #
338    source['local'] = None
339    for p in parsers:
340        if url.startswith(p):
341            source['type'] = p
342            if parsers[p](source, pathkey, config, opts):
343                break
344    source['script'] = ''
345    return source
346
347def _http_downloader(url, local, config, opts):
348    if path.exists(local):
349        return True
350    #
351    # Hack for GitHub.
352    #
353    if url.startswith('https://api.github.com'):
354        url = urllib_parse.urljoin(url, config.expand('tarball/%{version}'))
355    dst = os.path.relpath(path.host(local))
356    log.output('download: (full) %s -> %s' % (url, dst))
357    log.notice('download: %s -> %s' % (_sensible_url(url, len(dst)), dst))
358    failed = False
359    if _do_download(opts):
360        _in = None
361        _out = None
362        _length = None
363        _have = 0
364        _chunk_size = 256 * 1024
365        _chunk = None
366        _last_percent = 200.0
367        _last_msg = ''
368        _have_status_output = False
369        _url = url
370        try:
371            try:
372                _in = None
373                _ssl_context = None
374                # See #2656
375                _req = urllib_request.Request(_url)
376                _req.add_header('User-Agent', 'Wget/1.16.3 (freebsd10.1)')
377                try:
378                    import ssl
379                    _ssl_context = ssl._create_unverified_context()
380                    _in = urllib_request.urlopen(_req, context = _ssl_context)
381                except:
382                    log.output('download: no ssl context')
383                    _ssl_context = None
384                if _ssl_context is None:
385                    _in = urllib_request.urlopen(_req)
386                if _url != _in.geturl():
387                    _url = _in.geturl()
388                    log.output(' redirect: %s' % (_url))
389                    log.notice(' redirect: %s' % (_sensible_url(_url)))
390                _out = open(path.host(local), 'wb')
391                try:
392                    _length = int(_in.info()['Content-Length'].strip())
393                except:
394                    pass
395                while True:
396                    _msg = '\rdownloading: %s - %s ' % (dst, _humanize_bytes(_have))
397                    if _length:
398                        _percent = round((float(_have) / _length) * 100, 2)
399                        if _percent != _last_percent:
400                            _msg += 'of %s (%0.0f%%) ' % (_humanize_bytes(_length), _percent)
401                    if _msg != _last_msg:
402                        extras = (len(_last_msg) - len(_msg))
403                        log.stdout_raw('%s%s' % (_msg, ' ' * extras + '\b' * extras))
404                        _last_msg = _msg
405                        _have_status_output = True
406                    _chunk = _in.read(_chunk_size)
407                    if not _chunk:
408                        break
409                    _out.write(_chunk)
410                    _have += len(_chunk)
411                log.stdout_raw('\n\r')
412            except:
413                if _have_status_output:
414                    log.stdout_raw('\n\r')
415                raise
416        except IOError as err:
417            log.notice('download: %s: error: %s' % (_sensible_url(_url), str(err)))
418            if path.exists(local):
419                os.remove(path.host(local))
420            failed = True
421        except ValueError as err:
422            log.notice('download: %s: error: %s' % (_sensible_url(_url), str(err)))
423            if path.exists(local):
424                os.remove(path.host(local))
425            failed = True
426        except:
427            msg = 'download: %s: error' % (_sensible_url(_url))
428            log.stderr(msg)
429            log.notice(msg)
430            if _in is not None:
431                _in.close()
432            if _out is not None:
433                _out.close()
434            raise
435        if _out is not None:
436            _out.close()
437        if _in is not None:
438            _in.close()
439            del _in
440        if not failed:
441            if not path.isfile(local):
442                raise error.general('source is not a file: %s' % (path.host(local)))
443            if not _hash_check(path.basename(local), local, config.macros, False):
444                raise error.general('checksum failure file: %s' % (dst))
445    return not failed
446
447def _git_downloader(url, local, config, opts):
448    repo = git.repo(local, opts, config.macros)
449    rlp = os.path.relpath(path.host(local))
450    us = url.split('?')
451    #
452    # Handle the various git protocols.
453    #
454    # remove 'git' from 'git://xxxx/xxxx?protocol=...'
455    #
456    url_base = us[0][len('git'):]
457    for a in us[1:]:
458        _as = a.split('=')
459        if _as[0] == 'protocol':
460            if len(_as) != 2:
461                raise error.general('invalid git protocol option: %s' % (_as))
462            if _as[1] == 'none':
463                # remove the rest of the protocol header leaving nothing.
464                us[0] = url_base[len('://'):]
465            else:
466                if _as[1] not in ['ssh', 'git', 'http', 'https', 'ftp', 'ftps', 'rsync']:
467                    raise error.general('unknown git protocol: %s' % (_as[1]))
468                us[0] = _as[1] + url_base
469    if not repo.valid():
470        log.notice('git: clone: %s -> %s' % (us[0], rlp))
471        if _do_download(opts):
472            repo.clone(us[0], local)
473    else:
474        repo.clean(['-f', '-d'])
475        repo.reset('--hard')
476        repo.checkout('master')
477    for a in us[1:]:
478        _as = a.split('=')
479        if _as[0] == 'branch' or _as[0] == 'checkout':
480            if len(_as) != 2:
481                raise error.general('invalid git branch/checkout: %s' % (_as))
482            log.notice('git: checkout: %s => %s' % (us[0], _as[1]))
483            if _do_download(opts):
484                repo.checkout(_as[1])
485        elif _as[0] == 'submodule':
486            if len(_as) != 2:
487                raise error.general('invalid git submodule: %s' % (_as))
488            log.notice('git: submodule: %s <= %s' % (us[0], _as[1]))
489            if _do_download(opts):
490                repo.submodule(_as[1])
491        elif _as[0] == 'fetch':
492            log.notice('git: fetch: %s -> %s' % (us[0], rlp))
493            if _do_download(opts):
494                repo.fetch()
495        elif _as[0] == 'merge':
496            log.notice('git: merge: %s' % (us[0]))
497            if _do_download(opts):
498                repo.merge()
499        elif _as[0] == 'pull':
500            log.notice('git: pull: %s' % (us[0]))
501            if _do_download(opts):
502                repo.pull()
503        elif _as[0] == 'reset':
504            arg = []
505            if len(_as) > 1:
506                arg = ['--%s' % (_as[1])]
507            log.notice('git: reset: %s' % (us[0]))
508            if _do_download(opts):
509                repo.reset(arg)
510        elif _as[0] == 'protocol':
511            pass
512        else:
513            raise error.general('invalid git option: %s' % (_as))
514    return True
515
516def _cvs_downloader(url, local, config, opts):
517    rlp = os.path.relpath(path.host(local))
518    us = url.split('?')
519    module = None
520    tag = None
521    date = None
522    src_prefix = None
523    for a in us[1:]:
524        _as = a.split('=')
525        if _as[0] == 'module':
526            if len(_as) != 2:
527                raise error.general('invalid cvs module: %s' % (a))
528            module = _as[1]
529        elif _as[0] == 'src-prefix':
530            if len(_as) != 2:
531                raise error.general('invalid cvs src-prefix: %s' % (a))
532            src_prefix = _as[1]
533        elif _as[0] == 'tag':
534            if len(_as) != 2:
535                raise error.general('invalid cvs tag: %s' % (a))
536            tag = _as[1]
537        elif _as[0] == 'date':
538            if len(_as) != 2:
539                raise error.general('invalid cvs date: %s' % (a))
540            date = _as[1]
541    repo = cvs.repo(local, opts, config.macros, src_prefix)
542    if not repo.valid():
543        if not path.isdir(local):
544            log.notice('Creating source directory: %s' % \
545                           (os.path.relpath(path.host(local))))
546            if _do_download(opts):
547                path.mkdir(local)
548            log.notice('cvs: checkout: %s -> %s' % (us[0], rlp))
549            if _do_download(opts):
550                repo.checkout(':%s' % (us[0][6:]), module, tag, date)
551    for a in us[1:]:
552        _as = a.split('=')
553        if _as[0] == 'update':
554            log.notice('cvs: update: %s' % (us[0]))
555            if _do_download(opts):
556                repo.update()
557        elif _as[0] == 'reset':
558            log.notice('cvs: reset: %s' % (us[0]))
559            if _do_download(opts):
560                repo.reset()
561    return True
562
563def _file_downloader(url, local, config, opts):
564    if not path.exists(local):
565        try:
566            src = url[7:]
567            dst = local
568            log.notice('download: copy %s -> %s' % (src, dst))
569            path.copy(src, dst)
570        except:
571            return False
572    return True
573
574downloaders = { 'http': _http_downloader,
575                'ftp':  _http_downloader,
576                'pw':   _http_downloader,
577                'git':  _git_downloader,
578                'cvs':  _cvs_downloader,
579                'file': _file_downloader }
580
581def get_file(url, local, opts, config):
582    if local is None:
583        raise error.general('source/patch path invalid')
584    if not path.isdir(path.dirname(local)) and not opts.download_disabled():
585        log.notice('Creating source directory: %s' % \
586                       (os.path.relpath(path.host(path.dirname(local)))))
587    log.output('making dir: %s' % (path.host(path.dirname(local))))
588    if _do_download(opts):
589        path.mkdir(path.dirname(local))
590    if not path.exists(local) and opts.download_disabled():
591        raise error.general('source not found: %s' % (path.host(local)))
592    #
593    # Check if a URL has been provided on the command line. If the package is
594    # released push to the start the RTEMS URL unless overrided by the command
595    # line option --with-release-url. The variant --without-release-url can
596    # override the released check.
597    #
598    url_bases = opts.urls()
599    try:
600        rtems_release_url_value = config.macros.expand('%{release_path}')
601    except:
602        rtems_release_url_value = None
603        log.output('RTEMS release URL could not be expanded')
604    rtems_release_url = None
605    if version.released() and rtems_release_url_value:
606        rtems_release_url = rtems_release_url_value
607    with_rel_url = opts.with_arg('release-url')
608    if with_rel_url[1] == 'not-found':
609        if config.defined('without_release_url'):
610            with_rel_url = ('without_release-url', 'yes')
611    if with_rel_url[0] == 'with_release-url':
612        if with_rel_url[1] == 'yes':
613            if rtems_release_url_value is None:
614                raise error.general('no valid release URL')
615            rtems_release_url = rtems_release_url_value
616        elif with_rel_url[1] == 'no':
617            pass
618        else:
619            rtems_release_url = with_rel_url[1]
620    elif with_rel_url[0] == 'without_release-url' and with_rel_url[1] == 'yes':
621        rtems_release_url = None
622    if rtems_release_url is not None:
623        log.trace('release url: %s' % (rtems_release_url))
624        #
625        # If the URL being fetched is under the release path do not add the
626        # sources release path because it is already there.
627        #
628        if not url.startswith(rtems_release_url):
629            if url_bases is None:
630                url_bases = [rtems_release_url]
631            else:
632                url_bases.append(rtems_release_url)
633    urls = []
634    if url_bases is not None:
635        #
636        # Split up the URL we are being asked to download.
637        #
638        url_path = urllib_parse.urlsplit(url)[2]
639        slash = url_path.rfind('/')
640        if slash < 0:
641            url_file = url_path
642        else:
643            url_file = url_path[slash + 1:]
644        log.trace('url_file: %s' %(url_file))
645        for base in url_bases:
646            if base[-1:] != '/':
647                base += '/'
648            next_url = urllib_parse.urljoin(base, url_file)
649            log.trace('url: %s' %(next_url))
650            urls.append(next_url)
651    urls += url.split()
652    log.trace('_url: %s -> %s' % (','.join(urls), local))
653    for url in urls:
654        for dl in downloaders:
655            if url.startswith(dl):
656                if downloaders[dl](url, local, config, opts):
657                    return
658    if _do_download(opts):
659        raise error.general('downloading %s: all paths have failed, giving up' % (url))
Note: See TracBrowser for help on using the repository browser.