Merge pull request #9 from Mic92/fixes

make per-project gcroots
This commit is contained in:
Jörg Thalheim 2023-10-12 17:54:14 +02:00 committed by GitHub
commit 508714f7bf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 266 additions and 33 deletions

161
.gitignore vendored
View file

@ -1 +1,162 @@
result
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

View file

@ -19,7 +19,11 @@ from buildbot.process.project import Project
from buildbot.process.properties import Interpolate, Properties
from buildbot.process.results import ALL_RESULTS, statusToString
from buildbot.steps.trigger import Trigger
from github_projects import GithubProject, load_projects # noqa: E402
from github_projects import ( # noqa: E402
GithubProject,
create_project_hook,
load_projects,
)
from twisted.internet import defer
@ -337,7 +341,7 @@ def nix_update_flake_config(
"--base",
project.default_branch,
],
doStepIf=util.Interpolate("has_pr") != "OPEN",
doStepIf=lambda s: s.getProperty("has_pr") != "OPEN",
)
)
return util.BuilderConfig(
@ -468,12 +472,13 @@ def nix_build_config(
"--add-root",
# FIXME: cleanup old build attributes
util.Interpolate(
"/nix/var/nix/profiles/per-user/buildbot-worker/result-%(prop:attr)s"
"/nix/var/nix/gcroots/per-user/buildbot-worker/%(prop:project)s/%(prop:attr)s"
),
"-r",
util.Property("out_path"),
],
doStepIf=lambda s: s.getProperty("branch") == s.getProperty("github.repository.default_branch"),
doStepIf=lambda s: s.getProperty("branch")
== s.getProperty("github.repository.default_branch"),
)
)
factory.addStep(
@ -510,6 +515,7 @@ class GithubConfig:
webhook_secret_name: str = "github-webhook-secret"
token_secret_name: str = "github-token"
project_cache_file: Path = Path("github-project-cache.json")
topic: str | None = "build-with-buildbot"
def token(self) -> str:
return read_secret_file(self.token_secret_name)
@ -619,6 +625,7 @@ class NixConfigurator(ConfiguratorBase):
# Shape of this file:
# [ { "name": "<worker-name>", "pass": "<worker-password>", "cores": "<cpu-cores>" } ]
github: GithubConfig,
url: str,
nix_supported_systems: list[str],
nix_eval_max_memory_size: int = 4096,
nix_workers_secret_name: str = "buildbot-nix-workers",
@ -628,11 +635,13 @@ class NixConfigurator(ConfiguratorBase):
self.nix_eval_max_memory_size = nix_eval_max_memory_size
self.nix_supported_systems = nix_supported_systems
self.github = github
self.url = url
self.systemd_credentials_dir = os.environ["CREDENTIALS_DIRECTORY"]
def configure(self, config: dict[str, Any]) -> None:
projects = load_projects(self.github.token(), self.github.project_cache_file)
projects = [p for p in projects if "build-with-buildbot" in p.topics]
if self.github.topic is not None:
projects = [p for p in projects if self.github.topic in p.topics]
worker_config = json.loads(read_secret_file(self.nix_workers_secret_name))
worker_names = []
config["workers"] = config.get("workers", [])
@ -644,6 +653,15 @@ class NixConfigurator(ConfiguratorBase):
worker_names.append(worker_name)
config["projects"] = config.get("projects", [])
for project in projects:
create_project_hook(
project.owner,
project.repo,
self.github.token(),
f"{self.url}/change_hook/github",
)
for project in projects:
config_for_project(
config,
@ -654,6 +672,7 @@ class NixConfigurator(ConfiguratorBase):
self.nix_supported_systems,
self.nix_eval_max_memory_size,
)
config["services"] = config.get("services", [])
config["services"].append(
reporters.GitHubStatusPush(

View file

@ -30,18 +30,28 @@ def http_request(
headers = headers.copy()
headers["User-Agent"] = "buildbot-nix"
req = urllib.request.Request(url, headers=headers, method=method, data=body)
try:
resp = urllib.request.urlopen(req)
except urllib.request.HTTPError as e:
body = ""
try:
body = e.fp.read()
except Exception:
pass
raise Exception(
f"Request for {method} {url} failed with {e.code} {e.reason}: {body}"
) from e
return HttpResponse(resp)
def paginated_github_request(url: str, token: str) -> list[dict[str, Any]]:
next_url: str | None = url
repos = []
items = []
while next_url:
try:
res = http_request(
next_url,
headers={"Authorization": f"token {token}"},
headers={"Authorization": f"Bearer {token}"},
)
except OSError as e:
raise Exception(f"failed to fetch {next_url}: {e}") from e
@ -53,34 +63,67 @@ def paginated_github_request(url: str, token: str) -> list[dict[str, Any]]:
link_parts = link.split(";")
if link_parts[1].strip() == 'rel="next"':
next_url = link_parts[0][1:-1]
repos += res.json()
return repos
items += res.json()
return items
class GithubProject:
def __init__(self, repo: dict[str, Any]) -> None:
self.repo = repo
def __init__(self, data: dict[str, Any]) -> None:
self.data = data
@property
def repo(self) -> str:
return self.data["name"]
@property
def owner(self) -> str:
return self.data["owner"]["login"]
@property
def name(self) -> str:
return self.repo["full_name"]
return self.data["full_name"]
@property
def url(self) -> str:
return self.repo["html_url"]
return self.data["html_url"]
@property
def id(self) -> str:
n = self.repo["full_name"]
n = self.data["full_name"]
return n.replace("/", "-")
@property
def default_branch(self) -> str:
return self.repo["default_branch"]
return self.data["default_branch"]
@property
def topics(self) -> list[str]:
return self.repo["topics"]
return self.data["topics"]
def create_project_hook(owner: str, repo: str, token: str, webhook_url: str) -> None:
hooks = paginated_github_request(
f"https://api.github.com/repos/{owner}/{repo}/hooks?per_page=100", token
)
config = dict(url=webhook_url, content_type="json", insecure_ssl="0")
data = dict(name="web", active=True, events=["push", "pull_request"], config=config)
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"Content-Type": "application/json",
"X-GitHub-Api-Version": "2022-11-28",
}
for hook in hooks:
if hook["config"]["url"] == webhook_url:
log.msg(f"hook for {owner}/{repo} already exists")
return
http_request(
f"https://api.github.com/repos/{owner}/{repo}/hooks",
method="POST",
headers=headers,
data=data,
)
def load_projects(github_token: str, repo_cache_file: Path) -> list[GithubProject]:

View file

@ -29,8 +29,8 @@ in
webhookSecretFile = "/var/lib/secrets/buildbot-nix/github-webhook-secret";
oauthSecretFile = "/var/lib/secrets/buildbot-nix/github-oauth-secret";
oauthId = "aaaaaaaaaaaaaaaaaaaa";
githubUser = "mic92-buildbot";
githubAdmins = [ "Mic92" ];
user = "mic92-buildbot";
admins = [ "Mic92" ];
};
};
services.nginx.virtualHosts."buildbot2.thalheim.io" = {

View file

@ -22,16 +22,16 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1695522116,
"narHash": "sha256-hISZSYVmlpJYKNR+kRWk5JBTQUX9lOJYSFPfObwOkDk=",
"owner": "Mic92",
"lastModified": 1697009197,
"narHash": "sha256-viVRhBTFT8fPJTb1N3brQIpFZnttmwo3JVKNuWRVc3s=",
"owner": "Nixos",
"repo": "nixpkgs",
"rev": "7031d27d0086c378212c138e15bda5d70037bd0f",
"rev": "01441e14af5e29c9d27ace398e6dd0b293e25a54",
"type": "github"
},
"original": {
"owner": "Mic92",
"ref": "buildbot",
"owner": "Nixos",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}

View file

@ -15,8 +15,8 @@
webhookSecretFile = "/var/lib/secrets/buildbot-nix/github-webhook-secret";
oauthSecretFile = "/var/lib/secrets/buildbot-nix/github-oauth-secret";
oauthId = "aaaaaaaaaaaaaaaaaaaa";
githubUser = "mic92-buildbot";
githubAdmins = [ "Mic92" ];
user = "mic92-buildbot";
admins = [ "Mic92" ];
};
};
};

View file

@ -39,15 +39,23 @@ in
description = "Github oauth id. Used for the login button";
};
# Most likely you want to use the same user as for the buildbot
githubUser = lib.mkOption {
user = lib.mkOption {
type = lib.types.str;
description = "Github user that is used for the buildbot";
};
githubAdmins = lib.mkOption {
admins = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Users that are allowed to login to buildbot, trigger builds and change settings";
};
topic = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = "build-with-buildbot";
description = ''
Projects that have this topic will be built by buildbot.
If null, all projects that the buildbot github user has access to, are built.
'';
};
};
workersFile = lib.mkOption {
type = lib.types.path;
@ -97,9 +105,11 @@ in
NixConfigurator(
github=GithubConfig(
oauth_id=${builtins.toJSON cfg.github.oauthId},
admins=${builtins.toJSON cfg.github.githubAdmins},
buildbot_user=${builtins.toJSON cfg.github.githubUser},
admins=${builtins.toJSON cfg.github.admins},
buildbot_user=${builtins.toJSON cfg.github.user},
topic=${builtins.toJSON cfg.github.topic},
),
url=${builtins.toJSON config.services.buildbot-master.buildbotUrl},
nix_eval_max_memory_size=${builtins.toJSON cfg.evalMaxMemorySize},
nix_supported_systems=${builtins.toJSON cfg.buildSystems},
)

View file

@ -1,12 +1,12 @@
[tool.ruff]
target-version = "py311"
line-length = 88
select = ["E", "F", "I", "U"]
select = ["E", "F", "I", "U", "N"]
ignore = [ "E501" ]
[tool.mypy]
python_version = "3.10"
pretty = true
warn_redundant_casts = true
disallow_untyped_calls = true
disallow_untyped_defs = true