summaryrefslogtreecommitdiff
path: root/tic/repo.py
blob: a7c09d4be6d382e9858d0c402a931370a1f6f03a (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
#!/usr/bin/python
# Copyright (c) 2016 Samsung Electronics Co., Ltd
#
# Licensed under the Flora License, Version 1.1 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://floralicense.org/license/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Contributors:
# - S-Core Co., Ltd

import logging
import os
import base64
import hashlib
import collections
from lxml import etree
from tic.utils import file
from tic.utils import process
from tic.utils.error import TICError
from tic.utils.grabber import myurlgrab2
from tic.utils import misc
from tic.config import configmgr

REPOMD_EL_PRIMARY = 'primary'
REPOMD_EL_PATTERNS = 'patterns'
REPOMD_EL_COMPS = 'comps'
REPOMD_EL_GROUP = 'group'
REPOMD_EL_TYPE = 'type'
REPOMD_ATTRIB_LOCATION = '%slocation'
REPOMD_ATTRIB_LOCATION = '%sopen-checksum'

def _get_uncompressed_data_from_url(url, filename, proxies=None):
    # download file
    filename = myurlgrab2(url, filename)
    # Check if file compressed or not
    if filename.endswith(".gz"):
        decompress_filename = os.path.splitext(filename)[0]
        filename = file.decompress_gzip(filename, decompress_filename)
    elif filename.endswith(".bz2"):
        process.run(['bunzip2', "-f", filename])
        filename = os.path.splitext(filename)[0]
    return filename

def _get_repodata(baseurl, proxies, tempdir, cachedir, reponame, filehref,
                            sumtype=None, checksum=None):
    logger = logging.getLogger(__name__)
    url = os.path.join(baseurl, filehref)
    filename_tmp = str("%s/%s" % (cachedir, os.path.basename(filehref)))
    if os.path.splitext(filename_tmp)[1] in (".gz", ".bz2"):
        filename = os.path.splitext(filename_tmp)[0]
    else:
        filename = filename_tmp
    if sumtype and checksum and os.path.exists(filename):
        if sumtype == 'sha256':
            file_checksum = hashlib.sha256(open(filename, 'rb').read()).hexdigest()
        elif sumtype == 'md5':
            file_checksum = hashlib.md5(open(filename, 'rb').read()).hexdigest()
        else:
            sumcmd = "%ssum" % sumtype
            result = process.run([sumcmd, filename])[1].strip()
            file_checksum = result.split()[0]
        # use cached file
        if file_checksum and file_checksum == checksum:
            logger.info('use a cache file - ' + str(filename))
            return filename

    temp_file = os.path.join(tempdir, os.path.basename(filehref))
    file_path =_get_uncompressed_data_from_url(url, temp_file, proxies)
    return file.copyfile_flock(file_path, filename)

def get_repodata_from_repos(repos, cachedir):
    logger = logging.getLogger(__name__)
    
    def _set_attrib(ns, key, element):
            fpath_info[key] = element.find(''.join([ns, 'location'])).attrib['href']
            checksum = element.find(''.join([ns, 'open-checksum']))
            checksum_info[key] = checksum.text
            sumtype_info[key] = checksum.attrib['type']
    
    repodata = []
    temp_path = os.path.join(cachedir, 'temp', str(misc.get_timestamp()))
    for repo in repos:
        reponame = repo.get('name')
        baseurl = repo.get('url')

        # make temp_dir
        base64url = base64.urlsafe_b64encode(baseurl)
        temp_dir = os.path.join(temp_path, base64url)
        repomd_file = os.path.join(temp_dir, 'repomd.xml')
        file.make_dirs(temp_dir)

        #TODO: support local files(local directory)
        # local/remote repository 
        url = os.path.join(baseurl, 'repodata/repomd.xml')
        repomd = myurlgrab2(url, repomd_file)

        try:
            tree = etree.parse(repomd)
            t_root = tree.getroot()
        except etree.XMLSyntaxError as e:
            logger.info(e)
            raise TICError(configmgr.message['xml_parse_error'] % ('repomd.xml', url))

        # make cache_dir
        repo_checksum = hashlib.sha256(open(repomd_file, 'rb').read()).hexdigest()
        cache_dir = os.path.join(cachedir, 'cached', base64url, repo_checksum)
        file.make_dirs(cache_dir)
        
        fpath_info = dict()
        checksum_info = dict()
        sumtype_info = dict()

        namespace = t_root.tag
        namespace = namespace[0:namespace.rindex('}')+1]
                
        for element in t_root.findall(''.join([namespace, 'data'])):
            if element.attrib[REPOMD_EL_TYPE] == REPOMD_EL_GROUP:
                # group(comps)
                _set_attrib(namespace, REPOMD_EL_COMPS, element)
            else:
                # type: primary, patterns
                _set_attrib(namespace, element.attrib[REPOMD_EL_TYPE], element)

        for i_name in [REPOMD_EL_PRIMARY, REPOMD_EL_PATTERNS, REPOMD_EL_COMPS]:
            if i_name in fpath_info:
                fpath_info[i_name] = _get_repodata(baseurl,
                                             None,
                                             temp_dir,
                                             cache_dir,
                                             reponame,
                                             fpath_info[i_name],
                                             sumtype_info[i_name],
                                             checksum_info[i_name])
            else:
                fpath_info[i_name] = None
            
        repodata.append({"name":reponame,
                            "baseurl":baseurl,
                            "checksum":repo_checksum,
                            "repomd":repomd,
                            "primary":fpath_info['primary'],
                            "cachedir":cache_dir,
                            "proxies":None,
                            "patterns":fpath_info['patterns'],
                            "comps":fpath_info['comps']})
    return repodata


RepoType = collections.namedtuple('Repo', 'name, url')
def Repo(name, baseurl):
    return RepoType(name, baseurl)