summaryrefslogtreecommitdiff
path: root/apps/patchmetrics/gerrit.py
blob: 0929f0c0e8e6a015f4a9556fe1b326c1d404de7b (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
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
from datetime import datetime
import email
import urllib
import urllib2

import json

from patchwork.models import Patch, Project, State
from patchmetrics.models import GerritChange
from patchmetrics.gerrit_values import (
    GERRIT_CREATED_KEY,
    GERRIT_DEFAULT_JSON,
    GERRIT_ID_KEY,
    GERRIT_NUMBER_KEY,
    GERRIT_PROJECT_KEY,
    GERRIT_QUERY_LIMIT,
    GERRIT_QUERY_OWNER,
    GERRIT_QUERY_RESUME_SORTKEY,
    GERRIT_SANITIZABLE_VALUE,
    GERRIT_STATUS_KEY,
    GERRIT_SUBJECT_KEY,
    GERRIT_UPDATED_KEY,
)


ROOT_URL = 'https://android-review.googlesource.com/gerrit/rpc'
# This is the URL for the REST interface.
ROOT_REST_URL = 'https://android-review.googlesource.com'
# The default path for the REST interface.
CHANGES_QUERY_PATH = '/changes/'
# This is the query prefix used for gerrit REST interface.
GERRIT_QUERY_PREFIX = 'q='
# Separator for gerrit query parameters.
GERRIT_QUERY_SEPARATOR = '+'
# Default separator for URL query string.
QUERY_STRING_SEP = '&'
# Default character for starting a query string.
QUERY_STRING_START = '?'
# A mapping from AOSP states to our internal ones.
STATE_MAP = {'MERGED': 'Accepted', 'NEW': 'New', 'ABANDONED': 'Rejected'}


class GerritError(Exception):
    """The gerrit server returned an error in response to a query."""


def get_aosp_changes_from(email, resume_key=None, page_size=25,
                          return_format=GERRIT_DEFAULT_JSON):
    """Get the list of changes authored by the given email address.

    :param email: The email of the user to get the changes of.
    :param resume_key: Only include changes whose 'sortkey_after' is lower
                        than this. Use None if you want to start from the
                        beginning.
    :param page_size: Number of items to include in the list, defaults to 25.
    :param return_format: The format of the response, defaults to
                          'JSON_COMPACT' for JSON format without spaces, also
                          possible to specify 'JSON'.
    """
    query_params = {GERRIT_QUERY_OWNER: email,
                    GERRIT_QUERY_LIMIT: page_size,
                    GERRIT_QUERY_RESUME_SORTKEY: resume_key}
    return rest_api_request(ROOT_REST_URL, CHANGES_QUERY_PATH, query_params)


def rest_api_request(url, path, query_params):
    """Calls the gerrit REST interface and return the JSON response.

    :param url: the root URL of the web service.
    :param path: the path of the REST interface, after the URL.
    :param query_params: the parameters for the gerrit query interface, must
                         be a dictionary.
    """
    request_url = create_request_query_url(url, path, query_params)
    return gerrit_request(request_url)


def create_request_query_url(url, path, query_params):
    """Creates the full query URL from the various elements.

    :param url: the root URL of the web service, without path to the REST
                interface.
    :param path: the path of the REST interface, after the URL.
    :param query_params: the parameters for the gerrit query interface, must
                         be a dictionary.
    """
    if not url.endswith('/') and not path.startswith('/'):
        url += '/'
    if not path.endswith('/'):
        path += '/'

    request_url = url + path + QUERY_STRING_START
    request_url += create_gerrit_rest_query(query_params)

    return request_url


def create_gerrit_rest_query(query_params):
    """Creates the gerrit query based on the passed parametes.

    The query result should be in the form of:
    &q=key:value+key:value[+key:value ...]

    :param query_params: a dictionary containing the (key,value) pairs that
                         will be used for the query.
    """
    if not isinstance(query_params, dict):
        raise TypeError("'query_params' must be of type 'dict', got '%s'" %
                        type(query_params).__name__)

    params_list = []
    gerrit_query = ''
    for key, value in query_params.iteritems():
        # We cannot have None values here.
        if value:
            # We need string, remove white chars and quote values.
            # gerrit accepts single or double quotes and curly brackets.
            value = ("\"%s\"" % str(value).strip())
            params_list.append(":".join((key, urllib.quote(value))))
    # The resulting query string, without separators or prefixes, should be in
    # the form of:
    # key:value+key:value
    # This is a normal query, more complex queries need to be thought of, since
    # we can express also OR, AND and NOT operators. By default it is an AND.
    if params_list:
        gerrit_query = (GERRIT_QUERY_PREFIX +
            GERRIT_QUERY_SEPARATOR.join(params_list))

    return gerrit_query


def gerrit_request(request_url):
    """Performs the REST call, opening the connection to the web service.

    :param request_url: the full URL of the request to be performed.
    """
    json_object = None
    try:
        request = urllib2.Request(request_url)
        # Looks like, starting with gerrit version 2.5, we need to do this to
        # talk with it. More info here:
        # https://groups.google.com/group/repo-discuss/msg/78e70b07ad1aacce
        # https://gerrit-review.googlesource.com/Documentation/rest-api.html
        request.add_header("Accept", "application/json")
        # The request in this case needs to be a GET.
        json_string = sanitize_json_response(urllib2.urlopen(request).read())
        json_object = json.loads(json_string)
    except urllib2.HTTPError, ex:
        # If we get back an error code 400, it probably means that what we are
        # looking for does not exist. We need to make sure of that and handle
        # it. As it is now, we raise the same expected exception with the same
        # message as before.
        if ex.code == 400:
            raise GerritError(ex.read())
        else:
            raise(ex)

    return json_object


def sanitize_json_response(json_string):
    """Cleans up the JSON response got from the REST interface, in order to be
    valid JSON.

    :param json_string: the JSON string to clean up.
    """
    # The JSON response is not valid JSON, there is a magic sequence at the
    # beginning of the result. We are paranoid, and remove also other white
    # spaces.
    valid_json = json_string
    if json_string.startswith(GERRIT_SANITIZABLE_VALUE):
        valid_json = json_string.lstrip(GERRIT_SANITIZABLE_VALUE)
    return valid_json.strip()


def create_or_update_patches_from_aosp_changes(results, author):
    """Create or update Patch objects from the given list of results.

    For each of the result in the list, make sure there's a matching Patch
    (and GerritChange) object in our DB matching it and update it to be in
    sync with the remote change.

    Return a list with they IDs of the created/updated changes.
    """
    print "Checking changes submitted by %s ..." % author.email
    updated_changes = []
    for result in results:
        gerrit_id = result.get(GERRIT_NUMBER_KEY)
        last_updated_on = datetime.strptime(result.get(GERRIT_UPDATED_KEY),
                                            '%Y-%m-%d %H:%M:%S.%f000')
        try:
            existing = GerritChange.objects.get(gerrit_id=gerrit_id)
        except GerritChange.DoesNotExist:
            existing = None
        date_created = datetime.strptime(result.get(GERRIT_CREATED_KEY),
                                         '%Y-%m-%d %H:%M:%S.%f000')
        change_dict = dict(
            id=gerrit_id, project=result.get(GERRIT_PROJECT_KEY),
            last_updated_on=last_updated_on,
            status=result.get(GERRIT_STATUS_KEY),
            subject=result.get(GERRIT_SUBJECT_KEY), date_created=date_created,
            change_id=result.get(GERRIT_ID_KEY))
        if existing is None:
            create_patch_from_aosp_change(change_dict, author)
            updated_changes.append(gerrit_id)
        elif existing.last_updated_on < last_updated_on:
            update_local_gerrit_change_from_aosp_change(existing, change_dict)
            updated_changes.append(gerrit_id)
        else:
            # The changes are sorted most recently updated first, so as soon
            # as we see one that doesn't need to be updated in our DB we know
            # for sure that the following ones don't need to be updated
            # either.
            break
    print "Done"
    print "#" * 60, "\n"
    return updated_changes


def get_state_for_aosp_status(aosp_status):
    return State.objects.get(name=STATE_MAP[aosp_status])


def get_project_for_aosp_name(aosp_name):
    name = get_project_name_for_aosp_name(aosp_name)
    try:
        return Project.objects.get(linkname=name)
    except Project.DoesNotExist:
        project = Project(linkname=name, name="AOSP %s" % aosp_name,
                          listid=name, listemail=name)
        project.save()
        return project


def get_project_name_for_aosp_name(aosp_name):
    return 'aosp-' + aosp_name.replace('/', '-')


def update_local_gerrit_change_from_aosp_change(gerrit_change, change_dict):
    """Update the local GerritChange from the given change_dict."""
    print "Updating GerritChange/Patch for %s" % gerrit_change.url
    gerrit_change.last_updated_on = change_dict['last_updated_on']
    assert gerrit_change.gerrit_id == change_dict['id'], (
        "The ID of the local GerritChange (%d) doesn't match that of the "
        "remote change (%d)" % (gerrit_change.gerrit_id, change_dict['id']))
    # This will take care of updating the state of the Patch object linked to
    # this GerritChange.
    gerrit_change.status = change_dict['status']
    gerrit_change.save()
    patch = gerrit_change.patch
    patch.name = change_dict['subject']
    # XXX: Is it possible to change the project of a gerrit change, after it's
    # created?
    # patch.project = get_project_for_aosp_name(change_dict['project'])
    # XXX: Is this appropriate?  Need to find out what can cause
    # lastUpdatedOn to change on gerrit.
    # patch.date_last_state_change = change_dict['last_updated_on']
    patch.save()


def create_patch_from_aosp_change(change, author):
    """Create a Patch and GerritChange for the given change and author.

    :param change: A dict with the following keys: id, change_id, project,
                   date_created, subject, status, last_updated_on.
    :param author: The Person who authored this change.
    """
    # This is the unique identifier that gerrit includes in the changes'
    # commit message to later identify when it's committed.
    change_id = change['change_id']
    project = get_project_for_aosp_name(change['project'])
    date = change['date_created']
    name = change['subject']
    # Patch.msgid can't be None, so we make a dummy one here.
    msgid = email.utils.make_msgid()
    # We don't set the patch state because it will be set when we save the
    # GerritChange that is linked to it.
    patch = Patch(author=author, submitter=author, date=date, name=name,
                  project=project, msgid=msgid)
    patch.save()
    gerrit_change = GerritChange(
        gerrit_id=change['id'], patch=patch, status=change['status'],
        change_id=change_id, last_updated_on=change['last_updated_on'])
    gerrit_change.save()

    if patch.date_last_state_change is not None:
        # We're creating a new patch and it's already had a state change so
        # it's best to use the last_updated_on date as date_last_state_change
        # than to leave it as datetime.now(), which was set above when we
        # saved the GerritChange instance.
        patch.date_last_state_change = change['last_updated_on']
        patch.save()

    print "Created GerritChange/Patch for %s" % gerrit_change.url
    return patch