Skip to content

Commit

Permalink
Fix parsePostgresURL issue (grafana#1111)
Browse files Browse the repository at this point in the history
* Fix parsePostgresURL issue

* Update Implementation and fix unit test

* Add nolint and fix unit test

* Update changelog

* move changelog entry to unreleased

Co-authored-by: Robert Fratto <[email protected]>
  • Loading branch information
saputradharma and rfratto authored Nov 18, 2021
1 parent 014c9f3 commit 831b661
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Main (unreleased)

- [BUGFIX] Fix panic when using postgres_exporter (@saputradharma)

# v0.21.0 (2021-11-17)

- [ENHANCEMENT] Update Cortex dependency to v1.10.0-92-g85c378182. (@rlankfo)
Expand Down
15 changes: 13 additions & 2 deletions pkg/integrations/postgres_exporter/postgres_exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,24 @@ func parsePostgresURL(url string) (map[string]string, error) {

res := map[string]string{}

unescaper := strings.NewReplacer(`\'`, `'`, `\\`, `\`)

for _, keypair := range strings.Split(raw, " ") {
parts := strings.SplitN(keypair, "=", 1)
parts := strings.SplitN(keypair, "=", 2)
if len(parts) != 2 {
panic(fmt.Sprintf("unexpected keypair %s from pq", keypair))
}

res[parts[0]] = parts[1]
key := parts[0]
value := parts[1]

// Undo all the transformations ParseURL did: remove wrapping
// quotes and then unescape the escaped characters.
value = strings.TrimPrefix(value, "'")
value = strings.TrimSuffix(value, "'")
value = unescaper.Replace(value)

res[key] = value
}

return res, nil
Expand Down
24 changes: 24 additions & 0 deletions pkg/integrations/postgres_exporter/postgres_exporter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package postgres_exporter //nolint:golint

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_ParsePostgresURL(t *testing.T) {
dsn := "postgresql://linus:42secret@localhost:5432/postgres?sslmode=disable"
expected := map[string]string{
"dbname": "postgres",
"host": "localhost",
"password": "42secret",
"port": "5432",
"sslmode": "disable",
"user": "linus",
}

actual, err := parsePostgresURL(dsn)
require.NoError(t, err)
require.Equal(t, actual, expected)

}

0 comments on commit 831b661

Please sign in to comment.