#!/usr/bin/env python

# Note:
#
# Certain Docker images build with newer versions of Docker may not work with the default ENTRYPOINT.
# We are tracking this issue with the docker2aci team here: https://github.com/appc/docker2aci/issues/198
# In the meanwhile, please provide your ENTRYPOINT command explicitly in your `dx-docker run` command.

"""dx-docker Run Docker images in your DNAnexus app."""

import argparse
import sys
import os
import subprocess
import pprint
import json
import multiprocessing.dummy
import tempfile
import glob
import datetime
import dateutil.parser
import dxpy.utils.printing
import dxpy
import urllib
import tarfile
import shutil

CACHE_DIR = '/tmp/dx-docker-cache'

def shell(cmd, ignore_error=False):
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError as e:
        if ignore_error:
            return
        else:
            sys.exit(e.returncode)

def shell_suppress(cmd, ignore_error=False):
    out = ""
    try:
        out = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        print e.output
        if ignore_error:
            pass
        else:
            raise
    return out

def makedirs(path):
    try:
        os.makedirs(path)
    except:  # If the directory already exists, continue gracefully
        pass

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

def get_aci_fname(image):
    matching_files = glob.glob("{cachedir}/{image}.aci".format(cachedir=CACHE_DIR, image=urllib.quote_plus(image)))
    if len(matching_files) == 0:
        return None
    elif len(matching_files) == 1:
        return matching_files[0]
    else:
        raise Exception("dx-docker cache error: Exactly one aci archive should correspond to an image name: {} found archives".format(len(matching_files)))

def extract_aci(acifile):
    tmpdir = tempfile.mkdtemp()
    shell_suppress(["tar", "-xf", acifile, "--exclude", "rootfs/dev/*", "-C", tmpdir], ignore_error=True)
    return tmpdir

def get_aci(image, imgname, prefix="", quiet=False):
    def docker2aci_line(cmd):
        popen = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=open(os.devnull, "w"), universal_newlines=True)
        stderr_lines = iter(popen.stderr.readline, "")
        for stderr_line in stderr_lines:
            yield stderr_line

        popen.stderr.close()
        return_code = popen.wait()
        if return_code != 0:
            raise subprocess.CalledProcessError(return_code, cmd)
    tmpdir = tempfile.mkdtemp()
    os.chdir(tmpdir)
    cmd = ["docker2aci", "-compression", "none", imgname]
    try:
        if quiet:
            shell_suppress(cmd)
        else:
            layers = {}
            for line in docker2aci_line(cmd):
                fields = line.rstrip().split()
                if len(fields) == 7 and fields[0] == "Downloading":
                    _, imghash, downloaded, unita, _, total, unitb = line.rstrip().split()
                else:
                    sys.stderr.write(line)
                    continue
                percent = round(float(downloaded)/float(total),1)
                def print_progress():
                    sys.stderr.write(dxpy.utils.printing.BLUE(imghash)+": "+dxpy.utils.printing.YELLOW("{} {}/{} {}\n".format(downloaded, unita, total, unitb)))
                if imghash not in layers:
                    layers[imghash] = percent
                    if percent == 1:
                        print_progress()
                elif layers[imghash] != percent and percent > 0:
                    print_progress()
                    layers[imghash] = percent
    except Exception as e:
        raise Exception("Failed to obtain image {}.  Does this image exist in the specified repository?\n\n{}".format(image, e))

    img_dirname = prefix+CACHE_DIR
    makedirs(img_dirname)
    os.rename(glob.glob(tmpdir+"/*.aci")[0], img_dirname+"/"+urllib.quote_plus(image)+".aci")
    shutil.rmtree(tmpdir)


def register_docker_subcommand(cmd):
    orig_user_agent = dxpy.USER_AGENT
    dxpy.USER_AGENT += " dx-docker {}".format(cmd)
    dxpy.api.system_greet()
    dxpy.USER_AGENT = orig_user_agent

parser_pull = subparsers.add_parser('pull', help="Pulls a docker image for use in DNAnexus")
parser_pull.add_argument("image", help="image name")
parser_pull.add_argument("-q", "--quiet", action='store_true', help="Suppress printing pull progress to stderr")
def pull(args):
    if not os.path.isdir(CACHE_DIR):
        makedirs(CACHE_DIR)

    get_aci(args.image, "docker://"+args.image, quiet=args.quiet)
parser_pull.set_defaults(func=pull)

parser_run = subparsers.add_parser('run', help="Runs a docker image in a container")
parser_run.add_argument("-v", "--volume", help="Directory to mount inside the container. Can be supplied multiple times (e.g. -v /mnt/data:/mnt/data -v /host:/guest", action='append', default=[])
parser_run.add_argument("-e", "--env", help="Environment variables to set within container. Can be supplied multiple times (e.g. -e foo=bar -e pizza=pie", action='append', default=[])
parser_run.add_argument("--entrypoint",  help="Overwrite default entry point for image")
parser_run.add_argument("-w", "--workdir",  help="Working directory")
parser_run.add_argument("-q", "--quiet",  action='store_true', help="Suppress printing of image metadata")
parser_run.add_argument("--rootfs",  help="Use directory pointed to here for rootfs instead of extracting the image (for expert use/development purposes)")
parser_run.add_argument("--rm",  action="store_true", help="Automatically remove the container when it exits")
parser_run.add_argument("image", help="image name")
parser_run.add_argument("command", help="command to run within container", nargs=argparse.REMAINDER, default=[])
def run(args):
    register_docker_subcommand("run")
    acifile = get_aci_fname(args.image)
    if not acifile:
        pull(parser_pull.parse_args([args.image]))
        acifile = get_aci_fname(args.image)

    if args.rootfs:
        tmpdir = args.rootfs
    else:
        tmpdir = extract_aci(acifile)

    with open("{tmpdir}/manifest".format(tmpdir=tmpdir)) as f:
        imagemeta = json.loads(f.read())

    annotations = {a['name'].split("/")[-1]: a['value'] for a in imagemeta['annotations']}
    labels = {a['name'].split("/")[-1]: a['value'] for a in imagemeta['labels']}
    if not args.quiet:
        def print_annotation(name, key, data=annotations):
            if key in data:
                sys.stderr.write(dxpy.utils.printing.BLUE(name)+"\t"+dxpy.utils.printing.YELLOW(data[key])+"\n")

        stats = {
            'size': shell_suppress(["du", "-sh", tmpdir]).split()[0]
        }

        if 'created' in annotations:
            created_time = dateutil.parser.parse(annotations['created'])
            current_time = datetime.datetime.now(dateutil.tz.tzutc())
            time_since_creation = current_time - created_time
            if (time_since_creation.days == 0 and time_since_creation.seconds < 10*60):
               human_readable_delta = "(just now)"
            else:
               human_readable_delta = "({}d {}h ago)".format(time_since_creation.days, time_since_creation.seconds/3600)
            stats['created'] = annotations['created'] + ' ' + human_readable_delta

        print_annotation("Image Repo", 'repository')
        print_annotation("Image Tag", 'version', data=labels)
        print_annotation("Image Size", 'size', data=stats)
        print_annotation("Image ID", 'imageid')
        print_annotation("Parent ID", 'parentimageid')
        print_annotation("Last Updated", 'created', data=stats)
        print_annotation("Registry", 'registryurl')
        print_annotation("ENTRYPOINT", 'entrypoint')
        print_annotation("Working Dir", 'workingDirectory', data=imagemeta['app'])
        print_annotation("Default CMD", 'cmd')
        sys.stderr.write("\n\n")

    vols = ["/run/shm/:/dev/shm"] + args.volume
    volume = []
    for v in vols:
       volume.append("-b")
       volume.append(v)

    entrypoint = []
    if args.entrypoint:
        entrypoint = [args.entrypoint]
    elif 'entrypoint' in annotations:
        entrypoint = json.loads(annotations['entrypoint'])

    cmd = []
    if args.command:
         cmd = args.command
    elif 'cmd' in annotations and not args.entrypoint:
         cmd = json.loads(annotations['cmd'])

    container_cmd = entrypoint + cmd

    workdir = "/"
    if 'workingDirectory' in imagemeta['app']:
       workdir = imagemeta['app']['workingDirectory']
    if args.workdir:
       workdir = args.workdir

    default_homedir_env = "HOME=/root"
    env = ["env", "-i", default_homedir_env]
    if 'environment' in imagemeta['app']:
        env.extend(args.env + [var['name'] +"="+var['value']  for var in imagemeta['app']['environment']])

    if args.rm and not args.quiet:
        sys.stderr.write(dxpy.utils.printing.YELLOW("--rm: Note that by default the container is not preserved after execution\n"))

    # TODO: implement some form of nested subprocesses to avoid quoting command array if possible
    proot_cmd =  ["proot", "-R", "{tmpdir}/rootfs".format(tmpdir=tmpdir)] + volume + ["-w", workdir] + env + ["/bin/sh", "-c"] + [" ".join(("'"+x+"'" for x in container_cmd))]
    shell(proot_cmd)
    if not args.rootfs:
        shutil.rmtree(tmpdir)
parser_run.set_defaults(func=run)

def local_image_to_aci(image, tmpdir, dirprefix):
    # Ensure core utilities are available on local host
    shell_suppress(["which", "docker"])
    shell_suppress(["which", "docker2aci"])

    # Perform the operations to save and subsequently cache Docker image to the platform
    sys.stderr.write(dxpy.utils.printing.YELLOW("Exporting Docker image {}\n".format(image)))
    docker_tarball = tmpdir+"/image.docker.tgz"
    shell(["docker", "save", "-o", docker_tarball, image])
    get_aci(image, docker_tarball, prefix=dirprefix)

parser_add_to_applet = subparsers.add_parser('add-to-applet', help="Adds a local Docker image to an applet")
parser_add_to_applet.add_argument("image", help="image name")
parser_add_to_applet.add_argument("applet", help="directory corresponding to applet")
def add_to_applet(args):
    register_docker_subcommand("add-to-applet")
    try:
        with open(args.applet+"/dxapp.json") as f:
            json.loads(f.read())
    except Exception as e:
        raise Exception("{} does not appear to have a dxapp.json that parses. Please make sure you have selected a working DNAnexus applet directory\n\n{}.".format(args.applet, e))
    tmpdir = tempfile.mkdtemp()
    local_image_to_aci(args.image, tmpdir, os.path.abspath(args.applet)+"/resources")
    shutil.rmtree(tmpdir)
parser_add_to_applet.set_defaults(func=add_to_applet)

parser_create_asset = subparsers.add_parser('create-asset', help="EXPERIMENTAL: Caches a local Docker image as an asset in the DNAnexus platform (subject to change)")
parser_create_asset.add_argument("--output_path", "-o", help="Project ID and path in project to upload image to (defaults to project root)")
parser_create_asset.add_argument("image", help="image name")
def create_asset(args):
    register_docker_subcommand("create-asset")
    # Create asset
    tmpdir = tempfile.mkdtemp()
    asset_path = tmpdir+"/resources/usr/bin"
    makedirs(asset_path)

    local_image_to_aci(args.image, tmpdir, tmpdir+"/resources")

    imagename = args.image.replace("/", "%").replace(":","#")
    # Create the asset configuration
    dxasset = { 'name': imagename }
    dxasset['title'] = "DNAnexus asset for Docker image "+args.image
    dxasset['description'] = dxasset['title']
    dxasset['version'] = "0.0.1"
    dxasset['distribution'] = "Ubuntu"
    dxasset['release'] = "14.04"
    dxasset['instanceType'] = "mem2_ssd1_x4"
    with open("{}/dxasset.json".format(tmpdir), "w") as f:
        f.write(json.dumps(dxasset))

    project_name = ""
    project_path = ""
    if args.output_path:
        if ":" in args.output_path:
            project_name, project_path = args.output_path.split(":")
            destpath = args.output_path + imagename
        else:
            project_name = dxpy.PROJECT_CONTEXT_ID
            project_path = args.output_path
            destpath = project_name + ":" + args.output_path + imagename
    else:
        project_name = dxpy.PROJECT_CONTEXT_ID
        project_path = ""
        destpath = project_name + ":" + imagename

    sys.stderr.write(dxpy.utils.printing.YELLOW("Building DNAnexus asset for {}\n".format(args.image)))
    escaped_image_name = args.image.replace("/","\\/").replace(":", "\\:")
    image_tarball = imagename+".tar.gz"
    os.chdir(tmpdir)
    with tarfile.open(image_tarball, "w:gz") as tar:
        tar.add(tmpdir+"/resources", "/")
    asset_tarball_id = shell_suppress(["dx", "upload", "--wait", "--brief", "--visibility", "hidden", image_tarball]).rstrip()
    asset_tarball_id = dxpy.upload_local_file(image_tarball, wait_on_close=True, hidden=True).get_id()
    record_name = args.image
    record_details = {"archiveFileId": {"$dnanexus_link": asset_tarball_id}}
    record_properties = {
                          "title": dxasset["title"],
                          "description": dxasset["description"],
                          "version": "0.0.1",
                          "distribution": dxasset["distribution"],
                          "release": dxasset["release"]
                        }
    asset_bundle = dxpy.new_dxrecord(name=record_name,
                                     types=["AssetBundle"], details=record_details,
                                     properties=record_properties, close=True)

    # Add a property called {"AssetBundle": record-xxx} to the hidden tarball
    asset_file = dxpy.DXFile(asset_tarball_id)
    asset_file.set_properties({"AssetBundle": asset_bundle.get_id()})

    # Print output message for successful building of asset
    if project_path == "":
        project_path = "/"
    sys.stderr.write(dxpy.utils.printing.YELLOW("Image {} successfully cached in DNAnexus platform.\n".format(args.image)))
    sys.stderr.write("To include this cached image in an application, please include the following within the runspec/assetDepends list in your dxapp.json.\n")
    sys.stderr.write("    {"+dxpy.utils.printing.BLUE("""
        "project": \"{}\",
        "folder": \"{}\",
        "name": \"{}\",
        "version": "0.0.1"
    """).format(project_name, project_path, args.image)+"}\n")

    # Remove the temporary directory
    shutil.rmtree(tmpdir)

parser_create_asset.set_defaults(func=create_asset)


if __name__ == "__main__":
    args = parser.parse_args()
    args.func(args)
