Created
March 11, 2016 04:53
-
-
Save guenter/b5ff9dc95ef76e00760e to your computer and use it in GitHub Desktop.
Generate Marathon JSON from Docker images.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Generate Marathon JSON from Docker images. | |
Usage: | |
docker2marathon.py [options] <image> | |
docker2marathon.py (-h | --help) | |
Options: | |
--cpus=<shares> CPU shares for this app [default: 0.5] | |
--mem=<megabytes> MB of memory for this app [default: 256] | |
""" | |
import sys | |
import subprocess | |
import codecs | |
import json | |
from docopt import docopt | |
def exec_command(cmd, env=None, stdin=None): | |
"""Execute CLI command | |
:param cmd: Program and arguments | |
:type cmd: [str] | |
:param env: Environment variables | |
:type env: dict | |
:param stdin: File to use for stdin | |
:type stdin: file | |
:returns: A tuple with the returncode, stdout and stderr | |
:rtype: (int, bytes, bytes) | |
""" | |
process = subprocess.Popen( | |
cmd, | |
stdin=stdin, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
env=env) | |
# This is needed to get rid of '\r' from Windows's lines endings. | |
stdout, stderr = [std_stream.replace(b'\r', b'') | |
for std_stream in process.communicate()] | |
return (process.returncode, stdout, stderr) | |
args = docopt(__doc__, version='0.0.1') | |
image = args["<image>"] | |
cpus = float(args["--cpus"]) | |
mem = int(args["--mem"]) | |
print("Pulling Docker image {}".format(image), file=sys.stderr) | |
exec_command(["docker", "pull", image]) | |
print("Inspecting Docker image {}".format(image), file=sys.stderr) | |
code, stdout, stderr = exec_command(["docker", "inspect", image]) | |
image_json = json.loads(stdout.decode(encoding='UTF-8')) | |
portMappings = [{"containerPort": int(k.split("/")[0]), "protocol": k.split("/")[1], "hostPort": 0} for (k, v) in image_json[0]["Config"]["ExposedPorts"].items()] | |
healthChecks = [{"protocol": "TCP", "portIndex": i} for i, portMap in enumerate(portMappings)] | |
appId = image.split(":")[0] | |
marathon_json = { | |
"id": appId, | |
"instances": 1, | |
"cpus": cpus, | |
"mem": mem, | |
"container": { | |
"type": "DOCKER", | |
"docker": { | |
"image": image, | |
"network": "BRIDGE", | |
"portMappings": portMappings | |
} | |
}, | |
"healthChecks": healthChecks | |
} | |
print(json.dumps(marathon_json)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment