2 Margebot: A Errbot Plugin for Gitlab MR reminders
5 from datetime
import datetime
, timezone
7 from dateutil
import parser
8 from dateutil
.tz
import tzutc
9 from dateutil
.relativedelta
import relativedelta
10 from errbot
import BotPlugin
, arg_botcmd
, botcmd
, re_botcmd
, webhook
11 from errbot
.templating
import tenv
12 from errcron
.bot
import CrontabMixin
16 class MargeGitlab(gitlab
.Gitlab
):
18 Subclass gitlab.Gitlab so extra_data args can be added
19 to the addprojecthook() and editprojecthook() methods
22 def __init__(self
, host
, token
="", oauth_token
="", verify_ssl
=True):
23 super().__init
__(host
, token
, oauth_token
, verify_ssl
)
25 def addprojecthook_extra(self
, project_id
, url
, push
=False, issues
=False, merge_requests
=False, tag_push
=False, extra_data
=None):
27 A copy parent addprojecthook with an extra_data field
29 data
= {"id": project_id
, "url": url
}
31 for ed_key
, ed_value
in extra_data
.items():
32 data
[ed_key
] = ed_value
33 data
['push_events'] = int(bool(push
))
34 data
['issues_events'] = int(bool(issues
))
35 data
['merge_requests_events'] = int(bool(merge_requests
))
36 data
['tag_push_events'] = int(bool(tag_push
))
37 request
= requests
.post("{0}/{1}/hooks".format(self
.projects_url
, project_id
),
38 headers
=self
.headers
, data
=data
, verify
=self
.verify_ssl
)
39 if request
.status_code
== 201:
43 def editprojecthook_extra(self
, project_id
, hook_id
, url
, push
=False, issues
=False, merge_requests
=False, tag_push
=False, extra_data
=None):
45 A copy of the parent editprojecthook with an extra_data field
47 data
= {"id": project_id
, "hook_id": hook_id
, "url": url
}
49 for ed_key
, ed_value
in extra_data
.items():
50 data
[ed_key
] = ed_value
51 data
['push_events'] = int(bool(push
))
52 data
['issues_events'] = int(bool(issues
))
53 data
['merge_requests_events'] = int(bool(merge_requests
))
54 data
['tag_push_events'] = int(bool(tag_push
))
55 request
= requests
.put("{0}/{1}/hooks/{2}".format(self
.projects_url
, project_id
, hook_id
),
56 headers
=self
.headers
, data
=data
, verify
=self
.verify_ssl
)
57 return request
.status_code
== 200
60 def deltastr(any_delta
):
62 Output a datetime delta in the format "x days, y hours, z minutes ago"
66 hours
= any_delta
.seconds
// 3600
67 mins
= (any_delta
.seconds
// 60) % 60
69 for (key
, val
) in [("day", days
), ("hour", hours
), ("minute", mins
)]:
71 l_delta
.append("1 " + key
)
73 l_delta
.append("{} {}s".format(val
, key
))
78 retval
= ", ".join(l_delta
) + " ago"
82 class Marge(BotPlugin
, CrontabMixin
):
84 I remind you about merge requests
88 Add a merge request webook of the form
89 'https://webookserver/margeboot/<rooms>'
90 to the projects you want tracked. <rooms> should be a
91 comma-separated list of short room names (anything before the '@')
92 that you want notified.
94 Add <roomname>@domain to the CHATROOM_PRESENCE list in config.py for
95 rooms margebot should join
99 # Set in config now: '0 11,17 * * * .crontab_hook' # 7:00AM and 1:00PM EST warnings
102 def __init__(self
, *args
, **kwargs
):
104 self
.chatroom_host
= None
106 self
.soak_delta
= None
107 self
.webhook_url
= None
108 super().__init
__(*args
, **kwargs
)
110 def get_configuration_template(self
):
112 GITLAB_HOST: Host name of your gitlab server
113 GITLAB_ADMIN_TOKEN: PAT from an admin's https://${GIT_HOST}/profile/personal_access_tokens.
114 CHATROOM_HOST: Chatroom host. Usually 'chatroom' + FQDN of Jabber server
115 CRONTAB: Schedule of automated merge request checks in '%M %H %d %m %w' format
116 VERIFY_SSL : True, False, or path to CA cert to verify cert
117 CRONTAB_SOAK_HOURS : Don't send out reminders about MRs opened less than this many hours
118 WEBHOOK_URL : URL to use for defining MR integration in gitlab
120 return {'GITLAB_HOST': 'gitlab.example.com',
121 'GITLAB_ADMIN_TOKEN': 'gitlab-admin-user-private-token',
122 'CHATROOM_HOST': 'conference.jabber.example.com',
123 'CRONTAB': '0 11,17 * * *',
125 'CRONTAB_SOAK_HOURS': 1,
126 'WEBHOOK_URL': 'https://webhooks.example.com:3142/margebot/'}
128 def check_configuration(self
, configuration
):
130 Check that the plugin has been configured properly
132 super().check_configuration(configuration
)
136 Initialization done when the plugin is activated
139 self
.log
.info('Margebot is not configured. Forbid activation')
141 self
.git_host
= self
.config
['GITLAB_HOST']
142 self
.chatroom_host
= self
.config
['CHATROOM_HOST']
143 Marge
.CRONTAB
= ['{} .crontab_hook'.format(self
.config
['CRONTAB'])]
144 gitlab_auth_token
= self
.config
['GITLAB_ADMIN_TOKEN']
145 verify_ssl
= self
.config
['VERIFY_SSL']
146 self
.gitlab
= MargeGitlab(self
.git_host
, gitlab_auth_token
, verify_ssl
=verify_ssl
)
147 self
.activate_crontab()
149 self
.soak_delta
= relativedelta(hours
=self
.config
['CRONTAB_SOAK_HOURS'])
150 self
.webhook_url
= self
.config
['WEBHOOK_URL']
151 if self
.webhook_url
[-1] != '/':
152 self
.webhook_url
+= '/'
155 def deactivate(self
):
157 Anything that needs to be tore down when the plugin is deactivated goes here.
161 @webhook('/margebot/<rooms>/')
162 def gitlab_hook(self
, request
, rooms
):
164 Webhook that listens on http://<server>:<port>/gitlab
167 self
.log
.info("webhook: request: {}, rooms: {}".format(request
, rooms
))
168 # self.log.info("state: {}".format(request['object_attributes']['state']))
170 # verify it's a merge request
171 if request
['object_kind'] != 'merge_request':
172 self
.log
.error('unexpecting object_kind: {}'.format(request
['object_kind']))
173 elif 'opened' in request
['object_attributes']['state']:
175 if request
['object_attributes']['work_in_progress']:
179 url
= request
['project']['homepage']
180 title
= request
['object_attributes']['title']
182 author_id
= request
['object_attributes']['author_id'] # map this to user name ...
183 author
= self
.gitlab
.getuser(author_id
)
185 author_name
= author
['username']
187 self
.log
.info("unexpected author_id {}".format(author_id
))
188 author_name
= author_id
190 target_project_id
= request
['object_attributes']['target_project_id']
191 iid
= request
['object_attributes']['iid']
192 mr_id
= request
['object_attributes']['id']
194 msg_template
= "Hi there ! {} has opened a new {}MR: \"{}\"\n{}/merge_requests/{}"
195 msg
= msg_template
.format(author_name
, wip
, title
, url
, iid
)
197 if 'OPEN_MRS' not in self
.keys():
199 self
['OPEN_MRS'] = empty_dict
201 open_mrs
= self
['OPEN_MRS']
203 if (target_project_id
, mr_id
, rooms
) not in open_mrs
:
204 for a_room
in rooms
.split(','):
206 self
.send(self
.build_identifier(a_room
+ '@' + self
.chatroom_host
), msg
)
208 self
.log
.info("webhook: Saving ({}, {}, {})".format(target_project_id
, mr_id
, rooms
))
209 open_mrs
[(target_project_id
, mr_id
, rooms
)] = True
210 self
['OPEN_MRS'] = open_mrs
213 def mr_status_msg(self
, a_mr
, author
=None):
215 Create the merge request status message
217 self
.log
.info("mr_status_msg: a_mr: {}".format(a_mr
))
219 # Only weed out MRs less than the soak time for the crontab output (where author==None)
220 now
= datetime
.now(timezone
.utc
)
221 creation_time
= parser
.parse(a_mr
['created_at'], tzinfos
=tzutc
)
223 self
.log
.info("times: {}, {}, {}".format(creation_time
, self
.soak_delta
, now
))
224 if creation_time
+ self
.soak_delta
> now
:
225 project_id
= a_mr
['target_project_id']
227 soak_hours
= self
.config
['CRONTAB_SOAK_HOURS']
228 info_template
= "skipping: MR <{},{}> was opened less than {} hours ago"
229 info_msg
= info_template
.format(project_id
, mr_id
, soak_hours
)
230 self
.log
.info(info_msg
)
233 str_open_since
= deltastr(now
- creation_time
)
236 if a_mr
['work_in_progress']:
237 warning
= "still WIP"
238 elif a_mr
['merge_status'] != 'can_be_merged':
239 warning
= "there are merge conflicts"
242 authored
= (a_mr
['author']['id'] == author
)
246 # getapprovals is only available in GitLab 8.9 EE or greater
247 # (not the open source CE version)
248 # approvals = self.gitlab.getapprovals(a_mr['id'])
250 # for approved in approvals['approved_by']:
251 # also_approved += "," + approved['user']['name']
253 upvotes
= a_mr
['upvotes']
254 msg
= "{} (opened {})".format(a_mr
['web_url'], str_open_since
)
256 msg
+= ": Has 2+ upvotes and could be merged in now"
258 msg
+= " except {}.".format(warning
)
264 msg
+= ": Your MR is waiting for another upvote"
266 msg
+= ": Waiting for another upvote"
268 msg
+= " but {}.".format(warning
)
274 msg
+= ": Your MR has no upvotes"
276 msg
+= ": No upvotes, please review"
278 msg
+= " but {}.".format(warning
)
282 return {'creation_time': creation_time
, 'msg': msg
}
284 def crontab_hook(self
, polled_time
):
286 Send a scheduled message to the rooms margebot is watching
287 about open MRs the room cares about.
290 self
.log
.info("crontab_hook triggered at {}".format(polled_time
))
292 reminder_msg
= {} # Map of reminder_msg['roomname@domain'] = [(created_at,msg)]
294 # initialize the reminders
297 reminder_msg
[a_room
.node
] = []
301 # Let's walk through the MRs we've seen already:
302 open_mrs
= self
['OPEN_MRS']
304 for (project_id
, mr_id
, notify_rooms
) in open_mrs
:
306 # Lookup the MR from the project/id
307 a_mr
= self
.gitlab
.getmergerequest(project_id
, mr_id
)
309 self
.log
.debug("Couldn't find project: {}, id: {}".format(project_id
, mr_id
))
312 # If the MR is tagged 'never-close' ignore it
313 if 'labels' in a_mr
and 'never-close' in a_mr
['labels']:
316 self
.log
.info("a_mr: {} {} {} {}".format(project_id
, mr_id
, notify_rooms
, a_mr
['state']))
318 # If the MR is no longer open, skip to the next MR,
319 # and don't include this MR in the next check
320 if 'opened' not in a_mr
['state']:
323 still_open_mrs
[(project_id
, mr_id
, notify_rooms
)] = True
325 msg_dict
= self
.mr_status_msg(a_mr
)
329 for a_room
in notify_rooms
.split(','):
330 reminder_msg
[a_room
].append(msg_dict
)
332 # Remind each of the rooms about open MRs
333 for a_room
, room_msg_list
in reminder_msg
.items():
334 if room_msg_list
!= []:
336 to_room
= a_room
+ '@' + self
.config
['CHATROOM_HOST']
337 msg
= tenv().get_template('reviews.md').render(msg_list
=room_msg_list
)
338 self
.send(self
.build_identifier(to_room
), msg
)
340 self
['OPEN_MRS'] = still_open_mrs
342 @botcmd(template
="reviews")
343 def reviews(self
, msg
, args
):
345 Returns a list of MRs that are waiting for some luv.
346 Also returns a list of MRs that have had enough luv but aren't merged in yet.
348 # Sending directly to Margbot: sender in the form sender@....
349 # Sending to a chatroom: snder in the form room@rooms/sender
351 log_template
= 'reviews: msg: {}, args: {}, \nmsg.frm: {}, \nmsg.msg.frm: {}, chatroom_host: {}'
352 self
.log
.info(log_template
.format(msg
, args
, msg
.frm
.__dict
__, dir(msg
.frm
), self
.config
['CHATROOM_HOST']))
353 self
.log
.info('reviews: bot mode: {}'.format(self
._bot
.mode
))
355 if self
._bot
.mode
== "xmpp":
356 if msg
.frm
.domain
== self
.config
['CHATROOM_HOST']:
357 sender
= msg
.frm
.resource
359 sender
= msg
.frm
.node
361 sender
= str(msg
.frm
).split('@')[0]
364 if 'OPEN_MRS' not in keys
:
365 self
.log
.error('OPEN_MRS not in {}'.format(keys
))
366 return "No MRs to review"
368 sender_gitlab_id
= None
369 sender_users
= self
.gitlab
.getusers(search
=(('username', sender
)))
371 self
.log
.error('problem mapping {} to a gitlab user'.format(sender
))
372 sender_gitlab_id
= None
374 sender_gitlab_id
= sender_users
[0]['id']
376 # Walk through the MRs we've seen already:
380 open_mrs
= self
['OPEN_MRS']
381 for (project
, mr_id
, notify_rooms
) in open_mrs
:
383 # Lookup the MR from the project/id
384 a_mr
= self
.gitlab
.getmergerequest(project
, mr_id
)
386 self
.log
.debug("Couldn't find project: {}, id: {}".format(project
, id))
389 self
.log
.info('project: {}, id: {}, a_mr: {}'.format(project
, id, a_mr
))
391 # If the MR is tagged 'never-close' ignore it
392 if 'labels' in a_mr
and 'never-close' in a_mr
['labels']:
395 # If the MR is no longer open, skip to the next MR,
396 # and don't include this MR in the next check
397 if 'opened' not in a_mr
['state']:
400 still_open_mrs
[(project
, mr_id
, notify_rooms
)] = True
402 msg_dict
= self
.mr_status_msg(a_mr
, author
=sender_gitlab_id
)
406 msg_list
.append(msg_dict
)
408 self
['OPEN_MRS'] = still_open_mrs
410 return {'sender': sender
, 'msg_list': msg_list
}
412 @arg_botcmd('rooms', type=str, help="Comma-separated room list without @conference-room suffix")
413 @arg_botcmd('repo', type=str, help="repo to start watching for MRs in NAMESPACE/PROJECT_NAME format")
414 def watchrepo(self
, msg
, repo
, rooms
):
416 Add the margebot webhook to a repo, and prepopulate any open MRs in the repo with margebot
418 self
.log
.info("msg={}".format(msg
))
419 self
.log
.info("repo={}".format(repo
))
420 self
.log
.info("rooms={}".format(rooms
))
422 # get the group/repo repo, error out if it doesn't exist
423 project
= self
.gitlab
.getproject(repo
)
425 msg
= "Couldn't find repo {}".format(repo
)
426 self
.log
.info("watchrepo: {}".format(msg
))
429 self
.log
.info('project: {}'.format(project
))
431 target_project_id
= project
['id']
433 # Check is the project already includes the margebot hook
434 # If no hooks, will it return False or [] ?
436 hooks
= self
.gitlab
.getprojecthooks(target_project_id
)
437 self
.log
.error("hooks = {}".format(hooks
))
439 msg
= "Couldn't find {} hooks".format(repo
)
440 self
.log
.error("watchrepo: {}".format(msg
))
444 self
.log
.info('a_hook: {}'.format(a_hook
))
445 if a_hook
['merge_requests_events'] and a_hook
['url'].startswith(self
.webhook_url
):
449 # If so replace it (or error out ?)
450 url
= "{}{}".format(self
.webhook_url
, rooms
) # webhooks_url will end in '/'
453 old_rooms
= marge_hook
['url'].split(self
.webhook_url
, 1)[1]
454 if old_rooms
== rooms
:
455 msg
= "Already reporting {} MRs to the {} room(s)".format(repo
, rooms
)
456 self
.log
.info('watchrepo: {}'.format(msg
))
459 hook_updated
= self
.gitlab
.editprojecthook_extra(target_project_id
, marge_hook
['id'], url
, merge_requests
=True, extra_data
={'enable_ssl_verification': False})
460 s_watch_msg
= "Updating room list for {} MRs from {} to {}".format(repo
, old_rooms
, rooms
)
463 hook_updated
= self
.gitlab
.addprojecthook_extra(target_project_id
, url
, merge_requests
=True, extra_data
={'enable_ssl_verification': False})
464 s_watch_msg
= "Now watching for new MRs in the {} repo to the {} roomi(s)".format(repo
, rooms
)
468 msg
= "Couldn't {} hook: {}".format(s_action
, repo
)
469 self
.log
.error("watchrepo: {}".format(msg
))
472 open_mrs
= self
['OPEN_MRS']
474 # get the open MRs in the repo
476 # If updating the room list, walk through the existing MR list
477 if s_action
== "update":
479 for (project_id
, mr_id
, old_rooms
) in open_mrs
:
480 # pragma pylint: disable=simplifiable-if-statement
481 if project_id
== target_project_id
:
482 new_open_mrs
[(project_id
, mr_id
, rooms
)] = True
484 new_open_mrs
[(project_id
, mr_id
, old_rooms
)] = True
485 # pragma pylint: enable=simplifiable-if-statement
486 open_mrs
= new_open_mrs
488 # If adding a new repo, check for existing opened/reopened MRs in the repo.
490 for state
in ['opened', 'reopened']:
492 mr_list
= self
.gitlab
.getmergerequests(target_project_id
, page
=page
, per_page
=100, state
=state
)
493 while (mr_list
is not False) and (mr_list
!= []):
494 for an_mr
in mr_list
:
496 self
.log
.info('watchrepo: an_mr WATS THE ID\n{}'.format(an_mr
))
498 open_mrs
[(target_project_id
, mr_id
, rooms
)] = True
499 # Get the next page of MRs
501 mr_list
= self
.gitlab
.getmergerequests(target_project_id
, page
=page
, per_page
=100)
503 self
['OPEN_MRS'] = open_mrs
506 mr_msg
= "No open MRs were found in the repo."
508 mr_msg
= "1 open MR was found in the repo. Run !reviews to see the updated MR list."
510 mr_msg
= "{} open MRs were found in the repo. Run !reviews to see the updated MR list."
512 return "{}\n{}".format(s_watch_msg
, mr_msg
)
514 # pragma pylint: disable=unused-argument
517 def xyzzy(self
, msg
, args
):
519 Don't call this command...
521 yield "/me whispers \"All open MRs have been merged into master.\""
523 yield "(just kidding)"
525 @re_botcmd(pattern
=r
"I blame marge(bot)?", prefixed
=False, flags
=re
.IGNORECASE
)
526 def dont_blame_margebot(self
, msg
, match
):
528 margebot is innocent.
530 yield u
"(\u300D\uFF9F\uFF9B\uFF9F)\uFF63NOOOooooo say it ain't so."
532 @re_botcmd(pattern
=r
"good bot", prefixed
=False, flags
=re
.IGNORECASE
)
533 def best_bot(self
, msg
, match
):
535 margebot is the best.
539 @re_botcmd(pattern
=r
"magfest", prefixed
=False, flags
=re
.IGNORECASE
)
540 def margefest(self
, msg
, args
):
544 return "More like MargeFest, amirite ?"
546 @re_botcmd(pattern
=r
"margebot sucks", prefixed
=False, flags
=re
.IGNORECASE
)
547 def bring_it_up_with_the_steering_committee(self
, msg
, args
):
549 Bring it up with the committee
551 return "Bring it up with the Margebot steering committee."
553 @re_botcmd(pattern
=r
".*", prefixed
=True)
554 def catchall(self
, msg
,args
):
556 Don't have the bot complain about unknown commands if the first word in a msg is its name
561 # pragma pylint: enable=unused-argument