diff --git a/.gitea/workflows/images.yml b/.gitea/workflows/images.yml index 8279673..5eea555 100644 --- a/.gitea/workflows/images.yml +++ b/.gitea/workflows/images.yml @@ -30,11 +30,40 @@ jobs: GITEA_SERVER_URL: ${{ github.server_url }} run: | set -euo pipefail - if ! curl --fail --silent --show-error --connect-timeout 5 --max-time 15 \ - --output /dev/null "${GITEA_SERVER_URL%/}/api/v1/version"; then - echo 'Gitea HTTPS is unreachable from the job environment. Check runner-host DNS and container.options --add-host=git.anya.jp:172.18.0.10; see docs/operations/gitea-images.md.' >&2 + if ! command -v node >/dev/null 2>&1; then + echo 'Runner tool missing: node. Use a job environment with Node.js 20+ for the JavaScript Actions. No network check was performed.' >&2 exit 1 fi + node <<'NODE' + const https = require('node:https'); + let url; + try { + url = new URL(process.env.GITEA_SERVER_URL.replace(/\/$/, '') + '/api/v1/version'); + if (url.protocol !== 'https:' || url.username || url.password) throw new Error(); + } catch { + console.error('Invalid GITEA_SERVER_URL: expected an HTTPS URL without credentials.'); + process.exit(1); + } + const request = https.get(url, { rejectUnauthorized: true }, response => { + clearTimeout(deadline); + response.destroy(); // Only the verified TLS connection and HTTP status are needed. + if (response.statusCode !== 200) { + console.error(`Gitea responded with HTTP ${response.statusCode}; check the reverse proxy and access policy.`); + process.exitCode = 1; + } else { + console.log('Gitea HTTPS connectivity OK (TLS certificate verified).'); + } + }); + const deadline = setTimeout(() => { + request.destroy(Object.assign(new Error('Request deadline exceeded'), { code: 'ETIMEDOUT' })); + }, 15000); + request.on('error', error => { + clearTimeout(deadline); + console.error(`Gitea HTTPS check failed: ${error.code || 'UNKNOWN'}.`); + console.error('Check job-container DNS/hosts, routing and TLS trust. See docs/operations/gitea-images.md.'); + process.exitCode = 1; + }); + NODE - name: Check runner and publication configuration id: config diff --git a/docs/operations/gitea-images.md b/docs/operations/gitea-images.md index 70f6ec3..bb9f3d6 100644 --- a/docs/operations/gitea-images.md +++ b/docs/operations/gitea-images.md @@ -46,7 +46,7 @@ registry への 3 回の push は原子的ではない。途中で通信・認 runner の実行環境には以下が必要。 -- Linux amd64、bash、git、curl、Docker CLI と利用可能な Docker daemon。 +- Linux amd64、bash、git、Docker CLI と利用可能な Docker daemon。 - Node.js 20 対応の JavaScript Action 実行環境。 - Gitea、GitHub、Docker Hub、Go module proxy、npm registry への疎通。 - 3 イメージとビルドキャッシュを扱えるディスク容量。 @@ -121,7 +121,12 @@ getent ahostsv4 git.anya.jp curl --fail --connect-timeout 5 --max-time 15 https://git.anya.jp/api/v1/version ``` -workflowにもcheckoutより前のHTTPS疎通チェックを置いている。ただしrunner自体が +workflowにもcheckoutより前のHTTPS疎通チェックを置いている。これはJavaScript +Actionでも必要なNode.jsの標準HTTPSモジュールを使うため、ジョブ環境にcurlを +追加する必要はない。Node.js自体がない場合はツール不足として明示し、DNS・TLS・ +タイムアウト・HTTPエラーと区別する。TLS検証は有効、応答待ちは15秒で打ち切る。 +上のcurlコマンドはホストでの手動確認例。 +ただしrunner自体が Giteaへ接続できなければジョブは取得できないため、このチェックも実行されない。 Waitingのままならrunnerのオンライン状態・ラベル・空きスロットも確認する。 @@ -134,7 +139,49 @@ URLは `https://git.anya.jp` のまま保ち、IPのURLへの変更やTLS検証 2026-09-27の確認では、作業ホストと `--add-host` 付き一時コンテナの両方から 指定IPのGiteaへTLS検証付きで接続できた。実際のrunnerの設定変更・再起動は未実施。 -### 4. Registry 認証 +### 4. Docker版 Runner 3 の提示構成について + +`docker.io/gitea/runner:3` を利用する場合、環境変数 +`GITEA_RUNNER_LABELS: "ubuntu-latest"` はUbuntuコンテナを指定するものではない。 +実行方式の省略はhostモードなので、runnerコンテナ自身の中でジョブを実行する。 +curl等の不足を避けるには、ジョブイメージまで明示する。 + +```yaml +# Gitea側 docker-compose.yml の runner.environment を変更 +GITEA_RUNNER_LABELS: "ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest" +``` + +`./runner/data:/data` と `./runner/config.yaml:/config.yaml` の配置なら、 +`runner/config.yaml` の該当箇所へ以下をマージする。登録済みの `.runner` は消さない。 +環境変数のラベルは `runner.labels` より優先するため、Compose側も変更する。 + +```yaml +runner: + file: /data/.runner + capacity: 1 + timeout: 2h +container: + options: "--add-host=git.anya.jp:172.18.0.10" + docker_host: "unix:///var/run/docker.sock" + # 提示構成で既に存在するネットワークを利用し、自動的な /16 の作成を避ける。 + # このネットワークへ参加させるのは信頼済みジョブに限る。 + network: "anya-npm-net" +``` + +これは共有Docker socketを使用する構成で、強い権限を持つ点は変わらない。 +将来は本番サービスと別のCI専用daemon/networkへ分離する。 +runnerサービスに既にある `extra_hosts` とsocketのvolumeは維持する。 +ジョブ完了後、Gitea側のComposeディレクトリでrunnerだけを再作成する。 + +```bash +docker compose up -d --no-deps --force-recreate runner +``` + +`restart` だけではCompose環境変数の変更が反映されない。serverサービスや +登録データの削除・再登録は不要。新しいジョブ環境にもDocker CLIがあることと、 +`docker version` でdaemonに接続できることを確認する。 + +### 5. Registry 認証 Repository Settings → Actions → Secrets に次の値を設定する。 @@ -213,4 +260,5 @@ Gitea 上の runner / secrets の設定と実行成功は、ローカル検証 - [Gitea 1.24 Actions の互換性・制限](https://docs.gitea.com/1.24/usage/actions/comparison/) - [Gitea Container Registry](https://docs.gitea.com/usage/packages/container/) - [Gitea Runner設定(runner自身のバージョンに合わせて参照)](https://docs.gitea.com/runner/2/configuration/) +- [Gitea Runner 3 のラベルと優先順位](https://docs.gitea.com/runner/labels/) - [DockerコンテナのDNSとhosts](https://docs.docker.com/engine/network/#dns-services) diff --git a/tools/ci/test_gitea_preflight.py b/tools/ci/test_gitea_preflight.py new file mode 100644 index 0000000..5d177dd --- /dev/null +++ b/tools/ci/test_gitea_preflight.py @@ -0,0 +1,92 @@ +"""Exercise the actual pre-checkout script without requiring curl or a network.""" +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +WORKFLOW = Path(__file__).resolve().parents[2] / ".gitea/workflows/images.yml" +STEP = " - name: Check Gitea HTTPS connectivity before checkout\n" + + +class GiteaPreflightTest(unittest.TestCase): + def setUp(self): + self.bash = shutil.which("bash") + self.node = shutil.which("node") + if not self.bash or not self.node: + self.skipTest("bash and node required") + block = WORKFLOW.read_text().split(STEP, 1)[1].split("\n - name:", 1)[0] + lines = block.split(" run: |\n", 1)[1].splitlines() + self.script = "\n".join(line[10:] if line.startswith(" ") else line for line in lines) + + def run_check(self, mode="ok", url="https://gitea.example.test", node=True): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + if node: + (root / "node").symlink_to(self.node) + stub = root / "https.cjs" + stub.write_text(""" +const {EventEmitter} = require('node:events'); +const https = require('node:https'); +const assert = require('node:assert/strict'); +https.get = (url, options, callback) => { + assert.equal(url.pathname, '/api/v1/version'); + assert.equal(options.rejectUnauthorized, true); + const request = new EventEmitter(); + request.destroy = error => request.emit('error', error); + process.nextTick(() => { + if (process.env.CHECK_MODE === 'dns') { + request.emit('error', {code: 'ENOTFOUND'}); + } else if (process.env.CHECK_MODE === 'tls') { + request.emit('error', {code: 'CERT_HAS_EXPIRED'}); + } else if (process.env.CHECK_MODE !== 'timeout') { + callback({statusCode: process.env.CHECK_MODE === 'http' ? 503 : 200, destroy() {}}); + } + }); + return request; +}; +if (process.env.CHECK_MODE === 'timeout') { + const original = global.setTimeout; + global.setTimeout = (callback, delay) => { + assert.equal(delay, 15000); + return original(callback, 1); + }; +} +""") + env = dict(os.environ, PATH=tmp, GITEA_SERVER_URL=url, + NODE_OPTIONS=f"--require={stub}", CHECK_MODE=mode) + return subprocess.run([self.bash, "-c", self.script], env=env, + capture_output=True, text=True, timeout=5) + + def test_success_without_curl(self): + result = self.run_check() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("connectivity OK", result.stdout) + + def test_missing_node_is_not_a_network_error(self): + result = self.run_check(node=False) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Runner tool missing: node", result.stderr) + self.assertIn("No network check was performed", result.stderr) + self.assertNotIn("HTTPS check failed", result.stderr) + + def test_invalid_url(self): + for url in ["http://gitea.example.test", "bad url", "https://user:pass@gitea.example.test"]: + with self.subTest(url=url): + result = self.run_check(url=url) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Invalid GITEA_SERVER_URL", result.stderr) + + def test_failure_diagnostics(self): + for mode, message in [("http", "HTTP 503"), ("dns", "ENOTFOUND"), + ("tls", "CERT_HAS_EXPIRED"), ("timeout", "ETIMEDOUT")]: + with self.subTest(mode=mode): + result = self.run_check(mode=mode) + self.assertNotEqual(result.returncode, 0) + self.assertIn(message, result.stderr) + + +if __name__ == "__main__": + unittest.main()