Compare commits

...
8 Commits
Author SHA1 Message Date
claude 7ab973ff67 Merge pull request 'Gitea sources without a token: direct archive links' (#17) from gitea-anonymous into master 2026-11-15 01:30:35 +01:00
rektdieandclaude 4bd7a68864 Gitea sources without a token: direct archive links
With REQUIRE_SIGNIN_VIEW off, public Gitea repositories can be read
anonymously, so the token is no longer required. Without one, the server
calls the Gitea API without credentials and hands workers the plain
<repo>/archive/<commit>.zip link, like Github. With a token, private
repositories still go through the signed /giteaSource/ proxy.

When a lookup fails without a token, the error says the repository must
be public.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:30:15 +01:00
claude 30032fd42d Merge pull request 'Add Rigby (MCTS engine) to the engine list' (#15) from add-rigby into master 2026-11-15 00:46:10 +01:00
claude f915c30f02 Merge pull request 'Accept engine sources from Gitea servers' (#16) from gitea-sources into master 2026-11-15 00:45:59 +01:00
rektdieandclaude 754283d95e Sign Gitea source links with the Gitea token
settings.py, SECRET_KEY included, is part of the public repository, so
links signed with it could be forged to read any repository the token can
see. The token in Config/credentials.gitea is gitignored and is now the
signing key. Without a token, Gitea tests are refused at creation and no
link validates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:45:17 +01:00
rektdieandclaude e8cd615d83 Rigby: take sources from Gitea
Needs the Gitea source support from the gitea-sources branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:43:28 +01:00
rektdieandclaude c721cc6b5b Accept engine sources from Gitea servers
Tests, tunes and datagen could only use https://github.com/<user>/<repo>.
Gitea servers listed under "gitea_hosts" in Config/config.json are now
accepted too, starting with https://gitea.rektdie.com.

- OpenBench/git_hosts.py holds all host logic: repo validation, API base,
  resolving a branch/tag/sha, compare counts, diff links and source URLs.
- The server talks to Gitea with the token in Config/credentials.gitea and
  sends it nowhere else; Github requests stay unchanged.
- Gitea may require a login even to read, so workers cannot download the
  archive themselves. The server gives them a /giteaSource/ link signed with
  an HMAC of repo and commit (SECRET_KEY), and streams the archive from the
  Gitea API. No client change, no client version bump.
- Diff links, the out-of-date check and the profile page handle Gitea repos;
  the repo fields of the forms accept every configured prefix.
- Private engines stay Github-only, they depend on Github Actions artifacts.
- Static version bumped to v5 for the changed default_text.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:42:43 +01:00
rektdieandclaude 619d29b12e Add Rigby (MCTS engine) to the engine list
Rigby is a PUCT search engine, so its tree needs far more memory than an
alpha-beta hash: STC and LTC run with Hash=64 and Hash=256. Non-regression
presets are included for simplifications. Reference nps is calibrated
against Eleanor on the same machine (1.10M measured for 800k reference,
Rigby measures 1.08M).

The source points at a GitHub mirror, because test creation only accepts
github.com repositories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:36:42 +01:00
12 changed files with 387 additions and 52 deletions

No files matched your search

+6 -1
View File
@@ -8,6 +8,10 @@
"require_manual_registration" : false, "require_manual_registration" : false,
"balance_engine_throughputs" : true, "balance_engine_throughputs" : true,
"gitea_hosts" : [
"https://gitea.rektdie.com"
],
"books" : [ "books" : [
"2moves_v1.epd", "2moves_v1.epd",
"3moves_FRC.epd", "3moves_FRC.epd",
@@ -33,6 +37,7 @@
"Prelude", "Prelude",
"Simpler", "Simpler",
"Stormphrax", "Stormphrax",
"Impact" "Impact",
"Rigby"
] ]
} }
+78
View File
@@ -0,0 +1,78 @@
{
"private" : false,
"nps" : 780000,
"source" : "https://gitea.rektdie.com/rektdie/Rigby",
"build" : {
"path" : "",
"compilers" : ["clang++"],
"cpuflags" : [],
"systems" : ["Linux", "Windows", "Darwin"]
},
"test_presets" : {
"default" : {
"base_branch" : "main",
"book_name" : "UHO_Lichess_4852_v1.epd",
"test_bounds" : "[0.00, 5.00]",
"test_confidence" : "[0.05, 0.05]",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10"
},
"STC" : {
"both_options" : "Threads=1 Hash=64",
"both_time_control" : "8.0+0.08",
"workload_size" : 32
},
"LTC" : {
"both_options" : "Threads=1 Hash=256",
"both_time_control" : "40.0+0.4",
"workload_size" : 8
},
"Non-Regression STC" : {
"test_bounds" : "[-5.00, 0.00]",
"both_options" : "Threads=1 Hash=64",
"both_time_control" : "8.0+0.08",
"workload_size" : 32
},
"Non-Regression LTC" : {
"test_bounds" : "[-5.00, 0.00]",
"both_options" : "Threads=1 Hash=256",
"both_time_control" : "40.0+0.4",
"workload_size" : 8
}
},
"tune_presets" : {
"default" : {
"book_name" : "UHO_Lichess_4852_v1.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10"
},
"STC" : {
"dev_options" : "Threads=1 Hash=64",
"dev_time_control" : "8.0+0.08"
},
"LTC" : {
"dev_options" : "Threads=1 Hash=256",
"dev_time_control" : "40.0+0.4"
}
},
"datagen_presets" : {
"default" : {
"win_adj" : "None",
"draw_adj" : "None",
"workload_size" : 128
}
}
}
+6 -1
View File
@@ -25,7 +25,7 @@ import traceback
from OpenSite.settings import PROJECT_PATH from OpenSite.settings import PROJECT_PATH
OPENBENCH_STATIC_VERSION = 'v4' OPENBENCH_STATIC_VERSION = 'v5'
OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py
@@ -101,6 +101,11 @@ def verify_general_config(conf):
assert type(conf.get("require_manual_registration") == bool) assert type(conf.get("require_manual_registration") == bool)
assert type(conf.get("balance_engine_throughputs" ) == bool) assert type(conf.get("balance_engine_throughputs" ) == bool)
# Optional: Gitea servers that may serve engine sources, e.g. "https://gitea.example.com"
hosts = conf.get("gitea_hosts", [])
assert type(hosts) == list
assert all(type(x) == str and x.startswith('https://') and x.count('/') == 2 for x in hosts)
def verify_engine_basics(conf): def verify_engine_basics(conf):
assert type(conf.get('private')) == bool assert type(conf.get('private')) == bool
+214
View File
@@ -0,0 +1,214 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench 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 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench 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, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Everything OpenBench needs to know about where engine sources live.
#
# Sources can be on Github, or on a Gitea server listed under "gitea_hosts" in
# Config/config.json.
#
# Workers download sources with a plain GET and no credentials. Github archives
# are public, so workers fetch them directly. For Gitea there are two modes:
#
# - Without a token, the repository must be readable anonymously (public, and
# REQUIRE_SIGNIN_VIEW off on the Gitea server). The API is called without
# credentials and workers get the plain archive link, exactly like Github.
#
# - With an API token in Config/credentials.gitea, private repositories and
# servers that require a login work too. The token is never sent to any other
# host. Workers cannot log in, so the server hands them a signed link to
# /giteaSource/, which fetches the archive with the token and passes it on.
#
# The links are signed with the Gitea token itself, not Django's SECRET_KEY:
# settings.py is part of the public repository, and a forged link would let
# anyone read every repository the token can see. Replacing the token
# invalidates the source links of tests created before.
import hashlib
import hmac
import os
import re
import urllib.parse
import requests
import OpenBench.config
from OpenSite.settings import PROJECT_PATH
GITHUB_PREFIX = 'https://github.com/'
GITHUB_PATTERN = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
REPO_TAIL = r'\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$'
REQUEST_TIMEOUT = 30
def gitea_hosts():
return [host.rstrip('/') for host in OpenBench.config.OPENBENCH_CONFIG.get('gitea_hosts', [])]
def repo_prefixes():
return [GITHUB_PREFIX] + ['%s/' % (host) for host in gitea_hosts()]
def gitea_host(repo):
for host in gitea_hosts():
if repo.startswith(host + '/'):
return host
return None
def is_gitea(repo):
return gitea_host(repo) is not None
def is_valid_repo(repo):
if re.match(GITHUB_PATTERN, repo):
return True
host = gitea_host(repo)
return bool(host and re.match(REPO_TAIL, repo[len(host):]))
def owner_and_name(repo):
host = gitea_host(repo) or GITHUB_PREFIX.rstrip('/')
owner, name = repo[len(host):].strip('/').split('/')[:2]
return owner, name
def api_base(repo):
if (host := gitea_host(repo)):
return '%s/api/v1/repos/%s/%s' % ((host,) + owner_and_name(repo))
return repo.rstrip('/').replace('github.com', 'api.github.com/repos')
def read_gitea_token():
path = os.path.join(PROJECT_PATH, 'Config', 'credentials.gitea')
if os.path.exists(path):
with open(path) as fin:
return fin.readline().strip() or None
def gitea_headers():
token = read_gitea_token()
return { 'Authorization' : 'token %s' % (token) } if token else {}
def api_headers(engine, repo):
if is_gitea(repo):
return gitea_headers()
import OpenBench.utils
return OpenBench.utils.read_git_credentials(engine) or {}
def fetch_commit(repo, ref, headers):
# Returns { 'sha', 'tree', 'message' } for a branch, tag, or commit sha.
# Raises when the reference cannot be resolved.
base = api_base(repo)
bysha = bool(re.search('^[0-9a-fA-F]{40}$', ref))
if is_gitea(repo):
# One endpoint resolves branches, tags and commit shas alike
params = { 'sha' : ref, 'limit' : 1, 'stat' : 'false', 'verification' : 'false', 'files' : 'false' }
data = requests.get(base + '/commits', params=params, headers=headers, timeout=REQUEST_TIMEOUT).json()
data = data[0]
else:
# Lookup branch or commit sha, but will fail for tags
url = '%s/%s/%s' % (base, 'commits' if bysha else 'branches', ref)
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = '%s/commits/%s' % (base, ref)
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# A lookup by sha must land on exactly that commit
if bysha and data['sha'].lower() != ref.lower():
raise ValueError('%s resolved to %s' % (ref, data['sha']))
return {
'sha' : data['sha'],
'tree' : (data['commit'].get('tree') or {}).get('sha'),
'message' : data['commit']['message'],
}
def commits_ahead(repo, dev_sha, base_sha, headers):
# Number of commits on base_sha that dev_sha does not have
base = api_base(repo)
if is_gitea(repo):
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
params = { 'verification' : 'false', 'files' : 'false' }
return int(requests.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT).json().get('total_commits', 0))
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
return int(requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json().get('ahead_by', 0))
def compare_url(repo, base_sha, dev_sha):
repo = repo.rstrip('/')
if is_gitea(repo):
return '%s/compare/%s...%s' % (repo, base_sha, dev_sha)
return '%s/compare/%s..%s' % (repo, base_sha, dev_sha)
def source_signature(repo, sha):
# Without a token there is nothing secret to sign with, and nothing to fetch with
if not (key := read_gitea_token()):
return None
message = ('openbench-gitea-source\n%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8')
return hmac.new(key.encode('utf-8'), message, hashlib.sha256).hexdigest()
def source_url(request, repo, commit):
# Github serves archives by tree sha, so identical trees share one download
if not is_gitea(repo):
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['tree'])
# Without a token the repository is public: workers download it directly.
# Gitea archives are addressed by commit, not by tree.
if not read_gitea_token():
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['sha'])
query = urllib.parse.urlencode({
'repo' : repo.rstrip('/'),
'sha' : commit['sha'],
'sig' : source_signature(repo, commit['sha']),
})
return request.build_absolute_uri('/giteaSource/?%s' % (query))
def verify_source_request(repo, sha, sig):
if not (is_valid_repo(repo) and is_gitea(repo) and re.match('^[0-9a-fA-F]{40}$', sha or '')):
return False
expected = source_signature(repo, sha)
return bool(expected) and hmac.compare_digest(expected, sig or '')
def open_gitea_archive(repo, sha):
# Streams the .zip for one commit from the Gitea API
url = '%s/archive/%s.zip' % (api_base(repo), sha)
response = requests.get(url, headers=gitea_headers(), stream=True, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
return response
+6 -1
View File
@@ -1,5 +1,9 @@
function enforce_default_text(id, text) { function enforce_default_text(id, text) {
// `text` may be a list of accepted prefixes; the first one is the default.
var prefixes = Array.isArray(text) ? text : [text];
text = prefixes[0];
window.addEventListener('DOMContentLoaded', function() { window.addEventListener('DOMContentLoaded', function() {
var field = document.getElementById(id); var field = document.getElementById(id);
@@ -9,7 +13,8 @@ function enforce_default_text(id, text) {
field.addEventListener('input', function() { field.addEventListener('input', function() {
if (field.value.startsWith(text) || field.value === text) // Accept any allowed prefix, and anything still being typed towards one
if (prefixes.some(function(p) { return field.value.startsWith(p) || p.startsWith(field.value); }))
return; return;
if (field.value.endsWith('/')) if (field.value.endsWith('/'))
+6 -2
View File
@@ -22,6 +22,7 @@ import html
import json import json
import re, django import re, django
import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models
import OpenBench.git_hosts
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
@@ -53,14 +54,17 @@ def gitDiffLink(test):
if test.dev_engine in engines and engines[test.dev_engine]['private']: if test.dev_engine in engines and engines[test.dev_engine]['private']:
repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source'] repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source']
elif OpenBench.git_hosts.is_gitea(test.dev_repo):
repo = test.dev_repo # Gitea sources point at this server's /giteaSource/
else: else:
repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2]) repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2])
if test.test_mode == 'SPSA': if test.test_mode == 'SPSA':
if OpenBench.git_hosts.is_gitea(repo):
return OpenBench.utils.path_join(repo, 'commit', test.dev.sha)
return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8]) return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8])
return OpenBench.utils.path_join(repo, 'compare', return OpenBench.git_hosts.compare_url(repo, test.base.sha[:8], test.dev.sha[:8])
'{0}..{1}'.format( test.base.sha[:8], test.dev.sha[:8]))
def shortStatBlock(test): def shortStatBlock(test):
+1
View File
@@ -83,6 +83,7 @@ urlpatterns = [
django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info), django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info),
django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload), django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload),
django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network), django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network),
django.urls.path(r'giteaSource/', OpenBench.views.gitea_source),
django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error), django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error),
django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps), django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps),
django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error), django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error),
+4 -8
View File
@@ -436,16 +436,12 @@ def branch_is_out_of_date(test):
if test.dev_engine != test.base_engine: if test.dev_engine != test.base_engine:
return False return False
# Format the request to the Github endpoint import OpenBench.git_hosts
base = 'https://api.github.com/repos/'
base = test.dev_repo.replace('github.com', 'api.github.com/repos')
url = path_join(base, 'compare', '%s...%s' % (test.dev.sha, test.base.sha))
try: try:
# Out of date if ahead_by is non-zero # Out of date if the base has commits that the dev branch lacks
headers = read_git_credentials(test.dev_engine) headers = OpenBench.git_hosts.api_headers(test.dev_engine, test.dev_repo)
data = requests.get(url, headers=headers).json() return OpenBench.git_hosts.commits_ahead(test.dev_repo, test.dev.sha, test.base.sha, headers) > 0
return data.get('ahead_by', 0) > 0
except: except:
# If something went wrong, just ignore it # If something went wrong, just ignore it
+29 -3
View File
@@ -25,6 +25,7 @@ import django.shortcuts
import django.contrib.auth import django.contrib.auth
import OpenBench.config import OpenBench.config
import OpenBench.git_hosts
import OpenBench.utils import OpenBench.utils
import OpenBench.uiutils import OpenBench.uiutils
@@ -232,7 +233,10 @@ def profile_config(request):
for (engine, current_repo) in profile.repos.items(): for (engine, current_repo) in profile.repos.items():
repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/') repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/')
repo = 'https://github.com/%s' % (repo_name) repo = repo_name if repo_name.startswith('https://') else 'https://github.com/%s' % (repo_name)
if repo_name and not OpenBench.git_hosts.is_valid_repo(repo):
return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
if repo != current_repo and repo_name: if repo != current_repo and repo_name:
changes += 'Updated Engine: %s to use %s\n' % (engine, repo) changes += 'Updated Engine: %s to use %s\n' % (engine, repo)
@@ -246,8 +250,8 @@ def profile_config(request):
if engine_name != 'None' and engine_repo: if engine_name != 'None' and engine_repo:
if not engine_repo.startswith('https://github.com/'): if not OpenBench.git_hosts.is_valid_repo(engine_repo):
return redirect(request, '/profile/', error='Repositories must be on Github') return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
if not profile.engine: if not profile.engine:
profile.engine = engine_name profile.engine = engine_name
@@ -802,6 +806,28 @@ def client_worker_info(request):
# Pass back the Machine Id, and Secret Token for this session # Pass back the Machine Id, and Secret Token for this session
return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret }) return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret })
def gitea_source(request):
# Workers download sources with a plain GET. The link carries a signature
# made at test creation, so only repo/sha pairs this server handed out work.
repo = request.GET.get('repo', '')
sha = request.GET.get('sha' , '')
sig = request.GET.get('sig' , '')
if not OpenBench.git_hosts.verify_source_request(repo, sha, sig):
return django.http.HttpResponseForbidden('Invalid source link')
try:
upstream = OpenBench.git_hosts.open_gitea_archive(repo, sha)
except Exception:
import traceback; traceback.print_exc()
return HttpResponse('Unable to fetch the source archive', status=502)
owner, name = OpenBench.git_hosts.owner_and_name(repo)
response = django.http.StreamingHttpResponse(upstream.iter_content(chunk_size=1 << 16), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s-%s.zip"' % (name, sha[:8])
return response
@csrf_exempt @csrf_exempt
def client_get_network(request, engine, name): def client_get_network(request, engine, name):
+34 -33
View File
@@ -42,6 +42,7 @@ import requests
import traceback import traceback
import OpenBench.config import OpenBench.config
import OpenBench.git_hosts
import OpenBench.utils import OpenBench.utils
from OpenBench.models import * from OpenBench.models import *
@@ -245,9 +246,10 @@ def verify_draw_adj(errors, request, field):
except: errors.append('Invalid Draw Adjudication Setting. Try "None"?') except: errors.append('Invalid Draw Adjudication Setting. Try "None"?')
def verify_github_repo(errors, request, field): def verify_github_repo(errors, request, field):
pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$' try: assert OpenBench.git_hosts.is_valid_repo(request.POST[field])
try: assert re.match(pattern, request.POST[field]) except:
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>') hosts = ', '.join('%s<User>/<Repo>' % (prefix) for prefix in OpenBench.git_hosts.repo_prefixes())
errors.append('Sources must be found on %s' % (hosts))
def verify_network(errors, request, field, field_name, engine_field): def verify_network(errors, request, field, field_name, engine_field):
try: try:
@@ -353,19 +355,26 @@ def collect_github_info(errors, request, field):
# Get branch name / commit sha / tag, and the API path for it # Get branch name / commit sha / tag, and the API path for it
branch = request.POST['{0}_branch'.format(field)] branch = request.POST['{0}_branch'.format(field)]
bysha = bool(re.search('^[0-9a-fA-F]{40}$', branch))
# All API requests will share this common path. Some engines are private. # All API requests will share this common path. Some engines are private.
base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos') repo = request.POST['%s_repo' % (field)]
base = OpenBench.git_hosts.api_base(repo)
engine = request.POST['%s_engine' % (field)] engine = request.POST['%s_engine' % (field)]
private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private'] private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']
gitea = OpenBench.git_hosts.is_gitea(repo)
headers = {} headers = {}
## Step 1: Verify the target of the API requests ## Step 1: Verify the target of the API requests
## [A] We will not attempt to reach any site other than api.github.com ## [A] We will not attempt to reach any site other than api.github.com,
## or a Gitea server listed under "gitea_hosts" in the config
## [B] Private engines may only use their main repo for sources of tests ## [B] Private engines may only use their main repo for sources of tests
## [C] Determine which, if any, credentials we want to pass along ## [C] Determine which, if any, credentials we want to pass along
# Private engines rely on Github Actions artifacts, which Gitea does not offer
if private and gitea:
errors.append('Private engines must be hosted on Github')
return (None, None)
# Private engines must have a token stored in credentials.enginename # Private engines must have a token stored in credentials.enginename
if private and not (headers := OpenBench.utils.read_git_credentials(engine)): if private and not (headers := OpenBench.utils.read_git_credentials(engine)):
errors.append('Server does not have access tokens for this engine') errors.append('Server does not have access tokens for this engine')
@@ -377,59 +386,51 @@ def collect_github_info(errors, request, field):
return (None, None) return (None, None)
# Avoid leaking our credentials to other websites # Avoid leaking our credentials to other websites
if not base.startswith('https://api.github.com/'): if not OpenBench.git_hosts.is_valid_repo(repo):
errors.append('OpenBench may only reach Github\'s API') errors.append('OpenBench may only reach Github\'s API or a configured Gitea server')
return (None, None) return (None, None)
## Step 2: Connect to the Github API for the given Branch or Commit SHA. # Gitea servers get their own token if there is one, and nothing else.
# Without a token the repository has to be readable anonymously.
if gitea:
headers = OpenBench.git_hosts.gitea_headers()
## Step 2: Connect to the Github or Gitea API for the given Branch or Commit SHA.
## [A] We will attempt to parse the most recent commit message for a ## [A] We will attempt to parse the most recent commit message for a
## bench, unless one was supplied. ## bench, unless one was supplied.
## [B] We will translate any branch name into a commit SHA for later use, ## [B] We will translate any branch name into a commit SHA for later use,
## so we may compare branches and generate diff URLs ## so we may compare branches and generate diff URLs
## [C] If the engine is public, we will construct the URL to download the ## [C] If the engine is public, we will construct the URL to download the
## source code from Github into a .zip file. ## source code into a .zip file. Gitea sources go through this server.
## [D] If the engine is private, we will carry onto Step 3. ## [D] If the engine is private, we will carry onto Step 3.
try: # Fetch data from the Github API try: # Resolve the branch, tag, or commit sha
commit = OpenBench.git_hosts.fetch_commit(repo, branch, headers)
# Lookup branch or commit sha, but will fail for tags assert commit['message'] is not None and commit['sha']
url = OpenBench.utils.path_join(base, 'commits' if bysha else 'branches', branch) assert private or commit['tree']
data = requests.get(url, headers=headers).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = OpenBench.utils.path_join(base, 'commits', branch)
data = requests.get(url, headers=headers).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# Check that all the data we need going forward is present
assert 'message' in data['commit'] and 'sha' in data
assert private or 'sha' in data['commit']['tree']
except: # Unable to find for whatever reason except: # Unable to find for whatever reason
traceback.print_exc() traceback.print_exc()
errors.append('%s could not be found' % (branch or 'Branch')) hint = ' (no Gitea token on the server, so the repository must be public)' if gitea and not headers else ''
errors.append('%s could not be found%s' % (branch or 'Branch', hint))
return (None, None) return (None, None)
# Extract the bench from the web form, or from the commit message # Extract the bench from the web form, or from the commit message
if not (bench := determine_bench(request, field, data['commit']['message'])): if not (bench := determine_bench(request, field, commit['message'])):
errors.append('Unable to parse a Bench for %s' % (branch)) errors.append('Unable to parse a Bench for %s' % (branch))
return (None, None) return (None, None)
# Public Engines: Construct the .zip download and return everything # Public Engines: Construct the .zip download and return everything
if not private: if not private:
treeurl = data['commit']['tree']['sha'] + '.zip' source = OpenBench.git_hosts.source_url(request, repo, commit)
source = OpenBench.utils.path_join(request.POST['%s_repo' % (field)], 'archive', treeurl) return (source, branch, commit['sha'], bench), True
return (source, branch, data['sha'], bench), True
## Step 3: Construct the URL for the API request to list all Artifacts ## Step 3: Construct the URL for the API request to list all Artifacts
## [A] OpenBench artifacts are always run via a file named openbench.yml ## [A] OpenBench artifacts are always run via a file named openbench.yml
## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext ## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext
## [C] If those artifacts are not found, we flag the test as awaiting, and try later. ## [C] If those artifacts are not found, we flag the test as awaiting, and try later.
url, has_all = fetch_artifact_url(base, engine, headers, data['sha']) url, has_all = fetch_artifact_url(base, engine, headers, commit['sha'])
return (url, branch, data['sha'], bench), has_all return (url, branch, data['sha'], bench), has_all
def requests_illegal_fork(request, field): def requests_illegal_fork(request, field):
+2 -2
View File
@@ -15,8 +15,8 @@
document.addEventListener( document.addEventListener(
'DOMContentLoaded', function () { 'DOMContentLoaded', function () {
change_engine('{{ profile.engine }}', 'dev', '{{workload}}'); change_engine('{{ profile.engine }}', 'dev', '{{workload}}');
enforce_default_text('dev_repo', 'https://github.com/'); enforce_default_text('dev_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
enforce_default_text('base_repo', 'https://github.com/'); enforce_default_text('base_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
}, false }, false
); );
</script> </script>
+1 -1
View File
@@ -7,7 +7,7 @@
<script src="{% static 'default_text.js' %}?{{ static_version }}"></script> <script src="{% static 'default_text.js' %}?{{ static_version }}"></script>
<script> <script>
enforce_default_text('new-engine-repo', 'https://github.com/'); enforce_default_text('new-engine-repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
</script> </script>
{% endblock %} {% endblock %}