1#!/usr/bin/env python3
2#
3# Copyright (c) 2019-2020 Red Hat, Inc.
4#
5# Author:
6#  Cleber Rosa <crosa@redhat.com>
7#
8# This work is licensed under the terms of the GNU GPL, version 2 or
9# later.  See the COPYING file in the top-level directory.
10
11"""
12Checks the GitLab pipeline status for a given commit ID
13"""
14
15# pylint: disable=C0103
16
17import argparse
18import http.client
19import json
20import os
21import subprocess
22import time
23import sys
24
25
26class CommunicationFailure(Exception):
27    """Failed to communicate to gitlab.com APIs."""
28
29
30class NoPipelineFound(Exception):
31    """Communication is successfull but pipeline is not found."""
32
33
34def get_local_branch_commit(branch):
35    """
36    Returns the commit sha1 for the *local* branch named "staging"
37    """
38    result = subprocess.run(['git', 'rev-parse', branch],
39                            stdin=subprocess.DEVNULL,
40                            stdout=subprocess.PIPE,
41                            stderr=subprocess.DEVNULL,
42                            cwd=os.path.dirname(__file__),
43                            universal_newlines=True).stdout.strip()
44    if result == branch:
45        raise ValueError("There's no local branch named '%s'" % branch)
46    if len(result) != 40:
47        raise ValueError("Branch '%s' HEAD doesn't look like a sha1" % branch)
48    return result
49
50
51def get_json_http_response(url):
52    """
53    Returns the JSON content of an HTTP GET request to gitlab.com
54    """
55    connection = http.client.HTTPSConnection('gitlab.com')
56    connection.request('GET', url=url)
57    response = connection.getresponse()
58    if response.code != http.HTTPStatus.OK:
59        msg = "Received unsuccessful response: %s (%s)" % (response.code,
60                                                           response.reason)
61        raise CommunicationFailure(msg)
62    return json.loads(response.read())
63
64
65def get_pipeline_status(project_id, commit_sha1):
66    """
67    Returns the JSON content of the pipeline status API response
68    """
69    url = '/api/v4/projects/{}/pipelines?sha={}'.format(project_id,
70                                                        commit_sha1)
71    json_response = get_json_http_response(url)
72
73    # As far as I can tell, there should be only one pipeline for the same
74    # project + commit. If this assumption is false, we can add further
75    # filters to the url, such as username, and order_by.
76    if not json_response:
77        raise NoPipelineFound("No pipeline found")
78    return json_response[0]
79
80
81def wait_on_pipeline_success(timeout, interval,
82                             project_id, commit_sha):
83    """
84    Waits for the pipeline to finish within the given timeout
85    """
86    start = time.time()
87    while True:
88        if time.time() >= (start + timeout):
89            msg = ("Timeout (-t/--timeout) of %i seconds reached, "
90                   "won't wait any longer for the pipeline to complete")
91            msg %= timeout
92            print(msg)
93            return False
94
95        try:
96            status = get_pipeline_status(project_id, commit_sha)
97        except NoPipelineFound:
98            print('Pipeline has not been found, it may not have been created yet.')
99            time.sleep(1)
100            continue
101
102        pipeline_status = status['status']
103        status_to_wait = ('created', 'waiting_for_resource', 'preparing',
104                          'pending', 'running')
105        if pipeline_status in status_to_wait:
106            print('%s...' % pipeline_status)
107            time.sleep(interval)
108            continue
109
110        if pipeline_status == 'success':
111            return True
112
113        msg = "Pipeline failed, check: %s" % status['web_url']
114        print(msg)
115        return False
116
117
118def create_parser():
119    parser = argparse.ArgumentParser(
120        prog='pipeline-status',
121        description='check or wait on a pipeline status')
122
123    parser.add_argument('-t', '--timeout', type=int, default=7200,
124                        help=('Amount of time (in seconds) to wait for the '
125                              'pipeline to complete.  Defaults to '
126                              '%(default)s'))
127    parser.add_argument('-i', '--interval', type=int, default=60,
128                        help=('Amount of time (in seconds) to wait between '
129                              'checks of the pipeline status.  Defaults '
130                              'to %(default)s'))
131    parser.add_argument('-w', '--wait', action='store_true', default=False,
132                        help=('Wether to wait, instead of checking only once '
133                              'the status of a pipeline'))
134    parser.add_argument('-p', '--project-id', type=int, default=11167699,
135                        help=('The GitLab project ID. Defaults to the project '
136                              'for https://gitlab.com/qemu-project/qemu, that '
137                              'is, "%(default)s"'))
138    parser.add_argument('-b', '--branch', type=str, default="staging",
139                        help=('Specify the branch to check. '
140                              'Use HEAD for your current branch. '
141                              'Otherwise looks at "%(default)s"'))
142    parser.add_argument('-c', '--commit',
143                        default=None,
144                        help=('Look for a pipeline associated with the given '
145                              'commit.  If one is not explicitly given, the '
146                              'commit associated with the default branch '
147                              'is used.'))
148    parser.add_argument('--verbose', action='store_true', default=False,
149                        help=('A minimal verbosity level that prints the '
150                              'overall result of the check/wait'))
151    return parser
152
153def main():
154    """
155    Script entry point
156    """
157    parser = create_parser()
158    args = parser.parse_args()
159
160    if not args.commit:
161        args.commit = get_local_branch_commit(args.branch)
162
163    success = False
164    try:
165        if args.wait:
166            success = wait_on_pipeline_success(
167                args.timeout,
168                args.interval,
169                args.project_id,
170                args.commit)
171        else:
172            status = get_pipeline_status(args.project_id,
173                                         args.commit)
174            success = status['status'] == 'success'
175    except Exception as error:      # pylint: disable=W0703
176        if args.verbose:
177            print("ERROR: %s" % error.args[0])
178    except KeyboardInterrupt:
179        if args.verbose:
180            print("Exiting on user's request")
181
182    if success:
183        if args.verbose:
184            print('success')
185        sys.exit(0)
186    else:
187        if args.verbose:
188            print('failure')
189        sys.exit(1)
190
191
192if __name__ == '__main__':
193    main()
194