aboutsummaryrefslogtreecommitdiff
path: root/scripts/autobuild-run
blob: 84e4d4095b01d3f52d7e3b2551031d9d617af25c (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
#!/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',
    '--http-url': 'http://autobuild.buildroot.org/',
    '--toolchains-csv': 'support/config-fragments/autobuild/toolchain-configs.csv',
    '--repo': 'https://github.com/buildroot/buildroot.git',
}

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-url URL                 URL of resource to submit your results.
                                 Defaults to %(--http-url)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.
  -d, --debug                    Send log output to stdout instead of log file
  --toolchains-csv CSVFILE       Toolchain configuration file
  -r, --repo URL                 URL of Buildroot repository to clone
                                 Defaults to %(--repo)s

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 stat
import sys
from time import localtime, strftime, sleep
from distutils.version import StrictVersion
import platform
from threading import Thread, Event
import datetime

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

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

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

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

    decode_bytes = _identity
    encode_str = _identity

# A number of packages can take > 60mins of build time (e.g
# gst-ffmpeg, qt5webkit, mimic)
HUNG_BUILD_TIMEOUT = 120 # mins
VERSION = 1

def rm_ro(f, p, _):
    """Handler for rmtree() to remove read-only files and directories
    """
    os.chmod(os.path.dirname(p), stat.S_IRWXU)
    os.chmod(p, stat.S_IRWXU) # 'X' if p is a directory, benign if a file
    f(p)

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

class SystemInfo:
    DEFAULT_NEEDED_PROGS = ["make", "git", "gcc"]
    DEFAULT_OPTIONAL_PROGS = ["bzr", "diffoscope", "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

class Builder:
    def __init__(self, instance, njobs, sysinfo,
                 http_url, http_login, http_password,
                 submitter, make_opts, nice, toolchains_csv,
                 repo, upload, buildpid, debug):
        self.instance = instance
        self.njobs = njobs
        self.sysinfo = sysinfo
        self.http_url = http_url
        self.http_login = http_login
        self.http_password = http_password
        self.submitter = submitter
        self.make_opts = make_opts
        self.nice = nice
        self.toolchains_csv = toolchains_csv
        self.repo = repo
        self.upload = upload
        self.buildpid = buildpid
        self.debug = debug
        self.build_parallel = False

        # frequently needed directories
        self.idir = "instance-%d" % self.instance
        self.srcdir = os.path.join(self.idir, "buildroot")
        self.dldir = os.path.abspath(os.path.join(self.idir, "dl"))
        # 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.
        self.outputdir = os.path.abspath(os.path.join(self.idir, "output-1"))
        # We use a different output directory for more variance in reproducibility
        # testing.
        self.outputdir_2 = os.path.abspath(os.path.join(self.idir, "output-2"))
        self.resultdir = os.path.join(self.outputdir, "results")

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

        if self.debug:
            self.log = sys.stdout
        else:
            self.log = open(os.path.join(self.idir, "instance.log"), "a+")

    def check_version(self):
        with urlopen_closing(urlparse.urljoin(self.http_url, 'version')) as r:
            version = int(decode_bytes(r.readline()).strip())
        if version > VERSION:
            print("ERROR: script version too old, please upgrade.")
            sys.exit(1)

    def get_branch(self):
        """Returns the branch that should be built. It fetches a CSV file from
        the autobuild server that provides the list of branches to test
        (first field) and their weight (second field). We build a list of
        branches, where the branch name is repeated N times, with N being
        the weight of the branch. We then pick a random branch in this
        list. This way, branches with a higher weight are more likely to
        be selected.
        """
        csv_branches = []
        with urlopen_closing(urlparse.urljoin(self.http_url, 'branches')) as r:
            for l in r.readlines():
                csv_branches.append(decode_bytes(l))
        branches = []
        for branch in csv.reader(csv_branches):
            branches += [branch[0]] * int(branch[1])

        return branches[randint(0, len(branches) - 1)]

    def prepare_build(self):
        """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.
        """

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

        # Create the download directory if it doesn't exist
        if not os.path.exists(self.dldir):
            os.mkdir(self.dldir)

        # recursively find files under root
        def find_files(root):
            for r, d, f in os.walk(root):
                # do not remove individual files from git caches. 'git' can
                # be either dl/<package>/git or dl/git and we want to
                # eventually remove tarballs for the git package, so check
                # for '.git' instead to match only dl/<package>/git/.git .
                if '.git' in d:
                    del d[:]
                    continue
                for i in f:
                    yield os.path.join(r, i)

        # 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 = list(find_files(self.dldir))
            if not flist:
                break
            f = flist[randint(0, len(flist) - 1)]
            log_write(self.log, "INFO: removing %s from downloads" %
                      os.path.relpath(f, self.dldir))
            os.remove(f)

        branch = self.get_branch()
        log_write(self.log, "INFO: testing branch '%s'" % branch)

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

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

        ret = subprocess.call(["git", "checkout", "FETCH_HEAD"], cwd=abssrcdir, stdout=self.log, stderr=self.log)
        if ret != 0:
            log_write(self.log, "ERROR: could not check out Buildroot sources")
            return -1

        # Create an empty output directory. We remove it first, in case a previous build was aborted.
        if os.path.exists(self.outputdir):
            shutil.rmtree(self.outputdir, onerror=rm_ro)
        os.mkdir(self.outputdir)

        # If it exists, remove the other output directory used for reproducibility testing
        if os.path.exists(self.outputdir_2):
            shutil.rmtree(self.outputdir_2, onerror=rm_ro)
        with open(os.path.join(self.outputdir, "branch"), "w") as branchf:
            branchf.write(branch)

        return 0

    def gen_config(self):
        """Generate a new random configuration."""

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

        if self.debug:
            devnull = self.log
        else:
            devnull = open(os.devnull, "w")

        args = [os.path.join(self.srcdir, "utils/genrandconfig"),
                "-o", self.outputdir, "-b", self.srcdir]

        toolchains_csv = self.toolchains_csv
        if toolchains_csv:
            if not os.path.isabs(toolchains_csv):
                toolchains_csv = os.path.join(self.srcdir, toolchains_csv)
            args.extend(["--toolchains-csv", toolchains_csv])

        ret = subprocess.call(args, stdout=devnull, stderr=self.log)
        return ret

    def stop_on_build_hang(self, monitor_thread_hung_build_flag,
                           monitor_thread_stop_flag, sub_proc,
                           outputdir):
        build_time_logfile = os.path.join(outputdir, "build/build-time.log")
        while True:
            if monitor_thread_stop_flag.is_set():
                return
            if os.path.exists(build_time_logfile):
                mtime = datetime.datetime.fromtimestamp(os.stat(build_time_logfile).st_mtime)

                if mtime < datetime.datetime.now() - datetime.timedelta(minutes=HUNG_BUILD_TIMEOUT):
                    if sub_proc.poll() is None:
                        monitor_thread_hung_build_flag.set() # Used by do_build() to determine build hang
                        log_write(self.log, "INFO: build hung")
                        sub_proc.kill()
                    break
            monitor_thread_stop_flag.wait(30)

    def check_reproducibility(self):
        """Check reproducibility of builds

        Use diffoscope on the built images, if diffoscope is not
        installed, fallback to cmp
        """

        reproducible_results = os.path.join(self.outputdir, "results", "diffoscope-results.json")
        reproducible_results_txt = os.path.join(self.outputdir, "results", "diffoscope-results.txt")
        # Using only tar images for now
        build_1_image = os.path.join(self.outputdir, "images", "rootfs.tar")
        build_2_image = os.path.join(self.outputdir_2, "images", "rootfs.tar")

        with open(reproducible_results, 'w') as diff:
            if self.sysinfo.has("diffoscope"):
                # Prefix to point diffoscope towards cross-tools
                prefix = subprocess.check_output(["make", "--no-print-directory", "O=%s" % self.outputdir,
                                                  "-C", self.srcdir, "printvars", "VARS=TARGET_CROSS"])
                # Remove TARGET_CROSS= and \n from the string
                prefix = prefix[13:-1]
                log_write(self.log, "INFO: running diffoscope on images")
                subprocess.call(["diffoscope", build_1_image, build_2_image,
                                 "--tool-prefix-binutils", prefix, "--json", reproducible_results,
                                 "--text", reproducible_results_txt, "--max-text-report-size", "40000"],
                                stderr=self.log)
            else:
                log_write(self.log, "INFO: diffoscope not installed, falling back to cmp")
                subprocess.call(["cmp", "-b", build_1_image, build_2_image], stdout=diff, stderr=self.log)

        if os.stat(reproducible_results).st_size > 0:
            log_write(self.log, "INFO: Build is non-reproducible.")
            return -1

        # rootfs images match byte-for-byte -> reproducible image
        log_write(self.log, "INFO: Build is reproducible!")
        return 0

    def do_build(self, outputdir):
        """Run the build itself"""

        f = open(os.path.join(outputdir, "logfile"), "w+")
        log_write(self.log, "INFO: build started")

        cmd = ["nice", "-n", str(self.nice),
               "make", "O=%s" % outputdir,
               "-C", self.srcdir, "BR2_DL_DIR=%s" % self.dldir,
               "BR2_JLEVEL=%s" % self.njobs] \
            + self.make_opts.split()

        # when building in parallel, we use both -jX and BR2_JLEVEL=X,
        # trusting the make job server to properly throttle the total
        # number of processes.
        if self.build_parallel:
            cmd.append("-j%s" % self.njobs)

        sub = subprocess.Popen(cmd, stdout=f, stderr=f)

        # Setup hung build monitoring thread
        monitor_thread_hung_build_flag = Event()
        monitor_thread_stop_flag = Event()
        build_monitor = Thread(target=self.stop_on_build_hang,
                               args=(monitor_thread_hung_build_flag,
                                     monitor_thread_stop_flag,
                                     sub, outputdir))
        build_monitor.daemon = True
        build_monitor.start()

        self.buildpid[self.instance] = sub.pid
        ret = sub.wait()
        self.buildpid[self.instance] = 0

        # If build failed, monitor thread would have exited at this point
        if monitor_thread_hung_build_flag.is_set():
            log_write(self.log, "INFO: build timed out [%d]" % ret)
            return -2
        else:
            # Stop monitor thread as this build didn't timeout
            monitor_thread_stop_flag.set()
        # Monitor thread should be exiting around this point

        if ret != 0:
            log_write(self.log, "INFO: build failed [%d]" % ret)
            return -1

        cmd = ["make", "O=%s" % outputdir, "-C", self.srcdir,
               "BR2_DL_DIR=%s" % self.dldir, "legal-info"] \
            + self.make_opts.split()
        ret = subprocess.call(cmd, stdout=f, stderr=f)
        if ret != 0:
            log_write(self.log, "INFO: build failed during legal-info")
            return -1
        log_write(self.log, "INFO: build successful")
        return 0

    def do_reproducible_build(self):
        """Run the builds for reproducibility testing

        Build twice with the same configuration. Calls do_build() to
        perform the actual build.
        """

        # Start the first build
        log_write(self.log, "INFO: Reproducible Build Test, starting build 1")
        ret = self.do_build(self.outputdir)
        if ret != 0:
            log_write(self.log, "INFO: build 1 failed, skipping build 2")
            return ret

        # Create the second output directory if it does not exist
        if not os.path.exists(self.outputdir_2):
            os.mkdir(self.outputdir_2)

        # Copy .config to the other output directory
        shutil.copyfile(os.path.join(self.outputdir, ".config"),
                        os.path.join(self.outputdir_2, ".config"))

        # Start the second build
        log_write(self.log, "INFO: Reproducible Build Test, starting build 2")
        ret = self.do_build(self.outputdir_2)
        if ret != 0:
            log_write(self.log, "INFO: build 2 failed")
            return ret

        # Assuming both have built successfully
        ret = self.check_reproducibility()
        return ret

    def send_results(self, result):
        """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.
        """

        shutil.copyfile(os.path.join(self.outputdir, ".config"),
                        os.path.join(self.resultdir, "config"))
        shutil.copyfile(os.path.join(self.outputdir, "defconfig"),
                        os.path.join(self.resultdir, "defconfig"))
        shutil.copyfile(os.path.join(self.outputdir, "branch"),
                        os.path.join(self.resultdir, "branch"))

        def copy_if_exists(directory, src, dst=None):
            if os.path.exists(os.path.join(self.outputdir, directory, src)):
                shutil.copyfile(os.path.join(self.outputdir, directory, src),
                                os.path.join(self.resultdir, src if dst is None else dst))

        copy_if_exists("build", "build-time.log")
        copy_if_exists("build", "packages-file-list.txt")
        copy_if_exists("build", "packages-file-list-host.txt")
        copy_if_exists("build", "packages-file-list-staging.txt")
        copy_if_exists("legal-info", "manifest.csv", "licenses-manifest.csv")

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

        # Return True if the result should be rejected, False otherwise
        def reject_results():
            lastlines = decode_bytes(subprocess.Popen(
                ["tail", "-n", "3", os.path.join(self.outputdir, "logfile")],
                stdout=subprocess.PIPE).communicate()[0]).splitlines()

            # Reject results where qemu-user refused to build
            regexp = re.compile(r'^package/qemu/qemu.mk:.*Refusing to build qemu-user')
            for line in lastlines:
                if regexp.match(line):
                    return True

            return False

        if reject_results():
            return

        def get_failure_reason():
            # Output is a tuple (package, version), or None.
            lastlines = decode_bytes(subprocess.Popen(
                ["tail", "-n", "3", os.path.join(self.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

        reason = get_failure_reason()
        if reason:
            with open(os.path.join(self.resultdir, "reason"), "w+") as reasonf:
                reasonf.write("-".join(reason))

        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(self.outputdir, "logfile"), resultfile)],
                                shell=True)

            if not reason:
                extract_last_500_lines()
            else:
                f = open(os.path.join(self.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(self.resultdir, "build-end.log"))

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

            if not reason:
                return

            srcroot = os.path.join(self.outputdir, "build", '-'.join(reason))
            destroot = os.path.join(self.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(self.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(self.resultdir, "submitter"), "w+") as submitterf:
            submitterf.write(self.submitter)

        def get_os_release_path():
            for p in ['/etc/os-release', '/usr/lib/os-release']:
                if os.path.exists(p):
                    return p
            return None

        def save_host_distro_info():
            host_distro = os.path.join(self.resultdir, "host-distro")
            os_release = get_os_release_path()
            if os_release is None:
                with open(host_distro, "w") as f:
                    f.write('Unknown')
            else:
                shutil.copyfile(os_release, host_distro)

        save_host_distro_info()

        # 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=self.outputdir, stdout=self.log, stderr=self.log)
        if ret != 0:
            log_write(self.log, "ERROR: could not make results tarball")
            sys.exit(1)

        if self.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" % (self.http_login, self.http_password),
                                   "-H", "Expect:",
                                   "-F", "uploadedfile=@%s" % os.path.join(self.outputdir, "results.tar.bz2"),
                                   "-F", "uploadsubmit=1",
                                   urlparse.urljoin(self.http_url, 'submit/')],
                                  stdout=self.log, stderr=self.log)
            if ret != 0:
                log_write(self.log, "INFO: results could not be submitted, %d" % ret)
            else:
                log_write(self.log, "INFO: results were submitted successfully")
        else:
            # No http login/password, keep tarballs locally
            with open(os.path.join(self.outputdir, "results.tar.bz2"), 'rb') as f:
                sha1 = hashlib.sha1(f.read()).hexdigest()
            resultfilename = "instance-%d-%s.tar.bz2" % (self.instance, sha1)
            os.rename(os.path.join(self.outputdir, "results.tar.bz2"), resultfilename)
            summaryfilename = "instance-%d-%s.summary" % (self.instance, sha1)
            with open(summaryfilename, 'wt') as f:
                f.write("%d,%s\n" % (result, ','.join(reason or ("", ))))

            log_write(self.log, "INFO: results saved as %s" % resultfilename)

    def run_one_build(self):
        self.check_version()

        ret = self.prepare_build()
        if ret != 0:
            return

        os.mkdir(self.resultdir)

        ret = self.gen_config()
        if ret != 0:
            log_write(self.log, "WARN: failed to generate configuration")
            return

        # Check if the build test is supposed to be a reproducible test
        with open(os.path.join(self.outputdir, ".config"), "r") as fconf:
            conf = fconf.read()
            reproducible = "BR2_REPRODUCIBLE=y\n" in conf
            per_package = "BR2_PER_PACKAGE_DIRECTORIES=y\n" in conf

        self.build_parallel = per_package and randint(0, 1) == 0

        if reproducible:
            ret = self.do_reproducible_build()
        else:
            ret = self.do_build(self.outputdir)

        self.send_results(ret)

    def run_instance(self):
        """Main per-instance loop

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

        log_write(self.log, "INFO: instance started")

        while True:
            try:
                self.run_one_build()
            except URLError, e:
                sleep(30)

# 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'

    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)

    # Enforce the sanest umask here, to avoid buildroot doing it on its
    # own and causing a double-make call, thus adding extraneous lines
    # in case of failures.
    os.umask(0o022)

    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'])):
        builder = Builder(
            instance = i,
            njobs = args['--njobs'],
            sysinfo = sysinfo,
            http_url = args['--http-url'],
            http_login = args['--http-login'],
            http_password = args['--http-password'],
            submitter = args['--submitter'],
            make_opts = (args['--make-opts'] or ''),
            nice = (args['--nice'] or 0),
            toolchains_csv = args['--toolchains-csv'],
            repo = args['--repo'],
            upload = upload,
            buildpid = buildpid,
            debug = args['--debug'])
        p = multiprocessing.Process(target=builder.run_instance)
        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()