Last active
December 29, 2015 14:13
-
-
Save tawateer/1bd4a4b9495c65bd5afe to your computer and use it in GitHub Desktop.
基础镜像构建脚本
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" 基础镜像构建脚本. | |
会自动构建依赖的镜像, 比如构建基础镜像 centos6, 则以 centos6 开头的镜像都会构建, 比如: | |
centos6-java8 | |
centos6-java8-tomcat8 | |
根据镜像长度判断依赖关系. | |
""" | |
import os | |
import sys | |
import re | |
import logging | |
import argparse | |
import subprocess | |
DOCKER_REGISTRY = "dockerhub.internal.nosa.me" | |
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, | |
format='%(message)s') | |
def shell(cmd, exit=True): | |
process = subprocess.Popen(args=cmd, stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, shell=True) | |
so, se = process.communicate() | |
rc = process.poll() | |
if rc == 0: | |
message = "cmd:%s" % cmd | |
logging.info(message) | |
return so.strip() | |
else: | |
message = "cmd:%s, out:%s, error:%s" % (cmd, so, se) | |
logging.error(message) | |
if exit == True: | |
sys.exit(1) | |
else: | |
return False | |
def list_subdirs(dir): | |
for root, subdirs, files in os.walk(dir): | |
return subdirs | |
def build(dir, name, tag=None): | |
if tag is None: | |
path = "{docker_registry}/{name}".format( | |
docker_registry=DOCKER_REGISTRY, name=name) | |
else: | |
path = "{docker_registry}/{name}:{tag}".format( | |
docker_registry=DOCKER_REGISTRY, name=name, tag=tag) | |
cmd = "cd {dir} && docker build --rm=true -t {path} . && docker push {path}".format( | |
dir=dir, path=path) | |
shell(cmd) | |
def main(): | |
parser = argparse.ArgumentParser(description='build base image') | |
parser.add_argument( | |
'-n', '--name', required=True, type=str, help='image name') | |
args = parser.parse_args() | |
# log image name. | |
logging.info("name:%s" % args.name) | |
# get images will be built. | |
dirs = list_subdirs(os.getcwd()) | |
def match(s): | |
if re.match("^%s" % args.name, s) is None: | |
return False | |
else: | |
return True | |
names = filter(match, dirs) | |
# sort images by name length. | |
names.sort(key=lambda i: len(i)) | |
# log image names. | |
logging.info("names:%s" % names) | |
# build image. | |
for name in names: | |
build(name, name) | |
logging.info("build %s succ" % name) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment