Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: clean more connection config (#15462)

Danny Xu357647ad90ef
diff --git a/backend/component/dbfactory/dbfactory.go b/backend/component/dbfactory/dbfactory.go
index 70a93b0fb1..993cec0556 100644
--- a/backend/component/dbfactory/dbfactory.go
+++ b/backend/component/dbfactory/dbfactory.go
@@ -14,20 +14,14 @@ import (
// DBFactory is the factory for building database driver.
type DBFactory struct {
- mysqlBinDir string
- pgBinDir string
mongoBinDir string
- dataDir string
store *store.Store
}
// New creates a new database driver factory.
-func New(store *store.Store, mysqlBinDir, mongoBinDir, pgBinDir, dataDir string) *DBFactory {
+func New(store *store.Store, mongoBinDir string) *DBFactory {
return &DBFactory{
- mysqlBinDir: mysqlBinDir,
mongoBinDir: mongoBinDir,
- pgBinDir: pgBinDir,
- dataDir: dataDir,
store: store,
}
}
@@ -48,12 +42,7 @@ func (d *DBFactory) GetAdminDatabaseDriver(ctx context.Context, instance *store.
// GetDataSourceDriver returns the database driver for a data source.
func (d *DBFactory) GetDataSourceDriver(ctx context.Context, instance *store.InstanceMessage, dataSource *storepb.DataSource, connectionContext db.ConnectionContext) (db.Driver, error) {
dbBinDir := ""
- switch instance.Metadata.GetEngine() {
- case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:
- dbBinDir = d.mysqlBinDir
- case storepb.Engine_POSTGRES, storepb.Engine_RISINGWAVE:
- dbBinDir = d.pgBinDir
- case storepb.Engine_MONGODB:
+ if instance.Metadata.GetEngine() == storepb.Engine_MONGODB {
dbBinDir = d.mongoBinDir
}
@@ -61,13 +50,6 @@ func (d *DBFactory) GetDataSourceDriver(ctx context.Context, instance *store.Ins
if err != nil {
return nil, err
}
- sshConfig := db.SSHConfig{
- Host: dataSource.GetSshHost(),
- Port: dataSource.GetSshPort(),
- User: dataSource.GetSshUser(),
- Password: dataSource.GetSshPassword(),
- PrivateKey: dataSource.GetSshPrivateKey(),
- }
var dbSaslConfig db.SASLConfig
switch t := dataSource.GetSaslConfig().GetMechanism().(type) {
case *storepb.SASLConfig_KrbConfig:
@@ -100,32 +82,8 @@ func (d *DBFactory) GetDataSourceDriver(ctx context.Context, instance *store.Ins
ConnectionContext: connectionContext,
Password: password,
- TLSConfig: db.TLSConfig{
- UseSSL: dataSource.GetUseSsl(),
- SslCA: dataSource.GetSslCa(),
- SslCert: dataSource.GetSslCert(),
- SslKey: dataSource.GetSslKey(),
- },
- SRV: dataSource.GetSrv(),
- AuthenticationDatabase: dataSource.GetAuthenticationDatabase(),
- SID: dataSource.GetSid(),
- ServiceName: dataSource.ServiceName,
- SSHConfig: sshConfig,
- AuthenticationPrivateKey: dataSource.GetAuthenticationPrivateKey(),
- AuthenticationType: dataSource.GetAuthenticationType(),
- SASLConfig: dbSaslConfig,
- AdditionalAddresses: dataSource.GetAdditionalAddresses(),
- ReplicaSet: dataSource.GetReplicaSet(),
- DirectConnection: dataSource.GetDirectConnection(),
- Region: dataSource.GetRegion(),
- WarehouseID: dataSource.GetWarehouseId(),
- RedisType: dataSource.GetRedisType(),
- MasterName: dataSource.GetMasterName(),
- MasterUsername: dataSource.GetMasterUsername(),
- MasterPassword: dataSource.GetMasterPassword(),
- ExtraConnectionParameters: dataSource.GetExtraConnectionParameters(),
- MaximumSQLResultSize: maximumSQLResultSize,
- ClientSecretCredential: dataSource.GetClientSecretCredential(),
+ SASLConfig: dbSaslConfig,
+ MaximumSQLResultSize: maximumSQLResultSize,
},
)
if err != nil {
diff --git a/backend/plugin/db/bigquery/bigquery.go b/backend/plugin/db/bigquery/bigquery.go
index 1ed80ca58e..51e753c505 100644
--- a/backend/plugin/db/bigquery/bigquery.go
+++ b/backend/plugin/db/bigquery/bigquery.go
@@ -56,7 +56,7 @@ func (d *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Connectio
d.databaseName = config.ConnectionContext.DatabaseName
var o []option.ClientOption
- if config.AuthenticationType != storepb.DataSource_GOOGLE_CLOUD_SQL_IAM {
+ if config.DataSource.GetAuthenticationType() != storepb.DataSource_GOOGLE_CLOUD_SQL_IAM {
o = append(o, option.WithCredentialsJSON([]byte(config.Password)))
}
client, err := bigquery.NewClient(ctx, config.DataSource.Host, o...)
diff --git a/backend/plugin/db/clickhouse/clickhouse.go b/backend/plugin/db/clickhouse/clickhouse.go
index 0db9252f3e..7c32d96702 100644
--- a/backend/plugin/db/clickhouse/clickhouse.go
+++ b/backend/plugin/db/clickhouse/clickhouse.go
@@ -60,8 +60,7 @@ func newDriver(db.DriverConfig) db.Driver {
// Open opens a ClickHouse driver.
func (driver *Driver) Open(_ context.Context, dbType storepb.Engine, config db.ConnectionConfig) (db.Driver, error) {
addr := fmt.Sprintf("%s:%s", config.DataSource.Host, config.DataSource.Port)
- // Set SSL configuration.
- tlsConfig, err := config.TLSConfig.GetSslConfig()
+ tlsConfig, err := db.GetTLSConfig(config.DataSource)
if err != nil {
return nil, errors.Wrap(err, "sql: tls config error")
}
diff --git a/backend/plugin/db/cockroachdb/cockroachdb.go b/backend/plugin/db/cockroachdb/cockroachdb.go
index 52cd9ed423..892a3f86ed 100644
--- a/backend/plugin/db/cockroachdb/cockroachdb.go
+++ b/backend/plugin/db/cockroachdb/cockroachdb.go
@@ -70,8 +70,8 @@ func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Conn
return nil, err
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
@@ -148,13 +148,13 @@ func getCockroachConnectionConfig(config db.ConnectionConfig) (*pgx.ConnConfig,
return nil, errors.Errorf("port must be set")
}
- if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||
- (config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {
+ if (config.DataSource.GetSslCert() == "" && config.DataSource.GetSslKey() != "") ||
+ (config.DataSource.GetSslCert() != "" && config.DataSource.GetSslKey() == "") {
return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")
}
connStr := fmt.Sprintf("host=%s port=%s", config.DataSource.Host, config.DataSource.Port)
- sslMode := getSSLMode(config.TLSConfig, config.SSHConfig)
+ sslMode := getSSLMode(config.DataSource)
connStr += fmt.Sprintf(" sslmode=%s", sslMode)
routingID := getRoutingIDFromCockroachCloudURL(config.DataSource.Host)
@@ -170,12 +170,12 @@ func getCockroachConnectionConfig(config db.ConnectionConfig) (*pgx.ConnConfig,
connConfig.Config.Password = config.Password
connConfig.Config.Database = config.ConnectionContext.DatabaseName
- cfg, err := config.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(config.DataSource)
if err != nil {
return nil, err
}
- if cfg != nil {
- connConfig.TLSConfig = cfg
+ if tlscfg != nil {
+ connConfig.TLSConfig = tlscfg
}
if config.ConnectionContext.ReadOnly {
connConfig.RuntimeParams["default_transaction_read_only"] = "true"
diff --git a/backend/plugin/db/cockroachdb/util.go b/backend/plugin/db/cockroachdb/util.go
index 99c661a5fc..db162e2d37 100644
--- a/backend/plugin/db/cockroachdb/util.go
+++ b/backend/plugin/db/cockroachdb/util.go
@@ -1,6 +1,8 @@
package cockroachdb
-import "github.com/bytebase/bytebase/backend/plugin/db"
+import (
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
// sslMode is the PGSSLMode type.
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE
@@ -17,12 +19,12 @@ const (
SSLModeVerifyFull sslMode = "verify-full"
)
-func getSSLMode(tlsConfig db.TLSConfig, sshConfig db.SSHConfig) sslMode {
+func getSSLMode(ds *storepb.DataSource) sslMode {
sslMode := SSLModePrefer
- if tlsConfig.UseSSL {
+ if ds.GetUseSsl() {
sslMode = SSLModeVerifyFull
- if tlsConfig.SslCA != "" {
- if sshConfig.Host != "" {
+ if ds.GetSslCa() != "" {
+ if ds.GetSshHost() != "" {
sslMode = SSLModeVerifyCA
}
}
diff --git a/backend/plugin/db/cosmosdb/cosmosdb.go b/backend/plugin/db/cosmosdb/cosmosdb.go
index c2a489e4db..5cccafdaca 100644
--- a/backend/plugin/db/cosmosdb/cosmosdb.go
+++ b/backend/plugin/db/cosmosdb/cosmosdb.go
@@ -43,7 +43,7 @@ func newDriver(_ db.DriverConfig) db.Driver {
func (driver *Driver) Open(_ context.Context, _ storepb.Engine, connCfg db.ConnectionConfig) (db.Driver, error) {
endpoint := connCfg.DataSource.Host
var credential azcore.TokenCredential
- if clientSecretCredential := connCfg.ClientSecretCredential; clientSecretCredential != nil {
+ if clientSecretCredential := connCfg.DataSource.GetClientSecretCredential(); clientSecretCredential != nil {
c, err := azidentity.NewClientSecretCredential(clientSecretCredential.TenantId, clientSecretCredential.ClientId, clientSecretCredential.ClientSecret, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to create client secret credential")
diff --git a/backend/plugin/db/databricks/databricks.go b/backend/plugin/db/databricks/databricks.go
index 052d909857..08baa6bf4a 100644
--- a/backend/plugin/db/databricks/databricks.go
+++ b/backend/plugin/db/databricks/databricks.go
@@ -44,17 +44,17 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
// only support token authentication.
client, err := databricks.NewWorkspaceClient(&databricks.Config{
Host: config.DataSource.Host,
- Token: config.AuthenticationPrivateKey,
+ Token: config.DataSource.GetAuthenticationPrivateKey(),
})
if err != nil {
return nil, err
}
d.Client = client
- if config.WarehouseID == "" {
+ if config.DataSource.GetWarehouseId() == "" {
return nil, errors.New("Warehouse ID must be set")
}
- d.WarehouseID = config.WarehouseID
+ d.WarehouseID = config.DataSource.GetWarehouseId()
d.curCatalog = config.ConnectionContext.DatabaseName
return d, nil
}
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index 067d55c2e5..c536a05dd2 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -146,57 +146,11 @@ type ConnectionConfig struct {
ConnectionContext ConnectionContext
Password string
- TLSConfig TLSConfig
// Only used for Hive.
SASLConfig SASLConfig
- // SRV is only supported for MongoDB now.
- SRV bool
- // AuthenticationDatabase is only supported for MongoDB now.
- AuthenticationDatabase string
- // SID and ServiceName are Oracle only.
- SID string
- ServiceName string
- SSHConfig SSHConfig
- // AuthenticationPrivateKey is used by Snowflake and Databricks (databricks access token).
- AuthenticationPrivateKey string
-
- // AuthenticationType is for the database connection, we support normal username & password or Google IAM.
- AuthenticationType storepb.DataSource_AuthenticationType
-
- // AdditionalAddresses and ReplicaSet name are used for MongoDB.
- AdditionalAddresses []*storepb.DataSource_Address
- ReplicaSet string
- DirectConnection bool
-
- // Region is the location of where the DB is, works for AWS RDS.
- Region string
-
- // WarehouseID is used by Databricks.
- WarehouseID string
-
- RedisType storepb.DataSource_RedisType
- MasterName string
- MasterUsername string
- MasterPassword string
-
- // ExtraConnectionParameters contains additional parameters to include in connection strings
- // For example, "target_session_attrs=read-write" for Postgres HA clusters
- ExtraConnectionParameters map[string]string
// The maximum number of bytes for sql results in response body.
MaximumSQLResultSize int64
-
- // At most one of the following could be set.
- ClientSecretCredential *storepb.DataSource_ClientSecretCredential
-}
-
-// SSHConfig is the configuration for connection over SSH.
-type SSHConfig struct {
- Host string
- Port string
- User string
- Password string
- PrivateKey string
}
// ConnectionContext is the context for connection.
diff --git a/backend/plugin/db/elasticsearch/elasticsearch.go b/backend/plugin/db/elasticsearch/elasticsearch.go
index dbb604654b..635f030074 100644
--- a/backend/plugin/db/elasticsearch/elasticsearch.go
+++ b/backend/plugin/db/elasticsearch/elasticsearch.go
@@ -78,7 +78,7 @@ func (*Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionCon
u, err := url.Parse(address)
if err != nil || u.Host == "" {
protocol := "http"
- if config.TLSConfig.UseSSL {
+ if config.DataSource.GetUseSsl() {
protocol = "https"
}
address = fmt.Sprintf("%s://%s", protocol, address)
@@ -111,12 +111,12 @@ func (*Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionCon
},
}
- if config.TLSConfig.SslCert != "" {
+ if config.DataSource.GetSslCert() != "" {
certPool := x509.NewCertPool()
- if ok := certPool.AppendCertsFromPEM([]byte(config.TLSConfig.SslCert)); !ok {
+ if ok := certPool.AppendCertsFromPEM([]byte(config.DataSource.GetSslCert())); !ok {
return nil, errors.New("cannot add CA cert to pool")
}
- esConfig.CACert = []byte(config.TLSConfig.SslCert)
+ esConfig.CACert = []byte(config.DataSource.GetSslCert())
esConfig.Transport = &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Second,
diff --git a/backend/plugin/db/elasticsearch/role.go b/backend/plugin/db/elasticsearch/role.go
index 738e3ae5ee..d31c2b3cea 100644
--- a/backend/plugin/db/elasticsearch/role.go
+++ b/backend/plugin/db/elasticsearch/role.go
@@ -52,7 +52,7 @@ func (d *Driver) getInstanceRoles() ([]*storepb.InstanceRole, error) {
func (d *Driver) getUserPrivileges(usrName string) (string, error) {
header := http.Header{}
- header.Add("Authorization", d.config.AuthenticationPrivateKey)
+ header.Add("Authorization", d.config.DataSource.GetAuthenticationPrivateKey())
header.Add("es-security-runas-user", usrName)
resp, err := esapi.SecurityGetUserPrivilegesRequest{Header: header}.Do(context.Background(), d.typedClient)
if err != nil {
diff --git a/backend/plugin/db/mongodb/mongodb.go b/backend/plugin/db/mongodb/mongodb.go
index 4c6fe12894..db9e6dc13a 100644
--- a/backend/plugin/db/mongodb/mongodb.go
+++ b/backend/plugin/db/mongodb/mongodb.go
@@ -52,14 +52,14 @@ func newDriver(dc db.DriverConfig) db.Driver {
func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, connCfg db.ConnectionConfig) (db.Driver, error) {
connectionURI := getBasicMongoDBConnectionURI(connCfg)
opts := options.Client().ApplyURI(connectionURI)
- tlsConfig, err := connCfg.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(connCfg.DataSource)
if err != nil {
return nil, errors.Wrap(err, "failed to get SSL config")
}
- if tlsConfig != nil {
+ if tlscfg != nil {
// TODO(zp): User uses ssh tunnel?
- tlsConfig.InsecureSkipVerify = true
- opts.SetTLSConfig(tlsConfig)
+ tlscfg.InsecureSkipVerify = true
+ opts.SetTLSConfig(tlscfg)
}
client, err := mongo.Connect(ctx, opts)
if err != nil {
@@ -111,12 +111,12 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ db.Execut
"--quiet",
}
- if driver.connCfg.TLSConfig.UseSSL {
+ if driver.connCfg.DataSource.GetUseSsl() {
mongoshArgs = append(mongoshArgs, "--tls")
mongoshArgs = append(mongoshArgs, "--tlsAllowInvalidHostnames")
uuid := uuid.New().String()
- if driver.connCfg.TLSConfig.SslCA == "" {
+ if driver.connCfg.DataSource.GetSslCa() == "" {
mongoshArgs = append(mongoshArgs, "--tlsUseSystemCA")
} else {
// Write the tlsCAFile to a temporary file, and use the temporary file as the value of --tlsCAFile.
@@ -126,26 +126,26 @@ func (driver *Driver) Execute(ctx context.Context, statement string, _ db.Execut
// While error occurred in mongosh, the temporary file may not created, so we ignore the error here.
_ = os.Remove(caFileName)
}()
- if err := os.WriteFile(caFileName, []byte(driver.connCfg.TLSConfig.SslCA), 0400); err != nil {
+ if err := os.WriteFile(caFileName, []byte(driver.connCfg.DataSource.GetSslCa()), 0400); err != nil {
return 0, errors.Wrap(err, "failed to write tlsCAFile to temporary file")
}
mongoshArgs = append(mongoshArgs, "--tlsCAFile", caFileName)
}
- if driver.connCfg.TLSConfig.SslKey != "" && driver.connCfg.TLSConfig.SslCert != "" {
+ if driver.connCfg.DataSource.GetSslKey() != "" && driver.connCfg.DataSource.GetSslCert() != "" {
clientCertName := fmt.Sprintf("mongodb-tls-client-cert-%s-%s", driver.connCfg.ConnectionContext.DatabaseName, uuid)
defer func() {
// While error occurred in mongosh, the temporary file may not created, so we ignore the error here.
_ = os.Remove(clientCertName)
}()
var sb strings.Builder
- if _, err := sb.WriteString(driver.connCfg.TLSConfig.SslKey); err != nil {
+ if _, err := sb.WriteString(driver.connCfg.DataSource.GetSslKey()); err != nil {
return 0, errors.Wrapf(err, "failed to write ssl key into string builder")
}
if _, err := sb.WriteString("\n"); err != nil {
return 0, errors.Wrapf(err, "failed to write new line into string builder")
}
- if _, err := sb.WriteString(driver.connCfg.TLSConfig.SslCert); err != nil {
+ if _, err := sb.WriteString(driver.connCfg.DataSource.GetSslCert()); err != nil {
return 0, errors.Wrapf(err, "failed to write ssl cert into string builder")
}
if err := os.WriteFile(clientCertName, []byte(sb.String()), 0400); err != nil {
@@ -194,7 +194,7 @@ func getBasicMongoDBConnectionURI(connConfig db.ConnectionConfig) string {
// For mongosh, it can handle this case correctly, but for driver, it will throw the error likes "error parsing uri: must have a / before the query ?".
Path: "/",
}
- if connConfig.SRV {
+ if connConfig.DataSource.GetSrv() {
u.Scheme = "mongodb+srv"
}
if connConfig.DataSource.Username != "" {
@@ -204,7 +204,7 @@ func getBasicMongoDBConnectionURI(connConfig db.ConnectionConfig) string {
if connConfig.DataSource.Port != "" {
u.Host = fmt.Sprintf("%s:%s", u.Host, connConfig.DataSource.Port)
}
- for _, additionalAddress := range connConfig.AdditionalAddresses {
+ for _, additionalAddress := range connConfig.DataSource.GetAdditionalAddresses() {
address := additionalAddress.Host
if additionalAddress.Port != "" {
address = fmt.Sprintf("%s:%s", address, additionalAddress.Port)
@@ -215,17 +215,17 @@ func getBasicMongoDBConnectionURI(connConfig db.ConnectionConfig) string {
u.Path = connConfig.ConnectionContext.DatabaseName
}
authDatabase := "admin"
- if connConfig.AuthenticationDatabase != "" {
- authDatabase = connConfig.AuthenticationDatabase
+ if connConfig.DataSource.GetAuthenticationDatabase() != "" {
+ authDatabase = connConfig.DataSource.GetAuthenticationDatabase()
}
values := u.Query()
values.Add("authSource", authDatabase)
- if connConfig.ReplicaSet != "" {
- values.Add("replicaSet", connConfig.ReplicaSet)
+ if connConfig.DataSource.GetReplicaSet() != "" {
+ values.Add("replicaSet", connConfig.DataSource.GetReplicaSet())
}
values.Add("appName", "bytebase")
- if connConfig.DirectConnection {
+ if connConfig.DataSource.GetDirectConnection() {
values.Add("directConnection", "true")
}
u.RawQuery = values.Encode()
@@ -273,12 +273,12 @@ func (driver *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement stri
"false",
}
- if driver.connCfg.TLSConfig.UseSSL {
+ if driver.connCfg.DataSource.GetUseSsl() {
mongoshArgs = append(mongoshArgs, "--tls")
mongoshArgs = append(mongoshArgs, "--tlsAllowInvalidHostnames")
uuid := uuid.New().String()
- if driver.connCfg.TLSConfig.SslCA == "" {
+ if driver.connCfg.DataSource.GetSslCa() == "" {
mongoshArgs = append(mongoshArgs, "--tlsUseSystemCA")
} else {
// Write the tlsCAFile to a temporary file, and use the temporary file as the value of --tlsCAFile.
@@ -288,26 +288,26 @@ func (driver *Driver) QueryConn(ctx context.Context, _ *sql.Conn, statement stri
// While error occurred in mongosh, the temporary file may not created, so we ignore the error here.
_ = os.Remove(caFileName)
}()
- if err := os.WriteFile(caFileName, []byte(driver.connCfg.TLSConfig.SslCA), 0400); err != nil {
+ if err := os.WriteFile(caFileName, []byte(driver.connCfg.DataSource.GetSslCa()), 0400); err != nil {
return nil, errors.Wrap(err, "failed to write tlsCAFile to temporary file")
}
mongoshArgs = append(mongoshArgs, "--tlsCAFile", caFileName)
}
- if driver.connCfg.TLSConfig.SslKey != "" && driver.connCfg.TLSConfig.SslCert != "" {
+ if driver.connCfg.DataSource.GetSslKey() != "" && driver.connCfg.DataSource.GetSslCert() != "" {
clientCertName := fmt.Sprintf("mongodb-tls-client-cert-%s-%s", driver.connCfg.ConnectionContext.DatabaseName, uuid)
defer func() {
// While error occurred in mongosh, the temporary file may not created, so we ignore the error here.
_ = os.Remove(clientCertName)
}()
var sb strings.Builder
- if _, err := sb.WriteString(driver.connCfg.TLSConfig.SslKey); err != nil {
+ if _, err := sb.WriteString(driver.connCfg.DataSource.GetSslKey()); err != nil {
return nil, errors.Wrapf(err, "failed to write ssl key into string builder")
}
if _, err := sb.WriteString("\n"); err != nil {
return nil, errors.Wrapf(err, "failed to write new line into string builder")
}
- if _, err := sb.WriteString(driver.connCfg.TLSConfig.SslCert); err != nil {
+ if _, err := sb.WriteString(driver.connCfg.DataSource.GetSslCert()); err != nil {
return nil, errors.Wrapf(err, "failed to write ssl cert into string builder")
}
if err := os.WriteFile(clientCertName, []byte(sb.String()), 0400); err != nil {
diff --git a/backend/plugin/db/mongodb/mongodb_test.go b/backend/plugin/db/mongodb/mongodb_test.go
index 7c9850fb49..cc626d1b39 100644
--- a/backend/plugin/db/mongodb/mongodb_test.go
+++ b/backend/plugin/db/mongodb/mongodb_test.go
@@ -9,7 +9,6 @@ import (
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/durationpb"
- "github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/plugin/db"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"
@@ -40,8 +39,7 @@ func TestGetMongoDBConnectionURL(t *testing.T) {
Password: "",
DirectConnection: true,
},
- Password: "",
- DirectConnection: true,
+ Password: "",
},
want: "mongodb://localhost:27017/?appName=bytebase&authSource=admin&directConnection=true",
},
@@ -72,9 +70,7 @@ func TestGetMongoDBConnectionURL(t *testing.T) {
ConnectionContext: db.ConnectionContext{
DatabaseName: "sampleDB",
},
- Password: "passwd",
- SRV: true,
- MaximumSQLResultSize: common.DefaultMaximumSQLResultSize,
+ Password: "passwd",
},
want: "mongodb+srv://bytebase:[email protected]/sampleDB?appName=bytebase&authSource=admin",
},
@@ -91,32 +87,28 @@ func TestGetMongoDBConnectionURL(t *testing.T) {
ConnectionContext: db.ConnectionContext{
DatabaseName: "sampleDB",
},
- Password: "passwd",
- AuthenticationDatabase: "admin",
- SRV: true,
- MaximumSQLResultSize: common.DefaultMaximumSQLResultSize,
+ Password: "passwd",
},
want: "mongodb+srv://bytebase:[email protected]/sampleDB?appName=bytebase&authSource=admin",
},
{
connConfig: db.ConnectionConfig{
DataSource: &storepb.DataSource{
- Host: "node1.cluster0.sample.mongodb.net",
- Port: "27017",
- Username: "bytebase",
- Password: "passwd",
+ Host: "node1.cluster0.sample.mongodb.net",
+ Port: "27017",
+ Username: "bytebase",
+ Password: "passwd",
+ AdditionalAddresses: []*storepb.DataSource_Address{
+ {Host: "node2.cluster0.sample.mongodb.net", Port: "27017"},
+ {Host: "node3.cluster0.sample.mongodb.net", Port: "27017"},
+ },
+ ReplicaSet: "rs0",
AuthenticationDatabase: "admin",
},
ConnectionContext: db.ConnectionContext{
DatabaseName: "sampleDB",
},
Password: "passwd",
- AdditionalAddresses: []*storepb.DataSource_Address{
- {Host: "node2.cluster0.sample.mongodb.net", Port: "27017"},
- {Host: "node3.cluster0.sample.mongodb.net", Port: "27017"},
- },
- ReplicaSet: "rs0",
- MaximumSQLResultSize: common.DefaultMaximumSQLResultSize,
},
want: "mongodb://bytebase:[email protected]:27017,node2.cluster0.sample.mongodb.net:27017,node3.cluster0.sample.mongodb.net:27017/sampleDB?appName=bytebase&authSource=admin&replicaSet=rs0",
},
diff --git a/backend/plugin/db/mssql/mssql.go b/backend/plugin/db/mssql/mssql.go
index 84ace2ad37..420eb15759 100644
--- a/backend/plugin/db/mssql/mssql.go
+++ b/backend/plugin/db/mssql/mssql.go
@@ -66,7 +66,7 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
query.Add("tlsmin", "1.0")
var err error
- if config.TLSConfig.UseSSL && config.TLSConfig.SslCA != "" {
+ if config.DataSource.GetUseSsl() && config.DataSource.GetSslCa() != "" {
// Due to Golang runtime limitation, x509 package will throw the error of 'certificate relies on legacy Common Name field, use SANs instead.
// Driver reads the certificate from file instead of regarding it as certificate content.
// https://github.com/microsoft/go-mssqldb/blob/main/msdsn/conn_str.go#L159
@@ -84,7 +84,7 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
driver.certFilePath = fName
}
}(err)
- _, err = file.WriteString(config.TLSConfig.SslCA)
+ _, err = file.WriteString(config.DataSource.GetSslCa())
if err != nil {
return nil, errors.Wrapf(err, "failed to write certificate to file %s", fName)
}
@@ -97,12 +97,12 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
driverName := "sqlserver"
password := config.Password
- if config.AuthenticationType == storepb.DataSource_AZURE_IAM {
+ if config.DataSource.GetAuthenticationType() == storepb.DataSource_AZURE_IAM {
driverName = azuread.DriverName
- if config.ClientSecretCredential != nil {
+ if config.DataSource.GetClientSecretCredential() != nil {
query.Add("fedauth", azuread.ActiveDirectoryServicePrincipal)
- query.Add("user id", fmt.Sprintf("%s@%s", config.ClientSecretCredential.ClientId, config.ClientSecretCredential.TenantId))
- query.Add("password", config.ClientSecretCredential.ClientSecret)
+ query.Add("user id", fmt.Sprintf("%s@%s", config.DataSource.GetClientSecretCredential().ClientId, config.DataSource.GetClientSecretCredential().TenantId))
+ query.Add("password", config.DataSource.GetClientSecretCredential().ClientSecret)
password = ""
} else {
query.Add("fedauth", azuread.ActiveDirectoryDefault)
diff --git a/backend/plugin/db/mysql/mysql.go b/backend/plugin/db/mysql/mysql.go
index 33939131ac..992ff5ea6d 100644
--- a/backend/plugin/db/mysql/mysql.go
+++ b/backend/plugin/db/mysql/mysql.go
@@ -79,7 +79,7 @@ func (d *Driver) Open(ctx context.Context, dbType storepb.Engine, connCfg db.Con
var dsn string
var err error
- switch connCfg.AuthenticationType {
+ switch connCfg.DataSource.GetAuthenticationType() {
case storepb.DataSource_GOOGLE_CLOUD_SQL_IAM:
dsn, err = getCloudSQLConnection(ctx, connCfg)
case storepb.DataSource_AWS_RDS_IAM:
@@ -115,8 +115,8 @@ func (d *Driver) getMySQLConnection(connCfg db.ConnectionConfig) (string, error)
}
params := []string{"multiStatements=true", "maxAllowedPacket=0"}
- if connCfg.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(connCfg.SSHConfig)
+ if connCfg.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(connCfg.DataSource)
if err != nil {
return "", err
}
@@ -128,13 +128,13 @@ func (d *Driver) getMySQLConnection(connCfg db.ConnectionConfig) (string, error)
protocol = "mysql+tcp"
}
- tlsConfig, err := connCfg.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(connCfg.DataSource)
if err != nil {
return "", errors.Wrap(err, "sql: tls config error")
}
tlsKey := uuid.NewString()
- if tlsConfig != nil {
- if err := mysql.RegisterTLSConfig(tlsKey, tlsConfig); err != nil {
+ if tlscfg != nil {
+ if err := mysql.RegisterTLSConfig(tlsKey, tlscfg); err != nil {
return "", errors.Wrap(err, "sql: failed to register tls config")
}
// TLS config is only used during sql.Open, so should be safe to deregister afterwards.
@@ -193,7 +193,7 @@ func getRDSConnection(ctx context.Context, connCfg db.ConnectionConfig) (string,
}
authenticationToken, err := auth.BuildAuthToken(
- ctx, dbEndpoint, connCfg.Region, connCfg.DataSource.Username, cfg.Credentials)
+ ctx, dbEndpoint, connCfg.DataSource.GetRegion(), connCfg.DataSource.Username, cfg.Credentials)
if err != nil {
return "", errors.Wrap(err, "failed to create authentication token")
}
diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.go
index ca3254f767..ffa7e6e1ba 100644
--- a/backend/plugin/db/oracle/oracle.go
+++ b/backend/plugin/db/oracle/oracle.go
@@ -67,10 +67,10 @@ func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Conn
}
options := make(map[string]string)
options["CONNECTION TIMEOUT"] = "0"
- if config.SID != "" {
- options["SID"] = config.SID
+ if config.DataSource.GetSid() != "" {
+ options["SID"] = config.DataSource.GetSid()
}
- dsn := goora.BuildUrl(config.DataSource.Host, port, config.ServiceName, config.DataSource.Username, config.Password, options)
+ dsn := goora.BuildUrl(config.DataSource.Host, port, config.DataSource.GetServiceName(), config.DataSource.Username, config.Password, options)
db, err := sql.Open("oracle", dsn)
if err != nil {
return nil, err
@@ -82,7 +82,7 @@ func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Conn
}
driver.db = db
driver.databaseName = config.ConnectionContext.DatabaseName
- driver.serviceName = config.ServiceName
+ driver.serviceName = config.DataSource.GetServiceName()
driver.connectionCtx = config.ConnectionContext
driver.maximumSQLResultSize = config.MaximumSQLResultSize
return driver, nil
diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.go
index 6d32902a3f..8c0c3e15bf 100644
--- a/backend/plugin/db/pg/pg.go
+++ b/backend/plugin/db/pg/pg.go
@@ -72,7 +72,7 @@ func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Conn
var pgxConnConfig *pgx.ConnConfig
var err error
- switch config.AuthenticationType {
+ switch config.DataSource.GetAuthenticationType() {
case storepb.DataSource_GOOGLE_CLOUD_SQL_IAM:
pgxConnConfig, err = getCloudSQLConnectionConfig(ctx, config)
case storepb.DataSource_AWS_RDS_IAM:
@@ -88,8 +88,8 @@ func (driver *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Conn
pgxConnConfig.RuntimeParams["default_transaction_read_only"] = "true"
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
@@ -149,18 +149,18 @@ func getPGConnectionConfig(config db.ConnectionConfig) (*pgx.ConnConfig, error)
return nil, errors.Errorf("port must be set")
}
- if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||
- (config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {
+ if (config.DataSource.GetSslCert() == "" && config.DataSource.GetSslKey() != "") ||
+ (config.DataSource.GetSslCert() != "" && config.DataSource.GetSslKey() == "") {
return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")
}
connStr := fmt.Sprintf("host=%s port=%s", config.DataSource.Host, config.DataSource.Port)
- sslMode := getSSLMode(config.TLSConfig, config.SSHConfig)
+ sslMode := getSSLMode(config.DataSource)
connStr += fmt.Sprintf(" sslmode=%s", sslMode)
// Add target_session_attrs=read-write if specified in ExtraConnectionParameters
- if len(config.ExtraConnectionParameters) > 0 {
- for key, value := range config.ExtraConnectionParameters {
+ if len(config.DataSource.GetExtraConnectionParameters()) > 0 {
+ for key, value := range config.DataSource.GetExtraConnectionParameters() {
connStr += fmt.Sprintf(" %s=%s", key, value)
}
}
@@ -173,12 +173,12 @@ func getPGConnectionConfig(config db.ConnectionConfig) (*pgx.ConnConfig, error)
connConfig.Config.Password = config.Password
connConfig.Config.Database = config.ConnectionContext.DatabaseName
- cfg, err := config.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(config.DataSource)
if err != nil {
return nil, err
}
- if cfg != nil {
- connConfig.TLSConfig = cfg
+ if tlscfg != nil {
+ connConfig.TLSConfig = tlscfg
}
return connConfig, nil
@@ -192,7 +192,7 @@ func getRDSConnectionPassword(ctx context.Context, conf db.ConnectionConfig) (st
dbEndpoint := fmt.Sprintf("%s:%s", conf.DataSource.Host, conf.DataSource.Port)
authenticationToken, err := auth.BuildAuthToken(
- ctx, dbEndpoint, conf.Region, conf.DataSource.Username, cfg.Credentials)
+ ctx, dbEndpoint, conf.DataSource.GetRegion(), conf.DataSource.Username, cfg.Credentials)
if err != nil {
return "", errors.Wrap(err, "failed to create authentication token")
}
diff --git a/backend/plugin/db/pg/util.go b/backend/plugin/db/pg/util.go
index 3d978a9c73..af59215d28 100644
--- a/backend/plugin/db/pg/util.go
+++ b/backend/plugin/db/pg/util.go
@@ -1,6 +1,8 @@
package pg
-import "github.com/bytebase/bytebase/backend/plugin/db"
+import (
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
// sslMode is the PGSSLMode type.
// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE
@@ -17,12 +19,12 @@ const (
SSLModeVerifyFull sslMode = "verify-full"
)
-func getSSLMode(tlsConfig db.TLSConfig, sshConfig db.SSHConfig) sslMode {
+func getSSLMode(ds *storepb.DataSource) sslMode {
sslMode := SSLModePrefer
- if tlsConfig.UseSSL {
+ if ds.GetUseSsl() {
sslMode = SSLModeVerifyFull
- if tlsConfig.SslCA != "" {
- if sshConfig.Host != "" {
+ if ds.GetSslCa() != "" {
+ if ds.GetSshHost() != "" {
sslMode = SSLModeVerifyCA
}
}
diff --git a/backend/plugin/db/redis/redis.go b/backend/plugin/db/redis/redis.go
index 1a454356da..5e1242a56f 100644
--- a/backend/plugin/db/redis/redis.go
+++ b/backend/plugin/db/redis/redis.go
@@ -48,7 +48,7 @@ func newDriver(_ db.DriverConfig) db.Driver {
// Open opens the redis driver.
func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionConfig) (db.Driver, error) {
- tlsConfig, err := config.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(config.DataSource)
if err != nil {
return nil, errors.Wrap(err, "redis: failed to get tls config")
}
@@ -61,17 +61,17 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
db = database
}
d.databaseName = fmt.Sprintf("%d", db)
- switch config.RedisType {
+ switch config.DataSource.GetRedisType() {
case storepb.DataSource_REDIS_TYPE_UNSPECIFIED, storepb.DataSource_STANDALONE:
options := &redis.Options{
Addr: fmt.Sprintf("%s:%s", config.DataSource.Host, config.DataSource.Port),
Username: config.DataSource.Username,
Password: config.Password,
- TLSConfig: tlsConfig,
+ TLSConfig: tlscfg,
DB: db,
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
@@ -89,23 +89,23 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
d.databaseName = fmt.Sprintf("%d", db)
d.rdb = client
case storepb.DataSource_SENTINEL:
- sentinelAddrs := make([]string, 0, 1+len(config.AdditionalAddresses))
+ sentinelAddrs := make([]string, 0, 1+len(config.DataSource.GetAdditionalAddresses()))
sentinelAddrs = append(sentinelAddrs, fmt.Sprintf("%s:%s", config.DataSource.Host, config.DataSource.Port))
- for _, sentinelAddr := range config.AdditionalAddresses {
+ for _, sentinelAddr := range config.DataSource.GetAdditionalAddresses() {
sentinelAddrs = append(sentinelAddrs, fmt.Sprintf("%s:%s", sentinelAddr.Host, sentinelAddr.Port))
}
options := &redis.FailoverOptions{
- MasterName: config.MasterName,
- Username: config.MasterUsername,
- Password: config.MasterPassword,
+ MasterName: config.DataSource.GetMasterName(),
+ Username: config.DataSource.GetMasterUsername(),
+ Password: config.DataSource.GetMasterPassword(),
SentinelUsername: config.DataSource.Username,
SentinelPassword: config.Password,
SentinelAddrs: sentinelAddrs,
DB: db,
- TLSConfig: tlsConfig,
+ TLSConfig: tlscfg,
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
@@ -123,19 +123,19 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
client := redis.NewFailoverClient(options)
d.rdb = client
case storepb.DataSource_CLUSTER:
- addrs := make([]string, 0, 1+len(config.AdditionalAddresses))
+ addrs := make([]string, 0, 1+len(config.DataSource.GetAdditionalAddresses()))
addrs = append(addrs, fmt.Sprintf("%s:%s", config.DataSource.Host, config.DataSource.Port))
- for _, addr := range config.AdditionalAddresses {
+ for _, addr := range config.DataSource.GetAdditionalAddresses() {
addrs = append(addrs, fmt.Sprintf("%s:%s", addr.Host, addr.Port))
}
options := &redis.ClusterOptions{
Addrs: addrs,
Username: config.DataSource.Username,
Password: config.Password,
- TLSConfig: tlsConfig,
+ TLSConfig: tlscfg,
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
@@ -152,7 +152,7 @@ func (d *Driver) Open(_ context.Context, _ storepb.Engine, config db.ConnectionC
client := redis.NewClusterClient(options)
d.rdb = client
default:
- return nil, errors.Errorf("unsupported redis type %s", config.RedisType.String())
+ return nil, errors.Errorf("unsupported redis type %s", config.DataSource.GetRedisType().String())
}
d.maximumSQLResultSize = config.MaximumSQLResultSize
diff --git a/backend/plugin/db/redshift/redshift.go b/backend/plugin/db/redshift/redshift.go
index b506ee57a7..b06ef5f7a0 100644
--- a/backend/plugin/db/redshift/redshift.go
+++ b/backend/plugin/db/redshift/redshift.go
@@ -72,8 +72,8 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
return nil, errors.Errorf("user must be set")
}
- if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||
- (config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {
+ if (config.DataSource.GetSslCert() == "" && config.DataSource.GetSslKey() != "") ||
+ (config.DataSource.GetSslCert() != "" && config.DataSource.GetSslKey() == "") {
return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")
}
@@ -85,15 +85,15 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
pgxConnConfig.Config.Password = config.Password
pgxConnConfig.Config.Database = config.ConnectionContext.DatabaseName
- if config.TLSConfig.SslCert != "" {
- cfg, err := config.TLSConfig.GetSslConfig()
+ if config.DataSource.GetSslCert() != "" {
+ tlscfg, err := db.GetTLSConfig(config.DataSource)
if err != nil {
return nil, err
}
- pgxConnConfig.TLSConfig = cfg
+ pgxConnConfig.TLSConfig = tlscfg
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
diff --git a/backend/plugin/db/risingwave/risingwave.go b/backend/plugin/db/risingwave/risingwave.go
index a3a2cb71c1..9c1e0970e9 100644
--- a/backend/plugin/db/risingwave/risingwave.go
+++ b/backend/plugin/db/risingwave/risingwave.go
@@ -76,8 +76,8 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
return nil, errors.Errorf("port must be set")
}
- if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||
- (config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {
+ if (config.DataSource.GetSslCert() == "" && config.DataSource.GetSslKey() != "") ||
+ (config.DataSource.GetSslCert() != "" && config.DataSource.GetSslKey() == "") {
return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")
}
@@ -89,15 +89,15 @@ func (driver *Driver) Open(_ context.Context, _ storepb.Engine, config db.Connec
pgxConnConfig.Config.User = config.DataSource.Username
pgxConnConfig.Config.Password = config.Password
pgxConnConfig.Config.Database = config.ConnectionContext.DatabaseName
- if config.TLSConfig.SslCert != "" {
- cfg, err := config.TLSConfig.GetSslConfig()
+ if config.DataSource.GetSslCert() != "" {
+ tlscfg, err := db.GetTLSConfig(config.DataSource)
if err != nil {
return nil, err
}
- pgxConnConfig.TLSConfig = cfg
+ pgxConnConfig.TLSConfig = tlscfg
}
- if config.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(config.SSHConfig)
+ if config.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(config.DataSource)
if err != nil {
return nil, err
}
diff --git a/backend/plugin/db/snowflake/snowflake.go b/backend/plugin/db/snowflake/snowflake.go
index eb02df57fc..ff0af369fa 100644
--- a/backend/plugin/db/snowflake/snowflake.go
+++ b/backend/plugin/db/snowflake/snowflake.go
@@ -80,8 +80,8 @@ func buildSnowflakeDSN(config db.ConnectionConfig) (string, string, error) {
User: config.DataSource.Username,
Password: config.Password,
}
- if config.AuthenticationPrivateKey != "" {
- rsaPrivKey, err := decodeRSAPrivateKey(config.AuthenticationPrivateKey)
+ if config.DataSource.GetAuthenticationPrivateKey() != "" {
+ rsaPrivKey, err := decodeRSAPrivateKey(config.DataSource.GetAuthenticationPrivateKey())
if err != nil {
return "", "", errors.Wrapf(err, "failed to decode rsa private key")
}
diff --git a/backend/plugin/db/spanner/spanner.go b/backend/plugin/db/spanner/spanner.go
index 1f43d0c16d..d16e38163e 100644
--- a/backend/plugin/db/spanner/spanner.go
+++ b/backend/plugin/db/spanner/spanner.go
@@ -64,7 +64,7 @@ func (d *Driver) Open(ctx context.Context, _ storepb.Engine, config db.Connectio
d.connCtx = config.ConnectionContext
var o []option.ClientOption
- if config.AuthenticationType != storepb.DataSource_GOOGLE_CLOUD_SQL_IAM {
+ if config.DataSource.GetAuthenticationType() != storepb.DataSource_GOOGLE_CLOUD_SQL_IAM {
o = append(o, option.WithCredentialsJSON([]byte(config.Password)))
}
if config.ConnectionContext.DatabaseName != "" {
diff --git a/backend/plugin/db/ssl.go b/backend/plugin/db/ssl.go
index 98f5f8ddea..6fd59805da 100644
--- a/backend/plugin/db/ssl.go
+++ b/backend/plugin/db/ssl.go
@@ -5,23 +5,17 @@ import (
"crypto/x509"
"github.com/pkg/errors"
-)
-// TLSConfig is the configuration for SSL connection.
-type TLSConfig struct {
- UseSSL bool
- SslCA string
- SslCert string
- SslKey string
-}
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
// GetSslConfig gets the SSL config for connection.
-func (tc TLSConfig) GetSslConfig() (*tls.Config, error) {
- if !tc.UseSSL {
+func GetTLSConfig(ds *storepb.DataSource) (*tls.Config, error) {
+ if !ds.GetUseSsl() {
return nil, nil
}
var rootCertPool *x509.CertPool
- if tc.SslCA == "" {
+ if ds.GetSslCa() == "" {
p, err := x509.SystemCertPool()
if err != nil {
return nil, err
@@ -29,7 +23,7 @@ func (tc TLSConfig) GetSslConfig() (*tls.Config, error) {
rootCertPool = p
} else {
rootCertPool = x509.NewCertPool()
- if ok := rootCertPool.AppendCertsFromPEM([]byte(tc.SslCA)); !ok {
+ if ok := rootCertPool.AppendCertsFromPEM([]byte(ds.GetSslCa())); !ok {
return nil, errors.Errorf("rootCertPool.AppendCertsFromPEM() failed to append server CA pem")
}
}
@@ -37,12 +31,12 @@ func (tc TLSConfig) GetSslConfig() (*tls.Config, error) {
cfg := &tls.Config{
RootCAs: rootCertPool,
}
- if (tc.SslCert == "" && tc.SslKey != "") || (tc.SslCert != "" && tc.SslKey == "") {
+ if (ds.GetSslCert() == "" && ds.GetSslKey() != "") || (ds.GetSslCert() != "" && ds.GetSslKey() == "") {
return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")
}
- if tc.SslCert != "" && tc.SslKey != "" {
+ if ds.GetSslCert() != "" && ds.GetSslKey() != "" {
var clientCert []tls.Certificate
- certs, err := tls.X509KeyPair([]byte(tc.SslCert), []byte(tc.SslKey))
+ certs, err := tls.X509KeyPair([]byte(ds.GetSslCert()), []byte(ds.GetSslKey()))
if err != nil {
return nil, err
}
diff --git a/backend/plugin/db/starrocks/starrocks.go b/backend/plugin/db/starrocks/starrocks.go
index 7c8208bd72..50e4db1450 100644
--- a/backend/plugin/db/starrocks/starrocks.go
+++ b/backend/plugin/db/starrocks/starrocks.go
@@ -73,8 +73,8 @@ func (driver *Driver) Open(_ context.Context, dbType storepb.Engine, connCfg db.
protocol = "unix"
}
params := []string{"multiStatements=true", "maxAllowedPacket=0"}
- if connCfg.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(connCfg.SSHConfig)
+ if connCfg.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(connCfg.DataSource)
if err != nil {
return nil, err
}
@@ -86,14 +86,13 @@ func (driver *Driver) Open(_ context.Context, dbType storepb.Engine, connCfg db.
protocol = "mysql+tcp"
}
- // TODO(zp): mysql and mysqlbinlog doesn't support SSL yet. We need to write certs to temp files and load them as CLI flags.
- tlsConfig, err := connCfg.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(connCfg.DataSource)
if err != nil {
return nil, errors.Wrap(err, "sql: tls config error")
}
tlsKey := uuid.NewString()
- if tlsConfig != nil {
- if err := mysql.RegisterTLSConfig(tlsKey, tlsConfig); err != nil {
+ if tlscfg != nil {
+ if err := mysql.RegisterTLSConfig(tlsKey, tlscfg); err != nil {
return nil, errors.Wrap(err, "sql: failed to register tls config")
}
// TLS config is only used during sql.Open, so should be safe to deregister afterwards.
diff --git a/backend/plugin/db/tidb/tidb.go b/backend/plugin/db/tidb/tidb.go
index f7068133fb..06a3a37984 100644
--- a/backend/plugin/db/tidb/tidb.go
+++ b/backend/plugin/db/tidb/tidb.go
@@ -76,8 +76,8 @@ func (d *Driver) Open(_ context.Context, dbType storepb.Engine, connCfg db.Conne
protocol = "unix"
}
params := []string{"multiStatements=true", "maxAllowedPacket=0"}
- if connCfg.SSHConfig.Host != "" {
- sshClient, err := util.GetSSHClient(connCfg.SSHConfig)
+ if connCfg.DataSource.GetSshHost() != "" {
+ sshClient, err := util.GetSSHClient(connCfg.DataSource)
if err != nil {
return nil, err
}
@@ -89,14 +89,13 @@ func (d *Driver) Open(_ context.Context, dbType storepb.Engine, connCfg db.Conne
protocol = "mysql+tcp"
}
- // TODO(zp): mysql and mysqlbinlog doesn't support SSL yet. We need to write certs to temp files and load them as CLI flags.
- tlsConfig, err := connCfg.TLSConfig.GetSslConfig()
+ tlscfg, err := db.GetTLSConfig(connCfg.DataSource)
if err != nil {
return nil, errors.Wrap(err, "sql: tls config error")
}
tlsKey := uuid.NewString()
- if tlsConfig != nil {
- if err := mysql.RegisterTLSConfig(tlsKey, tlsConfig); err != nil {
+ if tlscfg != nil {
+ if err := mysql.RegisterTLSConfig(tlsKey, tlscfg); err != nil {
return nil, errors.Wrap(err, "sql: failed to register tls config")
}
// TLS config is only used during sql.Open, so should be safe to deregister afterwards.
diff --git a/backend/plugin/db/util/ssh.go b/backend/plugin/db/util/ssh.go
index c981f66b52..84c0ce1781 100644
--- a/backend/plugin/db/util/ssh.go
+++ b/backend/plugin/db/util/ssh.go
@@ -11,18 +11,18 @@ import (
"golang.org/x/crypto/ssh/agent"
"github.com/bytebase/bytebase/backend/common/log"
- "github.com/bytebase/bytebase/backend/plugin/db"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
// GetSSHClient returns a ssh client.
-func GetSSHClient(cfg db.SSHConfig) (*ssh.Client, error) {
+func GetSSHClient(ds *storepb.DataSource) (*ssh.Client, error) {
sshConfig := &ssh.ClientConfig{
- User: cfg.User,
+ User: ds.GetSshUser(),
Auth: []ssh.AuthMethod{},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
- if cfg.PrivateKey != "" {
- signer, err := ssh.ParsePrivateKey([]byte(cfg.PrivateKey))
+ if ds.GetSshPrivateKey() != "" {
+ signer, err := ssh.ParsePrivateKey([]byte(ds.GetSshPrivateKey()))
if err != nil {
return nil, err
}
@@ -41,13 +41,13 @@ func GetSSHClient(cfg db.SSHConfig) (*ssh.Client, error) {
}
}
// When there's a non empty password add the password AuthMethod.
- if cfg.Password != "" {
+ if ds.GetSshPassword() != "" {
sshConfig.Auth = append(sshConfig.Auth, ssh.PasswordCallback(func() (string, error) {
- return cfg.Password, nil
+ return ds.GetSshPassword(), nil
}))
}
// Connect to the SSH Server
- sshConn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", cfg.Host, cfg.Port), sshConfig)
+ sshConn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", ds.GetSshHost(), ds.GetSshPort()), sshConfig)
if err != nil {
return nil, err
}
diff --git a/backend/server/server.go b/backend/server/server.go
index a26070c51a..09cb855fb7 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -95,12 +95,6 @@ type Server struct {
rolloutService *apiv1.RolloutService
issueService *apiv1.IssueService
- // MySQL utility binaries
- mysqlBinDir string
- // MongoDB utility binaries
- mongoBinDir string
- // Postgres utility binaries
- pgBinDir string
// PG server stoppers.
stopper []func()
@@ -141,21 +135,21 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
}
// Install mongoutil.
- s.mongoBinDir, err = mongoutil.Install(profile.ResourceDir)
+ mongoBinDir, err := mongoutil.Install(profile.ResourceDir)
if err != nil {
return nil, errors.Wrap(err, "cannot install mongo utility binaries")
}
// Installs the Postgres and utility binaries and creates the 'activeProfile.pgUser' user/database
// to store Bytebase's own metadata.
- s.pgBinDir, err = postgres.Install(profile.ResourceDir)
+ pgBinDir, err := postgres.Install(profile.ResourceDir)
if err != nil {
return nil, err
}
var connCfg dbdriver.ConnectionConfig
if profile.UseEmbedDB() {
- stopper, err := postgres.StartMetadataInstance(profile.DataDir, profile.ResourceDir, s.pgBinDir, profile.PgUser, profile.DemoName, profile.DatastorePort, profile.Mode)
+ stopper, err := postgres.StartMetadataInstance(profile.DataDir, profile.ResourceDir, pgBinDir, profile.PgUser, profile.DemoName, profile.DatastorePort, profile.Mode)
if err != nil {
return nil, err
}
@@ -175,12 +169,12 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
if profile.SampleDatabasePort != 0 {
// Only create batch sample databases in demo mode. For normal mode, user starts from the free version
// and batch databases are useless because batch requires enterprise license.
- stopper := postgres.StartAllSampleInstances(ctx, s.pgBinDir, profile.DataDir, profile.SampleDatabasePort, profile.DemoName != "")
+ stopper := postgres.StartAllSampleInstances(ctx, pgBinDir, profile.DataDir, profile.SampleDatabasePort, profile.DemoName != "")
s.stopper = append(s.stopper, stopper...)
}
// Connect to the instance that stores bytebase's own metadata.
- storeDB := store.NewDB(connCfg, s.pgBinDir, profile.Readonly, profile.Mode)
+ storeDB := store.NewDB(connCfg, pgBinDir, profile.Readonly, profile.Mode)
// For embedded database, we will create the database if it does not exist.
if err := storeDB.Open(ctx, profile.UseEmbedDB() /* createDB */); err != nil {
// return s so that caller can call s.Close() to shut down the postgres server if embedded.
@@ -234,13 +228,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {
return nil, errors.Wrapf(err, "failed to create iam manager")
}
s.webhookManager = webhook.NewManager(storeInstance, s.iamManager)
- s.dbFactory = dbfactory.New(
- s.store,
- s.mysqlBinDir,
- s.mongoBinDir,
- s.pgBinDir,
- profile.DataDir,
- )
+ s.dbFactory = dbfactory.New(s.store, mongoBinDir)
// Configure echo server.
s.echoServer = echo.New()
diff --git a/backend/store/metadb.go b/backend/store/metadb.go
index 08cf0f5591..537d2e1ea2 100644
--- a/backend/store/metadb.go
+++ b/backend/store/metadb.go
@@ -87,11 +87,8 @@ func GetConnectionConfig(pgURL string) (dbdriver.ConnectionConfig, error) {
return dbdriver.ConnectionConfig{}, errors.Errorf("missing database in the --pg connection string")
}
connCfg.ConnectionContext.DatabaseName = u.Path[1:]
-
- connCfg.TLSConfig = dbdriver.TLSConfig{
- SslCA: q.Get("sslrootcert"),
- SslKey: q.Get("sslkey"),
- SslCert: q.Get("sslcert"),
- }
+ connCfg.DataSource.SslCa = q.Get("sslrootcert")
+ connCfg.DataSource.SslKey = q.Get("sslkey")
+ connCfg.DataSource.SslCert = q.Get("sslcert")
return connCfg, nil
}