phase2: remove unused 'other_builds' property
[buildbot.git] / phase2 / master.cfg
index 58c5e5795dfe069e31364735a6213fa6b1b2ad16..5e8b71cb9f9f42a83970814e917009cd2e876cf6 100644 (file)
@@ -3,17 +3,26 @@
 
 import os
 import re
+import sys
 import base64
 import subprocess
 import configparser
 
+from dateutil.tz import tzutc
+from datetime import datetime, timedelta
+
+from twisted.internet import defer
+from twisted.python import log
+
 from buildbot import locks
+from buildbot.data import resultspec
 from buildbot.changes import filter
 from buildbot.changes.gitpoller import GitPoller
 from buildbot.config import BuilderConfig
 from buildbot.plugins import schedulers
 from buildbot.plugins import steps
 from buildbot.plugins import util
+from buildbot.process import results
 from buildbot.process.factory import BuildFactory
 from buildbot.process.properties import Property
 from buildbot.process.properties import WithProperties
@@ -28,6 +37,10 @@ from buildbot.steps.transfer import StringDownload
 from buildbot.worker import Worker
 
 
+if not os.path.exists("twistd.pid"):
+    with open("twistd.pid", "w") as pidfile:
+        pidfile.write("{}".format(os.getpid()))
+
 ini = configparser.ConfigParser()
 ini.read(os.getenv("BUILDMASTER_CONFIG", "./config.ini"))
 
@@ -40,28 +53,24 @@ buildbot_url = ini.get("phase2", "buildbot_url")
 # a shorter alias to save typing.
 c = BuildmasterConfig = {}
 
-####### BUILDSLAVES
+####### BUILDWORKERS
 
-# The 'workers' list defines the set of recognized buildslaves. Each element is
-# a Worker object, specifying a unique slave name and password.  The same
-# slave name and password must be configured on the slave.
+# The 'workers' list defines the set of recognized buildworkers. Each element is
+# a Worker object, specifying a unique worker name and password.  The same
+# worker name and password must be configured on the worker.
 
-slave_port = 9990
+worker_port = 9990
 persistent = False
-other_builds = 0
 tree_expire = 0
 git_ssh = False
 git_ssh_key = None
 
 if ini.has_option("phase2", "port"):
-       slave_port = ini.get("phase2", "port")
+       worker_port = ini.get("phase2", "port")
 
 if ini.has_option("phase2", "persistent"):
        persistent = ini.getboolean("phase2", "persistent")
 
-if ini.has_option("phase2", "other_builds"):
-       other_builds = ini.getint("phase2", "other_builds")
-
 if ini.has_option("phase2", "expire"):
        tree_expire = ini.getint("phase2", "expire")
 
@@ -77,9 +86,9 @@ c['workers'] = []
 max_builds = dict()
 
 for section in ini.sections():
-       if section.startswith("slave "):
+       if section.startswith("worker "):
                if ini.has_option(section, "name") and ini.has_option(section, "password") and \
-                  ini.has_option(section, "phase") and ini.getint(section, "phase") == 2:
+                       ini.has_option(section, "phase") and ini.getint(section, "phase") == 2:
                        name = ini.get(section, "name")
                        password = ini.get(section, "password")
                        sl_props = { 'shared_wd': False }
@@ -98,17 +107,19 @@ for section in ini.sections():
 
                        c['workers'].append(Worker(name, password, max_builds = max_builds[name], properties = sl_props))
 
-# 'slavePortnum' defines the TCP port to listen on for connections from workers.
-# This must match the value configured into the buildslaves (with their
+# 'workerPortnum' defines the TCP port to listen on for connections from workers.
+# This must match the value configured into the buildworkers (with their
 # --master option)
-c['protocols'] = {'pb': {'port': slave_port}}
+c['protocols'] = {'pb': {'port': worker_port}}
 
 # coalesce builds
 c['collapseRequests'] = True
 
 # Reduce amount of backlog data
-c['buildHorizon'] = 30
-c['logHorizon'] = 20
+c['configurators'] = [util.JanitorConfigurator(
+    logHorizon=timedelta(days=3),
+    hour=6,
+)]
 
 ####### CHANGESOURCES
 
@@ -163,6 +174,7 @@ if not os.path.isdir(work_dir+'/source.git'):
 else:
        subprocess.call(["git", "pull"], cwd = work_dir+'/source.git')
 
+os.makedirs(work_dir+'/source.git/tmp', exist_ok=True)
 findarches = subprocess.Popen(['./scripts/dump-target-info.pl', 'architectures'],
        stdout = subprocess.PIPE, cwd = work_dir+'/source.git')
 
@@ -183,7 +195,7 @@ c['change_source'] = []
 
 def parse_feed_entry(line):
        parts = line.strip().split()
-       if parts[0] == "src-git":
+       if parts[0].startswith("src-git"):
                feeds.append(parts)
                url = parts[2].strip().split(';')
                branch = url[1] if len(url) > 1 else 'master'
@@ -195,12 +207,15 @@ make = subprocess.Popen(['make', '--no-print-directory', '-C', work_dir+'/source
 
 line = make.stdout.readline()
 if line:
-       parse_feed_entry(line)
+       parse_feed_entry(str(line, 'utf-8'))
 
-with open(work_dir+'/source.git/feeds.conf.default', 'r') as f:
+with open(work_dir+'/source.git/feeds.conf.default', 'r', encoding='utf-8') as f:
        for line in f:
                parse_feed_entry(line)
 
+if len(c['change_source']) == 0:
+       log.err("FATAL ERROR: no change_sources defined, aborting!")
+       sys.exit(-1)
 
 ####### SCHEDULERS
 
@@ -262,7 +277,7 @@ c['schedulers'].append(ForceScheduler(
 
 # The 'builders' list defines the Builders, which tell Buildbot how to perform a build:
 # what steps, and which workers can execute them.  Note that any particular build will
-# only take place on one slave.
+# only take place on one worker.
 
 def GetDirectorySuffix(props):
        verpat = re.compile(r'^([0-9]{2})\.([0-9]{2})(?:\.([0-9]+)(?:-rc([0-9]+))?|-(SNAPSHOT))$')
@@ -274,7 +289,7 @@ def GetDirectorySuffix(props):
 
 def GetNumJobs(props):
        if props.hasProperty("workername") and props.hasProperty("nproc"):
-               return ((int(props["nproc"]) / (max_builds[props["workername"]] + other_builds)) + 1)
+               return ((int(props["nproc"]) / max_builds[props["workername"]]) + 1)
        else:
                return 1
 
@@ -304,7 +319,7 @@ def IsArchitectureSelected(target):
 def UsignSec2Pub(seckey, comment="untrusted comment: secret key"):
        try:
                seckey = base64.b64decode(seckey)
-       except:
+       except Exception:
                return None
 
        return "{}\n{}".format(re.sub(r"\bsecret key$", "public key", comment),
@@ -313,21 +328,96 @@ def UsignSec2Pub(seckey, comment="untrusted comment: secret key"):
 def IsSharedWorkdir(step):
        return bool(step.getProperty("shared_wd"))
 
+@defer.inlineCallbacks
+def getNewestCompleteTime(bldr):
+       """Returns the complete_at of the latest completed and not SKIPPED
+       build request for this builder, or None if there are no such build
+       requests. We need to filter out SKIPPED requests because we're
+       using collapseRequests=True which is unfortunately marking all
+       previous requests as complete when new buildset is created.
+
+       @returns: datetime instance or None, via Deferred
+       """
+
+       bldrid = yield bldr.getBuilderId()
+       completed = yield bldr.master.data.get(
+                       ('builders', bldrid, 'buildrequests'),
+                       [
+                               resultspec.Filter('complete', 'eq', [True]),
+                               resultspec.Filter('results', 'ne', [results.SKIPPED]),
+                       ],
+                       order=['-complete_at'], limit=1)
+       if not completed:
+               return
+
+       complete_at = completed[0]['complete_at']
+
+       last_build = yield bldr.master.data.get(
+                       ('builds', ),
+                       [
+                               resultspec.Filter('builderid', 'eq', [bldrid]),
+                       ],
+                       order=['-started_at'], limit=1)
+
+       if last_build and last_build[0]:
+               last_complete_at = last_build[0]['complete_at']
+               if last_complete_at and (last_complete_at > complete_at):
+                       return last_complete_at
+
+       return complete_at
+
+@defer.inlineCallbacks
+def prioritizeBuilders(master, builders):
+       """Returns sorted list of builders by their last timestamp of completed and
+       not skipped build.
+
+       @returns: list of sorted builders
+       """
+
+       def is_building(bldr):
+               return bool(bldr.building) or bool(bldr.old_building)
+
+       def bldr_info(bldr):
+               d = defer.maybeDeferred(getNewestCompleteTime, bldr)
+               d.addCallback(lambda complete_at: (complete_at, bldr))
+               return d
+
+       def bldr_sort(item):
+               (complete_at, bldr) = item
 
+               if not complete_at:
+                       date = datetime.min
+                       complete_at = date.replace(tzinfo=tzutc())
+
+               if is_building(bldr):
+                       date = datetime.max
+                       complete_at = date.replace(tzinfo=tzutc())
+
+               return (complete_at, bldr.name)
+
+       results = yield defer.gatherResults([bldr_info(bldr) for bldr in builders])
+       results.sort(key=bldr_sort)
+
+       for r in results:
+               log.msg("prioritizeBuilders: {:>20} complete_at: {}".format(r[1].name, r[0]))
+
+       return [r[1] for r in results]
+
+c['prioritizeBuilders'] = prioritizeBuilders
 c['builders'] = []
 
-dlLock = locks.WorkerLock("slave_dl")
+dlLock = locks.WorkerLock("worker_dl")
 
-slaveNames = [ ]
+workerNames = [ ]
 
-for slave in c['workers']:
-       slaveNames.append(slave.workername)
+for worker in c['workers']:
+       workerNames.append(worker.workername)
 
 force_factory = BuildFactory()
 
 c['builders'].append(BuilderConfig(
        name        = "00_force_build",
-       workernames = slaveNames,
+       workernames = workerNames,
        factory     = force_factory))
 
 for arch in arches:
@@ -527,7 +617,9 @@ for arch in arches:
                description = "Clearing failure logs",
                workdir = "build/sdk",
                command = ["rm", "-rf", "logs/package/error.txt", "faillogs/"],
-               haltOnFailure = False
+               haltOnFailure = False,
+               flunkOnFailure = False,
+               warnOnFailure = True,
        ))
 
        factory.addStep(ShellCommand(
@@ -624,7 +716,9 @@ for arch in arches:
                description = "Finding failure logs",
                workdir = "build/sdk/logs/package/feeds",
                command = ["sh", "-c", "sed -ne 's!^ *ERROR: package/feeds/\\([^ ]*\\) .*$!\\1!p' ../error.txt | sort -u | xargs -r find > ../../../logs.txt"],
-               haltOnFailure = False
+               haltOnFailure = False,
+               flunkOnFailure = False,
+               warnOnFailure = True,
        ))
 
        factory.addStep(ShellCommand(
@@ -632,7 +726,9 @@ for arch in arches:
                description = "Collecting failure logs",
                workdir = "build/sdk",
                command = ["rsync", "-av", "--files-from=logs.txt", "logs/package/feeds/", "faillogs/"],
-               haltOnFailure = False
+               haltOnFailure = False,
+               flunkOnFailure = False,
+               warnOnFailure = True,
        ))
 
        factory.addStep(ShellCommand(
@@ -642,6 +738,8 @@ for arch in arches:
                command = ["rsync", "-4", "--progress", "--delete", "--delay-updates", "--partial-dir=.~tmp~%s" %(arch[0]), "-avz", "faillogs/", WithProperties("%s/faillogs%%(suffix)s/%s/" %(rsync_bin_url, arch[0]), suffix=GetDirectorySuffix)],
                env={'RSYNC_PASSWORD': rsync_bin_key},
                haltOnFailure = False,
+               flunkOnFailure = False,
+               warnOnFailure = True,
                logEnviron = False
        ))
 
@@ -650,7 +748,7 @@ for arch in arches:
                        name = "sourcelist",
                        description = "Finding source archives to upload",
                        workdir = "build/sdk",
-                       command = "find dl/ -maxdepth 1 -type f -not -size 0 -not -name '.*' -newer ../sdk.archive -printf '%f\\n' > sourcelist",
+                       command = "find dl/ -maxdepth 1 -type f -not -size 0 -not -name '.*' -not -name '*.hash' -not -name '*.dl' -newer ../sdk.archive -printf '%f\\n' > sourcelist",
                        haltOnFailure = True
                ))
 
@@ -659,9 +757,11 @@ for arch in arches:
                        description = "Uploading source archives",
                        workdir = "build/sdk",
                        command = ["rsync", "--files-from=sourcelist", "-4", "--progress", "--checksum", "--delay-updates",
-                                  WithProperties("--partial-dir=.~tmp~%s~%%(workername)s" %(arch[0])), "-avz", "dl/", "%s/" %(rsync_src_url)],
+                                       WithProperties("--partial-dir=.~tmp~%s~%%(workername)s" %(arch[0])), "-avz", "dl/", "%s/" %(rsync_src_url)],
                        env={'RSYNC_PASSWORD': rsync_src_key},
                        haltOnFailure = False,
+                       flunkOnFailure = False,
+                       warnOnFailure = True,
                        logEnviron = False
                ))
 
@@ -671,10 +771,23 @@ for arch in arches:
                command=["df", "-h", "."],
                env={'LC_ALL': 'C'},
                haltOnFailure = False,
+               flunkOnFailure = False,
+               warnOnFailure = False,
+               alwaysRun = True
+       ))
+
+       factory.addStep(ShellCommand(
+               name = "du",
+               description = "Reporting estimated file space usage",
+               command=["du", "-sh", "."],
+               env={'LC_ALL': 'C'},
+               haltOnFailure = False,
+               flunkOnFailure = False,
+               warnOnFailure = False,
                alwaysRun = True
        ))
 
-       c['builders'].append(BuilderConfig(name=arch[0], workernames=slaveNames, factory=factory))
+       c['builders'].append(BuilderConfig(name=arch[0], workernames=workerNames, factory=factory))
 
        c['schedulers'].append(schedulers.Triggerable(name="trigger_%s" % arch[0], builderNames=[ arch[0] ]))
        force_factory.addStep(steps.Trigger(