-
Notifications
You must be signed in to change notification settings - Fork 342
/
setup.go
163 lines (138 loc) · 5.04 KB
/
setup.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
package testutil
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/deepmap/oapi-codegen/pkg/securityprovider"
"github.com/rs/xid"
"github.com/spf13/viper"
"github.com/treeverse/lakefs/pkg/api"
"github.com/treeverse/lakefs/pkg/logging"
)
const defaultSetupTimeout = 5 * time.Minute
type SetupTestingEnvParams struct {
Name string
StorageNS string
// Only if non-empty
AdminAccessKeyID string
AdminSecretAccessKey string
}
func SetupTestingEnv(params *SetupTestingEnvParams) (logging.Logger, api.ClientWithResponsesInterface, *s3.S3) {
logger := logging.Default()
viper.SetDefault("setup_lakefs", true)
viper.SetDefault("setup_lakefs_timeout", defaultSetupTimeout)
viper.SetDefault("endpoint_url", "http://localhost:8000")
viper.SetDefault("s3_endpoint", "s3.local.lakefs.io:8000")
viper.SetDefault("access_key_id", "")
viper.SetDefault("secret_access_key", "")
viper.SetDefault("storage_namespace", fmt.Sprintf("s3://%s/%s", params.StorageNS, xid.New().String()))
viper.SetDefault("version", "dev")
viper.SetDefault("lakectl_dir", "..")
viper.AddConfigPath(".")
viper.SetEnvPrefix(strings.ToUpper(params.Name))
viper.SetConfigName(strings.ToLower(params.Name))
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil && !errors.As(err, &viper.ConfigFileNotFoundError{}) {
logger.WithError(err).Fatal("Failed to read configuration")
}
ctx := context.Background()
// initialize the env/repo
logger = logging.Default()
logger.WithField("settings", viper.AllSettings()).Info(fmt.Sprintf("Starting %s", params.Name))
endpointURL := ParseEndpointURL(logger, viper.GetString("endpoint_url"))
client, err := api.NewClientWithResponses(endpointURL)
if err != nil {
logger.WithError(err).Fatal("could not initialize API client")
}
if err := waitUntilLakeFSRunning(ctx, logger, client); err != nil {
logger.WithError(err).Fatal("Waiting for lakeFS")
}
setupLakeFS := viper.GetBool("setup_lakefs")
if setupLakeFS {
// first setup of lakeFS
adminUserName := params.Name
requestBody := api.SetupJSONRequestBody{
Username: adminUserName,
}
if params.AdminAccessKeyID != "" || params.AdminSecretAccessKey != "" {
requestBody.Key = &api.AccessKeyCredentials{
AccessKeyId: params.AdminAccessKeyID,
SecretAccessKey: params.AdminSecretAccessKey,
}
}
res, err := client.SetupWithResponse(ctx, requestBody)
if err != nil {
logger.WithError(err).Fatal("Failed to setup lakeFS")
}
if res.StatusCode() != http.StatusOK {
logger.WithField("status", res.HTTPResponse.Status).Fatal("Failed to setup lakeFS")
}
logger.Info("Cluster setup successfully")
credentialsWithSecret := res.JSON200
viper.Set("access_key_id", credentialsWithSecret.AccessKeyId)
viper.Set("secret_access_key", credentialsWithSecret.SecretAccessKey)
}
client, err = NewClientFromCreds(logger, viper.GetString("access_key_id"), viper.GetString("secret_access_key"), endpointURL)
if err != nil {
logger.WithError(err).Fatal("could not initialize API client with security provider")
}
s3Endpoint := viper.GetString("s3_endpoint")
awsSession := session.Must(session.NewSession())
svc := s3.New(awsSession,
aws.NewConfig().
WithRegion("us-east-1").
WithEndpoint(s3Endpoint).
WithDisableSSL(true).
WithCredentials(credentials.NewCredentials(
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: viper.GetString("access_key_id"),
SecretAccessKey: viper.GetString("secret_access_key"),
}})))
return logger, client, svc
}
// Parses the given endpoint string
func ParseEndpointURL(logger logging.Logger, endpointURL string) string {
u, err := url.Parse(endpointURL)
if err != nil {
logger.WithError(err).Fatal("could not initialize API client with security provider")
}
if u.Path == "" || u.Path == "/" {
endpointURL = strings.TrimRight(endpointURL, "/") + api.BaseURL
}
return endpointURL
}
// Creates a client using the credentials of a user
func NewClientFromCreds(logger logging.Logger, accessKeyID string, secretAccessKey string, endpointURL string) (*api.ClientWithResponses, error) {
basicAuthProvider, err := securityprovider.NewSecurityProviderBasicAuth(accessKeyID, secretAccessKey)
if err != nil {
logger.WithError(err).Fatal("could not initialize basic auth security provider")
}
return api.NewClientWithResponses(endpointURL, api.WithRequestEditorFn(basicAuthProvider.Intercept))
}
const checkIteration = 5 * time.Second
func waitUntilLakeFSRunning(ctx context.Context, logger logging.Logger, cl api.ClientWithResponsesInterface) error {
setupCtx, cancel := context.WithTimeout(ctx, viper.GetDuration("setup_lakefs_timeout"))
defer cancel()
for {
_, err := cl.HealthCheckWithResponse(setupCtx)
if err == nil {
return nil
}
logger.WithError(err).Info("Setup failed")
select {
case <-setupCtx.Done():
return setupCtx.Err()
case <-time.After(checkIteration):
}
}
}