# 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

        base_url = self._get_docker_host_base_url(docker_host)
        image_name = self._get_image_name()

        logger.debug('%s %s' % (base_url, image_name))

        token = self._build_image_on_docker_host(
            base_url=base_url,
            build_file=self.build_file,
            dockerfile=self.dockerfile,
            image_name=image_name,
            image_version=self.image.version)
        if not token:
            logger.error("Build image on docker host failed")
            self._update_image_status(status="failed")
            return None
        logger.info('Image %s:%s has been builded, with token %s', image_name,
            self.image.version, token)

        digest = self._push_image_to_registry(base_url, image_name,
            self.image.version, token)
        if not digest:
            logger.error("Push image from docker host to registry failed")
            self._update_image_status(status="failed")
            return None
        logger.info('Image %s:%s has been pushed to registry, with digest %s',
            image_name, self.image.version, digest)

        self._update_image_status(status="active", digest=digest, token=token)


# 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


        base_url = self._get_docker_host_base_url(docker_host)
        image_name = self._get_image_name()

        logger.debug('%s %s' % (base_url, image_name))

        token = self._build_image_on_docker_host(
            base_url=base_url,
            build_file=self.build_file,
            dockerfile=self.dockerfile,
            image_name=image_name,
            image_version=self.image.version)
        if not token:
            logger.error("Build image on docker host failed")
            self._update_image_status(status="failed")
            return None
        logger.info('Image %s:%s has been builded, with token %s', image_name,
            self.image.version, token)

        digest = self._push_image_to_registry(base_url, image_name,
            self.image.version, token)
        if not digest:
            logger.error("Push image from docker host to registry failed")
            self._update_image_status(status="failed")
            return None
        logger.info('Image %s:%s has been pushed to registry, with digest %s',
            image_name, self.image.version, digest)

        self._update_image_status(status="active", digest=digest, token=token)


        remove_file_from_disk(self.build_file)