-
Notifications
You must be signed in to change notification settings - Fork 1
/
gerrit-report2.py
executable file
·410 lines (324 loc) · 12.6 KB
/
gerrit-report2.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/python
import argparse
import subprocess
import json
import re
import config
import collections
from datetime import datetime, timedelta
import time
from pprint import pprint
from slacker import Slacker
slack = Slacker(config.token)
option_age = ""
option_owner = None
option_protocol = 'slack'
option_ssm = None
option_stat = None
query_cache = {}
HOST="openbmc.gerrit"
def query(*args):
COMMAND = """gerrit query \
--format json --all-reviewers \
--dependencies --current-patch-set -- \
'%s'""" % " ".join(args)
s = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
results = list(map(json.loads, s.stdout.read().splitlines()))
# print json.dumps(results,indent=4)
del results[-1]
for r in results:
query_cache[r['id']] = r
return results
def changes():
args = ""
if option_owner:
args += " ( {0} )".format(option_owner)
return query(args,
"status:open", "-is:draft", "-label:Code-Review=-2",
"-project:openbmc/openbmc-test-automation")
def change_by_id(change_id):
if change_id in query_cache:
return query_cache[change_id]
c = query(change_id)
if len(c):
return c[0]
return None
username_map = {
'irc': {
'jenkins-openbmc': "Jenkins",
'williamspatrick': "stwcx",
},
'slack': {
'amboar': "@arj",
'anoo1': "@anoo",
'bradbishop': "@bradleyb",
'bjwyman': "@v2cib530",
'cbostic': "@cbostic",
'dhruvibm': "@dhruvaraj",
'dkodihal': "@dkodihal",
'devenrao': "@devenrao",
'geissonator': "@andrewg",
'eddiejames': "@eajames",
'gtmills': "@gmills",
'jenkins-openbmc': "Jenkins",
'jk-ozlabs' : "@jk",
'mine260309': "@shyulei",
'msbarth': "@msbarth",
'mtritz': "@mtritz",
'ngorugan': "@ngorugan",
'navrathi' : "@navrathi",
'ojayanth': "@ojayanth",
'ratagupt': "@ratagupt",
'shenki': "@jms",
'spinler': "@spinler",
'tomjoseph83': "@tomjoseph",
},
}
project_map = {
'openbmc/witherspoon-pfault-analysis': ('spinler','Matt Spinler'),
'openbmc/phosphor-mrw-tools':('spinler','Matt Spinler'),
'openbmc/mboxbridge': ('amboar','Andrew Jeffery'),
'openbmc/obmc-console': ('jk-ozlabs','Jeremy Kerr'),
'openbmc/btbridge': ('jk-ozlabs','Jeremy Kerr'),
'openbmc/inarp': ('jk-ozlabs','Jeremy Kerr'),
'openbmc/phosphor-settingsd' :('dkodihal','Deepak Kodihalli'),
'openbmc/phosphor-logging' :('dkodihal','Deepak Kodihalli'),
'openbmc/openpower-vpd-parser': ('dkodihal','Deepak Kodihalli'),
'openbmc/phosphor-mboxd': ('amboar','Andrew Jeffery'),
'openbmc/openbmc': ('bradbishop','Brad Bishop'),
'openbmc/phosphor-host-ipmid': ('tomjoseph83','Tom Joseph')
}
def map_username(user):
return username_map[option_protocol].get(
user[0], "[{0}: {1}]".format(user[0].encode('utf-8'), user[1].encode('utf-8')))
def map_approvals(approvals, owner):
mapped = {}
for a in approvals:
approval_type = a['type']
approval_owner = (a['by']['username'], a['by'].get('name'))
approval_score = int(a['value'])
if approval_type not in mapped:
mapped[approval_type] = {}
# Don't allow the owner to self-+1 on code-reviews.
if approval_type == 'Code-Review' and approval_owner == owner and \
approval_score > 0:
continue
mapped[approval_type][approval_owner] = approval_score
return mapped
def map_reviewers(reviewers, owner):
mapped = []
for r in reviewers:
if 'username' in r:
reviewer_user = r['username']
else:
reviewer_user = "Anonymous-User"
if 'name' in r:
reviewer_name = r['name']
else:
reviewer_name = "Anonymous Coward"
if reviewer_user == 'jenkins-openbmc':
continue
reviewer_username = (reviewer_user, reviewer_name)
if reviewer_user == owner[0]:
continue
mapped.append(reviewer_username)
return mapped
def map_project_reviewer(project_name):
if project_map.get(project_name) is None:
return ('bradbishop','Brad Bishop')
return project_map.get(project_name)
def reason(change):
subject = change['subject']
if change['owner'].get('name'):
real_name = change['owner'].get('name')
else:
real_name = change['owner']['username']
owner = (change['owner']['username'], real_name)
if 'allReviewers' in change:
reviewers = map_reviewers(change['allReviewers'], owner)
else:
reviewers = []
if 'approvals' in change['currentPatchSet']:
approvals = map_approvals(change['currentPatchSet']['approvals'], owner)
else:
approvals = {}
if len(reviewers) < 2:
return ("{0} has added insufficient reviewers.", [owner], None)
if ('Verified' in approvals):
verified = approvals['Verified']
scores = list(filter(lambda x: verified[x] < 0, verified))
if len(scores):
return ("{0} should resolve verification failure.", [owner], None)
if ('Code-Review' not in approvals):
return ("Missing code review by {0}.", reviewers, None)
reviewed = approvals['Code-Review']
rejected_by = list(filter(lambda x: reviewed[x] < 0, reviewed))
if len(rejected_by):
return ("{0} should resolve code review comments.", [owner], None)
reviewed_by = list(filter(lambda x: reviewed[x] > 0, reviewed))
if len(reviewed_by) < 2:
return ("Missing code review by {0}.",
set(reviewers) - set(reviewed_by), None)
if ('Verified' not in approvals):
return ("May be missing Jenkins verification ({0}).", [owner], None)
if ('dependsOn' in change) and (len(change['dependsOn'])):
for dep in change['dependsOn']:
if not dep['isCurrentPatchSet']:
return ("Depends on out of date patch set {1} ({0}).",
[owner], dep['id'])
dep_info = change_by_id(dep['id'])
if not dep_info:
continue
if dep_info['status'] != "MERGED":
return ("Depends on unmerged patch set {1} ({0}).",
[owner], dep['id'])
approved_by = list(filter(lambda x: reviewed[x] == 2, reviewed))
project_reviewer = map_project_reviewer(change['project'])
if len(approved_by):
return ("Ready for merge by {0}.", approved_by, None)
else:
return ("Awaiting merge review by {0}", [project_reviewer] , None)
send_to_slack = ['@andrewg',
'@anoo',
'@arj',
'@bradleyb',
'@cbostic',
'@devenrao',
'@dkodihal',
'@dhruvaraj',
'@eajames',
'@gmills',
'@jms',
'@jk',
'@msbarth',
'@mtritz',
'@navrathi',
'@ngorugan',
'@ojayanth',
'@ratagupt',
'@spinler',
'@tomjoseph',
'@v2cib530']
def do_report(args):
action_list = {}
stat_list = {}
oldest_action = {}
oldest_review = {}
for c in changes():
patchCreatedOn = c['currentPatchSet']['createdOn']
structTime = time.gmtime(patchCreatedOn)
timePatchCreatedOn = datetime(*structTime[:6])
timePatchCreatedOn -= timedelta(hours=5)
dCTM = datetime.now() - timePatchCreatedOn
print("{0} - {1}".format(c['url'], c['id']))
print(c['subject'].encode('utf-8'))
(r, people, dep) = reason(c)
people = ", ".join(map(map_username, people))
print(r.format(people, dep))
print("patch age:%s") % dCTM
print("----")
if "Depends on unmerged patch set" in r.format(people, dep):
continue
plist = people.split(",")
for p in plist:
p = p.strip()
message = "{0} - {1}".format(c['url'], c['id'].encode('utf-8'))
message = message + "\n" + c['subject'].encode('utf-8') + "\n" + r.format(people, dep)
message += "\npatch age:" + str(dCTM) + "\n----"
pattern = re.compile('bump version')
match_all = pattern.findall(c['subject'])
if match_all:
continue
action_list.setdefault(p, []).append(message)
if "Missing code review" in message:
if p not in oldest_action:
oldest_action.setdefault(p, []).append(patchCreatedOn)
oldest_action[p]= patchCreatedOn
elif oldest_action[p] > patchCreatedOn:
oldest_action[p] = patchCreatedOn
for slack_name, action_description in action_list.iteritems():
print "~~~~"
print slack_name
total_actions_message = "Number of Actions: %d" % len(action_description)
print total_actions_message
if option_ssm and slack_name in send_to_slack:
try:
slack.chat.post_message(slack_name, total_actions_message)
except Exception as e:
print slack_name + "hit exception:",
print e
review_count = 0
for description in action_description:
if slack_name in send_to_slack:
print description
if "Missing code review" in description:
review_count += 1
if option_ssm and slack_name in send_to_slack:
# print description
try:
slack.chat.post_message(slack_name, description)
except Exception as e:
print slack_name + "hit exception:",
print e
print "Number of Reviews: %d" % review_count
if slack_name in oldest_action:
structTime = time.gmtime(oldest_action[slack_name])
timePatchCreatedOn = datetime(*structTime[:6])
timePatchCreatedOn -= timedelta(hours=5)
dCTM = datetime.now() - timePatchCreatedOn
print "Oldest Action: %s" % dCTM
stat_list.setdefault(slack_name, []).append(review_count)
message = ""
for check_name in username_map['slack']:
slack_name = username_map['slack'][check_name]
if slack_name == 'Jenkins':
continue
if slack_name not in stat_list:
message = message + "%s has [0] reviews, oldest patch age:\n" % (slack_name)
sorted_stat_list = sorted(stat_list.items(), key=lambda x: (x[1],x[0]))
# sorted_stat_list.remove(('', [0]))
for s_name, cnt in sorted_stat_list:
if s_name in username_map['slack'].values():
dCTM = ""
if s_name in oldest_action:
structTime = time.gmtime(oldest_action[s_name])
timePatchCreatedOn = datetime(*structTime[:6])
timePatchCreatedOn -= timedelta(hours=5)
dCTM = datetime.now() - timePatchCreatedOn
message = message + "%s has %s reviews, oldest patch age: %s\n" % (s_name, cnt, dCTM)
print message
if option_stat:
print "sending stats to sprint_review_week channel"
slack.chat.post_message('#sprint_review_week',message)
# print "sending stats to openbmcdev channel"
# slack.chat.post_message('#openbmcdev',message)
parser = argparse.ArgumentParser()
parser.add_argument('--owner', help='Change owner', type=str,
action='append')
parser.add_argument('--protocol', help='Protocol for username conversion',
type=str, choices=(username_map.keys()))
parser.add_argument('-sm', action='store_true',help='send slack message flag')
parser.add_argument('-stat', action='store_true',help='send statistics to slack flag')
subparsers = parser.add_subparsers()
report = subparsers.add_parser('report', help='Generate report')
report.set_defaults(func=do_report)
args = parser.parse_args()
if ('owner' in args) and args.owner:
option_owner = " OR ".join(map(lambda x: "owner:" + x,
args.owner))
if 'protocol' in args and args.protocol:
option_protocol = args.protocol
if args.sm:
option_ssm = 'True'
print("will send messages to slack")
else:
print("no slack messges will be sent")
if args.stat:
option_stat = 'True'
if 'func' in args:
args.func(args)
else:
parser.print_help()