This repository has been archived by the owner on Oct 30, 2024. It is now read-only.
forked from mgit-at/sql_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql_oracle.go
282 lines (252 loc) · 6.86 KB
/
sql_oracle.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
//go:build !db2 && !hana && !mssql && oracle && !postgres
package main
import (
"context"
"database/sql"
"fmt"
"log/slog"
"net/url"
"strings"
_ "github.com/mattn/go-oci8"
"github.com/peekjef72/passwd_encrypt/encrypt"
// register the Oracle OCI-8 driver
)
// OpenConnection extracts the driver name from the DSN (expected as the URI scheme), adjusts it where necessary (e.g.
// some driver supported DSN formats don't include a scheme), opens a DB handle ensuring early termination if the
// context is closed (this is actually prevented by `database/sql` implementation), sets connection limits and returns
// the handle.
//
// url format "oracle://<hostname>:<port>/<instance>?user%20id=<login>&password=<password>&database=<database>&protocol=...&options="
//
// or:
//
// INSTANCE=<instance>; DATABASE=<database>; HOSTNAME=<hostname>; PORT=<port>; PROTOCOL=<protocol>; UID=<login>; PWD=<password>;<br>
//
// ## parameters synonym => final value
// * server, hostname => server
// * uid, user, login => user id
// * pwd, passwd, password => password
//
// valid options are:
// - loc
// - isolation
// - questionph
// - prefetch_rows
// - prefetch_memory
// - as
// - stmt_cache_size
func OpenConnection(
ctx context.Context,
logContext []interface{},
logger *slog.Logger,
dsn string,
auth AuthConfig,
maxConns, maxIdleConns int,
symbol_table map[string]interface{}) (*sql.DB, error) {
var driver string
// Extract driver name from DSN.
idx := strings.Index(dsn, "://")
if idx == -1 {
//return nil, fmt.Errorf("missing driver in data source name. Expected format `<driver>://<dsn>`")
driver = "oci8"
} else {
driver = dsn[:idx]
}
// Adjust DSN, where necessary.
var params map[string]string
switch driver {
case "oracle", "oci8":
var err error
if strings.HasPrefix(dsn, "oracle://") || strings.HasPrefix(dsn, "oci8://") {
// "oracle://<hostname>:<port>/<database>?user%20id=<login>&password=<password>&database=<database>&protocol=..."
params, err = splitConnectionStringURL(dsn)
if err != nil {
return nil, err
}
// if strings.HasPrefix(dsn, "oracle://") {
// }
} else {
// DATABASE=<database>; HOSTNAME=<hostname>; PORT=<port>; PROTOCOL=<protocol>; UID=<login>; PWD=<password>;
params, err = splitRawConnectionStringDSN(dsn)
if err != nil {
return nil, err
}
}
val, ok := params["server"]
if !ok || val == "" {
return nil, fmt.Errorf("server can't be empty")
}
val, ok = params["user id"]
if !ok || val == "" {
if auth.Username != "" {
params["user id"] = auth.Username
} else {
return nil, fmt.Errorf("user Id can't be empty")
}
}
val, ok = params["password"]
if !ok || val == "" {
if auth.Password != "" {
val = string(auth.Password)
} else {
return nil, fmt.Errorf("password has to be set")
}
}
passwd := val
if strings.HasPrefix(passwd, "/encrypted/") {
ciphertext := passwd[len("/encrypted/"):]
logger.Debug("debug ciphertext",
"ciphertext", ciphertext)
auth_key := GetMapValueString(symbol_table, "auth_key")
logger.Debug(
"debug authkey",
"auth_key", auth_key)
if auth_key == "" {
return nil, fmt.Errorf("password is encrypt and not ciphertext provided (auth_key)")
}
cipher, err := encrypt.NewAESCipher(auth_key)
if err != nil {
err := fmt.Errorf("can't obtain cipher to decrypt")
// level.Error(c.logger).Log("errmsg", err)
return nil, err
}
passwd, err = cipher.Decrypt(ciphertext, true)
if err != nil {
err := fmt.Errorf("invalid key provided to decrypt")
// level.Error(c.logger).Log("errmsg", err)
return nil, err
}
params["password"] = passwd
}
// 2 cases:
// a) old format: only instance is specified
// b) new for pdbs databases:
// instance and databases is specified
val, ok = params["instance"]
if !ok || val == "" {
val, ok = params["database"]
if !ok || val == "" {
return nil, fmt.Errorf("instance must be set")
} else {
// database is defined but not instance: switch values
params["instance"] = params["database"]
delete(params, "database")
}
}
// oci8.ParseDSN
// <user id>/<password>@(DESCRIPTION =
// (ADDRESS =
// (PROTOCOL = <protocol>)
// (host = <server>)
// (port = <port>)
// )
// (CONNECT_DATA =
// (SID = <service name>)
// )
// )
new_dns := new(strings.Builder)
// user
new_dns.WriteString(url.QueryEscape(params["user id"]))
new_dns.WriteString("/")
// password
new_dns.WriteString(url.QueryEscape(params["password"]))
new_dns.WriteString("@")
// DESCRIPTION
new_dns.WriteString("(DESCRIPTION = ")
// ADDRESS
new_dns.WriteString("(ADDRESS =")
// Protocol
new_dns.WriteString("(PROTOCOL = ")
if params["protocol"] != "" {
new_dns.WriteString(strings.ToUpper(params["protocol"]))
} else {
new_dns.WriteString("TCP")
}
new_dns.WriteString(") ")
// Hostname
new_dns.WriteString("(HOST =")
new_dns.WriteString(params["server"])
new_dns.WriteString(") ")
// Port
new_dns.WriteString(" ( PORT=")
if params["port"] != "" {
new_dns.WriteString(params["port"])
} else {
new_dns.WriteString("1531")
}
new_dns.WriteString(")")
// END ADDRESS
new_dns.WriteString(") ")
// SID or SERVICE_NAME
new_dns.WriteString("(CONNECT_DATA = (")
if _, ok := params["database"]; ok {
new_dns.WriteString(" SERVICE_NAME = ")
new_dns.WriteString(params["database"])
} else {
new_dns.WriteString(" SID = ")
new_dns.WriteString(params["instance"])
}
new_dns.WriteString("))")
// END DESCRIPTION
new_dns.WriteString(")")
new_dns.WriteString("?")
// others params
var params_list = []string{
"loc",
"isolation",
"questionph",
"prefetch_rows",
"prefetch_memory",
"as",
"stmt_cache_size",
}
for _, param := range params_list {
val, err := params[param]
if err {
new_dns.WriteString(param)
new_dns.WriteString("=")
if params["protocol"] != "" {
new_dns.WriteString(val)
new_dns.WriteString("&")
}
}
}
dsn = new_dns.String()
// add params to target symbol table
symbol_table["params"] = params
driver = "oci8"
default:
return nil, fmt.Errorf("driver '%s' not supported", driver)
}
// Open the DB handle in a separate goroutine so we can terminate early if the context closes.
var (
conn *sql.DB
err error
ch = make(chan error)
)
go func() {
conn, err = sql.Open(driver, dsn)
close(ch)
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ch:
if err != nil {
return nil, err
}
}
conn.SetMaxIdleConns(maxIdleConns)
conn.SetMaxOpenConns(maxConns)
logContext = append(logContext, "msg", fmt.Sprintf("Database handle successfully opened with driver %s.", driver))
logger.Debug("msg_stack",
logContext...)
return conn, nil
}
func my_split(s string, c string) (string, string) {
i := strings.LastIndex(s, c)
if i < 0 {
return s, ""
}
return s[:i], s[i+len(c):]
}