-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathattach.go
77 lines (64 loc) · 1.87 KB
/
attach.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
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/teemow/loopback/image"
"github.com/teemow/loopback/loop"
)
var (
attachCmd = &cobra.Command{
Use: "attach",
Short: "Attach a loopback device",
Long: `Attach a loopback device.
Attach an image as a loopback.
`,
Run: attachRun,
}
attachFlags struct {
name string
imagePath string
size int
fs string
createMissingImage bool
}
)
func init() {
attachCmd.Flags().StringVar(&attachFlags.name, "name", "", "Name of the volume")
attachCmd.Flags().StringVar(&attachFlags.imagePath, "image-path", "/var/lib/loopback", "Path for the loopback images")
attachCmd.Flags().IntVar(&attachFlags.size, "size", 1, "Size of the volume (in gigabytes)")
attachCmd.Flags().StringVar(&attachFlags.fs, "fs", "btrfs", "Filesystem")
attachCmd.Flags().BoolVar(&attachFlags.createMissingImage, "create-missing-image", false, "Creating image if it does not exist")
}
func attachRun(cmd *cobra.Command, args []string) {
var err error
if attachFlags.name == "" {
fmt.Fprintln(os.Stderr, "Image name parameter missing.")
os.Exit(1)
}
createAndFormatImage := false
if !image.Exists(attachFlags.name, attachFlags.imagePath) || !attachFlags.createMissingImage {
createAndFormatImage = true
}
if createAndFormatImage {
err = image.Create(attachFlags.name, attachFlags.imagePath, attachFlags.size)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't create image: %s\n", err)
os.Exit(1)
}
}
var device string
device, err = loop.Attach(attachFlags.name, attachFlags.imagePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't attach loopback: %s\n", err)
os.Exit(1)
}
if createAndFormatImage {
loop.Format(device, attachFlags.fs)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't format loopback: %s\n", err)
os.Exit(1)
}
}
os.Exit(0)
}