1
+ package compute
2
+
3
+ import (
4
+ "context"
5
+ "fmt"
6
+ "time"
7
+
8
+ "github.com/sirupsen/logrus"
9
+ "github.com/tailwarden/komiser/models"
10
+ "github.com/tailwarden/komiser/providers"
11
+ "google.golang.org/api/iterator"
12
+ "google.golang.org/api/option"
13
+
14
+ compute "cloud.google.com/go/compute/apiv1"
15
+ computepb "cloud.google.com/go/compute/apiv1/computepb"
16
+ )
17
+
18
+ func Disks (ctx context.Context , client providers.ProviderClient ) ([]models.Resource , error ) {
19
+ resources := make ([]models.Resource , 0 )
20
+
21
+ disksClient , err := compute .NewDisksRESTClient (ctx , option .WithCredentials (client .GCPClient .Credentials ))
22
+ if err != nil {
23
+ logrus .WithError (err ).Errorf ("failed to create compute client" )
24
+ return resources , err
25
+ }
26
+
27
+ req := & computepb.AggregatedListDisksRequest {
28
+ Project : client .GCPClient .Credentials .ProjectID ,
29
+ }
30
+ disks := disksClient .AggregatedList (ctx , req )
31
+
32
+ for {
33
+ disksListPair , err := disks .Next ()
34
+ if err == iterator .Done {
35
+ break
36
+ }
37
+ if err != nil {
38
+ logrus .WithError (err ).Errorf ("failed to list instances" )
39
+ return resources , err
40
+ }
41
+ if len (disksListPair .Value .Disks ) == 0 {
42
+ continue
43
+ }
44
+
45
+ for _ , disk := range disksListPair .Value .Disks {
46
+ tags := make ([]models.Tag , 0 )
47
+ if disk .Labels != nil {
48
+ for key , value := range disk .Labels {
49
+ tags = append (tags , models.Tag {
50
+ Key : key ,
51
+ Value : value ,
52
+ })
53
+ }
54
+ }
55
+
56
+ zone := extractZoneFromURL (disk .GetZone ())
57
+
58
+ resources = append (resources , models.Resource {
59
+ Provider : "GCP" ,
60
+ Account : client .Name ,
61
+ Service : "Compute Disk" ,
62
+ ResourceId : fmt .Sprintf ("%d" , disk .GetId ()),
63
+ Region : zone ,
64
+ Name : disk .GetName (),
65
+ FetchedAt : time .Now (),
66
+ Tags : tags ,
67
+ Link : fmt .Sprintf ("https://console.cloud.google.com/compute/disksDetail/zones/%s/disks/%s?project=%s" , zone , disk .GetName (), client .GCPClient .Credentials .ProjectID ),
68
+ })
69
+ }
70
+ }
71
+
72
+ logrus .WithFields (logrus.Fields {
73
+ "provider" : "GCP" ,
74
+ "account" : client .Name ,
75
+ "service" : "Compute Engine" ,
76
+ "resources" : len (resources ),
77
+ }).Info ("Fetched resources" )
78
+
79
+ return resources , nil
80
+ }
0 commit comments