buildbot-nix/buildbot_nix/__init__.py

760 lines
25 KiB
Python
Raw Normal View History

2023-09-10 08:11:56 +00:00
import json
import multiprocessing
import os
2023-09-17 20:14:56 +00:00
import sys
2023-09-10 08:11:56 +00:00
import uuid
from collections import defaultdict
2023-09-17 20:14:56 +00:00
from collections.abc import Generator
from dataclasses import dataclass
2023-09-10 08:11:56 +00:00
from pathlib import Path
2023-12-26 20:56:36 +00:00
from typing import TYPE_CHECKING, Any
2023-12-26 18:49:57 +00:00
2023-09-17 20:14:56 +00:00
from buildbot.configurators import ConfiguratorBase
2023-10-15 06:36:45 +00:00
from buildbot.plugins import reporters, schedulers, secrets, steps, util, worker
2023-09-10 08:11:56 +00:00
from buildbot.process import buildstep, logobserver, remotecommand
2023-09-17 20:14:56 +00:00
from buildbot.process.project import Project
from buildbot.process.properties import Interpolate, Properties
2023-09-10 08:11:56 +00:00
from buildbot.process.results import ALL_RESULTS, statusToString
from buildbot.steps.trigger import Trigger
2023-12-03 10:48:01 +00:00
from buildbot.util import asyncSleep
from buildbot.www.authz.endpointmatchers import EndpointMatcherBase, Match
from buildbot.www.oauth2 import OAuth2Auth
from buildbot.changes.gerritchangesource import GerritChangeSource
2023-10-27 08:49:40 +00:00
2023-12-26 20:56:36 +00:00
if TYPE_CHECKING:
from buildbot.process.log import Log
from twisted.internet import defer, threads
from twisted.logger import Logger
from twisted.python.failure import Failure
2023-12-03 10:48:01 +00:00
from .github_projects import (
2023-10-27 08:49:40 +00:00
slugify_project_name,
2023-10-15 06:36:45 +00:00
)
2023-09-10 08:11:56 +00:00
2023-11-18 07:18:46 +00:00
SKIPPED_BUILDER_NAME = "skipped-builds"
log = Logger()
class LixSystemsOAuth2(OAuth2Auth):
name = 'Lix'
faIcon = 'fa-login'
resourceEndpoint = "https://identity.lix.systems"
# is passing scope necessary?
authUri = 'https://identity.lix.systems/realms/lix-project/protocol/openid-connect/auth'
tokenUri = 'https://identity.lix.systems/realms/lix-project/protocol/openid-connect/token'
2023-09-10 08:11:56 +00:00
2023-12-26 20:56:36 +00:00
class BuildbotNixError(Exception):
pass
@dataclass
class GerritProject:
# `project` field.
name: str
2023-12-26 20:56:36 +00:00
2023-09-10 08:11:56 +00:00
class BuildTrigger(Trigger):
2023-12-26 20:56:36 +00:00
"""Dynamic trigger that creates a build for every attribute."""
2023-09-10 08:11:56 +00:00
def __init__(
2023-11-18 07:18:46 +00:00
self,
builds_scheduler: str,
skipped_builds_scheduler: str,
jobs: list[dict[str, Any]],
**kwargs: Any,
2023-09-10 08:11:56 +00:00
) -> None:
if "name" not in kwargs:
kwargs["name"] = "trigger"
self.jobs = jobs
self.config = None
2023-11-18 07:18:46 +00:00
self.builds_scheduler = builds_scheduler
self.skipped_builds_scheduler = skipped_builds_scheduler
2023-09-10 08:11:56 +00:00
Trigger.__init__(
self,
waitForFinish=True,
2023-11-18 07:18:46 +00:00
schedulerNames=[builds_scheduler, skipped_builds_scheduler],
2023-09-10 08:11:56 +00:00
haltOnFailure=True,
flunkOnFailure=True,
sourceStamps=[],
alwaysUseLatest=False,
updateSourceStamp=False,
**kwargs,
)
def createTriggerProperties(self, props: Any) -> Any: # noqa: N802
2023-09-10 08:11:56 +00:00
return props
def getSchedulersAndProperties(self) -> list[tuple[str, Properties]]: # noqa: N802
2023-09-10 08:11:56 +00:00
build_props = self.build.getProperties()
repo_name = build_props.getProperty(
"github.base.repo.full_name",
build_props.getProperty("github.repository.full_name"),
)
project_id = slugify_project_name(repo_name)
2023-09-10 08:11:56 +00:00
source = f"nix-eval-{project_id}"
triggered_schedulers = []
for job in self.jobs:
attr = job.get("attr", "eval-error")
name = attr
if repo_name is not None:
name = f"github:{repo_name}#checks.{name}"
else:
name = f"checks.{name}"
error = job.get("error")
2023-11-18 07:18:46 +00:00
props = Properties()
props.setProperty("virtual_builder_name", name, source)
props.setProperty("status_name", f"nix-build .#checks.{attr}", source)
2023-11-18 07:18:46 +00:00
props.setProperty("virtual_builder_tags", "", source)
if error is not None:
props.setProperty("error", error, source)
triggered_schedulers.append((self.skipped_builds_scheduler, props))
continue
if job.get("isCached"):
triggered_schedulers.append((self.skipped_builds_scheduler, props))
continue
drv_path = job.get("drvPath")
2023-09-10 08:11:56 +00:00
system = job.get("system")
out_path = job.get("outputs", {}).get("out")
build_props.setProperty(f"{attr}-out_path", out_path, source)
build_props.setProperty(f"{attr}-drv_path", drv_path, source)
props.setProperty("attr", attr, source)
props.setProperty("system", system, source)
props.setProperty("drv_path", drv_path, source)
props.setProperty("out_path", out_path, source)
# we use this to identify builds when running a retry
props.setProperty("build_uuid", str(uuid.uuid4()), source)
2023-11-17 15:27:55 +00:00
2023-11-18 07:18:46 +00:00
triggered_schedulers.append((self.builds_scheduler, props))
2023-09-10 08:11:56 +00:00
return triggered_schedulers
def getCurrentSummary(self) -> dict[str, str]: # noqa: N802
2023-12-26 20:56:36 +00:00
"""The original build trigger will the generic builder name `nix-build` in this case, which is not helpful"""
2023-09-10 08:11:56 +00:00
if not self.triggeredNames:
return {"step": "running"}
summary = []
if self._result_list:
for status in ALL_RESULTS:
count = self._result_list.count(status)
if count:
summary.append(
2023-12-26 20:56:36 +00:00
f"{self._result_list.count(status)} {statusToString(status, count)}",
2023-09-10 08:11:56 +00:00
)
return {"step": f"({', '.join(summary)})"}
class NixEvalCommand(buildstep.ShellMixin, steps.BuildStep):
2023-12-26 20:56:36 +00:00
"""Parses the output of `nix-eval-jobs` and triggers a `nix-build` build for
2023-09-10 08:11:56 +00:00
every attribute.
"""
def __init__(self, supported_systems: list[str], **kwargs: Any) -> None:
kwargs = self.setupShellMixin(kwargs)
super().__init__(**kwargs)
self.observer = logobserver.BufferLogObserver()
self.addLogObserver("stdio", self.observer)
self.supported_systems = supported_systems
@defer.inlineCallbacks
def run(self) -> Generator[Any, object, Any]:
# run nix-eval-jobs --flake .#checks to generate the dict of stages
2023-09-10 08:11:56 +00:00
cmd: remotecommand.RemoteCommand = yield self.makeRemoteShellCommand()
yield self.runCommand(cmd)
# if the command passes extract the list of stages
result = cmd.results()
if result == util.SUCCESS:
# create a ShellCommand for each stage and add them to the build
jobs = []
for line in self.observer.getStdout().split("\n"):
if line != "":
try:
job = json.loads(line)
except json.JSONDecodeError as e:
2023-12-26 20:56:36 +00:00
msg = f"Failed to parse line: {line}"
raise BuildbotNixError(msg) from e
2023-09-10 08:11:56 +00:00
jobs.append(job)
build_props = self.build.getProperties()
repo_name = build_props.getProperty(
"github.base.repo.full_name",
build_props.getProperty("github.repository.full_name"),
)
project_id = slugify_project_name(repo_name)
2023-09-10 08:11:56 +00:00
filtered_jobs = []
for job in jobs:
system = job.get("system")
2023-12-26 20:56:36 +00:00
if not system or system in self.supported_systems: # report eval errors
2023-09-10 08:11:56 +00:00
filtered_jobs.append(job)
self.build.addStepsAfterCurrentStep(
2023-10-27 09:39:11 +00:00
[
BuildTrigger(
2023-11-18 07:18:46 +00:00
builds_scheduler=f"{project_id}-nix-build",
skipped_builds_scheduler=f"{project_id}-nix-skipped-build",
name="build flake",
jobs=filtered_jobs,
2023-12-26 20:56:36 +00:00
),
],
2023-09-10 08:11:56 +00:00
)
return result
# FIXME this leaks memory... but probably not enough that we care
class RetryCounter:
def __init__(self, retries: int) -> None:
self.builds: dict[uuid.UUID, int] = defaultdict(lambda: retries)
2023-12-26 20:56:36 +00:00
def retry_build(self, build_id: uuid.UUID) -> int:
retries = self.builds[build_id]
2023-09-10 08:11:56 +00:00
if retries > 1:
2023-12-26 20:56:36 +00:00
self.builds[build_id] = retries - 1
2023-09-10 08:11:56 +00:00
return retries
2023-12-26 20:56:36 +00:00
return 0
2023-09-10 08:11:56 +00:00
# For now we limit this to two. Often this allows us to make the error log
# shorter because we won't see the logs for all previous succeeded builds
RETRY_COUNTER = RetryCounter(retries=2)
2023-11-18 07:18:46 +00:00
class EvalErrorStep(steps.BuildStep):
2023-12-26 20:56:36 +00:00
"""Shows the error message of a failed evaluation."""
2023-11-18 07:18:46 +00:00
@defer.inlineCallbacks
def run(self) -> Generator[Any, object, Any]:
error = self.getProperty("error")
attr = self.getProperty("attr")
# show eval error
error_log: Log = yield self.addLog("nix_error")
error_log.addStderr(f"{attr} failed to evaluate:\n{error}")
return util.FAILURE
2023-09-10 08:11:56 +00:00
class NixBuildCommand(buildstep.ShellMixin, steps.BuildStep):
2023-12-26 20:56:36 +00:00
"""Builds a nix derivation."""
2023-09-10 08:11:56 +00:00
def __init__(self, **kwargs: Any) -> None:
kwargs = self.setupShellMixin(kwargs)
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self) -> Generator[Any, object, Any]:
# run `nix build`
cmd: remotecommand.RemoteCommand = yield self.makeRemoteShellCommand()
yield self.runCommand(cmd)
res = cmd.results()
if res == util.FAILURE:
retries = RETRY_COUNTER.retry_build(self.getProperty("build_uuid"))
if retries > 0:
return util.RETRY
return res
class UpdateBuildOutput(steps.BuildStep):
2023-12-26 20:56:36 +00:00
"""Updates store paths in a public www directory.
2023-09-10 08:11:56 +00:00
This is useful to prefetch updates without having to evaluate
on the target machine.
"""
2023-11-04 08:50:23 +00:00
def __init__(self, path: Path, **kwargs: Any) -> None:
2023-09-10 08:11:56 +00:00
super().__init__(**kwargs)
2023-11-04 08:50:23 +00:00
self.path = path
2023-09-10 08:11:56 +00:00
def run(self) -> Generator[Any, object, Any]:
props = self.build.getProperties()
if props.getProperty("branch") != props.getProperty(
2023-12-26 20:56:36 +00:00
"github.repository.default_branch",
2023-09-10 08:11:56 +00:00
):
return util.SKIPPED
2023-11-17 15:27:55 +00:00
2023-12-26 20:56:36 +00:00
attr = Path(props.getProperty("attr")).name
2023-09-10 08:11:56 +00:00
out_path = props.getProperty("out_path")
# XXX don't hardcode this
2023-11-04 08:50:23 +00:00
self.path.mkdir(parents=True, exist_ok=True)
(self.path / attr).write_text(out_path)
2023-09-10 08:11:56 +00:00
return util.SUCCESS
2023-12-03 10:48:01 +00:00
# The builtin retry mechanism doesn't seem to work for github,
# since github is sometimes not delivering the pull request ref fast enough.
class GitWithRetry(steps.Git):
@defer.inlineCallbacks
def run_vc(
2023-12-26 20:56:36 +00:00
self,
branch: str,
revision: str,
patch: str,
2023-12-03 10:48:01 +00:00
) -> Generator[Any, object, Any]:
retry_counter = 0
while True:
try:
res = yield super().run_vc(branch, revision, patch)
2023-12-26 20:56:36 +00:00
except Exception as e: # noqa: BLE001
2023-12-03 10:48:01 +00:00
retry_counter += 1
if retry_counter == 3:
2023-12-26 20:56:36 +00:00
msg = "Failed to clone"
raise BuildbotNixError(msg) from e
2023-12-04 07:12:03 +00:00
log: Log = yield self.addLog("log")
yield log.addStderr(f"Retrying git clone (error: {e})\n")
2023-12-03 10:48:01 +00:00
yield asyncSleep(2 << retry_counter) # 2, 4, 8
2023-12-26 20:56:36 +00:00
else:
return res
2023-12-03 10:48:01 +00:00
2023-09-10 08:11:56 +00:00
def nix_eval_config(
project: GerritProject,
gerrit_private_key: str,
2023-09-10 08:11:56 +00:00
worker_names: list[str],
supported_systems: list[str],
eval_lock: util.MasterLock,
2023-11-12 06:07:30 +00:00
worker_count: int,
max_memory_size: int,
2023-09-10 08:11:56 +00:00
) -> util.BuilderConfig:
2023-12-26 20:56:36 +00:00
"""Uses nix-eval-jobs to evaluate hydraJobs from flake.nix in parallel.
2023-09-10 08:11:56 +00:00
For each evaluated attribute a new build pipeline is started.
"""
factory = util.BuildFactory()
# check out the source
factory.addStep(
steps.Gerrit(
repourl="ssh://buildbot@gerrit.lix.systems:2022/lix",
mode="full",
retry=[60, 60],
timeout=3600,
sshPrivateKey=gerrit_private_key
2023-12-26 20:56:36 +00:00
),
2023-09-10 08:11:56 +00:00
)
2024-01-15 12:41:48 +00:00
drv_gcroots_dir = util.Interpolate(
"/nix/var/nix/gcroots/per-user/buildbot-worker/%(prop:project)s/drvs/",
)
2023-09-10 08:11:56 +00:00
factory.addStep(
NixEvalCommand(
env={},
name="evaluate flake",
supported_systems=supported_systems,
command=[
2023-10-15 09:26:09 +00:00
"nix-eval-jobs",
2023-09-10 08:11:56 +00:00
"--workers",
2023-11-12 06:07:30 +00:00
str(worker_count),
2023-09-10 08:11:56 +00:00
"--max-memory-size",
str(max_memory_size),
"--option",
"accept-flake-config",
"true",
"--gc-roots-dir",
2024-01-15 12:41:48 +00:00
drv_gcroots_dir,
2023-09-10 08:11:56 +00:00
"--force-recurse",
2023-11-17 15:27:55 +00:00
"--check-cache-status",
2023-09-10 08:11:56 +00:00
"--flake",
".#checks",
],
haltOnFailure=True,
locks=[eval_lock.access("exclusive")],
2023-12-26 20:56:36 +00:00
),
2023-09-10 08:11:56 +00:00
)
2024-01-15 12:41:48 +00:00
factory.addStep(
steps.ShellCommand(
name="Cleanup drv paths",
command=[
"rm",
"-rf",
drv_gcroots_dir,
],
),
)
2023-09-10 08:11:56 +00:00
return util.BuilderConfig(
name=f"{project.name}/nix-eval",
workernames=worker_names,
project=project.name,
factory=factory,
properties=dict(status_name="nix-eval"),
)
2023-12-23 18:54:42 +00:00
@dataclass
class CachixConfig:
name: str
signing_key_secret_name: str | None = None
auth_token_secret_name: str | None = None
def cachix_env(self) -> dict[str, str]:
env = {}
if self.signing_key_secret_name is not None:
env["CACHIX_SIGNING_KEY"] = util.Secret(self.signing_key_secret_name)
if self.auth_token_secret_name is not None:
env["CACHIX_AUTH_TOKEN"] = util.Secret(self.auth_token_secret_name)
return env
2023-09-10 08:11:56 +00:00
def nix_build_config(
project: GerritProject,
2023-09-10 08:11:56 +00:00
worker_names: list[str],
2023-12-23 18:54:42 +00:00
cachix: CachixConfig | None = None,
2023-11-04 08:50:23 +00:00
outputs_path: Path | None = None,
2023-09-10 08:11:56 +00:00
) -> util.BuilderConfig:
2023-12-26 20:56:36 +00:00
"""Builds one nix flake attribute."""
2023-09-10 08:11:56 +00:00
factory = util.BuildFactory()
factory.addStep(
NixBuildCommand(
env={},
name="Build flake attr",
command=[
"nix",
"build",
"-L",
"--option",
"keep-going",
"true",
"--option",
# stop stuck builds after 20 minutes
"--max-silent-time",
str(60 * 20),
2023-09-10 08:11:56 +00:00
"--accept-flake-config",
"--out-link",
util.Interpolate("result-%(prop:attr)s"),
util.Interpolate("%(prop:drv_path)s^*"),
],
# 3 hours, defaults to 20 minutes
# We increase this over the default since the build output might end up in a different `nix build`.
timeout=60 * 60 * 3,
2023-09-10 08:11:56 +00:00
haltOnFailure=True,
2023-12-26 20:56:36 +00:00
),
2023-09-10 08:11:56 +00:00
)
2023-12-23 18:54:42 +00:00
if cachix:
2023-09-10 08:11:56 +00:00
factory.addStep(
steps.ShellCommand(
name="Upload cachix",
2023-12-23 18:54:42 +00:00
env=cachix.cachix_env(),
2023-09-10 08:11:56 +00:00
command=[
"cachix",
"push",
2023-12-23 18:54:42 +00:00
cachix.name,
2023-09-10 08:11:56 +00:00
util.Interpolate("result-%(prop:attr)s"),
],
2023-12-26 20:56:36 +00:00
),
2023-09-10 08:11:56 +00:00
)
2023-10-09 15:13:46 +00:00
2023-09-10 08:11:56 +00:00
factory.addStep(
steps.ShellCommand(
name="Register gcroot",
command=[
"nix-store",
"--add-root",
# FIXME: cleanup old build attributes
util.Interpolate(
2023-12-26 20:56:36 +00:00
"/nix/var/nix/gcroots/per-user/buildbot-worker/%(prop:project)s/%(prop:attr)s",
2023-09-10 08:11:56 +00:00
),
"-r",
util.Property("out_path"),
],
2023-11-18 07:18:46 +00:00
doStepIf=lambda s: s.getProperty("branch")
2023-10-12 10:43:57 +00:00
== s.getProperty("github.repository.default_branch"),
2023-12-26 20:56:36 +00:00
),
2023-09-10 08:11:56 +00:00
)
factory.addStep(
steps.ShellCommand(
name="Delete temporary gcroots",
command=["rm", "-f", util.Interpolate("result-%(prop:attr)s")],
2023-12-26 20:56:36 +00:00
),
2023-09-10 08:11:56 +00:00
)
2023-11-04 08:50:23 +00:00
if outputs_path is not None:
factory.addStep(
UpdateBuildOutput(
name="Update build output",
path=outputs_path,
2023-12-26 20:56:36 +00:00
),
2023-11-04 08:50:23 +00:00
)
2023-09-10 08:11:56 +00:00
return util.BuilderConfig(
name=f"{project.name}/nix-build",
project=project.name,
workernames=worker_names,
collapseRequests=False,
env={},
factory=factory,
)
2023-09-17 20:14:56 +00:00
2023-11-18 07:18:46 +00:00
def nix_skipped_build_config(
project: GerritProject,
2023-12-26 20:56:36 +00:00
worker_names: list[str],
2023-11-18 07:18:46 +00:00
) -> util.BuilderConfig:
2023-12-26 20:56:36 +00:00
"""Dummy builder that is triggered when a build is skipped."""
2023-11-18 07:18:46 +00:00
factory = util.BuildFactory()
factory.addStep(
EvalErrorStep(
name="Nix evaluation",
doStepIf=lambda s: s.getProperty("error"),
hideStepIf=lambda _, s: not s.getProperty("error"),
2023-12-26 20:56:36 +00:00
),
2023-11-18 07:18:46 +00:00
)
# This is just a dummy step showing the cached build
factory.addStep(
steps.BuildStep(
name="Nix build (cached)",
doStepIf=lambda _: False,
hideStepIf=lambda _, s: s.getProperty("error"),
2023-12-26 20:56:36 +00:00
),
2023-11-18 07:18:46 +00:00
)
return util.BuilderConfig(
name=f"{project.name}/nix-skipped-build",
project=project.name,
workernames=worker_names,
collapseRequests=False,
env={},
factory=factory,
)
2023-09-17 20:14:56 +00:00
def read_secret_file(secret_name: str) -> str:
directory = os.environ.get("CREDENTIALS_DIRECTORY")
if directory is None:
print("directory not set", file=sys.stderr)
sys.exit(1)
2023-10-27 09:09:20 +00:00
return Path(directory).joinpath(secret_name).read_text().rstrip()
2023-09-17 20:14:56 +00:00
def config_for_project(
config: dict[str, Any],
project: GerritProject,
2023-09-17 20:14:56 +00:00
worker_names: list[str],
nix_supported_systems: list[str],
2023-11-12 06:07:30 +00:00
nix_eval_worker_count: int,
2023-09-17 20:14:56 +00:00
nix_eval_max_memory_size: int,
eval_lock: util.MasterLock,
2023-12-23 18:54:42 +00:00
cachix: CachixConfig | None = None,
2023-11-04 08:50:23 +00:00
outputs_path: Path | None = None,
2023-09-17 20:14:56 +00:00
) -> Project:
config["projects"].append(Project(project.name))
config["schedulers"].extend(
[
# build everything pertaining to a project
# TODO(raito): will this catch also post-merge? we don't really care about that… do we?
2023-09-17 20:14:56 +00:00
schedulers.SingleBranchScheduler(
name=f"{project.name}-changes",
2023-09-17 20:14:56 +00:00
change_filter=util.ChangeFilter(
project=project.name,
2023-09-17 20:14:56 +00:00
),
builderNames=[f"{project.name}/nix-eval"],
),
# this is triggered from `nix-eval`
schedulers.Triggerable(
name=f"{project.name}-nix-build",
2023-09-17 20:14:56 +00:00
builderNames=[f"{project.name}/nix-build"],
),
2023-11-18 07:18:46 +00:00
# this is triggered from `nix-eval` when the build is skipped
schedulers.Triggerable(
name=f"{project.name}-nix-skipped-build",
2023-11-18 07:18:46 +00:00
builderNames=[f"{project.name}/nix-skipped-build"],
),
2023-09-17 20:14:56 +00:00
# allow to manually trigger a nix-build
schedulers.ForceScheduler(
name=f"{project.name}-force",
2023-10-27 08:49:40 +00:00
builderNames=[f"{project.name}/nix-eval"],
2023-10-27 08:35:26 +00:00
properties=[
util.StringParameter(
name="project",
label="Name of the Gerrit repository.",
2023-10-27 08:49:40 +00:00
default=project.name,
2023-12-26 20:56:36 +00:00
),
2023-10-27 08:49:40 +00:00
],
2023-09-17 20:14:56 +00:00
),
2023-12-26 20:56:36 +00:00
],
2023-09-17 20:14:56 +00:00
)
gerrit_private_key = None
with open('/var/lib/buildbot/master/id_gerrit', 'r') as f:
gerrit_private_key = f.read()
if gerrit_private_key is None:
raise RuntimeError('No gerrit private key to fetch the repositories')
2023-09-17 20:14:56 +00:00
config["builders"].extend(
[
# Since all workers run on the same machine, we only assign one of them to do the evaluation.
# This should prevent exessive memory usage.
nix_eval_config(
project,
gerrit_private_key,
worker_names,
2023-09-17 20:14:56 +00:00
supported_systems=nix_supported_systems,
2023-11-12 06:07:30 +00:00
worker_count=nix_eval_worker_count,
2023-09-17 20:14:56 +00:00
max_memory_size=nix_eval_max_memory_size,
eval_lock=eval_lock,
2023-09-17 20:14:56 +00:00
),
nix_build_config(
project,
worker_names,
2023-12-23 18:54:42 +00:00
cachix=cachix,
2023-11-04 08:50:23 +00:00
outputs_path=outputs_path,
2023-09-17 20:14:56 +00:00
),
2023-11-18 07:18:46 +00:00
nix_skipped_build_config(project, [SKIPPED_BUILDER_NAME]),
2023-12-26 20:56:36 +00:00
],
2023-09-17 20:14:56 +00:00
)
class PeriodicWithStartup(schedulers.Periodic):
def __init__(self, *args: Any, run_on_startup: bool = False, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.run_on_startup = run_on_startup
@defer.inlineCallbacks
def activate(self) -> Generator[Any, object, Any]:
if self.run_on_startup:
yield self.setState("last_build", None)
yield super().activate()
def gerritReviewCB(builderName, build, result, master, arg):
if result == util.RETRY:
return dict()
message = "Buildbot finished compiling your patchset\n"
message += "on configuration: %s\n" % builderName
message += "The result is: %s\n" % util.Results[result].upper()
if arg:
message += "\nFor more details visit:\n"
message += build['url'] + "\n"
if result == util.SUCCESS:
verified = 1
else:
verified = -1
return dict(message=message, labels={'Verified': verified})
def gerritStartCB(builderName, build, arg):
message = "Buildbot started compiling your patchset\n"
message += "on configuration: %s\n" % builderName
message += "See your build here: %s" % build['url']
return dict(message=message)
def gerritSummaryCB(buildInfoList, results, status, arg):
success = False
failure = False
msgs = []
for buildInfo in buildInfoList:
msg = "Builder %(name)s %(resultText)s (%(text)s)" % buildInfo
link = buildInfo.get('url', None)
if link:
msg += " - " + link
else:
msg += "."
msgs.append(msg)
if buildInfo['result'] == util.SUCCESS:
success = True
else:
failure = True
if success and not failure:
verified = 1
else:
verified = -1
return dict(message='\n\n'.join(msgs),
labels={
'Verified': verified
})
class GerritNixConfigurator(ConfiguratorBase):
2023-09-17 20:14:56 +00:00
"""Janitor is a configurator which create a Janitor Builder with all needed Janitor steps"""
def __init__(
self,
2023-12-26 20:56:36 +00:00
# Shape of this file: [ { "name": "<worker-name>", "pass": "<worker-password>", "cores": "<cpu-cores>" } ]
gerrit_server: str,
gerrit_user: str,
gerrit_port: int,
gerrit_sshkey_path: str,
2023-10-12 13:59:26 +00:00
url: str,
2023-09-17 20:14:56 +00:00
nix_supported_systems: list[str],
2023-11-12 06:07:30 +00:00
nix_eval_worker_count: int | None,
nix_eval_max_memory_size: int,
2023-12-26 20:56:36 +00:00
nix_workers_secret_name: str = "buildbot-nix-workers", # noqa: S107
2023-12-23 18:54:42 +00:00
cachix: CachixConfig | None = None,
2023-11-04 08:50:23 +00:00
outputs_path: str | None = None,
2023-09-17 20:14:56 +00:00
) -> None:
super().__init__()
self.gerrit_server = gerrit_server
self.gerrit_user = gerrit_user
self.gerrit_port = gerrit_port
2023-09-17 20:14:56 +00:00
self.nix_workers_secret_name = nix_workers_secret_name
self.nix_eval_max_memory_size = nix_eval_max_memory_size
2023-11-12 06:07:30 +00:00
self.nix_eval_worker_count = nix_eval_worker_count
2023-09-17 20:14:56 +00:00
self.nix_supported_systems = nix_supported_systems
self.gerrit_change_source = GerritChangeSource(gerrit_server, gerrit_user, gerritport=gerrit_port, identity_file=gerrit_sshkey_path)
2023-10-12 13:59:26 +00:00
self.url = url
2023-12-23 18:54:42 +00:00
self.cachix = cachix
2023-11-04 08:50:23 +00:00
if outputs_path is None:
self.outputs_path = None
else:
self.outputs_path = Path(outputs_path)
2023-09-17 20:14:56 +00:00
def configure(self, config: dict[str, Any]) -> None:
worker_config = json.loads(read_secret_file(self.nix_workers_secret_name))
worker_names = []
config.setdefault("projects", [])
config.setdefault("secretsProviders", [])
config.setdefault("www", {})
2023-09-17 20:14:56 +00:00
for item in worker_config:
cores = item.get("cores", 0)
for i in range(cores):
2023-11-09 07:18:03 +00:00
worker_name = f"{item['name']}-{i:03}"
2023-09-17 20:14:56 +00:00
config["workers"].append(worker.Worker(worker_name, item["pass"]))
worker_names.append(worker_name)
eval_lock = util.MasterLock("nix-eval")
2023-10-12 13:59:26 +00:00
# Configure the Lix project.
config_for_project(
config,
GerritProject(name="lix"),
worker_names,
self.nix_supported_systems,
self.nix_eval_worker_count or multiprocessing.cpu_count(),
self.nix_eval_max_memory_size,
eval_lock,
self.cachix,
self.outputs_path,
)
2023-10-12 13:59:26 +00:00
config["change_source"] = self.gerrit_change_source
2023-11-18 07:18:46 +00:00
config["workers"].append(worker.LocalWorker(SKIPPED_BUILDER_NAME))
2023-09-17 20:14:56 +00:00
config["services"].append(
reporters.GerritStatusPush(self.gerrit_server, self.gerrit_user,
reviewCB=gerritReviewCB,
reviewArg=self.url,
startCB=gerritStartCB,
startArg=self.url,
summaryCB=gerritSummaryCB,
summaryArg=self.url)
2023-09-17 20:14:56 +00:00
)
2023-09-17 20:14:56 +00:00
systemd_secrets = secrets.SecretInAFile(
2023-12-26 20:56:36 +00:00
dirname=os.environ["CREDENTIALS_DIRECTORY"],
2023-09-17 20:14:56 +00:00
)
config["secretsProviders"].append(systemd_secrets)
config["www"].setdefault("plugins", {})
config["www"]["plugins"].update(dict(base_react={}))
if "auth" not in config["www"]:
config["www"]["auth"] = LixSystemsOAuth2('buildbot', read_secret_file('buildbot-oauth2-secret'), autologin=True)