-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgce.go
266 lines (222 loc) · 7.98 KB
/
gce.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gcecloudprovider
import (
"context"
"fmt"
"net/http"
"os"
"runtime"
"time"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
"gopkg.in/gcfg.v1"
"cloud.google.com/go/compute/metadata"
"golang.org/x/oauth2"
computebeta "google.golang.org/api/compute/v0.beta"
"google.golang.org/api/compute/v1"
"google.golang.org/api/googleapi"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
)
const (
TokenURL = "https://accounts.google.com/o/oauth2/token"
diskSourceURITemplateSingleZone = "%s/zones/%s/disks/%s" // {gce.projectID}/zones/{disk.Zone}/disks/{disk.Name}"
diskSourceURITemplateRegional = "%s/regions/%s/disks/%s" //{gce.projectID}/regions/{disk.Region}/disks/repd"
diskTypeURITemplateSingleZone = "%s/zones/%s/diskTypes/%s" // {gce.projectID}/zones/{disk.Zone}/diskTypes/{disk.Type}"
diskTypeURITemplateRegional = "%s/regions/%s/diskTypes/%s" // {gce.projectID}/regions/{disk.Region}/diskTypes/{disk.Type}"
regionURITemplate = "projects/%s/regions/%s"
GCEComputeAPIEndpoint = "https://www.googleapis.com/compute/v1/"
GCEComputeBetaAPIEndpoint = "https://www.googleapis.com/compute/beta/"
GCEComputeAlphaAPIEndpoint = "https://www.googleapis.com/compute/alpha/"
replicaZoneURITemplateSingleZone = "%s/zones/%s" // {gce.projectID}/zones/{disk.Zone}
)
type CloudProvider struct {
service *compute.Service
betaService *computebeta.Service
project string
zone string
zonesCache map[string][]string
}
var _ GCECompute = &CloudProvider{}
type ConfigFile struct {
Global ConfigGlobal `gcfg:"global"`
}
type ConfigGlobal struct {
TokenURL string `gcfg:"token-url"`
TokenBody string `gcfg:"token-body"`
ProjectId string `gcfg:"project-id"`
Zone string `gcfg:"zone"`
}
func CreateCloudProvider(ctx context.Context, vendorVersion string, configPath string) (*CloudProvider, error) {
configFile, err := readConfig(configPath)
if err != nil {
return nil, err
}
// At this point configFile could still be nil.
// Any following code that uses configFile should handle nil pointer gracefully.
klog.V(2).Infof("Using GCE provider config %+v", configFile)
tokenSource, err := generateTokenSource(ctx, configFile)
if err != nil {
return nil, err
}
svc, err := createCloudService(ctx, vendorVersion, tokenSource)
if err != nil {
return nil, err
}
betasvc, err := createBetaCloudService(ctx, vendorVersion, tokenSource)
if err != nil {
return nil, err
}
project, zone, err := getProjectAndZone(configFile)
if err != nil {
return nil, fmt.Errorf("Failed getting Project and Zone: %w", err)
}
return &CloudProvider{
service: svc,
betaService: betasvc,
project: project,
zone: zone,
zonesCache: make(map[string]([]string)),
}, nil
}
func generateTokenSource(ctx context.Context, configFile *ConfigFile) (oauth2.TokenSource, error) {
if configFile != nil && configFile.Global.TokenURL != "" && configFile.Global.TokenURL != "nil" {
// configFile.Global.TokenURL is defined
// Use AltTokenSource
tokenSource := NewAltTokenSource(configFile.Global.TokenURL, configFile.Global.TokenBody)
klog.V(2).Infof("Using AltTokenSource %#v", tokenSource)
return tokenSource, nil
}
// Use DefaultTokenSource
tokenSource, err := google.DefaultTokenSource(
ctx,
compute.CloudPlatformScope,
compute.ComputeScope)
// DefaultTokenSource relies on GOOGLE_APPLICATION_CREDENTIALS env var being set.
if gac, ok := os.LookupEnv("GOOGLE_APPLICATION_CREDENTIALS"); ok {
klog.V(2).Infof("GOOGLE_APPLICATION_CREDENTIALS env var set %v", gac)
} else {
klog.Warningf("GOOGLE_APPLICATION_CREDENTIALS env var not set")
}
klog.V(2).Infof("Using DefaultTokenSource %#v", tokenSource)
return tokenSource, err
}
func readConfig(configPath string) (*ConfigFile, error) {
if configPath == "" {
return nil, nil
}
reader, err := os.Open(configPath)
if err != nil {
return nil, fmt.Errorf("couldn't open cloud provider configuration at %s: %w", configPath, err)
}
defer reader.Close()
cfg := &ConfigFile{}
if err := gcfg.FatalOnly(gcfg.ReadInto(cfg, reader)); err != nil {
return nil, fmt.Errorf("couldn't read cloud provider configuration at %s: %w", configPath, err)
}
return cfg, nil
}
func createBetaCloudService(ctx context.Context, vendorVersion string, tokenSource oauth2.TokenSource) (*computebeta.Service, error) {
client, err := newOauthClient(ctx, tokenSource)
if err != nil {
return nil, err
}
service, err := computebeta.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
return nil, err
}
service.UserAgent = fmt.Sprintf("GCE CSI Driver/%s (%s %s)", vendorVersion, runtime.GOOS, runtime.GOARCH)
return service, nil
}
func createCloudService(ctx context.Context, vendorVersion string, tokenSource oauth2.TokenSource) (*compute.Service, error) {
svc, err := createCloudServiceWithDefaultServiceAccount(ctx, vendorVersion, tokenSource)
return svc, err
}
func createCloudServiceWithDefaultServiceAccount(ctx context.Context, vendorVersion string, tokenSource oauth2.TokenSource) (*compute.Service, error) {
client, err := newOauthClient(ctx, tokenSource)
if err != nil {
return nil, err
}
service, err := compute.New(client)
if err != nil {
return nil, err
}
service.UserAgent = fmt.Sprintf("GCE CSI Driver/%s (%s %s)", vendorVersion, runtime.GOOS, runtime.GOARCH)
return service, nil
}
func newOauthClient(ctx context.Context, tokenSource oauth2.TokenSource) (*http.Client, error) {
if err := wait.PollImmediate(5*time.Second, 30*time.Second, func() (bool, error) {
if _, err := tokenSource.Token(); err != nil {
klog.Errorf("error fetching initial token: %v", err.Error())
return false, nil
}
return true, nil
}); err != nil {
return nil, err
}
return oauth2.NewClient(ctx, tokenSource), nil
}
func getProjectAndZone(config *ConfigFile) (string, string, error) {
var err error
var zone string
if config == nil || config.Global.Zone == "" {
zone, err = metadata.Zone()
if err != nil {
return "", "", err
}
klog.V(2).Infof("Using GCP zone from the Metadata server: %q", zone)
} else {
zone = config.Global.Zone
klog.V(2).Infof("Using GCP zone from the local GCE cloud provider config file: %q", zone)
}
var projectID string
if config == nil || config.Global.ProjectId == "" {
// Project ID is not available from the local GCE cloud provider config file.
// This could happen if the driver is not running in the master VM.
// Defaulting to project ID from the Metadata server.
projectID, err = metadata.ProjectID()
if err != nil {
return "", "", err
}
klog.V(2).Infof("Using GCP project ID from the Metadata server: %q", projectID)
} else {
projectID = config.Global.ProjectId
klog.V(2).Infof("Using GCP project ID from the local GCE cloud provider config file: %q", projectID)
}
return projectID, zone, nil
}
// isGCEError returns true if given error is a googleapi.Error with given
// reason (e.g. "resourceInUseByAnotherResource")
func IsGCEError(err error, reason string) bool {
apiErr, ok := err.(*googleapi.Error)
if !ok {
return false
}
for _, e := range apiErr.Errors {
if e.Reason == reason {
return true
}
}
return false
}
// IsGCENotFoundError returns true if the error is a googleapi.Error with
// notFound reason
func IsGCENotFoundError(err error) bool {
return IsGCEError(err, "notFound")
}
// IsInvalidError returns true if the error is a googleapi.Error with
// invalid reason
func IsGCEInvalidError(err error) bool {
return IsGCEError(err, "invalid")
}