~ursinha/ubuntu-ci-services-itself/401-copying-di-check

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
#!/usr/bin/env python
# Ubuntu CI Engine
# Copyright 2014 Canonical Ltd.

# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License version 3, as
# published by the Free Software Foundation.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import logging
import json
import os
import re
import sys
import time
import urllib2

from ci_utils import jenkins_utils
from ci_utils import dump_stack

MAX_RETRIES = 15
SERVICE_PATH = os.path.join(os.path.dirname(__file__), '../../juju-relations')

# set up a root logger for everything
stdout_handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter(
    '%(asctime)s %(levelname)-5s %(name)s: %(message)s', datefmt='%H:%M:%S')
stdout_handler.setFormatter(formatter)
l = logging.getLogger('')
l.addHandler(stdout_handler)
l.setLevel(logging.DEBUG)

logger = logging.getLogger('lander_get_next_ticket')


def _get(url):
    resp = urllib2.urlopen(url)
    resp = resp.read()
    return json.loads(resp)


def _get_parser():
    parser = argparse.ArgumentParser(
        description='Wraps the REST API calls with a progress queue monitor.')
    parser.add_argument('--service-name',
                        required=True,
                        help='The name of the service to connect.')
    parser.add_argument('--service-port',
                        required=True,
                        help='The port number of the service to connect.')
    parser.add_argument('--delay',
                        required=True,
                        type=int,
                        help='The delay in seconds between poll attempts.')
    return parser


def handle_next_ticket(jenkins_config, service_url):
    if jenkins_utils.is_master_job_running(jenkins_config):
        logging.info('{} is building, skip next ticket '
                     'request.'.format(jenkins_config['lander_master_job']))
    else:
        logging.info('Jenkins is available')
        url = '{}/api/v1/next/'.format(service_url)
        data = _get(url)
        return data


def poll(jenkins_config, service_url):
    rc = 1
    try:
        results = handle_next_ticket(jenkins_config, service_url)
        if results:
            out_data = results.get('objects', None)
            if out_data:
                out_data = out_data[0]
                request_id = out_data['id']
                logging.info('request_id: {}'.format(request_id))
                logging.info('request_parameters: {}'.format(out_data))
                job_parameters = {
                    'request_id': request_id,
                }
                jenkins_utils.trigger_build(jenkins_config, job_parameters)
        rc = 0
    except urllib2.HTTPError as e:
        body = e.read()
        logging.exception('Unable to handle request: %s: %s', e, body)
        results = {
            'result': 'ERROR',
            'resp_code': e.reason,
            'resp_body': body,
        }
    except Exception as e:
        logging.exception('Unexpected error: {}'.format(e))
        results = {
            'result': 'FAILED',
            'error': e.message,
        }

    return rc


def get_service_url(service_name, service_port):
    for root, dirs, files in os.walk(SERVICE_PATH):
        for name in files:
            with open(os.path.join(root, name)) as f:
                for line in f.readlines():
                    if re.match('%s:' % service_name, line):
                        (junk, url) = line.split(':')
                        return 'http://{}:{}'.format(url.strip(),
                                                     service_port)


def main(args):
    retries = MAX_RETRIES
    logging.info('Starting lander-jenkins worker.')
    while retries:
        logging.info('Trying to acquire jenkins config.')
        jenkins_config = jenkins_utils.get_config()
        if not jenkins_config:
            retries -= 1
            logging.error('Unable to acquire jenkins configuration, '
                          'will retry {} more times.'.format(retries))
            time.sleep(args.delay)
        else:
            break
    if not retries:
        logging.error('Failed to acquire jenkins configuration, '
                      'no more retries.')
        return -1

    retries = MAX_RETRIES
    while retries:
        logging.info('Trying to acquire ticket service url.')
        service_url = get_service_url(args.service_name, args.service_port)
        if not service_url:
            retries -= 1
            logging.error('Unable to acquire ticket service url, '
                          'will retry {} more times.'.format(retries))
            time.sleep(args.delay)
        else:
            break
    if not retries:
        logging.error('Failed to acquire ticket service url, '
                      'no more retries.')
        return -1

    while True:
        logging.info('Polling for a new ticket')
        ret = poll(jenkins_config, service_url)
        if ret:
            logging.error('Breaking out of polling loop')
            return ret
        time.sleep(args.delay)


if __name__ == '__main__':
    dump_stack.install_stack_dump_signal()
    args = _get_parser().parse_args()
    exit(main(args))