github.com/ranjib/nomad@v0.1.1-0.20160225204057-97751b02f70b/client/getter/getter.go (about)

     1  package getter
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/url"
     7  	"path"
     8  	"path/filepath"
     9  	"runtime"
    10  	"strings"
    11  	"sync"
    12  	"syscall"
    13  
    14  	gg "github.com/hashicorp/go-getter"
    15  )
    16  
    17  var (
    18  	// getters is the map of getters suitable for Nomad. It is initialized once
    19  	// and the lock is used to guard access to it.
    20  	getters map[string]gg.Getter
    21  	lock    sync.Mutex
    22  
    23  	// supported is the set of download schemes supported by Nomad
    24  	supported = []string{"http", "https", "s3"}
    25  )
    26  
    27  // getClient returns a client that is suitable for Nomad.
    28  func getClient(src, dst string) *gg.Client {
    29  	lock.Lock()
    30  	defer lock.Unlock()
    31  
    32  	// Return the pre-initialized client
    33  	if getters == nil {
    34  		getters = make(map[string]gg.Getter, len(supported))
    35  		for _, getter := range supported {
    36  			if impl, ok := gg.Getters[getter]; ok {
    37  				getters[getter] = impl
    38  			}
    39  		}
    40  	}
    41  
    42  	return &gg.Client{
    43  		Src:     src,
    44  		Dst:     dst,
    45  		Dir:     false, // Only support a single file for now.
    46  		Getters: getters,
    47  	}
    48  }
    49  
    50  func GetArtifact(destDir, source, checksum string, logger *log.Logger) (string, error) {
    51  	if source == "" {
    52  		return "", fmt.Errorf("Source url is empty in Artifact Getter")
    53  	}
    54  	u, err := url.Parse(source)
    55  	if err != nil {
    56  		return "", err
    57  	}
    58  
    59  	// if checksum is seperate, apply to source
    60  	if checksum != "" {
    61  		source = strings.Join([]string{source, fmt.Sprintf("checksum=%s", checksum)}, "?")
    62  		logger.Printf("[DEBUG] client.getter: Applying checksum to Artifact Source URL, new url: %s", source)
    63  	}
    64  
    65  	artifactFile := filepath.Join(destDir, path.Base(u.Path))
    66  	if err := getClient(source, artifactFile).Get(); err != nil {
    67  		return "", fmt.Errorf("Error downloading artifact: %s", err)
    68  	}
    69  
    70  	// Add execution permissions to the newly downloaded artifact
    71  	if runtime.GOOS != "windows" {
    72  		if err := syscall.Chmod(artifactFile, 0755); err != nil {
    73  			logger.Printf("[ERR] driver.raw_exec: Error making artifact executable: %s", err)
    74  		}
    75  	}
    76  	return artifactFile, nil
    77  }