-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
348 lines (295 loc) · 7.1 KB
/
util.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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package vm
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/dustin/go-humanize"
"github.com/ulikunitz/xz"
)
func getDataDir() (string, error) {
dir, err := os.UserHomeDir()
if err != nil {
return "", err
}
dir = filepath.Join(dir, ".local", "share", "vm")
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
return "", err
}
}
return dir, nil
}
func getImagesDir() (string, error) {
dir, err := getDataDir()
if err != nil {
return "", err
}
dir = filepath.Join(dir, "images")
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
return "", err
}
}
return dir, nil
}
func getInstancesDir() (string, error) {
dir, err := getDataDir()
if err != nil {
return "", err
}
dir = filepath.Join(dir, "instances")
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
return "", err
}
}
return dir, nil
}
// inspect begins a state-machine of sorts that will convert the file at filePath
// to a qcow2 image. If quiet is true, no progress is printed to stdout.
func inspect(filePath string, quiet bool) (string, error) {
switch filepath.Ext(filePath) {
case ".gz", ".xz":
return decompress(filePath, quiet)
case ".raw", ".img", ".vdi":
return convert(filePath, quiet)
case ".tar":
return unarchive(filePath, quiet)
case ".box":
newFilePath := strings.TrimSuffix(filePath, ".box") + ".tar.gz"
if err := os.Rename(filePath, newFilePath); err != nil {
return "", err
}
return inspect(newFilePath, quiet)
case ".qcow2":
return filePath, nil
}
return "", fmt.Errorf("unsupported file type: %v", filePath)
}
// transfer copies filePath into the images directory and returns the path to the
// new image. If quiet is true, no progress is printed to stdout.
func transfer(filePath string, quiet bool) (string, error) {
var err error
imagesDir, err := getImagesDir()
if err != nil {
return "", err
}
r, err := os.Open(filePath)
if err != nil {
return "", err
}
defer r.Close()
destFilePath := filepath.Join(imagesDir, filepath.Base(filePath))
w, err := os.Create(destFilePath + ".tmp")
if err != nil {
return "", err
}
defer w.Close()
var bytesWritten uint64
err = copyBytes(w, r, func(buf []byte) {
if !quiet {
bytesWritten += uint64(len(buf))
fmt.Printf("\r%s", strings.Repeat(" ", 40))
fmt.Printf("\rcopying... %s", humanize.Bytes(bytesWritten))
}
})
if !quiet {
fmt.Println()
}
if err != nil {
return "", err
}
err = os.Rename(destFilePath+".tmp", destFilePath)
if err != nil {
return "", err
}
return destFilePath, nil
}
// download streams the body of rawurl into a file in the images directory and
// returns a path to the new image. If quiet is true, no progress is printed to
// stdout.
func download(rawurl string, quiet bool) (string, error) {
URL, err := url.Parse(rawurl)
if err != nil {
return "", err
}
resp, err := http.Get(URL.String())
if err != nil {
return "", err
}
defer resp.Body.Close()
imagesDir, err := getImagesDir()
if err != nil {
return "", err
}
destFilePath := filepath.Join(imagesDir, filepath.Base(URL.Path))
w, err := os.Create(destFilePath + ".tmp")
if err != nil {
return "", err
}
defer w.Close()
var bytesWritten uint64
err = copyBytes(w, resp.Body, func(buf []byte) {
if !quiet {
bytesWritten += uint64(len(buf))
fmt.Printf("\r%s", strings.Repeat(" ", 40))
fmt.Printf("\rdownloading... %s", humanize.Bytes(bytesWritten))
}
})
if !quiet {
fmt.Println()
}
if err != nil {
return "", err
}
err = os.Rename(destFilePath+".tmp", destFilePath)
if err != nil {
return "", err
}
return destFilePath, nil
}
// decompress inspects the file extension of filePath and decompresses the file
// at filePath. Only gz and xz compression formats are supported. If quiet is
// true, no progress is printed to stdout.
func decompress(filePath string, quiet bool) (string, error) {
var err error
r, err := os.Open(filePath)
if err != nil {
return "", err
}
defer r.Close()
var g io.Reader
switch filepath.Ext(filePath) {
case ".gz":
g, err = gzip.NewReader(r)
case ".xz":
g, err = xz.NewReader(r)
}
if err != nil {
return "", err
}
destFilePath := strings.TrimSuffix(filePath, filepath.Ext(filePath))
w, err := os.Create(destFilePath + ".tmp")
if err != nil {
return "", err
}
defer w.Close()
var bytesWritten uint64
err = copyBytes(w, g, func(buf []byte) {
if !quiet {
bytesWritten += uint64(len(buf))
fmt.Printf("\r%s", strings.Repeat(" ", 40))
fmt.Printf("\rdecompressing... %s", humanize.Bytes(bytesWritten))
}
})
if !quiet {
fmt.Println()
}
if err != nil {
return "", err
}
if err := os.Rename(destFilePath+".tmp", destFilePath); err != nil {
return "", err
}
if err := os.Remove(filePath); err != nil {
return "", err
}
return inspect(destFilePath, quiet)
}
// convert calls qemu-img to convert the image at filePath to a qcow2 image. If
// quiet is true, no progress is printed to stdout.
func convert(filePath string, quiet bool) (string, error) {
var err error
destFilePath := strings.TrimSuffix(filePath, filepath.Ext(filePath)) + ".qcow2"
var format string
switch filepath.Ext(filePath) {
case ".vdi":
format = "vdi"
default:
format = "raw"
}
cmd := exec.Command("qemu-img", "convert",
"-f", format,
"-O", "qcow2",
filePath, destFilePath)
err = cmd.Run()
if err != nil {
return "", err
}
if err := os.Remove(filePath); err != nil {
return "", err
}
return inspect(destFilePath, quiet)
}
// unarchive extracts a file named "box.img" from the tar archive at filePath. If
// quiet is true, no progress is printed to stdout.
func unarchive(filePath string, quiet bool) (string, error) {
var err error
r, err := os.Open(filePath)
if err != nil {
return "", err
}
defer r.Close()
destFilePath := strings.TrimSuffix(filePath, ".tar") + ".qcow2"
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
if hdr.Name == "box.img" {
w, err := os.Create(destFilePath)
if err != nil {
return "", err
}
defer w.Close()
var bytesWritten uint64
err = copyBytes(w, tr, func(buf []byte) {
if !quiet {
bytesWritten += uint64(len(buf))
fmt.Printf("\r%s", strings.Repeat(" ", 40))
fmt.Printf("\rextracting... %s", humanize.Bytes(bytesWritten))
}
})
if !quiet {
fmt.Println()
}
if err != nil {
return "", err
}
}
}
if err := os.Remove(filePath); err != nil {
return "", err
}
return inspect(destFilePath, quiet)
}
// copyBytes transfers bytes from src to dest, piping through a TeeReader, calling
// writeFunc on each read from src.
func copyBytes(dest io.Writer, src io.Reader, writeFunc func(buf []byte)) error {
w := printWriter{
print: writeFunc,
}
_, err := io.Copy(dest, io.TeeReader(src, w))
if err != nil {
return err
}
return nil
}
type printWriter struct {
print func(buf []byte)
}
func (p printWriter) Write(buf []byte) (int, error) {
p.print(buf)
return len(buf), nil
}