/
vm_snapshots.go
58 lines (50 loc) · 1.47 KB
/
vm_snapshots.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
package gcp
import (
"context"
"fmt"
"github.com/one2nc/cloudlens/internal"
"github.com/rs/zerolog/log"
"google.golang.org/api/compute/v1"
)
func ListSnapshots(ctx context.Context) ([]SnapshotResp, error) {
var snapshotsResp []SnapshotResp
client, err := compute.NewService(ctx)
if err != nil {
log.Printf("Failed to create Compute Engine client: %v\n", err)
return snapshotsResp, err
}
project := ctx.Value(internal.KeyActiveProject).(string)
snapshots, err := client.Snapshots.List(project).Context(ctx).Do()
if err != nil {
log.Printf("Failed to fetch snapshots: %v\n", err)
return snapshotsResp, err
}
for _, snapshot := range snapshots.Items {
createdAt, err := GetLocalTime(snapshot.CreationTimestamp)
if err != nil {
log.Print(err)
return snapshotsResp, err
}
res := SnapshotResp{
Name: snapshot.Name,
Size: fmt.Sprintf("%v GB", snapshot.DiskSizeGb),
CreatedAt: createdAt,
}
snapshotsResp = append(snapshotsResp, res)
}
return snapshotsResp, nil
}
func GetSnapshot(ctx context.Context, snapshotID string) (*compute.Snapshot, error) {
client, err := compute.NewService(ctx)
if err != nil {
log.Printf("Failed to create Compute Engine client: %v\n", err)
return nil, err
}
project := ctx.Value(internal.KeyActiveProject).(string)
snapshot, err := client.Snapshots.Get(project, snapshotID).Context(ctx).Do()
if err != nil {
log.Printf("Failed to fetch snapshots: %v\n", err)
return nil, err
}
return snapshot, nil
}