forked from stellar/go
/
main.go
266 lines (222 loc) · 6.75 KB
/
main.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
package main
import (
"context"
"crypto/tls"
"database/sql"
"flag"
"fmt"
"net"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
migrate "github.com/rubenv/sql-migrate"
"github.com/sirupsen/logrus"
"github.com/stellar/go/exp/services/keystore"
"github.com/stellar/go/support/log"
_ "github.com/lib/pq"
)
var keystoreMigrations = &migrate.FileMigrationSource{
Dir: "migrations",
}
const dbDriverName = "postgres"
func main() {
ctx := context.Background()
tlsCert := flag.String("tls-cert", "", "TLS certificate file path")
tlsKey := flag.String("tls-key", "", "TLS private key file path")
logFilePath := flag.String("log-file", "", "Log file file path")
logLevel := flag.String("log-level", "info", "Log level used by logrus (debug, info, warn, error)")
auth := flag.Bool("auth", true, "Enable authentication")
apiType := flag.String("api-type", "REST", "Auth Forwarding API Type")
flag.Parse()
if len(flag.Args()) < 1 {
fmt.Fprintln(os.Stderr, "too few arguments")
os.Exit(1)
}
if (*tlsCert == "" && *tlsKey != "") || (*tlsCert != "" && *tlsKey == "") {
fmt.Fprintln(os.Stderr, "TLS cert and TLS key have to be presented together")
os.Exit(1)
}
if *logFilePath != "" {
logFile, err := os.OpenFile(*logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open file to log: %v\n", err)
os.Exit(1)
}
log.DefaultLogger.Logger.Out = logFile
ll, err := logrus.ParseLevel(*logLevel)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not parse log-level: %v\n", err)
os.Exit(1)
}
log.DefaultLogger.Logger.SetLevel(ll)
}
cfg := getConfig()
if cfg.ListenerPort < 0 {
fmt.Fprintf(os.Stderr, "Port number %d cannot be negative\n", cfg.ListenerPort)
os.Exit(1)
}
if *auth == true {
if cfg.AUTHURL == "" {
fmt.Fprintln(os.Stderr, "Auth is enabled but auth forwarding URL is not set")
os.Exit(1)
}
if _, err := url.Parse(cfg.AUTHURL); err != nil {
fmt.Fprintln(os.Stderr, "Invalid auth forwarding URL")
os.Exit(1)
}
}
aType := strings.ToUpper(*apiType)
if aType != keystore.REST && aType != keystore.GraphQL {
fmt.Fprintln(os.Stderr, `Auth forwarding endpoint type can only be either "REST" or "GRAPHQL"`)
os.Exit(1)
}
db, err := sql.Open(dbDriverName, cfg.DBURL)
if err != nil {
fmt.Fprintf(os.Stderr, "error opening database: %v\n", err)
os.Exit(1)
}
db.SetMaxOpenConns(cfg.MaxOpenDBConns)
db.SetMaxIdleConns(cfg.MaxIdleDBConns)
err = db.Ping()
if err != nil {
fmt.Fprintf(os.Stderr, "error accessing database: %v\n", err)
os.Exit(1)
}
cmd := flag.Arg(0)
switch cmd {
case "serve":
addr := ":" + strconv.Itoa(cfg.ListenerPort)
var authenticator *keystore.Authenticator
if *auth {
authenticator = &keystore.Authenticator{
URL: cfg.AUTHURL,
APIType: aType,
}
}
server := &http.Server{
Addr: addr,
Handler: keystore.ServeMux(keystore.NewService(ctx, db, authenticator)),
}
listener, err := net.Listen("tcp", addr)
if err != nil {
fmt.Fprintf(os.Stderr, "error listening: %v\n", err)
os.Exit(1)
}
listener = tcpKeepAliveListener{listener.(*net.TCPListener)}
if *tlsCert != "" {
cer, err := tls.LoadX509KeyPair(*tlsCert, *tlsKey)
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing TLS keypair: %v\n", err)
os.Exit(1)
}
listener = tls.NewListener(listener, &tls.Config{Certificates: []tls.Certificate{cer}})
}
go func() {
err := server.Serve(listener)
if err != nil {
panic(err)
}
}()
fmt.Fprintln(os.Stdout, "Server listening at https://localhost"+addr)
// block forever without using any resources so this process won't quit while
// the goroutine containing ListenAndServe is still working
select {}
case "migrate":
migrateCmd := flag.Arg(1)
switch migrateCmd {
case "up":
n, err := migrate.Exec(db, dbDriverName, keystoreMigrations, migrate.Up)
if err != nil {
fmt.Fprintf(os.Stderr, "error applying up migrations: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "Applied %d up migrations!\n", n)
case "down":
n, err := migrate.Exec(db, dbDriverName, keystoreMigrations, migrate.Down)
if err != nil {
fmt.Fprintf(os.Stderr, "error applying down migrations: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "Applied %d down migrations!\n", n)
case "redo":
migrations, _, err := migrate.PlanMigration(db, dbDriverName, keystoreMigrations, migrate.Down, 1)
if len(migrations) == 0 {
fmt.Fprintln(os.Stdout, "Nothing to do!")
os.Exit(0)
}
_, err = migrate.ExecMax(db, dbDriverName, keystoreMigrations, migrate.Down, 1)
if err != nil {
fmt.Fprintf(os.Stderr, "error applying the last down migration: %v\n", err)
os.Exit(1)
}
_, err = migrate.ExecMax(db, dbDriverName, keystoreMigrations, migrate.Up, 1)
if err != nil {
fmt.Fprintf(os.Stderr, "error applying the last up migration: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "Reapplied migration %s.\n", migrations[0].Id)
case "status":
unappliedMigrations := getUnappliedMigrations(db)
if len(unappliedMigrations) > 0 {
fmt.Fprintf(os.Stdout, "There are %d unapplied migrations:\n", len(unappliedMigrations))
for _, id := range unappliedMigrations {
fmt.Fprintln(os.Stdout, id)
}
} else {
fmt.Fprintln(os.Stdout, "All migrations have been applied!")
}
default:
fmt.Fprintf(os.Stderr, "unrecognized migration command: %q\n", migrateCmd)
os.Exit(1)
}
default:
fmt.Fprintf(os.Stderr, "unrecognized command: %q\n", cmd)
os.Exit(1)
}
}
// https://github.com/golang/go/blob/c5cf6624076a644906aa7ec5c91c4e01ccd375d3/src/net/http/server.go#L3272-L3288
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
tc, err := ln.AcceptTCP()
if err != nil {
return nil, err
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
func getUnappliedMigrations(db *sql.DB) []string {
migrations, err := keystoreMigrations.FindMigrations()
if err != nil {
fmt.Fprintf(os.Stderr, "error getting keystore migrations: %v\n", err)
os.Exit(1)
}
records, err := migrate.GetMigrationRecords(db, dbDriverName)
if err != nil {
fmt.Fprintf(os.Stderr, "error getting keystore migrations records: %v\n", err)
os.Exit(1)
}
unappliedMigrations := make(map[string]struct{})
for _, m := range migrations {
unappliedMigrations[m.Id] = struct{}{}
}
for _, r := range records {
if _, ok := unappliedMigrations[r.Id]; !ok {
fmt.Fprintf(os.Stdout, "Could not find migration file: %v\n", r.Id)
continue
}
delete(unappliedMigrations, r.Id)
}
result := make([]string, 0, len(unappliedMigrations))
for id := range unappliedMigrations {
result = append(result, id)
}
sort.Strings(result)
return result
}