-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.go
94 lines (83 loc) · 2.07 KB
/
fetch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"net/url"
"os"
"path/filepath"
"github.com/coreos/rocket/app-container/discovery"
"github.com/coreos/rocket/cas"
)
const (
imgDir = "images"
)
var (
cmdFetch = &Command{
Name: "fetch",
Summary: "Fetch image(s) and store them in the local cache",
Usage: "IMAGE_URL...",
Run: runFetch,
}
)
func fetchURL(img string, ds *cas.Store) (string, error) {
rem := cas.NewRemote(img, []string{})
err := ds.ReadIndex(rem)
if err != nil && rem.Blob == "" {
rem, err = rem.Download(*ds)
if err != nil {
return "", fmt.Errorf("downloading: %v\n", err)
}
}
return rem.Blob, nil
}
// fetchImage will take an image as either a URL or a name string and import it
// into the store if found.
func fetchImage(img string, ds *cas.Store) (string, error) {
// discover if it isn't a URL
u, err := url.Parse(img)
if err == nil && u.Scheme == "" {
app, err := discovery.NewAppFromString(img)
if globalFlags.Debug && err != nil {
fmt.Printf("discovery: %s\n", err)
}
if err == nil {
ep, err := discovery.DiscoverEndpoints(*app, true)
if err != nil {
return "", err
}
// TODO(philips): use all available mirrors
if globalFlags.Debug {
fmt.Printf("fetch: trying %v\n", ep.ACI)
}
img = ep.ACI[0]
u, err = url.Parse(img)
}
}
if err != nil { // download if it isn't a URL
return "", fmt.Errorf("%s: not a valid URL or hash", img)
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", fmt.Errorf("%s: rkt only supports http or https URLs", img)
}
return fetchURL(img, ds)
}
func runFetch(args []string) (exit int) {
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "fetch: Must provide at least one image\n")
return 1
}
root := filepath.Join(globalFlags.Dir, imgDir)
if err := os.MkdirAll(root, 0755); err != nil {
fmt.Fprintf(os.Stderr, "fetch: error creating image directory: %v", err)
return 1
}
ds := cas.NewStore(globalFlags.Dir)
for _, img := range args {
hash, err := fetchImage(img, ds)
if err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
return 1
}
fmt.Println(hash)
}
return
}