예제 #1
0
    def git_code(self):
        log_print("开始git代码...")
        if self.operation == "rollback":
            log_print("不需要拉取代码.")
            return True

        if self.git_branch == None:
            self.git_branch = "master"

        sh.cd('%s/../work_space' % BASE_PATH)
        if os.path.exists(self.deploy_name):
            sh.rm('-fr', self.deploy_name)
        sh.git('clone',
               '-b',
               self.git_branch,
               self.git_uri,
               self.deploy_name,
               _out=process_output)
        sh.cd(self.git_home_path)
        self._git_info()

        log_print("开始mvn编译部分...")
        sh.mvn('clean',
               'package',
               '-U',
               '-Dmaven.test.skip=true',
               _out=process_output)
        if not os.path.exists('target/%s' % self.package_file):
            log_print("mvn编译失败.")
            os._exit(4)
        log_print("mvn编译成功")
        sh.mkdir('docker-work')
예제 #2
0
 def _check_deployment(self, _deploy_name):
     _num = sh.wc(
         sh.kubectl('get', 'pod', '-l', 'app=%s' % _deploy_name, '-n',
                    self.name_space), '-l')
     self.num = int(_num.replace('\n', ""))
     if self.num < 2:
         log_print("%s pod 不存在." % _deploy_name)
         os._exit(4)
예제 #3
0
 def _deployment_var(self):
     _dep_env = os.environ.copy()
     try:
         _dep_env["NAME_SPACE"] = self.name_space
         _dep_env["DEPLOY_NAME"] = self.deploy_name
         _dep_env["IMAGE_ADDRESS"] = self.images_tag
         _dep_env["COMMIT_HASH"] = self.git_hash
     except NameError:
         log_print("yaml 变量为空.")
         os._exit(4)
     return _dep_env
예제 #4
0
    def __init__(self, arg_data):
        self.operation = arg_data['operation']
        self.env = arg_data['env']
        self.project_name = arg_data['project_name']
        self.git_branch = arg_data['branch']
        self.env_tag = arg_data['env_tag']
        self.time_tag = time.strftime('%Y%m%d%H%M%S', time.localtime())
        self.image_addr = "registry-vpc.cn-shenzhen.aliyuncs.com/library"

        for line in open("%s/../code_data/spring_boot_info.txt" % BASE_PATH):
            if re.match(self.project_name, line):
                d = line.replace('\n', '')
                log_print(d)
                __project_name = d.split("|")[0]
                if __project_name == self.project_name:
                    self.git_uri = d.split("|")[1]
                    self.git_home = d.split("|")[2]
                    self.package_file = d.split("|")[3]
                    self.name_space = d.split("|")[4]
                    self.domain = d.split("|")[5]
                break
            self.git_uri = None
        if not self.git_uri:
            log_print('项目信息未找到.')
            os._exit(4)

        if self.env_tag != None and self.env != "prod":
            self.deploy_name = "%s-%s-%s" % (self.env, self.project_name,
                                             self.env_tag)
            self.images_tag = "%s/%s:%s-%s" % (
                self.image_addr, self.project_name, self.env, self.env_tag)
        elif self.env_tag == None and self.env == "prod":
            self.deploy_name = "%s-%s" % (self.env, self.project_name)
            self.images_tag = "%s/%s:%s" % (self.image_addr, self.project_name,
                                            self.time_tag)
        else:
            print("env_tag 参数错误.")
            os._exit(4)

        if self.git_home != "pass":
            self.git_home_path = "%s/../work_space/%s/%s" % (
                BASE_PATH, self.deploy_name, self.git_home)
        else:
            self.git_home_path = "%s/../work_space/%s" % (BASE_PATH,
                                                          self.deploy_name)
예제 #5
0
    def image_create(self):
        log_print("开始docker image 构建部分...")
        _package_file_path = "%s/target/%s" % (self.git_home_path,
                                               self.package_file)
        self.docker_build_dir = '%s/docker-work/' % (self.git_home_path)
        _dorcker_file = '%s/../kubctl_template/springBoot/Dockerfile_template' % BASE_PATH

        # copy Dockerile, copy package_file
        sh.cd(self.docker_build_dir)
        sh.cp('-rp', _dorcker_file, 'Dockerfile')
        sh.cp('-rp', _package_file_path, self.package_file)

        # build images
        _docker_cmd = DockerCmd(self.images_tag, self.package_file,
                                self.deploy_name, self.env)
        _docker_cmd.docker_buil()
        _docker_cmd.docker_push_pull()
        _img_tag = _docker_cmd.docker_image()
        if _img_tag != self.images_tag:
            log_print("镜像构建失败.")
예제 #6
0
    def deployment_update(self):
        if self.env == "prod":
            log_print("prod 环境暂时手动更新, 镜像: %s." % self.images_tag)
            return True

        log_print("开始kubctl apply 部署")
        _deploy_file = '%s/../kubctl_template/springBoot/Deploy_template' % BASE_PATH

        sh.cd(self.docker_build_dir)
        _deploy_env = self._deployment_var()
        self._check_deployment(_deploy_env["DEPLOY_NAME"])

        sh.cp(_deploy_file, 'Deploy_template')
        _dep_file = sh.envsubst(sh.cat('Deploy_template'), _env=_deploy_env)
        _yaml_name = "%s.yaml" % _deploy_env["DEPLOY_NAME"]
        fo = open(_yaml_name, "w")
        for d_file in _dep_file:
            fo.write(d_file)
        fo.close()
        if not os.path.exists(_yaml_name):
            log_print("yaml文件创建失败.")
            os._exit(4)
        log_print("yaml文件创建成功,开始kubctl apply 更新...")
        sh.kubectl('apply', '-f', _yaml_name, _out=process_output)
예제 #7
0
    def ding_ding(self, action=None):
        #url = "https://xxxxxxxxxxxxxxx"
        url = "https://xxxxx"
        headers = {'Content-Type': 'application/json'}

        if action == "start":
            title = "服务部署-开始"
        elif action == "stop":
            log_print("进入360s持续检测...")
            _count = 0
            while (_count < 1):
                time.sleep(120)
                _count = _count + 1
                if self._pod_check() == True:
                    title = "服务部署-成功"
                    break
        try:
            title
        except NameError as ex:
            log_print(ex)
            title = "服务部署-失败"

        text_content = "## %s\n\n>项目: %s\n\n>环境: %s-%s\n\n>域名: %s\n\n>镜像: %s\n\n>分支: %s\n\n>哈希: %s\n\n>描述: %s\n\n>提交: %s" % (
            title, self.project_name, self.env, self.env_tag, self.domain,
            self.images_tag, self.git_branch, self.git_short_hash,
            self.git_message, self.git_cn)
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": text_content
            },
        }

        response = requests.post(url, headers=headers, data=json.dumps(data))
        log_print(response.text)
예제 #8
0
def arg_info():
    parser = argparse.ArgumentParser(description='Automated Deployment')
    parser.add_argument('-o',
                        '--operation',
                        metavar='deploy|RollBACK',
                        type=str,
                        choices=['deploy', 'rollback'],
                        required=True,
                        help='deploy rollback action')

    parser.add_argument('-e',
                        '--env',
                        metavar='dev|fat|uat|pro',
                        type=str,
                        choices=['test', 'fat', 'uat', 'pro'],
                        required=True,
                        help='Acting on the environment')

    parser.add_argument('-n',
                        '--project_name',
                        metavar='apiserver...',
                        type=str,
                        required=True,
                        help='code name')

    parser.add_argument('-c',
                        '--confirm',
                        metavar='apiserver...',
                        type=str,
                        required=True,
                        help='code name confirm')

    parser.add_argument('-b',
                        '--branch',
                        metavar='dev/master.',
                        type=str,
                        help='git branch')

    parser.add_argument('-t',
                        '--env_tag',
                        metavar='01|02|03|04',
                        type=str,
                        help='env tag')

    parser.add_argument('-l',
                        '--language',
                        metavar='node|spingboot',
                        type=str,
                        choices=['nodejs', 'spingboot'],
                        required=True,
                        help='code language')

    _arg_list = parser.parse_args()
    _arg_dict = {}
    _arg_dict['operation'] = _arg_list.operation
    _arg_dict['env'] = _arg_list.env
    _arg_dict['project_name'] = _arg_list.project_name
    _arg_dict['confirm'] = _arg_list.confirm
    _arg_dict['branch'] = _arg_list.branch
    _arg_dict['env_tag'] = _arg_list.env_tag
    _arg_dict['language'] = _arg_list.language

    if _arg_dict['project_name'] != _arg_dict['confirm']:
        log_print("程序名称输入不一致")
        sys.exit(4)

    log_print(_arg_dict)
    return _arg_dict