aboutsummaryrefslogtreecommitdiff
path: root/scripts/autobuild-run
blob: 3086da8116358f8ff6e3014f259cc95a45b12df8 (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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
#!/usr/bin/env python

# Copyright (C) 2014 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

# This script runs the autobuilder logic: it runs Buildroot builds for
# random configuration and submits the result to
# http://autobuild.buildroot.org.
#
# Configuration parameters are:
#
# - ninstances: the number of parallel, independent, build instances
#   that are executed. Due to the non-parallel nature of configure
#   scripts, it is recommended to have several parallel instances and
#   to lower the number of parallel jobs per instances. Can be defined
#   either through the command line, or through the configuration
#   file.
#
# - njobs: the number of parallel jobs inside a given instance (i.e
#   BR2_JLEVEL). Can be defined either through the command line, or
#   through the configuration file.
#
# - http-login, http-password: the HTTP login and password to submit
#   build results to http://autobuild.buildroot.org. Request those
#   credentials from Thomas Petazzoni
#   <thomas.petazzoni@free-electrons.com>. These configuration
#   parameters can only be defined through the configuration file.
#
# - submitter: a human-readable string identifying the
#   submitter/machine. Example: "Peter Korsgaard (gcc110)".
#
# TODO:
#
# - Instead of excluding all configurations that have
#   BR2_PACKAGE_CLASSPATH=y, improve the script to detect whether the
#   necessary host machine requirements are there to build classpath.
# - Extend required dependencies to subversion, mercurial, cpio, wget, python,
#   etc.
# - Detect selection of multiple virtual package providers and don't consider it
#   a failure
# - Fix problem in removal of output directory: sometimes this fails with
#   message 'directory not empty' which suggests that someone is writing to the
#   directory at the time of removal.

from __future__ import print_function

# Don't tell docopt about the defaults, as it would not allow the following
# priority hierarchy for arguments: command-line > config file > defaults
defaults = {
    '--ninstances': '1',
    '--njobs': '1',
    '--submitter': 'N/A',
    '--make-opts': '',
    '--nice': 0,
    '--pid-file': '/tmp/buildroot-autobuild.pid',
}

doc = """autobuild-run - run Buildroot autobuilder

Usage: autobuild-run [options]

Options:
  -h, --help                     show this help message and exit
  -V, --version                  show version
  -n, --ninstances NINSTANCES    number of parallel instances
                                 Defaults to %(--ninstances)s.
  -j, --njobs NJOBS              number of parallel jobs
                                 Defaults to %(--njobs)s.
  --nice N                       Niceness, positive number
                                 Defaults to %(--nice)s.
  -s, --submitter SUBMITTER      name/machine of submitter
                                 Defaults to %(--submitter)s.
  --http-login LOGIN             username to send results with
                                 Not set by default.
  --http-password PASSWORD       password to send results with (for security
                                 reasons it is recommended to define this in the
                                 config file instead, with user-read permissions
                                 only)
                                 Not set by default.
  --make-opts OPTSTRING          string of extra options to pass to Buildroot
                                 make, such as specific command wrappers
                                 Empty by default.
  --pid-file PATH                path to a file where to store the PID
                                 Defaults to %(--pid-file)s.
  -c, --config CONFIG            path to configuration file
                                 Not set by default.

Format of the configuration file:

  All arguments can also be specified in the configuration file specified with
  --config, using 'key = value' format (not including the leading --
  characters). For example:

   [main]
   ninstances = <value>
   njobs = <value>
   nice = <value>
   http-login = <value>
   http-password = <value>
   submitter = <value>


""" % defaults

__doc__ = doc

import contextlib
import csv
import docopt
import errno
import hashlib
import mmap
import multiprocessing
import os
from random import randint
import re
import shutil
import signal
import subprocess
import sys
from time import localtime, strftime
from distutils.version import StrictVersion
import platform

if sys.hexversion >= 0x3000000:
    import configparser
    import urllib.request as _urllib
else:
    import ConfigParser as configparser
    import urllib2 as _urllib

urlopen = _urllib.urlopen
urlopen_closing = lambda uri: contextlib.closing(urlopen(uri))

if sys.hexversion >= 0x3000000:
    def decode_bytes(b):
        return b.decode()

    def decode_byte_list(bl):
        return [b.decode() for b in bl]

    def encode_str(s):
        return s.encode()
else:
    def _identity(e):
        return e

    decode_bytes = _identity
    decode_byte_list = _identity
    encode_str = _identity

MAX_DURATION = 60 * 60 * 8
VERSION = 1

def log_write(logf, msg):
    logf.write("[%s] %s\n" % (strftime("%a, %d %b %Y %H:%M:%S", localtime()), msg))
    logf.flush()

def check_version():
    with urlopen_closing('http://autobuild.buildroot.org/version') as r:
        version = int(decode_bytes(r.readline()).strip())
    if version > VERSION:
        print("ERROR: script version too old, please upgrade.")
        sys.exit(1)

class SystemInfo:
    DEFAULT_NEEDED_PROGS = ["make", "git", "gcc", "timeout"]
    DEFAULT_OPTIONAL_PROGS = ["bzr", "java", "javac", "jar"]

    def __init__(self):
        self.needed_progs = list(self.__class__.DEFAULT_NEEDED_PROGS)
        self.optional_progs = list(self.__class__.DEFAULT_OPTIONAL_PROGS)
        self.progs = {}

    def find_prog(self, name, flags=os.X_OK, env=os.environ):
        if not name or name[0] == os.sep: raise ValueError(name)

        prog_path = env.get("PATH", None)
        # for windows compatibility, we'd need to take PATHEXT into account

        if prog_path:
            for prog_dir in filter(None, prog_path.split(os.pathsep)):
                # os.join() not necessary: non-empty prog_dir
                # and name[0] != os.sep
                prog = prog_dir + os.sep + name
                if os.access(prog, flags):
                    return prog
        # --
        return None

    def has(self, prog):
        """Checks whether a program is available.
        Lazily evaluates missing entries.

        Returns: None if prog not found, else path to the program [evaluates to True]
        """
        try:
            return self.progs[prog]
        except KeyError:
            pass

        have_it = self.find_prog(prog)
        # java[c] needs special care
        if have_it and prog in ('java', 'javac'):
            with open(os.devnull, "w") as devnull:
                if subprocess.call("%s -version | grep gcj" % prog, shell=True,
                                   stdout=devnull, stderr=devnull) != 1:
                    have_it = False
        # --
        self.progs[prog] = have_it
        return have_it

    def check_requirements(self):
        """Checks program dependencies.

        Returns: True if all mandatory programs are present, else False.
        """
        do_check_has_prog = self.has

        missing_requirements = False
        for prog in self.needed_progs:
            if not do_check_has_prog(prog):
                print("ERROR: your system lacks the '%s' program" % prog)
                missing_requirements = True

        # check optional programs here,
        # else they'd get checked by each worker instance
        for prog in self.optional_progs:
            do_check_has_prog(prog)

        return not missing_requirements

def get_toolchain_configs():
    """Fetch and return the possible toolchain configurations

    This function returns an array of dictionaries, with for each toolchain:
        - url: the URL of the toolchain defconfig
        - libc: the C library used by the toolchain
        - hostarch: the host architecture for which the toolchain is built
        - contents: an array of lines of the defconfig
    """
    tc_cfg_uri = 'http://autobuild.buildroot.org/toolchains/configs/toolchain-configs.csv'

    with urlopen_closing(tc_cfg_uri) as r:
        l = decode_byte_list(r.readlines())
    configs = []

    (_, _, _, _, hostarch) = os.uname()
    # ~2015 distros report x86 when on a 32bit install
    if hostarch == 'i686' or hostarch == 'i386' or hostarch == 'x86':
        hostarch = 'x86'

    for row in csv.reader(l):
        config = {}
        config["url"] = row[0]
        config["hostarch"] = row[1]
        keep = False

        # Keep all toolchain configs that work regardless of the host
        # architecture
        if config['hostarch'] == "any":
            keep = True

        # Keep all toolchain configs that can work on the current host
        # architecture
        if hostarch == config["hostarch"]:
            keep = True

        # Assume that x86 32 bits toolchains work on x86_64 build
        # machines
        if hostarch == 'x86_64' and config["hostarch"] == "x86":
            keep = True

        if not keep:
            continue

        config["libc"] = row[2]
        with urlopen_closing(config["url"]) as r:
            config["contents"] = decode_byte_list(r.readlines())
        configs.append(config)
    return configs

def prepare_build(**kwargs):
    """Prepare for the next build of the specified instance

    This function prepares the build by making sure all the needed
    directories are created, cloning or updating the Buildroot source
    code, and cleaning up remaining stuff from previous builds.
    """

    idir = "instance-%d" % kwargs['instance']
    log = kwargs['log']

    log_write(log, "INFO: preparing a new build")

    # Create the download directory if it doesn't exist
    dldir = os.path.join(idir, "dl")
    if not os.path.exists(dldir):
        os.mkdir(dldir)

    # Remove 5 random files from the download directory. Removing
    # random files from the download directory allows to ensure we
    # regularly re-download files to check that their upstream
    # location is still correct.
    for i in range(0, 5):
        flist = os.listdir(dldir)
        if not flist:
            break
        f = flist[randint(0, len(flist) - 1)]
        log_write(log, "INFO: removing %s from downloads" % f)
        os.remove(os.path.join(dldir, f))

    # Clone Buildroot. This only happens if the source directory
    # didn't exist already.
    srcdir = os.path.join(idir, "buildroot")
    if not os.path.exists(srcdir):
        ret = subprocess.call(["git", "clone", "https://github.com/buildroot/buildroot.git", srcdir],
                              stdout=log, stderr=log)
        if ret != 0:
            log_write(log, "ERROR: could not clone Buildroot sources")
            return -1

    # Update the Buildroot sources.
    abssrcdir = os.path.abspath(srcdir)
    ret = subprocess.call(["git", "pull"], cwd=abssrcdir, stdout=log, stderr=log)
    if ret != 0:
        log_write(log, "ERROR: could not pull Buildroot sources")
        return -1

    # Create an empty output directory. We remove it first, in case a previous build was aborted.
    outputdir = os.path.join(idir, "output")
    if os.path.exists(outputdir):
        # shutil.rmtree doesn't remove write-protected files
        subprocess.call(["rm", "-rf", outputdir])
    os.mkdir(outputdir)

    return 0

def is_toolchain_usable(**kwargs):
    """Check if the toolchain is actually usable."""

    idir = "instance-%d" % kwargs['instance']
    sysinfo = kwargs['sysinfo']
    log = kwargs['log']

    outputdir = os.path.join(idir, "output")
    with open(os.path.join(outputdir, ".config")) as configf:
        configlines = configf.readlines()

    # The latest Linaro toolchains on x86-64 hosts requires glibc
    # 2.14+ on the host.
    if platform.machine() == 'x86_64':
        if 'BR2_TOOLCHAIN_EXTERNAL_LINARO_ARM=y\n' in configlines or \
           'BR2_TOOLCHAIN_EXTERNAL_LINARO_AARCH64=y\n' in configlines or \
           'BR2_TOOLCHAIN_EXTERNAL_LINARO_ARMEB=y\n' in configlines:
            ldd_version_output = subprocess.Popen(['ldd', '--version'], stdout=subprocess.PIPE).communicate()[0]
            glibc_version = ldd_version_output.splitlines()[0].split()[-1]
            if StrictVersion('2.14') > StrictVersion(glibc_version):
                log_write(log, "WARN: ignoring the Linaro ARM toolchains becausee too old host glibc")
                return False

    return True

def fixup_config(**kwargs):
    """Finalize the configuration and reject any problematic combinations

    This function returns 'True' when the configuration has been
    accepted, and 'False' when the configuration has not been accepted because
    it is known to fail (in which case another random configuration will be
    generated).
    """

    idir = "instance-%d" % kwargs['instance']
    sysinfo = kwargs['sysinfo']

    outputdir = os.path.join(idir, "output")
    with open(os.path.join(outputdir, ".config")) as configf:
        configlines = configf.readlines()

    # Make sure Qt license is approved
    if "BR2_PACKAGE_QT=y\n" in configlines:
        if "# BR2_PACKAGE_QT_LICENSE_APPROVED is not set\n" in configlines:
            configlines.remove("# BR2_PACKAGE_QT_LICENSE_APPROVED is not set\n")
            configlines.append("BR2_PACKAGE_QT_LICENSE_APPROVED=y\n")
    if "BR2_PACKAGE_QT5BASE=y\n" in configlines:
        if "# BR2_PACKAGE_QT5BASE_LICENSE_APPROVED is not set\n" in configlines:
            configlines.remove("# BR2_PACKAGE_QT5BASE_LICENSE_APPROVED is not set\n")
            configlines.append("BR2_PACKAGE_QT5BASE_LICENSE_APPROVED=y\n")
    # Make sure LTP is not enabled when we have an uClibc toolchain
    if "BR2_PACKAGE_LTP_TESTSUITE=y\n" in configlines and \
       "BR2_TOOLCHAIN_USES_UCLIBC=y\n" in configlines:
        configlines.remove("BR2_PACKAGE_LTP_TESTSUITE=y\n")
    if "BR2_NEEDS_HOST_JAVA=y\n" in configlines and not sysinfo.has("java"):
        return False
    if "BR2_NEEDS_HOST_JAVAC=y\n" in configlines and not sysinfo.has("javac"):
        return False
    if "BR2_NEEDS_HOST_JAR=y\n" in configlines and not sysinfo.has("jar"):
        return False
    # python-nfc needs bzr
    if 'BR2_PACKAGE_PYTHON_NFC=y\n' in configlines and not sysinfo.has("bzr"):
        return False
    # The ctng toolchain is affected by PR58854
    if 'BR2_PACKAGE_LTTNG_TOOLS=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/armv5-ctng-linux-gnueabi.tar.xz"\n' in configlines:
        return False
    # The ctng toolchain tigger an assembler error with guile package when compiled with -Os (same issue as for CS ARM 2014.05-29)
    if 'BR2_PACKAGE_GUILE=y\n' in configlines and 'BR2_OPTIMIZE_S=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/armv5-ctng-linux-gnueabi.tar.xz"\n' in configlines:
        return False
    # The ctng toolchain is affected by PR58854
    if 'BR2_PACKAGE_LTTNG_TOOLS=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/armv6-ctng-linux-uclibcgnueabi.tar.xz"\n' in configlines:
        return False
    # The ctng toolchain is affected by PR58854
    if 'BR2_PACKAGE_LTTNG_TOOLS=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/armv7-ctng-linux-gnueabihf.tar.xz"\n' in configlines:
        return False
    # The ctng toolchain is affected by PR60155
    if 'BR2_PACKAGE_SDL=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/powerpc-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # The ctng toolchain is affected by PR60155
    if 'BR2_PACKAGE_LIBMPEG2=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/powerpc-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # This MIPS toolchain uses eglibc-2.18 which lacks SYS_getdents64
    if 'BR2_PACKAGE_STRONGSWAN=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mips64el-ctng_n64-linux-gnu.tar.xz"\n' in configlines:
        return False
    # This MIPS toolchain uses eglibc-2.18 which lacks SYS_getdents64
    if 'BR2_PACKAGE_PYTHON3=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mips64el-ctng_n64-linux-gnu.tar.xz"\n' in configlines:
        return False
    # libffi not available on sh2a and ARMv7-M, but propagating libffi
    # arch dependencies in Buildroot is really too much work, so we
    # handle this here.
    if 'BR2_sh2a=y\n' in configlines and  'BR2_PACKAGE_LIBFFI=y\n' in configlines:
        return False
    if 'BR2_ARM_CPU_ARMV7M=y\n' in configlines and  'BR2_PACKAGE_LIBFFI=y\n' in configlines:
        return False
    if 'BR2_PACKAGE_SUNXI_BOARDS=y\n' in configlines:
        configlines.remove('BR2_PACKAGE_SUNXI_BOARDS_FEX_FILE=""\n')
        configlines.append('BR2_PACKAGE_SUNXI_BOARDS_FEX_FILE="a10/hackberry.fex"\n')
    # This MIPS uClibc toolchain fails to build the gdb package
    if 'BR2_PACKAGE_GDB=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mipsel-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # This MIPS uClibc toolchain fails to build the rt-tests package
    if 'BR2_PACKAGE_RT_TESTS=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mipsel-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # This MIPS uClibc toolchain fails to build the civetweb package
    if 'BR2_PACKAGE_CIVETWEB=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mipsel-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # This MIPS ctng toolchain fails to build the python3 package
    if 'BR2_PACKAGE_PYTHON3=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mips64el-ctng_n64-linux-gnu.tar.xz"\n' in configlines:
        return False
    # This MIPS uClibc toolchain fails to build the strace package
    if 'BR2_PACKAGE_STRACE=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mipsel-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # This MIPS uClibc toolchain fails to build the cdrkit package
    if 'BR2_PACKAGE_CDRKIT=y\n' in configlines and \
       'BR2_STATIC_LIBS=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mipsel-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # uClibc vfork static linking issue
    if 'BR2_PACKAGE_ALSA_LIB=y\n' in configlines and \
       'BR2_STATIC_LIBS=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/i486-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # This MIPS uClibc toolchain fails to build the weston package
    if 'BR2_PACKAGE_WESTON=y\n' in configlines and \
       'BR2_TOOLCHAIN_EXTERNAL_URL="http://autobuild.buildroot.org/toolchains/tarballs/mipsel-ctng-linux-uclibc.tar.xz"\n' in configlines:
        return False
    # The cs nios2 2016.05 toolchain is affected by binutils PR19405
    if 'BR2_TOOLCHAIN_EXTERNAL_CODESOURCERY_NIOSII=y\n' in configlines and \
       'BR2_PACKAGE_BOOST=y\n' in configlines:
        return False
    # The cs nios2 2016.05 toolchain is affected by binutils PR19405
    if 'BR2_TOOLCHAIN_EXTERNAL_CODESOURCERY_NIOSII=y\n' in configlines and \
       'BR2_PACKAGE_QT5BASE_GUI=y\n' in configlines:
        return False

    with open(os.path.join(outputdir, ".config"), "w+") as configf:
        configf.writelines(configlines)

    return True

def gen_config(**kwargs):
    """Generate a new random configuration

    This function generates the configuration, by choosing a random
    toolchain configuration and then generating a random selection of
    packages.
    """

    idir = "instance-%d" % kwargs['instance']
    log = kwargs['log']

    # We need the absolute path to use with O=, because the relative
    # path to the output directory here is not relative to the
    # Buildroot sources, but to the location of the autobuilder
    # script.
    outputdir = os.path.abspath(os.path.join(idir, "output"))
    srcdir = os.path.join(idir, "buildroot")

    log_write(log, "INFO: generate the configuration")

    # Select a random toolchain configuration
    configs = get_toolchain_configs()
    i = randint(0, len(configs) - 1)
    config = configs[i]

    configlines = config["contents"]

    # Amend the configuration with a few things.
    configlines.append("BR2_PACKAGE_BUSYBOX_SHOW_OTHERS=y\n")
    configlines.append("# BR2_TARGET_ROOTFS_TAR is not set\n")
    configlines.append("BR2_COMPILER_PARANOID_UNSAFE_PATH=y\n")
    if randint(0, 20) == 0:
        configlines.append("BR2_ENABLE_DEBUG=y\n")
    if randint(0, 30) == 0:
        configlines.append("BR2_INIT_SYSTEMD=y\n")
    elif randint(0, 20) == 0:
        configlines.append("BR2_ROOTFS_DEVICE_CREATION_DYNAMIC_EUDEV=y\n")
    if config["libc"] != "glibc" and randint(0, 20) == 0:
        configlines.append("BR2_STATIC_LIBS=y\n")

    # Write out the configuration file
    with open(os.path.join(outputdir, ".config"), "w+") as configf:
        configf.writelines(configlines)

    devnull = open(os.devnull, "w")

    ret = subprocess.call(["yes '' 2>/dev/null| make O=%s -C %s oldconfig" % \
                           (outputdir, srcdir)], shell=True, stdout=devnull, stderr=devnull)
    if ret != 0:
        log_write(log, "ERROR: cannot oldconfig")
        return -1

    if not is_toolchain_usable(**kwargs):
        return -1

    # Now, generate the random selection of packages, and fixup
    # things if needed.
    # Safe-guard, in case we can not quickly come to a valid
    # configuration: allow at most 100 (arbitrary) iterations.
    bounded_loop = 100
    while True:
        if bounded_loop == 0:
            log_write(log, "ERROR: cannot generate random configuration after 100 iterations")
            return -1
        bounded_loop -= 1
        ret = subprocess.call(["make", "O=%s" % outputdir, "-C", srcdir,
                               "KCONFIG_PROBABILITY=%d" % randint(1,30), "randpackageconfig"],
                              stdout=devnull, stderr=devnull)
        if ret != 0:
            log_write(log, "ERROR: cannot generate random configuration")
            return -1
        if fixup_config(**kwargs):
            break

    ret = subprocess.call(["yes '' 2>/dev/null| make O=%s -C %s oldconfig" % \
                           (outputdir, srcdir)], shell=True, stdout=devnull, stderr=devnull)
    if ret != 0:
        log_write(log, "ERROR: cannot oldconfig")
        return -1

    ret = subprocess.call(["make", "O=%s" % outputdir, "-C", srcdir, "savedefconfig"],
                          stdout=devnull, stderr=devnull)
    if ret != 0:
        log_write(log, "ERROR: cannot savedefconfig")
        return -1

    return 0

def do_build(**kwargs):
    """Run the build itself"""

    idir = "instance-%d" % kwargs['instance']
    log = kwargs['log']
    nice = kwargs['nice']

    # We need the absolute path to use with O=, because the relative
    # path to the output directory here is not relative to the
    # Buildroot sources, but to the location of the autobuilder
    # script.
    dldir = os.path.abspath(os.path.join(idir, "dl"))
    outputdir = os.path.abspath(os.path.join(idir, "output"))
    srcdir = os.path.join(idir, "buildroot")
    f = open(os.path.join(outputdir, "logfile"), "w+")
    log_write(log, "INFO: build started")

    cmd = ["timeout", str(MAX_DURATION),
            "nice", "-n", str(nice),
            "make", "O=%s" % outputdir,
            "-C", srcdir, "BR2_DL_DIR=%s" % dldir,
            "BR2_JLEVEL=%s" % kwargs['njobs']] \
          + kwargs['make_opts'].split()
    sub = subprocess.Popen(cmd, stdout=f, stderr=f)
    kwargs['buildpid'][kwargs['instance']] = sub.pid
    ret = sub.wait()
    kwargs['buildpid'][kwargs['instance']] = 0

    # 124 is a special error code that indicates we have reached the
    # timeout
    if ret == 124:
        log_write(log, "INFO: build timed out")
        return -2
    if ret != 0:
        log_write(log, "INFO: build failed")
        return -1
    cmd = ["make", "O=%s" % outputdir, "-C", srcdir,
            "BR2_DL_DIR=%s" % dldir, "legal-info"] \
          + kwargs['make_opts'].split()
    ret = subprocess.call(cmd, stdout=f, stderr=f)
    if ret != 0:
        log_write(log, "INFO: build failed during legal-info")
        return -1
    log_write(log, "INFO: build successful")
    return 0

def send_results(result, **kwargs):
    """Prepare and store/send tarball with results

    This function prepares the tarball with the results, and either
    submits them to the official server (if the appropriate credentials
    are available) or stores them locally as tarballs.
    """

    idir = "instance-%d" % kwargs['instance']
    log = kwargs['log']

    outputdir = os.path.abspath(os.path.join(idir, "output"))
    srcdir = os.path.join(idir, "buildroot")
    resultdir = os.path.join(outputdir, "results")

    os.mkdir(resultdir)

    shutil.copyfile(os.path.join(outputdir, ".config"),
                    os.path.join(resultdir, "config"))
    shutil.copyfile(os.path.join(outputdir, "defconfig"),
                    os.path.join(resultdir, "defconfig"))
    if os.path.exists(os.path.join(outputdir, "build", "build-time.log")):
        shutil.copyfile(os.path.join(outputdir, "build", "build-time.log"),
                        os.path.join(resultdir, "build-time.log"))
    if os.path.exists(os.path.join(outputdir, "legal-info", "manifest.csv")):
        shutil.copyfile(os.path.join(outputdir, "legal-info", "manifest.csv"),
                        os.path.join(resultdir, "licenses-manifest.csv"))

    subprocess.call(["git log master -n 1 --pretty=format:%%H > %s" % \
                     os.path.join(resultdir, "gitid")],
                    shell=True, cwd=srcdir)

    def get_failure_reason():
        # Output is a tuple (package, version), or None.
        lastlines = decode_bytes(subprocess.Popen(
            ["tail", "-n", "3", os.path.join(outputdir, "logfile")],
            stdout=subprocess.PIPE).communicate()[0]).splitlines()

        regexp = re.compile(r'make: \*\*\* .*/(?:build|toolchain)/([^/]*)/')
        for line in lastlines:
            m = regexp.search(line)
            if m:
                return m.group(1).rsplit('-', 1)

        # not found
        return None

    def extract_end_log(resultfile):
        """Save the last part of the build log, starting from the failed package"""

        def extract_last_500_lines():
            subprocess.call(["tail -500 %s > %s" % \
                             (os.path.join(outputdir, "logfile"), resultfile)],
                            shell=True)

        reason = get_failure_reason()
        if not reason:
            extract_last_500_lines()
        else:
            f = open(os.path.join(outputdir, "logfile"), 'r')
            mf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
            mf.seek(0)
            # Search for first action on the failed package
            offset = mf.find(encode_str('>>> %s' % ' '.join(reason)))
            if offset != -1:
                with open(resultfile, "w") as endlog:
                    endlog.write(decode_bytes(mf[offset:]))
            else:
                # not found, use last 500 lines as fallback
                extract_last_500_lines()

            mf.close()
            f.close()

    extract_end_log(os.path.join(resultdir, "build-end.log"))

    def copy_config_log_files():
        """Recursively copy any config.log files from the failing package"""

        reason = get_failure_reason()
        if not reason:
            return

        srcroot = os.path.join(outputdir, "build", '-'.join(reason))
        destroot = os.path.join(resultdir, '-'.join(reason))
        config_files = ('config.log', 'CMakeCache.txt', 'CMakeError.log',
            'CMakeOutput.log')

        for root, dirs, files in os.walk(srcroot):
            dest = os.path.join(destroot, os.path.relpath(root, srcroot))

            for fname in files:
                if fname in config_files:
                    if not os.path.exists(dest):
                        os.makedirs(dest)
                    shutil.copy(os.path.join(root, fname), os.path.join(dest, fname))

    copy_config_log_files()

    resultf = open(os.path.join(resultdir, "status"), "w+")
    if result == 0:
        resultf.write("OK")
    elif result == -1:
        resultf.write("NOK")
    elif result == -2:
        resultf.write("TIMEOUT")
    resultf.close()

    with open(os.path.join(resultdir, "submitter"), "w+") as submitterf:
        submitterf.write(kwargs['submitter'])

    # Yes, shutil.make_archive() would be nice, but it doesn't exist
    # in Python 2.6.
    ret = subprocess.call(["tar", "cjf", "results.tar.bz2", "results"],
                          cwd=outputdir, stdout=log, stderr=log)
    if ret != 0:
        log_write(log, "ERROR: could not make results tarball")
        sys.exit(1)

    if kwargs['upload']:
        # Submit results. Yes, Python has some HTTP libraries, but
        # none of the ones that are part of the standard library can
        # upload a file without writing dozens of lines of code.
        ret = subprocess.call(["curl", "-u",
                               "%s:%s" % (kwargs['http_login'], kwargs['http_password']),
                               "-H", "Expect:",
                               "-F", "uploadedfile=@%s" % os.path.join(outputdir, "results.tar.bz2"),
                               "-F", "uploadsubmit=1",
                               "http://autobuild.buildroot.org/submit/"],
                              stdout=log, stderr=log)
        if ret != 0:
            log_write(log, "INFO: results could not be submitted, %d" % ret)
        else:
            log_write(log, "INFO: results were submitted successfully")
    else:
        # No http login/password, keep tarballs locally
        with open(os.path.join(outputdir, "results.tar.bz2"), 'rb') as f:
            sha1 = hashlib.sha1(f.read()).hexdigest()
        resultfilename = "instance-%d-%s.tar.bz2" % (kwargs['instance'], sha1)
        os.rename(os.path.join(outputdir, "results.tar.bz2"), resultfilename)
        log_write(log, "INFO: results saved as %s" % resultfilename)

def run_instance(**kwargs):
    """Main per-instance loop

    Prepare the build, generate a configuration, run the build, and submit the
    results.
    """

    idir = "instance-%d" % kwargs['instance']

    # If it doesn't exist, create the instance directory
    if not os.path.exists(idir):
        os.mkdir(idir)

    kwargs['log'] = open(os.path.join(idir, "instance.log"), "a+")
    log_write(kwargs['log'], "INFO: instance started")

    while True:
        check_version()

        ret = prepare_build(**kwargs)
        if ret != 0:
            continue

        ret = gen_config(**kwargs)
        if ret != 0:
            continue

        ret = do_build(**kwargs)

        send_results(ret, **kwargs)

# args / config file merging inspired by:
# https://github.com/docopt/docopt/blob/master/examples/config_file_example.py

def load_ini_config(configfile):
    """Load configuration from file, returning a docopt-like dictionary"""

    if not os.path.exists(configfile):
        print("ERROR: configuration file %s does not exist" % configfile)
        sys.exit(1)

    config = configparser.RawConfigParser()
    if not config.read(configfile):
        print("ERROR: cannot parse configuration file %s" % configfile)
        sys.exit(1)

    # Prepend '--' to options specified in the config file, so they can be
    # merged with those given on the command-line
    return dict(('--%s' % key, value) for key, value in config.items('main'))


def merge(dict_1, dict_2):
    """Merge two dictionaries.

    Values that evaluate to true take priority over falsy values.
    `dict_1` takes priority over `dict_2`.

    """
    return dict((str(key), dict_1.get(key) or dict_2.get(key))
                for key in set(dict_2) | set(dict_1))

def main():

    # Avoid locale settings of autobuilder machine leaking in, for example
    # showing error messages in another language.
    os.environ['LC_ALL'] = 'C'

    check_version()
    sysinfo = SystemInfo()

    args = docopt.docopt(doc, version=VERSION)

    if args['--config']:
        ini_config = load_ini_config(args['--config'])
        # merge config/args, priority given to args
        args = merge(args, ini_config)

    # load in defaults at lowest priority
    args = merge(args, defaults)

    # Save our PID very early, so we can be stopped
    with open(args['--pid-file'], "w+") as pidf:
        pidf.write("%d" % os.getpid())

    # http_login/password could theoretically be allowed as empty, so check
    # explicitly on None.
    upload = (args['--http-login'] is not None) \
             and (args['--http-password'] is not None)
    if upload:
        sysinfo.needed_progs.append("curl")
    else:
        print("WARN: due to the lack of http login/password details, results will not be submitted")
        print("WARN: tarballs of results will be kept locally only")

    if not sysinfo.check_requirements():
        sys.exit(1)

    def sigterm_handler(signum, frame):
        """Kill all children"""

        # uninstall signal handler to prevent being called for all subprocesses
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        signal.signal(signal.SIGTERM, signal.SIG_DFL)

        # stop all instances to prevent new children to be spawned
        for p in processes:
            p.terminate()

        # kill build processes started with timeout (that puts its children
        # explicitly in a separate process group)
        for pid in buildpid:
            if pid == 0:
                continue
            try:
                os.kill(pid, signal.SIGTERM)
            except OSError as e:
                if e.errno != errno.ESRCH: # No such process, ignore
                    raise

        # kill any remaining children in our process group
        os.killpg(os.getpgid(os.getpid()), signal.SIGTERM)

        sys.exit(1)

    buildpid = multiprocessing.Array('i', int(args['--ninstances']))
    processes = []
    for i in range(0, int(args['--ninstances'])):
        p = multiprocessing.Process(target=run_instance, kwargs=dict(
                instance = i,
                njobs = args['--njobs'],
                sysinfo = sysinfo,
                http_login = args['--http-login'],
                http_password = args['--http-password'],
                submitter = args['--submitter'],
                make_opts = (args['--make-opts'] or ''),
                nice = (args['--nice'] or 0),
                upload = upload,
                buildpid = buildpid
            ))
        p.start()
        processes.append(p)

    signal.signal(signal.SIGINT, sigterm_handler)
    signal.signal(signal.SIGTERM, sigterm_handler)

    for p in processes:
        p.join()

if __name__ == '__main__':
    main()