summaryrefslogtreecommitdiffstats
path: root/packager_activity.py
blob: 1c35f49c572bbc2e83e6a44ac0248874db979df7 (plain)
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
#!/usr/bin/env python -tt
#-*- coding: utf-8 -*-

#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""
This program retrieves all the people in the packager group and check against
datagrepper when were their last action.

Dependencies:
* python-requests
* python-argparse
* python-fedora
* python-arrow
* python-progressbar
"""

import datetime
import getpass
import json
import time
import urllib
import socket

import arrow
import fedora.client.fas2
import requests

from progressbar import Bar, ETA, Percentage, ProgressBar, RotatingMarker


DATAGREPPER_URL = 'https://apps.fedoraproject.org/datagrepper/raw/'


def get_fas_userlist(fas_credentials):
    creds = fas_credentials

    fasclient = fedora.client.fas2.AccountSystem(
        username=creds['username'],
        password=creds['password'],
    )

    timeout = socket.getdefaulttimeout()
    socket.setdefaulttimeout(600)
    try:
        print("Downloading FAS cache")
        request = fasclient.send_request('/user/list',
                                         req_params={'search': '*'},
                                         auth=True)
    finally:
        socket.setdefaulttimeout(timeout)

    # We don't actually check for CLA+1, just "2 groups"
    output = []
    for people in request['people']:
        if 'group_roles' in people and \
            'packager' in people['group_roles'] and\
            people['group_roles']['packager']['role_status'] == 'approved':
            output.append(people['username'])

    return output


def get_last_action_of_user(username):
    """ Query datagrepper to retrieve the last action of the provided user.
    """
    #print('Query history for {0}'.format(username))

    data = {'start': 0,
            'user': [username],
            'rows_per_page': 1,
            'order': 'desc',
            }
    output = requests.get(DATAGREPPER_URL, params=data)
    try:
        json_output = json.loads(output.text)
    except Exception, err:
        print 'ERROR for user %s' % username
        print 'ERROR:', err.message
        return []

    if not json_output['raw_messages']:
        #print 'ERROR no messages for user %s' % username
        return None

    return arrow.get(json_output['raw_messages'][0]['timestamp'])


def main():
    # We need some credential to work:
    username = raw_input('FAS username: ')
    password = getpass.getpass('FAS password: ')
    creds = { 'username': username, 'password': password}

    # Do a long query against FAS to get all the user
    peoples = get_fas_userlist(creds)
    print '%s packagers to investigate' % len(peoples)

    output = {}
    no_msg = []
    widgets = ['Getting date: ', Percentage(), ' ',
               Bar(marker=RotatingMarker()), ' ', ETA()]
    pbar = ProgressBar(widgets=widgets, maxval=len(peoples)).start()
    cnt = 0
    pkger_active = {}
    for people in peoples:
        action_date = get_last_action_of_user(people)
        pkger_active[people] = action_date
        if action_date is not None:
            delta = arrow.utcnow() - action_date
            if delta.days in output:
                output[delta.days] += 1
            else:
                output[delta.days] = 1
        else:
            no_msg.append(people)
            if 'nodate' in output:
                output['nodate'] += 1
            else:
                output['nodate'] = 1
        cnt = cnt + 1
        pbar.update(cnt)
    pbar.finish()

    with open('pkger_active_date.csv', 'w') as stream:
        stream.write('Packager,Last activity,Last activity in days\n')
        for pkg in pkger_active:
            delta = None
            if pkger_active[pkg] is not None:
                delta = arrow.utcnow() - pkger_active[pkg]
                delta = delta.days
            stream.write('%s,%s,%s\n' %(pkg, pkger_active[pkg], delta))
    print 'pkger_active_date.csv written'

    with open('pkger_active_per_day.csv', 'w') as stream:
        stream.write('Days,Numbers\n')
        days = sorted(output.keys())
        for key in days:
            stream.write('{0},{1}\n'.format(key, output[key]))
    print 'pkger_active_per_day.csv written'

    print 'Could not find any dates for %s users' % len(no_msg)


if __name__ == '__main__':
    main()