Skip to content
Open
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
54 changes: 38 additions & 16 deletions pkg/devspace/dependency/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ func init() {
// downloadMutex makes sure we only download a single dependency at a time
var downloadMutex = sync.Mutex{}

// fetchedSources holds the ids of git and url sources this process has already
// cloned, pulled or downloaded. A single command loads the config more than once
// and resolves the same source for every import, nested import and dependency that
// references it, so without this every one of those would contact the remote again.
// Guarded by downloadMutex.
var fetchedSources = map[string]bool{}

// ResetFetchedSources makes the next DownloadDependency call for every source
// contact its remote again.
func ResetFetchedSources() {
downloadMutex.Lock()
defer downloadMutex.Unlock()

fetchedSources = map[string]bool{}
}

func GetDependencyPath(workingDirectory string, source *latest.SourceConfig) (configPath string, err error) {
ID, err := GetDependencyID(source)
if err != nil {
Expand Down Expand Up @@ -144,15 +160,16 @@ func DownloadDependency(ctx context.Context, workingDirectory string, source *la
log.Debugf("Cloned %s", gitPath)
}

// Git pull
if !source.DisablePull && source.Revision == "" {
// Git pull, at most once per source in this process
if !source.DisablePull && source.Revision == "" && !(fetchedSources[ID] && statErr == nil) {
err = repo.Pull(ctx)
if err != nil {
log.Warn(err)
}

log.Debugf("Pulled %s", gitPath)
}
fetchedSources[ID] = true

// Resolve local source
} else if source.Path != "" {
Expand All @@ -164,41 +181,46 @@ func DownloadDependency(ctx context.Context, workingDirectory string, source *la
configPath := filepath.Join(localPath, constants.DefaultConfigPath)
_, statErr := os.Stat(configPath)

if !source.DisablePull || statErr != nil {
// Create the file
out, err := os.Create(configPath)
if statErr != nil || (!source.DisablePull && !fetchedSources[ID]) {
// Get the data
resp, err := http.Get(source.Path)
if err != nil {
if statErr == nil {
log.Warnf("Error creating file: %v", err)
log.Warnf("Error retrieving url %s: %v", source.Path, err)
return getDependencyConfigPath(localPath, source)
}

return "", err
return "", errors.Wrapf(err, "request %s", source.Path)
}
defer out.Close()
defer resp.Body.Close()

// Get the data
resp, err := http.Get(source.Path)
// Download completely before touching the cached file, so a failed
// download never replaces a good cached copy
var body []byte
if resp.StatusCode < 200 || resp.StatusCode > 299 {
err = fmt.Errorf("unexpected status %s", resp.Status)
} else {
body, err = io.ReadAll(resp.Body)
}
if err != nil {
if statErr == nil {
log.Warnf("Error retrieving url %s: %v", source.Path, err)
return getDependencyConfigPath(localPath, source)
}

return "", errors.Wrapf(err, "request %s", source.Path)
return "", errors.Wrapf(err, "download %s", source.Path)
}
defer resp.Body.Close()

// Write the body to file
_, err = io.Copy(out, resp.Body)
err = os.WriteFile(configPath, body, 0666)
if err != nil {
if statErr == nil {
log.Warnf("Error retrieving url %s: %v", source.Path, err)
log.Warnf("Error creating file: %v", err)
return getDependencyConfigPath(localPath, source)
}

return "", errors.Wrapf(err, "download %s", source.Path)
return "", err
}
fetchedSources[ID] = true
}
} else {
if filepath.IsAbs(source.Path) {
Expand Down
181 changes: 181 additions & 0 deletions pkg/devspace/dependency/util/util_fetch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
package util

import (
"context"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"testing"

"github.com/loft-sh/devspace/pkg/devspace/config/versions/latest"
"github.com/loft-sh/devspace/pkg/util/log"
"gotest.tools/assert"
)

func gitCommit(t *testing.T, dir, content string) {
t.Helper()
assert.NilError(t, os.WriteFile(filepath.Join(dir, "devspace.yaml"), []byte(content), 0644))
for _, args := range [][]string{
{"add", "."},
{"-c", "user.name=test", "-c", "user.email=test@example.com", "commit", "-q", "-m", content},
} {
out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()
assert.NilError(t, err, string(out))
}
}

// fileURL builds a file URL that is valid for both unix paths and windows drive paths.
func fileURL(dir string) string {
p := filepath.ToSlash(dir)
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
return "file://" + p
}

// useTempDependencyFolder points the dependency cache at a fresh folder and starts
// with no source marked as fetched.
func useTempDependencyFolder(t *testing.T) {
t.Helper()
oldFolder := DependencyFolderPath
DependencyFolderPath = filepath.Join(t.TempDir(), "dependencies")
ResetFetchedSources()
t.Cleanup(func() {
DependencyFolderPath = oldFolder
ResetFetchedSources()
})
}

func newOrigin(t *testing.T, content string) string {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git is not installed")
}
origin := filepath.Join(t.TempDir(), "origin")
assert.NilError(t, os.MkdirAll(origin, 0755))
out, err := exec.Command("git", "-C", origin, "init", "-q", "-b", "main").CombinedOutput()
assert.NilError(t, err, string(out))
gitCommit(t, origin, content)
return origin
}

func readSource(t *testing.T, source *latest.SourceConfig) string {
t.Helper()
configPath, err := DownloadDependency(context.Background(), "", source, log.Discard)
assert.NilError(t, err)
if info, statErr := os.Stat(configPath); statErr == nil && info.IsDir() {
configPath = filepath.Join(configPath, "devspace.yaml")
}
content, err := os.ReadFile(configPath)
assert.NilError(t, err)
return string(content)
}

func TestDownloadDependencyPullsOncePerProcess(t *testing.T) {
useTempDependencyFolder(t)
origin := newOrigin(t, "version: first\n")

source := &latest.SourceConfig{Git: fileURL(origin), Branch: "main"}
assert.Equal(t, readSource(t, source), "version: first\n")

// a new commit is not fetched again within the same process
gitCommit(t, origin, "version: second\n")
assert.Equal(t, readSource(t, source), "version: first\n")

// after a reset the source is pulled again
ResetFetchedSources()
assert.Equal(t, readSource(t, source), "version: second\n")
}

func TestDownloadDependencyDisablePullNeverPulls(t *testing.T) {
useTempDependencyFolder(t)
origin := newOrigin(t, "version: first\n")

source := &latest.SourceConfig{Git: fileURL(origin), Branch: "main", DisablePull: true}
assert.Equal(t, readSource(t, source), "version: first\n")

gitCommit(t, origin, "version: second\n")
ResetFetchedSources()
assert.Equal(t, readSource(t, source), "version: first\n")
}

func TestDownloadDependencyFailedPullIsNotRetried(t *testing.T) {
useTempDependencyFolder(t)
origin := newOrigin(t, "version: first\n")

source := &latest.SourceConfig{Git: fileURL(origin), Branch: "main"}
assert.Equal(t, readSource(t, source), "version: first\n")

// the failed pull falls back to the cached copy and is logged, not retried
moved := origin + "-moved"
assert.NilError(t, os.Rename(origin, moved))
assert.Equal(t, readSource(t, source), "version: first\n")

assert.NilError(t, os.Rename(moved, origin))
gitCommit(t, origin, "version: second\n")
assert.Equal(t, readSource(t, source), "version: first\n")
}

func TestDownloadDependencyURLDownloadsOncePerProcess(t *testing.T) {
useTempDependencyFolder(t)

var requests int32
body := "version: first\n"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&requests, 1)
_, _ = w.Write([]byte(body))
}))
defer server.Close()

source := &latest.SourceConfig{Path: server.URL + "/devspace.yaml"}
assert.Equal(t, readSource(t, source), "version: first\n")

body = "version: second\n"
assert.Equal(t, readSource(t, source), "version: first\n")
assert.Equal(t, atomic.LoadInt32(&requests), int32(1))

ResetFetchedSources()
assert.Equal(t, readSource(t, source), "version: second\n")
assert.Equal(t, atomic.LoadInt32(&requests), int32(2))
}

func TestDownloadDependencyURLErrorKeepsCacheAndRetries(t *testing.T) {
useTempDependencyFolder(t)

var fail atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if fail.Load() {
http.Error(w, "boom", http.StatusInternalServerError)
return
}
_, _ = w.Write([]byte("version: good\n"))
}))
defer server.Close()

source := &latest.SourceConfig{Path: server.URL + "/devspace.yaml"}
assert.Equal(t, readSource(t, source), "version: good\n")

// a failed download leaves the cached file intact and the source unfetched
fail.Store(true)
ResetFetchedSources()
assert.Equal(t, readSource(t, source), "version: good\n")

fail.Store(false)
assert.Equal(t, readSource(t, source), "version: good\n")
}

func TestDownloadDependencyURLErrorWithoutCacheFails(t *testing.T) {
useTempDependencyFolder(t)

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "boom", http.StatusInternalServerError)
}))
defer server.Close()

_, err := DownloadDependency(context.Background(), "", &latest.SourceConfig{Path: server.URL + "/devspace.yaml"}, log.Discard)
assert.ErrorContains(t, err, "500")
}