import logging
import requests
import time

from reprounzip.parameters import _bundled_parameters
from reprounzip.utils import itervalues


logger = logging.getLogger(__name__)


def _vagrant_req(method, url, json):
    headers = {'User-Agent': 'reprozip testsuite'}
    if json:
        headers['Accept'] = 'application/json'
    for _ in range(5):
        res = requests.request(
            method,
            url,
            headers=headers,
            allow_redirects=True,
        )
        if res.status_code == 429:
            logger.info("(got 429, sleeping)")
            time.sleep(60)
        else:
            return res


def check_vagrant():
    error = False

    # Get all Vagrant boxes from bundled parameters
    boxes = set()
    for distribution in itervalues(
        _bundled_parameters['vagrant_boxes']['boxes'],
    ):
        for version in distribution['versions']:
            for image in itervalues(version['architectures']):
                boxes.add(image)

    # Check that they exist
    for box in boxes:
        # Get metadata
        url = 'https://vagrantcloud.com/' + box
        metadata = _vagrant_req(
            'GET',
            url,
            True,
        )
        if metadata.status_code != 200:
            logger.error(
                "Vagrant box not found: %d %s",
                metadata.status_code, url,
            )
            error = True
            continue
        metadata = metadata.json()

        # Find most recent version
        versions = [
            v for v in metadata.get('versions', ())
            if v.get('status') == 'active'
        ]
        if not versions:
            logger.error("No versions for Vagrant box %s", box)
            error = True
            continue
        max_version = max(metadata['versions'], key=lambda v: v['version'])

        # Go over each provider
        for provider in max_version['providers']:
            url = provider['url']
            res = _vagrant_req(
                'HEAD',
                url,
                False,
            )
            # Status should be 200
            if res.status_code != 200:
                logger.error(
                    "Got %d getting Vagrant box %s: %s",
                    res.status_code, box, url,
                )
                error = True
            # Content-Type should not start with "text/" (but can be unset)
            elif res.headers.get('Content-Type', '').startswith('text/'):
                logger.error(
                    "Got type %s getting Vagrant box %s: %s",
                    res.headers['Content-Type'], box, url,
                )
                error = True
            # Size should be at least 10 MB
            elif int(res.headers.get('Content-Length', 1E8)) < 1E7:
                logger.error(
                    "Got file size %s getting Vagrant box %s: %s",
                    res.headers['Content-Length'], box, url,
                )
                error = True
            else:
                logger.info("Vagrant box ok: %s (%s)", box, provider['name'])

    if error:
        raise AssertionError("Missing Vagrant boxes")


def check_docker():
    pass

@@ -130,16 +130,27 @@
 ervalues
+, iteritems
 %0A%0A%0Alogge
@@ -3187,9 +3187,2081 @@
     
-pass
+error = False%0A%0A    # Get all Docker images from bundled parameters%0A    images = set()%0A    for distribution in itervalues(%0A        _bundled_parameters%5B'docker_images'%5D%5B'images'%5D,%0A    ):%0A        for version in distribution%5B'versions'%5D:%0A            images.add(version%5B'image'%5D)%0A%0A    # Rewrite images in canonical format, organize by repository%0A    repositories = %7B%7D%0A    for image in images:%0A        image = image.split('/')%0A        if ':' in image%5B-1%5D:%0A            image%5B-1%5D, tag = image%5B-1%5D.split(':', 1)%0A        else:%0A            tag = 'latest'%0A        if len(image) == 1:%0A            image = %5B'docker.io', 'library'%5D + image%0A        elif len(image) == 2:%0A            image = %5B'docker.io'%5D + image%0A        repositories.setdefault(tuple(image%5B:3%5D), set()).add(tag)%0A%0A    # Check that each repository has the required tags%0A    for repository, tags in iteritems(repositories):%0A        registry = repository%5B0%5D%0A        if registry == 'docker.io':%0A            registry = 'hub.docker.com'%0A        else:%0A            raise AssertionError(%22Registry unsupported: %25s%22 %25 registry)%0A        url = (%0A            'https://' + registry%0A            + '/v1/repositories/' + repository%5B1%5D%0A            + '/' + repository%5B2%5D%0A            + '/tags'%0A        )%0A        res = requests.get(url)%0A        if res.status_code != 200:%0A            logger.error(%0A                %22Docker repository not found: %25d %25s%22,%0A                res.status_code,%0A                url,%0A            )%0A            error = True%0A            continue%0A        actual_tags = res.json()%0A        actual_tags = set(entry%5B'name'%5D for entry in actual_tags)%0A        for tag in tags:%0A            if tag not in actual_tags:%0A                logger.error(%0A                    %22Docker repository %25s missing tag %25s%22,%0A                    '/'.join(repository),%0A                    tag,%0A                )%0A            else:%0A                logger.info(%0A                    %22Docker image ok: %25s:%25s%22,%0A                    '/'.join(repository),%0A                    tag,%0A                )%0A%0A    if error:%0A        raise AssertionError(%22Missing Docker boxes%22)
 %0A

Implement checking Docker images