-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
93 lines (79 loc) · 1.95 KB
/
db.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
package db
import (
"context"
"fmt"
"net"
"os"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/crypto/ssh"
)
type mySQLSSHDriver struct {
sshClient *ssh.Client
}
func (e *mySQLSSHDriver) Dial(ctx context.Context, addr string) (net.Conn, error) {
return e.sshClient.Dial("tcp", addr)
}
var (
conn *sqlx.DB
sshConn *ssh.Client
)
func NewSQLLite(dataSourceName string) error {
var err error
conn, err = sqlx.Connect("sqlite3", dataSourceName)
if err != nil {
return fmt.Errorf("connect: %w", err)
}
return nil
}
// New creates a new database connection
func New(dataSourceName string) error {
var err error
connType := "mysql"
if sshConn != nil {
mysql.RegisterDialContext("mysql+ssh", (&mySQLSSHDriver{sshConn}).Dial)
}
conn, err = sqlx.Connect(connType, dataSourceName)
if err != nil {
return fmt.Errorf("connect: %w", err)
}
return nil
}
func NewSSH(host string, port int, user string, pass string, dataSourceName string) error {
var err error
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pass),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
sshConn, err = ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), sshConfig)
if err != nil {
return fmt.Errorf("dial: %w", err)
}
return New(dataSourceName)
}
func NewSSHPSK(host string, port int, user string, pskPath string, dataSourceName string) error {
data, err := os.ReadFile(pskPath)
if err != nil {
return fmt.Errorf("read file: %w", err)
}
signer, err := ssh.ParsePrivateKey(data)
if err != nil {
return fmt.Errorf("parse private key: %w", err)
}
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
sshConn, err = ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), sshConfig)
if err != nil {
return fmt.Errorf("dial: %w", err)
}
return New(dataSourceName)
}