forked from kubernetes/test-infra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate_testgrid_tabs.py
executable file
·209 lines (171 loc) · 8.05 KB
/
migrate_testgrid_tabs.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
# Copyright 2019 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Migrates information from Testgrid's Config.yaml to a subdirectory of Prow Jobs
Only moves Dashboard Tabs
Skips any Dashboard Tab Configuration that contains unusual keys, even if they're incorrect keys.
"""
import re
import argparse
from os import walk
import ruamel.yaml
# Prow files that will be ignored
PROW_BLACKLIST = [
# Ruamel won't be able to successfully dump fejta-bot-periodics
# See https://bitbucket.org/ruamel/yaml/issues/258/applying-json-patch-breaks-comment
"fejta-bot-periodics.yaml",
# Generated security jobs are generated with the same name as kubernetes/kubernetes
# presubmits, but we never want to migrate to the generated ones.
"generated-security-jobs.yaml",
# generated.yaml is generated by generate_tests.py, and will be overwritten.
"generated.yaml",
]
MAX_WIDTH = 2000000000
def main(testgrid_config, prow_dir):
with open(testgrid_config, "r") as confFile:
config = ruamel.yaml.load(confFile,
Loader=ruamel.yaml.RoundTripLoader,
preserve_quotes=True)
for dashboard in config["dashboards"]:
if "dashboard_tab" in dashboard:
for dashTab in dashboard["dashboard_tab"][:]:
if assert_tab_keys(dashTab):
move_tab(dashboard, dashTab, prow_dir)
with open(testgrid_config, "w") as confFile:
ruamel.yaml.dump(config, confFile,
Dumper=ruamel.yaml.RoundTripDumper, width=MAX_WIDTH)
confFile.truncate()
def move_tab(dashboard, dashTab, prow_dir):
"""Moves a given dashboard to the matching prow job in prow_dir, if possible"""
dashboardName = dashboard["name"]
prowJobName = dashTab["test_group_name"]
prowJobFileName = find_prow_job(prowJobName, prow_dir)
if prowJobFileName == "":
return
# Matching file found; patch and delete
print("Patching {0} in {1}".format(prowJobName, prowJobFileName))
with open(prowJobFileName, "r") as prowJobFile:
prowConfig = ruamel.yaml.load(prowJobFile,
Loader=ruamel.yaml.RoundTripLoader,
preserve_quotes=True)
# For each presubmits, postsubmits, periodic:
# presubmits -> <any repository> -> [{name: prowjob}]
if "presubmits" in prowConfig:
for _, jobs in prowConfig["presubmits"].items():
for job in jobs:
if prowJobName == job["name"]:
job = patch_prow_job(job, dashTab, dashboardName)
# postsubmits -> <any repository> -> [{name: prowjob}]
if "postsubmits" in prowConfig:
for _, jobs in prowConfig["postsubmits"].items():
for job in jobs:
if prowJobName == job["name"]:
job = patch_prow_job(job, dashTab, dashboardName)
# periodics -> [{name: prowjob}]
if "periodics" in prowConfig:
for job in prowConfig["periodics"]:
if prowJobName == job["name"]:
job = patch_prow_job(job, dashTab, dashboardName)
# Dump ProwConfig to prowJobFile
with open(prowJobFileName, "w") as prowJobFile:
ruamel.yaml.dump(prowConfig, prowJobFile,
Dumper=ruamel.yaml.RoundTripDumper, width=MAX_WIDTH)
prowJobFile.truncate()
# delete tab
dashboard["dashboard_tab"].remove(dashTab)
def assert_tab_keys(tab):
"""Asserts if a dashboard tab is able to be migrated.
To be migratable, the annotations must only contain whitelisted keys
AND alert_options, if present, must contain and only contain "alert_mail_to_addresses"
"""
whitelist = ["name", "description", "test_group_name", "alert_options",
"num_failures_to_alert", "alert_stale_results_hours", "num_columns_recent"]
if [k for k in tab.keys() if k not in whitelist]:
return False
if "alert_options" in tab:
alertKeys = tab["alert_options"].keys()
if len(alertKeys) != 1 or "alert_mail_to_addresses" not in alertKeys:
return False
return True
def find_prow_job(name, path):
"""Finds a Prow Job in a given subdirectory.
Returns the first file that contains the named prow job
Returns "" if there isn't one
Dives into subdirectories
Ignores PROW_BLACKLIST
"""
pattern = re.compile("name: '?\"?" + name + "'?\"?$", re.MULTILINE)
for (dirpath, _, filenames) in walk(path):
for filename in filenames:
if filename.endswith(".yaml") and filename not in PROW_BLACKLIST:
for _, line in enumerate(open(dirpath + "/" + filename)):
for _ in re.finditer(pattern, line):
#print "Found %s in %s" % (name, filename)
return dirpath + "/" + filename
return ""
def patch_prow_job(prowYaml, dashTab, dashboardName):
"""Updates a Prow YAML object.
Assumes a valid prow yaml and a compatible dashTab
Will create a new annotation or amend an existing one
"""
if "annotations" in prowYaml:
# There exists an annotation; amend it
annotation = prowYaml["annotations"]
if "testgrid-dashboards" in prowYaml["annotations"]:
# Existing annotation includes a testgrid annotation
# The dashboard name must come first if it's a sig-release-master-* dashboard
if dashboardName.startswith("sig-release-master"):
annotation["testgrid-dashboards"] = (dashboardName
+ ", "
+ annotation["testgrid-dashboards"])
else:
annotation["testgrid-dashboards"] += (", " + dashboardName)
else:
#Existing annotation is non-testgrid-related
annotation["testgrid-dashboards"] = dashboardName
else:
# There is no annotation; construct it
annotation = {"testgrid-dashboards": dashboardName}
# Append optional annotations
if ("name" in dashTab
and "testgrid-tab-name" not in annotation
and dashTab["name"] != dashTab["test_group_name"]):
annotation["testgrid-tab-name"] = dashTab["name"]
if ("alert_options" in dashTab
and "alert_mail_to_addresses" in dashTab["alert_options"]
and "testgrid-alert-email" not in annotation):
annotation["testgrid-alert-email"] = dashTab["alert_options"]["alert_mail_to_addresses"]
opt_arguments = [("description", "description"),
("num_failures_to_alert", "testgrid-num-failures-to-alert"),
("alert_stale_results_hours", "testgrid-alert-stale-results-hours"),
("num_columns_recent", "testgrid-num-columns-recent")]
for tabName, annotationName in opt_arguments:
if (tabName in dashTab and annotationName not in annotation):
# Numeric arguments need to be coerced into strings to be parsed correctly
annotation[annotationName] = str(dashTab[tabName])
prowYaml["annotations"] = annotation
return prowYaml
if __name__ == '__main__':
PARSER = argparse.ArgumentParser(
description='Migrates Testgrid Tabs to Prow')
PARSER.add_argument(
'--testgrid-config',
default='../testgrid/config.yaml',
help='Path to testgrid/config.yaml')
PARSER.add_argument(
'--prow-job-dir',
default='../config/jobs',
help='Path to Prow Job Directory')
ARGS = PARSER.parse_args()
main(ARGS.testgrid_config, ARGS.prow_job_dir)