This repository has been archived by the owner on Jul 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.go
283 lines (244 loc) · 8.97 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
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
"cloud.google.com/go/profiler"
"contrib.go.opencensus.io/exporter/stackdriver"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.opencensus.io/exporter/jaeger"
"go.opencensus.io/exporter/prometheus"
"go.opencensus.io/plugin/ocgrpc"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/plugin/ochttp/propagation/b3"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
"google.golang.org/grpc"
)
const (
port = "8080"
defaultCurrency = "USD"
cookieMaxAge = 60 * 60 * 48
cookiePrefix = "shop_"
cookieSessionID = cookiePrefix + "session-id"
cookieCurrency = cookiePrefix + "currency"
)
var (
whitelistedCurrencies = map[string]bool{
"USD": true,
"EUR": true,
"CAD": true,
"JPY": true,
"GBP": true,
"TRY": true}
)
type ctxKeySessionID struct{}
type frontendServer struct {
productCatalogSvcAddr string
productCatalogSvcConn *grpc.ClientConn
currencySvcAddr string
currencySvcConn *grpc.ClientConn
cartSvcAddr string
cartSvcConn *grpc.ClientConn
recommendationSvcAddr string
recommendationSvcConn *grpc.ClientConn
checkoutSvcAddr string
checkoutSvcConn *grpc.ClientConn
shippingSvcAddr string
shippingSvcConn *grpc.ClientConn
adSvcAddr string
adSvcConn *grpc.ClientConn
}
var stackdriverExporter view.Exporter
func main() {
ctx := context.Background()
log := logrus.New()
log.Level = logrus.DebugLevel
log.Formatter = &logrus.TextFormatter{}
go initProfiling(log, "frontend", "1.0.0")
go func (log logrus.FieldLogger) {
initTracing(log)
initStats(log)
}(log)
srvPort := port
if os.Getenv("PORT") != "" {
srvPort = os.Getenv("PORT")
}
addr := os.Getenv("LISTEN_ADDR")
svc := new(frontendServer)
mustMapEnv(&svc.productCatalogSvcAddr, "PRODUCT_CATALOG_SERVICE_ADDR")
mustMapEnv(&svc.currencySvcAddr, "CURRENCY_SERVICE_ADDR")
mustMapEnv(&svc.cartSvcAddr, "CART_SERVICE_ADDR")
mustMapEnv(&svc.recommendationSvcAddr, "RECOMMENDATION_SERVICE_ADDR")
mustMapEnv(&svc.checkoutSvcAddr, "CHECKOUT_SERVICE_ADDR")
mustMapEnv(&svc.shippingSvcAddr, "SHIPPING_SERVICE_ADDR")
mustMapEnv(&svc.adSvcAddr, "AD_SERVICE_ADDR")
svc.currencySvcConn = mustConnGRPC(ctx, svc.currencySvcAddr)
svc.productCatalogSvcConn = mustConnGRPC(ctx, svc.productCatalogSvcAddr)
svc.cartSvcConn = mustConnGRPC(ctx, svc.cartSvcAddr)
svc.recommendationSvcConn = mustConnGRPC(ctx, svc.recommendationSvcAddr)
svc.shippingSvcConn = mustConnGRPC(ctx, svc.shippingSvcAddr)
svc.checkoutSvcConn = mustConnGRPC(ctx, svc.checkoutSvcAddr)
svc.adSvcConn = mustConnGRPC(ctx, svc.adSvcAddr)
r := mux.NewRouter()
r.HandleFunc("/", svc.homeHandler).Methods(http.MethodGet, http.MethodHead)
r.HandleFunc("/product/{id}", svc.productHandler).Methods(http.MethodGet, http.MethodHead)
r.HandleFunc("/cart", svc.viewCartHandler).Methods(http.MethodGet, http.MethodHead)
r.HandleFunc("/cart", svc.addToCartHandler).Methods(http.MethodPost)
r.HandleFunc("/cart/empty", svc.emptyCartHandler).Methods(http.MethodPost)
r.HandleFunc("/setCurrency", svc.setCurrencyHandler).Methods(http.MethodPost)
r.HandleFunc("/logout", svc.logoutHandler).Methods(http.MethodGet)
r.HandleFunc("/cart/checkout", svc.placeOrderHandler).Methods(http.MethodPost)
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
r.HandleFunc("/robots.txt", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "User-agent: *\nDisallow: /") })
r.HandleFunc("/_healthz", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })
var handler http.Handler = r
handler = &logHandler{log: log, next: handler} // add logging
handler = ensureSessionID(handler) // add session ID
handler = &ochttp.Handler{ // add opencensus instrumentation
Handler: handler,
Propagation: &b3.HTTPFormat{}}
log.Infof("starting server on " + addr + ":" + srvPort)
log.Fatal(http.ListenAndServe(addr+":"+srvPort, handler))
}
func initJaegerTracing(log logrus.FieldLogger) {
// Register the Jaeger exporter to be able to retrieve
// the collected spans.
exporter, err := jaeger.NewExporter(jaeger.Options{
Endpoint: "http://jaeger:14268",
Process: jaeger.Process{
ServiceName: "frontend",
},
})
if err != nil {
log.Fatal(err)
}
trace.RegisterExporter(exporter)
}
func initPrometheusStatsExporter(log logrus.FieldLogger) *prometheus.Exporter {
exporter, err := prometheus.NewExporter(prometheus.Options{})
if err != nil {
log.Fatal("error registering prometheus exporter")
return nil
}
view.RegisterExporter(exporter)
return exporter
}
func startPrometheusExporter(log logrus.FieldLogger, exporter *prometheus.Exporter) {
addr := ":9090"
log.Infof("starting prometheus server at %s", addr)
http.Handle("/metrics", exporter)
log.Fatal(http.ListenAndServe(addr, nil))
}
func initStackDriverStatsExporter(log logrus.FieldLogger) {
// Reuse stactdriver exporter for stats if one is already created for tracing.
if stackdriverExporter == nil {
var err error
stackdriverExporter, err = stackdriver.NewExporter(stackdriver.Options{})
if err != nil {
// log.Warn is used since there are multiple backends (stackdriver & prometheus)
// to store the metrics. In production setup most likely you would use only one backend.
// In that case you should use log.Fatal.
log.Warn("error creating stackdriver exporter");
return
}
}
view.RegisterExporter(stackdriverExporter)
}
func initStats(log logrus.FieldLogger) {
log.Infof("init stats")
initStackDriverStatsExporter(log)
// Start prometheus exporter as well
exporter := initPrometheusStatsExporter(log)
go startPrometheusExporter(log, exporter)
if err := view.Register(ochttp.DefaultServerViews...); err != nil {
log.Fatal("error registering default http server views")
}
if err := view.Register(ocgrpc.DefaultClientViews...); err != nil {
log.Fatal("error registering default grpc client views")
}
}
func initTracing(log logrus.FieldLogger) {
// This is a demo app with low QPS. trace.AlwaysSample() is used here
// to make sure traces are available for observation and analysis.
// In a production environment or high QPS setup please use
// trace.ProbabilitySampler set at the desired probability.
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
initJaegerTracing(log)
// TODO(ahmetb) this method is duplicated in other microservices using Go
// since they are not sharing packages.
for i := 1; i <= 3; i++ {
log = log.WithField("retry", i)
exporter, err := stackdriver.NewExporter(stackdriver.Options{})
if err != nil {
// log.Warnf is used since there are multiple backends (stackdriver & jaeger)
// to store the traces. In production setup most likely you would use only one backend.
// In that case you should use log.Fatalf.
log.Warnf("failed to initialize stackdriver exporter: %+v", err)
} else {
trace.RegisterExporter(exporter)
log.Info("registered stackdriver tracing")
stackdriverExporter = exporter
return
}
d := time.Second * 20 * time.Duration(i)
log.Debugf("sleeping %v to retry initializing stackdriver exporter", d)
time.Sleep(d)
}
log.Warn("could not initialize stackdriver exporter after retrying, giving up")
}
func initProfiling(log logrus.FieldLogger, service, version string) {
// TODO(ahmetb) this method is duplicated in other microservices using Go
// since they are not sharing packages.
for i := 1; i <= 3; i++ {
log = log.WithField("retry", i)
if err := profiler.Start(profiler.Config{
Service: service,
ServiceVersion: version,
// ProjectID must be set if not running on GCP.
// ProjectID: "my-project",
}); err != nil {
log.Warnf("warn: failed to start profiler: %+v", err)
} else {
log.Info("started stackdriver profiler")
return
}
d := time.Second * 10 * time.Duration(i)
log.Debugf("sleeping %v to retry initializing stackdriver profiler", d)
time.Sleep(d)
}
log.Warn("warning: could not initialize stackdriver profiler after retrying, giving up")
}
func mustMapEnv(target *string, envKey string) {
v := os.Getenv(envKey)
if v == "" {
panic(fmt.Sprintf("environment variable %q not set", envKey))
}
*target = v
}
func mustConnGRPC(ctx context.Context, addr string) *grpc.ClientConn {
conn, err := grpc.DialContext(ctx, addr,
grpc.WithInsecure(),
grpc.WithStatsHandler(&ocgrpc.ClientHandler{}))
if err != nil {
panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
}
return conn
}