/
config.go
470 lines (415 loc) · 13 KB
/
config.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package athenadriver
import (
"net/url"
"regexp"
"strings"
"strconv"
"time"
)
// Config is for AWS Athena Driver Config.
// Be noted this is different from aws.Config.
type Config struct {
dsn url.URL `yaml:"dns"`
values url.Values `yaml:"values"`
}
var reSecretAccessKey = regexp.MustCompile(`secretAccessKey=[^&]+`)
var reAccessID = regexp.MustCompile(`accessID=[^&]+`)
var reSessionToken = regexp.MustCompile(`sessionToken=[^&]+`)
var (
credAccessEnvKey = []string{
"AWS_ACCESS_KEY_ID",
"AWS_ACCESS_KEY",
}
credSecretEnvKey = []string{
"AWS_SECRET_ACCESS_KEY",
"AWS_SECRET_KEY",
}
credSessionEnvKey = []string{
"AWS_SESSION_TOKEN",
}
regionEnvKeys = []string{
"AWS_REGION",
"AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set
}
stsRegionalEndpointKey = []string{
"AWS_STS_REGIONAL_ENDPOINTS",
}
)
// NewDefaultConfig is to new a Config with some default values.
func NewDefaultConfig(outputBucket string, region string, accessID string,
secretAccessKey string) (*Config, error) {
conf := NewNoOpsConfig()
err := conf.SetOutputBucket(outputBucket)
if err != nil {
return nil, err
}
err = conf.SetRegion(region)
if err != nil {
return nil, err
}
err = conf.SetAccessID(accessID)
if err != nil {
return nil, err
}
err = conf.SetSecretAccessKey(secretAccessKey)
conf.SetResultPollIntervalSeconds(PoolInterval)
return conf, err
}
// NewNoOpsConfig is to create a noop version of driver Config WITHOUT credentials.
func NewNoOpsConfig() *Config {
a := Config{
dsn: url.URL{},
}
a.dsn.Scheme = "s3"
a.values = make(map[string][]string, 32)
a.values.Set("db", DefaultDBName)
a.values.Set("region", DefaultRegion)
a.SetMissingAsEmptyString(true)
a.SetWGRemoteCreationAllowed(true)
return &a
}
// NewConfig is to create Config from a string.
func NewConfig(s string) (*Config, error) {
u, err := url.Parse(s)
if err != nil {
return nil, err
}
a := Config{
dsn: *u,
}
a.values, err = url.ParseQuery(u.RawQuery)
if !a.isValid() {
return nil, ErrConfigInvalidConfig
}
return &a, err
}
func (c *Config) isValid() bool {
return c.dsn.Scheme == "s3" && c.values.Get("region") != ""
}
// String is to return the string form of DSN.
func (c *Config) String() string {
return c.dsn.String()
}
// Stringify is to return the string form of DSN like JSON.stringify().
// Please refer to: https://www.w3schools.com/js/js_json_stringify.asp
func (c *Config) Stringify() string {
c.dsn.RawQuery = c.values.Encode()
return c.String()
}
// SafeStringify is a secure version of Stringify(), with security information masked with *.
func (c *Config) SafeStringify() string {
rawString := c.Stringify()
s := reSecretAccessKey.ReplaceAllString(rawString, `secretAccessKey=*`)
s = reAccessID.ReplaceAllString(s, `accessID=*`)
s = reSessionToken.ReplaceAllString(s, `sessionToken=*`)
return s
}
// SetOutputBucket is to set S3 bucket for result set.
// On March 1, 2018, we updated our naming conventions for S3 buckets in the US East (N. Virginia) Region to match
// the naming conventions that we use in all other worldwide AWS Regions.
// Amazon S3 no longer supports creating bucket names that contain uppercase letters or underscores.
// https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules
func (c *Config) SetOutputBucket(o string) error {
if !strings.HasPrefix(o, "s3://") {
return ErrConfigOutputLocation
}
o = o[5:]
ss := strings.SplitN(o, "/", 2)
if len(ss) == 2 {
c.dsn.Host = ss[0]
c.dsn.Path = ss[1]
} else {
c.dsn.Host = ss[0]
c.dsn.Path = ""
}
return nil
}
// SetRegion is to set region.
func (c *Config) SetRegion(o string) error {
if len(o) == 0 {
return ErrConfigRegion
}
c.values.Set("region", o)
return nil
}
// GetRegion is getter of Region.
func (c *Config) GetRegion() string {
if val := c.values.Get("region"); val != "" {
return val
}
return GetFromEnvVal(regionEnvKeys)
}
// SetUser is a setter of User.
func (c *Config) SetUser(o string) {
c.dsn.User = url.UserPassword(o, "")
}
// SetDB is a setter of DB.
func (c *Config) SetDB(o string) {
c.values.Set("db", o)
}
// GetDB is getter of DB.
func (c *Config) GetDB() string {
if val := c.values.Get("db"); val != "" {
return val
}
return DefaultDBName
}
// SetResultPollIntervalSeconds is a setter of Overriding poll interval.
func (c *Config) SetResultPollIntervalSeconds(n int) {
c.values.Set("resultPollIntervalSeconds", strconv.Itoa(n))
}
// GetResultPollIntervalSeconds is getter of resultPollIntervalSeconds.
func (c *Config) GetResultPollIntervalSeconds() time.Duration {
if val := c.values.Get("resultPollIntervalSeconds"); val != "" {
n, err := strconv.Atoi(val)
if err != nil {
return time.Duration(PoolInterval) * time.Second
}
return time.Duration(n) * time.Second
}
return time.Duration(PoolInterval) * time.Second
}
// SetWorkGroup is a setter of WorkGroup.
func (c *Config) SetWorkGroup(w *Workgroup) error {
if w == nil {
return ErrConfigWGPointer
}
c.values.Set("workgroupName", w.Name)
if w.Tags != nil {
tagsString := c.values.Get("tag")
for _, tag := range w.Tags.Get() {
tagsString += "|" + *tag.Key + "`" + *tag.Value
}
c.values.Set("tag", tagsString)
}
if w.Config == nil {
w.Config = GetDefaultWGConfig()
}
c.values.Set("workgroupConfig", w.Config.String())
return nil
}
// SetAccessID is a setter of AWS Access ID.
func (c *Config) SetAccessID(o string) error {
if len(o) == 0 {
return ErrConfigAccessIDRequired
}
c.values.Set("accessID", o)
return nil
}
// GetAccessID is a getter of AWS Access ID. It will try to get access ID from:
// 1. string stored in c.values
// 2. environmental variable ${AWS_ACCESS_KEY_ID} or ${AWS_ACCESS_KEY}
func (c *Config) GetAccessID() string {
if val := c.values.Get("accessID"); val != "" {
return val
}
return GetFromEnvVal(credAccessEnvKey)
}
// SetSecretAccessKey is a setter of AWS Access Key.
func (c *Config) SetSecretAccessKey(o string) error {
if len(o) == 0 {
return ErrConfigAccessKeyRequired
}
c.values.Set("secretAccessKey", o)
return nil
}
// GetSecretAccessKey is a getter of AWS Access Key.
func (c *Config) GetSecretAccessKey() string {
if val := c.values.Get("secretAccessKey"); val != "" {
return val
}
return GetFromEnvVal(credSecretEnvKey)
}
// SetSessionToken is a setter of AWS Session Token.
func (c *Config) SetSessionToken(o string) {
c.values.Set("sessionToken", o)
}
// GetSessionToken is a getter of AWS Session Token.
func (c *Config) GetSessionToken() string {
if val := c.values.Get("sessionToken"); val != "" {
return val
}
return GetFromEnvVal(credSessionEnvKey)
}
// GetUser is getter of User.
func (c *Config) GetUser() string {
return c.dsn.User.Username()
}
// GetOutputBucket is getter of OutputBucket.
func (c *Config) GetOutputBucket() string {
if strings.HasPrefix(c.dsn.Path, "/") {
return c.dsn.Scheme + "://" + c.dsn.Host + c.dsn.Path
}
return c.dsn.Scheme + "://" + c.dsn.Host + "/" + c.dsn.Path
}
// GetWorkgroup is getter of Workgroup.
func (c *Config) GetWorkgroup() Workgroup {
tagString := c.values.Get("tag")
if len(tagString) == 0 {
wg := Workgroup{
Name: c.values.Get("workgroupName"),
Config: GetDefaultWGConfig(),
}
return wg
}
tags := strings.Split(tagString[1:], "|")
t := NewWGTags()
for _, tag := range tags {
ts := strings.Split(tag, "`")
t.AddTag(ts[0], ts[1])
}
wg := Workgroup{
Name: c.values.Get("workgroupName"),
Config: GetDefaultWGConfig(),
Tags: t,
}
return wg
}
// IsMissingAsEmptyString return true if missing value is set to be returned as empty string.
func (c *Config) IsMissingAsEmptyString() bool {
return c.values.Get("missingAsEmptyString") == "true"
}
// IsMissingAsDefault return true if missing value is set to be returned as default data.
func (c *Config) IsMissingAsDefault() bool {
return c.values.Get("missingAsDefault") == "true"
}
// IsMissingAsNil return true if missing value is set to be returned as nil.
func (c *Config) IsMissingAsNil() bool {
return c.values.Get("missingAsNil") == "true"
}
// SetMissingAsEmptyString is to set if missing value is returned as empty string.
func (c *Config) SetMissingAsEmptyString(b bool) {
missingAsEmptyString := "true"
if !b {
missingAsEmptyString = "false"
}
c.values.Set("missingAsEmptyString", missingAsEmptyString)
}
// SetMissingAsDefault is to set if missing value is returned as default data.
func (c *Config) SetMissingAsDefault(b bool) {
if b {
c.values.Set("missingAsDefault", "true")
} else {
c.values.Set("missingAsDefault", "false")
}
}
// SetMissingAsNil is to set if missing value is returned as nil.
func (c *Config) SetMissingAsNil(b bool) {
if b {
c.values.Set("missingAsNil", "true")
} else {
c.values.Set("missingAsNil", "false")
}
}
// CheckColumnMasked is to check if a specific column has been masked by some value.
// https://stackoverflow.com/questions/30285169/replace-the-empty-or-null-value-with-specific-value-in-hive-query-result/30289503
func (c *Config) CheckColumnMasked(columnName string) (string, bool) {
if val, ok := c.values["masked_"+columnName]; ok {
return val[0], true
}
return "", false
}
// SetMaskedColumnValue is to set masked value for some column.
func (c *Config) SetMaskedColumnValue(columnName string, value string) {
c.values.Set("masked_"+columnName, value)
}
// IsWGRemoteCreationAllowed is to check if we are allowed to create workgroup with API from client.
func (c *Config) IsWGRemoteCreationAllowed() bool {
return c.values.Get("WGRemoteCreation") == "true"
}
// SetWGRemoteCreationAllowed is to set if we are allowed to create workgroup with API from client.
func (c *Config) SetWGRemoteCreationAllowed(b bool) {
if b {
c.values.Set("WGRemoteCreation", "true")
} else {
c.values.Set("WGRemoteCreation", "false")
}
}
// IsLoggingEnabled is to check if driver level logging enabled.
func (c *Config) IsLoggingEnabled() bool {
return c.values.Get("LoggingEnabled") != "false"
}
// SetLogging is to set if driver level logging enabled.
func (c *Config) SetLogging(b bool) {
if b {
c.values.Set("LoggingEnabled", "true")
} else {
c.values.Set("LoggingEnabled", "false")
}
}
// IsMetricsEnabled is to check if driver level metrics enabled.
func (c *Config) IsMetricsEnabled() bool {
return c.values.Get("MetricsEnabled") == "true"
}
// SetMetrics is to set if driver level logging enabled.
func (c *Config) SetMetrics(b bool) {
if b {
c.values.Set("MetricsEnabled", "true")
} else {
c.values.Set("MetricsEnabled", "false")
}
}
// SetReadOnly is to set if only SELECT/SHOW/DESC are allowed
func (c *Config) SetReadOnly(b bool) {
if b {
c.values.Set("ReadOnly", "true")
} else {
c.values.Set("ReadOnly", "false")
}
}
// IsReadOnly is to check if only SELECT/SHOW/DESC are allowed
func (c *Config) IsReadOnly() bool {
return c.values.Get("ReadOnly") == "true"
}
// SetMoneyWise is to set if we are in the moneywise mode
func (c *Config) SetMoneyWise(b bool) {
if b {
c.values.Set("MoneyWise", "true")
} else {
c.values.Set("MoneyWise", "false")
}
}
// IsMoneyWise is to check if we are in the moneywise mode
func (c *Config) IsMoneyWise() bool {
return c.values.Get("MoneyWise") == "true"
}
// SetAWSProfile is to manually set the credential provider
// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html
func (c *Config) SetAWSProfile(profile string) {
c.values.Set("AWSProfile", profile)
}
// GetAWSProfile is to get the credential provider name manually set by user
func (c *Config) GetAWSProfile() string {
return c.values.Get("AWSProfile")
}
// SetServiceLimitOverride is to set values from a ServiceLimitOverride
func (c *Config) SetServiceLimitOverride(serviceLimitOverride ServiceLimitOverride) {
for k, v := range serviceLimitOverride.GetAsStringMap() {
c.values.Set(k, v)
}
}
// GetServiceLimitOverride is to get the ServiceLimitOverride manually set by a user
func (c *Config) GetServiceLimitOverride() *ServiceLimitOverride {
serviceLimitOverride := NewServiceLimitOverride()
serviceLimitOverride.SetFromValues(c.values)
return serviceLimitOverride
}