-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathbackend_ce.go
More file actions
84 lines (72 loc) · 2.44 KB
/
Copy pathbackend_ce.go
File metadata and controls
84 lines (72 loc) · 2.44 KB
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
// Copyright IBM Corp. 2016, 2025
// SPDX-License-Identifier: BUSL-1.1
//go:build !enterprise
package database
import (
"context"
"fmt"
"github.com/hashicorp/go-uuid"
v5 "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
)
// GetConnectionWithConfig gets or creates a database connection with the given config for community edition
func (b *databaseBackend) GetConnectionWithConfig(ctx context.Context, name string, config *DatabaseConfig) (*dbPluginInstance, error) {
// fast path, reuse the existing connection
dbi := b.connections.Get(name)
if dbi != nil {
return dbi, nil
}
// slow path, create a new connection
// if we don't lock the rest of the operation, there is a race condition for multiple callers of this function
b.createConnectionLock.Lock()
defer b.createConnectionLock.Unlock()
// check again in case we lost the race
dbi = b.connections.Get(name)
if dbi != nil {
return dbi, nil
}
id, err := uuid.GenerateUUID()
if err != nil {
return nil, err
}
// Override the configured version if there is a pinned version.
pinnedVersion, err := b.getPinnedVersion(ctx, config.PluginName)
if err != nil {
return nil, err
}
pluginVersion := config.PluginVersion
if pinnedVersion != "" {
pluginVersion = pinnedVersion
}
dbw, err := newDatabaseWrapperWithMetricsLabels(ctx, config.PluginName, pluginVersion, b.System(), b.logger, b.metricsLabelsForConnection(name))
if err != nil {
return nil, fmt.Errorf("unable to create database instance: %w", err)
}
initReq := v5.InitializeRequest{
Config: config.ConnectionDetails,
VerifyConnection: config.VerifyConnection,
}
// Bound cache-miss initialization so a blocked handshake cannot stall callers
// indefinitely while the connection creation lock is held.
_, err = b.initializeConnection(ctx, dbw, initReq)
if err != nil {
b.closeDatabaseWrapperAfterInitError(dbw, err)
return nil, err
}
dbi = &dbPluginInstance{
database: dbw,
id: id,
name: name,
runningPluginVersion: pluginVersion,
}
conn, ok := b.connections.PutIfEmpty(name, dbi)
if !ok {
// this is a bug
b.Logger().Warn("BUG: there was a race condition adding to the database connection map")
// There was already an existing connection, so we will use that and close our new one to avoid a race condition.
err := dbi.Close()
if err != nil {
b.Logger().Warn("Error closing new database connection", "error", err)
}
}
return conn, nil
}