-
Notifications
You must be signed in to change notification settings - Fork 0
/
boot-images.go
104 lines (83 loc) · 2.17 KB
/
boot-images.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
95
96
97
98
99
100
101
102
103
104
package api
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/Masterminds/semver"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/pkg/errors"
"github.com/spf13/afero"
)
type BootImage struct {
SubPath string
URL string
Size int64
}
func (b BootImage) GetName() string {
// try to find a semver version somewhere in the path...
for _, p := range strings.Split(b.URL, "/") {
version, err := semver.NewVersion(strings.TrimPrefix(p, "v"))
if err == nil {
return version.String()
}
}
return b.URL
}
func (b BootImage) GetSubPath() string {
return b.SubPath
}
func (b BootImage) GetSize() int64 {
return b.Size
}
func (b BootImage) HasMD5() bool {
return true
}
func (b BootImage) DownloadMD5(ctx context.Context, target *afero.File, c *http.Client, s3downloader *s3manager.Downloader) (string, error) {
md5URL := b.URL + ".md5"
req, err := http.NewRequest(http.MethodGet, md5URL, nil)
if err != nil {
return "", errors.Wrap(err, "unable to create get request")
}
req = req.WithContext(ctx)
resp, err := c.Do(req)
if err != nil {
return "", errors.Wrap(err, "boot image md5 download error")
}
defer resp.Body.Close()
if target != nil {
_, err = io.Copy(*target, resp.Body)
if err != nil {
return "", errors.Wrap(err, "boot image md5 download error")
}
return "", nil
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "boot image md5 download error")
}
parts := strings.Split(string(body), " ")
if len(parts) == 0 {
return "", fmt.Errorf("md5 sum file has unexpected format")
}
return parts[0], nil
}
func (b BootImage) Download(ctx context.Context, target afero.File, c *http.Client, s3downloader *s3manager.Downloader) (int64, error) {
req, err := http.NewRequest(http.MethodGet, b.URL, nil)
if err != nil {
return 0, errors.Wrap(err, "unable to create get request")
}
req = req.WithContext(ctx)
resp, err := c.Do(req)
if err != nil {
return 0, errors.Wrap(err, "boot image download error")
}
defer resp.Body.Close()
n, err := io.Copy(target, resp.Body)
if err != nil {
return 0, errors.Wrap(err, "boot image download error")
}
return n, nil
}