-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsdk.go
393 lines (348 loc) · 11.6 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
package dcsdk
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"github.com/doublecloud/go-sdk/gen/airflow"
"github.com/doublecloud/go-sdk/gen/organization"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"os"
"sort"
"strings"
"sync"
"time"
dcv1 "github.com/doublecloud/go-genproto/doublecloud/v1"
"github.com/doublecloud/go-sdk/gen/clickhouse"
"github.com/doublecloud/go-sdk/gen/kafka"
"github.com/doublecloud/go-sdk/gen/logs"
"github.com/doublecloud/go-sdk/gen/network"
"github.com/doublecloud/go-sdk/gen/transfer"
"github.com/doublecloud/go-sdk/gen/visualization"
"github.com/doublecloud/go-sdk/iamkey"
"github.com/doublecloud/go-sdk/operation"
"github.com/doublecloud/go-sdk/pkg/grpcclient"
"github.com/doublecloud/go-sdk/pkg/sdkerrors"
"github.com/google/uuid"
"golang.org/x/sync/singleflight"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/grpclog"
"google.golang.org/protobuf/types/known/timestamppb"
)
type Endpoint string
type APIEndpoint struct {
Id Endpoint
Address string
}
const (
DefaultPageSize int64 = 1000
ClickHouseServiceID Endpoint = "clickhouse"
KafkaServiceID Endpoint = "kafka"
VpcServiceID Endpoint = "vpc"
TransferServiceID Endpoint = "transfer"
VisualizationServiceID Endpoint = "visualization"
LogsServiceID Endpoint = "logs"
OrganizationServiceID Endpoint = "organization"
AirflowServiceID Endpoint = "airflow"
)
// 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 DoubleCloud against which the SDK is used.
// Most users won't need to explicitly set it.
Endpoint string
OverrideEndpoint bool
Plaintext bool
}
// SDK is a DoubleCloud SDK
type SDK struct {
conf Config
cc grpcclient.ConnContext
endpoints struct {
initDone bool
mu sync.Mutex
ep map[Endpoint]*APIEndpoint
}
initErr error
initCall singleflight.Group
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.double.cloud:443"
if conf.Endpoint == "" {
conf.Endpoint = defaultEndpoint
}
const DefaultTimeout = 20 * time.Second
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.WithChainUnaryInterceptor(tokenMiddleware.InterceptUnary),
grpc.WithChainStreamInterceptor(tokenMiddleware.InterceptStream),
)
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 handy structure
func (sdk *SDK) WrapOperation(o *dcv1.Operation, err error) (*operation.Operation, error) {
if err != nil {
return nil, err
}
if strings.HasPrefix(o.Id, operation.CLICKHOUSE_OPERATION_PREFIX) {
return operation.New(sdk.ClickHouse().Operation(), o), nil
}
if strings.HasPrefix(o.Id, operation.KAFKA_OPERATION_PREFIX) {
return operation.New(sdk.Kafka().Operation(), o), nil
}
if strings.HasPrefix(o.Id, operation.TRANSFER_ENDPOINTS_OPERATION_PREFIX) || strings.HasPrefix(o.Id, operation.TRANSFER_OPERATION_PREFIX) {
return operation.New(sdk.Transfer().Operation(), o), nil
}
if strings.HasPrefix(o.Id, operation.AIRFLOW_OPERATION_PREFIX) {
return operation.New(sdk.Airflow().Operation(), o), nil
}
if _, err := uuid.Parse(o.Id); err == nil {
return operation.New(sdk.Network().Operation(), o), nil
}
return nil, sdkerrors.WithMessage(fmt.Errorf("opID: %q", o.Id), "Unknown operation type")
}
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("init", func() (any, error) {
sdk.muErr.Lock()
sdk.initErr = sdk.initConns(ctx)
sdk.muErr.Unlock()
return nil, 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 *APIEndpoint, exist bool) {
sdk.endpoints.mu.Lock()
defer sdk.endpoints.mu.Unlock()
ep, exist = sdk.endpoints.ep[endpointName]
return
}
func (sdk *SDK) InitErr() error {
sdk.muErr.Lock()
defer sdk.muErr.Unlock()
return sdk.initErr
}
func endpointsMap(baseEndpoint string, overrideEndpoint bool) map[Endpoint]*APIEndpoint {
m := make(map[Endpoint]*APIEndpoint)
for _, v := range []Endpoint{ClickHouseServiceID, KafkaServiceID, VpcServiceID, TransferServiceID, VisualizationServiceID, LogsServiceID, AirflowServiceID} {
var endpoint string
if overrideEndpoint {
endpoint = baseEndpoint
} else {
endpoint = fmt.Sprintf("%v.%s", v, baseEndpoint)
}
m[v] = &APIEndpoint{
Id: v,
Address: endpoint,
}
}
return m
}
func (sdk *SDK) initConns(ctx context.Context) error {
sdk.endpoints.mu.Lock()
defer sdk.endpoints.mu.Unlock()
sdk.endpoints.ep = endpointsMap(sdk.conf.Endpoint, sdk.conf.OverrideEndpoint)
sdk.endpoints.initDone = true
return nil
}
func tokenURL() string {
if os.Getenv("DOUBLE_CLOUD_TOKEN_URL") != "" {
return os.Getenv("DOUBLE_CLOUD_TOKEN_URL")
}
return "https://auth.double.cloud/oauth/token"
}
func exchangeJWT2IAM(ctx context.Context, request *iamkey.CreateIamTokenRequest) (*iamkey.CreateIamTokenResponse, error) {
client := http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: time.Second, // One second should be enough for localhost connection.
KeepAlive: -1, // No keep alive. Near token per hour requested.
}).DialContext,
},
}
data := fmt.Sprintf("grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=%v", request.GetJwt())
req, err := http.NewRequest("POST", tokenURL(), strings.NewReader(data))
if err != nil {
return nil, sdkerrors.WithMessage(err, "request make failed")
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// TODO: define user-agent version
req.Header.Set("User-Agent", "doublecloud-go-sdk")
reqDump, _ := httputil.DumpRequestOut(req, false)
grpclog.Infof("Going to request SA token:\n%s", reqDump)
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
return nil, sdkerrors.WithMessage(err, "failed to exchange JWT")
}
defer resp.Body.Close()
respDump, _ := httputil.DumpResponse(resp, false)
grpclog.Infof("response (without body, because contains sensitive token):\n%s", respDump)
if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("%s.\n"+
"Is this IAM running using Service Account? That is, Instance.service_account_id should not be empty.",
resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
if err != nil {
body = []byte(fmt.Sprintf("Failed response body read failed: %s", err.Error()))
}
grpclog.Errorf("IAM service token get failed: %s. Body:\n%s", resp.Status, body)
return nil, fmt.Errorf("%s", resp.Status)
}
if err != nil {
return nil, fmt.Errorf("reponse read failed: %s", err)
}
var tokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
TokenType string `json:"token_type"`
}
err = json.Unmarshal(body, &tokenResponse)
if err != nil {
grpclog.Errorf("Failed to unmarshal SA token response body.\nError: %s\nBody:\n%s", err, body)
return nil, sdkerrors.WithMessage(err, "body unmarshal failed")
}
expiresAt := timestamppb.Now()
expiresAt.Seconds += tokenResponse.ExpiresIn - 1
expiresAt.Nanos = 0 // Truncate is for readability.
return &iamkey.CreateIamTokenResponse{
IamToken: tokenResponse.AccessToken,
ExpiresAt: expiresAt,
}, nil
}
func (sdk *SDK) CreateIAMToken(ctx context.Context) (*iamkey.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 exchangeJWT2IAM(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) (*iamkey.CreateIamTokenResponse, error) {
// Later
return nil, nil
}
var now = time.Now
func (sdk *SDK) Kafka() *kafka.Kafka {
return kafka.NewKafka(sdk.getConn(KafkaServiceID))
}
func (sdk *SDK) Network() *network.Network {
return network.NewNetwork(sdk.getConn(VpcServiceID))
}
func (sdk *SDK) ClickHouse() *clickhouse.ClickHouse {
return clickhouse.NewClickHouse(sdk.getConn(ClickHouseServiceID))
}
func (sdk *SDK) Transfer() *transfer.Transfer {
return transfer.NewTransfer(sdk.getConn(TransferServiceID))
}
func (sdk *SDK) Visualization() *visualization.Visualization {
return visualization.NewVisualization(sdk.getConn(VisualizationServiceID))
}
func (sdk *SDK) Logs() *logs.Export {
return logs.NewExport(sdk.getConn(LogsServiceID))
}
func (sdk *SDK) Organization() *organization.Organization {
return organization.NewOrganization(sdk.getConn(OrganizationServiceID))
}
func (sdk *SDK) Airflow() *airflow.Airflow {
return airflow.NewAirflow(sdk.getConn(AirflowServiceID))
}