This repository has been archived by the owner on Aug 15, 2022. It is now read-only.
forked from estafette/estafette-gke-node-pool-shifter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcloud.go
109 lines (86 loc) · 2.45 KB
/
gcloud.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
package main
import (
"context"
"fmt"
"golang.org/x/oauth2/google"
"net/http"
"strings"
"google.golang.org/api/compute/v1"
container "google.golang.org/api/container/v1beta1"
)
const (
// operationWaitTimeoutSecond define the time wait in second before assuming the failure of a GCloud operation
operationWaitTimeoutSecond = 600
// operationPollIntervalSecond define the interval in second before each GCloud operation status check
operationPollIntervalSecond = 10
)
type GCloud struct {
Client *http.Client
Cluster string
Context context.Context
Project string
Location string
}
type GCloudClient interface {
GetProjectDetailsFromNode(string) error
NewGCloudContainerClient() (GCloudContainerClient, error)
}
// NewGCloudClient return a GCloud client
func NewGCloudClient() (gcloud GCloudClient, err error) {
ctx := context.Background()
client, err := google.DefaultClient(ctx, container.CloudPlatformScope)
if err != nil {
err = fmt.Errorf("Error creating GCloud client:\n%v", err)
}
gcloud = &GCloud{
Client: client,
Context: ctx,
}
return
}
// NewGCloudContainerClient return a GCloud container client
func (g *GCloud) NewGCloudContainerClient() (gcloud GCloudContainerClient, err error) {
ctx := context.Background()
service, err := container.NewService(ctx)
if err != nil {
err = fmt.Errorf("Error creating GCloud container client:\n%v", err)
return
}
gcloud = &GCloudContainer{
Client: g,
Service: service,
}
return
}
// GetProjectDetailsFromNode retrieve project id, zone and cluster id from a given node spec provider id
func (g *GCloud) GetProjectDetailsFromNode(providerId string) (err error) {
if providerId == "" {
return fmt.Errorf("Provider ID is empty, doesn't seem to run in Google Cloud")
}
s := strings.Split(providerId, "/")
g.Project = s[2]
ctx := context.Background()
service, err := compute.NewService(ctx)
if err != nil {
err = fmt.Errorf("Error creating GCloud compute client: %v", err)
return
}
node, err := service.Instances.Get(g.Project, s[3], s[4]).Context(g.Context).Do()
if err != nil {
err = fmt.Errorf("error retrieving instance details from GCloud: %v", err)
return
}
// get cluster name from node metadata
for _, metadata := range node.Metadata.Items {
if metadata.Key == "cluster-name" {
g.Cluster = *metadata.Value
}
if metadata.Key == "cluster-location" {
g.Location = *metadata.Value
}
if g.Cluster != "" && g.Location != "" {
break
}
}
return
}