find-inactive-packagers/find_inactive_packagers.py
Ben Cotton 7f8483bf11 Wrap the getbugs call in a try/except
This prevents a Bugzilla timeout from derailing the whole run

Signed-off-by: Ben Cotton <bcotton@fedoraproject.org>
2022-08-18 13:38:26 -04:00

321 lines
14 KiB
Python

# -*- coding:utf-8 -*-
#
# MIT License
#
# Copyright (c) 2022 Mattia Verga <mattia.verga@protonmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""Detect inactive user in the packager group.
The script will search for any activity in the last year in:
- src.fedoraproject.org
- pagure.io
- bodhi (through datagrepper)
- Fedora mailing lists
- Red Hat bugzilla
It will output the 'inactive_packagers.csv' file with a list of all users in the packager
group and their email which are found to be inactive. This can be used to contact
the inactive users, asking them to show some activity in pagure, datagrepper or mailing lists.
The step-one subcommand will open tickets against inactive packagers in a Pagure repository.
The step-two is used to confront the results of a previous run (provided by the csv file)
and a fresh run, to identify which users still don't show any activity. Therefore we should
consider these users to have abandoned Fedora.
Use the '--privacy' flag to not print emails in the log.
To run the script you'll need:
- fasjson_client to be installed
- an active kerberos ticket to login to fasjson.fedoraproject.org
- a bugzilla API key stored as OS env variable 'BZ_API_KEY'
"""
import click
import logging
import requests
import sys
from copy import copy
from datetime import datetime, timezone
from dateutil import parser as dateparser
from os import getenv
from bugzilla import Bugzilla
from fasjson_client import Client
BZ_API_KEY = getenv('BZ_API_KEY', None)
PAGURE_API_KEY = getenv('PAGURE_API_KEY', None)
PAGURE_NEW_TICKET_URL = getenv('PAGURE_NEW_TICKET_URL', 'https://pagure.io/api/0/find-inactive-packagers/new_issue')
# A list of comma separated values to assign tags to the created ticket or empty string
PAGURE_NEW_TICKET_TAGS = getenv('PAGURE_NEW_TICKET_TAGS', 'inactive_packager')
# A username to whom assign the ticket by default or None
PAGURE_NEW_TICKET_ASSIGNEE = getenv('PAGURE_NEW_TICKET_ASSIGNEE', None)
# A list of system users that should never be removed from the packager group
EXCLUDE_USERS = ['releng']
PING_INACTIVE_TEXT = '''Hello @{username},
during our periodic check as per the "[Inactive packagers policy](https://docs.fedoraproject.org/en-US/fesco/Policy_for_inactive_packagers/)"
we detected no activity from you as a packager, nor in
other Fedora community places, like Bodhi or mailing lists.
In order to reduce security risks from possible accounts hijacking
we\'re trying to contact you to know if you\'re still reachable and
if your email set in Fedora Account System ({email}) is still valid.
Please, let us know if you\'re still intersted in participating
in Fedora and if you still need your account to be listed in the `packager` group.
Without any reply from you, in two months we will proceed to remove
your account from the `packager` group. Your account will still be active.
'''
logging.basicConfig(level=logging.INFO,
format='%(message)s',
handlers=[
logging.FileHandler(f'find_inactive_packagers_{datetime.now(timezone.utc).strftime("%Y_%m_%d")}.log', 'w+'),
logging.StreamHandler(sys.stdout)
])
@click.group(invoke_without_command=True)
@click.option('--privacy', default=False, help='Hide users email in log.')
@click.pass_context
def cli(ctx, privacy):
"""Detect inactive user in the packager group.
Running the script without step-one or step-two subcommands only outputs results in csv files.
"""
ctx.ensure_object(dict)
fasclient = Client('https://fasjson.fedoraproject.org/')
packagers = fasclient.list_group_members(groupname='packager').result
logging.info(f'### Found {len(packagers)} users in the packager group. ###')
inactive_packagers = []
# Check for activity in Pagure
# may take a while...
logging.info(f'Checking users activity in src.fedoraproject.org...')
for i, p in enumerate(packagers):
if i > 0 and i % 100 == 0:
logging.info(f'Done {i}.')
user = p.get('username')
if user in EXCLUDE_USERS:
continue
try:
resp_src = requests.get(f'https://src.fedoraproject.org/api/0/user/{user}/activity/stats').json()
if not resp_src:
logging.info(f'No packaging activity detected for user {user}')
resp_pag = requests.get(f'https://pagure.io/api/0/user/{user}/activity/stats').json()
if not resp_pag:
logging.info(f'No pagure activity detected for user {user}')
inactive_packagers.append(user)
except Exception:
# May happen when the user never interacted with pagure
logging.warning(f'Error while retrieving data for user {user}.')
inactive_packagers.append(user)
logging.info(f'### Found {len(inactive_packagers)} users with no activity in pagure/src.fp.org over the last year. ###')
# Check for activity in Bodhi through datagrepper messages
logging.info(f'Checking users activity in Bodhi...')
for i, p in enumerate(copy(inactive_packagers)):
try:
page = 1
found_activity = False
while True:
r = requests.get(f'https://apps.fedoraproject.org/datagrepper/raw/?user={p}'
f'&category=bodhi&order=desc&delta=31536000&rows_per_page=50'
f'&page={page}').json()
for message in r.get('raw_messages', []):
agent = message.get('msg', dict()).get('agent', None)
if agent == p:
logging.info(f'Found recent activity in Bodhi for user {p}')
inactive_packagers.remove(p)
found_activity = True
break
if found_activity or page >= r.get('pages', 1):
break
else:
page += 1
except Exception:
# May happen if there are a lot of entries in datagrepper
logging.error(f'Error while retrieving data for user {p}')
if i % 100 == 0:
logging.info(f'Done {i}.')
logging.info(f'### Found {len(inactive_packagers)} users which also show no activity in Bodhi over the last year. ###')
# Check for any activity in mailing lists
logging.info(f'Checking users activity in mailing lists...')
packager_email_map = {}
for i, p in enumerate(inactive_packagers):
try:
packager = fasclient.get_user(username=p).result
recent_found = False
for email in packager['emails']:
r = requests.get(f'https://lists.fedoraproject.org/archives/api/sender/{email}/emails/?ordering=-date').json()
if r.get('count', 0) != 0:
last_email_date = datetime.fromisoformat(r.get('results')[0]['date'].replace('Z', '+00:00'))
time_delta = datetime.now(timezone.utc) - last_email_date
if time_delta.days <= 365:
logging.info(f'Found recent email from user {p}: {last_email_date}.')
recent_found = True
break
if not recent_found:
packager_email_map[p] = packager['emails']
except Exception:
logging.error(f'Error while retrieving last mailing lists activity for user {p}.')
packager_email_map[p] = packager['emails']
if i % 100 == 0:
logging.info(f'Done {i}.')
logging.info(f'### Found {len(packager_email_map)} users which show also no activity in mailing lists over the last year. ###')
# Check for activity in Bugzilla
# Let's run last since it's the slowest
if BZ_API_KEY:
logging.info(f'Checking users activity in bugzilla...')
bzclient = Bugzilla(url='https://bugzilla.redhat.com/xmlrpc.cgi', api_key=BZ_API_KEY)
for i, p in enumerate(copy(packager_email_map).items()):
if i > 0 and i % 100 == 0:
logging.info(f'Done {i}.')
username = p[0]
bzuser = None
# Some users have their @fedoraproject.org alias set as BZ email
for bzemail in p[1] + [f'{username}@fedoraproject.org']:
try:
bzuser = bzclient.getuser(bzemail)
break
except Exception:
logging.warning(f'Unable to find user {username} by email {bzemail if not privacy else "***"} in Bugzilla.')
if not bzuser:
logging.error(f'Unable to check user {username} activity in Bugzilla because I cannot find them.')
continue
try:
bugs = bzclient.query({
"email1" : bzuser.email,
"emaillongdesc1" : "1",
"emailtype1" : "substring",
"query_format" : "advanced",
"order": "changeddate DESC",
"chfieldfrom" : "-1y",
"chfieldto" : "Now",
"limit": 1000})
except Exception:
logging.error(f'Error while retrieving Bugzilla data for user {username}')
continue
ids = [bug.bug_id for bug in bugs]
user_comments = []
try:
bzbugs = bzclient.getbugs(ids)
except Exception:
logging.error(f'Error while retrieving Bugzilla comments for user {username}')
continue
for bug in bzbugs:
user_comments.extend([com for com in bug.longdescs if com['creator_id'] == bzuser.userid])
if not user_comments:
continue
last_com_date = None
for comment in user_comments:
if not last_com_date or last_com_date < comment.get('time'):
last_com_date = comment.get('time')
# convert DateTime object to datetime.datetime
last_com_date = dateparser.parse(f'{last_com_date.value} UTC')
time_delta = datetime.now(timezone.utc) - last_com_date
if time_delta.days <= 365:
logging.info(f'User {username} made a comment in Bugzilla on {last_com_date.strftime("%Y_%m_%d")}.')
packager_email_map.pop(username)
logging.info(f'### Found {len(packager_email_map)} users which also show no activity in Bugzilla over the last year. ###')
ctx.obj['packager_email_map'] = packager_email_map
if packager_email_map:
with open('inactive_packagers.csv', 'w') as fout:
for user, emails in packager_email_map.items():
emailstring = '|'.join(emails)
logging.info(f'{user} - {emailstring if not privacy else "***"}')
fout.write(f'{user},{emailstring}\n')
@cli.command()
@click.pass_context
def step_one(ctx):
"""Open Pagure tickets against inactive packagers."""
packager_email_map = ctx.obj['packager_email_map']
if packager_email_map:
# Open Pagure tickets
if PAGURE_API_KEY and PAGURE_NEW_TICKET_URL:
headers = {'Authorization': f'token {PAGURE_API_KEY}'}
for user, emails in packager_email_map.items():
data = {'title': f'Inactive packager detected for user {user}',
'issue_content': PING_INACTIVE_TEXT.format(username = user, email = emails[0]),
'tag': PAGURE_NEW_TICKET_TAGS.split(','),
'assignee': PAGURE_NEW_TICKET_ASSIGNEE}
try:
resp = requests.post(PAGURE_NEW_TICKET_URL, data=data, headers=headers)
if resp.status_code == 401:
logging.error(f'Invalid or expired Pagure token, queue processing will stop immediately.')
break
if resp.status_code != 200:
logging.error(f'Error opening Pagure ticket for user {user}')
except Exception:
logging.error(f'Error opening Pagure ticket for user {user}')
continue
@cli.command()
@click.argument('csvfile', type=click.File('r'))
@click.pass_context
def step_two(ctx, csvfile):
"""Open Pagure tickets against inactive packagers.
Confront the list of inactive packagers detected in a previous run provided by CSVFILE
with the list of inactive users from a fresh run and output the list of users which
haven't replied to the Pagure ticket or that still don't show any activity.
"""
packager_email_map = ctx.obj['packager_email_map']
prev_results = {}
for line in csvfile:
user, emails = line.split(',')
prev_results[user] = emails.strip()
if packager_email_map:
if prev_results:
still_inactive = set(prev_results.keys()).intersection(packager_email_map.keys())
logging.info(f'### These {len(still_inactive)} users didn\'t react to previous inquiry: ###')
with open('still_inactive.csv', 'w') as finactive:
for user in still_inactive:
logging.info(f'{user}')
finactive.write(f'{user}\n')
else:
logging.info(f'### The provided csv file listed no users. ###')
if __name__ == '__main__':
cli()