-
Notifications
You must be signed in to change notification settings - Fork 1
/
postgres.go
77 lines (62 loc) · 2.15 KB
/
postgres.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
package main
import (
"database/sql"
"fmt"
machineryEnvVars "github.com/uselagoon/machinery/utils/variables"
"log"
"net/http"
"os"
"strings"
_ "github.com/lib/pq"
)
var (
postgresSSL = "disable"
postgresVersion string
postgresConnectionStr string
)
func postgresHandler(w http.ResponseWriter, r *http.Request) {
service := r.URL.Query().Get("service")
localService, lagoonService := cleanRoute(service)
postgresUser := machineryEnvVars.GetEnv(fmt.Sprintf("%s_USERNAME", lagoonService), "lagoon")
postgresPassword := machineryEnvVars.GetEnv(fmt.Sprintf("%s_PASSWORD", lagoonService), "lagoon")
postgresHost := machineryEnvVars.GetEnv(fmt.Sprintf("%s_HOST", lagoonService), localService)
postgresPort := machineryEnvVars.GetEnv(fmt.Sprintf("%s_PORT", lagoonService), "5432")
postgresDatabase := machineryEnvVars.GetEnv(fmt.Sprintf("%s_DATABASE", lagoonService), "lagoon")
postgresConnectionStr = fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s host=%s port=%s", postgresUser, postgresPassword, postgresDatabase, postgresSSL, postgresHost, postgresPort)
log.Print(fmt.Sprintf("Using %s as the connstring", postgresConnectionStr))
fmt.Fprintf(w, dbConnectorPairs(postgresDBConnector(postgresConnectionStr), postgresVersion))
}
func postgresDBConnector(connectionString string) map[string]string {
db, err := sql.Open("postgres", connectionString)
if err != nil {
log.Print(err)
}
defer db.Close()
createTable := "CREATE TABLE IF NOT EXISTS env(env_key text, env_value text)"
_, err = db.Exec(createTable)
if err != nil {
log.Print(err)
}
query := "INSERT INTO env(env_key, env_value) VALUES ($1, $2)"
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
_, err := db.Exec(query, pair[0], pair[1])
if err != nil {
log.Print(err)
}
}
gitSHA := "LAGOON_%"
rows, err := db.Query(`SELECT * FROM env where env_key LIKE $1`, gitSHA)
if err != nil {
log.Print(err)
}
db.QueryRow("SELECT VERSION()").Scan(&postgresVersion)
defer rows.Close()
results := make(map[string]string)
for rows.Next() {
var envKey, envValue string
_ = rows.Scan(&envKey, &envValue)
results[envKey] = envValue
}
return results
}