-
Notifications
You must be signed in to change notification settings - Fork 2
/
template_get.go
85 lines (71 loc) · 1.49 KB
/
template_get.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
package vm
import (
"crypto/sha512"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
)
// TemplateGet downloads and prepares a disk template for use as a backing disk
// image. If quiet is true, no progress is printed to stdout.
func TemplateGet(name, arch string, quiet bool) error {
index, err := newIndex()
if err != nil {
return err
}
var template template
for _, t := range index.Templates {
if t.ININame == name && t.Arch == arch {
template = t
break
}
}
URL, err := url.Parse(baseURL)
if err != nil {
return err
}
URL.Path += template.File
filePath, err := download(URL.String(), quiet)
if err != nil {
return err
}
checksum, ok := template.Checksum["sha512"]
if !ok {
checksum = template.Checksum[""]
}
if err := verify(filePath, checksum); err != nil {
return err
}
destFilePath := strings.TrimSuffix(filePath, ".xz")
destFilePath += "." + template.Format + ".xz"
err = os.Rename(filePath, destFilePath)
if err != nil {
return err
}
if _, err := inspect(destFilePath, quiet); err != nil {
return err
}
return nil
}
func verify(filePath, checksum string) error {
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return err
}
hash := sha512.New()
_, err = hash.Write(data)
if err != nil {
return err
}
computed := fmt.Sprintf("%x", hash.Sum(nil))
if checksum != computed {
return fmt.Errorf("invalid checksum: %v != %v", checksum, computed)
}
return nil
}