# Path: backend/models.py
# class Image(models.Model):
#     """
#     Image represents the model of every application, and there are many
#     different version images in every application.
#     """
#     STATUS_CHOICES = (
#         ('deleted', 'deleted'),
#         ('deleting', 'deleting'),
#         ('active', 'active'),
#         ('creating', 'creating'),
#         ('failed', 'failed')
#     )
# 
#     user = models.ForeignKey(MyUser,  on_delete=models.CASCADE, null=True,
#         default=True)
#     project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
#         default=True)
# 
#     name = models.CharField(max_length=32, default='')
#     desc = models.TextField(max_length=256, null=True)
#     version = models.CharField(max_length=32)
#     digest = models.CharField(max_length=64, blank=True, null=True, default='')
#     token = models.CharField(max_length=64, blank=True, null=True, default='')
#     is_public = models.BooleanField(default=False)
#     status = models.CharField(max_length=16, choices=STATUS_CHOICES,
#         default='creating')
#     create_time = models.DateTimeField(auto_now=True)
# 
# Path: backend/utils.py
# def fetch_digest_from_response(response):
#     """
#     Fetch the image digest from response when push image from docker host to
#     private registry.
#     """
#     # logger.debug(response)
#     res = json.loads(response.decode())
#     items = res.get('status').split(' ')
#     res = [item for item in items if item.startswith('sha256:')]
#     digest = res[0].split(':')[-1]
# 
#     return digest
# 
# def get_optimal_docker_host():
#     """
#     Returns the optimal docker host to build image.
#     """
#     scheduler = DockerSchedulerFactory.get_scheduler()
#     docker_host = scheduler.get_optimal_docker_host()
#     return docker_host
# 
# def remove_file_from_disk(filename):
#     """
#     Delete the file from disk.
#     """
#     if os.path.exists(filename):
#         os.remove(filename)
# 
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
#     """
#     Factory of DockerScheduler, to use the only one scheduler allways.
#     """
#     _scheduler = None
# 
#     @classmethod
#     def get_scheduler(self):
#         if not self._scheduler:
#             self._scheduler = DockerScheduler(settings.MASTER_IP,
#                 settings.ETCD_PORT)
#         return self._scheduler


import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
    remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory
        Delete image from docker host if exists image called
        image_name:image_version.
        """
        image_complete_name = '%s:%s' %(image_name, image_version)
        client = Client(base_url=base_url)
        try:
            client.remove_image(image=image_complete_name, force=True)
        except Exception:
            logger.info('There is no image called %s on docker host %s' %
                (image_complete_name, base_url))
            return None

        logger.info('Image %s on docker host %s has been deleted.' %
                (image_complete_name, base_url))

    def _get_docker_host_base_url(self, host):
        """
        Returns the base url of docker host.
        """
        return 'tcp://%s:%s' % (host, str(settings.DOCKER_PORT))


class ImageCloner(object):
    """
    ImageCloner is to clone a public image into private project.
    """
    public_image = None
    private_image = None

    def __init__(self, puid, prid):

# Path: backend/models.py
# class Image(models.Model):
#     """
#     Image represents the model of every application, and there are many
#     different version images in every application.
#     """
#     STATUS_CHOICES = (
#         ('deleted', 'deleted'),
#         ('deleting', 'deleting'),
#         ('active', 'active'),
#         ('creating', 'creating'),
#         ('failed', 'failed')
#     )
# 
#     user = models.ForeignKey(MyUser,  on_delete=models.CASCADE, null=True,
#         default=True)
#     project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True,
#         default=True)
# 
#     name = models.CharField(max_length=32, default='')
#     desc = models.TextField(max_length=256, null=True)
#     version = models.CharField(max_length=32)
#     digest = models.CharField(max_length=64, blank=True, null=True, default='')
#     token = models.CharField(max_length=64, blank=True, null=True, default='')
#     is_public = models.BooleanField(default=False)
#     status = models.CharField(max_length=16, choices=STATUS_CHOICES,
#         default='creating')
#     create_time = models.DateTimeField(auto_now=True)
# 
# Path: backend/utils.py
# def fetch_digest_from_response(response):
#     """
#     Fetch the image digest from response when push image from docker host to
#     private registry.
#     """
#     # logger.debug(response)
#     res = json.loads(response.decode())
#     items = res.get('status').split(' ')
#     res = [item for item in items if item.startswith('sha256:')]
#     digest = res[0].split(':')[-1]
# 
#     return digest
# 
# def get_optimal_docker_host():
#     """
#     Returns the optimal docker host to build image.
#     """
#     scheduler = DockerSchedulerFactory.get_scheduler()
#     docker_host = scheduler.get_optimal_docker_host()
#     return docker_host
# 
# def remove_file_from_disk(filename):
#     """
#     Delete the file from disk.
#     """
#     if os.path.exists(filename):
#         os.remove(filename)
# 
# Path: backend/schedule.py
# class DockerSchedulerFactory(object):
#     """
#     Factory of DockerScheduler, to use the only one scheduler allways.
#     """
#     _scheduler = None
# 
#     @classmethod
#     def get_scheduler(self):
#         if not self._scheduler:
#             self._scheduler = DockerScheduler(settings.MASTER_IP,
#                 settings.ETCD_PORT)
#         return self._scheduler


# Path: backend/image.py
import logging, json
from threading import Thread
from django.conf import settings
from docker import Client
from docker.errors import APIError
from backend.models import Image
from backend.utils import (fetch_digest_from_response, get_optimal_docker_host,
    remove_file_from_disk)
from backend.schedule import DockerSchedulerFactory

        Delete image from docker host if exists image called
        image_name:image_version.
        """
        image_complete_name = '%s:%s' %(image_name, image_version)
        client = Client(base_url=base_url)
        try:
            client.remove_image(image=image_complete_name, force=True)
        except Exception:
            logger.info('There is no image called %s on docker host %s' %
                (image_complete_name, base_url))
            return None

        logger.info('Image %s on docker host %s has been deleted.' %
                (image_complete_name, base_url))

    def _get_docker_host_base_url(self, host):
        """
        Returns the base url of docker host.
        """
        return 'tcp://%s:%s' % (host, str(settings.DOCKER_PORT))


class ImageCloner(object):
    """
    ImageCloner is to clone a public image into private project.
    """
    public_image = None
    private_image = None

    def __init__(self, puid, prid):

        self.public_image = Image.objects.get(id=puid)