aboutsummaryrefslogtreecommitdiff
path: root/utils/daily-mail
blob: 014d034a6c4b470c8704199ee266dd49d1869fe7 (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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
#!/usr/bin/env python

import _mysql
import sys
import os
import textwrap
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
from datetime import date, timedelta, datetime
import localconfig
import csv
from collections import defaultdict
import math
import argparse
import re
import json
from packaging import version
import certifi
from urllib3 import HTTPSConnectionPool
from urllib3.exceptions import HTTPError
from multiprocessing import Pool as ProcessPool

sys.path.append(os.path.join(localconfig.brbase, "utils"))
import getdeveloperlib  # noqa: E402

RE_DATE = re.compile(r'^\d\d\d\d-\d\d-\d\d$')
RE_HASH_40 = re.compile(r'.*[a-fA-F0-9]{40}.*')

baseurl = "autobuild.buildroot.net"
http_baseurl = "http://" + baseurl

developers = getdeveloperlib.parse_developers(localconfig.brbase)
gitlab_ci_http_pool = None


def get_branches():
    """Returns the list of branches currently tested by the autobuilders."""
    branch_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "web", "branches")
    with open(branch_file) as r:
        csv_branches = r.readlines()
    branches = []
    for branch in csv.reader(csv_branches):
        branches.append(branch[0])
    return branches


def get_overall_stats(db, datestr, branches):
    '''
    Find, for the previous day, the global statistics: number of
    success, failures, timeouts, and total number of builds.
    '''
    stats = {}
    for branch in branches:
        db.query("""select status,count(id) as count from results
        where date(builddate) = '{}' and branch = '{}' group by status""".format(datestr, branch))
        r = db.use_result()
        result = dict(r.fetch_row(maxrows=0))
        if '0' in result:
            success = int(result['0'])
        else:
            success = 0
        if '1' in result:
            failures = int(result['1'])
        else:
            failures = 0
        if '2' in result:
            timeouts = int(result['2'])
        else:
            timeouts = 0
        total = success + failures + timeouts
        stats[branch] = (success, failures, timeouts, total)
    return stats


class Notification:
    def __init__(self):
        self.arch_notifications = defaultdict(list)
        self.package_notifications = defaultdict(list)
        self.defconfig_notifications = defaultdict(list)
        self.runtime_test_notifications = defaultdict(list)
        self.package_version_notification = []


def get_mklist(basepath):
    '''
    Calculate the list of .mk files in the Buildroot source tree, will
    be used to guess the name of the packages that caused build
    failures.
    '''
    mklist = []
    for root, dirs, files in os.walk(basepath):
        for f in files:
            if not f.endswith(".mk"):
                continue
            mklist.append(os.path.splitext(f)[0])
    return mklist


mklist = get_mklist(localconfig.brbase)


def add_arch_notification(branch, notifications, build_result):
    '''
    Add to the notifications{} dict notifications that are related to
    architecture "maintainers".
    '''
    arch = build_result['arch']
    for dev in developers:
        if arch not in dev.architectures:
            continue
        n = notifications.setdefault(dev, Notification())
        n.arch_notifications[branch].append(build_result)


def find_package(reason):
    '''
    Given a failure reason as provided by the autobuilders, tries to
    find the corresponding package by stripping progressively the last
    "-<something>" parts of the failure reason. A failure reason like
    "qt5location-5.6.1-1" will first attempt to find a package named
    "qt5location-5.6.1" (which will not find any match) and then attempt
    to find a package named "qt5location" (which will match an existing
    package).
    '''
    if reason == "unknown":
        return
    # Strip host- prefix so that host packages can match
    if reason.startswith("host-"):
        reason = reason[5:]
    # Strip a first component of the version
    while "-" in reason:
        reason = reason[:reason.rindex("-")]
        if reason in mklist:
            return reason
    return None


ORPHAN_DEVELOPER = "Arnout Vandecappelle <arnout@mind.be>"


def get_orphan_developer():
    for dev in developers:
        if dev.name == ORPHAN_DEVELOPER:
            return dev
    return None


def add_package_notification(branch, notifications, build_result):
    '''
    Add to the notifications{} dict notifications that are related to
    package "maintainers".
    '''
    pkg = find_package(build_result['reason'])
    if not pkg:
        return
    orphan = True
    for dev in developers:
        if pkg not in dev.packages:
            continue
        orphan = False
        n = notifications.setdefault(dev, Notification())
        n.package_notifications[branch].append(build_result)
    if orphan:
        dev = get_orphan_developer()
        n = notifications.setdefault(dev, Notification())
        n.package_notifications[branch].append(build_result)
    build_result['orphan'] = orphan


def add_defconfig_notification(branch, notifications, job):
    '''
    Add to the notifications{} dict notifications that are related to
    defconfig "maintainers".
    '''
    orphan = True
    for dev in developers:
        if job['name'] in dev.defconfigs:
            orphan = False
            notif = notifications.setdefault(dev, Notification())
            notif.defconfig_notifications[branch].append(job)
    if orphan:
        job['orphan'] = True
        notif = notifications.setdefault(get_orphan_developer(), Notification())
        notif.defconfig_notifications[branch].append(job)


def add_runtime_test_notification(branch, notifications, job):
    '''
    Add to the notifications{} dict notifications that are related to
    runtime-tests "maintainers".
    '''
    orphan = True
    for dev in developers:
        if job['full_name'] in dev.runtime_tests:
            orphan = False
            notif = notifications.setdefault(dev, Notification())
            notif.runtime_test_notifications[branch].append(job)
    if orphan:
        job['orphan'] = True
        notif = notifications.setdefault(get_orphan_developer(), Notification())
        notif.runtime_test_notifications[branch].append(job)


def add_outdated_pkg_notification(notifications, package):
    '''
    Add to the notifications{} dict notifications that are related to
    package "maintainers".
    '''
    orphan = True
    for dev in developers:
        if package['name'] in dev.packages:
            orphan = False
            notif = notifications.setdefault(dev, Notification())
            notif.package_version_notification.append(package)
    if orphan:
        package['orphan'] = True
        notif = notifications.setdefault(get_orphan_developer(), Notification())
        notif.package_version_notification.append(package)


def shrink_str(string, length, align='right', fill='...'):
    '''
    Returns the `string` shrinked to fit `length` characters and with `fill`
    added on `align`.

    :Example:

    >>> shrink_str('This is a very long string!', 10)
    'This is...'

    >>> shrink_str('This is a very long string!', 20, align='center', fill='[...]')
    'This is[...] string!'
    '''
    if len(fill) > length:
        raise ValueError('`length` cannot be shorter than `fill`')
    if align == 'right':
        return string[:length-len(fill)] + fill if len(string) > length else string
    elif align == 'left':
        return fill + string[len(string)-length+len(fill):] if len(string) > length else string
    elif align == 'center':
        lcut = math.floor((length - len(fill)) / 2)
        rcut = len(string) - math.ceil((length - len(fill)) / 2)
        return string[:lcut] + fill + string[rcut:] if len(string) > length else string
    else:
        raise ValueError('align must be either `left`, `right` or `center`')


def show_gitlab_ci_jobs(jobs, job_column_description, job_column_length, show_orphan=False):
    # Header
    contents = ''
    if show_orphan:
        contents += '{:>{}} | {:^61} | {:^5}\n'.format(job_column_description, job_column_length,
                                                               'link to the job', 'orph?')
        contents += '{0:->{1}}-+-{0:-^61}-+-{0:-^5}\n'.format('', job_column_length)
    else:
        contents += '{:>{}} | {:^61}\n'.format(job_column_description, job_column_length,
                                                       'link to the job')
        contents += '{0:->{1}}-+-{0:-^61}\n'.format('', job_column_length)

    # Data
    for job in sorted(jobs, key=lambda j: (j['kind'], j['name'])):
        name = shrink_str(job['name'], job_column_length, align='left')
        orphan = 'ORPH' if job.get('orphan') else ''

        contents += '{:>{}} | {:^61}'.format(name, job_column_length, job['web_url'])
        if show_orphan:
            contents += ' | {:^5}'.format(orphan)
        contents += '\n'

    return contents


def show_results(results, show_status, show_orphan=False):
    contents = ""
    # Header
    if show_status:
        contents += '{:^12} | {:^30} | {:^3} | {:^79}'.format('arch', 'reason', 'OK?', 'url')
    else:
        contents += '{:^12} | {:^30} | {:^79}'.format('arch', 'reason', 'url')
    if show_orphan:
        contents += ' | {:^5}'.format('orph?')

    if show_status:
        contents += '\n{0:-^12}-+-{0:-^30}-+-{0:-^3}-+-{0:-^79}-'.format('')
    else:
        contents += '\n{0:-^12}-+-{0:-^30}-+-{0:-^79}-'.format('')
    if show_orphan:
        contents += '+-{0:-^5}-'.format('')
    contents += '\n'

    # Actual data
    for r in results:
        arch = r['arch']
        reason = shrink_str(r['reason'], 30)
        status = int(r['status'])
        if status == 1:
            status_str = "NOK"
        elif status == 2:
            status_str = "TIM"
        orphan_str = 'ORPH' if r.get('orphan') else ''
        url = http_baseurl + "/results/" + r['identifier']
        if show_status:
            contents += "{:^12} | {:^30} | {:^3} | {:^79}".format(arch, reason, status_str, url)
        else:
            contents += "{:^12} | {:^30} | {:^79}".format(arch, reason, url)
        if show_orphan:
            contents += " | {:^4}\n".format(orphan_str)
        else:
            contents += "\n"
    return contents


def show_outdated(packages, show_orphan=False):
    contents = ''
    # Header
    contents += '{:^30} | {:^8} | {:^44} | {:^12} | {:^12}'.format('name', 'found by',
                                                                   'link to release-monitoring.org',
                                                                   'version', 'upstream')
    if show_orphan:
        contents += ' | {:^5}'.format('orph?')
    contents += '\n{0:-^30}-+-{0:-^8}-+-{0:-^44}-+-{0:-^12}-+-{0:-^12}-'.format('')
    if show_orphan:
        contents += '+-{:-^5}-'.format('')
    contents += '\n'

    # Actual data
    for pkg in packages:
        name = shrink_str(pkg['name'], 30)
        version = shrink_str(pkg['version'], 12)
        upstream = shrink_str(pkg['upstream'], 12)
        orphan_str = 'ORPH' if pkg.get('orphan') else ''
        url = 'https://release-monitoring.org/project/{:0>5}'.format(pkg['id'])

        contents += '{:>30} | {:^8} | {:0>5} | {:12} | {:12}'.format(name, pkg['from'], url, version, upstream)
        if show_orphan:
            contents += ' | {:4}'.format(orphan_str)
        contents += '\n'
    return contents


def developers_email(smtp, branches, notifications, datestr, dry_run):
    '''
    Send the e-mails to the individual developers
    '''
    for dev, notif in notifications.iteritems():
        to = dev.name
        email_from = localconfig.fromaddr
        subject = "[{}] Your daily results for {}".format(baseurl, datestr)
        contents = "Hello,\n\n"

        archs = notif.arch_notifications
        packages = notif.package_notifications
        defconfigs = notif.defconfig_notifications
        runtime_tests = notif.runtime_test_notifications
        if archs or packages or defconfigs or runtime_tests:
            contents += "Recent build failures and runtime-tests failures\n"
            contents += "================================================\n\n"
            contents += textwrap.fill("This is the list of Buildroot build failures that occurred on {}, "
                                      "and for which you are a registered architecture developer, package "
                                      "developer or defconfig developer. This list also include runtime "
                                      "tests failures. Please help us improving the quality of Buildroot by "
                                      "investigating those build failures and sending patches to fix them. "
                                      "Thanks!".format(datestr))
            contents += "\n\n"
        show_orphan = dev.name == ORPHAN_DEVELOPER

        for branch in branches:
            archs = notif.arch_notifications.get(branch, [])
            packages = notif.package_notifications.get(branch, [])
            defconfigs = notif.defconfig_notifications.get(branch, [])
            runtimes = notif.runtime_test_notifications.get(branch, [])

            if not any(map(len, (archs, packages, defconfigs, runtimes))):
                continue

            contents += "Results for the '{}' branch\n".format(branch)
            contents += "-------------------------" + "-" * len(branch) + "\n\n"

            if len(archs) != 0:
                contents += "Build failures related to your architectures:\n\n"
                contents += show_results(archs, show_status=False, show_orphan=False)
                contents += "\n\n"
            if len(packages) != 0:
                contents += "Build failures related to your packages:\n\n"
                contents += show_results(packages, show_status=False, show_orphan=show_orphan)
                contents += "\n\n"
            if len(defconfigs) != 0:
                contents += "Build failures related to your defconfigs:\n\n"
                contents += show_gitlab_ci_jobs(defconfigs, job_column_description='defconfig',
                                                job_column_length=33, show_orphan=show_orphan)
                contents += "\n\n"
            if len(runtimes) != 0:
                contents += "Build failures related to your runtime tests:\n\n"
                contents += show_gitlab_ci_jobs(runtimes, job_column_description='runtime-test',
                                                job_column_length=25, show_orphan=show_orphan)

            contents += "\n"

        outdated = notif.package_version_notification
        if len(outdated) != 0:
            contents += "Outdated packages\n"
            contents += "=================\n\n"
            contents += textwrap.fill("This is the list of packages for which a new version has been "
                                      "detected and for which you are a registered developer. Please "
                                      "help us improving the quality of Buildroot by bumping these "
                                      "packages to their latest version. Thanks!")
            contents += '\n\n'
            contents += show_outdated(outdated, show_orphan=show_orphan)
            contents += '\n'

        contents += "-- \n"
        contents += http_baseurl
        if dry_run:
            print "====================================================="
            print "To: {}".format(to)
            print "From: {}".format(email_from)
            print "Subject: {}".format(subject)
            print
            print contents
            print "====================================================="
        else:
            msg = MIMEText(contents)
            msg['Subject'] = subject
            msg['To'] = to
            msg['From'] = email_from
            msg['Date'] = formatdate()
            smtp.sendmail(email_from, to, msg.as_string())
            print "To: {}".format(dev.name)


def global_email_branch_result(results, results_by_reason):
    contents = "Classification of failures by reason\n"
    contents += "------------------------------------\n\n"
    for r in results_by_reason:
        reason = shrink_str(r['reason'], 30)
        count = int(r['reason_count'])
        contents += "{:>30} | {:<2}\n".format(reason, count)
    contents += "\n\n"
    contents += "Detail of failures\n"
    contents += "------------------\n\n"
    contents += show_results(results, show_status=True, show_orphan=True)
    return contents


def global_email_branch_gitlab_result(gitlab_results):
    defconfigs = [j for p in gitlab_results for j in p['jobs'] if j['kind'] == 'defconfig']
    runtime_tests = [j for p in gitlab_results for j in p['jobs'] if j['kind'] == 'runtime-test']

    contents = ""
    if len(defconfigs) != 0:
        contents += 'Detail of defconfig failures\n'
        contents += '----------------------------\n\n'
        contents += show_gitlab_ci_jobs(defconfigs, job_column_description='defconfig',
                                        job_column_length=33, show_orphan=True)
        contents += "\n\n"
    if len(runtime_tests) != 0:
        contents += "Detail of runtime-test failures\n"
        contents += "-------------------------------\n\n"
        contents += show_gitlab_ci_jobs(runtime_tests, job_column_description='runtime-test',
                                        job_column_length=25, show_orphan=True)
        contents += "\n\n"
    return contents


def global_email(smtp, branches, results, results_by_reason, datestr, overall, outdated_pkgs, gitlab_results, dry_run):
    '''
    Send the global e-mail to the mailing list
    '''
    to = "buildroot@buildroot.org"
    email_from = localconfig.fromaddr
    subject = "[{}] Daily results for {}".format(baseurl, datestr)
    contents = "Hello,\n\n"
    if len(overall) != 0:
        contents += "Autobuild statistics for {}\n".format(datestr)
        contents += "===============================\n\n"
        contents += "      branch |  OK | NOK | TIM | TOT |\n"
    for branch in sorted(overall.iterkeys()):
        stats = overall[branch]
        if stats[3] == 0:
            continue
        contents += "  {:^10} | {:^3} | {:^3} | {:^3} | {:^3} |\n".format(branch, stats[0], stats[1], stats[2], stats[3])
    if any(map(len, (overall, gitlab_results))):
        contents += "\n"
    for branch in branches:
        branch_results = results.get(branch, [])
        branch_gitlab_results = gitlab_results.get(branch, [])
        if not any(map(len, (branch_results, branch_gitlab_results))):
            continue
        contents += "Results for branch '{}'\n".format(branch)
        contents += "=====================" + "=" * len(branch) + "\n\n"
        if len(branch_results) != 0:
            contents += global_email_branch_result(branch_results, results_by_reason[branch])
            contents += "\n\n"
        if len(branch_gitlab_results) != 0:
            contents += global_email_branch_gitlab_result(branch_gitlab_results)
            contents += "\n\n"
    if outdated_pkgs:
        contents += "Packages having a newer version\n"
        contents += "===============================\n\n"
        contents += show_outdated(outdated_pkgs, show_orphan=True)
    contents += "\n"
    contents += "-- \n"
    contents += http_baseurl
    if dry_run:
        print "====================================================="
        print "To: {}".format(to)
        print "From: {}".format(email_from)
        print "Subject: {}".format(subject)
        print
        print contents
        print "====================================================="
    else:
        msg = MIMEText(contents)
        msg['Subject'] = subject
        msg['To'] = to
        msg['From'] = email_from
        msg['Date'] = formatdate()
        smtp.sendmail(email_from, [to], msg.as_string())
        print "To: buildroot@buildroot.net"


def get_build_results(db, datestr, branches):
    '''
    Get the list of build failures for the past day
    '''
    results = {}
    for branch in branches:
        db.query("""select * from results
        where date(builddate) = '{}'
        and status != 0 and branch = '{}'
        order by reason""".format(datestr, branch))
        r = db.use_result()
        results[branch] = r.fetch_row(how=1, maxrows=0)
    return results


def get_build_results_grouped_by_reason(db, datestr, branches):
    results_by_reason = {}
    for branch in branches:
        db.query("""select reason,count(id) as reason_count from results
        where date(builddate) = '{}' and status != 0 and branch = '{}'
        group by reason order by reason_count desc, reason""".format(datestr, branch))
        r = db.use_result()
        results_by_reason[branch] = r.fetch_row(how=1, maxrows=0)
    return results_by_reason


def get_outdated_pkgs(path):
    with open(path, 'r') as f:
        stats = json.load(f)
    s = []
    for name, pkg in stats['packages'].items():
        status, latest_ver, p_id = pkg['latest_version']
        cur_ver = pkg['current_version']
        # if not upstream version was found, skip
        if status not in (2, 3):
            continue
        # if there's no current or no latest version to compare, skip
        if not cur_ver or not latest_ver:
            continue
        # if the current version is a Git hash, skip as
        # release-monitoring.org only knows about "regular" releases
        if RE_HASH_40.match(cur_ver):
            continue
        # if the current version in Buildroot is newer or equal to the
        # latest reported by release-monitoring, skip
        if version.parse(str(cur_ver)) >= version.parse(str(latest_ver)):
            continue

        s.append({'name': str(name),
                  'id': p_id,
                  'version': str(cur_ver),
                  'upstream': str(latest_ver),
                  'from': 'DISTRO' if status == 2 else 'GUESS'})
    return sorted(s, key=lambda pkg: pkg['name'])


def request_paginated_url(pool, url, page_size=100, page_name='page', **request_kwargs):
    '''
    Simple helper to retrieve data from call paginated url.
    Request's result is assumed to be json list.
    '''
    request_kwargs.setdefault('fields', {})
    request_kwargs['fields']['per_page'] = page_size
    results = []
    page = 1
    while True:
        request_kwargs['fields'][page_name] = page
        try:
            req = pool.request('GET', url, **request_kwargs)
        except HTTPError:
            print('error: there was an error with gitlab api. '
                  'Please make sure your identification token is right and try again.')
            break
        if req.status != 200:
            print('error: there was an error with gitlab api. '
                  'Please make sure your identification token is right and try again.')
            break
        res = json.loads(req.data)
        results += res
        page += 1
        if len(res) != page_size:
            break
    return results


def get_pipeline_details(project_id, pipeline, **request_kwargs):
    pool = gitlab_ci_http_pool
    pipeline_url = '/api/v4/projects/{}/pipelines/{}'.format(project_id, pipeline)
    try:
        pipeline_req = pool.request('GET', pipeline_url, **request_kwargs)
    except HTTPError:
        print('error: there were an error while fetching the gitlab-ci pipeline\'s details. '
              'Please make sure your identification token is right and try again.')
        return {}
    if pipeline_req.status != 200:
        print('error: there were an error while fetching the gitlab-ci pipeline\'s details. '
              'Please make sure your identification token is right and try again.')
        return {}
    infos = json.loads(pipeline_req.data)
    return infos


def get_pipeline_jobs(project_id, pipeline, kinds=None, **request_kwargs):
    pool = gitlab_ci_http_pool
    jobs_url = '/api/v4/projects/{}/pipelines/{}/jobs'.format(project_id, pipeline)
    jobs = request_paginated_url(pool, jobs_url, **request_kwargs)
    for job in jobs:
        # Remove the unnecessary 'pipeline' field
        del job['pipeline']
        # Backup the actual name and set the job's kind and name depending on the naming scheme
        name = job['full_name'] = job['name']
        if name.endswith('_defconfig'):
            job['kind'] = 'defconfig'
            job['name'] = name[:-10]
        elif name.startswith('tests.'):
            job['kind'] = 'runtime-test'
            job['name'] = name.split('.')[-1]
        else:
            job['kind'] = 'other'
    # Filter failed jobs then sort them
    jobs = (job for job in jobs if job['status'] == 'failed')
    if kinds:
        jobs = (job for job in jobs if job['kind'] in kinds)
    return sorted(jobs, key=lambda j: (j['name'], j['kind']))


def get_gitlab_ci_pipelines(http_pool, process_pool, project_id, branches, date, ndays=None):
    '''
    Returns all gitlab-ci pipelines ran after the given `date`
    '''
    date_to = date
    date_from = date - ndays if ndays else date
    per_page = process_pool._processes
    if per_page > 100:
        raise ValueError('gitlab-ci supports a max pagination of 100 results per page. '
                         'The pool passed as argument must have 100 or less processes.')
    fields = {'per_page': per_page}
    url = '/api/v4/projects/{}/pipelines'.format(project_id)
    page = 1
    pipelines = []

    # Fetch pipelines until `date_from` in reached
    while True:
        # List pipelines
        fields['page'] = page
        page += 1
        try:
            cur_pipelines = http_pool.request('GET', url, fields=fields)
        except HTTPError:
            print('error: there was an error while fetching the gitlab-ci pipelines. '
                  'Please make sure your identification token is right and try again.')
            return pipelines
        if cur_pipelines.status != 200:
            print('error: was were an error while fetching the gitlab-ci pipeline\'s details. '
                  'Please make sure your identification token is right and try again.')
            return pipelines
        cur_pipelines = json.loads(cur_pipelines.data)

        # Handle cases where the requested date is older than all pipelines
        if len(cur_pipelines) == 0:
            return pipelines

        # Keep only failed pipelines, and the pipelines for the
        # interesting branches
        cur_pipelines = [p for p in cur_pipelines if p['status'] == 'failed' and p['ref'] in branches]

        # Request more infos about each pipeline (for instance the date)
        pipelines_infos = [process_pool.apply_async(get_pipeline_details, (project_id, p['id']))
                           for p in cur_pipelines]
        pipelines_infos = [p.get() for p in pipelines_infos]

        # Add pipeline in the right period, break once the from_date is found
        for p in pipelines_infos:
            cur_date = datetime.strptime(p['finished_at'], '%Y-%m-%dT%H:%M:%S.%fZ').date()
            if cur_date < date_from:
                return pipelines
            if cur_date > date_to:
                continue
            pipelines.append(p)

    return pipelines


def get_gitlab_ci(branches, date, ndays=None, kinds=None):
    '''
    Retrieve failed jobs from gitlab-ci grouped by pipelines
    from `date` (optionally up to `ndays` old)
    If `kinds` list is provided, only jobs matching one of the
    given kind will be returned.
    '''
    header = {'PRIVATE-TOKEN': localconfig.gitlab_user_token}
    project_id = localconfig.gitlab_project_id
    failed_filter = {'fields': {'status': 'failed'}}

    # Build pools
    global gitlab_ci_http_pool
    gitlab_ci_http_pool = HTTPSConnectionPool('gitlab.com', port=443, cert_reqs='CERT_REQUIRED',
                                              ca_certs=certifi.where(), timeout=30, headers=header)
    process_pool = ProcessPool(processes=64)

    # Fetch pipelines
    pipelines = get_gitlab_ci_pipelines(gitlab_ci_http_pool, process_pool, project_id,
                                        branches, date, ndays)

    # Get jobs ran by those pipelines
    pipelines_jobs = [process_pool.apply_async(get_pipeline_jobs, (project_id, p['id'], kinds),
                                               failed_filter) for p in pipelines]
    for pipeline, jobs in zip(pipelines, pipelines_jobs):
        pipeline['jobs'] = jobs.get()

    # Group pipelines by branch
    pipelines = {branch: [p for p in pipelines if p['ref'] == branch] for branch in branches}
    return pipelines


def calculate_notifications(results, outdated_pkgs, gitlab_results):
    '''
    Prepare the notifications{} dict for the notifications to individual
    developers, based on architecture developers, package developers,
    defconfig developers and runtime developers.
    '''
    notifications = {}
    for branch in results.keys():
        for result in results[branch]:
            status = int(result['status'])
            if status != 1:
                continue
            add_arch_notification(branch, notifications, result)
            add_package_notification(branch, notifications, result)

    for pkg in outdated_pkgs:
        add_outdated_pkg_notification(notifications, pkg)

    for branch, pipelines in gitlab_results.iteritems():
        for pipeline in pipelines:
            for job in pipeline['jobs']:
                if job['kind'] == 'defconfig':
                    add_defconfig_notification(branch, notifications, job)
                elif job['kind'] == 'runtime-test':
                    add_runtime_test_notification(branch, notifications, job)

    return notifications


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dry-run', action='store_true', help='Do not send email, only show output')
    parser.add_argument('--date', action='store', help='Use this date instead of yesterday')
    parser.add_argument('--branches', action='store', nargs='+', help='List of branches (blank separated)')
    parser.add_argument('--dest', action='store', nargs='+', choices=['dev', 'global'],
                        help='List of emails type to send (ie. global, dev)')
    parser.add_argument('--data', action='store', nargs='+',
                        choices=['autobuild', 'outdated', 'defconfig', 'runtime-test'],
                        help='List of information to add in emails (blank separated)')
    args = parser.parse_args()
    if args.date and not RE_DATE.match(args.date):
        parser.error('date must be in format YYYY-MM-DD')
    return args


def __main__():
    args = parse_args()
    if args.date:
        date_struct = datetime.strptime(args.date, '%Y-%m-%d').date()
    else:
        date_struct = date.today() - timedelta(1)
    date_str = date_struct.isoformat()
    branches = args.branches or get_branches()
    email_dest = set(args.dest) if args.dest else {'dev', 'global'}
    email_data = set(args.data) if args.data else {'autobuild', 'outdated', 'defconfig', 'runtime-test'}

    db = _mysql.connect(host=localconfig.host,
                        user=localconfig.user,
                        passwd=localconfig.passwd,
                        db=localconfig.db)
    if 'autobuild' in email_data:
        overall_stats = get_overall_stats(db, date_str, branches)
        results = get_build_results(db, date_str, branches)
        results_by_reason = get_build_results_grouped_by_reason(db, date_str, branches)
    else:
        overall_stats = {}
        results = {}
        results_by_reason = {}
    outdated_pkgs = get_outdated_pkgs(localconfig.pkg_stats) if 'outdated' in email_data else []
    if email_data & {'defconfig', 'runtime-test'}:
        gitlab_ci = get_gitlab_ci(branches, date_struct, kinds=email_data)
    else:
        gitlab_ci = {}
    notifications = calculate_notifications(results, outdated_pkgs, gitlab_ci)
    smtp = smtplib.SMTP(localconfig.smtphost, localconfig.smtpport)
    smtp.starttls()
    smtp.login(localconfig.smtpuser, localconfig.smtppass)
    if 'dev' in email_dest:
        developers_email(smtp, branches, notifications, date_str, args.dry_run)
    if 'global' in email_dest:
        global_email(smtp, branches, results, results_by_reason, date_str,
                     overall_stats, outdated_pkgs, gitlab_ci, args.dry_run)
    smtp.quit()


__main__()