-
Notifications
You must be signed in to change notification settings - Fork 20
/
snapshot_list.go
106 lines (86 loc) · 2.55 KB
/
snapshot_list.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
package cmd
import (
"fmt"
"strings"
humanize "github.com/dustin/go-humanize"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
type snapshotListItemOutput struct {
ID string `json:"id"`
Date string `json:"date"`
Instance string `json:"instance"`
State string `json:"state"`
Size string `json:"size"`
}
type snapshotListOutput []snapshotListItemOutput
func (o *snapshotListOutput) toJSON() { outputJSON(o) }
func (o *snapshotListOutput) toText() { outputText(o) }
func (o *snapshotListOutput) toTable() { outputTable(o) }
func init() {
snapshotCmd.AddCommand(&cobra.Command{
Use: "list [vm name | vm id]+",
Short: "List snapshot",
Long: fmt.Sprintf(`This command lists existing Compute instance disk snapshots.
Supported output template annotations: %s`,
strings.Join(outputterTemplateAnnotations(&snapshotListOutput{}), ", ")),
Aliases: gListAlias,
RunE: func(cmd *cobra.Command, args []string) error {
return output(listSnapshots(args))
},
})
}
func listSnapshots(instances []string) (outputter, error) {
out := snapshotListOutput{}
if len(instances) == 0 {
snapshots, err := cs.ListWithContext(gContext, egoscale.Snapshot{})
if err != nil {
return nil, err
}
for _, s := range snapshots {
snapshot := s.(*egoscale.Snapshot)
instance := snapshotVMName(*snapshot)
out = append(out, snapshotListItemOutput{
ID: snapshot.ID.String(),
Instance: instance,
Date: snapshot.Created,
State: snapshot.State,
Size: humanize.IBytes(uint64(snapshot.Size)),
})
}
return &out, nil
}
for _, i := range instances {
instance, err := getVirtualMachineByNameOrID(i)
if err != nil {
return nil, err
}
volume, err := cs.GetWithContext(gContext, &egoscale.Volume{
VirtualMachineID: instance.ID,
Type: "ROOT",
})
if err != nil {
return nil, err
}
snapshots, err := cs.ListWithContext(gContext, egoscale.Snapshot{VolumeID: volume.(*egoscale.Volume).ID})
if err != nil {
return nil, err
}
for _, s := range snapshots {
snapshot := s.(*egoscale.Snapshot)
out = append(out, snapshotListItemOutput{
ID: snapshot.ID.String(),
Instance: instance.Name,
Date: snapshot.Created,
State: snapshot.State,
Size: humanize.IBytes(uint64(snapshot.Size)),
})
}
}
return &out, nil
}
// snapshotVMName returns the instance name based on the snapshot name.
func snapshotVMName(snapshot egoscale.Snapshot) string {
names := strings.SplitN(snapshot.Name, "_"+snapshot.VolumeName+"_", 2)
return names[0]
}