python自动探测git提交触发jenkins部署


import requests,json,sqlite3,uuid
import time
import datetime
from Jenkins_Api import jenkins_job_build
from send_email import send_mail_build

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
}

#gitlab地址
git_url='https://git.xxx.com/'
#gitlab的token
git_token='xxxxxxxxxxxxxx'
#收件人(列表)
mailto_list=['[email protected]','[email protected]']           


session = requests.Session()
headers['PRIVATE-TOKEN']=git_token
session.headers = headers
git_login=session.get(git_url,headers=headers)

#增量获取所有工程所有分支的提交日志
def gitlab_project_commits():
    project_branchs_commit_api = git_url + '/api/v4/projects/25/repository/commits?per_page=1&ref_name=test'
    # print(project_branchs_commit_api)
    project_branchs_commit_headers = session.head(project_branchs_commit_api).headers
    project_branchs_commit_api_page=project_branchs_commit_api+'&page=1'
    # print(project_branchs_commit_api_page)
    project_branchs = session.get(project_branchs_commit_api_page).text
    project_branchs_commit_json = json.loads(project_branchs)
    print(project_branchs_commit_json[0])
    project_branch_commit_json = project_branchs_commit_json[0]
    print("分支信息获取完成")
    return project_branch_commit_json

def push_jenkins(job_name,branch):
    # 实例化jenkins对象
    job = jenkins_job_build()
    # 启动构建任务,第二个参数是非必填的,看jenkins任务是否需要传
    item_numb=job.build_jenkins_job(job_name,{"branchName":branch})
    # 获取构建编号
    get_build_number = job.build_number(item_numb)
    #判断任务是否正在构建,如果在构建就等待10秒
    while job.job_is_building(job_name, get_build_number) is True:
        time.sleep(10)
    #构建完成后,获取构建结果
    get_build_status = job.get_job_build_status(job_name,get_build_number)
    return get_build_status

def send_email(email,title,content):
    mailto_list.append(email)
    if send_mail_build().send_mail(mailto_list,title,content):  #邮件主题和邮件内容
        print("send email done!")
        return True
    else:
        print("send email failed!")
        return False


if __name__ == "__main__":

    last_commit_id = ""
    while True:
        time.sleep(10)
        project_branch_commit_json = gitlab_project_commits()
        current_commit_id = project_branch_commit_json['id']
        if current_commit_id != last_commit_id:
            commit_create_at=project_branch_commit_json['created_at']
            commit_create_at= commit_create_at[0:19].replace("T"," ")
            date_time = datetime.datetime.strptime(commit_create_at,'%Y-%m-%d %H:%M:%S')
            date_time +=  datetime.timedelta(minutes=5)
            sleep_time = (date_time - datetime.datetime.now()).total_seconds()
            if sleep_time > 0:
                # 休眠后执行
                time.sleep(sleep_time)
                # 触发jenkins
                pjr = push_jenkins("job_name","test")
                project_branch_commit_json["push_jenkins_result"] = pjr
                ses = send_email(project_branch_commit_json['author_email'],"【Jenkins】自动部署通知",str(project_branch_commit_json));
                print("休眠后执行",ses)
            else:
                # 直接执行
                # 触发jenkins
                pjr = push_jenkins("job_name","test")
                project_branch_commit_json["push_jenkins_result"] = pjr
                ses = send_email(project_branch_commit_json['author_email'],"【Jenkins】自动部署通知",str(project_branch_commit_json));
                print("直接执行",ses)
            last_commit_id = current_commit_id
            print("发布完成")
        print("未发现新的提交")



jenkins_job_build


# -*- coding:utf-8 -*-
import time

import jenkins
 # jenkins地址
jenkins_server_url = 'http://jenkins.xxxx.com/'  
# 登陆jenkins的用户名
user_id = 'admin'    
# 登陆jenkins后,在用户名>设置>API Token,下可以生成一个token
api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  


class jenkins_job_build(object):
    def __init__(self):
        # 初始化jenkins对象,连接远程的jenkins master server
        self.server = jenkins.Jenkins(jenkins_server_url, username=user_id, password=api_token)

    # 启动任务
    def build_jenkins_job(self, job_name,parameters=None):
        item_number = self.server.build_job(job_name,parameters=parameters)
        return item_number   # 返回的是启动任务列队号,不是构建号,下面这个方法才是获取构建编号

    # 获取启动任务对应的构建编号
    def build_number(self,item_number):
        while True:
            time.sleep(1)
            build_info = self.server.get_queue_item(item_number)
            if 'executable' in build_info:
                build_number =build_info['executable']["number"]
                return build_number

    # 获取jenkins任务最后次构建号
    def get_job_lastBuild_number(self, job_name):
        lastBuild_number = self.server.get_job_info(job_name)['lastBuild']['number']
        return lastBuild_number

    # 判断任务是否构建完成,正在构建返回的是True
    def job_is_building(self, job_name, build_number):
        is_building = self.server.get_build_info(job_name, build_number)['building']
        return is_building

    # 获取构建完成后的结果
    def get_job_build_status(self, job_name, build_number):
        job_status = self.server.get_build_info(job_name, build_number)['result']
        return job_status

    # 获取所有正在构建中的jenkins任务
    def get_all_building_jobs(self):
        building_jobs = self.server.get_running_builds()
        return building_jobs

    # 获取所有jenkins任务
    def get_all_jobs(self):
        jobs = self.server.get_jobs()
        return jobs

    # 获取jenkins构建时控制台输出的日志
    def get_build_job_log(self,job_name,job_number):
        return self.server.get_build_console_output(job_name,job_number)

send_mail_build

#! /usr/bin/env python

import smtplib

from email.mime.text import MIMEText

mailto_list=['[email protected]','[email protected]']           #收件人(列表)
mail_host="smtp.163.com"            #使用的邮箱的smtp服务器地址
mail_user="xxxxxx"                           #用户名
mail_pass="xxxxxx"                             #密码
mail_postfix="163.com"                     #邮箱的后缀

class send_mail_build(object):
    def __init__(self):
        self.server = smtplib.SMTP()
        self.server.connect(mail_host)                            #连接服务器
        self.server.login(mail_user,mail_pass)               #登录操作


    def send_mail(self,to_list,sub,content):
        me="jenkins auto push"+"<"+mail_user+"@"+mail_postfix+">"
        msg = MIMEText(content,_subtype='plain')
        msg['Subject'] = sub
        msg['From'] = me
        msg['To'] = ";".join(to_list)                #将收件人列表以‘;’分隔
        try:
            self.server.sendmail(me, to_list, msg.as_string())
            self.server.close()
            return True
        except Exception as e:
            self.server.close()
            print(str(e))
            return False

你可能感兴趣的:(python,jenkins)