forked from elastic/opbeans-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
301 lines (274 loc) · 8.04 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gin-contrib/cache"
"github.com/gin-contrib/cache/persistence"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"github.com/gomodule/redigo/redis"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.elastic.co/apm"
"go.elastic.co/apm/module/apmgin"
"go.elastic.co/apm/module/apmhttp"
"go.elastic.co/apm/module/apmlogrus"
"go.elastic.co/apm/module/apmsql"
)
const (
cacheURLFormat = "'inmem' or 'redis://user:pass@host'"
indexTemplateName = "index"
)
var (
listenAddr = flag.String("listen", ":8000", "Address on which to listen for HTTP requests")
backendAddrs = flag.String("backend", "", "Comma-separated list of addresses of opbeans services to proxy API requests to ($OPBEANS_SERVICES)")
database = flag.String("db", "sqlite3::memory:", "Database URL")
frontendDir = flag.String("frontend", "frontend/build", "Frontend assets dir")
cacheURL = flag.String("cache", "inmem", "Cache URL ("+cacheURLFormat+")")
healthcheckAddr = flag.String("healthcheck", "", "Address to connect to for Docker healthchecking")
logLevel = &logLevelFlag{Level: logrus.InfoLevel}
logJSON = flag.Bool("log-json", false, "Format log records as JSON")
)
func init() {
flag.Var(logLevel, "log-level", "Set the log level (trace, debug, info, warn, error, fatal, panic)")
}
func main() {
flag.Parse()
logrus.SetLevel(logLevel.Level)
if *logJSON {
logrus.SetFormatter(newJSONFormatter())
}
logrus.AddHook(&apmlogrus.Hook{})
if *healthcheckAddr != "" {
if err := healthcheck(); err != nil {
logrus.Errorf("healthcheck failed: %s", err)
os.Exit(1)
}
return
}
// Instrument the default HTTP transport, so that outgoing
// (reverse-proxy) requests are reported as spans.
http.DefaultTransport = apmhttp.WrapRoundTripper(http.DefaultTransport, apmhttp.WithClientTrace())
if err := Main(); err != nil {
logrus.Fatal(err)
}
}
func Main() error {
frontendBuildDir := filepath.FromSlash(*frontendDir)
indexFilePath := filepath.Join(frontendBuildDir, "index.html")
faviconFilePath := filepath.Join(frontendBuildDir, "favicon.ico")
staticDirPath := filepath.Join(frontendBuildDir, "static")
imagesDirPath := filepath.Join(frontendBuildDir, "images")
var backendURLs []*url.URL
if *backendAddrs == "" {
*backendAddrs = os.Getenv("OPBEANS_SERVICES")
}
if *backendAddrs != "" {
for _, field := range strings.Split(*backendAddrs, ",") {
field = strings.TrimSpace(field)
if u, err := url.Parse(field); err == nil && u.Scheme != "" {
backendURLs = append(backendURLs, u)
continue
}
// Not an absolute URL, so should be a host or host/port pair.
hostport := field
if _, _, err := net.SplitHostPort(hostport); err != nil {
// A bare host was specified; assume the same port
// that we're listening on.
_, port, err := net.SplitHostPort(*listenAddr)
if err != nil {
port = "3000"
}
hostport = net.JoinHostPort(hostport, port)
}
backendURLs = append(backendURLs, &url.URL{Scheme: "http", Host: hostport})
}
}
// Read index.html, replace <head> with <head><script>...
// that injects the dynamic page load properties for RUM.
indexFileBytes, err := ioutil.ReadFile(indexFilePath)
if err != nil {
return err
}
indexFileContent := strings.Replace(string(indexFileBytes), "<head>", `<head>
<script type="text/javascript">
window.rumConfig = {
pageLoadTraceId: {{.TraceContext.Trace}},
pageLoadSpanId: {{.EnsureParent}},
pageLoadSampled: {{.Sampled}},
}
</script>`, 1)
indexTemplate, err := template.New(indexTemplateName).Parse(indexFileContent)
if err != nil {
return err
}
db, err := newDatabase()
if err != nil {
return err
}
defer db.Close()
cacheStore, err := newCache()
if err != nil {
return err
}
r := gin.New()
r.Use(cache.Cache(&cacheStore))
r.Use(apmgin.Middleware(r))
r.Use(logrusMiddleware)
pprof.Register(r)
r.Static("/static", staticDirPath)
r.Static("/images", imagesDirPath)
r.StaticFile("/favicon.ico", faviconFilePath)
r.SetHTMLTemplate(indexTemplate)
r.GET("/", handleIndex)
r.GET("/oopsie", handleOopsie)
r.GET("/rum-config.js", handleRUMConfig)
r.Use(func(c *gin.Context) {
// Paths used by the frontend for state.
for _, prefix := range []string{
"/dashboard",
"/products",
"/customers",
"/orders",
} {
if strings.HasPrefix(c.Request.URL.Path, prefix) {
tx := apm.TransactionFromContext(c.Request.Context())
if tx != nil {
tx.Name = c.Request.Method + " " + prefix
}
handleIndex(c)
return
}
}
c.Next()
})
// Create API routes. We install middleware for /api which probabilistically
// proxies these requests to another opbeans service to demonstrate distributed
// tracing, and test agent compatibility.
proxyProbability := 0.5
if value := os.Getenv("OPBEANS_DT_PROBABILITY"); value != "" {
f, err := strconv.ParseFloat(value, 64)
if err != nil {
return errors.Wrapf(err, "failed to parse OPBEANS_DT_PROBABILITY")
}
if f < 0.0 || f > 1.0 {
return errors.Errorf("invalid OPBEANS_DT_PROBABILITY value %s: out of range [0,1.0]", value)
}
proxyProbability = f
}
rand.Seed(time.Now().UnixNano())
maybeProxy := func(c *gin.Context) {
if len(backendURLs) > 0 && rand.Float64() < proxyProbability {
u := backendURLs[rand.Intn(len(backendURLs))]
logrus.WithFields(apmlogrus.TraceContext(c.Request.Context())).Infof("proxying API request to %s", u)
httputil.NewSingleHostReverseProxy(u).ServeHTTP(c.Writer, c.Request)
c.Abort()
return
}
c.Next()
}
apiGroup := r.Group("/api", maybeProxy)
addAPIHandlers(apiGroup, db)
return r.Run(*listenAddr)
}
func handleIndex(c *gin.Context) {
c.HTML(200, indexTemplateName, apm.TransactionFromContext(c.Request.Context()))
}
func handleRUMConfig(c *gin.Context) {
apmServerURL := os.Getenv("ELASTIC_APM_JS_SERVER_URL")
if apmServerURL == "" {
apmServerURL = "http://localhost:8200"
} else {
apmServerURL = template.JSEscapeString(apmServerURL)
}
content := fmt.Sprintf("window.elasticApmJsBaseServerUrl = '%s';\n", apmServerURL)
c.Data(200, "application/javascript", []byte(content))
}
func healthcheck() error {
resp, err := http.Get(fmt.Sprintf("http://%s/api/orders", *healthcheckAddr))
if err != nil {
return err
}
defer resp.Body.Close()
var orders []Order
return json.NewDecoder(resp.Body).Decode(&orders)
}
func newDatabase() (*sqlx.DB, error) {
fields := strings.SplitN(*database, ":", 2)
if len(fields) != 2 {
return nil, errors.Errorf(
"expected database URL with format %q, got %q",
"<driver>:<connection-string>",
*database,
)
}
driver := fields[0]
db, err := apmsql.Open(driver, fields[1])
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
db.Close()
return nil, err
}
dbx := sqlx.NewDb(db, driver)
if err := initDatabase(dbx, driver); err != nil {
db.Close()
return nil, err
}
return dbx, nil
}
func newCache() (persistence.CacheStore, error) {
const defaultExpiration = time.Minute
if *cacheURL == "inmem" {
return persistence.NewInMemoryStore(defaultExpiration), nil
}
if !strings.HasPrefix(*cacheURL, "redis") {
return nil, errors.Errorf(
"invalid cache URL %q, expected %s",
*cacheURL, cacheURLFormat,
)
}
redisPool := newRedisPool(*cacheURL)
return persistence.NewRedisCacheWithPool(redisPool, defaultExpiration), nil
}
func newRedisPool(url string) *redis.Pool {
return &redis.Pool{
MaxIdle: 5,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.DialURL(url)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if _, err := c.Do("PING"); err != nil {
return err
}
return nil
},
}
}
func handleOopsie(c *gin.Context) {
switch c.Query("type") {
case "string":
panic("boom")
case "pkg/errors":
err := errors.New("boom")
panic(errors.Wrap(err, "failure while shaking the room"))
default:
panic(fmt.Errorf("sonic %s", "boom"))
}
}