open-nomad/client/getter/getter.go

78 lines
1.8 KiB
Go
Raw Normal View History

package getter
import (
2015-11-03 21:16:17 +00:00
"fmt"
"log"
"net/url"
2016-03-18 22:33:01 +00:00
"path/filepath"
2016-02-18 02:48:13 +00:00
"sync"
2015-11-03 21:16:17 +00:00
gg "github.com/hashicorp/go-getter"
2016-03-15 02:55:30 +00:00
"github.com/hashicorp/nomad/nomad/structs"
)
2016-02-18 02:48:13 +00:00
var (
// getters is the map of getters suitable for Nomad. It is initialized once
// and the lock is used to guard access to it.
getters map[string]gg.Getter
lock sync.Mutex
2016-02-23 18:33:58 +00:00
// supported is the set of download schemes supported by Nomad
supported = []string{"http", "https", "s3"}
2016-02-18 02:48:13 +00:00
)
2016-03-15 02:55:30 +00:00
// getClient returns a client that is suitable for Nomad downloading artifacts.
2016-02-18 02:48:13 +00:00
func getClient(src, dst string) *gg.Client {
lock.Lock()
defer lock.Unlock()
// Return the pre-initialized client
if getters == nil {
2016-02-23 18:33:58 +00:00
getters = make(map[string]gg.Getter, len(supported))
for _, getter := range supported {
if impl, ok := gg.Getters[getter]; ok {
getters[getter] = impl
}
2016-02-18 02:48:13 +00:00
}
}
return &gg.Client{
Src: src,
Dst: dst,
2016-03-15 02:55:30 +00:00
Mode: gg.ClientModeAny,
2016-02-18 02:48:13 +00:00
Getters: getters,
}
}
2016-03-15 02:55:30 +00:00
// getGetterUrl returns the go-getter URL to download the artifact.
func getGetterUrl(artifact *structs.TaskArtifact) (string, error) {
u, err := url.Parse(artifact.GetterSource)
2015-11-03 21:16:17 +00:00
if err != nil {
2016-03-15 02:55:30 +00:00
return "", fmt.Errorf("failed to parse source URL %q: %v", artifact.GetterSource, err)
2015-11-03 21:16:17 +00:00
}
2016-03-15 02:55:30 +00:00
// Build the url
q := u.Query()
for k, v := range artifact.GetterOptions {
q.Add(k, v)
2015-11-03 21:16:17 +00:00
}
2016-03-15 02:55:30 +00:00
u.RawQuery = q.Encode()
return u.String(), nil
}
2016-03-18 22:33:01 +00:00
// GetArtifact downloads an artifact into the specified task directory.
func GetArtifact(artifact *structs.TaskArtifact, taskDir string, logger *log.Logger) error {
2016-03-15 02:55:30 +00:00
url, err := getGetterUrl(artifact)
if err != nil {
return err
2015-11-03 21:16:17 +00:00
}
2016-03-15 02:55:30 +00:00
// Download the artifact
2016-03-18 22:33:01 +00:00
dest := filepath.Join(taskDir, artifact.RelativeDest)
if err := getClient(url, dest).Get(); err != nil {
return fmt.Errorf("GET error: %v", err)
2015-11-03 21:16:17 +00:00
}
2016-03-15 02:55:30 +00:00
return nil
}