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        raise CommunicationFailure("Failed to receive a successful response")
60    return json.loads(response.read())
61
62
63def get_pipeline_status(project_id, commit_sha1):
64    """
65    Returns the JSON content of the pipeline status API response
66    """
67    url = '/api/v4/projects/{}/pipelines?sha={}'.format(project_id,
68                                                        commit_sha1)
69    json_response = get_json_http_response(url)
70
71    # As far as I can tell, there should be only one pipeline for the same
72    # project + commit. If this assumption is false, we can add further
73    # filters to the url, such as username, and order_by.
74    if not json_response:
75        raise NoPipelineFound("No pipeline found")
76    return json_response[0]
77
78
79def wait_on_pipeline_success(timeout, interval,
80                             project_id, commit_sha):
81    """
82    Waits for the pipeline to finish within the given timeout
83    """
84    start = time.time()
85    while True:
86        if time.time() >= (start + timeout):
87            msg = ("Timeout (-t/--timeout) of %i seconds reached, "
88                   "won't wait any longer for the pipeline to complete")
89            msg %= timeout
90            print(msg)
91            return False
92
93        try:
94            status = get_pipeline_status(project_id, commit_sha)
95        except NoPipelineFound:
96            print('Pipeline has not been found, it may not have been created yet.')
97            time.sleep(1)
98            continue
99
100        pipeline_status = status['status']
101        status_to_wait = ('created', 'waiting_for_resource', 'preparing',
102                          'pending', 'running')
103        if pipeline_status in status_to_wait:
104            print('%s...' % pipeline_status)
105            time.sleep(interval)
106            continue
107
108        if pipeline_status == 'success':
109            return True
110
111        msg = "Pipeline failed, check: %s" % status['web_url']
112        print(msg)
113        return False
114
115
116def create_parser():
117    parser = argparse.ArgumentParser(
118        prog='pipeline-status',
119        description='check or wait on a pipeline status')
120
121    parser.add_argument('-t', '--timeout', type=int, default=7200,
122                        help=('Amount of time (in seconds) to wait for the '
123                              'pipeline to complete.  Defaults to '
124                              '%(default)s'))
125    parser.add_argument('-i', '--interval', type=int, default=60,
126                        help=('Amount of time (in seconds) to wait between '
127                              'checks of the pipeline status.  Defaults '
128                              'to %(default)s'))
129    parser.add_argument('-w', '--wait', action='store_true', default=False,
130                        help=('Wether to wait, instead of checking only once '
131                              'the status of a pipeline'))
132    parser.add_argument('-p', '--project-id', type=int, default=11167699,
133                        help=('The GitLab project ID. Defaults to the project '
134                              'for https://gitlab.com/qemu-project/qemu, that '
135                              'is, "%(default)s"'))
136    parser.add_argument('-b', '--branch', type=str, default="staging",
137                        help=('Specify the branch to check. '
138                              'Use HEAD for your current branch. '
139                              'Otherwise looks at "%(default)s"'))
140    parser.add_argument('-c', '--commit',
141                        default=None,
142                        help=('Look for a pipeline associated with the given '
143                              'commit.  If one is not explicitly given, the '
144                              'commit associated with the default branch '
145                              'is used.'))
146    parser.add_argument('--verbose', action='store_true', default=False,
147                        help=('A minimal verbosity level that prints the '
148                              'overall result of the check/wait'))
149    return parser
150
151def main():
152    """
153    Script entry point
154    """
155    parser = create_parser()
156    args = parser.parse_args()
157
158    if not args.commit:
159        args.commit = get_local_branch_commit(args.branch)
160
161    success = False
162    try:
163        if args.wait:
164            success = wait_on_pipeline_success(
165                args.timeout,
166                args.interval,
167                args.project_id,
168                args.commit)
169        else:
170            status = get_pipeline_status(args.project_id,
171                                         args.commit)
172            success = status['status'] == 'success'
173    except Exception as error:      # pylint: disable=W0703
174        if args.verbose:
175            print("ERROR: %s" % error.args[0])
176    except KeyboardInterrupt:
177        if args.verbose:
178            print("Exiting on user's request")
179
180    if success:
181        if args.verbose:
182            print('success')
183        sys.exit(0)
184    else:
185        if args.verbose:
186            print('failure')
187        sys.exit(1)
188
189
190if __name__ == '__main__':
191    main()
192