mirror of
https://gitea.com/gitea/act_runner.git
synced 2026-11-28 06:42:21 +08:00
fix: upload artifacts directly when jobs cannot reach the runner's cache (#1425)
- Jobs that cannot reach the runner's `docker_gwbridge` address skip the cache with a warning, instead of timing out on artifact uploads - Document how to keep the cache when jobs cannot reach the detected `cache.host` Fixes https://gitea.com/gitea/runner/issues/1423 _Written by Claude (Opus 5.5)._ Reviewed-on: https://gitea.com/gitea/runner/pulls/1425 Reviewed-by: bircni <bircni@icloud.com> Co-authored-by: silverwind <2021+silverwind@noreply.gitea.com>
This commit is contained in:
@@ -27,6 +27,12 @@ var hostOS = runtime.GOOS // replaced in tests
|
||||
// DrainGracePeriod caps the wait for container output to drain so the log tail is not truncated
|
||||
const DrainGracePeriod = 2 * time.Second
|
||||
|
||||
// CacheIsolation is how jobs reach a cache address on another network: attach ContainerID to theirs, or not at all on a docker_gwbridge gateway.
|
||||
type CacheIsolation struct {
|
||||
ContainerID string
|
||||
GatewayBridge bool
|
||||
}
|
||||
|
||||
// ExitCodeError reports a non-zero process exit code from a container command.
|
||||
type ExitCodeError int
|
||||
|
||||
|
||||
@@ -238,23 +238,23 @@ func removeNetwork(ctx context.Context, cli client.APIClient, name string) error
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// IsolatedCacheContainer returns the container holding addr, when jobs on jobNetwork cannot reach it there.
|
||||
func IsolatedCacheContainer(ctx context.Context, addr netip.Addr, jobNetwork string) (string, error) {
|
||||
// DetectCacheIsolation finds what jobs on jobNetwork need to reach a cache address held by another container.
|
||||
func DetectCacheIsolation(ctx context.Context, addr netip.Addr, jobNetwork string) (CacheIsolation, error) {
|
||||
cli, err := GetDockerClient(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return CacheIsolation{}, err
|
||||
}
|
||||
defer cli.Close()
|
||||
return isolatedCacheContainer(ctx, cli, addr, jobNetwork)
|
||||
return detectCacheIsolation(ctx, cli, addr, jobNetwork)
|
||||
}
|
||||
|
||||
func isolatedCacheContainer(ctx context.Context, cli client.APIClient, addr netip.Addr, jobNetwork string) (string, error) {
|
||||
func detectCacheIsolation(ctx context.Context, cli client.APIClient, addr netip.Addr, jobNetwork string) (CacheIsolation, error) {
|
||||
if jobNetwork == "host" || strings.HasPrefix(jobNetwork, "container:") {
|
||||
return "", nil
|
||||
return CacheIsolation{}, nil
|
||||
}
|
||||
containers, err := cli.ContainerList(ctx, client.ContainerListOptions{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
return CacheIsolation{}, err
|
||||
}
|
||||
var holderID, holderContainer string
|
||||
for _, summary := range containers.Items {
|
||||
@@ -268,18 +268,29 @@ func isolatedCacheContainer(ctx context.Context, cli client.APIClient, addr neti
|
||||
}
|
||||
}
|
||||
}
|
||||
if holderID == "" {
|
||||
return "", nil
|
||||
if holderID == "" { // ContainerList omits docker_gwbridge gateway endpoints, which attaching their container to a job network would remove
|
||||
gateway, err := cli.NetworkInspect(ctx, "docker_gwbridge", client.NetworkInspectOptions{})
|
||||
if cerrdefs.IsNotFound(err) {
|
||||
return CacheIsolation{}, nil
|
||||
} else if err != nil {
|
||||
return CacheIsolation{}, err
|
||||
}
|
||||
for _, endpoint := range gateway.Network.Containers {
|
||||
if endpoint.IPv4Address.Addr() == addr || endpoint.IPv6Address.Addr() == addr {
|
||||
return CacheIsolation{GatewayBridge: true}, nil
|
||||
}
|
||||
}
|
||||
return CacheIsolation{}, nil
|
||||
}
|
||||
holder, err := cli.NetworkInspect(ctx, holderID, client.NetworkInspectOptions{})
|
||||
if err != nil || holder.Network.Driver != "bridge" {
|
||||
return "", err
|
||||
return CacheIsolation{}, err
|
||||
}
|
||||
if jobNetwork != "" {
|
||||
job, err := cli.NetworkInspect(ctx, jobNetwork, client.NetworkInspectOptions{})
|
||||
if err != nil || job.Network.ID == holderID {
|
||||
return "", err
|
||||
return CacheIsolation{}, err
|
||||
}
|
||||
}
|
||||
return holderContainer, nil
|
||||
return CacheIsolation{ContainerID: holderContainer}, nil
|
||||
}
|
||||
|
||||
@@ -20,10 +20,11 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestIsolatedCacheContainer(t *testing.T) {
|
||||
func TestDetectCacheIsolation(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
cache, lan := netip.MustParseAddr("172.18.0.3"), netip.MustParseAddr("192.168.1.20")
|
||||
cache, lan, gateway := netip.MustParseAddr("172.18.0.3"), netip.MustParseAddr("192.168.1.20"), netip.MustParsePrefix("172.19.0.3/16")
|
||||
client := &mockDockerClient{}
|
||||
client.On("NetworkInspect", ctx, "docker_gwbridge", mobyclient.NetworkInspectOptions{}).Return(mobyclient.NetworkInspectResult{}, cerrdefs.ErrNotFound).Once()
|
||||
client.On("ContainerList", ctx, mobyclient.ContainerListOptions{}).Return(mobyclient.ContainerListResult{Items: []container.Summary{{}, {
|
||||
ID: "0123456789abcdef",
|
||||
NetworkSettings: &container.NetworkSettingsSummary{Networks: map[string]*network.EndpointSettings{
|
||||
@@ -31,26 +32,29 @@ func TestIsolatedCacheContainer(t *testing.T) {
|
||||
"lan": {NetworkID: "beef", IPAddress: lan},
|
||||
}},
|
||||
}}}, nil)
|
||||
for ref, inspected := range map[string]network.Network{
|
||||
"c0ffee": {ID: "c0ffee", Name: "compose", Driver: "bridge"},
|
||||
"beef": {ID: "beef", Name: "lan", Driver: "macvlan"},
|
||||
"c0f": {ID: "c0ffee"},
|
||||
"jobs": {ID: "f00d"},
|
||||
for ref, inspected := range map[string]network.Inspect{
|
||||
"c0ffee": {Network: network.Network{ID: "c0ffee", Name: "compose", Driver: "bridge"}},
|
||||
"beef": {Network: network.Network{ID: "beef", Name: "lan", Driver: "macvlan"}},
|
||||
"c0f": {Network: network.Network{ID: "c0ffee"}},
|
||||
"jobs": {Network: network.Network{ID: "f00d"}},
|
||||
"docker_gwbridge": {Containers: map[string]network.EndpointResource{"fedcba9876543210": {IPv4Address: gateway}}},
|
||||
} {
|
||||
client.On("NetworkInspect", ctx, ref, mobyclient.NetworkInspectOptions{}).
|
||||
Return(mobyclient.NetworkInspectResult{Network: network.Inspect{Network: inspected}}, nil)
|
||||
Return(mobyclient.NetworkInspectResult{Network: inspected}, nil)
|
||||
}
|
||||
check := func(addr netip.Addr, jobNetwork, want string) {
|
||||
got, err := isolatedCacheContainer(ctx, client, addr, jobNetwork)
|
||||
check := func(addr netip.Addr, jobNetwork string, want CacheIsolation) {
|
||||
got, err := detectCacheIsolation(ctx, client, addr, jobNetwork)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got, jobNetwork)
|
||||
}
|
||||
check(cache, "", "0123456789ab")
|
||||
check(cache, "jobs", "0123456789ab")
|
||||
check(cache, "c0f", "")
|
||||
check(cache, "host", "")
|
||||
check(lan, "", "")
|
||||
check(netip.MustParseAddr("10.0.0.5"), "", "")
|
||||
check(cache, "", CacheIsolation{ContainerID: "0123456789ab"})
|
||||
check(cache, "jobs", CacheIsolation{ContainerID: "0123456789ab"})
|
||||
check(cache, "c0f", CacheIsolation{})
|
||||
check(cache, "host", CacheIsolation{})
|
||||
check(lan, "", CacheIsolation{})
|
||||
check(gateway.Addr(), "jobs", CacheIsolation{})
|
||||
check(gateway.Addr(), "jobs", CacheIsolation{GatewayBridge: true})
|
||||
check(netip.MustParseAddr("10.0.0.5"), "", CacheIsolation{})
|
||||
}
|
||||
|
||||
func TestIsAddressPoolExhausted(t *testing.T) {
|
||||
|
||||
@@ -23,8 +23,8 @@ func GetDockerClient(context.Context) (client.APIClient, error) {
|
||||
return nil, errors.ErrUnsupported
|
||||
}
|
||||
|
||||
func IsolatedCacheContainer(context.Context, netip.Addr, string) (string, error) {
|
||||
return "", nil
|
||||
func DetectCacheIsolation(context.Context, netip.Addr, string) (CacheIsolation, error) {
|
||||
return CacheIsolation{}, nil
|
||||
}
|
||||
|
||||
// ImageExistsLocally returns a boolean indicating if an image with the
|
||||
|
||||
@@ -73,8 +73,8 @@ type Runner struct {
|
||||
cacheHandler *artifactcache.Handler
|
||||
capabilities string
|
||||
|
||||
isolatedCacheContainer func(cacheURL string) string
|
||||
instanceTransport http.RoundTripper
|
||||
cacheIsolation func(cacheURL string) container.CacheIsolation
|
||||
instanceTransport http.RoundTripper
|
||||
|
||||
runningTasks sync.Map
|
||||
runningCount atomic.Int64
|
||||
@@ -141,7 +141,7 @@ func NewRunner(cfg *config.Config, reg *config.Registration, cli client.Client)
|
||||
now: time.Now,
|
||||
runHealthCheck: executeHealthCheck,
|
||||
}
|
||||
runner.isolatedCacheContainer = lastResult(runner.detectIsolatedCacheContainer)
|
||||
runner.cacheIsolation = lastResult(runner.detectCacheIsolation)
|
||||
runner.instanceTransport = instanceTransport
|
||||
return runner
|
||||
}
|
||||
@@ -196,7 +196,7 @@ func (r *Runner) cleanupOrphanDockerResources(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
cutoff := r.now().Add(-orphanDockerResourceAge)
|
||||
if err := removeOrphanNetworks(ctx, r.uuid, r.isolatedCacheContainer(r.cacheHandler.ExternalURL()), cutoff); err != nil {
|
||||
if err := removeOrphanNetworks(ctx, r.uuid, r.cacheIsolation(r.cacheHandler.ExternalURL()).ContainerID, cutoff); err != nil {
|
||||
logging.Warnf("failed to clean up networks left behind by earlier jobs: %v", err)
|
||||
}
|
||||
if err := removeOrphanJobVolumes(ctx, r.uuid, cutoff); err != nil {
|
||||
@@ -676,13 +676,13 @@ func (r *Runner) run(ctx context.Context, task *runnerv1.Task, reporter *report.
|
||||
return execErr
|
||||
}
|
||||
|
||||
func lastResult(compute func(key string) (string, bool)) func(key string) string {
|
||||
func lastResult[T any](compute func(key string) (T, bool)) func(key string) T {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
lastKey string
|
||||
result string
|
||||
result T
|
||||
)
|
||||
return func(key string) string {
|
||||
return func(key string) T {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if key == lastKey {
|
||||
@@ -968,10 +968,16 @@ func (r *Runner) cacheForJob(job *model.Job, platform string, logf func(string,
|
||||
if cacheURL == "" || strings.HasPrefix(platform, labels.SchemeKubernetes+"://") || (jobContainer == nil || jobContainer.Image == "") && platform == labels.SelfHostedPlatform {
|
||||
return cacheURL, ""
|
||||
}
|
||||
if cacheContainer := r.isolatedCacheContainer(cacheURL); cacheContainer != "" {
|
||||
isolation := r.cacheIsolation(cacheURL)
|
||||
if isolation.GatewayBridge {
|
||||
logf("::warning::%s", runner.EscapeCommandData("Cache disabled for this job because it cannot reach the runner's docker_gwbridge address. "+
|
||||
"Set cache.host to the host's address and publish a fixed cache.port on it in host mode."))
|
||||
return "", ""
|
||||
}
|
||||
if isolation.ContainerID != "" {
|
||||
isolatedURL, _ := url.Parse(cacheURL)
|
||||
isolatedURL.Host = net.JoinHostPort(cacheContainer, isolatedURL.Port())
|
||||
return isolatedURL.String(), cacheContainer
|
||||
isolatedURL.Host = net.JoinHostPort(isolation.ContainerID, isolatedURL.Port())
|
||||
return isolatedURL.String(), isolation.ContainerID
|
||||
}
|
||||
network, enableIPv6 := r.cfg.Container.Network, r.cfg.Container.NetworkCreateOptions.EnableIPv6
|
||||
if addr, err := netip.ParseAddr(hostOf(cacheURL)); err == nil && addr.Is6() && r.cfg.Cache.Host == "" &&
|
||||
@@ -982,19 +988,19 @@ func (r *Runner) cacheForJob(job *model.Job, platform string, logf func(string,
|
||||
return cacheURL, ""
|
||||
}
|
||||
|
||||
func (r *Runner) detectIsolatedCacheContainer(cacheURL string) (string, bool) {
|
||||
func (r *Runner) detectCacheIsolation(cacheURL string) (container.CacheIsolation, bool) {
|
||||
addr, err := netip.ParseAddr(hostOf(cacheURL))
|
||||
if err != nil {
|
||||
return "", true
|
||||
return container.CacheIsolation{}, true
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cacheContainer, err := container.IsolatedCacheContainer(ctx, addr, r.cfg.Container.Network)
|
||||
isolation, err := container.DetectCacheIsolation(ctx, addr, r.cfg.Container.Network)
|
||||
if err != nil {
|
||||
logging.Warnf("cannot check whether jobs reach the cache server: %v", err)
|
||||
return "", false
|
||||
return container.CacheIsolation{}, false
|
||||
}
|
||||
return cacheContainer, true
|
||||
return isolation, true
|
||||
}
|
||||
|
||||
// taskLogFields returns key/value pairs for logging.With.
|
||||
|
||||
@@ -341,7 +341,9 @@ func TestRunnerOnIdleRemovesOrphanNetworks(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
r := &Runner{uuid: "runner-1", cfg: cfg, labels: labels.Labels{kubernetesLabel}, now: func() time.Time { return now }}
|
||||
r.isolatedCacheContainer = func(_cacheURL string) string { return "a1b2c3d4e5f6" }
|
||||
r.cacheIsolation = func(_cacheURL string) container.CacheIsolation {
|
||||
return container.CacheIsolation{ContainerID: "a1b2c3d4e5f6"}
|
||||
}
|
||||
r.OnIdle(t.Context())
|
||||
assert.Equal(t, []string{"runner-1"}, swept)
|
||||
assert.Equal(t, swept, sweptVolumes)
|
||||
@@ -353,7 +355,7 @@ func TestRunnerOnIdleRemovesOrphanNetworks(t *testing.T) {
|
||||
dockerReachable = func(context.Context) bool { return false }
|
||||
t.Cleanup(func() { dockerReachable = origDockerReachable })
|
||||
hostOnly := &Runner{uuid: "runner-2", cfg: &config.Config{Runner: cfg.Runner}, now: func() time.Time { return now }}
|
||||
hostOnly.isolatedCacheContainer = func(_cacheURL string) string { return "" }
|
||||
hostOnly.cacheIsolation = func(_cacheURL string) container.CacheIsolation { return container.CacheIsolation{} }
|
||||
hostOnly.OnIdle(t.Context())
|
||||
assert.Equal(t, []string{"runner-1"}, swept)
|
||||
assert.Equal(t, swept, sweptVolumes)
|
||||
|
||||
@@ -391,7 +391,9 @@ func TestNewRunnerCacheServiceV2(t *testing.T) {
|
||||
|
||||
workflow, err := model.ReadWorkflow(strings.NewReader(`jobs: {native: {runs-on: native}, linux: {runs-on: linux}, containerized: {runs-on: native, container: alpine}, empty: {runs-on: native, container: ""}}`))
|
||||
require.NoError(t, err)
|
||||
r.isolatedCacheContainer = func(_cacheURL string) string { return "a1b2c3d4e5f6" }
|
||||
r.cacheIsolation = func(_cacheURL string) container.CacheIsolation {
|
||||
return container.CacheIsolation{ContainerID: "a1b2c3d4e5f6"}
|
||||
}
|
||||
pickPlatform := func(runsOn []string) string { return map[string]string{"native": labels.SelfHostedPlatform}[runsOn[0]] }
|
||||
for job, isolated := range map[string]bool{"native": false, "linux": true, "containerized": true, "empty": false} {
|
||||
cacheURL, cacheContainer := r.cacheForJob(workflow.GetJob(job), pickPlatform(workflow.GetJob(job).RunsOn()), t.Logf)
|
||||
@@ -405,14 +407,14 @@ func TestNewRunnerCacheServiceV2(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheForJobIPv6WarningAndIsolationRecheck(t *testing.T) {
|
||||
func TestCacheForJobWarningsAndIsolationRecheck(t *testing.T) {
|
||||
handler, err := artifactcache.StartHandler(artifactcache.Options{OutboundIP: "2001:db8::1", Upstream: "http://cache.invalid"})
|
||||
require.NoError(t, err)
|
||||
defer handler.Close()
|
||||
var checked []string
|
||||
r := &Runner{cfg: &config.Config{}, cacheHandler: handler, isolatedCacheContainer: lastResult(func(cacheURL string) (string, bool) {
|
||||
r := &Runner{cfg: &config.Config{}, cacheHandler: handler, cacheIsolation: lastResult(func(cacheURL string) (container.CacheIsolation, bool) {
|
||||
checked = append(checked, cacheURL)
|
||||
return "", cacheURL != "http://unreachable"
|
||||
return container.CacheIsolation{}, cacheURL != "http://unreachable"
|
||||
})}
|
||||
warnings := 0
|
||||
logf := func(_format string, _args ...any) { warnings++ }
|
||||
@@ -435,9 +437,15 @@ func TestCacheForJobIPv6WarningAndIsolationRecheck(t *testing.T) {
|
||||
r.cacheForJob(workflow.GetJob("containerized"), labels.SelfHostedPlatform, logf)
|
||||
assert.Equal(t, 3, warnings)
|
||||
|
||||
r.isolatedCacheContainer("http://unreachable")
|
||||
r.isolatedCacheContainer("http://unreachable")
|
||||
r.cacheIsolation("http://unreachable")
|
||||
r.cacheIsolation("http://unreachable")
|
||||
assert.Len(t, checked, 3)
|
||||
|
||||
r.cacheIsolation = func(_cacheURL string) container.CacheIsolation { return container.CacheIsolation{GatewayBridge: true} }
|
||||
cacheURL, cacheContainer := r.cacheForJob(workflow.GetJob("containerized"), labels.SelfHostedPlatform, logf)
|
||||
assert.Empty(t, cacheURL)
|
||||
assert.Empty(t, cacheContainer)
|
||||
assert.Equal(t, 4, warnings)
|
||||
}
|
||||
|
||||
func TestRestoreCalledWorkflowContext(t *testing.T) {
|
||||
|
||||
@@ -177,9 +177,8 @@ cache:
|
||||
# Directory where cache blobs are stored on disk. Default: $HOME/.cache/actcache
|
||||
# Ignored when external_server is set.
|
||||
#dir: ""
|
||||
# Outbound IP or hostname that job containers use to reach this runner's cache server.
|
||||
# Leave empty to detect automatically. 0.0.0.0 is not valid here.
|
||||
# A runner container on the jobs' Docker daemon attaches to each job network automatically.
|
||||
# IP or hostname jobs reach the cache server at, detected when empty. 0.0.0.0 is not valid.
|
||||
# If jobs cannot reach the detected one, set the host's address and publish a fixed port.
|
||||
#host: ""
|
||||
# Port for the built-in cache server. 0 picks a random free port.
|
||||
#port: 0
|
||||
|
||||
Reference in New Issue
Block a user