Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/exec_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func updateHermitChannel(l *ui.UI, state *state.State, ref manifest.Reference, f
state.ReadPackageState(pkg)
switch {
case force || debug.Flags.AlwaysCheckSelf:
pkg.UpdatedAt = time.Time{}
return errors.WithStack(state.UpgradeChannel(l.Task(ref.String()), pkg))
case pkg.UpdatedAt.IsZero():
// Record a new installation as just checked to prevent an immediate upgrade check.
pkg.UpdatedAt = time.Now()
Expand Down
10 changes: 0 additions & 10 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,6 @@ func (c *Cache) IsCached(checksum string, uri redact.URL) bool {
return err == nil
}

// Evict a file from the cache.
func (c *Cache) Evict(b *ui.Task, checksum string, uri redact.URL) error {
b.SubTask("remove").Debugf("rm -rf %s", c.Path(checksum, uri))
err := os.RemoveAll(c.Path(checksum, uri))
if err != nil && !os.IsNotExist(err) {
return errors.WithStack(err)
}
return nil
}

// Clean the cache.
func (c *Cache) Clean() error {
return os.RemoveAll(c.root)
Expand Down
53 changes: 48 additions & 5 deletions cache/git.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cache

import (
"io/fs"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -39,27 +40,69 @@ func (s *gitSource) Download(b *ui.Task, cache *Cache, checksum string) (string,
}
pinned = advertised == ""
}
// Other processes treat an existing checkout as cached and copy it without
// waiting for this download, so clone into a temporary directory and move
// the complete checkout into place.
if err := os.MkdirAll(filepath.Dir(checkoutDir), 0700); err != nil {
return "", "", "", errors.WithStack(err)
}
tmpDir, err := os.MkdirTemp(filepath.Dir(checkoutDir), filepath.Base(checkoutDir)+".*.hermit.tmp.download")
if err != nil {
return "", "", "", errors.WithStack(err)
}
defer os.RemoveAll(tmpDir)
if pinned {
err = s.checkoutGitCommit(b, cache.root, repo, tag, checkoutDir)
err = s.checkoutGitCommit(b, cache.root, repo, tag, tmpDir)
} else {
args := redact.Args(util.GitArgs("clone", "--depth=1")...)
if tag != "" {
args = append(args, redact.Plain("--branch="+tag))
}
args = append(args, redact.Plain("--"), repo, redact.Plain(checkoutDir))
args = append(args, redact.Plain("--"), repo, redact.Plain(tmpDir))
err = s.runner.RunInDir(b, cache.root, args...)
}
if err != nil {
return "", "", "", errors.WithStack(err)
}

bts, err := s.runner.CaptureInDir(b, checkoutDir, redact.Args("git", "rev-parse", "HEAD")...)
etag, err := s.checkoutHead(b, tmpDir)
if err != nil {
return "", "", "", errors.WithStack(err)
}
etag := strings.Trim(string(bts), "\n")
if err := s.installCheckout(b, tmpDir, checkoutDir, etag); err != nil {
return "", "", "", errors.WithStack(err)
}
return checkoutDir, etag, "", nil
}

return filepath.Join(cache.root, base), etag, "", nil
func (s *gitSource) checkoutHead(b *ui.Task, dir string) (string, error) {
bts, err := s.runner.CaptureInDir(b, dir, redact.Args("git", "rev-parse", "HEAD")...)
if err != nil {
return "", errors.WithStack(err)
}
return strings.TrimSpace(string(bts)), nil
}

// installCheckout moves the checkout of commit etag in tmpDir to dest.
//
// A checkout of the same commit already at dest came from a concurrent
// download, and other processes may be copying from it, so it is kept. A
// checkout of another commit is an older channel version, which is replaced.
func (s *gitSource) installCheckout(b *ui.Task, tmpDir, dest, etag string) error {
err := os.Rename(tmpDir, dest)
if !errors.Is(err, fs.ErrExist) {
return errors.WithStack(err)
}
if existing, err := s.checkoutHead(b, dest); err == nil && existing == etag {
return nil
}
// Move the old checkout aside so that dest is missing only between two renames.
old := tmpDir + ".old"
if err := os.Rename(dest, old); err != nil {
return errors.WithStack(err)
}
defer os.RemoveAll(old)
return errors.WithStack(os.Rename(tmpDir, dest))
}

func (s *gitSource) ETag(b *ui.Task) (etag string, err error) {
Expand Down
50 changes: 50 additions & 0 deletions cache/source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,56 @@ func TestGitSourceUsesCredentialsButRedactsDisplay(t *testing.T) {
assert.NotContains(t, buf.String(), "sekret")
}

// headRunner reports head for checkoutDir and newHead for any other directory.
type headRunner struct {
checkoutDir string
head, newHead string
}

func (h *headRunner) RunInDir(_ *ui.Task, _ string, _ ...redact.Value) error { return nil }

func (h *headRunner) CaptureInDir(_ ui.Logger, dir string, _ ...redact.Value) ([]byte, error) {
if dir == h.checkoutDir {
return []byte(h.head + "\n"), nil
}
return []byte(h.newHead + "\n"), nil
}

// Git downloads clone into a temporary directory, because concurrent processes
// copy any checkout they find in the cache.
func TestGitSourceDownloadInstallsCompleteCheckout(t *testing.T) {
tests := []struct {
name string
head string
wantMarker bool
}{
{name: "KeepsConcurrentCheckoutOfSameCommit", head: "new", wantMarker: true},
{name: "ReplacesOlderCheckout", head: "old", wantMarker: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
cache := &Cache{root: t.TempDir()}
url := redact.URL("https://example.com/repo.git#channel")
checkoutDir := cache.Path("", url)
assert.NoError(t, os.MkdirAll(checkoutDir, 0700))
marker := filepath.Join(checkoutDir, "marker")
assert.NoError(t, os.WriteFile(marker, nil, 0600))
src := &gitSource{URL: url, runner: &headRunner{checkoutDir: checkoutDir, head: test.head, newHead: "new"}}

u, _ := ui.NewForTesting()
path, etag, _, err := src.Download(u.Task("test"), cache, "")
assert.NoError(t, err)

assert.Equal(t, [2]string{checkoutDir, "new"}, [2]string{path, etag})
_, err = os.Stat(marker)
assert.Equal(t, test.wantMarker, err == nil, "existing checkout kept")
entries, err := os.ReadDir(filepath.Dir(checkoutDir))
assert.NoError(t, err)
assert.Equal(t, 1, len(entries), "temporary checkouts left behind")
})
}
}

func TestHTTPSourceDoesNotLeakURLCredentials(t *testing.T) {
u, buf := ui.NewForTesting()
task := u.Task("test")
Expand Down
12 changes: 9 additions & 3 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ func TestEnsureUpToDate(t *testing.T) {
WithUpdateInterval(1 * time.Hour).
WithSource(fixture.Server.URL).
Result()
// The last check time is the modification time of the package's metadata.
ageLastCheck := func() {
path := filepath.Join(fixture.State.Root(), "metadata", pkg.Reference.String()+".etag")
lastCheck := time.Now().Add(-2 * time.Hour)
assert.NoError(t, os.Chtimes(path, lastCheck, lastCheck))
}

// Initial install
_, err := fixture.Env.Install(fixture.P, pkg)
Expand All @@ -120,7 +126,7 @@ func TestEnsureUpToDate(t *testing.T) {
assert.Equal(t, data, string(file))

// Update after a check is needed but etag has not changed
pkg.UpdatedAt = time.Now().Add(-2 * time.Hour)
ageLastCheck()
err = fixture.Env.EnsureChannelIsUpToDate(fixture.P, pkg)
assert.NoError(t, err)
assert.Equal(t, 1, getCalls)
Expand All @@ -129,7 +135,7 @@ func TestEnsureUpToDate(t *testing.T) {
assert.Equal(t, data, string(file))

// Update after a check is needed and the etag has changed
pkg.UpdatedAt = time.Now().Add(-2 * time.Hour)
ageLastCheck()
etag = "changed"
data = strings.Repeat("other", 1024)
err = fixture.Env.EnsureChannelIsUpToDate(fixture.P, pkg)
Expand All @@ -146,7 +152,7 @@ func TestEnsureUpToDate(t *testing.T) {

// Check etag retained when the connection fails
fail = true
pkg.UpdatedAt = time.Now().Add(-2 * time.Hour)
ageLastCheck()
err = fixture.Env.EnsureChannelIsUpToDate(fixture.P, pkg)
assert.NoError(t, err)
dbPkg, err = dao.GetPackage(pkg.Reference.String())
Expand Down
69 changes: 69 additions & 0 deletions integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1542,6 +1542,75 @@ EOF
touch -t 200001010000 "$HERMIT_STATE_DIR/metadata/fresh@edge.etag"
hermit activate . > /dev/null
assert test "$(cat observed.txt)" = second
`,
},
{
// Concurrent first uses used to replace the manifest checkout while
// other processes read it, failing with "unknown package", and to
// reinstall channel packages while others were installing them.
name: "ConcurrentFirstUsesFromGitSource",
script: `
hermit init --no-git .
git_commit() {
git -C "$1" -c user.name='Hermit Test' -c user.email=hermit@example.com \
-c commit.gpgsign=false commit -qm "$2"
}

mkdir -p packages upstream.git manifests.git
printf '#!/bin/sh\necho pinned\n' > packages/pinned
chmod +x packages/pinned
tar -czf packages/pinned.tgz -C packages pinned
git -C upstream.git init -q
printf '#!/bin/sh\necho channel\n' > upstream.git/channel
chmod +x upstream.git/channel
git -C upstream.git add channel
git_commit upstream.git first
git -C upstream.git branch -M channel

git -C manifests.git init -q
cat > manifests.git/pinned.hcl <<'EOF'
description = "Pinned package"
source = "${env}/packages/pinned.tgz"
binaries = ["pinned"]
version "1.0.0" {}
EOF
cat > manifests.git/channel.hcl <<'EOF'
description = "Channel package"
binaries = ["channel"]
channel "edge" {
update = "1h"
source = "file://${env}/upstream.git#channel"
}
EOF
git -C manifests.git add .
git_commit manifests.git manifests
printf 'sources = ["file://%s/manifests.git"]\n' "$PWD" > bin/hermit.hcl
ln -s hermit bin/.pinned-1.0.0.pkg
ln -s .pinned-1.0.0.pkg bin/pinned
ln -s hermit bin/.channel@edge.pkg
ln -s .channel@edge.pkg bin/channel

state_root="$HERMIT_STATE_DIR"
for round in 1 2 3 4 5; do
# Each round starts from an empty state directory.
export HERMIT_STATE_DIR="$state_root/round-$round"
for i in 1 2 3 4 5 6 7 8; do
for tool in pinned channel; do
(./bin/$tool > "out-$round-$tool-$i" 2>&1; echo $? > "rc-$round-$tool-$i") &
done
done
wait
for i in 1 2 3 4 5 6 7 8; do
for tool in pinned channel; do
if [ "$(cat "rc-$round-$tool-$i")" != 0 ] || [ "$(cat "out-$round-$tool-$i")" != "$tool" ]; then
hermit-send "error: round $round: $tool failed: $(cat "out-$round-$tool-$i")"
exit 1
fi
done
done
# A first use records the installed channel version instead of reinstalling it.
assert test -s "$HERMIT_STATE_DIR/metadata/channel@edge.etag"
done
`,
},
{
Expand Down
72 changes: 51 additions & 21 deletions sources/git.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sources

import (
"context"
"io/fs"
"os"
"path/filepath"
Expand All @@ -10,8 +11,14 @@ import (
"github.com/cashapp/hermit/redact"
"github.com/cashapp/hermit/ui"
"github.com/cashapp/hermit/util"
"github.com/cashapp/hermit/util/flock"
)

// syncLockTimeout is how long a sync waits for another process to finish
// cloning or pulling the same source. It is longer than the state lock timeout
// because a first clone of a large manifest repository can be slow.
const syncLockTimeout = 5 * time.Minute

// GitSource is a new Source based on a git repo
type GitSource struct {
fs *uriFS
Expand Down Expand Up @@ -40,26 +47,44 @@ func NewGitSource(uri redact.URL, sourceDir string, runner util.CommandRunner) *
func (s *GitSource) Sync(p *ui.UI, force bool) (bool, error) {
info, _ := os.Stat(s.path)
task := p.Task(s.fs.uri)
if info == nil || force || time.Since(info.ModTime()) >= SyncFrequency {
err := s.ensureSourcesDirExists()
if err != nil {
return false, errors.WithStack(err)
}
if info != nil && !force && time.Since(info.ModTime()) < SyncFrequency {
task.Debugf("Update skipped, updated within the last %s", SyncFrequency)
return false, nil
}
if err := s.ensureSourcesDirExists(); err != nil {
return false, errors.WithStack(err)
}

err = syncGit(task, s.sourceDir, s.remote, s.path, s.runner)
// If the sync failed while the repo had already been cloned, log a warning
// If the repo has not yet been cloned, fail.
if err != nil {
if info != nil {
task.Warnf("git sync failed: %s", err)
return false, nil
}
return false, errors.Wrap(err, "git sync failed")
}
// Hermit processes share the checkout. Unserialised syncs clone or pull it
// concurrently, and a failed pull or a clone replaces the checkout that other
// processes are reading manifests from.
waitStart := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), syncLockTimeout)
release, err := flock.Acquire(ctx, s.path+".lock", "syncing "+s.fs.uri)
cancel()
if err != nil {
return false, errors.Wrap(err, "failed to acquire the source sync lock")
}
defer release() //nolint:errcheck

// A sync that finished while we waited is as fresh as one we would run now.
info, _ = os.Stat(s.path)
if info != nil && info.ModTime().After(waitStart) {
task.Debugf("Update skipped, synced by another process")
return true, nil
}
task.Debugf("Update skipped, updated within the last %s", SyncFrequency)
return false, nil

err = syncGit(task, s.sourceDir, s.remote, s.path, s.runner)
// If the sync failed while the repo had already been cloned, log a warning
// If the repo has not yet been cloned, fail.
if err != nil {
if info != nil {
task.Warnf("git sync failed: %s", err)
return false, nil
}
return false, errors.Wrap(err, "git sync failed")
}
return true, nil
}

func (s *GitSource) URI() string {
Expand Down Expand Up @@ -106,11 +131,16 @@ func syncGit(b *ui.Task, dir string, source redact.URL, finalDest string, runner
if err = runner.RunInDir(b, dest, cloneArgs...); err != nil {
return errors.WithStack(err)
}
_ = os.RemoveAll(finalDest)
// And finally, rename it into place.
if err = os.Rename(dest, finalDest); err != nil && !os.IsExist(err) { // Prevent races.
// Other processes read manifests without the sync lock, so move the old
// checkout aside rather than deleting it in place. This shrinks the window in
// which no checkout exists from a recursive delete to a single rename.
old := dest + ".old"
if err = os.Rename(finalDest, old); err != nil && !os.IsNotExist(err) {
return errors.WithStack(err)
}
defer os.RemoveAll(old)
if err = os.Rename(dest, finalDest); err != nil {
return errors.WithStack(err)
}

return nil
}
Loading
Loading