Jenkins API 调研


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import requests
import json

USERNAME = "xx"
API_TOKEN = "xx"
JENKINS_URL = "http://192.168.5.112:8080/"

def postJenkins(url, params={}):
res = requests.post(f"{url}/api/json?pretty=true", params, auth=(USERNAME, API_TOKEN), verify=False)
return res

def postJenkinsJson(url, params={}):
res = postJenkins(url, params)
return res.json()

def postJenkinsText(url, params={}):
res = postJenkins(url, params)
return res.text()

def dev2build(projectName = 'ppfe-dev2',params={}):
# 使用指定参数构建
# params = {'branchName': 'origin/release/test'}
# 使用默认参数构建
# params = {}
url = f"{JENKINS_URL}job/{projectName}/buildWithParameters"
build(url, params)

def build(url, params={}):
res = postJenkins(url, params)
# 201 为构建成功
if res.status_code == 201:
print('构建成功')
else:
print('构建失败')

def getProjectInfo(projectViewName='pp-dev2', projectName = 'ppfe-dev2'):
url = f"{JENKINS_URL}view/{projectViewName}/job/{projectName}"
jsonObj = postJenkinsJson(url)

# 参数
resParameterDefinitions = jsonObj['actions'][0]['parameterDefinitions'][0]
# 默认分支
resDefaultBranch = resParameterDefinitions['defaultParameterValue']['value']
# 所有分支
resAllBranch = resParameterDefinitions['allValueItems']['values']
# 基础信息
resUrl = jsonObj['url']
resName = jsonObj['name']
resDescription = jsonObj['description']
# 是否可构建
resBuildable = jsonObj['buildable']
# 是否在队列中
resInQueue = jsonObj['inQueue']
# 构建记录
resBuilds = jsonObj['builds']
# 最后一次构建
resLastBuild = jsonObj['lastBuild']
# 最后一次成功构建
resLastSuccessfulBuild = jsonObj['lastSuccessfulBuild']
# 下一次构建号
resNextBuildNumber = jsonObj['nextBuildNumber']

return {
'url': resUrl,
'name': resName,
'description': resDescription,
'buildable': resBuildable,
'inQueue': resInQueue,
'builds': resBuilds,
'lastBuild': resLastBuild,
'lastSuccessfulBuild': resLastSuccessfulBuild,
'nextBuildNumber': resNextBuildNumber,
'defaultBranch': resDefaultBranch,
'allBranch': resAllBranch,
# 'jsonObj': jsonObj
}

# 1. 获取项目信息,ok
projectInfo = getProjectInfo()
# 1.1 构建项目,默认参数,ok
# dev2build()

# 2. 获取最后一次构建成功的结果,ok
# url = projectInfo['lastSuccessfulBuild']['url']
# resBuildInfo = postJenkinsJson(url)
# print(resBuildInfo)

# 3. 停止构建,ok
# 3.1 TODO: 获取队列的最后一个在构建的任务,或直接传入
# 3.2 停止构建
# url = f"{JENKINS_URL}job/ppfe-dev2/147/stop"
# res = postJenkins(url)
# print(res.status_code)

# 4. 获取构建进度,ok
url = "http://192.168.5.112:8080/view/pp-dev2/job/ppfe-dev2/151/"
res = postJenkinsJson(url)
print(json.dumps(res))
# "timestamp": 1704423345912, # 开始时间
# "estimatedDuration": 380584, # 预计耗时

# 5. 获取构建日志
# TODO