# Path: slicer_cli_web/girder_worker_plugin/cli_progress.py
# class CLIProgressCLIWriter(StreamWriter):
#     def __init__(self, job_manager):
#         super(CLIProgressCLIWriter, self).__init__()
# 
#         self._job_manager = job_manager
#         self._buf = b''
#         self._state = None
#         re_start = re.compile('<filter-start>.*</filter-start>[\\s]*', re.MULTILINE | re.DOTALL)
#         re_end = re.compile('<filter-end>.*</filter-end>[\\s]*', re.MULTILINE | re.DOTALL)
#         re_time = re.compile('<filter-time>[^<]*</filter-time>[\\s]*', re.MULTILINE)
#         re_stage_progress = re.compile(
#             '<filter-stage-progress>[^<]*</filter-stage-progress>[\\s]*', re.MULTILINE)
# 
#         self._re_progress = re.compile('<filter-progress>([^<]*)</filter-progress>[\\s]*',
#                                        re.MULTILINE)
#         self._re_name = re.compile('<filter-name>([^<]*)</filter-name>[\\s]*', re.MULTILINE)
#         self._re_comment = re.compile('<filter-comment>([^<]*)</filter-comment>[\\s]*',
#                                       re.MULTILINE)
# 
#         self._re_clean = [re_start, re_end, re_time, re_stage_progress, self._re_progress,
#                           self._re_name, self._re_comment]
# 
#         self._last_name = 'Unknown'
#         self._last_comment = ''
# 
#     def forward(self, buf):
#         self._job_manager.write(buf)
# 
#     def write(self, buf):
#         act = self._buf + buf
#         self.buf = b''
# 
#         if b'</filter-' not in act:
#             if b'<filter-' in act:
#                 # cache for next time
#                 self._buf = act
#                 return
#             return self.forward(act)
# 
#         t = act.decode('utf-8')
# 
#         self._update(t)
# 
#         for clean in self._re_clean:
#             if not t:
#                 break
#             t = clean.sub('', t)
#         if t:
#             self.forward(t.encode('utf-8'))
# 
#     def _update(self, text):
#         name = self._re_name.findall(text)
#         comment = self._re_comment.findall(text)
#         progress = self._re_progress.findall(text)
# 
#         if name:
#             self._last_name = name[-1].strip()
#         if comment:
#             self._last_comment = comment[-1].strip()
# 
#         msg = self._last_name
#         if self._last_comment:
#             msg = '%s: %s' % (msg, self._last_comment)
# 
#         if progress:
#             val = float(progress[-1])
#             self._job_manager.updateProgress(total=1, current=val, message=msg)
# 
#     def close(self):
#         # flush rest
#         if self._buf:
#             self.forward(self._buf)
#             self._buf = ''


from os import access, R_OK
from os.path import basename, isfile, abspath, join
from girder_worker.app import app
from girder_worker.docker.transforms import BindMountVolume, ContainerStdOut
from girder_worker.docker.io import FDReadStreamConnector
from girder_worker.docker.transforms.girder import GirderFileIdToVolume
from girder_worker.docker.tasks import _docker_run, DockerTask
from girder_worker_utils import _walk_obj
from girder_worker_utils.transforms.girder_io import GirderClientTransform
from .cli_progress import CLIProgressCLIWriter
    from docker.errors import ImageNotFound
    import docker


def _has_image(image):
    """
    Pulls the specified Docker image onto this worker if not already present
    """

    client = docker.from_env(version='auto')
    try:
        client.images.get(image)
        return True
    except ImageNotFound:
        return False
    finally:
        # close docker client to flush any caches
        client.close()


@app.task(base=DirectDockerTask, bind=True)
def run(task, **kwargs):
    """Wraps docker_run to support direct mount volumnes."""

    pull_image = kwargs.get('pull_image')
    if pull_image == 'if-not-present':
        kwargs['pull_image'] = not _has_image(kwargs['image'])

    if hasattr(task, 'job_manager'):
        stream_connectors = kwargs.setdefault('stream_connectors', [])
        stream_connectors.append(FDReadStreamConnector(
            input=ContainerStdOut(),

# Path: slicer_cli_web/girder_worker_plugin/cli_progress.py
# class CLIProgressCLIWriter(StreamWriter):
#     def __init__(self, job_manager):
#         super(CLIProgressCLIWriter, self).__init__()
# 
#         self._job_manager = job_manager
#         self._buf = b''
#         self._state = None
#         re_start = re.compile('<filter-start>.*</filter-start>[\\s]*', re.MULTILINE | re.DOTALL)
#         re_end = re.compile('<filter-end>.*</filter-end>[\\s]*', re.MULTILINE | re.DOTALL)
#         re_time = re.compile('<filter-time>[^<]*</filter-time>[\\s]*', re.MULTILINE)
#         re_stage_progress = re.compile(
#             '<filter-stage-progress>[^<]*</filter-stage-progress>[\\s]*', re.MULTILINE)
# 
#         self._re_progress = re.compile('<filter-progress>([^<]*)</filter-progress>[\\s]*',
#                                        re.MULTILINE)
#         self._re_name = re.compile('<filter-name>([^<]*)</filter-name>[\\s]*', re.MULTILINE)
#         self._re_comment = re.compile('<filter-comment>([^<]*)</filter-comment>[\\s]*',
#                                       re.MULTILINE)
# 
#         self._re_clean = [re_start, re_end, re_time, re_stage_progress, self._re_progress,
#                           self._re_name, self._re_comment]
# 
#         self._last_name = 'Unknown'
#         self._last_comment = ''
# 
#     def forward(self, buf):
#         self._job_manager.write(buf)
# 
#     def write(self, buf):
#         act = self._buf + buf
#         self.buf = b''
# 
#         if b'</filter-' not in act:
#             if b'<filter-' in act:
#                 # cache for next time
#                 self._buf = act
#                 return
#             return self.forward(act)
# 
#         t = act.decode('utf-8')
# 
#         self._update(t)
# 
#         for clean in self._re_clean:
#             if not t:
#                 break
#             t = clean.sub('', t)
#         if t:
#             self.forward(t.encode('utf-8'))
# 
#     def _update(self, text):
#         name = self._re_name.findall(text)
#         comment = self._re_comment.findall(text)
#         progress = self._re_progress.findall(text)
# 
#         if name:
#             self._last_name = name[-1].strip()
#         if comment:
#             self._last_comment = comment[-1].strip()
# 
#         msg = self._last_name
#         if self._last_comment:
#             msg = '%s: %s' % (msg, self._last_comment)
# 
#         if progress:
#             val = float(progress[-1])
#             self._job_manager.updateProgress(total=1, current=val, message=msg)
# 
#     def close(self):
#         # flush rest
#         if self._buf:
#             self.forward(self._buf)
#             self._buf = ''


# Path: slicer_cli_web/girder_worker_plugin/direct_docker_run.py
from os import access, R_OK
from os.path import basename, isfile, abspath, join
from girder_worker.app import app
from girder_worker.docker.transforms import BindMountVolume, ContainerStdOut
from girder_worker.docker.io import FDReadStreamConnector
from girder_worker.docker.transforms.girder import GirderFileIdToVolume
from girder_worker.docker.tasks import _docker_run, DockerTask
from girder_worker_utils import _walk_obj
from girder_worker_utils.transforms.girder_io import GirderClientTransform
from .cli_progress import CLIProgressCLIWriter
    from docker.errors import ImageNotFound
    import docker



def _has_image(image):
    """
    Pulls the specified Docker image onto this worker if not already present
    """

    client = docker.from_env(version='auto')
    try:
        client.images.get(image)
        return True
    except ImageNotFound:
        return False
    finally:
        # close docker client to flush any caches
        client.close()


@app.task(base=DirectDockerTask, bind=True)
def run(task, **kwargs):
    """Wraps docker_run to support direct mount volumnes."""

    pull_image = kwargs.get('pull_image')
    if pull_image == 'if-not-present':
        kwargs['pull_image'] = not _has_image(kwargs['image'])

    if hasattr(task, 'job_manager'):
        stream_connectors = kwargs.setdefault('stream_connectors', [])
        stream_connectors.append(FDReadStreamConnector(
            input=ContainerStdOut(),

            output=CLIProgressCLIWriter(task.job_manager)