Skip to content

Commit 4430cc8

Browse files
authored
feat: support greptimedb auth (#22)
* feat: support user & password Signed-off-by: evenyag <realevenyag@gmail.com> * chore: use && instead of || Signed-off-by: evenyag <realevenyag@gmail.com> --------- Signed-off-by: evenyag <realevenyag@gmail.com>
1 parent 04af3a3 commit 4430cc8

File tree

5 files changed

+68
-6
lines changed

5 files changed

+68
-6
lines changed

cmd/tsbs_load_greptime/creator.go

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"encoding/base64"
45
"encoding/json"
56
"fmt"
67
"io/ioutil"
@@ -17,6 +18,15 @@ func (d *dbCreator) Init() {
1718
d.daemonURL = daemonURLs[0] // pick first one since it always exists
1819
}
1920

21+
// addAuthHeader adds Basic authentication header to the request if credentials are provided
22+
func (d *dbCreator) addAuthHeader(req *http.Request) {
23+
if username != "" && password != "" {
24+
credentials := username + ":" + password
25+
encoded := base64.StdEncoding.EncodeToString([]byte(credentials))
26+
req.Header.Set("Authorization", "Basic "+encoded)
27+
}
28+
}
29+
2030
func (d *dbCreator) DBExists(dbName string) bool {
2131
dbs, err := d.listDatabases()
2232
if err != nil {
@@ -33,7 +43,14 @@ func (d *dbCreator) DBExists(dbName string) bool {
3343

3444
func (d *dbCreator) listDatabases() ([]string, error) {
3545
u := fmt.Sprintf("%s/v1/sql?sql=show%%20databases", d.daemonURL)
36-
resp, err := http.Get(u)
46+
req, err := http.NewRequest("GET", u, nil)
47+
if err != nil {
48+
return nil, fmt.Errorf("listDatabases error: %s", err.Error())
49+
}
50+
d.addAuthHeader(req)
51+
52+
client := &http.Client{}
53+
resp, err := client.Do(req)
3754
if err != nil {
3855
return nil, fmt.Errorf("listDatabases error: %s", err.Error())
3956
}
@@ -71,10 +88,20 @@ func (d *dbCreator) listDatabases() ([]string, error) {
7188

7289
func (d *dbCreator) RemoveOldDB(dbName string) error {
7390
u := fmt.Sprintf("%s/v1/sql?sql=drop+database+%s", d.daemonURL, dbName)
74-
resp, err := http.Post(u, "text/plain", nil)
91+
req, err := http.NewRequest("POST", u, nil)
7592
if err != nil {
7693
return fmt.Errorf("drop db error: %s", err.Error())
7794
}
95+
req.Header.Set("Content-Type", "text/plain")
96+
d.addAuthHeader(req)
97+
98+
client := &http.Client{}
99+
resp, err := client.Do(req)
100+
if err != nil {
101+
return fmt.Errorf("drop db error: %s", err.Error())
102+
}
103+
defer resp.Body.Close()
104+
78105
if resp.StatusCode != 200 {
79106
return fmt.Errorf("drop db returned non-200 code: %d", resp.StatusCode)
80107
}
@@ -84,7 +111,14 @@ func (d *dbCreator) RemoveOldDB(dbName string) error {
84111

85112
func (d *dbCreator) CreateDB(dbName string) error {
86113
u := fmt.Sprintf("%s/v1/sql?sql=create%%20database%%20%s", d.daemonURL, dbName)
87-
resp, err := http.Get(u)
114+
req, err := http.NewRequest("GET", u, nil)
115+
if err != nil {
116+
return fmt.Errorf("create db error: %s", err.Error())
117+
}
118+
d.addAuthHeader(req)
119+
120+
client := &http.Client{}
121+
resp, err := client.Do(req)
88122
if err != nil {
89123
return fmt.Errorf("create db error: %s", err.Error())
90124
}

cmd/tsbs_load_greptime/http_writer.go

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package main
44

55
import (
66
"bytes"
7+
"encoding/base64"
78
"fmt"
89
"net/url"
910
"time"
@@ -38,26 +39,42 @@ type HTTPWriterConfig struct {
3839

3940
// Debug label for more informative errors.
4041
DebugInfo string
42+
43+
// Username for authentication.
44+
Username string
45+
46+
// Password for authentication.
47+
Password string
4148
}
4249

4350
// HTTPWriter is a Writer that writes to an InfluxDB HTTP server.
4451
type HTTPWriter struct {
4552
client fasthttp.Client
4653

47-
c HTTPWriterConfig
48-
url []byte
54+
c HTTPWriterConfig
55+
url []byte
56+
authHeader []byte
4957
}
5058

5159
// NewHTTPWriter returns a new HTTPWriter from the supplied HTTPWriterConfig.
5260
func NewHTTPWriter(c HTTPWriterConfig, consistency string) *HTTPWriter {
53-
return &HTTPWriter{
61+
w := &HTTPWriter{
5462
client: fasthttp.Client{
5563
Name: httpClientName,
5664
},
5765

5866
c: c,
5967
url: []byte(c.Host + "/v1/influxdb/write?consistency=" + consistency + "&db=" + url.QueryEscape(c.Database)),
6068
}
69+
70+
// Generate Basic auth header if credentials are provided
71+
if c.Username != "" && c.Password != "" {
72+
credentials := c.Username + ":" + c.Password
73+
encoded := base64.StdEncoding.EncodeToString([]byte(credentials))
74+
w.authHeader = []byte("Basic " + encoded)
75+
}
76+
77+
return w
6178
}
6279

6380
var (
@@ -72,6 +89,9 @@ func (w *HTTPWriter) initializeReq(req *fasthttp.Request, body []byte, isGzip bo
7289
if isGzip {
7390
req.Header.Add(headerContentEncoding, headerGzip)
7491
}
92+
if len(w.authHeader) > 0 {
93+
req.Header.SetBytesKV([]byte("Authorization"), w.authHeader)
94+
}
7595
req.SetBody(body)
7696
}
7797

cmd/tsbs_load_greptime/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ var (
3030
useGzip bool
3131
doAbortOnExist bool
3232
consistency string
33+
username string
34+
password string
3335
)
3436

3537
// Global vars
@@ -75,6 +77,8 @@ func init() {
7577
consistency = viper.GetString("consistency")
7678
backoff = viper.GetDuration("backoff")
7779
useGzip = viper.GetBool("gzip")
80+
username = viper.GetString("user")
81+
password = viper.GetString("password")
7882

7983
if _, ok := consistencyChoices[consistency]; !ok {
8084
log.Fatalf("invalid consistency settings")

cmd/tsbs_load_greptime/process.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ func (p *processor) Init(numWorker int, _, _ bool) {
2626
DebugInfo: fmt.Sprintf("worker #%d, dest url: %s", numWorker, daemonURL),
2727
Host: daemonURL,
2828
Database: loader.DatabaseName(),
29+
Username: username,
30+
Password: password,
2931
}
3032
w := NewHTTPWriter(cfg, consistency)
3133
p.initWithHTTPWriter(numWorker, w)

pkg/targets/influx/implemented_target.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ func (t *influxTarget) TargetSpecificFlags(flagPrefix string, flagSet *pflag.Fla
2323
flagSet.String(flagPrefix+"consistency", "all", "Write consistency. Must be one of: any, one, quorum, all.")
2424
flagSet.Duration(flagPrefix+"backoff", time.Second, "Time to sleep between requests when server indicates backpressure is needed.")
2525
flagSet.Bool(flagPrefix+"gzip", true, "Whether to gzip encode requests (default true).")
26+
flagSet.String(flagPrefix+"user", "", "Username for authentication.")
27+
flagSet.String(flagPrefix+"password", "", "Password for authentication.")
2628
}
2729

2830
func (t *influxTarget) TargetName() string {

0 commit comments

Comments
 (0)