Ejemplo n.º 1
0
def init_hook(conduit):
    rhnd_data = pickle.load(open("/var/spool/up2date/loginAuth.pkl", "rb"))

    # https://github.com/spacewalkproject/spacewalk/blob/master/client/rhel/yum-rhn-plugin/rhnplugin.py#L298
    rhn_needed_headers = [
        'X-RHN-Server-Id', 'X-RHN-Auth-User-Id', 'X-RHN-Auth',
        'X-RHN-Auth-Server-Time', 'X-RHN-Auth-Expire-Offset'
    ]

    repos = conduit.getRepos()
    cachedir = conduit.getConf().cachedir

    for repo_item in rhnd_data['loginInfo']['X-RHN-Auth-Channels']:
        repo = YumRepository(repo_item[0])
        repo.baseurl = 'https://%s/XMLRPC/GET-REQ/%s' % (
            os.environ['SPACEWALK_HOST'], repo_item[0])
        repo.urls = repo.baseurl
        repo.name = repo_item[0]
        repo.basecachedir = cachedir
        repo.keepcache = 0

        repo.enable()

        for header in rhn_needed_headers:
            # https://github.com/spacewalkproject/spacewalk/blob/master/client/rhel/yum-rhn-plugin/rhnplugin.py#L403
            if len(str(rhnd_data['loginInfo'][header])) > 0:
                repo.http_headers[header] = str(rhnd_data['loginInfo'][header])
            else:
                repo.http_headers[
                    header] = "%s\r\nX-libcurl-Empty-Header-Workaround: *" % rhnd_data[
                        'loginInfo'][header]
        if not repos.findRepos(repo.id):
            repos.add(repo)
    def fetch(self):
        global jws_method, osvendor

        if self.osversion == None:
            raise Exception('OS version not found.')

        if self.hostkey == None or self.hostkey == '00000000000000000000000000000000':
            raise Exception('system hostkey not found.')

        params = {
            'method': jws_method,
            'hostkey': self.hostkey,
            'vendor': osvendor,
            'osname': self.osname,
            'osversion': self.osversion,
            'arch': self.basearch,
            'enablebeta': str(self.enable_beta),
            'software_id': self.software_id
        }

        request = "%s?%s" % (self.request, urllib.urlencode(params))

        hc = httplib.HTTPSConnection(self.url)
        hc.request("GET", request)
        hr = hc.getresponse()
        if hr.status != 200:
            raise Exception('unable to retrieve repository data.')

        buffer = hr.read()
        hc.close()
        response = self.byteify(json.loads(buffer))

        if not response.has_key('code'):
            raise Exception('malformed response.')

        if response['code'] != 0:
            if not response.has_key('errmsg'):
                raise Exception('request failed, error code: %d' %
                                (response['code']))
            else:
                raise Exception('%s Code: %d' %
                                (response['errmsg'], response['code']))

        if response.has_key('community') and response['community'] == 1:
            if not os.path.exists('/var/clearos/registration/verified'):
                repos_to_enable = self.yum_repos.findRepos(
                    'clearos-centos,clearos-centos-updates,clearos-epel,clearos-updates',
                    name_match=True,
                    ignore_case=True)
                repo_status(repos_to_enable, enable=True)
                touch('/var/clearos/registration/verified')

        if not response.has_key('repos'):
            raise Exception('malformed response, missing repos.')

        repos = []
        baseurl = False
        for r in response['repos']:
            repo = Repository(r['name'])
            baserepo = re.sub(r'^clearos-(.*?)(-testing)?$', r'\1', r['name'])
            repo.yumvar = self.conf.yumvar
            repo.name = varReplace(r['description'], repo.yumvar)
            repo.basecachedir = self.conf.cachedir
            repo.base_persistdir = self.conf._repos_persistdir

            if 'mirrorlist' in r:
                repo.setAttribute('mirrorlist',
                                  varReplace(r['mirrorlist'], repo.yumvar))
            else:
                urls = []
                for u in r['baseurl']:
                    url = varReplace(u['url'], repo.yumvar)
                    if len(u['username']) > 0:
                        url = urlparse(u['url'])
                        port = 80
                        if url.port != None:
                            port = url.port
                        url = "%s://%s:%s@%s:%s%s" % (
                            url.scheme, u['username'], u['password'],
                            url.netloc, port, url.path)
                    if u['url'].find('$basearch') < 0:
                        urls.append(url + '/' + self.basearch)
                    else:
                        urls.append(url)
                repo.setAttribute('baseurl', urls)

            repo.setAttribute('enabled', r['enabled'])
            repo.setAttribute('gpgcheck', r['gpgcheck'])
            if 'gpgkey' in r:
                repo.setAttribute('gpgkey', varReplace(r['gpgkey'],
                                                       repo.yumvar))
            if 'sslverify' in r:
                repo.setAttribute('sslverify', r['sslverify'])
            else:
                repo.setAttribute('sslverify', 0)

            if not r['name'].startswith('private-'):
                headers = r.get('header', {})
                headers.update(response.get('header', {}))
                if 'expire' in headers:
                    headers['hostid'] = self.hostkey

                pkgkeys = True
                pkg_headers = {}
                for key, value in headers.iteritems():
                    if key in ['hostid', 'expire', 'key']:
                        repo.http_headers['X-%s' % key.upper()] = value
                    elif key in ['everyting', baserepo]:
                        pkgkeys = False
                        repo.http_headers['X-KEY-%s' % key.upper()] = value
                    else:
                        pkg_headers['X-KEY-%s' % key.upper()] = value

                if pkgkeys:
                    repo.http_headers.update(pkg_headers)
                    group = re.sub(r'^clearos-', r'', r['name'])
                    request = '/pkgapi/%s/%s' % (self.osversion[:1], group)

                    try:
                        hc = httplib.HTTPSConnection('mirrorlist.clearos.com')
                        hc.request("GET", request, None, repo.http_headers)
                        hr = hc.getresponse()
                        if hr.status != 200:
                            raise Exception(
                                'unable to retrieve repository data.')

                        incpkgs = hr.read()
                        hc.close()
                        repo.setAttribute('includepkgs', incpkgs.split())
                    except:
                        pass

                    if not repo.includepkgs:
                        repo.setAttribute('includepkgs', ['None'])

            repos.append(repo)
        return repos