mirror of
https://github.com/dagucloud/dagu.git
synced 2026-12-05 05:32:51 +00:00
Run each project's git sync on the server (P19) (#4592)
This commit is contained in:
1 parent
9441dace50
commit
faa29b44fb
20 files changed
+1647
-38
No files matched your search
@@ -145,7 +145,9 @@ func (c *Context) registerServer(ctx context.Context, cache *persisfile.ProjectS
|
||||
Status: serviceregistry.ServiceStatusActive,
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
if err := registry.Register(ctx, serviceregistry.ServiceNameServer, host); err != nil {
|
||||
// The entry is renewed until unregister, not only until ctx ends, so it
|
||||
// stays live while shutdown waits for the projects' pulls.
|
||||
if err := registry.Register(context.WithoutCancel(ctx), serviceregistry.ServiceNameServer, host); err != nil {
|
||||
return nil, fmt.Errorf("failed to register with service registry: %w", err)
|
||||
}
|
||||
return func() { registry.Unregister(context.WithoutCancel(ctx)) }, nil
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -241,7 +242,15 @@ func runStartAll(ctx *Context, _ []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unregister()
|
||||
// A server still serving when start-all gives up waiting may still be
|
||||
// draining project git pulls, so it stays listed; its entry goes stale
|
||||
// once the process ends, and no delete overlaps the pulls.
|
||||
var serving atomic.Bool
|
||||
defer func() {
|
||||
if !serving.Load() {
|
||||
unregister()
|
||||
}
|
||||
}()
|
||||
runProjectStores(serviceCtx, projects)
|
||||
|
||||
// Use serviceCtx so auth initialization can respond to termination signals
|
||||
@@ -330,7 +339,10 @@ func runStartAll(ctx *Context, _ []string) error {
|
||||
tag.Host(serviceCtx.Config.Server.Host),
|
||||
tag.Port(serviceCtx.Config.Server.Port),
|
||||
)
|
||||
if err := server.Serve(serviceCtx); err != nil {
|
||||
serving.Store(true)
|
||||
err := server.Serve(serviceCtx)
|
||||
serving.Store(false)
|
||||
if err != nil {
|
||||
select {
|
||||
case errCh <- fmt.Errorf("server failed: %w", withPortInUseHint(err, webPortInUseHint)):
|
||||
default:
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/gitsync"
|
||||
"github.com/dagucloud/dagu/v2/internal/persis/file"
|
||||
"github.com/dagucloud/dagu/v2/internal/persis/file/projectregistry"
|
||||
"github.com/dagucloud/dagu/v2/internal/project"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
@@ -667,6 +668,43 @@ func runSyncMove(ctx *Context, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// projectSyncExclusions returns the paths that git_sync, whose settings are
|
||||
// global, leaves out by the git sync settings each project has stored.
|
||||
func projectSyncExclusions(ctx *Context, global *gitsync.Config) ([]string, error) {
|
||||
projects, err := projectregistry.New(ctx.Config.Paths.DataDir).List(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the project registry: %w", err)
|
||||
}
|
||||
var syncs []*gitsync.Config
|
||||
for _, p := range projects {
|
||||
// A project marked deleting keeps its path out until it is gone.
|
||||
if strings.EqualFold(p.Name, project.DefaultName) {
|
||||
continue
|
||||
}
|
||||
settings, err := file.NewProjectSettings(ctx.Config, ctx.serverStores, p.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
store, err := settings.GitSyncStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Settings whose credentials do not decrypt still name the
|
||||
// project's repository and path.
|
||||
projectSync, err := store.Get(ctx)
|
||||
if err != nil && projectSync == nil {
|
||||
return nil, fmt.Errorf("project %q: %w", p.Name, err)
|
||||
}
|
||||
// A delete removes the settings before the registry entry, so a
|
||||
// deleting project without them may still own files.
|
||||
if p.Deleting && projectSync == nil {
|
||||
return nil, fmt.Errorf("project %q is being deleted; run the command again once the delete has ended", p.Name)
|
||||
}
|
||||
syncs = append(syncs, projectSync)
|
||||
}
|
||||
return gitsync.ExcludedPaths(ctx.Config, global, syncs), nil
|
||||
}
|
||||
|
||||
// newSyncService creates a new GitSync service from the context configuration.
|
||||
func newSyncService(ctx *Context) (gitsync.Service, error) {
|
||||
syncCfg := gitsync.NewConfigFromGlobal(ctx.Config.GitSync)
|
||||
@@ -687,5 +725,12 @@ func newSyncService(ctx *Context) (gitsync.Service, error) {
|
||||
}
|
||||
opts = append(opts, gitsync.WithInventories(inventories))
|
||||
}
|
||||
if ctx.Config.ProjectsEnabled {
|
||||
excluded, err := projectSyncExclusions(ctx, syncCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts = append(opts, gitsync.WithExcludedPaths(func(*gitsync.Config) ([]string, error) { return excluded, nil }))
|
||||
}
|
||||
return gitsync.NewService(syncCfg, ctx.Config.Paths.DAGsDir, ctx.Config.Paths.WikiDir, ctx.Config.Paths.CalendarsDir, ctx.Config.Paths.DataDir, opts...), nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright (C) 2026 Yota Hamada
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package gitsync
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/pem"
|
||||
"testing"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
cryptossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// An SSH key given as content authenticates without a key file.
|
||||
func TestSSHKeyContentAuth(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pub, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
block, err := cryptossh.MarshalPrivateKey(key, "")
|
||||
require.NoError(t, err)
|
||||
|
||||
client := NewGitClient(&Config{Auth: AuthConfig{
|
||||
Type: AuthTypeSSH,
|
||||
SSHKey: string(pem.EncodeToMemory(block)),
|
||||
}}, "")
|
||||
auth, err := client.getAuth()
|
||||
require.NoError(t, err)
|
||||
keys, ok := auth.(*ssh.PublicKeys)
|
||||
require.True(t, ok)
|
||||
want, err := cryptossh.NewPublicKey(pub)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want.Marshal(), keys.Signer.PublicKey().Marshal())
|
||||
|
||||
client = NewGitClient(&Config{Auth: AuthConfig{Type: AuthTypeSSH, SSHKey: "not a key"}}, "")
|
||||
_, err = client.getAuth()
|
||||
require.Error(t, err)
|
||||
}
|
||||
+159
-1
@@ -3,7 +3,17 @@
|
||||
|
||||
package gitsync
|
||||
|
||||
import "github.com/dagucloud/dagu/v2/internal/cmn/config"
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-git/go-git/v5/plumbing/transport"
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/config"
|
||||
)
|
||||
|
||||
// Config holds the configuration for Git sync functionality.
|
||||
type Config struct {
|
||||
@@ -50,6 +60,10 @@ type AuthConfig struct {
|
||||
// SSHKeyPath is the path to the SSH private key file.
|
||||
SSHKeyPath string
|
||||
|
||||
// SSHKey is the SSH private key in PEM form. It takes precedence over
|
||||
// SSHKeyPath.
|
||||
SSHKey string
|
||||
|
||||
// SSHPassphrase is the passphrase for the SSH key (optional).
|
||||
SSHPassphrase string
|
||||
}
|
||||
@@ -105,6 +119,150 @@ func (c *Config) GetAuthorEmail() string {
|
||||
return "dagu@localhost"
|
||||
}
|
||||
|
||||
// ExcludedPaths returns the paths, relative to the repository's root, that
|
||||
// global, the git sync of paths.dags_dir, leaves out while projects are on:
|
||||
// paths.projects_dir when it lies inside paths.dags_dir, and the path that
|
||||
// each enabled sync of projects syncs of global's repository, with its
|
||||
// inventory file. Repository URLs are compared after normalization;
|
||||
// branches are not compared.
|
||||
func ExcludedPaths(cfg *config.Config, global *Config, projects []*Config) []string {
|
||||
if !cfg.ProjectsEnabled {
|
||||
return nil
|
||||
}
|
||||
var excluded []string
|
||||
// paths.projects_dir, and each project directory linked from it, is
|
||||
// left out under each local folder git_sync writes that holds it: the
|
||||
// DAG directory, and the wiki folder, which takes the repository's
|
||||
// wiki/ or legacy docs/.
|
||||
projectDirs := projectDirs(cfg.Paths.ProjectsDir)
|
||||
wikiDir := cfg.Paths.WikiDir
|
||||
if wikiDir == "" {
|
||||
wikiDir = filepath.Join(cfg.Paths.DAGsDir, "wiki")
|
||||
}
|
||||
for _, root := range []struct {
|
||||
local string
|
||||
repoDirs []string
|
||||
}{
|
||||
{cfg.Paths.DAGsDir, []string{"."}},
|
||||
{wikiDir, []string{"wiki", "docs"}},
|
||||
} {
|
||||
for _, projectDir := range projectDirs {
|
||||
rel, ok := projectsDirWithin(projectDir, root.local)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, dir := range root.repoDirs {
|
||||
excluded = append(excluded, cleanRepoPath(path.Join(cleanRepoPath(global.Path), dir, rel)))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, project := range projects {
|
||||
if project == nil || !project.Enabled || global.Repository == "" {
|
||||
continue
|
||||
}
|
||||
if repositoryKey(global.Repository) == repositoryKey(project.Repository) {
|
||||
excluded = append(excluded, cleanRepoPath(project.Path))
|
||||
// The project's inventory file may lie outside its path.
|
||||
if project.InventoryPath != "" {
|
||||
excluded = append(excluded, cleanRepoPath(project.InventoryPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
return excluded
|
||||
}
|
||||
|
||||
// projectDirs returns projectsDir and each directory a symbolic link in it
|
||||
// leads to, as a project directory may lie elsewhere through a link.
|
||||
func projectDirs(projectsDir string) []string {
|
||||
if projectsDir == "" {
|
||||
return nil
|
||||
}
|
||||
dirs := []string{projectsDir}
|
||||
entries, err := os.ReadDir(projectsDir)
|
||||
if err != nil {
|
||||
return dirs
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Type()&os.ModeSymlink == 0 {
|
||||
continue
|
||||
}
|
||||
if target, err := filepath.EvalSymlinks(filepath.Join(projectsDir, entry.Name())); err == nil {
|
||||
dirs = append(dirs, target)
|
||||
}
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
// projectsDirWithin returns the slash path of projectsDir relative to
|
||||
// root, "." when they are one, and reports whether it lies inside root.
|
||||
// Paths are compared after resolving links and without regard to case, as
|
||||
// a case-insensitive volume may spell one directory two ways; exclusions
|
||||
// match so anyway.
|
||||
func projectsDirWithin(projectsDir, root string) (string, bool) {
|
||||
if projectsDir == "" || root == "" {
|
||||
return "", false
|
||||
}
|
||||
rel, err := filepath.Rel(strings.ToLower(resolvedPath(root)), strings.ToLower(resolvedPath(projectsDir)))
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
|
||||
return "", false
|
||||
}
|
||||
return filepath.ToSlash(rel), true
|
||||
}
|
||||
|
||||
// resolvedPath returns dir with the symbolic links of its longest existing
|
||||
// part resolved, so that a directory not made yet resolves as its parent.
|
||||
func resolvedPath(dir string) string {
|
||||
dir = filepath.Clean(dir)
|
||||
rest := ""
|
||||
for {
|
||||
if resolved, err := filepath.EvalSymlinks(dir); err == nil {
|
||||
return filepath.Join(resolved, rest)
|
||||
}
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
return filepath.Join(dir, rest)
|
||||
}
|
||||
rest = filepath.Join(filepath.Base(dir), rest)
|
||||
dir = parent
|
||||
}
|
||||
}
|
||||
|
||||
// repositoryKey returns repo spelled so that the spellings of one
|
||||
// repository's URL compare equal.
|
||||
func repositoryKey(repo string) string {
|
||||
repo = strings.TrimSpace(repo)
|
||||
if !(&GitClient{}).isFullURL(repo) {
|
||||
// A clone takes a URL it does not know as an HTTPS one.
|
||||
repo = "https://" + repo
|
||||
}
|
||||
// The endpoint is read as go-git reads it for a clone, scp-like forms
|
||||
// included, and names host[:port]/org/repo; a port is kept only when
|
||||
// it is not its protocol's default.
|
||||
ep, err := transport.NewEndpoint(repo)
|
||||
if err != nil {
|
||||
return strings.ToLower(repo)
|
||||
}
|
||||
host := ep.Host
|
||||
if ep.Port != 0 && ep.Port != defaultPorts[ep.Protocol] {
|
||||
host += ":" + strconv.Itoa(ep.Port)
|
||||
}
|
||||
repoPath := strings.TrimSuffix(strings.Trim(ep.Path, "/"), ".git")
|
||||
return strings.ToLower(host + "/" + repoPath)
|
||||
}
|
||||
|
||||
// defaultPorts holds the port each protocol uses when a URL names none.
|
||||
var defaultPorts = map[string]int{"https": 443, "http": 80, "ssh": 22}
|
||||
|
||||
// cleanRepoPath returns p, a path in a repository, cleaned and relative to
|
||||
// the repository's root, which it spells ".".
|
||||
func cleanRepoPath(p string) string {
|
||||
cleaned := strings.TrimPrefix(path.Clean("/"+strings.ReplaceAll(p, `\`, "/")), "/")
|
||||
if cleaned == "" {
|
||||
return "."
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
// NewConfigFromGlobal creates a gitsync.Config from the global configuration.
|
||||
func NewConfigFromGlobal(cfg config.GitSyncConfig) *Config {
|
||||
return &Config{
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// Copyright (C) 2026 Yota Hamada
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package gitsync_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/config"
|
||||
"github.com/dagucloud/dagu/v2/internal/gitsync"
|
||||
)
|
||||
|
||||
func TestExcludedPaths(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
root := t.TempDir()
|
||||
cfg := &config.Config{ProjectsEnabled: true}
|
||||
cfg.Paths.DAGsDir = filepath.Join(root, "dags")
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "dags", "projects")
|
||||
global := &gitsync.Config{Enabled: true, Repository: "github.com/acme/dags"}
|
||||
projects := []*gitsync.Config{
|
||||
{Enabled: true, Repository: "github.com:443/acme/dags.git", Path: "/ops/", InventoryPath: "shared/nodes.json"},
|
||||
{Enabled: false, Repository: "github.com/acme/dags", Path: "billing"},
|
||||
{Enabled: true, Repository: "github.com/acme/other", Path: "sales"},
|
||||
nil,
|
||||
}
|
||||
assert.Equal(t, []string{"projects", "ops", "shared/nodes.json"}, gitsync.ExcludedPaths(cfg, global, projects))
|
||||
// Inside the wiki folder, projects are left out of wiki/ and docs/,
|
||||
// which both land there.
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "dags", "wiki", "projects")
|
||||
assert.Equal(t, []string{"wiki/projects", "wiki/projects", "docs/projects"}, gitsync.ExcludedPaths(cfg, global, nil))
|
||||
cfg.Paths.WikiDir = filepath.Join(root, "shared")
|
||||
cfg.Paths.ProjectsDir = cfg.Paths.WikiDir
|
||||
assert.Equal(t, []string{"wiki", "docs"}, gitsync.ExcludedPaths(cfg, global, nil), "a wiki folder that is projects_dir")
|
||||
cfg.Paths.WikiDir = ""
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "dags", "projects")
|
||||
|
||||
sshGlobal := &gitsync.Config{Enabled: true, Repository: "ssh://git@host/srv/dags.git"}
|
||||
scpProject := []*gitsync.Config{{Enabled: true, Repository: "git@host:/srv/dags.git", Path: "ops"}}
|
||||
assert.Equal(t, []string{"projects", "ops"}, gitsync.ExcludedPaths(cfg, sshGlobal, scpProject))
|
||||
portGlobal := &gitsync.Config{Enabled: true, Repository: "ssh://git@host:2222/srv/dags.git"}
|
||||
portProject := []*gitsync.Config{{Enabled: true, Repository: "git@host:2222:/srv/dags.git", Path: "ops"}}
|
||||
assert.Equal(t, []string{"projects", "ops"}, gitsync.ExcludedPaths(cfg, portGlobal, portProject))
|
||||
|
||||
// A project directory linked from projects_dir into the DAG directory
|
||||
// is left out where it lies.
|
||||
if runtime.GOOS != "windows" {
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(root, "dags", "ops"), 0o750))
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(root, "linked"), 0o750))
|
||||
require.NoError(t, os.Symlink(filepath.Join(root, "dags", "ops"), filepath.Join(root, "linked", "ops")))
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "linked")
|
||||
assert.Equal(t, []string{"ops"}, gitsync.ExcludedPaths(cfg, global, nil))
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "dags", "projects")
|
||||
}
|
||||
|
||||
// The paths are relative to the repository's root, whatever path
|
||||
// git_sync syncs, and a project syncing the whole repository leaves
|
||||
// none of it to git_sync.
|
||||
teams := &gitsync.Config{Enabled: true, Repository: "git@github.com:acme/dags.git", Path: "teams"}
|
||||
whole := slices.Concat(projects, []*gitsync.Config{{Enabled: true, Repository: "github.com/acme/dags"}})
|
||||
assert.Equal(t, []string{"teams/projects", "ops", "shared/nodes.json", "."}, gitsync.ExcludedPaths(cfg, teams, whole))
|
||||
|
||||
// A DAG directory reached through a link still holds the projects.
|
||||
if runtime.GOOS != "windows" {
|
||||
realDir := filepath.Join(root, "real")
|
||||
require.NoError(t, os.MkdirAll(realDir, 0o750))
|
||||
require.NoError(t, os.Symlink(realDir, filepath.Join(root, "link")))
|
||||
cfg.Paths.DAGsDir = filepath.Join(root, "link")
|
||||
cfg.Paths.ProjectsDir = filepath.Join(realDir, "projects")
|
||||
assert.Equal(t, []string{"projects", "ops", "shared/nodes.json"}, gitsync.ExcludedPaths(cfg, global, projects))
|
||||
}
|
||||
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "projects")
|
||||
assert.Equal(t, []string{"ops", "shared/nodes.json"}, gitsync.ExcludedPaths(cfg, global, projects))
|
||||
|
||||
cfg.ProjectsEnabled = false
|
||||
assert.Empty(t, gitsync.ExcludedPaths(cfg, global, projects))
|
||||
}
|
||||
|
||||
// A pull leaves an excluded path alone: it writes nothing there, and an item
|
||||
// synced before the path was excluded leaves the state with its file kept.
|
||||
func TestPullLeavesExcludedPathsOut(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
root := t.TempDir()
|
||||
remotePath := filepath.Join(root, "remote")
|
||||
remoteRepo := initPullExternalTestRepo(t, remotePath)
|
||||
commitPullExternalTestFile(t, remoteRepo, remotePath, "main.yaml", "steps: []\n", "main")
|
||||
commitPullExternalTestFile(t, remoteRepo, remotePath, "ops/etl.yaml", "steps: []\n", "ops")
|
||||
commitPullExternalTestFile(t, remoteRepo, remotePath, "ops.yaml", "steps: []\n", "beside ops")
|
||||
|
||||
dataDir := filepath.Join(root, "data")
|
||||
clonePullExternalTestRepo(ctx, t, dataDir, remotePath)
|
||||
dagsDir := filepath.Join(root, "dags")
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
excluded []string
|
||||
unknown error
|
||||
)
|
||||
svc := gitsync.NewService(&gitsync.Config{
|
||||
Enabled: true,
|
||||
Repository: remotePath,
|
||||
Branch: "main",
|
||||
PushEnabled: true,
|
||||
}, dagsDir, filepath.Join(dagsDir, "wiki"), "", dataDir, gitsync.WithExcludedPaths(func(*gitsync.Config) ([]string, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return excluded, unknown
|
||||
}))
|
||||
|
||||
_, err := svc.Pull(ctx)
|
||||
require.NoError(t, err)
|
||||
require.FileExists(t, filepath.Join(dagsDir, "ops", "etl.yaml"))
|
||||
|
||||
mu.Lock()
|
||||
excluded, unknown = []string{"ops"}, errors.New("settings unknown")
|
||||
mu.Unlock()
|
||||
|
||||
// While the exclusions are unknown, nothing is pulled or written.
|
||||
_, err = svc.Pull(ctx)
|
||||
require.ErrorContains(t, err, "settings unknown")
|
||||
require.ErrorContains(t, svc.Delete(ctx, "ops/etl", "remove", true), "settings unknown")
|
||||
|
||||
mu.Lock()
|
||||
unknown = nil
|
||||
mu.Unlock()
|
||||
|
||||
// While the state still lists it, the item cannot be deleted from the
|
||||
// remote, and no item moves under the excluded path.
|
||||
require.ErrorContains(t, svc.Delete(ctx, "ops/etl", "remove", true), "leaves out")
|
||||
require.ErrorContains(t, svc.Move(ctx, "main", "ops/main", "move", true), "leaves out")
|
||||
require.ErrorContains(t, svc.Discard(ctx, "ops/etl"), "leaves out")
|
||||
require.ErrorContains(t, svc.Move(ctx, "main", "OPS/main", "move", true), "leaves out", "matched without regard to case")
|
||||
assert.Equal(t, "steps: []\n", pullExternalFileContent(t, remoteRepo, "ops/etl.yaml"))
|
||||
assert.Equal(t, "steps: []\n", pullExternalFileContent(t, remoteRepo, "main.yaml"))
|
||||
|
||||
commitPullExternalTestFile(t, remoteRepo, remotePath, "ops/report.yaml", "steps: []\n", "report")
|
||||
removePullExternalTestFile(t, remoteRepo, "ops/etl.yaml", "remove etl")
|
||||
|
||||
result, err := svc.Pull(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, result.Deleted, "ops/etl")
|
||||
assert.FileExists(t, filepath.Join(dagsDir, "ops", "etl.yaml"), "the excluded item's file stays")
|
||||
assert.NoFileExists(t, filepath.Join(dagsDir, "ops", "report.yaml"), "nothing is written under an excluded path")
|
||||
|
||||
status, err := svc.GetStatus(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, status.Items, "main")
|
||||
assert.Contains(t, status.Items, "ops", "ops.yaml lies beside the excluded ops/, not in it")
|
||||
assert.NotContains(t, status.Items, "ops/etl")
|
||||
assert.NotContains(t, status.Items, "ops/report")
|
||||
}
|
||||
|
||||
// A clone whose origin is not the configured repository is not fetched, so
|
||||
// no credential goes to the repository the settings named before.
|
||||
func TestPullRefusesCloneOfOtherRepository(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
root := t.TempDir()
|
||||
oldRemote := filepath.Join(root, "old")
|
||||
oldRepo := initPullExternalTestRepo(t, oldRemote)
|
||||
commitPullExternalTestFile(t, oldRepo, oldRemote, "old.yaml", "steps: []\n", "old")
|
||||
newRemote := filepath.Join(root, "new")
|
||||
newRepo := initPullExternalTestRepo(t, newRemote)
|
||||
commitPullExternalTestFile(t, newRepo, newRemote, "new.yaml", "steps: []\n", "new")
|
||||
|
||||
dataDir := filepath.Join(root, "data")
|
||||
clonePullExternalTestRepo(ctx, t, dataDir, oldRemote)
|
||||
dagsDir := filepath.Join(root, "dags")
|
||||
svc := gitsync.NewService(&gitsync.Config{
|
||||
Enabled: true,
|
||||
Repository: newRemote,
|
||||
Branch: "main",
|
||||
}, dagsDir, filepath.Join(dagsDir, "wiki"), "", dataDir)
|
||||
|
||||
_, err := svc.Pull(ctx)
|
||||
require.ErrorContains(t, err, "remove the clone")
|
||||
assert.NoFileExists(t, filepath.Join(dagsDir, "old.yaml"))
|
||||
}
|
||||
|
||||
// A local file under an excluded path is not listed as untracked.
|
||||
func TestStatusLeavesExcludedLocalFilesOut(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
root := t.TempDir()
|
||||
dagsDir := filepath.Join(root, "dags")
|
||||
require.NoError(t, os.MkdirAll(dagsDir, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dagsDir, "main.yaml"), []byte("steps: []\n"), 0o600))
|
||||
svc := gitsync.NewService(&gitsync.Config{
|
||||
Enabled: true,
|
||||
Repository: "github.com/acme/dags",
|
||||
Branch: "main",
|
||||
}, dagsDir, filepath.Join(dagsDir, "wiki"), "", filepath.Join(root, "data"), gitsync.WithExcludedPaths(func(*gitsync.Config) ([]string, error) {
|
||||
return []string{"."}, nil
|
||||
}))
|
||||
|
||||
status, err := svc.GetStatus(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, status.Items)
|
||||
_, err = svc.GetSyncItemStatus(context.Background(), "main")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// A legacy docs/ directory that a project owns does not stand beside wiki/
|
||||
// as a second wiki of git_sync.
|
||||
func TestPullIgnoresExcludedWikiDirectory(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
root := t.TempDir()
|
||||
remotePath := filepath.Join(root, "remote")
|
||||
remoteRepo := initPullExternalTestRepo(t, remotePath)
|
||||
commitPullExternalTestFile(t, remoteRepo, remotePath, "wiki/runbook.md", "# Runbook\n", "wiki")
|
||||
commitPullExternalTestFile(t, remoteRepo, remotePath, "docs/guide.md", "# Guide\n", "docs")
|
||||
|
||||
dataDir := filepath.Join(root, "data")
|
||||
clonePullExternalTestRepo(ctx, t, dataDir, remotePath)
|
||||
dagsDir := filepath.Join(root, "dags")
|
||||
svc := gitsync.NewService(&gitsync.Config{
|
||||
Enabled: true,
|
||||
Repository: remotePath,
|
||||
Branch: "main",
|
||||
}, dagsDir, filepath.Join(dagsDir, "wiki"), "", dataDir, gitsync.WithExcludedPaths(func(*gitsync.Config) ([]string, error) {
|
||||
return []string{"docs"}, nil
|
||||
}))
|
||||
|
||||
_, err := svc.Pull(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.FileExists(t, filepath.Join(dagsDir, "wiki", "runbook.md"))
|
||||
}
|
||||
+53
-4
@@ -67,6 +67,13 @@ func (c *GitClient) getAuth() (transport.AuthMethod, error) {
|
||||
}, nil
|
||||
|
||||
case AuthTypeSSH:
|
||||
if c.cfg.Auth.SSHKey != "" {
|
||||
auth, err := newPublicKeys("git", []byte(c.cfg.Auth.SSHKey), c.cfg.Auth.SSHPassphrase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load SSH key: %w", err)
|
||||
}
|
||||
return auth, nil
|
||||
}
|
||||
if c.cfg.Auth.SSHKeyPath == "" {
|
||||
return nil, &ValidationError{Field: "auth.sshKeyPath", Message: "SSH key path is required for SSH auth"}
|
||||
}
|
||||
@@ -90,8 +97,15 @@ func newPublicKeysFromFile(user, keyPath, passphrase string) (*ssh.PublicKeys, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newPublicKeys(user, key, passphrase)
|
||||
}
|
||||
|
||||
var signer cryptossh.Signer
|
||||
// newPublicKeys parses key, a PEM private key, as the SSH key of user.
|
||||
func newPublicKeys(user string, key []byte, passphrase string) (*ssh.PublicKeys, error) {
|
||||
var (
|
||||
signer cryptossh.Signer
|
||||
err error
|
||||
)
|
||||
if passphrase == "" {
|
||||
signer, err = cryptossh.ParsePrivateKey(key)
|
||||
} else {
|
||||
@@ -173,6 +187,41 @@ func (c *GitClient) Open() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// remoteAuth returns the authentication for a fetch or push from the
|
||||
// clone. It refuses when the clone's origin is not the configured
|
||||
// repository, so no credential goes to a repository the configuration no
|
||||
// longer names.
|
||||
func (c *GitClient) remoteAuth() (transport.AuthMethod, error) {
|
||||
if c.repo != nil {
|
||||
if err := c.checkOrigin(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return c.getAuth()
|
||||
}
|
||||
|
||||
// checkOrigin returns an error when the clone has an origin that is not the
|
||||
// configured repository.
|
||||
func (c *GitClient) checkOrigin() error {
|
||||
remote, err := c.repo.Remote("origin")
|
||||
if errors.Is(err, git.ErrRemoteNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read the clone's origin: %w", err)
|
||||
}
|
||||
// A fetch uses the first URL and a push the last, so each must be the
|
||||
// configured repository as a clone would spell it.
|
||||
for _, url := range remote.Config().URLs {
|
||||
if url != c.cfg.Repository && url != c.normalizeRepoURL() {
|
||||
// The URLs are left out, as either may carry credentials.
|
||||
return fmt.Errorf("the clone at %s uses another repository than the configured one; remove the clone to sync the configured repository",
|
||||
c.repoPath)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsCloned checks if the repository has been cloned.
|
||||
func (c *GitClient) IsCloned() bool {
|
||||
_, err := os.Stat(filepath.Join(c.repoPath, ".git"))
|
||||
@@ -185,7 +234,7 @@ func (c *GitClient) Fetch(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
auth, err := c.getAuth()
|
||||
auth, err := c.remoteAuth()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -214,7 +263,7 @@ func (c *GitClient) Pull(ctx context.Context) (*PullResult, error) {
|
||||
return nil, fmt.Errorf("failed to get worktree: %w", err)
|
||||
}
|
||||
|
||||
auth, err := c.getAuth()
|
||||
auth, err := c.remoteAuth()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -618,7 +667,7 @@ func (c *GitClient) Push(ctx context.Context) error {
|
||||
return ErrPushDisabled
|
||||
}
|
||||
|
||||
auth, err := c.getAuth()
|
||||
auth, err := c.remoteAuth()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ var errNoInventories = errors.New("inventory_path is set, but node inventories a
|
||||
// and replaces the inventories the file holds and deletes the others. It
|
||||
// reports whether it changed them. Without an inventory path it does nothing.
|
||||
func (s *serviceImpl) syncInventories(ctx context.Context) (bool, error) {
|
||||
if s.cfg.InventoryPath == "" {
|
||||
if s.cfg.InventoryPath == "" || s.inventoryExcluded() {
|
||||
return false, nil
|
||||
}
|
||||
if s.inventories == nil {
|
||||
@@ -132,3 +132,10 @@ func sameInventories(stored []inventory.Stored, want []inventory.Inventory) (boo
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// inventoryExcluded reports whether the inventory file lies under a path
|
||||
// the service leaves out, so another sync owns it. The caller holds mu and
|
||||
// the paths.
|
||||
func (s *serviceImpl) inventoryExcluded() bool {
|
||||
return s.isRepoPathExcluded(s.cfg.InventoryPath)
|
||||
}
|
||||
+172
-23
@@ -194,12 +194,88 @@ type serviceImpl struct {
|
||||
stateManager *StateManager
|
||||
gitClient *GitClient
|
||||
mu sync.Mutex
|
||||
stopCh chan struct{}
|
||||
running bool
|
||||
// loopMu guards stopCh and running apart from mu, so Stop does not
|
||||
// wait for an operation in flight to take them.
|
||||
loopMu sync.Mutex
|
||||
stopCh chan struct{}
|
||||
running bool
|
||||
|
||||
// loops runs the auto-sync loop, so Stop can wait for it to end.
|
||||
loops sync.WaitGroup
|
||||
|
||||
// inventories are the node inventories a pull keeps in step with the
|
||||
// inventory file, or nil.
|
||||
inventories InventoryStore
|
||||
|
||||
// excluded returns the paths the service leaves out, or is nil.
|
||||
excluded func(cfg *Config) ([]string, error)
|
||||
// excludedNow holds excluded's paths while an operation runs, so that
|
||||
// all of its passes leave out the same paths, and excludedErr the
|
||||
// error excluded returned. mu guards both.
|
||||
excludedNow []string
|
||||
excludedErr error
|
||||
}
|
||||
|
||||
// WithExcludedPaths makes the service leave out the paths that excluded
|
||||
// returns for the service's configuration: slash-separated paths relative
|
||||
// to the repository's root, matched without regard to case, "." for the
|
||||
// whole repository. A
|
||||
// pull writes and deletes nothing under them, and nothing is published,
|
||||
// deleted, or moved there; their items leave the sync state while their
|
||||
// local files stay. excluded is called once per operation. While it
|
||||
// returns an error, pulls and every write to the repository fail with it.
|
||||
func WithExcludedPaths(excluded func(cfg *Config) ([]string, error)) ServiceOption {
|
||||
return func(s *serviceImpl) {
|
||||
s.excluded = excluded
|
||||
}
|
||||
}
|
||||
|
||||
// isExcluded reports whether relPath, an item ID or a path relative to
|
||||
// Config.Path, lies under a path that the service leaves out. The caller
|
||||
// holds mu and the paths.
|
||||
func (s *serviceImpl) isExcluded(relPath string) bool {
|
||||
return s.isRepoPathExcluded(path.Join(cleanRepoPath(s.cfg.Path), relPath))
|
||||
}
|
||||
|
||||
// isRepoPathExcluded reports whether repoPath, a path relative to the
|
||||
// repository's root, lies under a path that the service leaves out. The
|
||||
// caller holds mu and the paths.
|
||||
func (s *serviceImpl) isRepoPathExcluded(repoPath string) bool {
|
||||
repoPath = strings.ToLower(cleanRepoPath(repoPath))
|
||||
for _, dir := range s.excludedNow {
|
||||
dir = strings.ToLower(dir)
|
||||
if dir == "." || repoPath == dir || strings.HasPrefix(repoPath, dir+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// checkWritable returns an error when the service may not write the file
|
||||
// at relPath, relative to Config.Path: it lies under an excluded path, or
|
||||
// the excluded paths are unknown. The caller holds mu and the paths.
|
||||
func (s *serviceImpl) checkWritable(relPath string) error {
|
||||
if s.excludedErr != nil {
|
||||
return s.excludedErr
|
||||
}
|
||||
if s.isExcluded(relPath) {
|
||||
return &InvalidDAGIDError{DAGID: relPath, Reason: "lies in a path this git sync leaves out"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// holdExcluded fixes the paths the service leaves out until the returned
|
||||
// func is called. The caller holds mu.
|
||||
func (s *serviceImpl) holdExcluded() (release func()) {
|
||||
if s.excluded == nil {
|
||||
return func() {}
|
||||
}
|
||||
s.excludedNow, s.excludedErr = s.excluded(s.cfg)
|
||||
if s.excludedErr != nil {
|
||||
s.excludedErr = fmt.Errorf("cannot tell which paths projects sync: %w", s.excludedErr)
|
||||
s.excludedNow = nil
|
||||
}
|
||||
return func() { s.excludedNow, s.excludedErr = nil, nil }
|
||||
}
|
||||
|
||||
// NewService creates a new Git sync service. Empty Wiki and calendar paths
|
||||
@@ -236,8 +312,14 @@ func (s *serviceImpl) Pull(ctx context.Context) (*SyncResult, error) {
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
result := &SyncResult{Timestamp: time.Now()}
|
||||
if err := s.excludedErr; err != nil {
|
||||
result.Message = "Failed to pull changes"
|
||||
result.Errors = append(result.Errors, SyncError{Message: err.Error()})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Ensure repo is cloned and opened
|
||||
if err := s.ensureRepoReady(ctx); err != nil {
|
||||
@@ -574,7 +656,7 @@ func (s *serviceImpl) repoFileItem(file TrackedFile) (repoSyncItem, bool) {
|
||||
prefix := strings.TrimSuffix(filepath.ToSlash(path.Clean(s.cfg.Path)), "/") + "/"
|
||||
relPath = strings.TrimPrefix(repoPath, prefix)
|
||||
}
|
||||
if relPath == "" || relPath == "." || s.isInventoryFile(repoPath) {
|
||||
if relPath == "" || relPath == "." || s.isInventoryFile(repoPath) || s.isExcluded(relPath) {
|
||||
return repoSyncItem{}, false
|
||||
}
|
||||
|
||||
@@ -817,6 +899,12 @@ func (s *serviceImpl) scanLocalItems(state *State) error {
|
||||
s.scanWikiPageFiles(state)
|
||||
s.scanCalendarFiles(state)
|
||||
|
||||
// Local files under an excluded path belong to another sync.
|
||||
for itemID, itemState := range state.Items {
|
||||
if itemState.Status == StatusUntracked && s.isExcluded(itemID+s.syncItemFileExtension(itemID, itemState)) {
|
||||
delete(state.Items, itemID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1056,6 +1144,14 @@ func (s *serviceImpl) reconcile(state *State) bool {
|
||||
var toDelete []string
|
||||
|
||||
for dagID, dagState := range state.Items {
|
||||
// The item's file name counts too: a project may sync a directory
|
||||
// named like it, such as ops.yaml/.
|
||||
if s.isExcluded(dagID + s.syncItemFileExtension(dagID, dagState)) {
|
||||
// Another sync owns the item now; its file stays as it is.
|
||||
toDelete = append(toDelete, dagID)
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
fileExtension := s.syncItemFileExtension(dagID, dagState)
|
||||
filePath, err := s.safeItemFilePath(dagID, dagState.Kind, fileExtension)
|
||||
if err != nil {
|
||||
@@ -1125,8 +1221,14 @@ func (s *serviceImpl) Publish(ctx context.Context, dagID, message string, force
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
result := &SyncResult{Timestamp: time.Now()}
|
||||
if err := s.excludedErr; err != nil {
|
||||
result.Message = "Failed to pull changes"
|
||||
result.Errors = append(result.Errors, SyncError{Message: err.Error()})
|
||||
return result, err
|
||||
}
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1223,8 +1325,14 @@ func (s *serviceImpl) PublishAll(ctx context.Context, message string, dagIDs []s
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
result := &SyncResult{Timestamp: time.Now()}
|
||||
if err := s.excludedErr; err != nil {
|
||||
result.Message = "Failed to pull changes"
|
||||
result.Errors = append(result.Errors, SyncError{Message: err.Error()})
|
||||
return result, err
|
||||
}
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1331,6 +1439,7 @@ func (s *serviceImpl) Discard(_ context.Context, dagID string) error {
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1342,6 +1451,10 @@ func (s *serviceImpl) Discard(_ context.Context, dagID string) error {
|
||||
return &DAGNotFoundError{DAGID: dagID}
|
||||
}
|
||||
|
||||
if err := s.checkWritable(dagID + s.syncItemFileExtension(dagID, dagState)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Open repo
|
||||
if err := s.gitClient.Open(); err != nil {
|
||||
return err
|
||||
@@ -1406,6 +1519,7 @@ func (s *serviceImpl) Forget(_ context.Context, itemIDs []string) ([]string, err
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1453,6 +1567,7 @@ func (s *serviceImpl) Cleanup(_ context.Context) ([]string, error) {
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1485,6 +1600,7 @@ func (s *serviceImpl) Delete(ctx context.Context, itemID, message string, force
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1587,6 +1703,7 @@ func (s *serviceImpl) DeleteBatch(ctx context.Context, itemIDs []string, message
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1747,6 +1864,7 @@ func (s *serviceImpl) DeleteAllMissing(ctx context.Context, message string) ([]s
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -1806,6 +1924,7 @@ func (s *serviceImpl) Move(ctx context.Context, oldID, newID, message string, fo
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -2000,6 +2119,7 @@ func (s *serviceImpl) GetStatus(_ context.Context) (*OverallStatus, error) {
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
status.Repository = s.cfg.Repository
|
||||
status.Branch = s.cfg.Branch
|
||||
@@ -2069,6 +2189,7 @@ func (s *serviceImpl) GetSyncItemStatus(_ context.Context, itemID string) (*Sync
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -2098,6 +2219,7 @@ func (s *serviceImpl) GetSyncItemDiff(_ context.Context, itemID string) (*SyncIt
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
defer s.holdExcluded()()
|
||||
|
||||
state, err := s.stateManager.GetState()
|
||||
if err != nil {
|
||||
@@ -2294,8 +2416,13 @@ func (s *serviceImpl) fetchRemoteContent(itemID string, kind SyncItemKind, fileE
|
||||
}
|
||||
|
||||
// GetConfig returns the current configuration.
|
||||
// It is a copy, so a caller that changes it changes nothing until
|
||||
// UpdateConfig.
|
||||
func (s *serviceImpl) GetConfig(_ context.Context) (*Config, error) {
|
||||
return s.cfg, nil
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
cfg := *s.cfg
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// UpdateConfig updates the configuration.
|
||||
@@ -2341,59 +2468,74 @@ func (s *serviceImpl) TestConnection(ctx context.Context) (*ConnectionResult, er
|
||||
|
||||
// Start starts the auto-sync background worker.
|
||||
func (s *serviceImpl) Start(ctx context.Context) error {
|
||||
if !s.cfg.Enabled {
|
||||
s.mu.Lock()
|
||||
cfg := s.cfg
|
||||
s.mu.Unlock()
|
||||
if !cfg.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.loopMu.Lock()
|
||||
if s.running {
|
||||
s.mu.Unlock()
|
||||
s.loopMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
s.running = true
|
||||
s.stopCh = make(chan struct{})
|
||||
s.mu.Unlock()
|
||||
stop := make(chan struct{})
|
||||
s.stopCh = stop
|
||||
s.loopMu.Unlock()
|
||||
|
||||
// Initial sync on startup
|
||||
if s.cfg.AutoSync.OnStartup {
|
||||
if cfg.AutoSync.OnStartup {
|
||||
_, _ = s.Pull(ctx)
|
||||
}
|
||||
|
||||
// Start periodic sync if interval > 0
|
||||
if s.cfg.AutoSync.Enabled && s.cfg.AutoSync.Interval > 0 {
|
||||
go s.runAutoSync(ctx)
|
||||
// Start periodic sync if interval > 0, unless Stop came during the
|
||||
// initial sync.
|
||||
if interval := cfg.AutoSync.Interval; cfg.AutoSync.Enabled && interval > 0 {
|
||||
s.loopMu.Lock()
|
||||
if s.stopCh == stop && s.running {
|
||||
s.loops.Go(func() { s.runAutoSync(ctx, stop, time.Duration(interval)*time.Second) })
|
||||
}
|
||||
s.loopMu.Unlock()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop stops the auto-sync background worker.
|
||||
// Stop stops the auto-sync background worker and waits until it has ended.
|
||||
func (s *serviceImpl) Stop() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.loopMu.Lock()
|
||||
if !s.running {
|
||||
s.loopMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
close(s.stopCh)
|
||||
s.running = false
|
||||
s.loopMu.Unlock()
|
||||
|
||||
s.loops.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
// runAutoSync runs the auto-sync loop.
|
||||
func (s *serviceImpl) runAutoSync(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Duration(s.cfg.AutoSync.Interval) * time.Second)
|
||||
func (s *serviceImpl) runAutoSync(ctx context.Context, stop <-chan struct{}, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-s.stopCh:
|
||||
case <-stop:
|
||||
return
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
// A tick that races Stop must not start a pull after it.
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
if _, err := s.Pull(ctx); err != nil {
|
||||
// We don't return error here to keep the loop running,
|
||||
// but the error is already updated in s.updateLastSyncError via s.Pull
|
||||
@@ -3153,6 +3295,12 @@ func (s *serviceImpl) safeItemRepoPath(itemID string, kind SyncItemKind, extensi
|
||||
if s.isInventoryFile(repoPath) {
|
||||
return "", &InvalidDAGIDError{DAGID: itemID, Reason: "is the git sync inventory file, which Dagu never writes"}
|
||||
}
|
||||
if s.excludedErr != nil {
|
||||
return "", s.excludedErr
|
||||
}
|
||||
if s.isRepoPathExcluded(repoPath) {
|
||||
return "", &InvalidDAGIDError{DAGID: itemID, Reason: "lies in a path this git sync leaves out"}
|
||||
}
|
||||
return repoPath, nil
|
||||
}
|
||||
|
||||
@@ -3520,8 +3668,9 @@ func (s *serviceImpl) selectRepoWikiDir() (string, error) {
|
||||
if s.cfg != nil && s.cfg.Path != "" {
|
||||
root = filepath.Join(root, s.cfg.Path)
|
||||
}
|
||||
wikiExists := pathExists(filepath.Join(root, wikiDir))
|
||||
docsExists := pathExists(filepath.Join(root, legacyDocsDir))
|
||||
// A directory that another sync owns is not this sync's wiki.
|
||||
wikiExists := pathExists(filepath.Join(root, wikiDir)) && !s.isExcluded(wikiDir)
|
||||
docsExists := pathExists(filepath.Join(root, legacyDocsDir)) && !s.isExcluded(legacyDocsDir)
|
||||
if wikiExists && docsExists {
|
||||
return "", fmt.Errorf("git sync repository contains both %q and legacy %q Wiki directories", wikiDir, legacyDocsDir)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ const (
|
||||
CollectionDAGRunLeases = "dag_run_leases"
|
||||
CollectionDAGSettings = "dag_settings"
|
||||
CollectionDAGState = "dag_state"
|
||||
CollectionGitSync = "git_sync"
|
||||
CollectionDispatchTasks = "dispatch_tasks"
|
||||
CollectionHostKeys = "host_keys"
|
||||
CollectionIncidents = "incidents"
|
||||
|
||||
@@ -142,6 +142,7 @@ func projectCollectionSpecs(p config.ProjectPaths) map[string]collectionSpec {
|
||||
persis.CollectionDAGPins: {dir: other("dag-pins"), indented: true},
|
||||
persis.CollectionDAGSettings: {dir: other("dag-settings"), indented: true},
|
||||
persis.CollectionDAGState: {dir: p.DAGStateDir},
|
||||
persis.CollectionGitSync: {dir: settings("git-sync"), indented: true},
|
||||
persis.CollectionHostKeys: {dir: settings("host-keys"), indented: true},
|
||||
persis.CollectionIncidents: {dir: settings(incidentsDirName), idPrefixes: incidentIDPrefixes, indented: true},
|
||||
persis.CollectionInventories: {dir: settings("inventories"), indented: true},
|
||||
|
||||
@@ -220,9 +220,15 @@ func (c *ProjectStoreCache) retryFailed(ctx context.Context, wait time.Duration)
|
||||
// made one at a time. The cache records a project marked deleting as
|
||||
// released only after fn returns, so fn returns once it has stopped using
|
||||
// the stores of the projects the registry drops or marks deleting.
|
||||
// OnChange must be called before Run.
|
||||
// Called while the cache runs, OnChange first calls fn with the content
|
||||
// the cache followed last, if any.
|
||||
func (c *ProjectStoreCache) OnChange(fn func([]project.Project)) {
|
||||
c.changeMu.Lock()
|
||||
defer c.changeMu.Unlock()
|
||||
c.onChange = append(c.onChange, fn)
|
||||
if c.projects != nil {
|
||||
fn(c.projects)
|
||||
}
|
||||
}
|
||||
|
||||
// Default returns the default project's stores.
|
||||
|
||||
@@ -84,6 +84,27 @@ func TestProjectStoreCacheFollowsRegistry(t *testing.T) {
|
||||
assert.Equal(t, []string{"weather", "weather"}, opened)
|
||||
}
|
||||
|
||||
// A subscriber added while the cache runs hears the content the cache
|
||||
// followed last at once, then each later change.
|
||||
func TestProjectStoreCacheLateSubscriber(t *testing.T) {
|
||||
registry := newFakeRegistry()
|
||||
cache := persisfile.NewProjectStoreCache(registry, &persisfile.ProjectStores{},
|
||||
func(context.Context, project.Project) (*persisfile.ProjectStores, error) {
|
||||
return &persisfile.ProjectStores{}, nil
|
||||
}, &releaseLog{})
|
||||
runCache(t, cache)
|
||||
registry.show(defaultProject, weatherProject)
|
||||
|
||||
var heard [][]project.Project
|
||||
cache.OnChange(func(projects []project.Project) { heard = append(heard, projects) })
|
||||
require.Len(t, heard, 1)
|
||||
assert.Equal(t, []project.Project{defaultProject, weatherProject}, heard[0])
|
||||
|
||||
registry.show(defaultProject)
|
||||
require.Len(t, heard, 2)
|
||||
assert.Equal(t, []project.Project{defaultProject}, heard[1])
|
||||
}
|
||||
|
||||
// Stores that fail to open stay closed until the registry changes again.
|
||||
func TestProjectStoreCacheRetriesFailedOpen(t *testing.T) {
|
||||
fail := true
|
||||
|
||||
@@ -471,6 +471,16 @@ func (s *ProjectSettings) WebhookStore(enc *crypto.Encryptor) (*store.WebhookSto
|
||||
)
|
||||
}
|
||||
|
||||
// GitSyncStore opens the project's git sync settings, whose credentials the
|
||||
// server's key encrypts.
|
||||
func (s *ProjectSettings) GitSyncStore() (*store.GitSyncStore, error) {
|
||||
enc, err := s.server.Encryptor()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return store.NewGitSyncStore(s.backend.Collection(persis.CollectionGitSync), enc), nil
|
||||
}
|
||||
|
||||
// DAGPinStore opens the project's pinned DAGs.
|
||||
func (s *ProjectSettings) DAGPinStore() (*store.DAGPinStore, error) {
|
||||
return store.NewDAGPinStore(s.backend.Collection(persis.CollectionDAGPins))
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// Copyright (C) 2026 Yota Hamada
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/crypto"
|
||||
"github.com/dagucloud/dagu/v2/internal/gitsync"
|
||||
"github.com/dagucloud/dagu/v2/internal/persis"
|
||||
)
|
||||
|
||||
const gitSyncRecordID = "config"
|
||||
|
||||
var (
|
||||
errGitSyncNoEncryptor = errors.New("git sync store: the server's encryption key is unavailable")
|
||||
errGitSyncURLCredentials = errors.New("git sync store: the repository URL carries credentials; set them as the token instead")
|
||||
)
|
||||
|
||||
// GitSyncStore keeps a project's git sync settings. Its token, SSH key, and
|
||||
// SSH key passphrase are stored encrypted with the server's key.
|
||||
type GitSyncStore struct {
|
||||
rec *SingleRecord[gitSyncRecord]
|
||||
enc *crypto.Encryptor
|
||||
}
|
||||
|
||||
// gitSyncRecord is the stored form of a gitsync.Config.
|
||||
type gitSyncRecord struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Repository string `json:"repository"`
|
||||
Branch string `json:"branch"`
|
||||
Path string `json:"path,omitempty"`
|
||||
PushEnabled bool `json:"pushEnabled,omitempty"`
|
||||
InventoryPath string `json:"inventoryPath,omitempty"`
|
||||
|
||||
AuthType string `json:"authType,omitempty"`
|
||||
TokenEnc string `json:"tokenEnc,omitempty"`
|
||||
SSHKeyEnc string `json:"sshKeyEnc,omitempty"`
|
||||
SSHPassphraseEnc string `json:"sshPassphraseEnc,omitempty"`
|
||||
|
||||
AutoSyncEnabled bool `json:"autoSyncEnabled,omitempty"`
|
||||
AutoSyncOnStartup bool `json:"autoSyncOnStartup,omitempty"`
|
||||
AutoSyncInterval int `json:"autoSyncInterval,omitempty"`
|
||||
|
||||
AuthorName string `json:"authorName,omitempty"`
|
||||
AuthorEmail string `json:"authorEmail,omitempty"`
|
||||
}
|
||||
|
||||
// NewGitSyncStore returns the git sync settings kept in col, whose
|
||||
// credentials enc encrypts. A nil enc refuses settings with credentials.
|
||||
func NewGitSyncStore(col persis.Collection, enc *crypto.Encryptor) *GitSyncStore {
|
||||
return &GitSyncStore{rec: NewSingleRecord[gitSyncRecord](col, gitSyncRecordID), enc: enc}
|
||||
}
|
||||
|
||||
// Get returns the stored settings, or nil when none are stored. When a
|
||||
// credential cannot be decrypted, it returns the settings without that
|
||||
// credential along with the error, so the repository and path stay known.
|
||||
func (s *GitSyncStore) Get(ctx context.Context) (*gitsync.Config, error) {
|
||||
var rec gitSyncRecord
|
||||
found, err := s.rec.Load(ctx, &rec)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("git sync store: load: %w", err)
|
||||
}
|
||||
if !found {
|
||||
return nil, nil
|
||||
}
|
||||
cfg := &gitsync.Config{
|
||||
Enabled: rec.Enabled,
|
||||
Repository: rec.Repository,
|
||||
Branch: rec.Branch,
|
||||
Path: rec.Path,
|
||||
PushEnabled: rec.PushEnabled,
|
||||
InventoryPath: rec.InventoryPath,
|
||||
Auth: gitsync.AuthConfig{Type: rec.AuthType},
|
||||
AutoSync: gitsync.AutoSyncConfig{
|
||||
Enabled: rec.AutoSyncEnabled,
|
||||
OnStartup: rec.AutoSyncOnStartup,
|
||||
Interval: rec.AutoSyncInterval,
|
||||
},
|
||||
Commit: gitsync.CommitConfig{AuthorName: rec.AuthorName, AuthorEmail: rec.AuthorEmail},
|
||||
}
|
||||
var errs []error
|
||||
for _, field := range []struct {
|
||||
enc string
|
||||
dst *string
|
||||
}{
|
||||
{rec.TokenEnc, &cfg.Auth.Token},
|
||||
{rec.SSHKeyEnc, &cfg.Auth.SSHKey},
|
||||
{rec.SSHPassphraseEnc, &cfg.Auth.SSHPassphrase},
|
||||
} {
|
||||
if *field.dst, err = s.decrypt(field.enc); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
return cfg, fmt.Errorf("git sync store: decrypt credentials: %w", errors.Join(errs...))
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Save replaces the stored settings with cfg. SSHKeyPath is not stored: a
|
||||
// project's SSH key is kept in the store, not read from the server's disk.
|
||||
// It refuses an HTTP or HTTPS repository URL that carries credentials,
|
||||
// which would be stored in plain text.
|
||||
func (s *GitSyncStore) Save(ctx context.Context, cfg *gitsync.Config) error {
|
||||
repo := cfg.Repository
|
||||
if !strings.Contains(repo, "://") && !strings.HasPrefix(repo, "git@") {
|
||||
// A clone takes a URL without a scheme as an HTTPS one.
|
||||
repo = "https://" + repo
|
||||
}
|
||||
u, parseErr := url.Parse(repo)
|
||||
isHTTP := strings.HasPrefix(strings.ToLower(repo), "http://") || strings.HasPrefix(strings.ToLower(repo), "https://")
|
||||
// Credentials need an @; a URL that does not parse, such as a local
|
||||
// Windows path taken as one, carries none without it.
|
||||
if isHTTP && ((parseErr == nil && u.User != nil) || (parseErr != nil && strings.Contains(repo, "@"))) {
|
||||
return errGitSyncURLCredentials
|
||||
}
|
||||
rec := gitSyncRecord{
|
||||
Enabled: cfg.Enabled,
|
||||
Repository: cfg.Repository,
|
||||
Branch: cfg.Branch,
|
||||
Path: cfg.Path,
|
||||
PushEnabled: cfg.PushEnabled,
|
||||
InventoryPath: cfg.InventoryPath,
|
||||
AuthType: cfg.Auth.Type,
|
||||
AutoSyncEnabled: cfg.AutoSync.Enabled,
|
||||
AutoSyncOnStartup: cfg.AutoSync.OnStartup,
|
||||
AutoSyncInterval: cfg.AutoSync.Interval,
|
||||
AuthorName: cfg.Commit.AuthorName,
|
||||
AuthorEmail: cfg.Commit.AuthorEmail,
|
||||
}
|
||||
var err error
|
||||
for _, field := range []struct {
|
||||
plain string
|
||||
dst *string
|
||||
}{
|
||||
{cfg.Auth.Token, &rec.TokenEnc},
|
||||
{cfg.Auth.SSHKey, &rec.SSHKeyEnc},
|
||||
{cfg.Auth.SSHPassphrase, &rec.SSHPassphraseEnc},
|
||||
} {
|
||||
if *field.dst, err = s.encrypt(field.plain); err != nil {
|
||||
return fmt.Errorf("git sync store: encrypt credentials: %w", err)
|
||||
}
|
||||
}
|
||||
if err := s.rec.Save(ctx, &rec); err != nil {
|
||||
return fmt.Errorf("git sync store: save: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GitSyncStore) encrypt(value string) (string, error) {
|
||||
if value == "" {
|
||||
return "", nil
|
||||
}
|
||||
if s.enc == nil {
|
||||
return "", errGitSyncNoEncryptor
|
||||
}
|
||||
return s.enc.Encrypt(value)
|
||||
}
|
||||
|
||||
func (s *GitSyncStore) decrypt(value string) (string, error) {
|
||||
if value == "" {
|
||||
return "", nil
|
||||
}
|
||||
if s.enc == nil {
|
||||
return "", errGitSyncNoEncryptor
|
||||
}
|
||||
return s.enc.Decrypt(value)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// Copyright (C) 2026 Yota Hamada
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/crypto"
|
||||
"github.com/dagucloud/dagu/v2/internal/gitsync"
|
||||
"github.com/dagucloud/dagu/v2/internal/persis/file"
|
||||
"github.com/dagucloud/dagu/v2/internal/persis/store"
|
||||
)
|
||||
|
||||
func TestGitSyncStore(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
s := store.NewGitSyncStore(file.NewCollection(dir), newTestEncryptor(t))
|
||||
|
||||
got, err := s.Get(t.Context())
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, got, "nothing stored yet")
|
||||
|
||||
want := &gitsync.Config{
|
||||
Enabled: true,
|
||||
Repository: "github.com/acme/dags",
|
||||
Branch: "main",
|
||||
Path: "teams/ops",
|
||||
PushEnabled: true,
|
||||
Auth: gitsync.AuthConfig{
|
||||
Type: gitsync.AuthTypeSSH,
|
||||
Token: "token-plain-value",
|
||||
SSHKey: "ssh-key-plain-value",
|
||||
SSHPassphrase: "passphrase-plain-value",
|
||||
},
|
||||
AutoSync: gitsync.AutoSyncConfig{Enabled: true, OnStartup: true, Interval: 300},
|
||||
Commit: gitsync.CommitConfig{AuthorName: "Ops", AuthorEmail: "ops@example.com"},
|
||||
}
|
||||
require.NoError(t, s.Save(t.Context(), want))
|
||||
|
||||
got, err = s.Get(t.Context())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
|
||||
// The credentials are never on disk in plain text.
|
||||
files, err := filepath.Glob(filepath.Join(dir, "*.json"))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, files)
|
||||
for _, f := range files {
|
||||
data, err := os.ReadFile(f)
|
||||
require.NoError(t, err)
|
||||
for _, secret := range []string{"token-plain-value", "ssh-key-plain-value", "passphrase-plain-value"} {
|
||||
assert.False(t, strings.Contains(string(data), secret), "%s holds %s", f, secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Settings whose credentials another key encrypted still name their
|
||||
// repository and path.
|
||||
func TestGitSyncStoreOtherKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
saved := &gitsync.Config{
|
||||
Enabled: true, Repository: "github.com/acme/dags", Branch: "main", Path: "ops",
|
||||
Auth: gitsync.AuthConfig{Type: gitsync.AuthTypeToken, Token: "secret"},
|
||||
}
|
||||
require.NoError(t, store.NewGitSyncStore(file.NewCollection(dir), newTestEncryptor(t)).Save(t.Context(), saved))
|
||||
|
||||
other, err := crypto.NewEncryptor("another-key")
|
||||
require.NoError(t, err)
|
||||
got, err := store.NewGitSyncStore(file.NewCollection(dir), other).Get(t.Context())
|
||||
require.Error(t, err)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "github.com/acme/dags", got.Repository)
|
||||
assert.Equal(t, "ops", got.Path)
|
||||
assert.Empty(t, got.Auth.Token)
|
||||
}
|
||||
|
||||
func TestGitSyncStoreWithoutKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := store.NewGitSyncStore(file.NewCollection(t.TempDir()), nil)
|
||||
err := s.Save(t.Context(), &gitsync.Config{Enabled: true, Auth: gitsync.AuthConfig{Type: gitsync.AuthTypeToken, Token: "t"}})
|
||||
require.Error(t, err)
|
||||
require.NoError(t, s.Save(t.Context(), &gitsync.Config{Enabled: true, Repository: "github.com/acme/dags"}))
|
||||
}
|
||||
|
||||
// A repository URL that carries credentials is refused, since the URL is
|
||||
// stored in plain text.
|
||||
func TestGitSyncStoreRefusesURLCredentials(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := store.NewGitSyncStore(file.NewCollection(t.TempDir()), newTestEncryptor(t))
|
||||
for _, repo := range []string{"https://user:secret@github.com/acme/dags.git", "https://token@github.com/acme/dags.git", "user:secret@github.com/acme/dags", "https://user:%zz@github.com/acme/dags", "x:dummy@github.com/acme/dags"} {
|
||||
require.Error(t, s.Save(t.Context(), &gitsync.Config{Enabled: true, Repository: repo}), repo)
|
||||
}
|
||||
require.NoError(t, s.Save(t.Context(), &gitsync.Config{Enabled: true, Repository: "git@github.com:acme/dags.git"}))
|
||||
require.NoError(t, s.Save(t.Context(), &gitsync.Config{Enabled: true, Repository: `C:\repos\dags`}), "a local path is no URL")
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
// Copyright (C) 2026 Yota Hamada
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/config"
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/logger"
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/logger/tag"
|
||||
"github.com/dagucloud/dagu/v2/internal/gitsync"
|
||||
persisfile "github.com/dagucloud/dagu/v2/internal/persis/file"
|
||||
"github.com/dagucloud/dagu/v2/internal/project"
|
||||
)
|
||||
|
||||
// projectSyncs runs the git sync of each project other than the default
|
||||
// one, and git_sync, while projects are on. It follows the store cache:
|
||||
//
|
||||
// project's stores open -> read its git sync settings; when enabled,
|
||||
// start its service in the background
|
||||
// project's stores go -> stop its service and wait for its pull,
|
||||
// (dropped, deleting) before the cache records the release
|
||||
//
|
||||
// git_sync leaves out what the projects sync, so it refuses to pull or
|
||||
// write, and does not start, while the settings of a project are unknown.
|
||||
type projectSyncs struct {
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
// stores is the cache whose changes projectSyncs follows.
|
||||
stores *persisfile.ProjectStoreCache
|
||||
// global is git_sync's service, or nil.
|
||||
global gitsync.Service
|
||||
|
||||
mu sync.Mutex
|
||||
// running holds the sync of each project whose stores are open, by
|
||||
// project ID, also when it has no git sync. mu guards it.
|
||||
running map[string]*projectSync
|
||||
// settings holds the git sync settings last read of each registered
|
||||
// project, by project ID, kept while its stores are not open or it is
|
||||
// marked deleting, so git_sync keeps leaving its path out. mu guards it.
|
||||
settings map[string]*gitsync.Config
|
||||
// known reports that settings have been read of every project not
|
||||
// marked deleting, and globalStarted that git_sync has started. mu
|
||||
// guards them.
|
||||
known bool
|
||||
globalStarted bool
|
||||
// stopped reports that stop was called, and retrying that a retry is
|
||||
// due. mu guards them. quit closes on stop.
|
||||
stopped bool
|
||||
retrying bool
|
||||
quit chan struct{}
|
||||
// synced closes once stop has ended every project's sync.
|
||||
synced chan struct{}
|
||||
// cancel ends ctx, which the syncs and retries run with, on stop.
|
||||
cancel context.CancelFunc
|
||||
// starts runs git_sync's start and the retries, and draining the
|
||||
// stops of the syncs heard drops.
|
||||
starts sync.WaitGroup
|
||||
draining sync.WaitGroup
|
||||
}
|
||||
|
||||
// projectSync is the git sync of one project.
|
||||
type projectSync struct {
|
||||
stores *persisfile.ProjectStores
|
||||
// svc is nil when the project has no enabled git sync.
|
||||
svc gitsync.Service
|
||||
cancel context.CancelFunc
|
||||
// start runs the service's start, whose first pull may take long.
|
||||
start sync.WaitGroup
|
||||
}
|
||||
|
||||
// newProjectSyncs returns the git syncs of the projects that stores
|
||||
// holds. follow starts them.
|
||||
func newProjectSyncs(ctx context.Context, cfg *config.Config, stores *persisfile.ProjectStoreCache) *projectSyncs {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &projectSyncs{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
cfg: cfg,
|
||||
stores: stores,
|
||||
running: make(map[string]*projectSync),
|
||||
settings: make(map[string]*gitsync.Config),
|
||||
quit: make(chan struct{}),
|
||||
synced: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// follow starts following the store cache. global is git_sync's service,
|
||||
// or nil, which it starts once the projects are known.
|
||||
func (p *projectSyncs) follow(global gitsync.Service) {
|
||||
p.global = global
|
||||
p.stores.OnChange(p.heard)
|
||||
}
|
||||
|
||||
// errSettingsUnknown reports that the git sync settings of a project have
|
||||
// not been read.
|
||||
var errSettingsUnknown = errors.New("the git sync settings of a project have not been read yet")
|
||||
|
||||
// excluded returns the paths that git_sync, with settings global, leaves
|
||||
// out.
|
||||
func (p *projectSyncs) excluded(global *gitsync.Config) ([]string, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if !p.known {
|
||||
return nil, errSettingsUnknown
|
||||
}
|
||||
projects := make([]*gitsync.Config, 0, len(p.settings))
|
||||
for _, settings := range p.settings {
|
||||
projects = append(projects, settings)
|
||||
}
|
||||
return gitsync.ExcludedPaths(p.cfg, global, projects), nil
|
||||
}
|
||||
|
||||
// heard follows projects, the registry's content. It returns once the
|
||||
// syncs of the projects whose stores the cache no longer holds have
|
||||
// stopped.
|
||||
func (p *projectSyncs) heard(projects []project.Project) {
|
||||
live := make(map[string]project.Project, len(projects))
|
||||
for _, proj := range projects {
|
||||
if !proj.Deleting && !strings.EqualFold(proj.Name, project.DefaultName) {
|
||||
live[proj.ID] = proj
|
||||
}
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
if p.stopped {
|
||||
p.mu.Unlock()
|
||||
// The release is recorded once heard returns, so it waits until
|
||||
// stop has ended every sync.
|
||||
<-p.synced
|
||||
return
|
||||
}
|
||||
var gone []*projectSync
|
||||
for id, running := range p.running {
|
||||
stores, ok := p.stores.Get(id)
|
||||
if _, wanted := live[id]; !wanted || !ok || stores != running.stores {
|
||||
gone = append(gone, running)
|
||||
delete(p.running, id)
|
||||
}
|
||||
}
|
||||
// stop waits for these too, so a shutdown during the release does not
|
||||
// end before their pulls do.
|
||||
p.draining.Add(len(gone))
|
||||
// A project marked deleting keeps its path out of git_sync until it
|
||||
// leaves the registry, so neither the delete nor a refused one lets
|
||||
// git_sync copy its files.
|
||||
registered := make(map[string]bool, len(projects))
|
||||
for _, proj := range projects {
|
||||
registered[proj.ID] = true
|
||||
}
|
||||
for id := range p.settings {
|
||||
if !registered[id] {
|
||||
delete(p.settings, id)
|
||||
}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
for _, running := range gone {
|
||||
running.stop()
|
||||
p.draining.Done()
|
||||
}
|
||||
|
||||
// The registry always lists the default project, so an empty list is
|
||||
// one the cache could not read. A project marked deleting whose
|
||||
// settings were never read, as after a restart, is unknown until it
|
||||
// leaves the registry or its delete is refused.
|
||||
unknown := len(projects) == 0
|
||||
retry := false
|
||||
p.mu.Lock()
|
||||
for _, proj := range projects {
|
||||
if _, read := p.settings[proj.ID]; proj.Deleting && !read {
|
||||
unknown = true
|
||||
}
|
||||
// git_sync waits while the settings of a project new to it load.
|
||||
if _, read := p.settings[proj.ID]; !read && !strings.EqualFold(proj.Name, project.DefaultName) {
|
||||
p.known = false
|
||||
}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
for id, proj := range live {
|
||||
stores, ok := p.stores.Get(id)
|
||||
if !ok {
|
||||
p.mu.Lock()
|
||||
_, read := p.settings[id]
|
||||
p.mu.Unlock()
|
||||
unknown = unknown || !read
|
||||
continue
|
||||
}
|
||||
p.mu.Lock()
|
||||
_, known := p.running[id]
|
||||
p.mu.Unlock()
|
||||
if known {
|
||||
continue
|
||||
}
|
||||
settings, err := p.read(stores)
|
||||
if err != nil {
|
||||
logger.Warn(p.ctx, "Failed to read the git sync settings of a project",
|
||||
slog.String("project", proj.Name), tag.Error(err))
|
||||
}
|
||||
p.mu.Lock()
|
||||
if p.stopped {
|
||||
p.mu.Unlock()
|
||||
<-p.synced
|
||||
return
|
||||
}
|
||||
if settings == nil && err != nil {
|
||||
// The settings are read again on the next retry; until then,
|
||||
// the ones read last still apply.
|
||||
_, read := p.settings[id]
|
||||
unknown = unknown || !read
|
||||
retry = true
|
||||
p.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
p.settings[id] = settings
|
||||
running := &projectSync{stores: stores, cancel: func() {}}
|
||||
p.running[id] = running
|
||||
// Settings whose credentials did not decrypt name the paths
|
||||
// git_sync leaves out, but do not run.
|
||||
if err == nil && settings != nil && settings.Enabled {
|
||||
p.startLocked(proj, running, settings)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
p.known = !unknown
|
||||
p.mu.Unlock()
|
||||
if unknown || retry {
|
||||
p.retryLater()
|
||||
}
|
||||
if unknown {
|
||||
return
|
||||
}
|
||||
p.startGlobal()
|
||||
}
|
||||
|
||||
// readRetry is the wait before the settings that could not be read, or
|
||||
// the stores that did not open, are tried again.
|
||||
const readRetry = 30 * time.Second
|
||||
|
||||
// retryLater follows the cache again after readRetry.
|
||||
func (p *projectSyncs) retryLater() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.stopped || p.retrying {
|
||||
return
|
||||
}
|
||||
p.retrying = true
|
||||
p.starts.Go(func() {
|
||||
select {
|
||||
case <-p.ctx.Done():
|
||||
case <-p.quit:
|
||||
case <-time.After(readRetry):
|
||||
p.mu.Lock()
|
||||
p.retrying = false
|
||||
p.mu.Unlock()
|
||||
if err := p.stores.Refresh(p.ctx); err != nil {
|
||||
logger.Warn(p.ctx, "Failed to read the project registry", tag.Error(err))
|
||||
p.retryLater()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// read returns the git sync settings of the project whose stores are
|
||||
// stores, or nil when it has none.
|
||||
func (p *projectSyncs) read(stores *persisfile.ProjectStores) (*gitsync.Config, error) {
|
||||
store, err := stores.GitSyncStore()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return store.Get(p.ctx)
|
||||
}
|
||||
|
||||
// startLocked starts the sync of proj in the background. The caller holds
|
||||
// mu.
|
||||
func (p *projectSyncs) startLocked(proj project.Project, running *projectSync, settings *gitsync.Config) {
|
||||
// A missing DAG directory, such as one on a volume not mounted, is
|
||||
// not made again by a pull.
|
||||
if _, err := os.Stat(running.stores.Paths.DAGsDir); err != nil {
|
||||
logger.Warn(p.ctx, "Not starting the git sync of a project whose DAG directory is missing",
|
||||
slog.String("project", proj.Name), tag.Error(err))
|
||||
return
|
||||
}
|
||||
var opts []gitsync.ServiceOption
|
||||
if inventories, err := running.stores.InventoryStore(); err == nil {
|
||||
opts = append(opts, gitsync.WithInventories(inventories))
|
||||
} else {
|
||||
logger.Warn(p.ctx, "Failed to open the node inventories of a project for git sync",
|
||||
slog.String("project", proj.Name), tag.Error(err))
|
||||
}
|
||||
// The clone and sync state live in the project's state directory, and
|
||||
// the files go to its DAG directory, whose wiki is its wiki/ folder.
|
||||
paths := running.stores.Paths
|
||||
running.svc = gitsync.NewService(settings, paths.DAGsDir, "", "", paths.StateDir, opts...)
|
||||
ctx, cancel := context.WithCancel(p.ctx)
|
||||
running.cancel = cancel
|
||||
svc := running.svc
|
||||
running.start.Go(func() {
|
||||
if err := svc.Start(ctx); err != nil {
|
||||
logger.Error(ctx, "Failed to start the git sync of a project",
|
||||
slog.String("project", proj.Name), tag.Error(err))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// startGlobal starts git_sync once.
|
||||
func (p *projectSyncs) startGlobal() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.global == nil || p.globalStarted || p.stopped {
|
||||
return
|
||||
}
|
||||
p.globalStarted = true
|
||||
p.starts.Go(func() {
|
||||
if err := p.global.Start(p.ctx); err != nil {
|
||||
logger.Error(p.ctx, "Failed to start git sync auto-sync", tag.Error(err))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// stop stops every sync, git_sync included, and waits until the projects'
|
||||
// syncs have stopped, and git_sync for at most stopWait.
|
||||
func (p *projectSyncs) stop() {
|
||||
// A pull in flight, git_sync's startup pull included, ends at once.
|
||||
p.cancel()
|
||||
p.mu.Lock()
|
||||
if p.stopped {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
close(p.quit)
|
||||
p.stopped = true
|
||||
running := make([]*projectSync, 0, len(p.running))
|
||||
for _, r := range p.running {
|
||||
running = append(running, r)
|
||||
}
|
||||
clear(p.running)
|
||||
p.mu.Unlock()
|
||||
// The projects' pulls are waited for in full: the server unregisters
|
||||
// only after stop returns, and a delete must not overlap their writes.
|
||||
for _, r := range running {
|
||||
r.stop()
|
||||
}
|
||||
p.draining.Wait()
|
||||
close(p.synced)
|
||||
|
||||
// git_sync's startup pull and loop, and a retry following the cache,
|
||||
// touch no project, so a pull stalled where it does not heed its
|
||||
// context, as in an SSH handshake, holds shutdown at most stopWait.
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
if p.global != nil {
|
||||
_ = p.global.Stop()
|
||||
}
|
||||
p.starts.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(stopWait):
|
||||
logger.Warn(p.ctx, "Git sync did not stop in time; stopping without it")
|
||||
}
|
||||
}
|
||||
|
||||
// stopWait bounds how long stop waits for git_sync.
|
||||
const stopWait = 10 * time.Second
|
||||
|
||||
// stop stops the sync and waits for its start and auto-sync loop to end.
|
||||
func (s *projectSync) stop() {
|
||||
s.cancel()
|
||||
s.start.Wait()
|
||||
if s.svc != nil {
|
||||
_ = s.svc.Stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Copyright (C) 2026 Yota Hamada
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package frontend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-git/go-git/v5"
|
||||
"github.com/go-git/go-git/v5/plumbing"
|
||||
"github.com/go-git/go-git/v5/plumbing/object"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/dagucloud/dagu/v2/internal/cmn/config"
|
||||
"github.com/dagucloud/dagu/v2/internal/gitsync"
|
||||
persisfile "github.com/dagucloud/dagu/v2/internal/persis/file"
|
||||
"github.com/dagucloud/dagu/v2/internal/persis/file/projectregistry"
|
||||
"github.com/dagucloud/dagu/v2/internal/project"
|
||||
)
|
||||
|
||||
// A project's git sync pulls its own path of the repository into its DAG
|
||||
// directory and keeps its clone in its state directory. git_sync, syncing
|
||||
// the whole repository, leaves out that path and paths.projects_dir. A
|
||||
// project marked deleting stops syncing before its release is recorded.
|
||||
func TestProjectSyncs(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
root := t.TempDir()
|
||||
|
||||
remote := filepath.Join(root, "remote")
|
||||
repo, err := git.PlainInit(remote, false)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.Storer.SetReference(plumbing.NewSymbolicReference(
|
||||
plumbing.HEAD, plumbing.NewBranchReferenceName("main"))))
|
||||
for _, file := range []string{"main.yaml", "ops/etl.yaml", "projects/ops/stray.yaml"} {
|
||||
full := filepath.Join(remote, filepath.FromSlash(file))
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
|
||||
require.NoError(t, os.WriteFile(full, []byte("steps: []\n"), 0o600))
|
||||
wt, err := repo.Worktree()
|
||||
require.NoError(t, err)
|
||||
_, err = wt.Add(file)
|
||||
require.NoError(t, err)
|
||||
_, err = wt.Commit("add "+file, &git.CommitOptions{
|
||||
Author: &object.Signature{Name: "Test", Email: "test@example.com", When: time.Now()},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
cfg := &config.Config{ProjectsEnabled: true}
|
||||
cfg.Paths.DataDir = filepath.Join(root, "data")
|
||||
cfg.Paths.DAGsDir = filepath.Join(root, "dags")
|
||||
cfg.Paths.ProjectsDir = filepath.Join(root, "dags", "projects")
|
||||
server := persisfile.NewServerStores(cfg)
|
||||
registry := projectregistry.New(cfg.Paths.DataDir)
|
||||
_, err = registry.EnsureDefault(ctx)
|
||||
require.NoError(t, err)
|
||||
ops, err := registry.Create(ctx, project.CreateInput{Name: "ops"})
|
||||
require.NoError(t, err)
|
||||
opsPaths, err := cfg.ProjectPaths("ops")
|
||||
require.NoError(t, err)
|
||||
// A create makes the DAG directory; a sync makes none.
|
||||
require.NoError(t, os.MkdirAll(opsPaths.DAGsDir, 0o750))
|
||||
|
||||
// The test's remote is a local path, which a clone does not take as a
|
||||
// URL, so each clone is made beforehand where the sync keeps it.
|
||||
for _, dir := range []string{cfg.Paths.DataDir, opsPaths.StateDir} {
|
||||
_, err := git.PlainCloneContext(ctx, filepath.Join(dir, "gitsync", "repo"), false, &git.CloneOptions{
|
||||
URL: remote,
|
||||
ReferenceName: plumbing.NewBranchReferenceName("main"),
|
||||
SingleBranch: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
settings, err := persisfile.NewProjectSettings(cfg, server, "ops")
|
||||
require.NoError(t, err)
|
||||
gitSyncStore, err := settings.GitSyncStore()
|
||||
require.NoError(t, err)
|
||||
onStartup := gitsync.AutoSyncConfig{Enabled: true, OnStartup: true, Interval: 3600}
|
||||
require.NoError(t, gitSyncStore.Save(ctx, &gitsync.Config{
|
||||
Enabled: true, Repository: remote, Branch: "main", Path: "ops", AutoSync: onStartup,
|
||||
}))
|
||||
|
||||
open := func(ctx context.Context, p project.Project) (*persisfile.ProjectStores, error) {
|
||||
return persisfile.NewProjectStores(ctx, cfg, server, p, persisfile.ProjectStoreOptions{})
|
||||
}
|
||||
defaults, err := open(ctx, project.Project{Name: project.DefaultName})
|
||||
require.NoError(t, err)
|
||||
cache := persisfile.NewProjectStoreCache(registry, defaults, open, server.ProjectReleases)
|
||||
cacheDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(cacheDone)
|
||||
cache.Run(ctx)
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
<-cacheDone
|
||||
})
|
||||
|
||||
globalCfg := &gitsync.Config{Enabled: true, Repository: remote, Branch: "main", AutoSync: onStartup}
|
||||
syncs := newProjectSyncs(ctx, cfg, cache)
|
||||
global := gitsync.NewService(globalCfg, cfg.Paths.DAGsDir, "", "", cfg.Paths.DataDir,
|
||||
gitsync.WithExcludedPaths(syncs.excluded))
|
||||
syncs.follow(global)
|
||||
t.Cleanup(func() {
|
||||
syncs.stop()
|
||||
_ = global.Stop()
|
||||
})
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
return fileExists(filepath.Join(opsPaths.DAGsDir, "etl.yaml")) &&
|
||||
fileExists(filepath.Join(cfg.Paths.DAGsDir, "main.yaml"))
|
||||
}, 10*time.Second, 20*time.Millisecond)
|
||||
assert.NoFileExists(t, filepath.Join(opsPaths.DAGsDir, "main.yaml"), "the project syncs only its path")
|
||||
assert.NoDirExists(t, filepath.Join(opsPaths.DAGsDir, ".git"))
|
||||
assert.DirExists(t, filepath.Join(opsPaths.StateDir, "gitsync", "repo", ".git"))
|
||||
assert.NoFileExists(t, filepath.Join(cfg.Paths.DAGsDir, "ops", "etl.yaml"), "git_sync leaves out what the project syncs")
|
||||
assert.NoFileExists(t, filepath.Join(opsPaths.DAGsDir, "stray.yaml"), "git_sync leaves out paths.projects_dir")
|
||||
|
||||
_, err = registry.SetDeleting(ctx, ops.ID, true)
|
||||
require.NoError(t, err)
|
||||
require.Eventually(t, func() bool {
|
||||
syncs.mu.Lock()
|
||||
defer syncs.mu.Unlock()
|
||||
_, running := syncs.running[ops.ID]
|
||||
return !running
|
||||
}, 10*time.Second, 20*time.Millisecond)
|
||||
excluded, err := syncs.excluded(globalCfg)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"projects", "ops"}, excluded, "a project marked deleting keeps its path out")
|
||||
|
||||
require.NoError(t, registry.Delete(ctx, ops.ID))
|
||||
require.Eventually(t, func() bool {
|
||||
excluded, err := syncs.excluded(globalCfg)
|
||||
return err == nil && len(excluded) == 1 && excluded[0] == "projects"
|
||||
}, 10*time.Second, 20*time.Millisecond, "once the project is gone, only paths.projects_dir stays left out")
|
||||
}
|
||||
|
||||
// git_sync refuses to work while the registry could not be read, or while
|
||||
// a project marked deleting has settings this process never read, as after
|
||||
// a restart during a delete.
|
||||
func TestProjectSyncsUnknownSettings(t *testing.T) {
|
||||
cfg := &config.Config{ProjectsEnabled: true}
|
||||
cache := persisfile.NewProjectStoreCache(projectregistry.New(t.TempDir()), &persisfile.ProjectStores{}, nil, nil)
|
||||
syncs := newProjectSyncs(context.Background(), cfg, cache)
|
||||
t.Cleanup(syncs.stop)
|
||||
global := &gitsync.Config{Enabled: true, Repository: "github.com/acme/dags"}
|
||||
|
||||
syncs.heard(nil)
|
||||
_, err := syncs.excluded(global)
|
||||
require.ErrorIs(t, err, errSettingsUnknown)
|
||||
|
||||
defaults := project.Project{ID: "id-default", Name: project.DefaultName}
|
||||
syncs.heard([]project.Project{defaults, {ID: "id-ops", Name: "ops", Deleting: true}})
|
||||
_, err = syncs.excluded(global)
|
||||
require.ErrorIs(t, err, errSettingsUnknown)
|
||||
|
||||
syncs.heard([]project.Project{defaults})
|
||||
_, err = syncs.excluded(global)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
@@ -178,6 +178,8 @@ type Server struct {
|
||||
notificationState chatbridge.StateStore
|
||||
newNotificationLease func() chatbridge.Lease
|
||||
syncService gitsync.Service
|
||||
// projectSyncs runs the projects' git syncs while projects are on.
|
||||
projectSyncs *projectSyncs
|
||||
listener net.Listener
|
||||
onReady func(url string)
|
||||
onStopped func()
|
||||
@@ -518,7 +520,13 @@ func NewServer(setup ServerConfig, opts ...ServerOption) (*Server, error) {
|
||||
auditStore = closer
|
||||
}
|
||||
eventSvc := stores.Event
|
||||
syncSvc := initSyncService(ctx, cfg, stores.Inventory)
|
||||
// While projects are on, git_sync leaves out what the projects sync,
|
||||
// and starts once the projects are known.
|
||||
var projectGitSyncs *projectSyncs
|
||||
if setup.ProjectStores != nil {
|
||||
projectGitSyncs = newProjectSyncs(ctx, cfg, setup.ProjectStores)
|
||||
}
|
||||
syncSvc := initSyncService(ctx, cfg, stores.Inventory, projectGitSyncs)
|
||||
if syncSvc != nil {
|
||||
apiOpts = append(apiOpts, apiv1.WithSyncService(syncSvc))
|
||||
}
|
||||
@@ -816,6 +824,7 @@ func NewServer(setup ServerConfig, opts ...ServerOption) (*Server, error) {
|
||||
notificationState: stores.NotificationState,
|
||||
newNotificationLease: stores.NewNotificationLease,
|
||||
syncService: syncSvc,
|
||||
projectSyncs: projectGitSyncs,
|
||||
metricsRegistry: mr,
|
||||
dagRepository: dr,
|
||||
dagRunRepository: dagRunRepository,
|
||||
@@ -1049,8 +1058,10 @@ func (s *setupChecker) IsSetupRequired(ctx context.Context) bool {
|
||||
}
|
||||
|
||||
// initSyncService creates and returns a Git sync service if enabled.
|
||||
// inventories are the default project's node inventories, or nil.
|
||||
func initSyncService(ctx context.Context, cfg *config.Config, inventories gitsync.InventoryStore) gitsync.Service {
|
||||
// inventories are the default project's node inventories, or nil. While
|
||||
// projects are on, projects is not nil: the service leaves out what they
|
||||
// sync, and they start it.
|
||||
func initSyncService(ctx context.Context, cfg *config.Config, inventories gitsync.InventoryStore, projects *projectSyncs) gitsync.Service {
|
||||
if !cfg.GitSync.Enabled {
|
||||
return nil
|
||||
}
|
||||
@@ -1060,9 +1071,12 @@ func initSyncService(ctx context.Context, cfg *config.Config, inventories gitsyn
|
||||
if inventories != nil {
|
||||
opts = append(opts, gitsync.WithInventories(inventories))
|
||||
}
|
||||
if projects != nil {
|
||||
opts = append(opts, gitsync.WithExcludedPaths(projects.excluded))
|
||||
}
|
||||
svc := gitsync.NewService(syncCfg, cfg.Paths.DAGsDir, cfg.Paths.WikiDir, cfg.Paths.CalendarsDir, cfg.Paths.DataDir, opts...)
|
||||
|
||||
if syncCfg.AutoSync.Enabled {
|
||||
if syncCfg.AutoSync.Enabled && projects == nil {
|
||||
if err := svc.Start(ctx); err != nil {
|
||||
logger.Error(ctx, "Failed to start git sync auto-sync", tag.Error(err))
|
||||
} else {
|
||||
@@ -1284,6 +1298,16 @@ func (srv *Server) Serve(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
if srv.projectSyncs != nil {
|
||||
// The syncs start once the server listens, so a server that fails
|
||||
// to start leaves no pull running after it unregisters.
|
||||
var global gitsync.Service
|
||||
if srv.syncService != nil && srv.config.GitSync.AutoSync.Enabled {
|
||||
global = srv.syncService
|
||||
}
|
||||
srv.projectSyncs.follow(global)
|
||||
}
|
||||
|
||||
webURL := localURL(srv.listener.Addr(), srv.config.Server.TLS != nil, srv.funcsConfig.BasePath)
|
||||
metrics.StartUptime(ctx)
|
||||
logger.Info(ctx, "Server is starting", tag.Addr(srv.listener.Addr().String()), tag.URL(webURL))
|
||||
@@ -2107,8 +2131,13 @@ func newShutdownPhaseContext(parent context.Context, budget time.Duration) (cont
|
||||
func (srv *Server) shutdownActions(ctx context.Context) shutdownActions {
|
||||
actions := shutdownActions{}
|
||||
|
||||
if srv.syncService != nil {
|
||||
if srv.syncService != nil || srv.projectSyncs != nil {
|
||||
actions.stopSync = func() error {
|
||||
// The projects' syncs start and stop git_sync.
|
||||
if srv.projectSyncs != nil {
|
||||
srv.projectSyncs.stop()
|
||||
return nil
|
||||
}
|
||||
if err := srv.syncService.Stop(); err != nil {
|
||||
logger.Warn(ctx, "Failed to stop git sync service", tag.Error(err))
|
||||
return err
|
||||
|
||||
@@ -976,6 +976,10 @@ Rules:
|
||||
`<projects_dir>` lies inside `<dags_dir>`, `git_sync` leaves
|
||||
`<projects_dir>` out.
|
||||
- A project's auto sync fetches its repository once per interval.
|
||||
- The server runs each project's git sync. It stops a project's git sync
|
||||
before it releases the project for a delete. A project's own git sync
|
||||
does not refuse its delete: its clone is in the state directory, which
|
||||
the delete removes.
|
||||
|
||||
### User Interface
|
||||
|
||||
|
||||
Reference in new issue
Block a user