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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
// +build amd64,linux arm64,linux amd64,darwin arm64,darwin
package machine
import (
"fmt"
"io"
"io/ioutil"
"net/http"
url2 "net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/containers/image/v5/pkg/compression"
"github.com/docker/docker/pkg/archive"
"github.com/sirupsen/logrus"
"github.com/vbauerster/mpb/v6"
"github.com/vbauerster/mpb/v6/decor"
)
// GenericDownload is used when a user provides a URL
// or path for an image
type GenericDownload struct {
Download
}
// NewGenericDownloader is used when the disk image is provided by the user
func NewGenericDownloader(vmType, vmName, pullPath string) (DistributionDownload, error) {
var (
imageName string
)
dataDir, err := GetDataDir(vmType)
if err != nil {
return nil, err
}
dl := Download{}
// Is pullpath a file or url?
getURL, err := url2.Parse(pullPath)
if err != nil {
return nil, err
}
if len(getURL.Scheme) > 0 {
urlSplit := strings.Split(pullPath, "/")
imageName = urlSplit[len(urlSplit)-1]
dl.LocalUncompressedFile = filepath.Join(dataDir, imageName)
dl.URL = getURL
dl.LocalPath = filepath.Join(dataDir, imageName)
} else {
// Dealing with FilePath
imageName = filepath.Base(pullPath)
dl.LocalUncompressedFile = filepath.Join(dataDir, imageName)
dl.LocalPath = pullPath
}
dl.VMName = vmName
dl.ImageName = imageName
// The download needs to be pulled into the datadir
gd := GenericDownload{Download: dl}
gd.LocalUncompressedFile = gd.getLocalUncompressedName()
return gd, nil
}
func (g GenericDownload) getLocalUncompressedName() string {
var (
extension string
)
switch {
case strings.HasSuffix(g.LocalPath, ".bz2"):
extension = ".bz2"
case strings.HasSuffix(g.LocalPath, ".gz"):
extension = ".gz"
case strings.HasSuffix(g.LocalPath, ".xz"):
extension = ".xz"
}
uncompressedFilename := filepath.Join(filepath.Dir(g.LocalUncompressedFile), g.VMName+"_"+g.ImageName)
return strings.TrimSuffix(uncompressedFilename, extension)
}
func (g GenericDownload) DownloadImage() error {
// If we have a URL for this "downloader", we now pull it
if g.URL != nil {
if err := DownloadVMImage(g.URL, g.LocalPath); err != nil {
return err
}
}
return Decompress(g.LocalPath, g.getLocalUncompressedName())
}
func (g GenericDownload) Get() *Download {
return &g.Download
}
// DownloadVMImage downloads a VM image from url to given path
// with download status
func DownloadVMImage(downloadURL fmt.Stringer, localImagePath string) error {
out, err := os.Create(localImagePath)
if err != nil {
return err
}
defer func() {
if err := out.Close(); err != nil {
logrus.Error(err)
}
}()
resp, err := http.Get(downloadURL.String())
if err != nil {
return err
}
defer func() {
if err := resp.Body.Close(); err != nil {
logrus.Error(err)
}
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("error downloading VM image %s: %s", downloadURL, resp.Status)
}
size := resp.ContentLength
urlSplit := strings.Split(downloadURL.String(), "/")
prefix := "Downloading VM image: " + urlSplit[len(urlSplit)-1]
onComplete := prefix + ": done"
p := mpb.New(
mpb.WithWidth(60),
mpb.WithRefreshRate(180*time.Millisecond),
)
bar := p.AddBar(size,
mpb.BarFillerClearOnComplete(),
mpb.PrependDecorators(
decor.OnComplete(decor.Name(prefix), onComplete),
),
mpb.AppendDecorators(
decor.OnComplete(decor.CountersKibiByte("%.1f / %.1f"), ""),
),
)
proxyReader := bar.ProxyReader(resp.Body)
defer func() {
if err := proxyReader.Close(); err != nil {
logrus.Error(err)
}
}()
if _, err := io.Copy(out, proxyReader); err != nil {
return err
}
p.Wait()
return nil
}
func Decompress(localPath, uncompressedPath string) error {
uncompressedFileWriter, err := os.OpenFile(uncompressedPath, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
sourceFile, err := ioutil.ReadFile(localPath)
if err != nil {
return err
}
compressionType := archive.DetectCompression(sourceFile)
if compressionType != archive.Uncompressed {
fmt.Println("Extracting compressed file")
}
if compressionType == archive.Xz {
return decompressXZ(localPath, uncompressedFileWriter)
}
return decompressEverythingElse(localPath, uncompressedFileWriter)
}
// Will error out if file without .xz already exists
// Maybe extracting then renameing is a good idea here..
// depends on xz: not pre-installed on mac, so it becomes a brew dependency
func decompressXZ(src string, output io.Writer) error {
cmd := exec.Command("xzcat", "-k", src)
//cmd := exec.Command("xz", "-d", "-k", "-v", src)
stdOut, err := cmd.StdoutPipe()
if err != nil {
return err
}
//cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
go func() {
if _, err := io.Copy(output, stdOut); err != nil {
logrus.Error(err)
}
}()
return cmd.Run()
}
func decompressEverythingElse(src string, output io.Writer) error {
f, err := os.Open(src)
if err != nil {
return err
}
uncompressStream, _, err := compression.AutoDecompress(f)
if err != nil {
return err
}
defer func() {
if err := uncompressStream.Close(); err != nil {
logrus.Error(err)
}
}()
_, err = io.Copy(output, uncompressStream)
return err
}
|