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
26def get_local_staging_branch_commit():
27    """
28    Returns the commit sha1 for the *local* branch named "staging"
29    """
30    result = subprocess.run(['git', 'rev-parse', 'staging'],
31                            stdin=subprocess.DEVNULL,
32                            stdout=subprocess.PIPE,
33                            stderr=subprocess.DEVNULL,
34                            cwd=os.path.dirname(__file__),
35                            universal_newlines=True).stdout.strip()
36    if result == 'staging':
37        raise ValueError("There's no local branch named 'staging'")
38    if len(result) != 40:
39        raise ValueError("Branch staging HEAD doesn't look like a sha1")
40    return result
41
42
43def get_pipeline_status(project_id, commit_sha1):
44    """
45    Returns the JSON content of the pipeline status API response
46    """
47    url = '/api/v4/projects/{}/pipelines?sha={}'.format(project_id,
48                                                        commit_sha1)
49    connection = http.client.HTTPSConnection('gitlab.com')
50    connection.request('GET', url=url)
51    response = connection.getresponse()
52    if response.code != http.HTTPStatus.OK:
53        raise ValueError("Failed to receive a successful response")
54    json_response = json.loads(response.read())
55
56    # As far as I can tell, there should be only one pipeline for the same
57    # project + commit. If this assumption is false, we can add further
58    # filters to the url, such as username, and order_by.
59    if not json_response:
60        raise ValueError("No pipeline found")
61    return json_response[0]
62
63
64def wait_on_pipeline_success(timeout, interval,
65                             project_id, commit_sha):
66    """
67    Waits for the pipeline to finish within the given timeout
68    """
69    start = time.time()
70    while True:
71        if time.time() >= (start + timeout):
72            print("Waiting on the pipeline timed out")
73            return False
74
75        status = get_pipeline_status(project_id, commit_sha)
76        if status['status'] == 'running':
77            time.sleep(interval)
78            print('running...')
79            continue
80
81        if status['status'] == 'success':
82            return True
83
84        msg = "Pipeline failed, check: %s" % status['web_url']
85        print(msg)
86        return False
87
88
89def main():
90    """
91    Script entry point
92    """
93    parser = argparse.ArgumentParser(
94        prog='pipeline-status',
95        description='check or wait on a pipeline status')
96
97    parser.add_argument('-t', '--timeout', type=int, default=7200,
98                        help=('Amount of time (in seconds) to wait for the '
99                              'pipeline to complete.  Defaults to '
100                              '%(default)s'))
101    parser.add_argument('-i', '--interval', type=int, default=60,
102                        help=('Amount of time (in seconds) to wait between '
103                              'checks of the pipeline status.  Defaults '
104                              'to %(default)s'))
105    parser.add_argument('-w', '--wait', action='store_true', default=False,
106                        help=('Wether to wait, instead of checking only once '
107                              'the status of a pipeline'))
108    parser.add_argument('-p', '--project-id', type=int, default=11167699,
109                        help=('The GitLab project ID. Defaults to the project '
110                              'for https://gitlab.com/qemu-project/qemu, that '
111                              'is, "%(default)s"'))
112    try:
113        default_commit = get_local_staging_branch_commit()
114        commit_required = False
115    except ValueError:
116        default_commit = ''
117        commit_required = True
118    parser.add_argument('-c', '--commit', required=commit_required,
119                        default=default_commit,
120                        help=('Look for a pipeline associated with the given '
121                              'commit.  If one is not explicitly given, the '
122                              'commit associated with the local branch named '
123                              '"staging" is used.  Default: %(default)s'))
124    parser.add_argument('--verbose', action='store_true', default=False,
125                        help=('A minimal verbosity level that prints the '
126                              'overall result of the check/wait'))
127
128    args = parser.parse_args()
129
130    try:
131        if args.wait:
132            success = wait_on_pipeline_success(
133                args.timeout,
134                args.interval,
135                args.project_id,
136                args.commit)
137        else:
138            status = get_pipeline_status(args.project_id,
139                                         args.commit)
140            success = status['status'] == 'success'
141    except Exception as error:      # pylint: disable=W0703
142        success = False
143        if args.verbose:
144            print("ERROR: %s" % error.args[0])
145
146    if success:
147        if args.verbose:
148            print('success')
149        sys.exit(0)
150    else:
151        if args.verbose:
152            print('failure')
153        sys.exit(1)
154
155
156if __name__ == '__main__':
157    main()
158