-
Notifications
You must be signed in to change notification settings - Fork 15
/
sdk.go
432 lines (374 loc) · 13.4 KB
/
sdk.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Copyright (c) 2017 Yandex LLC. All rights reserved.
// Author: Alexey Baranov <[email protected]>
package ycsdk
import (
"context"
"crypto/tls"
"errors"
"fmt"
"sort"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"github.com/yandex-cloud/go-genproto/yandex/cloud/endpoint"
iampb "github.com/yandex-cloud/go-genproto/yandex/cloud/iam/v1"
"github.com/yandex-cloud/go-genproto/yandex/cloud/operation"
_ "github.com/yandex-cloud/go-genproto/yandex/cloud/quota" // Used in Operation.error.details
"github.com/yandex-cloud/go-sdk/dial"
apiendpoint "github.com/yandex-cloud/go-sdk/gen/apiendpoint"
"github.com/yandex-cloud/go-sdk/gen/audittrails"
"github.com/yandex-cloud/go-sdk/gen/backup"
"github.com/yandex-cloud/go-sdk/gen/compute"
"github.com/yandex-cloud/go-sdk/gen/dns"
"github.com/yandex-cloud/go-sdk/gen/iam"
"github.com/yandex-cloud/go-sdk/gen/iam/workload"
"github.com/yandex-cloud/go-sdk/gen/iam/workload/oidc"
k8s "github.com/yandex-cloud/go-sdk/gen/kubernetes"
"github.com/yandex-cloud/go-sdk/gen/monitoring"
gen_operation "github.com/yandex-cloud/go-sdk/gen/operation"
"github.com/yandex-cloud/go-sdk/gen/organizationmanager"
organizationmanagersaml "github.com/yandex-cloud/go-sdk/gen/organizationmanager/saml"
"github.com/yandex-cloud/go-sdk/gen/resourcemanager"
"github.com/yandex-cloud/go-sdk/gen/storage-api"
"github.com/yandex-cloud/go-sdk/gen/vpc"
"github.com/yandex-cloud/go-sdk/gen/vpc/privatelink"
"github.com/yandex-cloud/go-sdk/gen/ydb"
sdk_operation "github.com/yandex-cloud/go-sdk/operation"
"github.com/yandex-cloud/go-sdk/pkg/grpcclient"
"github.com/yandex-cloud/go-sdk/pkg/sdkerrors"
"github.com/yandex-cloud/go-sdk/pkg/singleflight"
)
type Endpoint string
const (
DefaultPageSize int64 = 1000
ComputeServiceID Endpoint = "compute"
IAMServiceID Endpoint = "iam"
OperationServiceID Endpoint = "operation"
OrganizationManagementServiceID Endpoint = "organization-manager"
ResourceManagementServiceID Endpoint = "resource-manager"
StorageServiceID Endpoint = "storage"
StorageAPIServiceID Endpoint = "storage-api"
MonitoringServiceID Endpoint = "monitoring"
SerialSSHServiceID Endpoint = "serialssh"
// revive:disable:var-naming
ApiEndpointServiceID Endpoint = "endpoint"
// revive:enable:var-naming
VpcServiceID Endpoint = "vpc"
KubernetesServiceID Endpoint = "managed-kubernetes"
DNSServiceID Endpoint = "dns"
YDBServiceID Endpoint = "ydb"
BackupServiceID Endpoint = "backup"
AuditTrailsServiceID Endpoint = "audittrails"
)
// Config is a config that is used to create SDK instance.
type Config struct {
// Credentials are used to authenticate the client. See Credentials for more info.
Credentials Credentials
// DialContextTimeout specifies timeout of dial on API endpoint that
// is used when building an SDK instance.
DialContextTimeout time.Duration
// TLSConfig is optional tls.Config that one can use in order to tune TLS options.
TLSConfig *tls.Config
// Endpoint is an API endpoint of Yandex.Cloud against which the SDK is used.
// Most users won't need to explicitly set it.
Endpoint string
Plaintext bool
}
// SDK is a Yandex.Cloud SDK
type SDK struct {
conf Config
cc grpcclient.ConnContext
endpoints struct {
initDone bool
mu sync.Mutex
ep map[Endpoint]*endpoint.ApiEndpoint
}
initErr error
initCall singleflight.Call
muErr sync.Mutex
}
// Build creates an SDK instance
func Build(ctx context.Context, conf Config, customOpts ...grpc.DialOption) (*SDK, error) {
if conf.Credentials == nil {
return nil, errors.New("credentials required")
}
const defaultEndpoint = "api.cloud.yandex.net:443"
if conf.Endpoint == "" {
conf.Endpoint = defaultEndpoint
}
const DefaultTimeout = 20 * time.Second
if conf.DialContextTimeout == 0 {
conf.DialContextTimeout = DefaultTimeout
}
switch creds := conf.Credentials.(type) {
case ExchangeableCredentials, NonExchangeableCredentials:
default:
return nil, fmt.Errorf("unsupported credentials type %T", creds)
}
sdk := &SDK{
cc: nil, // Later
conf: conf,
}
tokenMiddleware := NewIAMTokenMiddleware(sdk, now)
var dialOpts []grpc.DialOption
dialOpts = append(dialOpts,
grpc.WithContextDialer(dial.NewProxyDialer(dial.NewDialer())),
grpc.WithChainUnaryInterceptor(tokenMiddleware.InterceptUnary),
grpc.WithChainStreamInterceptor(tokenMiddleware.InterceptStream),
)
if conf.DialContextTimeout > 0 {
dialOpts = append(dialOpts, grpc.WithBlock(), grpc.WithTimeout(conf.DialContextTimeout)) // nolint
}
if conf.Plaintext {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
tlsConfig := conf.TLSConfig
if tlsConfig == nil {
tlsConfig = &tls.Config{}
}
creds := credentials.NewTLS(tlsConfig)
dialOpts = append(dialOpts, grpc.WithTransportCredentials(creds))
}
// Append custom options after default, to allow to customize dialer and etc.
dialOpts = append(dialOpts, customOpts...)
sdk.cc = grpcclient.NewLazyConnContext(grpcclient.DialOptions(dialOpts...))
return sdk, nil
}
// Shutdown shutdowns SDK and closes all open connections.
func (sdk *SDK) Shutdown(ctx context.Context) error {
return sdk.cc.Shutdown(ctx)
}
func (sdk *SDK) CheckEndpointConnection(ctx context.Context, endpoint Endpoint) error {
_, err := sdk.getConn(endpoint)(ctx)
return err
}
// WrapOperation wraps operation proto message to
func (sdk *SDK) WrapOperation(op *operation.Operation, err error) (*sdk_operation.Operation, error) {
if err != nil {
return nil, err
}
return sdk_operation.New(sdk.Operation(), op), nil
}
// IAM returns IAM object that is used to operate on Yandex Cloud Identity and Access Manager
func (sdk *SDK) IAM() *iam.IAM {
return iam.NewIAM(sdk.getConn(IAMServiceID))
}
func (sdk *SDK) Workload() *workload.Workload {
return workload.NewWorkload(sdk.getConn(IAMServiceID))
}
func (sdk *SDK) WorkloadOidc() *oidc.WorkloadOidc {
return oidc.NewWorkloadOidc(sdk.getConn(IAMServiceID))
}
// Compute returns Compute object that is used to operate on Yandex Compute Cloud
func (sdk *SDK) Compute() *compute.Compute {
return compute.NewCompute(sdk.getConn(ComputeServiceID))
}
// VPC returns VPC object that is used to operate on Yandex Virtual Private Cloud
func (sdk *SDK) VPC() *vpc.VPC {
return vpc.NewVPC(sdk.getConn(VpcServiceID))
}
// VPCPrivateLink returns PrivateLink object that is used to operate on Yandex Virtual Private Cloud Private Endpoints
func (sdk *SDK) VPCPrivateLink() *privatelink.PrivateLink {
return privatelink.NewPrivateLink(sdk.getConn(VpcServiceID))
}
// MDB returns MDB object that is used to operate on Yandex Managed Databases
func (sdk *SDK) MDB() *MDB {
return &MDB{sdk: sdk}
}
func (sdk *SDK) Serverless() *Serverless {
return &Serverless{sdk: sdk}
}
func (sdk *SDK) Marketplace() *Marketplace {
return &Marketplace{sdk: sdk}
}
// Operation gets OperationService client
func (sdk *SDK) Operation() *gen_operation.OperationServiceClient {
group := gen_operation.NewOperation(sdk.getConn(OperationServiceID))
return group.Operation()
}
func (sdk *SDK) OrganizationManager() *organizationmanager.OrganizationManager {
return organizationmanager.NewOrganizationManager(sdk.getConn(OrganizationManagementServiceID))
}
func (sdk *SDK) OSLoginServiceClient() *organizationmanager.OsLoginServiceClient {
manager := sdk.OrganizationManager()
return manager.OsLogin()
}
func (sdk *SDK) UserSSHKeyServiceClient() *organizationmanager.UserSshKeyServiceClient {
manager := sdk.OrganizationManager()
return manager.UserSshKey()
}
func (sdk *SDK) GroupMappingServiceClient() *organizationmanager.GroupMappingServiceClient {
manager := sdk.OrganizationManager()
return manager.GroupMapping()
}
func (sdk *SDK) OrganizationManagerSAML() *organizationmanagersaml.OrganizationManagerSAML {
return organizationmanagersaml.NewOrganizationManagerSAML(sdk.getConn(OrganizationManagementServiceID))
}
// ResourceManager returns ResourceManager object that is used to operate on Folders and Clouds
func (sdk *SDK) ResourceManager() *resourcemanager.ResourceManager {
return resourcemanager.NewResourceManager(sdk.getConn(ResourceManagementServiceID))
}
// revive:disable:var-naming
// ApiEndpoint gets ApiEndpointService client
func (sdk *SDK) ApiEndpoint() *apiendpoint.APIEndpoint {
return apiendpoint.NewAPIEndpoint(sdk.getConn(ApiEndpointServiceID))
}
// revive:enable:var-naming
// Kubernetes returns Kubernetes object that is used to operate on Yandex Managed Kubernetes
func (sdk *SDK) Kubernetes() *k8s.Kubernetes {
return k8s.NewKubernetes(sdk.getConn(KubernetesServiceID))
}
// DNS returns DNS object that is used to operate on Yandex DNS
func (sdk *SDK) DNS() *dns.DNS {
return dns.NewDNS(sdk.getConn(DNSServiceID))
}
// AI returns AI object that is used to do AI stuff.
func (sdk *SDK) AI() *AI {
return &AI{sdk: sdk}
}
// YDB returns object for Yandex Database operations.
func (sdk *SDK) YDB() *ydb.YDB {
return ydb.NewYDB(sdk.getConn(YDBServiceID))
}
func (sdk *SDK) Resolve(ctx context.Context, r ...Resolver) error {
args := make([]func() error, len(r))
for k, v := range r {
resolver := v
args[k] = func() error {
return resolver.Run(ctx, sdk)
}
}
return sdkerrors.CombineGoroutines(args...)
}
func (sdk *SDK) getConn(serviceID Endpoint) func(ctx context.Context) (*grpc.ClientConn, error) {
return func(ctx context.Context) (*grpc.ClientConn, error) {
if !sdk.initDone() {
sdk.initCall.Do(func() interface{} {
sdk.muErr.Lock()
sdk.initErr = sdk.initConns(ctx)
sdk.muErr.Unlock()
return nil
})
if err := sdk.InitErr(); err != nil {
return nil, err
}
}
endpoint, endpointExist := sdk.Endpoint(serviceID)
if !endpointExist {
return nil, &ServiceIsNotAvailableError{
ServiceID: serviceID,
APIEndpoint: sdk.conf.Endpoint,
availableServiceIDs: sdk.KnownServices(),
}
}
return sdk.cc.GetConn(ctx, endpoint.Address)
}
}
type ServiceIsNotAvailableError struct {
ServiceID Endpoint
APIEndpoint string
availableServiceIDs []string
}
func (s *ServiceIsNotAvailableError) Error() string {
return fmt.Sprintf("Service \"%v\" is not available at Cloud API endpoint \"%v\". Available services: %v",
s.ServiceID,
s.APIEndpoint,
s.availableServiceIDs,
)
}
var _ error = &ServiceIsNotAvailableError{}
func (sdk *SDK) initDone() (b bool) {
sdk.endpoints.mu.Lock()
b = sdk.endpoints.initDone
sdk.endpoints.mu.Unlock()
return
}
func (sdk *SDK) KnownServices() []string {
sdk.endpoints.mu.Lock()
result := make([]string, 0, len(sdk.endpoints.ep))
for k := range sdk.endpoints.ep {
result = append(result, string(k))
}
sdk.endpoints.mu.Unlock()
sort.Strings(result)
return result
}
func (sdk *SDK) Endpoint(endpointName Endpoint) (ep *endpoint.ApiEndpoint, exist bool) {
sdk.endpoints.mu.Lock()
ep, exist = sdk.endpoints.ep[endpointName]
sdk.endpoints.mu.Unlock()
return
}
func (sdk *SDK) InitErr() error {
sdk.muErr.Lock()
defer sdk.muErr.Unlock()
return sdk.initErr
}
func (sdk *SDK) initConns(ctx context.Context) error {
discoveryConn, err := sdk.cc.GetConn(ctx, sdk.conf.Endpoint)
if err != nil {
return err
}
ec := endpoint.NewApiEndpointServiceClient(discoveryConn)
const defaultEndpointPageSize = 100
listResponse, err := ec.List(ctx, &endpoint.ListApiEndpointsRequest{
PageSize: defaultEndpointPageSize,
})
if err != nil {
return err
}
sdk.endpoints.mu.Lock()
sdk.endpoints.ep = make(map[Endpoint]*endpoint.ApiEndpoint, len(listResponse.Endpoints))
for _, e := range listResponse.Endpoints {
sdk.endpoints.ep[Endpoint(e.Id)] = e
}
sdk.endpoints.initDone = true
sdk.endpoints.mu.Unlock()
return nil
}
func (sdk *SDK) CreateIAMToken(ctx context.Context) (*iampb.CreateIamTokenResponse, error) {
creds := sdk.conf.Credentials
switch creds := creds.(type) {
case ExchangeableCredentials:
req, err := creds.IAMTokenRequest()
if err != nil {
return nil, sdkerrors.WithMessage(err, "IAM token request build failed")
}
return sdk.IAM().IamToken().Create(ctx, req)
case NonExchangeableCredentials:
return creds.IAMToken(ctx)
default:
return nil, fmt.Errorf("credentials type %T is not supported yet", creds)
}
}
func (sdk *SDK) CreateIAMTokenForServiceAccount(ctx context.Context, serviceAccountID string) (*iampb.CreateIamTokenResponse, error) {
token, err := sdk.IAM().IamToken().CreateForServiceAccount(ctx, &iampb.CreateIamTokenForServiceAccountRequest{
ServiceAccountId: serviceAccountID,
})
if err != nil {
return nil, err
}
return &iampb.CreateIamTokenResponse{
IamToken: token.IamToken,
ExpiresAt: token.ExpiresAt,
}, nil
}
var now = time.Now
// StorageAPI returns storage object for operating with Object Storage service.
func (sdk *SDK) StorageAPI() *storage.StorageAPI {
return storage.NewStorageAPI(sdk.getConn(StorageAPIServiceID))
}
// Monitoring returns object for operating with Monitoring service.
func (sdk *SDK) Monitoring() *monitoring.Monitoring {
return monitoring.NewMonitoring(sdk.getConn(MonitoringServiceID))
}
// Backup returns backup for operating with Backup service.
func (sdk *SDK) Backup() *backup.Backup {
return backup.NewBackup(sdk.getConn(BackupServiceID))
}
// AuditTrails returns object for operating with Audit Trails service.
func (sdk *SDK) AuditTrails() *audittrails.AuditTrails {
return audittrails.NewAuditTrails(sdk.getConn(AuditTrailsServiceID))
}