allenwang37 commited on
Commit
d6178ea
·
verified ·
1 Parent(s): ea2c272

Publish Cloud-OpsBench v1.0.0 benchmark artifacts (part 27)

Browse files

Source: https://github.com/LLM4Ops/Cloud-OpsBench/tree/ea05dafbc87b5985df8721622d63d4229c2b4224

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. benchmark/boutique/runtime/28/code/productcatalogservice/catalog_loader.go +161 -0
  2. benchmark/boutique/runtime/28/code/productcatalogservice/product_catalog.go +83 -0
  3. benchmark/boutique/runtime/28/code/productcatalogservice/server.go +217 -0
  4. benchmark/boutique/runtime/28/code/recommendationservice/client.py +39 -0
  5. benchmark/boutique/runtime/28/code/recommendationservice/logger.py +41 -0
  6. benchmark/boutique/runtime/28/code/recommendationservice/recommendation_server.py +156 -0
  7. benchmark/boutique/runtime/28/code/shippingservice/main.go +183 -0
  8. benchmark/boutique/runtime/28/code/shippingservice/quote.go +48 -0
  9. benchmark/boutique/runtime/28/code/shippingservice/tracker.go +47 -0
  10. benchmark/boutique/runtime/28/metadata.json +10 -0
  11. benchmark/boutique/runtime/28/raw_data/alert.json +1 -0
  12. benchmark/boutique/runtime/28/raw_data/k8s_states.json +0 -0
  13. benchmark/boutique/runtime/28/raw_data/logs.json +144 -0
  14. benchmark/boutique/runtime/28/tool_cache.json +0 -0
  15. benchmark/boutique/runtime/29/code/adservice/src/main/java/hipstershop/AdService.java +238 -0
  16. benchmark/boutique/runtime/29/code/adservice/src/main/java/hipstershop/AdServiceClient.java +116 -0
  17. benchmark/boutique/runtime/29/code/cartservice/src/Program.cs +26 -0
  18. benchmark/boutique/runtime/29/code/cartservice/src/Startup.cs +84 -0
  19. benchmark/boutique/runtime/29/code/cartservice/src/cartstore/AlloyDBCartStore.cs +177 -0
  20. benchmark/boutique/runtime/29/code/cartservice/src/cartstore/ICartStore.cs +26 -0
  21. benchmark/boutique/runtime/29/code/cartservice/src/cartstore/RedisCartStore.cs +118 -0
  22. benchmark/boutique/runtime/29/code/cartservice/src/cartstore/SpannerCartStore.cs +185 -0
  23. benchmark/boutique/runtime/29/code/cartservice/src/services/CartService.cs +51 -0
  24. benchmark/boutique/runtime/29/code/cartservice/src/services/HealthCheckService.cs +41 -0
  25. benchmark/boutique/runtime/29/code/checkoutservice/main.go +394 -0
  26. benchmark/boutique/runtime/29/code/checkoutservice/money/money.go +132 -0
  27. benchmark/boutique/runtime/29/code/currencyservice/client.js +68 -0
  28. benchmark/boutique/runtime/29/code/currencyservice/server.js +198 -0
  29. benchmark/boutique/runtime/29/code/emailservice/email_client.py +39 -0
  30. benchmark/boutique/runtime/29/code/emailservice/email_server.py +200 -0
  31. benchmark/boutique/runtime/29/code/emailservice/logger.py +41 -0
  32. benchmark/boutique/runtime/29/code/frontend/deployment_details.go +64 -0
  33. benchmark/boutique/runtime/29/code/frontend/handlers.go +635 -0
  34. benchmark/boutique/runtime/29/code/frontend/main.go +235 -0
  35. benchmark/boutique/runtime/29/code/frontend/middleware.go +111 -0
  36. benchmark/boutique/runtime/29/code/frontend/money/money.go +132 -0
  37. benchmark/boutique/runtime/29/code/frontend/packaging_info.go +79 -0
  38. benchmark/boutique/runtime/29/code/frontend/rpc.go +127 -0
  39. benchmark/boutique/runtime/29/code/frontend/validator/validator.go +83 -0
  40. benchmark/boutique/runtime/29/code/paymentservice/charge.js +86 -0
  41. benchmark/boutique/runtime/29/code/paymentservice/index.js +75 -0
  42. benchmark/boutique/runtime/29/code/paymentservice/logger.js +27 -0
  43. benchmark/boutique/runtime/29/code/paymentservice/server.js +106 -0
  44. benchmark/boutique/runtime/29/code/productcatalogservice/catalog_loader.go +161 -0
  45. benchmark/boutique/runtime/29/code/productcatalogservice/product_catalog.go +83 -0
  46. benchmark/boutique/runtime/29/code/productcatalogservice/server.go +217 -0
  47. benchmark/boutique/runtime/29/code/recommendationservice/client.py +39 -0
  48. benchmark/boutique/runtime/29/code/recommendationservice/logger.py +41 -0
  49. benchmark/boutique/runtime/29/code/recommendationservice/recommendation_server.py +156 -0
  50. benchmark/boutique/runtime/29/code/shippingservice/main.go +183 -0
benchmark/boutique/runtime/28/code/productcatalogservice/catalog_loader.go ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // https://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "bytes"
19
+ "context"
20
+ "fmt"
21
+ "net"
22
+ "os"
23
+ "strings"
24
+
25
+ "cloud.google.com/go/alloydbconn"
26
+ secretmanager "cloud.google.com/go/secretmanager/apiv1"
27
+ "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
28
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
29
+ "github.com/golang/protobuf/jsonpb"
30
+ "github.com/jackc/pgx/v5/pgxpool"
31
+ )
32
+
33
+ func loadCatalog(catalog *pb.ListProductsResponse) error {
34
+ catalogMutex.Lock()
35
+ defer catalogMutex.Unlock()
36
+
37
+ if os.Getenv("ALLOYDB_CLUSTER_NAME") != "" {
38
+ return loadCatalogFromAlloyDB(catalog)
39
+ }
40
+
41
+ return loadCatalogFromLocalFile(catalog)
42
+ }
43
+
44
+ func loadCatalogFromLocalFile(catalog *pb.ListProductsResponse) error {
45
+ log.Info("loading catalog from local products.json file...")
46
+
47
+ catalogJSON, err := os.ReadFile("products.json")
48
+ if err != nil {
49
+ log.Warnf("failed to open product catalog json file: %v", err)
50
+ return err
51
+ }
52
+
53
+ if err := jsonpb.Unmarshal(bytes.NewReader(catalogJSON), catalog); err != nil {
54
+ log.Warnf("failed to parse the catalog JSON: %v", err)
55
+ return err
56
+ }
57
+
58
+ log.Info("successfully parsed product catalog json")
59
+ return nil
60
+ }
61
+
62
+ func getSecretPayload(project, secret, version string) (string, error) {
63
+ ctx := context.Background()
64
+ client, err := secretmanager.NewClient(ctx)
65
+ if err != nil {
66
+ log.Warnf("failed to create SecretManager client: %v", err)
67
+ return "", err
68
+ }
69
+ defer client.Close()
70
+
71
+ req := &secretmanagerpb.AccessSecretVersionRequest{
72
+ Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, secret, version),
73
+ }
74
+
75
+ // Call the API.
76
+ result, err := client.AccessSecretVersion(ctx, req)
77
+ if err != nil {
78
+ log.Warnf("failed to access SecretVersion: %v", err)
79
+ return "", err
80
+ }
81
+
82
+ return string(result.Payload.Data), nil
83
+ }
84
+
85
+ func loadCatalogFromAlloyDB(catalog *pb.ListProductsResponse) error {
86
+ log.Info("loading catalog from AlloyDB...")
87
+
88
+ projectID := os.Getenv("PROJECT_ID")
89
+ region := os.Getenv("REGION")
90
+ pgClusterName := os.Getenv("ALLOYDB_CLUSTER_NAME")
91
+ pgInstanceName := os.Getenv("ALLOYDB_INSTANCE_NAME")
92
+ pgDatabaseName := os.Getenv("ALLOYDB_DATABASE_NAME")
93
+ pgTableName := os.Getenv("ALLOYDB_TABLE_NAME")
94
+ pgSecretName := os.Getenv("ALLOYDB_SECRET_NAME")
95
+
96
+ pgPassword, err := getSecretPayload(projectID, pgSecretName, "latest")
97
+ if err != nil {
98
+ return err
99
+ }
100
+
101
+ dialer, err := alloydbconn.NewDialer(context.Background())
102
+ if err != nil {
103
+ log.Warnf("failed to set-up dialer connection: %v", err)
104
+ return err
105
+ }
106
+ cleanup := func() error { return dialer.Close() }
107
+ defer cleanup()
108
+
109
+ dsn := fmt.Sprintf(
110
+ "user=%s password=%s dbname=%s sslmode=disable",
111
+ "postgres", pgPassword, pgDatabaseName,
112
+ )
113
+
114
+ config, err := pgxpool.ParseConfig(dsn)
115
+ if err != nil {
116
+ log.Warnf("failed to parse DSN config: %v", err)
117
+ return err
118
+ }
119
+
120
+ pgInstanceURI := fmt.Sprintf("projects/%s/locations/%s/clusters/%s/instances/%s", projectID, region, pgClusterName, pgInstanceName)
121
+ config.ConnConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) {
122
+ return dialer.Dial(ctx, pgInstanceURI)
123
+ }
124
+
125
+ pool, err := pgxpool.NewWithConfig(context.Background(), config)
126
+ if err != nil {
127
+ log.Warnf("failed to set-up pgx pool: %v", err)
128
+ return err
129
+ }
130
+ defer pool.Close()
131
+
132
+ query := "SELECT id, name, description, picture, price_usd_currency_code, price_usd_units, price_usd_nanos, categories FROM " + pgTableName
133
+ rows, err := pool.Query(context.Background(), query)
134
+ if err != nil {
135
+ log.Warnf("failed to query database: %v", err)
136
+ return err
137
+ }
138
+ defer rows.Close()
139
+
140
+ catalog.Products = catalog.Products[:0]
141
+ for rows.Next() {
142
+ product := &pb.Product{}
143
+ product.PriceUsd = &pb.Money{}
144
+
145
+ var categories string
146
+ err = rows.Scan(&product.Id, &product.Name, &product.Description,
147
+ &product.Picture, &product.PriceUsd.CurrencyCode, &product.PriceUsd.Units,
148
+ &product.PriceUsd.Nanos, &categories)
149
+ if err != nil {
150
+ log.Warnf("failed to scan query result row: %v", err)
151
+ return err
152
+ }
153
+ categories = strings.ToLower(categories)
154
+ product.Categories = strings.Split(categories, ",")
155
+
156
+ catalog.Products = append(catalog.Products, product)
157
+ }
158
+
159
+ log.Info("successfully parsed product catalog from AlloyDB")
160
+ return nil
161
+ }
benchmark/boutique/runtime/28/code/productcatalogservice/product_catalog.go ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "strings"
20
+ "time"
21
+
22
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
23
+ "google.golang.org/grpc/codes"
24
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
25
+ "google.golang.org/grpc/status"
26
+ )
27
+
28
+ type productCatalog struct {
29
+ pb.UnimplementedProductCatalogServiceServer
30
+ catalog pb.ListProductsResponse
31
+ }
32
+
33
+ func (p *productCatalog) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
34
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
35
+ }
36
+
37
+ func (p *productCatalog) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
38
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
39
+ }
40
+
41
+ func (p *productCatalog) ListProducts(context.Context, *pb.Empty) (*pb.ListProductsResponse, error) {
42
+ time.Sleep(extraLatency)
43
+
44
+ return &pb.ListProductsResponse{Products: p.parseCatalog()}, nil
45
+ }
46
+
47
+ func (p *productCatalog) GetProduct(ctx context.Context, req *pb.GetProductRequest) (*pb.Product, error) {
48
+ time.Sleep(extraLatency)
49
+
50
+ catalog := p.parseCatalog()
51
+ for _, product := range catalog {
52
+ if req.Id == product.Id {
53
+ return product, nil
54
+ }
55
+ }
56
+
57
+ return nil, status.Errorf(codes.NotFound, "no product with ID %s", req.Id)
58
+ }
59
+
60
+ func (p *productCatalog) SearchProducts(ctx context.Context, req *pb.SearchProductsRequest) (*pb.SearchProductsResponse, error) {
61
+ time.Sleep(extraLatency)
62
+
63
+ var ps []*pb.Product
64
+ for _, product := range p.parseCatalog() {
65
+ if strings.Contains(strings.ToLower(product.Name), strings.ToLower(req.Query)) ||
66
+ strings.Contains(strings.ToLower(product.Description), strings.ToLower(req.Query)) {
67
+ ps = append(ps, product)
68
+ }
69
+ }
70
+
71
+ return &pb.SearchProductsResponse{Results: ps}, nil
72
+ }
73
+
74
+ func (p *productCatalog) parseCatalog() []*pb.Product {
75
+ if reloadCatalog || len(p.catalog.Products) == 0 {
76
+ err := loadCatalog(&p.catalog)
77
+ if err != nil {
78
+ return []*pb.Product{}
79
+ }
80
+ }
81
+
82
+ return p.catalog.Products
83
+ }
benchmark/boutique/runtime/28/code/productcatalogservice/server.go ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "flag"
20
+ "fmt"
21
+ "net"
22
+ "os"
23
+ "os/signal"
24
+ "sync"
25
+ "syscall"
26
+ "time"
27
+
28
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
29
+ "google.golang.org/grpc/credentials/insecure"
30
+ "google.golang.org/grpc/health"
31
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
32
+
33
+ "cloud.google.com/go/profiler"
34
+ "github.com/pkg/errors"
35
+ "github.com/sirupsen/logrus"
36
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
37
+ "go.opentelemetry.io/otel"
38
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
39
+ "go.opentelemetry.io/otel/propagation"
40
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
41
+ "google.golang.org/grpc"
42
+ )
43
+
44
+ var (
45
+ catalogMutex *sync.Mutex
46
+ log *logrus.Logger
47
+ extraLatency time.Duration
48
+
49
+ port = "3550"
50
+
51
+ reloadCatalog bool
52
+ )
53
+
54
+ func init() {
55
+ log = logrus.New()
56
+ log.Formatter = &logrus.JSONFormatter{
57
+ FieldMap: logrus.FieldMap{
58
+ logrus.FieldKeyTime: "timestamp",
59
+ logrus.FieldKeyLevel: "severity",
60
+ logrus.FieldKeyMsg: "message",
61
+ },
62
+ TimestampFormat: time.RFC3339Nano,
63
+ }
64
+ log.Out = os.Stdout
65
+ catalogMutex = &sync.Mutex{}
66
+ }
67
+
68
+ func main() {
69
+ if os.Getenv("ENABLE_TRACING") == "1" {
70
+ err := initTracing()
71
+ if err != nil {
72
+ log.Warnf("warn: failed to start tracer: %+v", err)
73
+ }
74
+ } else {
75
+ log.Info("Tracing disabled.")
76
+ }
77
+
78
+ if os.Getenv("DISABLE_PROFILER") == "" {
79
+ log.Info("Profiling enabled.")
80
+ go initProfiling("productcatalogservice", "1.0.0")
81
+ } else {
82
+ log.Info("Profiling disabled.")
83
+ }
84
+
85
+ flag.Parse()
86
+
87
+ // set injected latency
88
+ if s := os.Getenv("EXTRA_LATENCY"); s != "" {
89
+ v, err := time.ParseDuration(s)
90
+ if err != nil {
91
+ log.Fatalf("failed to parse EXTRA_LATENCY (%s) as time.Duration: %+v", v, err)
92
+ }
93
+ extraLatency = v
94
+ log.Infof("extra latency enabled (duration: %v)", extraLatency)
95
+ } else {
96
+ extraLatency = time.Duration(0)
97
+ }
98
+
99
+ sigs := make(chan os.Signal, 1)
100
+ signal.Notify(sigs, syscall.SIGUSR1, syscall.SIGUSR2)
101
+ go func() {
102
+ for {
103
+ sig := <-sigs
104
+ log.Printf("Received signal: %s", sig)
105
+ if sig == syscall.SIGUSR1 {
106
+ reloadCatalog = true
107
+ log.Infof("Enable catalog reloading")
108
+ } else {
109
+ reloadCatalog = false
110
+ log.Infof("Disable catalog reloading")
111
+ }
112
+ }
113
+ }()
114
+
115
+ if os.Getenv("PORT") != "" {
116
+ port = os.Getenv("PORT")
117
+ }
118
+ log.Infof("starting grpc server at :%s", port)
119
+ run(port)
120
+ select {}
121
+ }
122
+
123
+ func run(port string) string {
124
+ listener, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
125
+ if err != nil {
126
+ log.Fatal(err)
127
+ }
128
+
129
+ // Propagate trace context
130
+ otel.SetTextMapPropagator(
131
+ propagation.NewCompositeTextMapPropagator(
132
+ propagation.TraceContext{}, propagation.Baggage{}))
133
+ var srv *grpc.Server
134
+ srv = grpc.NewServer(
135
+ grpc.StatsHandler(otelgrpc.NewServerHandler()))
136
+
137
+ svc := &productCatalog{}
138
+ err = loadCatalog(&svc.catalog)
139
+ if err != nil {
140
+ log.Fatalf("could not parse product catalog: %v", err)
141
+ }
142
+
143
+ pb.RegisterProductCatalogServiceServer(srv, svc)
144
+ healthcheck := health.NewServer()
145
+ healthpb.RegisterHealthServer(srv, healthcheck)
146
+ go srv.Serve(listener)
147
+
148
+ return listener.Addr().String()
149
+ }
150
+
151
+ func initStats() {
152
+ // TODO(drewbr) Implement OpenTelemetry stats
153
+ }
154
+
155
+ func initTracing() error {
156
+ var (
157
+ collectorAddr string
158
+ collectorConn *grpc.ClientConn
159
+ )
160
+
161
+ ctx := context.Background()
162
+
163
+ mustMapEnv(&collectorAddr, "COLLECTOR_SERVICE_ADDR")
164
+ mustConnGRPC(ctx, &collectorConn, collectorAddr)
165
+
166
+ exporter, err := otlptracegrpc.New(
167
+ ctx,
168
+ otlptracegrpc.WithGRPCConn(collectorConn))
169
+ if err != nil {
170
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
171
+ }
172
+ tp := sdktrace.NewTracerProvider(
173
+ sdktrace.WithBatcher(exporter),
174
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
175
+ otel.SetTracerProvider(tp)
176
+ return err
177
+ }
178
+
179
+ func initProfiling(service, version string) {
180
+ for i := 1; i <= 3; i++ {
181
+ if err := profiler.Start(profiler.Config{
182
+ Service: service,
183
+ ServiceVersion: version,
184
+ // ProjectID must be set if not running on GCP.
185
+ // ProjectID: "my-project",
186
+ }); err != nil {
187
+ log.Warnf("failed to start profiler: %+v", err)
188
+ } else {
189
+ log.Info("started Stackdriver profiler")
190
+ return
191
+ }
192
+ d := time.Second * 10 * time.Duration(i)
193
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
194
+ time.Sleep(d)
195
+ }
196
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
197
+ }
198
+
199
+ func mustMapEnv(target *string, envKey string) {
200
+ v := os.Getenv(envKey)
201
+ if v == "" {
202
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
203
+ }
204
+ *target = v
205
+ }
206
+
207
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
208
+ var err error
209
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
210
+ defer cancel()
211
+ *conn, err = grpc.NewClient(addr,
212
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
213
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
214
+ if err != nil {
215
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
216
+ }
217
+ }
benchmark/boutique/runtime/28/code/recommendationservice/client.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import sys
18
+ import grpc
19
+ import demo_pb2
20
+ import demo_pb2_grpc
21
+
22
+ from logger import getJSONLogger
23
+ logger = getJSONLogger('recommendationservice-server')
24
+
25
+ if __name__ == "__main__":
26
+ # get port
27
+ if len(sys.argv) > 1:
28
+ port = sys.argv[1]
29
+ else:
30
+ port = "8080"
31
+
32
+ # set up server stub
33
+ channel = grpc.insecure_channel('localhost:'+port)
34
+ stub = demo_pb2_grpc.RecommendationServiceStub(channel)
35
+ # form request
36
+ request = demo_pb2.ListRecommendationsRequest(user_id="test", product_ids=["test"])
37
+ # make call to server
38
+ response = stub.ListRecommendations(request)
39
+ logger.info(response)
benchmark/boutique/runtime/28/code/recommendationservice/logger.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import sys
19
+ from pythonjsonlogger import jsonlogger
20
+
21
+ # TODO(yoshifumi) this class is duplicated since other Python services are
22
+ # not sharing the modules for logging.
23
+ class CustomJsonFormatter(jsonlogger.JsonFormatter):
24
+ def add_fields(self, log_record, record, message_dict):
25
+ super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
26
+ if not log_record.get('timestamp'):
27
+ log_record['timestamp'] = record.created
28
+ if log_record.get('severity'):
29
+ log_record['severity'] = log_record['severity'].upper()
30
+ else:
31
+ log_record['severity'] = record.levelname
32
+
33
+ def getJSONLogger(name):
34
+ logger = logging.getLogger(name)
35
+ handler = logging.StreamHandler(sys.stdout)
36
+ formatter = CustomJsonFormatter('%(timestamp)s %(severity)s %(name)s %(message)s')
37
+ handler.setFormatter(formatter)
38
+ logger.addHandler(handler)
39
+ logger.setLevel(logging.INFO)
40
+ logger.propagate = False
41
+ return logger
benchmark/boutique/runtime/28/code/recommendationservice/recommendation_server.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import random
19
+ import time
20
+ import traceback
21
+ from concurrent import futures
22
+
23
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
24
+ # import googlecloudprofiler
25
+
26
+ from google.auth.exceptions import DefaultCredentialsError
27
+ import grpc
28
+
29
+ import demo_pb2
30
+ import demo_pb2_grpc
31
+ from grpc_health.v1 import health_pb2
32
+ from grpc_health.v1 import health_pb2_grpc
33
+
34
+ from opentelemetry import trace
35
+ from opentelemetry.instrumentation.grpc import GrpcInstrumentorClient, GrpcInstrumentorServer
36
+ from opentelemetry.sdk.trace import TracerProvider
37
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
38
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
39
+
40
+ from logger import getJSONLogger
41
+ logger = getJSONLogger('recommendationservice-server')
42
+
43
+ def initStackdriverProfiling():
44
+ project_id = None
45
+ try:
46
+ project_id = os.environ["GCP_PROJECT_ID"]
47
+ except KeyError:
48
+ # Environment variable not set
49
+ pass
50
+
51
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
52
+ # for retry in range(1,4):
53
+ # try:
54
+ # if project_id:
55
+ # googlecloudprofiler.start(service='recommendation_server', service_version='1.0.0', verbose=0, project_id=project_id)
56
+ # else:
57
+ # googlecloudprofiler.start(service='recommendation_server', service_version='1.0.0', verbose=0)
58
+ # logger.info("Successfully started Stackdriver Profiler.")
59
+ # return
60
+ # except (BaseException) as exc:
61
+ # logger.info("Unable to start Stackdriver Profiler Python agent. " + str(exc))
62
+ # if (retry < 4):
63
+ # logger.info("Sleeping %d seconds to retry Stackdriver Profiler agent initialization"%(retry*10))
64
+ # time.sleep (1)
65
+ # else:
66
+ # logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up")
67
+ return
68
+
69
+ class RecommendationService(demo_pb2_grpc.RecommendationServiceServicer):
70
+ def ListRecommendations(self, request, context):
71
+ max_responses = 5
72
+ # fetch list of products from product catalog stub
73
+ cat_response = product_catalog_stub.ListProducts(demo_pb2.Empty())
74
+ product_ids = [x.id for x in cat_response.products]
75
+ filtered_products = list(set(product_ids)-set(request.product_ids))
76
+ num_products = len(filtered_products)
77
+ num_return = min(max_responses, num_products)
78
+ # sample list of indicies to return
79
+ indices = random.sample(range(num_products), num_return)
80
+ # fetch product ids from indices
81
+ prod_list = [filtered_products[i] for i in indices]
82
+ logger.info("[Recv ListRecommendations] product_ids={}".format(prod_list))
83
+ # build and return response
84
+ response = demo_pb2.ListRecommendationsResponse()
85
+ response.product_ids.extend(prod_list)
86
+ return response
87
+
88
+ def Check(self, request, context):
89
+ return health_pb2.HealthCheckResponse(
90
+ status=health_pb2.HealthCheckResponse.SERVING)
91
+
92
+ def Watch(self, request, context):
93
+ return health_pb2.HealthCheckResponse(
94
+ status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ logger.info("initializing recommendationservice")
99
+
100
+ try:
101
+ if "DISABLE_PROFILER" in os.environ:
102
+ raise KeyError()
103
+ else:
104
+ logger.info("Profiler enabled.")
105
+ initStackdriverProfiling()
106
+ except KeyError:
107
+ logger.info("Profiler disabled.")
108
+
109
+ try:
110
+ grpc_client_instrumentor = GrpcInstrumentorClient()
111
+ grpc_client_instrumentor.instrument()
112
+ grpc_server_instrumentor = GrpcInstrumentorServer()
113
+ grpc_server_instrumentor.instrument()
114
+ if os.environ["ENABLE_TRACING"] == "1":
115
+ trace.set_tracer_provider(TracerProvider())
116
+ otel_endpoint = os.getenv("COLLECTOR_SERVICE_ADDR", "localhost:4317")
117
+ trace.get_tracer_provider().add_span_processor(
118
+ BatchSpanProcessor(
119
+ OTLPSpanExporter(
120
+ endpoint = otel_endpoint,
121
+ insecure = True
122
+ )
123
+ )
124
+ )
125
+ except (KeyError, DefaultCredentialsError):
126
+ logger.info("Tracing disabled.")
127
+ except Exception as e:
128
+ logger.warn(f"Exception on Cloud Trace setup: {traceback.format_exc()}, tracing disabled.")
129
+
130
+ port = os.environ.get('PORT', "8080")
131
+ catalog_addr = os.environ.get('PRODUCT_CATALOG_SERVICE_ADDR', '')
132
+ if catalog_addr == "":
133
+ raise Exception('PRODUCT_CATALOG_SERVICE_ADDR environment variable not set')
134
+ logger.info("product catalog address: " + catalog_addr)
135
+ channel = grpc.insecure_channel(catalog_addr)
136
+ product_catalog_stub = demo_pb2_grpc.ProductCatalogServiceStub(channel)
137
+
138
+ # create gRPC server
139
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
140
+
141
+ # add class to gRPC server
142
+ service = RecommendationService()
143
+ demo_pb2_grpc.add_RecommendationServiceServicer_to_server(service, server)
144
+ health_pb2_grpc.add_HealthServicer_to_server(service, server)
145
+
146
+ # start server
147
+ logger.info("listening on port: " + port)
148
+ server.add_insecure_port('[::]:'+port)
149
+ server.start()
150
+
151
+ # keep alive
152
+ try:
153
+ while True:
154
+ time.sleep(10000)
155
+ except KeyboardInterrupt:
156
+ server.stop(0)
benchmark/boutique/runtime/28/code/shippingservice/main.go ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "net"
20
+ "os"
21
+ "time"
22
+
23
+ "cloud.google.com/go/profiler"
24
+ "github.com/sirupsen/logrus"
25
+ "golang.org/x/net/context"
26
+ "google.golang.org/grpc"
27
+ "google.golang.org/grpc/codes"
28
+ "google.golang.org/grpc/health"
29
+ "google.golang.org/grpc/reflection"
30
+ "google.golang.org/grpc/status"
31
+
32
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/shippingservice/genproto"
33
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
34
+ )
35
+
36
+ const (
37
+ defaultPort = "50051"
38
+ )
39
+
40
+ var log *logrus.Logger
41
+
42
+ func init() {
43
+ log = logrus.New()
44
+ log.Level = logrus.DebugLevel
45
+ log.Formatter = &logrus.JSONFormatter{
46
+ FieldMap: logrus.FieldMap{
47
+ logrus.FieldKeyTime: "timestamp",
48
+ logrus.FieldKeyLevel: "severity",
49
+ logrus.FieldKeyMsg: "message",
50
+ },
51
+ TimestampFormat: time.RFC3339Nano,
52
+ }
53
+ log.Out = os.Stdout
54
+ }
55
+
56
+ func main() {
57
+ if os.Getenv("DISABLE_TRACING") == "" {
58
+ log.Info("Tracing enabled, but temporarily unavailable")
59
+ log.Info("See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.")
60
+ go initTracing()
61
+ } else {
62
+ log.Info("Tracing disabled.")
63
+ }
64
+
65
+ if os.Getenv("DISABLE_PROFILER") == "" {
66
+ log.Info("Profiling enabled.")
67
+ go initProfiling("shippingservice", "1.0.0")
68
+ } else {
69
+ log.Info("Profiling disabled.")
70
+ }
71
+
72
+ port := defaultPort
73
+ if value, ok := os.LookupEnv("PORT"); ok {
74
+ port = value
75
+ }
76
+ port = fmt.Sprintf(":%s", port)
77
+
78
+ lis, err := net.Listen("tcp", port)
79
+ if err != nil {
80
+ log.Fatalf("failed to listen: %v", err)
81
+ }
82
+
83
+ var srv *grpc.Server
84
+ if os.Getenv("DISABLE_STATS") == "" {
85
+ log.Info("Stats enabled, but temporarily unavailable")
86
+ srv = grpc.NewServer()
87
+ } else {
88
+ log.Info("Stats disabled.")
89
+ srv = grpc.NewServer()
90
+ }
91
+ svc := &server{}
92
+ pb.RegisterShippingServiceServer(srv, svc)
93
+ healthcheck := health.NewServer()
94
+ healthpb.RegisterHealthServer(srv, healthcheck)
95
+ log.Infof("Shipping Service listening on port %s", port)
96
+
97
+ // Register reflection service on gRPC server.
98
+ reflection.Register(srv)
99
+ if err := srv.Serve(lis); err != nil {
100
+ log.Fatalf("failed to serve: %v", err)
101
+ }
102
+ }
103
+
104
+ // server controls RPC service responses.
105
+ type server struct {
106
+ pb.UnimplementedShippingServiceServer
107
+ }
108
+
109
+ // Check is for health checking.
110
+ func (s *server) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
111
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
112
+ }
113
+
114
+ func (s *server) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
115
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
116
+ }
117
+
118
+ // GetQuote produces a shipping quote (cost) in USD.
119
+ func (s *server) GetQuote(ctx context.Context, in *pb.GetQuoteRequest) (*pb.GetQuoteResponse, error) {
120
+ log.Info("[GetQuote] received request")
121
+ defer log.Info("[GetQuote] completed request")
122
+
123
+ // 1. Generate a quote based on the total number of items to be shipped.
124
+ count := 0
125
+ for _, item := range in.Items {
126
+ count += int(item.Quantity)
127
+ }
128
+ quote := CreateQuoteFromCount(count)
129
+
130
+ // 2. Generate a response.
131
+ return &pb.GetQuoteResponse{
132
+ CostUsd: &pb.Money{
133
+ CurrencyCode: "USD",
134
+ Units: int64(quote.Dollars),
135
+ Nanos: int32(quote.Cents * 10000000)},
136
+ }, nil
137
+
138
+ }
139
+
140
+ // ShipOrder mocks that the requested items will be shipped.
141
+ // It supplies a tracking ID for notional lookup of shipment delivery status.
142
+ func (s *server) ShipOrder(ctx context.Context, in *pb.ShipOrderRequest) (*pb.ShipOrderResponse, error) {
143
+ log.Info("[ShipOrder] received request")
144
+ defer log.Info("[ShipOrder] completed request")
145
+ // 1. Create a Tracking ID
146
+ baseAddress := fmt.Sprintf("%s, %s, %s", in.Address.StreetAddress, in.Address.City, in.Address.State)
147
+ id := CreateTrackingId(baseAddress)
148
+
149
+ // 2. Generate a response.
150
+ return &pb.ShipOrderResponse{
151
+ TrackingId: id,
152
+ }, nil
153
+ }
154
+
155
+ func initStats() {
156
+ //TODO(arbrown) Implement OpenTelemetry stats
157
+ }
158
+
159
+ func initTracing() {
160
+ // TODO(arbrown) Implement OpenTelemetry tracing
161
+ }
162
+
163
+ func initProfiling(service, version string) {
164
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
165
+ // since they are not sharing packages.
166
+ for i := 1; i <= 3; i++ {
167
+ if err := profiler.Start(profiler.Config{
168
+ Service: service,
169
+ ServiceVersion: version,
170
+ // ProjectID must be set if not running on GCP.
171
+ // ProjectID: "my-project",
172
+ }); err != nil {
173
+ log.Warnf("failed to start profiler: %+v", err)
174
+ } else {
175
+ log.Info("started Stackdriver profiler")
176
+ return
177
+ }
178
+ d := time.Second * 10 * time.Duration(i)
179
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
180
+ time.Sleep(d)
181
+ }
182
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
183
+ }
benchmark/boutique/runtime/28/code/shippingservice/quote.go ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "math"
20
+ )
21
+
22
+ // Quote represents a currency value.
23
+ type Quote struct {
24
+ Dollars uint32
25
+ Cents uint32
26
+ }
27
+
28
+ // String representation of the Quote.
29
+ func (q Quote) String() string {
30
+ return fmt.Sprintf("$%d.%d", q.Dollars, q.Cents)
31
+ }
32
+
33
+ // CreateQuoteFromCount takes a number of items and returns a shipping quote.
34
+ func CreateQuoteFromCount(count int) Quote {
35
+ if count == 0 {
36
+ return CreateQuoteFromFloat(0)
37
+ }
38
+ return CreateQuoteFromFloat(8.99)
39
+ }
40
+
41
+ // CreateQuoteFromFloat takes a price represented as a float and creates a Price struct.
42
+ func CreateQuoteFromFloat(value float64) Quote {
43
+ units, fraction := math.Modf(value)
44
+ return Quote{
45
+ uint32(units),
46
+ uint32(math.Trunc(fraction * 100)),
47
+ }
48
+ }
benchmark/boutique/runtime/28/code/shippingservice/tracker.go ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "math/rand"
20
+ )
21
+
22
+ // CreateTrackingId generates a tracking ID.
23
+ func CreateTrackingId(salt string) string {
24
+ return fmt.Sprintf("%c%c-%d%s-%d%s",
25
+ getRandomLetterCode(),
26
+ getRandomLetterCode(),
27
+ len(salt),
28
+ getRandomNumber(3),
29
+ len(salt)/2,
30
+ getRandomNumber(7),
31
+ )
32
+ }
33
+
34
+ // getRandomLetterCode generates a code point value for a capital letter.
35
+ func getRandomLetterCode() uint32 {
36
+ return 65 + uint32(rand.Intn(25))
37
+ }
38
+
39
+ // getRandomNumber generates a string representation of a number with the requested number of digits.
40
+ func getRandomNumber(digits int) string {
41
+ str := ""
42
+ for i := 0; i < digits; i++ {
43
+ str = fmt.Sprintf("%s%d", str, rand.Intn(10))
44
+ }
45
+
46
+ return str
47
+ }
benchmark/boutique/runtime/28/metadata.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "namespace": "boutique",
3
+ "query": "Partial Service Unreachability.",
4
+ "difficulty": "easy",
5
+ "result": {
6
+ "fault_taxonomy": "Runtime_Fault",
7
+ "fault_object": "app/productcatalogservice",
8
+ "root_cause": "container_memory_limit_too_low"
9
+ }
10
+ }
benchmark/boutique/runtime/28/raw_data/alert.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
benchmark/boutique/runtime/28/raw_data/k8s_states.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/boutique/runtime/28/raw_data/logs.json ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adservice": [
3
+ "{\"instant\":{\"epochSecond\":1762805164,\"nanoOfSecond\":803444760},\"thread\":\"Thread-0\",\"level\":\"INFO\",\"loggerName\":\"hipstershop.AdService\",\"message\":\"Stats enabled, but temporarily unavailable\",\"endOfBatch\":false,\"loggerFqcn\":\"org.apache.logging.log4j.spi.AbstractLogger\",\"threadId\":15,\"threadPriority\":5,\"logging.googleapis.com/trace\":\"${ctx:traceId}\",\"logging.googleapis.com/spanId\":\"${ctx:spanId}\",\"logging.googleapis.com/traceSampled\":\"${ctx:traceSampled}\",\"time\":\"2025-11-10T20:06:04.803Z\"}",
4
+ "{\"instant\":{\"epochSecond\":1762805164,\"nanoOfSecond\":803448601},\"thread\":\"main\",\"level\":\"INFO\",\"loggerName\":\"hipstershop.AdService\",\"message\":\"AdService starting.\",\"endOfBatch\":false,\"loggerFqcn\":\"org.apache.logging.log4j.spi.AbstractLogger\",\"threadId\":1,\"threadPriority\":5,\"logging.googleapis.com/trace\":\"${ctx:traceId}\",\"logging.googleapis.com/spanId\":\"${ctx:spanId}\",\"logging.googleapis.com/traceSampled\":\"${ctx:traceSampled}\",\"time\":\"2025-11-10T20:06:04.803Z\"}",
5
+ "{\"instant\":{\"epochSecond\":1762805165,\"nanoOfSecond\":402835521},\"thread\":\"Thread-0\",\"level\":\"INFO\",\"loggerName\":\"hipstershop.AdService\",\"message\":\"Tracing enabled but temporarily unavailable\",\"endOfBatch\":false,\"loggerFqcn\":\"org.apache.logging.log4j.spi.AbstractLogger\",\"threadId\":15,\"threadPriority\":5,\"logging.googleapis.com/trace\":\"${ctx:traceId}\",\"logging.googleapis.com/spanId\":\"${ctx:spanId}\",\"logging.googleapis.com/traceSampled\":\"${ctx:traceSampled}\",\"time\":\"2025-11-10T20:06:05.402Z\"}",
6
+ "{\"instant\":{\"epochSecond\":1762805165,\"nanoOfSecond\":404000920},\"thread\":\"Thread-0\",\"level\":\"INFO\",\"loggerName\":\"hipstershop.AdService\",\"message\":\"See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.\",\"endOfBatch\":false,\"loggerFqcn\":\"org.apache.logging.log4j.spi.AbstractLogger\",\"threadId\":15,\"threadPriority\":5,\"logging.googleapis.com/trace\":\"${ctx:traceId}\",\"logging.googleapis.com/spanId\":\"${ctx:spanId}\",\"logging.googleapis.com/traceSampled\":\"${ctx:traceSampled}\",\"time\":\"2025-11-10T20:06:05.404Z\"}",
7
+ "{\"instant\":{\"epochSecond\":1762805165,\"nanoOfSecond\":404564403},\"thread\":\"Thread-0\",\"level\":\"INFO\",\"loggerName\":\"hipstershop.AdService\",\"message\":\"Tracing enabled - Stackdriver exporter initialized.\",\"endOfBatch\":false,\"loggerFqcn\":\"org.apache.logging.log4j.spi.AbstractLogger\",\"threadId\":15,\"threadPriority\":5,\"logging.googleapis.com/trace\":\"${ctx:traceId}\",\"logging.googleapis.com/spanId\":\"${ctx:spanId}\",\"logging.googleapis.com/traceSampled\":\"${ctx:traceSampled}\",\"time\":\"2025-11-10T20:06:05.404Z\"}",
8
+ "{\"instant\":{\"epochSecond\":1762805166,\"nanoOfSecond\":609708114},\"thread\":\"main\",\"level\":\"INFO\",\"loggerName\":\"hipstershop.AdService\",\"message\":\"Ad Service started, listening on 9555\",\"endOfBatch\":false,\"loggerFqcn\":\"org.apache.logging.log4j.spi.AbstractLogger\",\"threadId\":1,\"threadPriority\":5,\"logging.googleapis.com/trace\":\"${ctx:traceId}\",\"logging.googleapis.com/spanId\":\"${ctx:spanId}\",\"logging.googleapis.com/traceSampled\":\"${ctx:traceSampled}\",\"time\":\"2025-11-10T20:06:06.609Z\"}"
9
+ ],
10
+ "cartservice": [
11
+ "info: Microsoft.Hosting.Lifetime[14]",
12
+ "Now listening on: http://[::]:7070",
13
+ "info: Microsoft.Hosting.Lifetime[0]",
14
+ "Application started. Press Ctrl+C to shut down.",
15
+ "info: Microsoft.Hosting.Lifetime[0]",
16
+ "Hosting environment: Production",
17
+ "info: Microsoft.Hosting.Lifetime[0]",
18
+ "Content root path: /app"
19
+ ],
20
+ "checkoutservice": [
21
+ "{\"message\":\"Tracing disabled.\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.128069993Z\"}",
22
+ "{\"message\":\"Profiling disabled.\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.128119477Z\"}",
23
+ "{\"message\":\"service config: \\u0026{UnimplementedCheckoutServiceServer:{} productCatalogSvcAddr:productcatalogservice:3550 productCatalogSvcConn:0xc000131008 cartSvcAddr:cartservice:7070 cartSvcConn:0xc000131408 currencySvcAddr:currencyservice:7000 currencySvcConn:0xc000131808 shippingSvcAddr:shippingservice:50051 shippingSvcConn:0xc000130c08 emailSvcAddr:emailservice:5000 emailSvcConn:0xc000131c08 paymentSvcAddr:paymentservice:50051 paymentSvcConn:0xc0004bc008}\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.130402583Z\"}",
24
+ "{\"message\":\"starting to listen on tcp: \\\"[::]:5050\\\"\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.130627097Z\"}"
25
+ ],
26
+ "currencyservice": [
27
+ "{\"severity\":\"info\",\"time\":1762805161617,\"pid\":1,\"hostname\":\"currencyservice-75686c9564-qrnb9\",\"name\":\"currencyservice-server\",\"message\":\"Profiler disabled.\"}",
28
+ "{\"severity\":\"info\",\"time\":1762805162119,\"pid\":1,\"hostname\":\"currencyservice-75686c9564-qrnb9\",\"name\":\"currencyservice-server\",\"message\":\"Tracing disabled.\"}",
29
+ "{\"severity\":\"info\",\"time\":1762805163109,\"pid\":1,\"hostname\":\"currencyservice-75686c9564-qrnb9\",\"name\":\"currencyservice-server\",\"message\":\"Starting gRPC server on port 7000...\"}",
30
+ "(node:1) DeprecationWarning: Calling start() is no longer necessary. It can be safely omitted.",
31
+ "(Use `node --trace-deprecation ...` to show where the warning was created)",
32
+ "{\"severity\":\"info\",\"time\":1762805163304,\"pid\":1,\"hostname\":\"currencyservice-75686c9564-qrnb9\",\"name\":\"currencyservice-server\",\"message\":\"CurrencyService gRPC server started on port 7000\"}"
33
+ ],
34
+ "emailservice": [
35
+ "/usr/local/lib/python3.12/site-packages/google/rpc/__init__.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81.",
36
+ "import pkg_resources",
37
+ "{\"timestamp\": 1762805165.119737, \"severity\": \"INFO\", \"name\": \"emailservice-server\", \"message\": \"starting the email service in dummy mode.\", \"taskName\": null}",
38
+ "{\"timestamp\": 1762805165.1199226, \"severity\": \"INFO\", \"name\": \"emailservice-server\", \"message\": \"Profiler disabled.\", \"taskName\": null}",
39
+ "{\"timestamp\": 1762805165.120006, \"severity\": \"INFO\", \"name\": \"emailservice-server\", \"message\": \"Tracing disabled.\", \"taskName\": null}",
40
+ "{\"timestamp\": 1762805165.1252596, \"severity\": \"INFO\", \"name\": \"emailservice-server\", \"message\": \"listening on port: 8080\", \"taskName\": null}"
41
+ ],
42
+ "frontend": [
43
+ "{\"message\":\"Tracing disabled.\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.80569469Z\"}",
44
+ "{\"message\":\"Profiling disabled.\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.8057464Z\"}",
45
+ "{\"message\":\"starting server on :8080\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:01.807084833Z\"}",
46
+ "{\"message\":\"Failed to fetch the name of the cluster in which the pod is runningmetadata: GCE metadata \\\"instance/attributes/cluster-name\\\" not defined\",\"severity\":\"error\",\"timestamp\":\"2025-11-10T20:06:01.819916696Z\"}",
47
+ "{\"message\":\"Failed to fetch the Zone of the node where the pod is scheduledmetadata: GCE metadata \\\"instance/zone\\\" not defined\",\"severity\":\"error\",\"timestamp\":\"2025-11-10T20:06:01.838567842Z\"}",
48
+ "{\"cluster\":\"\",\"hostname\":\"frontend-6778bd7b8b-cbk2x\",\"message\":\"Loaded deployment details\",\"severity\":\"debug\",\"timestamp\":\"2025-11-10T20:06:01.838614965Z\",\"zone\":\"\"}"
49
+ ],
50
+ "paymentservice": [
51
+ "{\"severity\":\"info\",\"time\":1762805162421,\"pid\":1,\"hostname\":\"paymentservice-78c5996648-h4j9p\",\"name\":\"paymentservice-server\",\"message\":\"Profiler disabled.\"}",
52
+ "{\"severity\":\"info\",\"time\":1762805162502,\"pid\":1,\"hostname\":\"paymentservice-78c5996648-h4j9p\",\"name\":\"paymentservice-server\",\"message\":\"Tracing disabled.\"}",
53
+ "(node:1) DeprecationWarning: Calling start() is no longer necessary. It can be safely omitted.",
54
+ "(Use `node --trace-deprecation ...` to show where the warning was created)",
55
+ "{\"severity\":\"info\",\"time\":1762805163316,\"pid\":1,\"hostname\":\"paymentservice-78c5996648-h4j9p\",\"name\":\"paymentservice-server\",\"message\":\"PaymentService gRPC server started on port 50051\"}"
56
+ ],
57
+ "productcatalogservice": [
58
+ "Error: Error from server (BadRequest): container \"server\" in pod \"productcatalogservice-6bdfff7c55-bntnp\" is waiting to start: ContainerCreating"
59
+ ],
60
+ "recommendationservice": [
61
+ "/usr/local/lib/python3.12/site-packages/opentelemetry/instrumentation/dependencies.py:4: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81.",
62
+ "from pkg_resources import (",
63
+ "{\"timestamp\": 1762805165.6152773, \"severity\": \"INFO\", \"name\": \"recommendationservice-server\", \"message\": \"initializing recommendationservice\", \"taskName\": null}",
64
+ "{\"timestamp\": 1762805165.6154165, \"severity\": \"INFO\", \"name\": \"recommendationservice-server\", \"message\": \"Profiler disabled.\", \"taskName\": null}",
65
+ "{\"timestamp\": 1762805165.6169107, \"severity\": \"INFO\", \"name\": \"recommendationservice-server\", \"message\": \"Tracing disabled.\", \"taskName\": null}",
66
+ "{\"timestamp\": 1762805165.6169996, \"severity\": \"INFO\", \"name\": \"recommendationservice-server\", \"message\": \"product catalog address: productcatalogservice:3550\", \"taskName\": null}",
67
+ "{\"timestamp\": 1762805165.6291184, \"severity\": \"INFO\", \"name\": \"recommendationservice-server\", \"message\": \"listening on port: 8080\", \"taskName\": null}"
68
+ ],
69
+ "redis-cart": [
70
+ "Starting Redis Server",
71
+ "1:C 10 Nov 2025 20:06:02.715 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo",
72
+ "1:C 10 Nov 2025 20:06:02.715 * Redis version=8.2.1, bits=64, commit=00000000, modified=1, pid=1, just started",
73
+ "1:C 10 Nov 2025 20:06:02.715 * Configuration loaded",
74
+ "1:M 10 Nov 2025 20:06:02.716 * monotonic clock: POSIX clock_gettime",
75
+ "1:M 10 Nov 2025 20:06:02.717 * Running mode=standalone, port=6379.",
76
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> RedisBloom version 8.2.0 (Git=unknown)",
77
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> Registering configuration options: [",
78
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ bf-error-rate : 0.01 }",
79
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ bf-initial-size : 100 }",
80
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ bf-expansion-factor : 2 }",
81
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ cf-bucket-size : 2 }",
82
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ cf-initial-size : 1024 }",
83
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ cf-max-iterations : 20 }",
84
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ cf-expansion-factor : 1 }",
85
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> \t{ cf-max-expansions : 32 }",
86
+ "1:M 10 Nov 2025 20:06:02.717 * <bf> ]",
87
+ "1:M 10 Nov 2025 20:06:02.717 * Module 'bf' loaded from /usr/local/lib/redis/modules//redisbloom.so",
88
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Redis version found by RedisSearch : 8.2.1 - oss",
89
+ "1:M 10 Nov 2025 20:06:02.720 * <search> RediSearch version 8.2.1 (Git=dba8dd0)",
90
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Low level api version 1 initialized successfully",
91
+ "1:M 10 Nov 2025 20:06:02.720 * <search> gc: ON, prefix min length: 2, min word length to stem: 4, prefix max expansions: 200, query timeout (ms): 500, timeout policy: return, cursor read size: 1000, cursor max idle (ms): 300000, max doctable size: 1000000, max number of search results: 1000000,",
92
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Initialized thread pools!",
93
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Disabled workers threadpool of size 0",
94
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Subscribe to config changes",
95
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Enabled role change notification",
96
+ "1:M 10 Nov 2025 20:06:02.720 * <search> Cluster configuration: AUTO partitions, type: 0, coordinator timeout: 0ms",
97
+ "1:M 10 Nov 2025 20:06:02.721 * <search> Register write commands",
98
+ "1:M 10 Nov 2025 20:06:02.721 * Module 'search' loaded from /usr/local/lib/redis/modules//redisearch.so",
99
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> RedisTimeSeries version 80200, git_sha=1439d4a439ca9c063e6ef124a510abff09a5d493",
100
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> Redis version found by RedisTimeSeries : 8.2.1 - oss",
101
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> Registering configuration options: [",
102
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-compaction-policy : }",
103
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-num-threads : 3 }",
104
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-retention-policy : 0 }",
105
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-duplicate-policy : block }",
106
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-chunk-size-bytes : 4096 }",
107
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-encoding : compressed }",
108
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-ignore-max-time-diff: 0 }",
109
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> \t{ ts-ignore-max-val-diff : 0.000000 }",
110
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> ]",
111
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> Detected redis oss",
112
+ "1:M 10 Nov 2025 20:06:02.721 * <timeseries> Enabled diskless replication",
113
+ "1:M 10 Nov 2025 20:06:02.721 * Module 'timeseries' loaded from /usr/local/lib/redis/modules//redistimeseries.so",
114
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Created new data type 'ReJSON-RL'",
115
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> version: 80200 git sha: unknown branch: unknown",
116
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Exported RedisJSON_V1 API",
117
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Exported RedisJSON_V2 API",
118
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Exported RedisJSON_V3 API",
119
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Exported RedisJSON_V4 API",
120
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Exported RedisJSON_V5 API",
121
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Enabled diskless replication",
122
+ "1:M 10 Nov 2025 20:06:02.722 * <ReJSON> Initialized shared string cache, thread safe: false.",
123
+ "1:M 10 Nov 2025 20:06:02.722 * Module 'ReJSON' loaded from /usr/local/lib/redis/modules//rejson.so",
124
+ "1:M 10 Nov 2025 20:06:02.722 * <search> Acquired RedisJSON_V5 API",
125
+ "1:M 10 Nov 2025 20:06:02.740 * Server initialized",
126
+ "1:M 10 Nov 2025 20:06:02.740 * <search> Loading event starts",
127
+ "1:M 10 Nov 2025 20:06:02.740 * <search> Enabled workers threadpool of size 4",
128
+ "1:M 10 Nov 2025 20:06:02.740 * Loading RDB produced by version 8.2.1",
129
+ "1:M 10 Nov 2025 20:06:02.740 * RDB age 320 seconds",
130
+ "1:M 10 Nov 2025 20:06:02.740 * RDB memory usage when created 1.24 Mb",
131
+ "1:M 10 Nov 2025 20:06:02.742 * Done loading RDB, keys loaded: 1381, keys expired: 0.",
132
+ "1:M 10 Nov 2025 20:06:02.742 * <search> Disabled workers threadpool of size 4",
133
+ "1:M 10 Nov 2025 20:06:02.742 * <search> Loading event ends",
134
+ "1:M 10 Nov 2025 20:06:02.742 * DB loaded from disk: 0.002 seconds",
135
+ "1:M 10 Nov 2025 20:06:02.742 * Ready to accept connections tcp"
136
+ ],
137
+ "shippingservice": [
138
+ "{\"message\":\"Tracing enabled, but temporarily unavailable\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:02.82991023Z\"}",
139
+ "{\"message\":\"See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:02.829973206Z\"}",
140
+ "{\"message\":\"Profiling disabled.\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:02.829991048Z\"}",
141
+ "{\"message\":\"Stats enabled, but temporarily unavailable\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:02.830141377Z\"}",
142
+ "{\"message\":\"Shipping Service listening on port :50051\",\"severity\":\"info\",\"timestamp\":\"2025-11-10T20:06:02.830173507Z\"}"
143
+ ]
144
+ }
benchmark/boutique/runtime/28/tool_cache.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmark/boutique/runtime/29/code/adservice/src/main/java/hipstershop/AdService.java ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018, Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package hipstershop;
18
+
19
+ import com.google.common.collect.ImmutableListMultimap;
20
+ import com.google.common.collect.ImmutableMap;
21
+ import com.google.common.collect.Iterables;
22
+ import hipstershop.Demo.Ad;
23
+ import hipstershop.Demo.AdRequest;
24
+ import hipstershop.Demo.AdResponse;
25
+ import io.grpc.Server;
26
+ import io.grpc.ServerBuilder;
27
+ import io.grpc.StatusRuntimeException;
28
+ import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
29
+ import io.grpc.services.*;
30
+ import io.grpc.stub.StreamObserver;
31
+ import java.io.IOException;
32
+ import java.util.ArrayList;
33
+ import java.util.Collection;
34
+ import java.util.List;
35
+ import java.util.Random;
36
+ import java.util.concurrent.TimeUnit;
37
+ import org.apache.logging.log4j.Level;
38
+ import org.apache.logging.log4j.LogManager;
39
+ import org.apache.logging.log4j.Logger;
40
+
41
+ public final class AdService {
42
+
43
+ private static final Logger logger = LogManager.getLogger(AdService.class);
44
+
45
+ @SuppressWarnings("FieldCanBeLocal")
46
+ private static int MAX_ADS_TO_SERVE = 2;
47
+
48
+ private Server server;
49
+ private HealthStatusManager healthMgr;
50
+
51
+ private static final AdService service = new AdService();
52
+
53
+ private void start() throws IOException {
54
+ int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "9555"));
55
+ healthMgr = new HealthStatusManager();
56
+
57
+ server =
58
+ ServerBuilder.forPort(port)
59
+ .addService(new AdServiceImpl())
60
+ .addService(healthMgr.getHealthService())
61
+ .build()
62
+ .start();
63
+ logger.info("Ad Service started, listening on " + port);
64
+ Runtime.getRuntime()
65
+ .addShutdownHook(
66
+ new Thread(
67
+ () -> {
68
+ // Use stderr here since the logger may have been reset by its JVM shutdown hook.
69
+ System.err.println(
70
+ "*** shutting down gRPC ads server since JVM is shutting down");
71
+ AdService.this.stop();
72
+ System.err.println("*** server shut down");
73
+ }));
74
+ healthMgr.setStatus("", ServingStatus.SERVING);
75
+ }
76
+
77
+ private void stop() {
78
+ if (server != null) {
79
+ healthMgr.clearStatus("");
80
+ server.shutdown();
81
+ }
82
+ }
83
+
84
+ private static class AdServiceImpl extends hipstershop.AdServiceGrpc.AdServiceImplBase {
85
+
86
+ /**
87
+ * Retrieves ads based on context provided in the request {@code AdRequest}.
88
+ *
89
+ * @param req the request containing context.
90
+ * @param responseObserver the stream observer which gets notified with the value of {@code
91
+ * AdResponse}
92
+ */
93
+ @Override
94
+ public void getAds(AdRequest req, StreamObserver<AdResponse> responseObserver) {
95
+ AdService service = AdService.getInstance();
96
+ try {
97
+ List<Ad> allAds = new ArrayList<>();
98
+ logger.info("received ad request (context_words=" + req.getContextKeysList() + ")");
99
+ if (req.getContextKeysCount() > 0) {
100
+ for (int i = 0; i < req.getContextKeysCount(); i++) {
101
+ Collection<Ad> ads = service.getAdsByCategory(req.getContextKeys(i));
102
+ allAds.addAll(ads);
103
+ }
104
+ } else {
105
+ allAds = service.getRandomAds();
106
+ }
107
+ if (allAds.isEmpty()) {
108
+ // Serve random ads.
109
+ allAds = service.getRandomAds();
110
+ }
111
+ AdResponse reply = AdResponse.newBuilder().addAllAds(allAds).build();
112
+ responseObserver.onNext(reply);
113
+ responseObserver.onCompleted();
114
+ } catch (StatusRuntimeException e) {
115
+ logger.log(Level.WARN, "GetAds Failed with status {}", e.getStatus());
116
+ responseObserver.onError(e);
117
+ }
118
+ }
119
+ }
120
+
121
+ private static final ImmutableListMultimap<String, Ad> adsMap = createAdsMap();
122
+
123
+ private Collection<Ad> getAdsByCategory(String category) {
124
+ return adsMap.get(category);
125
+ }
126
+
127
+ private static final Random random = new Random();
128
+
129
+ private List<Ad> getRandomAds() {
130
+ List<Ad> ads = new ArrayList<>(MAX_ADS_TO_SERVE);
131
+ Collection<Ad> allAds = adsMap.values();
132
+ for (int i = 0; i < MAX_ADS_TO_SERVE; i++) {
133
+ ads.add(Iterables.get(allAds, random.nextInt(allAds.size())));
134
+ }
135
+ return ads;
136
+ }
137
+
138
+ private static AdService getInstance() {
139
+ return service;
140
+ }
141
+
142
+ /** Await termination on the main thread since the grpc library uses daemon threads. */
143
+ private void blockUntilShutdown() throws InterruptedException {
144
+ if (server != null) {
145
+ server.awaitTermination();
146
+ }
147
+ }
148
+
149
+ private static ImmutableListMultimap<String, Ad> createAdsMap() {
150
+ Ad hairdryer =
151
+ Ad.newBuilder()
152
+ .setRedirectUrl("/product/2ZYFJ3GM2N")
153
+ .setText("Hairdryer for sale. 50% off.")
154
+ .build();
155
+ Ad tankTop =
156
+ Ad.newBuilder()
157
+ .setRedirectUrl("/product/66VCHSJNUP")
158
+ .setText("Tank top for sale. 20% off.")
159
+ .build();
160
+ Ad candleHolder =
161
+ Ad.newBuilder()
162
+ .setRedirectUrl("/product/0PUK6V6EV0")
163
+ .setText("Candle holder for sale. 30% off.")
164
+ .build();
165
+ Ad bambooGlassJar =
166
+ Ad.newBuilder()
167
+ .setRedirectUrl("/product/9SIQT8TOJO")
168
+ .setText("Bamboo glass jar for sale. 10% off.")
169
+ .build();
170
+ Ad watch =
171
+ Ad.newBuilder()
172
+ .setRedirectUrl("/product/1YMWWN1N4O")
173
+ .setText("Watch for sale. Buy one, get second kit for free")
174
+ .build();
175
+ Ad mug =
176
+ Ad.newBuilder()
177
+ .setRedirectUrl("/product/6E92ZMYYFZ")
178
+ .setText("Mug for sale. Buy two, get third one for free")
179
+ .build();
180
+ Ad loafers =
181
+ Ad.newBuilder()
182
+ .setRedirectUrl("/product/L9ECAV7KIM")
183
+ .setText("Loafers for sale. Buy one, get second one for free")
184
+ .build();
185
+ return ImmutableListMultimap.<String, Ad>builder()
186
+ .putAll("clothing", tankTop)
187
+ .putAll("accessories", watch)
188
+ .putAll("footwear", loafers)
189
+ .putAll("hair", hairdryer)
190
+ .putAll("decor", candleHolder)
191
+ .putAll("kitchen", bambooGlassJar, mug)
192
+ .build();
193
+ }
194
+
195
+ private static void initStats() {
196
+ if (System.getenv("DISABLE_STATS") != null) {
197
+ logger.info("Stats disabled.");
198
+ return;
199
+ }
200
+ logger.info("Stats enabled, but temporarily unavailable");
201
+
202
+ long sleepTime = 10; /* seconds */
203
+ int maxAttempts = 5;
204
+
205
+ // TODO(arbrown) Implement OpenTelemetry stats
206
+
207
+ }
208
+
209
+ private static void initTracing() {
210
+ if (System.getenv("DISABLE_TRACING") != null) {
211
+ logger.info("Tracing disabled.");
212
+ return;
213
+ }
214
+ logger.info("Tracing enabled but temporarily unavailable");
215
+ logger.info("See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.");
216
+
217
+ // TODO(arbrown) Implement OpenTelemetry tracing
218
+
219
+ logger.info("Tracing enabled - Stackdriver exporter initialized.");
220
+ }
221
+
222
+ /** Main launches the server from the command line. */
223
+ public static void main(String[] args) throws IOException, InterruptedException {
224
+
225
+ new Thread(
226
+ () -> {
227
+ initStats();
228
+ initTracing();
229
+ })
230
+ .start();
231
+
232
+ // Start the RPC server. You shouldn't see any output from gRPC before this.
233
+ logger.info("AdService starting.");
234
+ final AdService service = AdService.getInstance();
235
+ service.start();
236
+ service.blockUntilShutdown();
237
+ }
238
+ }
benchmark/boutique/runtime/29/code/adservice/src/main/java/hipstershop/AdServiceClient.java ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018, Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ package hipstershop;
18
+
19
+ import hipstershop.Demo.Ad;
20
+ import hipstershop.Demo.AdRequest;
21
+ import hipstershop.Demo.AdResponse;
22
+ import io.grpc.ManagedChannel;
23
+ import io.grpc.ManagedChannelBuilder;
24
+ import io.grpc.StatusRuntimeException;
25
+ import java.util.concurrent.TimeUnit;
26
+ import javax.annotation.Nullable;
27
+ import org.apache.logging.log4j.Level;
28
+ import org.apache.logging.log4j.LogManager;
29
+ import org.apache.logging.log4j.Logger;
30
+
31
+ /** A simple client that requests ads from the Ads Service. */
32
+ public class AdServiceClient {
33
+
34
+ private static final Logger logger = LogManager.getLogger(AdServiceClient.class);
35
+
36
+ private final ManagedChannel channel;
37
+ private final hipstershop.AdServiceGrpc.AdServiceBlockingStub blockingStub;
38
+
39
+ /** Construct client connecting to Ad Service at {@code host:port}. */
40
+ private AdServiceClient(String host, int port) {
41
+ this(
42
+ ManagedChannelBuilder.forAddress(host, port)
43
+ // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
44
+ // needing certificates.
45
+ .usePlaintext()
46
+ .build());
47
+ }
48
+
49
+ /** Construct client for accessing RouteGuide server using the existing channel. */
50
+ private AdServiceClient(ManagedChannel channel) {
51
+ this.channel = channel;
52
+ blockingStub = hipstershop.AdServiceGrpc.newBlockingStub(channel);
53
+ }
54
+
55
+ private void shutdown() throws InterruptedException {
56
+ channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
57
+ }
58
+
59
+ /** Get Ads from Server. */
60
+ public void getAds(String contextKey) {
61
+ logger.info("Get Ads with context " + contextKey + " ...");
62
+ AdRequest request = AdRequest.newBuilder().addContextKeys(contextKey).build();
63
+ AdResponse response;
64
+
65
+ try {
66
+ response = blockingStub.getAds(request);
67
+ } catch (StatusRuntimeException e) {
68
+ logger.log(Level.WARN, "RPC failed: " + e.getStatus());
69
+ return;
70
+ }
71
+ for (Ad ads : response.getAdsList()) {
72
+ logger.info("Ads: " + ads.getText());
73
+ }
74
+ }
75
+
76
+ private static int getPortOrDefaultFromArgs(String[] args) {
77
+ int portNumber = 9555;
78
+ if (2 < args.length) {
79
+ try {
80
+ portNumber = Integer.parseInt(args[2]);
81
+ } catch (NumberFormatException e) {
82
+ logger.warn(String.format("Port %s is invalid, use default port %d.", args[2], 9555));
83
+ }
84
+ }
85
+ return portNumber;
86
+ }
87
+
88
+ private static String getStringOrDefaultFromArgs(
89
+ String[] args, int index, @Nullable String defaultString) {
90
+ String s = defaultString;
91
+ if (index < args.length) {
92
+ s = args[index];
93
+ }
94
+ return s;
95
+ }
96
+
97
+ /**
98
+ * Ads Service Client main. If provided, the first element of {@code args} is the context key to
99
+ * get the ads from the Ads Service
100
+ */
101
+ public static void main(String[] args) throws InterruptedException {
102
+ // Add final keyword to pass checkStyle.
103
+ final String contextKeys = getStringOrDefaultFromArgs(args, 0, "camera");
104
+ final String host = getStringOrDefaultFromArgs(args, 1, "localhost");
105
+ final int serverPort = getPortOrDefaultFromArgs(args);
106
+
107
+ AdServiceClient client = new AdServiceClient(host, serverPort);
108
+ try {
109
+ client.getAds(contextKeys);
110
+ } finally {
111
+ client.shutdown();
112
+ }
113
+
114
+ logger.info("Exiting AdServiceClient...");
115
+ }
116
+ }
benchmark/boutique/runtime/29/code/cartservice/src/Program.cs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using Microsoft.AspNetCore.Hosting;
16
+ using Microsoft.Extensions.Hosting;
17
+ using cartservice;
18
+
19
+ CreateHostBuilder(args).Build().Run();
20
+
21
+ static IHostBuilder CreateHostBuilder(string[] args) =>
22
+ Host.CreateDefaultBuilder(args)
23
+ .ConfigureWebHostDefaults(webBuilder =>
24
+ {
25
+ webBuilder.UseStartup<Startup>();
26
+ });
benchmark/boutique/runtime/29/code/cartservice/src/Startup.cs ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System;
2
+ using Microsoft.AspNetCore.Builder;
3
+ using Microsoft.AspNetCore.Diagnostics.HealthChecks;
4
+ using Microsoft.AspNetCore.Hosting;
5
+ using Microsoft.AspNetCore.Http;
6
+ using Microsoft.Extensions.Configuration;
7
+ using Microsoft.Extensions.DependencyInjection;
8
+ using Microsoft.Extensions.Diagnostics.HealthChecks;
9
+ using Microsoft.Extensions.Hosting;
10
+ using cartservice.cartstore;
11
+ using cartservice.services;
12
+ using Microsoft.Extensions.Caching.StackExchangeRedis;
13
+
14
+ namespace cartservice
15
+ {
16
+ public class Startup
17
+ {
18
+ public Startup(IConfiguration configuration)
19
+ {
20
+ Configuration = configuration;
21
+ }
22
+
23
+ public IConfiguration Configuration { get; }
24
+
25
+ // This method gets called by the runtime. Use this method to add services to the container.
26
+ // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
27
+ public void ConfigureServices(IServiceCollection services)
28
+ {
29
+ string redisAddress = Configuration["REDIS_ADDR"];
30
+ string spannerProjectId = Configuration["SPANNER_PROJECT"];
31
+ string spannerConnectionString = Configuration["SPANNER_CONNECTION_STRING"];
32
+ string alloyDBConnectionString = Configuration["ALLOYDB_PRIMARY_IP"];
33
+
34
+ if (!string.IsNullOrEmpty(redisAddress))
35
+ {
36
+ services.AddStackExchangeRedisCache(options =>
37
+ {
38
+ options.Configuration = redisAddress;
39
+ });
40
+ services.AddSingleton<ICartStore, RedisCartStore>();
41
+ }
42
+ else if (!string.IsNullOrEmpty(spannerProjectId) || !string.IsNullOrEmpty(spannerConnectionString))
43
+ {
44
+ services.AddSingleton<ICartStore, SpannerCartStore>();
45
+ }
46
+ else if (!string.IsNullOrEmpty(alloyDBConnectionString))
47
+ {
48
+ Console.WriteLine("Creating AlloyDB cart store");
49
+ services.AddSingleton<ICartStore, AlloyDBCartStore>();
50
+ }
51
+ else
52
+ {
53
+ Console.WriteLine("Redis cache host(hostname+port) was not specified. Starting a cart service using in memory store");
54
+ services.AddDistributedMemoryCache();
55
+ services.AddSingleton<ICartStore, RedisCartStore>();
56
+ }
57
+
58
+
59
+ services.AddGrpc();
60
+ }
61
+
62
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
63
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
64
+ {
65
+ if (env.IsDevelopment())
66
+ {
67
+ app.UseDeveloperExceptionPage();
68
+ }
69
+
70
+ app.UseRouting();
71
+
72
+ app.UseEndpoints(endpoints =>
73
+ {
74
+ endpoints.MapGrpcService<CartService>();
75
+ endpoints.MapGrpcService<cartservice.services.HealthCheckService>();
76
+
77
+ endpoints.MapGet("/", async context =>
78
+ {
79
+ await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
80
+ });
81
+ });
82
+ }
83
+ }
84
+ }
benchmark/boutique/runtime/29/code/cartservice/src/cartstore/AlloyDBCartStore.cs ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using Grpc.Core;
17
+ using Npgsql;
18
+ using Microsoft.Extensions.Configuration;
19
+ using System.Threading.Tasks;
20
+ using Google.Api.Gax.ResourceNames;
21
+ using Google.Cloud.SecretManager.V1;
22
+
23
+ namespace cartservice.cartstore
24
+ {
25
+ public class AlloyDBCartStore : ICartStore
26
+ {
27
+ private readonly string tableName;
28
+ private readonly string connectionString;
29
+
30
+ public AlloyDBCartStore(IConfiguration configuration)
31
+ {
32
+ // Create a Cloud Secrets client.
33
+ SecretManagerServiceClient client = SecretManagerServiceClient.Create();
34
+ var projectId = configuration["PROJECT_ID"];
35
+ var secretId = configuration["ALLOYDB_SECRET_NAME"];
36
+ SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, "latest");
37
+
38
+ AccessSecretVersionResponse result = client.AccessSecretVersion(secretVersionName);
39
+ // Convert the payload to a string. Payloads are bytes by default.
40
+ string alloyDBPassword = result.Payload.Data.ToStringUtf8().TrimEnd('\r', '\n');
41
+
42
+ // TODO: Create a separate user for connecting within the application
43
+ // rather than using our superuser
44
+ string alloyDBUser = "postgres";
45
+ string databaseName = configuration["ALLOYDB_DATABASE_NAME"];
46
+ // TODO: Consider splitting workloads into read vs. write and take
47
+ // advantage of the AlloyDB read pools
48
+ string primaryIPAddress = configuration["ALLOYDB_PRIMARY_IP"];
49
+ connectionString = "Host=" +
50
+ primaryIPAddress +
51
+ ";Username=" +
52
+ alloyDBUser +
53
+ ";Password=" +
54
+ alloyDBPassword +
55
+ ";Database=" +
56
+ databaseName;
57
+
58
+ tableName = configuration["ALLOYDB_TABLE_NAME"];
59
+ }
60
+
61
+
62
+ public async Task AddItemAsync(string userId, string productId, int quantity)
63
+ {
64
+ Console.WriteLine($"AddItemAsync for {userId} called");
65
+ try
66
+ {
67
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
68
+
69
+ var fetchCmd = $"SELECT quantity FROM {tableName} WHERE userID='{userId}' AND productID='{productId}'";
70
+ var currentQuantity = 0;
71
+ var cmdRead = dataSource.CreateCommand(fetchCmd);
72
+ await using (var reader = await cmdRead.ExecuteReaderAsync())
73
+ {
74
+ while (await reader.ReadAsync())
75
+ currentQuantity += reader.GetInt32(0);
76
+ }
77
+
78
+ var totalQuantity = quantity + currentQuantity;
79
+
80
+ // Use INSERT ... ON CONFLICT to prevent duplicate key error
81
+ var insertCmd = $@"
82
+ INSERT INTO {tableName} (userId, productId, quantity)
83
+ VALUES ('{userId}', '{productId}', {totalQuantity})
84
+ ON CONFLICT (userId, productId)
85
+ DO UPDATE SET quantity = {totalQuantity};
86
+ ";
87
+
88
+ await using (var cmdInsert = dataSource.CreateCommand(insertCmd))
89
+ {
90
+ await Task.Run(() =>
91
+ {
92
+ return cmdInsert.ExecuteNonQueryAsync();
93
+ });
94
+ }
95
+ }
96
+ catch (Exception ex)
97
+ {
98
+ throw new RpcException(
99
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
100
+ }
101
+ }
102
+
103
+
104
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
105
+ {
106
+ Console.WriteLine($"GetCartAsync called for userId={userId}");
107
+ Hipstershop.Cart cart = new();
108
+ cart.UserId = userId;
109
+ try
110
+ {
111
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
112
+
113
+ var cartFetchCmd = $"SELECT productId, quantity FROM {tableName} WHERE userId = '{userId}'";
114
+ var cmd = dataSource.CreateCommand(cartFetchCmd);
115
+ await using (var reader = await cmd.ExecuteReaderAsync())
116
+ {
117
+ while (await reader.ReadAsync())
118
+ {
119
+ Hipstershop.CartItem item = new()
120
+ {
121
+ ProductId = reader.GetString(0),
122
+ Quantity = reader.GetInt32(1)
123
+ };
124
+ cart.Items.Add(item);
125
+ }
126
+ }
127
+ await Task.Run(() =>
128
+ {
129
+ return cart;
130
+ });
131
+ }
132
+ catch (Exception ex)
133
+ {
134
+ throw new RpcException(
135
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
136
+ }
137
+ return cart;
138
+ }
139
+
140
+
141
+ public async Task EmptyCartAsync(string userId)
142
+ {
143
+ Console.WriteLine($"EmptyCartAsync called for userId={userId}");
144
+
145
+ try
146
+ {
147
+ await using var dataSource = NpgsqlDataSource.Create(connectionString);
148
+ var deleteCmd = $"DELETE FROM {tableName} WHERE userID = '{userId}'";
149
+ await using (var cmd = dataSource.CreateCommand(deleteCmd))
150
+ {
151
+ await Task.Run(() =>
152
+ {
153
+ return cmd.ExecuteNonQueryAsync();
154
+ });
155
+ }
156
+ }
157
+ catch (Exception ex)
158
+ {
159
+ throw new RpcException(
160
+ new Status(StatusCode.FailedPrecondition, $"Unable to access cart storage due to an internal error. {ex}"));
161
+ }
162
+ }
163
+
164
+ public bool Ping()
165
+ {
166
+ try
167
+ {
168
+ return true;
169
+ }
170
+ catch (Exception)
171
+ {
172
+ return false;
173
+ }
174
+ }
175
+ }
176
+ }
177
+
benchmark/boutique/runtime/29/code/cartservice/src/cartstore/ICartStore.cs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System.Threading.Tasks;
16
+
17
+ namespace cartservice.cartstore
18
+ {
19
+ public interface ICartStore
20
+ {
21
+ Task AddItemAsync(string userId, string productId, int quantity);
22
+ Task EmptyCartAsync(string userId);
23
+ Task<Hipstershop.Cart> GetCartAsync(string userId);
24
+ bool Ping();
25
+ }
26
+ }
benchmark/boutique/runtime/29/code/cartservice/src/cartstore/RedisCartStore.cs ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using System.Linq;
17
+ using System.Threading.Tasks;
18
+ using Grpc.Core;
19
+ using Microsoft.Extensions.Caching.Distributed;
20
+ using Google.Protobuf;
21
+
22
+ namespace cartservice.cartstore
23
+ {
24
+ public class RedisCartStore : ICartStore
25
+ {
26
+ private readonly IDistributedCache _cache;
27
+
28
+ public RedisCartStore(IDistributedCache cache)
29
+ {
30
+ _cache = cache;
31
+ }
32
+
33
+ public async Task AddItemAsync(string userId, string productId, int quantity)
34
+ {
35
+ Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");
36
+
37
+ try
38
+ {
39
+ Hipstershop.Cart cart;
40
+ var value = await _cache.GetAsync(userId);
41
+ if (value == null)
42
+ {
43
+ cart = new Hipstershop.Cart();
44
+ cart.UserId = userId;
45
+ cart.Items.Add(new Hipstershop.CartItem { ProductId = productId, Quantity = quantity });
46
+ }
47
+ else
48
+ {
49
+ cart = Hipstershop.Cart.Parser.ParseFrom(value);
50
+ var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
51
+ if (existingItem == null)
52
+ {
53
+ cart.Items.Add(new Hipstershop.CartItem { ProductId = productId, Quantity = quantity });
54
+ }
55
+ else
56
+ {
57
+ existingItem.Quantity += quantity;
58
+ }
59
+ }
60
+ await _cache.SetAsync(userId, cart.ToByteArray());
61
+ }
62
+ catch (Exception ex)
63
+ {
64
+ throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
65
+ }
66
+ }
67
+
68
+ public async Task EmptyCartAsync(string userId)
69
+ {
70
+ Console.WriteLine($"EmptyCartAsync called with userId={userId}");
71
+
72
+ try
73
+ {
74
+ var cart = new Hipstershop.Cart();
75
+ await _cache.SetAsync(userId, cart.ToByteArray());
76
+ }
77
+ catch (Exception ex)
78
+ {
79
+ throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
80
+ }
81
+ }
82
+
83
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
84
+ {
85
+ Console.WriteLine($"GetCartAsync called with userId={userId}");
86
+
87
+ try
88
+ {
89
+ // Access the cart from the cache
90
+ var value = await _cache.GetAsync(userId);
91
+
92
+ if (value != null)
93
+ {
94
+ return Hipstershop.Cart.Parser.ParseFrom(value);
95
+ }
96
+
97
+ // We decided to return empty cart in cases when user wasn't in the cache before
98
+ return new Hipstershop.Cart();
99
+ }
100
+ catch (Exception ex)
101
+ {
102
+ throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
103
+ }
104
+ }
105
+
106
+ public bool Ping()
107
+ {
108
+ try
109
+ {
110
+ return true;
111
+ }
112
+ catch (Exception)
113
+ {
114
+ return false;
115
+ }
116
+ }
117
+ }
118
+ }
benchmark/boutique/runtime/29/code/cartservice/src/cartstore/SpannerCartStore.cs ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using Google.Cloud.Spanner.Data;
17
+ using Grpc.Core;
18
+ using Microsoft.Extensions.Configuration;
19
+ using System.Threading.Tasks;
20
+
21
+ namespace cartservice.cartstore
22
+ {
23
+ public class SpannerCartStore : ICartStore
24
+ {
25
+ private static readonly string TableName = "CartItems";
26
+ private static readonly string DefaultInstanceName = "onlineboutique";
27
+ private static readonly string DefaultDatabaseName = "carts";
28
+ private readonly string databaseString;
29
+
30
+ public SpannerCartStore(IConfiguration configuration)
31
+ {
32
+ string spannerProjectId = configuration["SPANNER_PROJECT"];
33
+ string spannerInstanceId = configuration["SPANNER_INSTANCE"];
34
+ string spannerDatabaseId = configuration["SPANNER_DATABASE"];
35
+ string spannerConnectionString = configuration["SPANNER_CONNECTION_STRING"];
36
+ SpannerConnectionStringBuilder builder = new();
37
+ if (!string.IsNullOrEmpty(spannerConnectionString)) {
38
+ builder.DataSource = spannerConnectionString;
39
+ databaseString = builder.ToString();
40
+ Console.WriteLine($"Spanner connection string: ${databaseString}");
41
+ return;
42
+ }
43
+ if (string.IsNullOrEmpty(spannerInstanceId))
44
+ spannerInstanceId = DefaultInstanceName;
45
+ if (string.IsNullOrEmpty(spannerDatabaseId))
46
+ spannerDatabaseId = DefaultDatabaseName;
47
+ builder.DataSource =
48
+ $"projects/{spannerProjectId}/instances/{spannerInstanceId}/databases/{spannerDatabaseId}";
49
+ databaseString = builder.ToString();
50
+ Console.WriteLine($"Built Spanner connection string: '{databaseString}'");
51
+ }
52
+
53
+
54
+ public async Task AddItemAsync(string userId, string productId, int quantity)
55
+ {
56
+ Console.WriteLine($"AddItemAsync for {userId} called");
57
+ try
58
+ {
59
+ using SpannerConnection spannerConnection = new(databaseString);
60
+ await spannerConnection.RunWithRetriableTransactionAsync(async transaction =>
61
+ {
62
+ int currentQuantity = 0;
63
+ var quantityLookup = spannerConnection.CreateSelectCommand(
64
+ $"SELECT * FROM {TableName} WHERE userId = @userId AND productId = @productId",
65
+ new SpannerParameterCollection
66
+ {
67
+ { "userId", SpannerDbType.String },
68
+ { "productId", SpannerDbType.String }
69
+ });
70
+ quantityLookup.Parameters["userId"].Value = userId;
71
+ quantityLookup.Parameters["productId"].Value = productId;
72
+ quantityLookup.Transaction = transaction;
73
+ using (var reader = await quantityLookup.ExecuteReaderAsync())
74
+ {
75
+ while (await reader.ReadAsync()) {
76
+ currentQuantity += reader.GetFieldValue<int>("quantity");
77
+ }
78
+ }
79
+
80
+ var cmd = spannerConnection.CreateInsertOrUpdateCommand(TableName,
81
+ new SpannerParameterCollection
82
+ {
83
+ { "userId", SpannerDbType.String },
84
+ { "productId", SpannerDbType.String },
85
+ { "quantity", SpannerDbType.Int64 }
86
+ });
87
+ cmd.Parameters["userId"].Value = userId;
88
+ cmd.Parameters["productId"].Value = productId;
89
+ cmd.Parameters["quantity"].Value = currentQuantity + quantity;
90
+ cmd.Transaction = transaction;
91
+ await Task.Run(() =>
92
+ {
93
+ return cmd.ExecuteNonQueryAsync();
94
+ });
95
+ });
96
+ }
97
+ catch (Exception ex)
98
+ {
99
+ throw new RpcException(
100
+ new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {databaseString}. {ex}"));
101
+ }
102
+ }
103
+
104
+
105
+ public async Task<Hipstershop.Cart> GetCartAsync(string userId)
106
+ {
107
+ Console.WriteLine($"GetCartAsync called for userId={userId}");
108
+ Hipstershop.Cart cart = new();
109
+ try
110
+ {
111
+ using SpannerConnection spannerConnection = new(databaseString);
112
+ var cmd = spannerConnection.CreateSelectCommand(
113
+ $"SELECT * FROM {TableName} WHERE userId = @userId",
114
+ new SpannerParameterCollection {
115
+ { "userId", SpannerDbType.String }
116
+ }
117
+ );
118
+ cmd.Parameters["userId"].Value = userId;
119
+ using var reader = await cmd.ExecuteReaderAsync();
120
+ while (await reader.ReadAsync())
121
+ {
122
+ // Only add the userId if something is in the cart.
123
+ // This is based on how the cartservice example behaves.
124
+ // An empty cart has no userId attached.
125
+ cart.UserId = userId;
126
+
127
+ Hipstershop.CartItem item = new()
128
+ {
129
+ ProductId = reader.GetFieldValue<string>("productId"),
130
+ Quantity = reader.GetFieldValue<int>("quantity")
131
+ };
132
+ cart.Items.Add(item);
133
+ }
134
+
135
+ return cart;
136
+ }
137
+ catch (Exception ex)
138
+ {
139
+ throw new RpcException(
140
+ new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {databaseString}. {ex}"));
141
+ }
142
+ }
143
+
144
+
145
+ public async Task EmptyCartAsync(string userId)
146
+ {
147
+ Console.WriteLine($"EmptyCartAsync called for userId={userId}");
148
+
149
+ try
150
+ {
151
+ using SpannerConnection spannerConnection = new(databaseString);
152
+ await Task.Run(() =>
153
+ {
154
+ var cmd = spannerConnection.CreateDmlCommand(
155
+ $"DELETE FROM {TableName} WHERE userId = @userId",
156
+ new SpannerParameterCollection
157
+ {
158
+ { "userId", SpannerDbType.String }
159
+ });
160
+ cmd.Parameters["userId"].Value = userId;
161
+ return cmd.ExecuteNonQueryAsync();
162
+ });
163
+ }
164
+
165
+ catch (Exception ex)
166
+ {
167
+ throw new RpcException(
168
+ new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {databaseString}. {ex}"));
169
+ }
170
+ }
171
+
172
+ public bool Ping()
173
+ {
174
+ try
175
+ {
176
+ return true;
177
+ }
178
+ catch (Exception)
179
+ {
180
+ return false;
181
+ }
182
+ }
183
+ }
184
+ }
185
+
benchmark/boutique/runtime/29/code/cartservice/src/services/CartService.cs ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using System.Threading.Tasks;
17
+ using Grpc.Core;
18
+ using Microsoft.Extensions.Logging;
19
+ using cartservice.cartstore;
20
+ using Hipstershop;
21
+
22
+ namespace cartservice.services
23
+ {
24
+ public class CartService : Hipstershop.CartService.CartServiceBase
25
+ {
26
+ private readonly static Empty Empty = new Empty();
27
+ private readonly ICartStore _cartStore;
28
+
29
+ public CartService(ICartStore cartStore)
30
+ {
31
+ _cartStore = cartStore;
32
+ }
33
+
34
+ public async override Task<Empty> AddItem(AddItemRequest request, ServerCallContext context)
35
+ {
36
+ await _cartStore.AddItemAsync(request.UserId, request.Item.ProductId, request.Item.Quantity);
37
+ return Empty;
38
+ }
39
+
40
+ public override Task<Cart> GetCart(GetCartRequest request, ServerCallContext context)
41
+ {
42
+ return _cartStore.GetCartAsync(request.UserId);
43
+ }
44
+
45
+ public async override Task<Empty> EmptyCart(EmptyCartRequest request, ServerCallContext context)
46
+ {
47
+ await _cartStore.EmptyCartAsync(request.UserId);
48
+ return Empty;
49
+ }
50
+ }
51
+ }
benchmark/boutique/runtime/29/code/cartservice/src/services/HealthCheckService.cs ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ using System;
16
+ using System.Threading.Tasks;
17
+ using Grpc.Core;
18
+ using Grpc.Health.V1;
19
+ using static Grpc.Health.V1.Health;
20
+ using cartservice.cartstore;
21
+
22
+ namespace cartservice.services
23
+ {
24
+ internal class HealthCheckService : HealthBase
25
+ {
26
+ private ICartStore _cartStore { get; }
27
+
28
+ public HealthCheckService (ICartStore cartStore)
29
+ {
30
+ _cartStore = cartStore;
31
+ }
32
+
33
+ public override Task<HealthCheckResponse> Check(HealthCheckRequest request, ServerCallContext context)
34
+ {
35
+ Console.WriteLine ("Checking CartService Health");
36
+ return Task.FromResult(new HealthCheckResponse {
37
+ Status = _cartStore.Ping() ? HealthCheckResponse.Types.ServingStatus.Serving : HealthCheckResponse.Types.ServingStatus.NotServing
38
+ });
39
+ }
40
+ }
41
+ }
benchmark/boutique/runtime/29/code/checkoutservice/main.go ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "fmt"
20
+ "net"
21
+ "os"
22
+ "time"
23
+
24
+ "cloud.google.com/go/profiler"
25
+ "github.com/google/uuid"
26
+ "github.com/pkg/errors"
27
+ "github.com/sirupsen/logrus"
28
+ "google.golang.org/grpc"
29
+ "google.golang.org/grpc/codes"
30
+ "google.golang.org/grpc/credentials/insecure"
31
+ "google.golang.org/grpc/health"
32
+ "google.golang.org/grpc/status"
33
+
34
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/checkoutservice/genproto"
35
+ money "github.com/GoogleCloudPlatform/microservices-demo/src/checkoutservice/money"
36
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
37
+
38
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
39
+ "go.opentelemetry.io/otel"
40
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
41
+ "go.opentelemetry.io/otel/propagation"
42
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
43
+ )
44
+
45
+ const (
46
+ listenPort = "5050"
47
+ usdCurrency = "USD"
48
+ )
49
+
50
+ var log *logrus.Logger
51
+
52
+ func init() {
53
+ log = logrus.New()
54
+ log.Level = logrus.DebugLevel
55
+ log.Formatter = &logrus.JSONFormatter{
56
+ FieldMap: logrus.FieldMap{
57
+ logrus.FieldKeyTime: "timestamp",
58
+ logrus.FieldKeyLevel: "severity",
59
+ logrus.FieldKeyMsg: "message",
60
+ },
61
+ TimestampFormat: time.RFC3339Nano,
62
+ }
63
+ log.Out = os.Stdout
64
+ }
65
+
66
+ type checkoutService struct {
67
+ pb.UnimplementedCheckoutServiceServer
68
+
69
+ productCatalogSvcAddr string
70
+ productCatalogSvcConn *grpc.ClientConn
71
+
72
+ cartSvcAddr string
73
+ cartSvcConn *grpc.ClientConn
74
+
75
+ currencySvcAddr string
76
+ currencySvcConn *grpc.ClientConn
77
+
78
+ shippingSvcAddr string
79
+ shippingSvcConn *grpc.ClientConn
80
+
81
+ emailSvcAddr string
82
+ emailSvcConn *grpc.ClientConn
83
+
84
+ paymentSvcAddr string
85
+ paymentSvcConn *grpc.ClientConn
86
+ }
87
+
88
+ func main() {
89
+ ctx := context.Background()
90
+ if os.Getenv("ENABLE_TRACING") == "1" {
91
+ log.Info("Tracing enabled.")
92
+ initTracing()
93
+
94
+ } else {
95
+ log.Info("Tracing disabled.")
96
+ }
97
+
98
+ if os.Getenv("ENABLE_PROFILER") == "1" {
99
+ log.Info("Profiling enabled.")
100
+ go initProfiling("checkoutservice", "1.0.0")
101
+ } else {
102
+ log.Info("Profiling disabled.")
103
+ }
104
+
105
+ port := listenPort
106
+ if os.Getenv("PORT") != "" {
107
+ port = os.Getenv("PORT")
108
+ }
109
+
110
+ svc := new(checkoutService)
111
+ mustMapEnv(&svc.shippingSvcAddr, "SHIPPING_SERVICE_ADDR")
112
+ mustMapEnv(&svc.productCatalogSvcAddr, "PRODUCT_CATALOG_SERVICE_ADDR")
113
+ mustMapEnv(&svc.cartSvcAddr, "CART_SERVICE_ADDR")
114
+ mustMapEnv(&svc.currencySvcAddr, "CURRENCY_SERVICE_ADDR")
115
+ mustMapEnv(&svc.emailSvcAddr, "EMAIL_SERVICE_ADDR")
116
+ mustMapEnv(&svc.paymentSvcAddr, "PAYMENT_SERVICE_ADDR")
117
+
118
+ mustConnGRPC(ctx, &svc.shippingSvcConn, svc.shippingSvcAddr)
119
+ mustConnGRPC(ctx, &svc.productCatalogSvcConn, svc.productCatalogSvcAddr)
120
+ mustConnGRPC(ctx, &svc.cartSvcConn, svc.cartSvcAddr)
121
+ mustConnGRPC(ctx, &svc.currencySvcConn, svc.currencySvcAddr)
122
+ mustConnGRPC(ctx, &svc.emailSvcConn, svc.emailSvcAddr)
123
+ mustConnGRPC(ctx, &svc.paymentSvcConn, svc.paymentSvcAddr)
124
+
125
+ log.Infof("service config: %+v", svc)
126
+
127
+ lis, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
128
+ if err != nil {
129
+ log.Fatal(err)
130
+ }
131
+
132
+ var srv *grpc.Server
133
+
134
+ // Propagate trace context always
135
+ otel.SetTextMapPropagator(
136
+ propagation.NewCompositeTextMapPropagator(
137
+ propagation.TraceContext{}, propagation.Baggage{}))
138
+ srv = grpc.NewServer(
139
+ grpc.StatsHandler(otelgrpc.NewServerHandler()),
140
+ )
141
+
142
+ pb.RegisterCheckoutServiceServer(srv, svc)
143
+ healthcheck := health.NewServer()
144
+ healthpb.RegisterHealthServer(srv, healthcheck)
145
+ log.Infof("starting to listen on tcp: %q", lis.Addr().String())
146
+ err = srv.Serve(lis)
147
+ log.Fatal(err)
148
+ }
149
+
150
+ func initStats() {
151
+ //TODO(arbrown) Implement OpenTelemetry stats
152
+ }
153
+
154
+ func initTracing() {
155
+ var (
156
+ collectorAddr string
157
+ collectorConn *grpc.ClientConn
158
+ )
159
+
160
+ ctx := context.Background()
161
+ ctx, cancel := context.WithTimeout(ctx, time.Second*3)
162
+ defer cancel()
163
+
164
+ mustMapEnv(&collectorAddr, "COLLECTOR_SERVICE_ADDR")
165
+ mustConnGRPC(ctx, &collectorConn, collectorAddr)
166
+
167
+ exporter, err := otlptracegrpc.New(
168
+ ctx,
169
+ otlptracegrpc.WithGRPCConn(collectorConn))
170
+ if err != nil {
171
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
172
+ }
173
+ tp := sdktrace.NewTracerProvider(
174
+ sdktrace.WithBatcher(exporter),
175
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
176
+ otel.SetTracerProvider(tp)
177
+
178
+ }
179
+
180
+ func initProfiling(service, version string) {
181
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
182
+ // since they are not sharing packages.
183
+ for i := 1; i <= 3; i++ {
184
+ if err := profiler.Start(profiler.Config{
185
+ Service: service,
186
+ ServiceVersion: version,
187
+ // ProjectID must be set if not running on GCP.
188
+ // ProjectID: "my-project",
189
+ }); err != nil {
190
+ log.Warnf("failed to start profiler: %+v", err)
191
+ } else {
192
+ log.Info("started Stackdriver profiler")
193
+ return
194
+ }
195
+ d := time.Second * 10 * time.Duration(i)
196
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
197
+ time.Sleep(d)
198
+ }
199
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
200
+ }
201
+
202
+ func mustMapEnv(target *string, envKey string) {
203
+ v := os.Getenv(envKey)
204
+ if v == "" {
205
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
206
+ }
207
+ *target = v
208
+ }
209
+
210
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
211
+ var err error
212
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
213
+ defer cancel()
214
+ *conn, err = grpc.NewClient(addr,
215
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
216
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
217
+ if err != nil {
218
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
219
+ }
220
+ }
221
+
222
+ func (cs *checkoutService) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
223
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
224
+ }
225
+
226
+ func (cs *checkoutService) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
227
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
228
+ }
229
+
230
+ func (cs *checkoutService) PlaceOrder(ctx context.Context, req *pb.PlaceOrderRequest) (*pb.PlaceOrderResponse, error) {
231
+ log.Infof("[PlaceOrder] user_id=%q user_currency=%q", req.UserId, req.UserCurrency)
232
+
233
+ orderID, err := uuid.NewUUID()
234
+ if err != nil {
235
+ return nil, status.Errorf(codes.Internal, "failed to generate order uuid")
236
+ }
237
+
238
+ prep, err := cs.prepareOrderItemsAndShippingQuoteFromCart(ctx, req.UserId, req.UserCurrency, req.Address)
239
+ if err != nil {
240
+ return nil, status.Errorf(codes.Internal, err.Error())
241
+ }
242
+
243
+ total := pb.Money{CurrencyCode: req.UserCurrency,
244
+ Units: 0,
245
+ Nanos: 0}
246
+ total = money.Must(money.Sum(total, *prep.shippingCostLocalized))
247
+ for _, it := range prep.orderItems {
248
+ multPrice := money.MultiplySlow(*it.Cost, uint32(it.GetItem().GetQuantity()))
249
+ total = money.Must(money.Sum(total, multPrice))
250
+ }
251
+
252
+ txID, err := cs.chargeCard(ctx, &total, req.CreditCard)
253
+ if err != nil {
254
+ return nil, status.Errorf(codes.Internal, "failed to charge card: %+v", err)
255
+ }
256
+ log.Infof("payment went through (transaction_id: %s)", txID)
257
+
258
+ shippingTrackingID, err := cs.shipOrder(ctx, req.Address, prep.cartItems)
259
+ if err != nil {
260
+ return nil, status.Errorf(codes.Unavailable, "shipping error: %+v", err)
261
+ }
262
+
263
+ _ = cs.emptyUserCart(ctx, req.UserId)
264
+
265
+ orderResult := &pb.OrderResult{
266
+ OrderId: orderID.String(),
267
+ ShippingTrackingId: shippingTrackingID,
268
+ ShippingCost: prep.shippingCostLocalized,
269
+ ShippingAddress: req.Address,
270
+ Items: prep.orderItems,
271
+ }
272
+
273
+ if err := cs.sendOrderConfirmation(ctx, req.Email, orderResult); err != nil {
274
+ log.Warnf("failed to send order confirmation to %q: %+v", req.Email, err)
275
+ } else {
276
+ log.Infof("order confirmation email sent to %q", req.Email)
277
+ }
278
+ resp := &pb.PlaceOrderResponse{Order: orderResult}
279
+ return resp, nil
280
+ }
281
+
282
+ type orderPrep struct {
283
+ orderItems []*pb.OrderItem
284
+ cartItems []*pb.CartItem
285
+ shippingCostLocalized *pb.Money
286
+ }
287
+
288
+ func (cs *checkoutService) prepareOrderItemsAndShippingQuoteFromCart(ctx context.Context, userID, userCurrency string, address *pb.Address) (orderPrep, error) {
289
+ var out orderPrep
290
+ cartItems, err := cs.getUserCart(ctx, userID)
291
+ if err != nil {
292
+ return out, fmt.Errorf("cart failure: %+v", err)
293
+ }
294
+ orderItems, err := cs.prepOrderItems(ctx, cartItems, userCurrency)
295
+ if err != nil {
296
+ return out, fmt.Errorf("failed to prepare order: %+v", err)
297
+ }
298
+ shippingUSD, err := cs.quoteShipping(ctx, address, cartItems)
299
+ if err != nil {
300
+ return out, fmt.Errorf("shipping quote failure: %+v", err)
301
+ }
302
+ shippingPrice, err := cs.convertCurrency(ctx, shippingUSD, userCurrency)
303
+ if err != nil {
304
+ return out, fmt.Errorf("failed to convert shipping cost to currency: %+v", err)
305
+ }
306
+
307
+ out.shippingCostLocalized = shippingPrice
308
+ out.cartItems = cartItems
309
+ out.orderItems = orderItems
310
+ return out, nil
311
+ }
312
+
313
+ func (cs *checkoutService) quoteShipping(ctx context.Context, address *pb.Address, items []*pb.CartItem) (*pb.Money, error) {
314
+ shippingQuote, err := pb.NewShippingServiceClient(cs.shippingSvcConn).
315
+ GetQuote(ctx, &pb.GetQuoteRequest{
316
+ Address: address,
317
+ Items: items})
318
+ if err != nil {
319
+ return nil, fmt.Errorf("failed to get shipping quote: %+v", err)
320
+ }
321
+ return shippingQuote.GetCostUsd(), nil
322
+ }
323
+
324
+ func (cs *checkoutService) getUserCart(ctx context.Context, userID string) ([]*pb.CartItem, error) {
325
+ cart, err := pb.NewCartServiceClient(cs.cartSvcConn).GetCart(ctx, &pb.GetCartRequest{UserId: userID})
326
+ if err != nil {
327
+ return nil, fmt.Errorf("failed to get user cart during checkout: %+v", err)
328
+ }
329
+ return cart.GetItems(), nil
330
+ }
331
+
332
+ func (cs *checkoutService) emptyUserCart(ctx context.Context, userID string) error {
333
+ if _, err := pb.NewCartServiceClient(cs.cartSvcConn).EmptyCart(ctx, &pb.EmptyCartRequest{UserId: userID}); err != nil {
334
+ return fmt.Errorf("failed to empty user cart during checkout: %+v", err)
335
+ }
336
+ return nil
337
+ }
338
+
339
+ func (cs *checkoutService) prepOrderItems(ctx context.Context, items []*pb.CartItem, userCurrency string) ([]*pb.OrderItem, error) {
340
+ out := make([]*pb.OrderItem, len(items))
341
+ cl := pb.NewProductCatalogServiceClient(cs.productCatalogSvcConn)
342
+
343
+ for i, item := range items {
344
+ product, err := cl.GetProduct(ctx, &pb.GetProductRequest{Id: item.GetProductId()})
345
+ if err != nil {
346
+ return nil, fmt.Errorf("failed to get product #%q", item.GetProductId())
347
+ }
348
+ price, err := cs.convertCurrency(ctx, product.GetPriceUsd(), userCurrency)
349
+ if err != nil {
350
+ return nil, fmt.Errorf("failed to convert price of %q to %s", item.GetProductId(), userCurrency)
351
+ }
352
+ out[i] = &pb.OrderItem{
353
+ Item: item,
354
+ Cost: price}
355
+ }
356
+ return out, nil
357
+ }
358
+
359
+ func (cs *checkoutService) convertCurrency(ctx context.Context, from *pb.Money, toCurrency string) (*pb.Money, error) {
360
+ result, err := pb.NewCurrencyServiceClient(cs.currencySvcConn).Convert(context.TODO(), &pb.CurrencyConversionRequest{
361
+ From: from,
362
+ ToCode: toCurrency})
363
+ if err != nil {
364
+ return nil, fmt.Errorf("failed to convert currency: %+v", err)
365
+ }
366
+ return result, err
367
+ }
368
+
369
+ func (cs *checkoutService) chargeCard(ctx context.Context, amount *pb.Money, paymentInfo *pb.CreditCardInfo) (string, error) {
370
+ paymentResp, err := pb.NewPaymentServiceClient(cs.paymentSvcConn).Charge(ctx, &pb.ChargeRequest{
371
+ Amount: amount,
372
+ CreditCard: paymentInfo})
373
+ if err != nil {
374
+ return "", fmt.Errorf("could not charge the card: %+v", err)
375
+ }
376
+ return paymentResp.GetTransactionId(), nil
377
+ }
378
+
379
+ func (cs *checkoutService) sendOrderConfirmation(ctx context.Context, email string, order *pb.OrderResult) error {
380
+ _, err := pb.NewEmailServiceClient(cs.emailSvcConn).SendOrderConfirmation(ctx, &pb.SendOrderConfirmationRequest{
381
+ Email: email,
382
+ Order: order})
383
+ return err
384
+ }
385
+
386
+ func (cs *checkoutService) shipOrder(ctx context.Context, address *pb.Address, items []*pb.CartItem) (string, error) {
387
+ resp, err := pb.NewShippingServiceClient(cs.shippingSvcConn).ShipOrder(ctx, &pb.ShipOrderRequest{
388
+ Address: address,
389
+ Items: items})
390
+ if err != nil {
391
+ return "", fmt.Errorf("shipment failed: %+v", err)
392
+ }
393
+ return resp.GetTrackingId(), nil
394
+ }
benchmark/boutique/runtime/29/code/checkoutservice/money/money.go ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package money
16
+
17
+ import (
18
+ "errors"
19
+
20
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/checkoutservice/genproto"
21
+ )
22
+
23
+ const (
24
+ nanosMin = -999999999
25
+ nanosMax = +999999999
26
+ nanosMod = 1000000000
27
+ )
28
+
29
+ var (
30
+ ErrInvalidValue = errors.New("one of the specified money values is invalid")
31
+ ErrMismatchingCurrency = errors.New("mismatching currency codes")
32
+ )
33
+
34
+ // IsValid checks if specified value has a valid units/nanos signs and ranges.
35
+ func IsValid(m pb.Money) bool {
36
+ return signMatches(m) && validNanos(m.GetNanos())
37
+ }
38
+
39
+ func signMatches(m pb.Money) bool {
40
+ return m.GetNanos() == 0 || m.GetUnits() == 0 || (m.GetNanos() < 0) == (m.GetUnits() < 0)
41
+ }
42
+
43
+ func validNanos(nanos int32) bool { return nanosMin <= nanos && nanos <= nanosMax }
44
+
45
+ // IsZero returns true if the specified money value is equal to zero.
46
+ func IsZero(m pb.Money) bool { return m.GetUnits() == 0 && m.GetNanos() == 0 }
47
+
48
+ // IsPositive returns true if the specified money value is valid and is
49
+ // positive.
50
+ func IsPositive(m pb.Money) bool {
51
+ return IsValid(m) && m.GetUnits() > 0 || (m.GetUnits() == 0 && m.GetNanos() > 0)
52
+ }
53
+
54
+ // IsNegative returns true if the specified money value is valid and is
55
+ // negative.
56
+ func IsNegative(m pb.Money) bool {
57
+ return IsValid(m) && m.GetUnits() < 0 || (m.GetUnits() == 0 && m.GetNanos() < 0)
58
+ }
59
+
60
+ // AreSameCurrency returns true if values l and r have a currency code and
61
+ // they are the same values.
62
+ func AreSameCurrency(l, r pb.Money) bool {
63
+ return l.GetCurrencyCode() == r.GetCurrencyCode() && l.GetCurrencyCode() != ""
64
+ }
65
+
66
+ // AreEquals returns true if values l and r are the equal, including the
67
+ // currency. This does not check validity of the provided values.
68
+ func AreEquals(l, r pb.Money) bool {
69
+ return l.GetCurrencyCode() == r.GetCurrencyCode() &&
70
+ l.GetUnits() == r.GetUnits() && l.GetNanos() == r.GetNanos()
71
+ }
72
+
73
+ // Negate returns the same amount with the sign negated.
74
+ func Negate(m pb.Money) pb.Money {
75
+ return pb.Money{
76
+ Units: -m.GetUnits(),
77
+ Nanos: -m.GetNanos(),
78
+ CurrencyCode: m.GetCurrencyCode()}
79
+ }
80
+
81
+ // Must panics if the given error is not nil. This can be used with other
82
+ // functions like: "m := Must(Sum(a,b))".
83
+ func Must(v pb.Money, err error) pb.Money {
84
+ if err != nil {
85
+ panic(err)
86
+ }
87
+ return v
88
+ }
89
+
90
+ // Sum adds two values. Returns an error if one of the values are invalid or
91
+ // currency codes are not matching (unless currency code is unspecified for
92
+ // both).
93
+ func Sum(l, r pb.Money) (pb.Money, error) {
94
+ if !IsValid(l) || !IsValid(r) {
95
+ return pb.Money{}, ErrInvalidValue
96
+ } else if l.GetCurrencyCode() != r.GetCurrencyCode() {
97
+ return pb.Money{}, ErrMismatchingCurrency
98
+ }
99
+ units := l.GetUnits() + r.GetUnits()
100
+ nanos := l.GetNanos() + r.GetNanos()
101
+
102
+ if (units == 0 && nanos == 0) || (units > 0 && nanos >= 0) || (units < 0 && nanos <= 0) {
103
+ // same sign <units, nanos>
104
+ units += int64(nanos / nanosMod)
105
+ nanos = nanos % nanosMod
106
+ } else {
107
+ // different sign. nanos guaranteed to not to go over the limit
108
+ if units > 0 {
109
+ units--
110
+ nanos += nanosMod
111
+ } else {
112
+ units++
113
+ nanos -= nanosMod
114
+ }
115
+ }
116
+
117
+ return pb.Money{
118
+ Units: units,
119
+ Nanos: nanos,
120
+ CurrencyCode: l.GetCurrencyCode()}, nil
121
+ }
122
+
123
+ // MultiplySlow is a slow multiplication operation done through adding the value
124
+ // to itself n-1 times.
125
+ func MultiplySlow(m pb.Money, n uint32) pb.Money {
126
+ out := m
127
+ for n > 1 {
128
+ out = Must(Sum(out, m))
129
+ n--
130
+ }
131
+ return out
132
+ }
benchmark/boutique/runtime/29/code/currencyservice/client.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *
3
+ * Copyright 2015 gRPC authors.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ *
17
+ */
18
+ require('@google-cloud/trace-agent').start();
19
+
20
+ const path = require('path');
21
+ const grpc = require('grpc');
22
+ const pino = require('pino');
23
+
24
+ const PROTO_PATH = path.join(__dirname, './proto/demo.proto');
25
+ const PORT = 7000;
26
+
27
+ const shopProto = grpc.load(PROTO_PATH).hipstershop;
28
+ const client = new shopProto.CurrencyService(`localhost:${PORT}`,
29
+ grpc.credentials.createInsecure());
30
+
31
+ const logger = pino({
32
+ name: 'currencyservice-client',
33
+ messageKey: 'message',
34
+ formatters: {
35
+ level (logLevelString, logLevelNum) {
36
+ return { severity: logLevelString }
37
+ }
38
+ }
39
+ });
40
+
41
+ const request = {
42
+ from: {
43
+ currency_code: 'CHF',
44
+ units: 300,
45
+ nanos: 0
46
+ },
47
+ to_code: 'EUR'
48
+ };
49
+
50
+ function _moneyToString (m) {
51
+ return `${m.units}.${m.nanos.toString().padStart(9,'0')} ${m.currency_code}`;
52
+ }
53
+
54
+ client.getSupportedCurrencies({}, (err, response) => {
55
+ if (err) {
56
+ logger.error(`Error in getSupportedCurrencies: ${err}`);
57
+ } else {
58
+ logger.info(`Currency codes: ${response.currency_codes}`);
59
+ }
60
+ });
61
+
62
+ client.convert(request, (err, response) => {
63
+ if (err) {
64
+ logger.error(`Error in convert: ${err}`);
65
+ } else {
66
+ logger.log(`Convert: ${_moneyToString(request.from)} to ${_moneyToString(response)}`);
67
+ }
68
+ });
benchmark/boutique/runtime/29/code/currencyservice/server.js ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018 Google LLC.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const pino = require('pino');
18
+ const logger = pino({
19
+ name: 'currencyservice-server',
20
+ messageKey: 'message',
21
+ formatters: {
22
+ level (logLevelString, logLevelNum) {
23
+ return { severity: logLevelString }
24
+ }
25
+ }
26
+ });
27
+
28
+ if(process.env.DISABLE_PROFILER) {
29
+ logger.info("Profiler disabled.")
30
+ }
31
+ else {
32
+ logger.info("Profiler enabled.")
33
+ require('@google-cloud/profiler').start({
34
+ serviceContext: {
35
+ service: 'currencyservice',
36
+ version: '1.0.0'
37
+ }
38
+ });
39
+ }
40
+
41
+ // Register GRPC OTel Instrumentation for trace propagation
42
+ // regardless of whether tracing is emitted.
43
+ const { GrpcInstrumentation } = require('@opentelemetry/instrumentation-grpc');
44
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
45
+
46
+ registerInstrumentations({
47
+ instrumentations: [new GrpcInstrumentation()]
48
+ });
49
+
50
+ if(process.env.ENABLE_TRACING == "1") {
51
+ logger.info("Tracing enabled.")
52
+
53
+ const { resourceFromAttributes } = require('@opentelemetry/resources');
54
+
55
+ const { ATTR_SERVICE_NAME } = require('@opentelemetry/semantic-conventions');
56
+
57
+ const opentelemetry = require('@opentelemetry/sdk-node');
58
+
59
+ const { OTLPTraceExporter } = require('@opentelemetry/exporter-otlp-grpc');
60
+
61
+ const collectorUrl = process.env.COLLECTOR_SERVICE_ADDR;
62
+ const traceExporter = new OTLPTraceExporter({url: collectorUrl});
63
+ const sdk = new opentelemetry.NodeSDK({
64
+ resource: resourceFromAttributes({
65
+ [ ATTR_SERVICE_NAME ]: process.env.OTEL_SERVICE_NAME || 'currencyservice',
66
+ }),
67
+ traceExporter: traceExporter,
68
+ });
69
+
70
+ sdk.start()
71
+ }
72
+ else {
73
+ logger.info("Tracing disabled.")
74
+ }
75
+
76
+ const path = require('path');
77
+ const grpc = require('@grpc/grpc-js');
78
+ const protoLoader = require('@grpc/proto-loader');
79
+
80
+ const MAIN_PROTO_PATH = path.join(__dirname, './proto/demo.proto');
81
+ const HEALTH_PROTO_PATH = path.join(__dirname, './proto/grpc/health/v1/health.proto');
82
+
83
+ const PORT = process.env.PORT;
84
+
85
+ const shopProto = _loadProto(MAIN_PROTO_PATH).hipstershop;
86
+ const healthProto = _loadProto(HEALTH_PROTO_PATH).grpc.health.v1;
87
+
88
+ /**
89
+ * Helper function that loads a protobuf file.
90
+ */
91
+ function _loadProto (path) {
92
+ const packageDefinition = protoLoader.loadSync(
93
+ path,
94
+ {
95
+ keepCase: true,
96
+ longs: String,
97
+ enums: String,
98
+ defaults: true,
99
+ oneofs: true
100
+ }
101
+ );
102
+ return grpc.loadPackageDefinition(packageDefinition);
103
+ }
104
+
105
+ /**
106
+ * Helper function that gets currency data from a stored JSON file
107
+ * Uses public data from European Central Bank
108
+ */
109
+ function _getCurrencyData (callback) {
110
+ const data = require('./data/currency_conversion.json');
111
+ callback(data);
112
+ }
113
+
114
+ /**
115
+ * Helper function that handles decimal/fractional carrying
116
+ */
117
+ function _carry (amount) {
118
+ const fractionSize = Math.pow(10, 9);
119
+ amount.nanos += (amount.units % 1) * fractionSize;
120
+ amount.units = Math.floor(amount.units) + Math.floor(amount.nanos / fractionSize);
121
+ amount.nanos = amount.nanos % fractionSize;
122
+ return amount;
123
+ }
124
+
125
+ /**
126
+ * Lists the supported currencies
127
+ */
128
+ function getSupportedCurrencies (call, callback) {
129
+ logger.info('Getting supported currencies...');
130
+ _getCurrencyData((data) => {
131
+ callback(null, {currency_codes: Object.keys(data)});
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Converts between currencies
137
+ */
138
+ function convert (call, callback) {
139
+ try {
140
+ _getCurrencyData((data) => {
141
+ const request = call.request;
142
+
143
+ // Convert: from_currency --> EUR
144
+ const from = request.from;
145
+ const euros = _carry({
146
+ units: from.units / data[from.currency_code],
147
+ nanos: from.nanos / data[from.currency_code]
148
+ });
149
+
150
+ euros.nanos = Math.round(euros.nanos);
151
+
152
+ // Convert: EUR --> to_currency
153
+ const result = _carry({
154
+ units: euros.units * data[request.to_code],
155
+ nanos: euros.nanos * data[request.to_code]
156
+ });
157
+
158
+ result.units = Math.floor(result.units);
159
+ result.nanos = Math.floor(result.nanos);
160
+ result.currency_code = request.to_code;
161
+
162
+ logger.info(`conversion request successful`);
163
+ callback(null, result);
164
+ });
165
+ } catch (err) {
166
+ logger.error(`conversion request failed: ${err}`);
167
+ callback(err.message);
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Endpoint for health checks
173
+ */
174
+ function check (call, callback) {
175
+ callback(null, { status: 'SERVING' });
176
+ }
177
+
178
+ /**
179
+ * Starts an RPC server that receives requests for the
180
+ * CurrencyConverter service at the sample server port
181
+ */
182
+ function main () {
183
+ logger.info(`Starting gRPC server on port ${PORT}...`);
184
+ const server = new grpc.Server();
185
+ server.addService(shopProto.CurrencyService.service, {getSupportedCurrencies, convert});
186
+ server.addService(healthProto.Health.service, {check});
187
+
188
+ server.bindAsync(
189
+ `[::]:${PORT}`,
190
+ grpc.ServerCredentials.createInsecure(),
191
+ function() {
192
+ logger.info(`CurrencyService gRPC server started on port ${PORT}`);
193
+ server.start();
194
+ },
195
+ );
196
+ }
197
+
198
+ main();
benchmark/boutique/runtime/29/code/emailservice/email_client.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import grpc
18
+
19
+ import demo_pb2
20
+ import demo_pb2_grpc
21
+
22
+ from logger import getJSONLogger
23
+ logger = getJSONLogger('emailservice-client')
24
+
25
+ def send_confirmation_email(email, order):
26
+ channel = grpc.insecure_channel('[::]:8080')
27
+ stub = demo_pb2_grpc.EmailServiceStub(channel)
28
+ try:
29
+ response = stub.SendOrderConfirmation(demo_pb2.SendOrderConfirmationRequest(
30
+ email = email,
31
+ order = order
32
+ ))
33
+ logger.info('Request sent.')
34
+ except grpc.RpcError as err:
35
+ logger.error(err.details())
36
+ logger.error('{}, {}'.format(err.code().name, err.code().value))
37
+
38
+ if __name__ == '__main__':
39
+ logger.info('Client for email service.')
benchmark/boutique/runtime/29/code/emailservice/email_server.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from concurrent import futures
18
+ import argparse
19
+ import os
20
+ import sys
21
+ import time
22
+ import grpc
23
+ import traceback
24
+ from jinja2 import Environment, FileSystemLoader, select_autoescape, TemplateError
25
+ from google.api_core.exceptions import GoogleAPICallError
26
+ from google.auth.exceptions import DefaultCredentialsError
27
+
28
+ import demo_pb2
29
+ import demo_pb2_grpc
30
+ from grpc_health.v1 import health_pb2
31
+ from grpc_health.v1 import health_pb2_grpc
32
+
33
+ from opentelemetry import trace
34
+ from opentelemetry.instrumentation.grpc import GrpcInstrumentorServer
35
+ from opentelemetry.sdk.trace import TracerProvider
36
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
37
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
38
+
39
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
40
+ # import googlecloudprofiler
41
+
42
+ from logger import getJSONLogger
43
+ logger = getJSONLogger('emailservice-server')
44
+
45
+ # Loads confirmation email template from file
46
+ env = Environment(
47
+ loader=FileSystemLoader('templates'),
48
+ autoescape=select_autoescape(['html', 'xml'])
49
+ )
50
+ template = env.get_template('confirmation.html')
51
+
52
+ class BaseEmailService(demo_pb2_grpc.EmailServiceServicer):
53
+ def Check(self, request, context):
54
+ return health_pb2.HealthCheckResponse(
55
+ status=health_pb2.HealthCheckResponse.SERVING)
56
+
57
+ def Watch(self, request, context):
58
+ return health_pb2.HealthCheckResponse(
59
+ status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)
60
+
61
+ class EmailService(BaseEmailService):
62
+ def __init__(self):
63
+ raise Exception('cloud mail client not implemented')
64
+ super().__init__()
65
+
66
+ @staticmethod
67
+ def send_email(client, email_address, content):
68
+ response = client.send_message(
69
+ sender = client.sender_path(project_id, region, sender_id),
70
+ envelope_from_authority = '',
71
+ header_from_authority = '',
72
+ envelope_from_address = from_address,
73
+ simple_message = {
74
+ "from": {
75
+ "address_spec": from_address,
76
+ },
77
+ "to": [{
78
+ "address_spec": email_address
79
+ }],
80
+ "subject": "Your Confirmation Email",
81
+ "html_body": content
82
+ }
83
+ )
84
+ logger.info("Message sent: {}".format(response.rfc822_message_id))
85
+
86
+ def SendOrderConfirmation(self, request, context):
87
+ email = request.email
88
+ order = request.order
89
+
90
+ try:
91
+ confirmation = template.render(order = order)
92
+ except TemplateError as err:
93
+ context.set_details("An error occurred when preparing the confirmation mail.")
94
+ logger.error(err.message)
95
+ context.set_code(grpc.StatusCode.INTERNAL)
96
+ return demo_pb2.Empty()
97
+
98
+ try:
99
+ EmailService.send_email(self.client, email, confirmation)
100
+ except GoogleAPICallError as err:
101
+ context.set_details("An error occurred when sending the email.")
102
+ print(err.message)
103
+ context.set_code(grpc.StatusCode.INTERNAL)
104
+ return demo_pb2.Empty()
105
+
106
+ return demo_pb2.Empty()
107
+
108
+ class DummyEmailService(BaseEmailService):
109
+ def SendOrderConfirmation(self, request, context):
110
+ logger.info('A request to send order confirmation email to {} has been received.'.format(request.email))
111
+ return demo_pb2.Empty()
112
+
113
+ class HealthCheck():
114
+ def Check(self, request, context):
115
+ return health_pb2.HealthCheckResponse(
116
+ status=health_pb2.HealthCheckResponse.SERVING)
117
+
118
+ def start(dummy_mode):
119
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),)
120
+ service = None
121
+ if dummy_mode:
122
+ service = DummyEmailService()
123
+ else:
124
+ raise Exception('non-dummy mode not implemented yet')
125
+
126
+ demo_pb2_grpc.add_EmailServiceServicer_to_server(service, server)
127
+ health_pb2_grpc.add_HealthServicer_to_server(service, server)
128
+
129
+ port = os.environ.get('PORT', "8080")
130
+ logger.info("listening on port: "+port)
131
+ server.add_insecure_port('[::]:'+port)
132
+ server.start()
133
+ try:
134
+ while True:
135
+ time.sleep(3600)
136
+ except KeyboardInterrupt:
137
+ server.stop(0)
138
+
139
+ def initStackdriverProfiling():
140
+ project_id = None
141
+ try:
142
+ project_id = os.environ["GCP_PROJECT_ID"]
143
+ except KeyError:
144
+ # Environment variable not set
145
+ pass
146
+
147
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
148
+ # for retry in range(1,4):
149
+ # try:
150
+ # if project_id:
151
+ # googlecloudprofiler.start(service='email_server', service_version='1.0.0', verbose=0, project_id=project_id)
152
+ # else:
153
+ # googlecloudprofiler.start(service='email_server', service_version='1.0.0', verbose=0)
154
+ # logger.info("Successfully started Stackdriver Profiler.")
155
+ # return
156
+ # except (BaseException) as exc:
157
+ # logger.info("Unable to start Stackdriver Profiler Python agent. " + str(exc))
158
+ # if (retry < 4):
159
+ # logger.info("Sleeping %d to retry initializing Stackdriver Profiler"%(retry*10))
160
+ # time.sleep (1)
161
+ # else:
162
+ # logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up")
163
+ return
164
+
165
+
166
+ if __name__ == '__main__':
167
+ logger.info('starting the email service in dummy mode.')
168
+
169
+ # Profiler
170
+ try:
171
+ if "DISABLE_PROFILER" in os.environ:
172
+ raise KeyError()
173
+ else:
174
+ logger.info("Profiler enabled.")
175
+ initStackdriverProfiling()
176
+ except KeyError:
177
+ logger.info("Profiler disabled.")
178
+
179
+ # Tracing
180
+ try:
181
+ if os.environ["ENABLE_TRACING"] == "1":
182
+ otel_endpoint = os.getenv("COLLECTOR_SERVICE_ADDR", "localhost:4317")
183
+ trace.set_tracer_provider(TracerProvider())
184
+ trace.get_tracer_provider().add_span_processor(
185
+ BatchSpanProcessor(
186
+ OTLPSpanExporter(
187
+ endpoint = otel_endpoint,
188
+ insecure = True
189
+ )
190
+ )
191
+ )
192
+ grpc_server_instrumentor = GrpcInstrumentorServer()
193
+ grpc_server_instrumentor.instrument()
194
+
195
+ except (KeyError, DefaultCredentialsError):
196
+ logger.info("Tracing disabled.")
197
+ except Exception as e:
198
+ logger.warn(f"Exception on Cloud Trace setup: {traceback.format_exc()}, tracing disabled.")
199
+
200
+ start(dummy_mode = True)
benchmark/boutique/runtime/29/code/emailservice/logger.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import sys
19
+ from pythonjsonlogger import jsonlogger
20
+
21
+ # TODO(yoshifumi) this class is duplicated since other Python services are
22
+ # not sharing the modules for logging.
23
+ class CustomJsonFormatter(jsonlogger.JsonFormatter):
24
+ def add_fields(self, log_record, record, message_dict):
25
+ super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
26
+ if not log_record.get('timestamp'):
27
+ log_record['timestamp'] = record.created
28
+ if log_record.get('severity'):
29
+ log_record['severity'] = log_record['severity'].upper()
30
+ else:
31
+ log_record['severity'] = record.levelname
32
+
33
+ def getJSONLogger(name):
34
+ logger = logging.getLogger(name)
35
+ handler = logging.StreamHandler(sys.stdout)
36
+ formatter = CustomJsonFormatter('%(timestamp)s %(severity)s %(name)s %(message)s')
37
+ handler.setFormatter(formatter)
38
+ logger.addHandler(handler)
39
+ logger.setLevel(logging.INFO)
40
+ logger.propagate = False
41
+ return logger
benchmark/boutique/runtime/29/code/frontend/deployment_details.go ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "net/http"
5
+ "os"
6
+ "time"
7
+
8
+ "cloud.google.com/go/compute/metadata"
9
+ "github.com/sirupsen/logrus"
10
+ )
11
+
12
+ var deploymentDetailsMap map[string]string
13
+ var log *logrus.Logger
14
+
15
+ func init() {
16
+ initializeLogger()
17
+ // Use a goroutine to ensure loadDeploymentDetails()'s GCP API
18
+ // calls don't block non-GCP deployments. See issue #685.
19
+ go loadDeploymentDetails()
20
+ }
21
+
22
+ func initializeLogger() {
23
+ log = logrus.New()
24
+ log.Level = logrus.DebugLevel
25
+ log.Formatter = &logrus.JSONFormatter{
26
+ FieldMap: logrus.FieldMap{
27
+ logrus.FieldKeyTime: "timestamp",
28
+ logrus.FieldKeyLevel: "severity",
29
+ logrus.FieldKeyMsg: "message",
30
+ },
31
+ TimestampFormat: time.RFC3339Nano,
32
+ }
33
+ log.Out = os.Stdout
34
+ }
35
+
36
+ func loadDeploymentDetails() {
37
+ deploymentDetailsMap = make(map[string]string)
38
+ var metaServerClient = metadata.NewClient(&http.Client{})
39
+
40
+ podHostname, err := os.Hostname()
41
+ if err != nil {
42
+ log.Error("Failed to fetch the hostname for the Pod", err)
43
+ }
44
+
45
+ podCluster, err := metaServerClient.InstanceAttributeValue("cluster-name")
46
+ if err != nil {
47
+ log.Error("Failed to fetch the name of the cluster in which the pod is running", err)
48
+ }
49
+
50
+ podZone, err := metaServerClient.Zone()
51
+ if err != nil {
52
+ log.Error("Failed to fetch the Zone of the node where the pod is scheduled", err)
53
+ }
54
+
55
+ deploymentDetailsMap["HOSTNAME"] = podHostname
56
+ deploymentDetailsMap["CLUSTERNAME"] = podCluster
57
+ deploymentDetailsMap["ZONE"] = podZone
58
+
59
+ log.WithFields(logrus.Fields{
60
+ "cluster": podCluster,
61
+ "zone": podZone,
62
+ "hostname": podHostname,
63
+ }).Debug("Loaded deployment details")
64
+ }
benchmark/boutique/runtime/29/code/frontend/handlers.go ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "encoding/json"
20
+ "fmt"
21
+ "html/template"
22
+ "io"
23
+ "math/rand"
24
+ "net"
25
+ "net/http"
26
+ "os"
27
+ "strconv"
28
+ "strings"
29
+ "time"
30
+
31
+ "github.com/gorilla/mux"
32
+ "github.com/pkg/errors"
33
+ "github.com/sirupsen/logrus"
34
+
35
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/genproto"
36
+ "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/money"
37
+ "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/validator"
38
+ )
39
+
40
+ type platformDetails struct {
41
+ css string
42
+ provider string
43
+ }
44
+
45
+ var (
46
+ frontendMessage = strings.TrimSpace(os.Getenv("FRONTEND_MESSAGE"))
47
+ isCymbalBrand = "true" == strings.ToLower(os.Getenv("CYMBAL_BRANDING"))
48
+ assistantEnabled = "true" == strings.ToLower(os.Getenv("ENABLE_ASSISTANT"))
49
+ templates = template.Must(template.New("").
50
+ Funcs(template.FuncMap{
51
+ "renderMoney": renderMoney,
52
+ "renderCurrencyLogo": renderCurrencyLogo,
53
+ }).ParseGlob("templates/*.html"))
54
+ plat platformDetails
55
+ )
56
+
57
+ var validEnvs = []string{"local", "gcp", "azure", "aws", "onprem", "alibaba"}
58
+
59
+ func (fe *frontendServer) homeHandler(w http.ResponseWriter, r *http.Request) {
60
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
61
+ log.WithField("currency", currentCurrency(r)).Info("home")
62
+ currencies, err := fe.getCurrencies(r.Context())
63
+ if err != nil {
64
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
65
+ return
66
+ }
67
+ products, err := fe.getProducts(r.Context())
68
+ if err != nil {
69
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve products"), http.StatusInternalServerError)
70
+ return
71
+ }
72
+ cart, err := fe.getCart(r.Context(), sessionID(r))
73
+ if err != nil {
74
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve cart"), http.StatusInternalServerError)
75
+ return
76
+ }
77
+
78
+ type productView struct {
79
+ Item *pb.Product
80
+ Price *pb.Money
81
+ }
82
+ ps := make([]productView, len(products))
83
+ for i, p := range products {
84
+ price, err := fe.convertCurrency(r.Context(), p.GetPriceUsd(), currentCurrency(r))
85
+ if err != nil {
86
+ renderHTTPError(log, r, w, errors.Wrapf(err, "failed to do currency conversion for product %s", p.GetId()), http.StatusInternalServerError)
87
+ return
88
+ }
89
+ ps[i] = productView{p, price}
90
+ }
91
+
92
+ // Set ENV_PLATFORM (default to local if not set; use env var if set; otherwise detect GCP, which overrides env)_
93
+ var env = os.Getenv("ENV_PLATFORM")
94
+ // Only override from env variable if set + valid env
95
+ if env == "" || stringinSlice(validEnvs, env) == false {
96
+ fmt.Println("env platform is either empty or invalid")
97
+ env = "local"
98
+ }
99
+ // Autodetect GCP
100
+ addrs, err := net.LookupHost("metadata.google.internal.")
101
+ if err == nil && len(addrs) >= 0 {
102
+ log.Debugf("Detected Google metadata server: %v, setting ENV_PLATFORM to GCP.", addrs)
103
+ env = "gcp"
104
+ }
105
+
106
+ log.Debugf("ENV_PLATFORM is: %s", env)
107
+ plat = platformDetails{}
108
+ plat.setPlatformDetails(strings.ToLower(env))
109
+
110
+ if err := templates.ExecuteTemplate(w, "home", injectCommonTemplateData(r, map[string]interface{}{
111
+ "show_currency": true,
112
+ "currencies": currencies,
113
+ "products": ps,
114
+ "cart_size": cartSize(cart),
115
+ "banner_color": os.Getenv("BANNER_COLOR"), // illustrates canary deployments
116
+ "ad": fe.chooseAd(r.Context(), []string{}, log),
117
+ })); err != nil {
118
+ log.Error(err)
119
+ }
120
+ }
121
+
122
+ func (plat *platformDetails) setPlatformDetails(env string) {
123
+ if env == "aws" {
124
+ plat.provider = "AWS"
125
+ plat.css = "aws-platform"
126
+ } else if env == "onprem" {
127
+ plat.provider = "On-Premises"
128
+ plat.css = "onprem-platform"
129
+ } else if env == "azure" {
130
+ plat.provider = "Azure"
131
+ plat.css = "azure-platform"
132
+ } else if env == "gcp" {
133
+ plat.provider = "Google Cloud"
134
+ plat.css = "gcp-platform"
135
+ } else if env == "alibaba" {
136
+ plat.provider = "Alibaba Cloud"
137
+ plat.css = "alibaba-platform"
138
+ } else {
139
+ plat.provider = "local"
140
+ plat.css = "local"
141
+ }
142
+ }
143
+
144
+ func (fe *frontendServer) productHandler(w http.ResponseWriter, r *http.Request) {
145
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
146
+ id := mux.Vars(r)["id"]
147
+ if id == "" {
148
+ renderHTTPError(log, r, w, errors.New("product id not specified"), http.StatusBadRequest)
149
+ return
150
+ }
151
+ log.WithField("id", id).WithField("currency", currentCurrency(r)).
152
+ Debug("serving product page")
153
+
154
+ p, err := fe.getProduct(r.Context(), id)
155
+ if err != nil {
156
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve product"), http.StatusInternalServerError)
157
+ return
158
+ }
159
+ currencies, err := fe.getCurrencies(r.Context())
160
+ if err != nil {
161
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
162
+ return
163
+ }
164
+
165
+ cart, err := fe.getCart(r.Context(), sessionID(r))
166
+ if err != nil {
167
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve cart"), http.StatusInternalServerError)
168
+ return
169
+ }
170
+
171
+ price, err := fe.convertCurrency(r.Context(), p.GetPriceUsd(), currentCurrency(r))
172
+ if err != nil {
173
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to convert currency"), http.StatusInternalServerError)
174
+ return
175
+ }
176
+
177
+ // ignores the error retrieving recommendations since it is not critical
178
+ recommendations, err := fe.getRecommendations(r.Context(), sessionID(r), []string{id})
179
+ if err != nil {
180
+ log.WithField("error", err).Warn("failed to get product recommendations")
181
+ }
182
+
183
+ product := struct {
184
+ Item *pb.Product
185
+ Price *pb.Money
186
+ }{p, price}
187
+
188
+ // Fetch packaging info (weight/dimensions) of the product
189
+ // The packaging service is an optional microservice you can run as part of a Google Cloud demo.
190
+ var packagingInfo *PackagingInfo = nil
191
+ if isPackagingServiceConfigured() {
192
+ packagingInfo, err = httpGetPackagingInfo(id)
193
+ if err != nil {
194
+ fmt.Println("Failed to obtain product's packaging info:", err)
195
+ }
196
+ }
197
+
198
+ if err := templates.ExecuteTemplate(w, "product", injectCommonTemplateData(r, map[string]interface{}{
199
+ "ad": fe.chooseAd(r.Context(), p.Categories, log),
200
+ "show_currency": true,
201
+ "currencies": currencies,
202
+ "product": product,
203
+ "recommendations": recommendations,
204
+ "cart_size": cartSize(cart),
205
+ "packagingInfo": packagingInfo,
206
+ })); err != nil {
207
+ log.Println(err)
208
+ }
209
+ }
210
+
211
+ func (fe *frontendServer) addToCartHandler(w http.ResponseWriter, r *http.Request) {
212
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
213
+ quantity, _ := strconv.ParseUint(r.FormValue("quantity"), 10, 32)
214
+ productID := r.FormValue("product_id")
215
+ payload := validator.AddToCartPayload{
216
+ Quantity: quantity,
217
+ ProductID: productID,
218
+ }
219
+ if err := payload.Validate(); err != nil {
220
+ renderHTTPError(log, r, w, validator.ValidationErrorResponse(err), http.StatusUnprocessableEntity)
221
+ return
222
+ }
223
+ log.WithField("product", payload.ProductID).WithField("quantity", payload.Quantity).Debug("adding to cart")
224
+
225
+ p, err := fe.getProduct(r.Context(), payload.ProductID)
226
+ if err != nil {
227
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve product"), http.StatusInternalServerError)
228
+ return
229
+ }
230
+
231
+ if err := fe.insertCart(r.Context(), sessionID(r), p.GetId(), int32(payload.Quantity)); err != nil {
232
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to add to cart"), http.StatusInternalServerError)
233
+ return
234
+ }
235
+ w.Header().Set("location", baseUrl + "/cart")
236
+ w.WriteHeader(http.StatusFound)
237
+ }
238
+
239
+ func (fe *frontendServer) emptyCartHandler(w http.ResponseWriter, r *http.Request) {
240
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
241
+ log.Debug("emptying cart")
242
+
243
+ if err := fe.emptyCart(r.Context(), sessionID(r)); err != nil {
244
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to empty cart"), http.StatusInternalServerError)
245
+ return
246
+ }
247
+ w.Header().Set("location", baseUrl + "/")
248
+ w.WriteHeader(http.StatusFound)
249
+ }
250
+
251
+ func (fe *frontendServer) viewCartHandler(w http.ResponseWriter, r *http.Request) {
252
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
253
+ log.Debug("view user cart")
254
+ currencies, err := fe.getCurrencies(r.Context())
255
+ if err != nil {
256
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
257
+ return
258
+ }
259
+ cart, err := fe.getCart(r.Context(), sessionID(r))
260
+ if err != nil {
261
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve cart"), http.StatusInternalServerError)
262
+ return
263
+ }
264
+
265
+ // ignores the error retrieving recommendations since it is not critical
266
+ recommendations, err := fe.getRecommendations(r.Context(), sessionID(r), cartIDs(cart))
267
+ if err != nil {
268
+ log.WithField("error", err).Warn("failed to get product recommendations")
269
+ }
270
+
271
+ shippingCost, err := fe.getShippingQuote(r.Context(), cart, currentCurrency(r))
272
+ if err != nil {
273
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to get shipping quote"), http.StatusInternalServerError)
274
+ return
275
+ }
276
+
277
+ type cartItemView struct {
278
+ Item *pb.Product
279
+ Quantity int32
280
+ Price *pb.Money
281
+ }
282
+ items := make([]cartItemView, len(cart))
283
+ totalPrice := pb.Money{CurrencyCode: currentCurrency(r)}
284
+ for i, item := range cart {
285
+ p, err := fe.getProduct(r.Context(), item.GetProductId())
286
+ if err != nil {
287
+ renderHTTPError(log, r, w, errors.Wrapf(err, "could not retrieve product #%s", item.GetProductId()), http.StatusInternalServerError)
288
+ return
289
+ }
290
+ price, err := fe.convertCurrency(r.Context(), p.GetPriceUsd(), currentCurrency(r))
291
+ if err != nil {
292
+ renderHTTPError(log, r, w, errors.Wrapf(err, "could not convert currency for product #%s", item.GetProductId()), http.StatusInternalServerError)
293
+ return
294
+ }
295
+
296
+ multPrice := money.MultiplySlow(*price, uint32(item.GetQuantity()))
297
+ items[i] = cartItemView{
298
+ Item: p,
299
+ Quantity: item.GetQuantity(),
300
+ Price: &multPrice}
301
+ totalPrice = money.Must(money.Sum(totalPrice, multPrice))
302
+ }
303
+ totalPrice = money.Must(money.Sum(totalPrice, *shippingCost))
304
+ year := time.Now().Year()
305
+
306
+ if err := templates.ExecuteTemplate(w, "cart", injectCommonTemplateData(r, map[string]interface{}{
307
+ "currencies": currencies,
308
+ "recommendations": recommendations,
309
+ "cart_size": cartSize(cart),
310
+ "shipping_cost": shippingCost,
311
+ "show_currency": true,
312
+ "total_cost": totalPrice,
313
+ "items": items,
314
+ "expiration_years": []int{year, year + 1, year + 2, year + 3, year + 4},
315
+ })); err != nil {
316
+ log.Println(err)
317
+ }
318
+ }
319
+
320
+ func (fe *frontendServer) placeOrderHandler(w http.ResponseWriter, r *http.Request) {
321
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
322
+ log.Debug("placing order")
323
+
324
+ var (
325
+ email = r.FormValue("email")
326
+ streetAddress = r.FormValue("street_address")
327
+ zipCode, _ = strconv.ParseInt(r.FormValue("zip_code"), 10, 32)
328
+ city = r.FormValue("city")
329
+ state = r.FormValue("state")
330
+ country = r.FormValue("country")
331
+ ccNumber = r.FormValue("credit_card_number")
332
+ ccMonth, _ = strconv.ParseInt(r.FormValue("credit_card_expiration_month"), 10, 32)
333
+ ccYear, _ = strconv.ParseInt(r.FormValue("credit_card_expiration_year"), 10, 32)
334
+ ccCVV, _ = strconv.ParseInt(r.FormValue("credit_card_cvv"), 10, 32)
335
+ )
336
+
337
+ payload := validator.PlaceOrderPayload{
338
+ Email: email,
339
+ StreetAddress: streetAddress,
340
+ ZipCode: zipCode,
341
+ City: city,
342
+ State: state,
343
+ Country: country,
344
+ CcNumber: ccNumber,
345
+ CcMonth: ccMonth,
346
+ CcYear: ccYear,
347
+ CcCVV: ccCVV,
348
+ }
349
+ if err := payload.Validate(); err != nil {
350
+ renderHTTPError(log, r, w, validator.ValidationErrorResponse(err), http.StatusUnprocessableEntity)
351
+ return
352
+ }
353
+
354
+ order, err := pb.NewCheckoutServiceClient(fe.checkoutSvcConn).
355
+ PlaceOrder(r.Context(), &pb.PlaceOrderRequest{
356
+ Email: payload.Email,
357
+ CreditCard: &pb.CreditCardInfo{
358
+ CreditCardNumber: payload.CcNumber,
359
+ CreditCardExpirationMonth: int32(payload.CcMonth),
360
+ CreditCardExpirationYear: int32(payload.CcYear),
361
+ CreditCardCvv: int32(payload.CcCVV)},
362
+ UserId: sessionID(r),
363
+ UserCurrency: currentCurrency(r),
364
+ Address: &pb.Address{
365
+ StreetAddress: payload.StreetAddress,
366
+ City: payload.City,
367
+ State: payload.State,
368
+ ZipCode: int32(payload.ZipCode),
369
+ Country: payload.Country},
370
+ })
371
+ if err != nil {
372
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to complete the order"), http.StatusInternalServerError)
373
+ return
374
+ }
375
+ log.WithField("order", order.GetOrder().GetOrderId()).Info("order placed")
376
+
377
+ order.GetOrder().GetItems()
378
+ recommendations, _ := fe.getRecommendations(r.Context(), sessionID(r), nil)
379
+
380
+ totalPaid := *order.GetOrder().GetShippingCost()
381
+ for _, v := range order.GetOrder().GetItems() {
382
+ multPrice := money.MultiplySlow(*v.GetCost(), uint32(v.GetItem().GetQuantity()))
383
+ totalPaid = money.Must(money.Sum(totalPaid, multPrice))
384
+ }
385
+
386
+ currencies, err := fe.getCurrencies(r.Context())
387
+ if err != nil {
388
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
389
+ return
390
+ }
391
+
392
+ if err := templates.ExecuteTemplate(w, "order", injectCommonTemplateData(r, map[string]interface{}{
393
+ "show_currency": false,
394
+ "currencies": currencies,
395
+ "order": order.GetOrder(),
396
+ "total_paid": &totalPaid,
397
+ "recommendations": recommendations,
398
+ })); err != nil {
399
+ log.Println(err)
400
+ }
401
+ }
402
+
403
+ func (fe *frontendServer) assistantHandler(w http.ResponseWriter, r *http.Request) {
404
+ currencies, err := fe.getCurrencies(r.Context())
405
+ if err != nil {
406
+ renderHTTPError(log, r, w, errors.Wrap(err, "could not retrieve currencies"), http.StatusInternalServerError)
407
+ return
408
+ }
409
+
410
+ if err := templates.ExecuteTemplate(w, "assistant", injectCommonTemplateData(r, map[string]interface{}{
411
+ "show_currency": false,
412
+ "currencies": currencies,
413
+ })); err != nil {
414
+ log.Println(err)
415
+ }
416
+ }
417
+
418
+ func (fe *frontendServer) logoutHandler(w http.ResponseWriter, r *http.Request) {
419
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
420
+ log.Debug("logging out")
421
+ for _, c := range r.Cookies() {
422
+ c.Expires = time.Now().Add(-time.Hour * 24 * 365)
423
+ c.MaxAge = -1
424
+ http.SetCookie(w, c)
425
+ }
426
+ w.Header().Set("Location", baseUrl + "/")
427
+ w.WriteHeader(http.StatusFound)
428
+ }
429
+
430
+ func (fe *frontendServer) getProductByID(w http.ResponseWriter, r *http.Request) {
431
+ id := mux.Vars(r)["ids"]
432
+ if id == "" {
433
+ return
434
+ }
435
+
436
+ p, err := fe.getProduct(r.Context(), id)
437
+ if err != nil {
438
+ return
439
+ }
440
+
441
+ jsonData, err := json.Marshal(p)
442
+ if err != nil {
443
+ fmt.Println(err)
444
+ return
445
+ }
446
+
447
+ w.Write(jsonData)
448
+ w.WriteHeader(http.StatusOK)
449
+ }
450
+
451
+ func (fe *frontendServer) chatBotHandler(w http.ResponseWriter, r *http.Request) {
452
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
453
+ type Response struct {
454
+ Message string `json:"message"`
455
+ }
456
+
457
+ type LLMResponse struct {
458
+ Content string `json:"content"`
459
+ Details map[string]any `json:"details"`
460
+ }
461
+
462
+ var response LLMResponse
463
+
464
+ url := "http://" + fe.shoppingAssistantSvcAddr
465
+ req, err := http.NewRequest(http.MethodPost, url, r.Body)
466
+ if err != nil {
467
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to create request"), http.StatusInternalServerError)
468
+ return
469
+ }
470
+ req.Header.Set("Content-Type", "application/json")
471
+ req.Header.Set("Accept", "application/json")
472
+ res, err := http.DefaultClient.Do(req)
473
+ if err != nil {
474
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to send request"), http.StatusInternalServerError)
475
+ return
476
+ }
477
+
478
+ body, err := io.ReadAll(res.Body)
479
+ if err != nil {
480
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to read response"), http.StatusInternalServerError)
481
+ return
482
+ }
483
+
484
+ fmt.Printf("%+v\n", body)
485
+ fmt.Printf("%+v\n", res)
486
+
487
+ err = json.Unmarshal(body, &response)
488
+ if err != nil {
489
+ renderHTTPError(log, r, w, errors.Wrap(err, "failed to unmarshal body"), http.StatusInternalServerError)
490
+ return
491
+ }
492
+
493
+ // respond with the same message
494
+ json.NewEncoder(w).Encode(Response{Message: response.Content})
495
+
496
+ w.WriteHeader(http.StatusOK)
497
+ }
498
+
499
+ func (fe *frontendServer) setCurrencyHandler(w http.ResponseWriter, r *http.Request) {
500
+ log := r.Context().Value(ctxKeyLog{}).(logrus.FieldLogger)
501
+ cur := r.FormValue("currency_code")
502
+ payload := validator.SetCurrencyPayload{Currency: cur}
503
+ if err := payload.Validate(); err != nil {
504
+ renderHTTPError(log, r, w, validator.ValidationErrorResponse(err), http.StatusUnprocessableEntity)
505
+ return
506
+ }
507
+ log.WithField("curr.new", payload.Currency).WithField("curr.old", currentCurrency(r)).
508
+ Debug("setting currency")
509
+
510
+ if payload.Currency != "" {
511
+ http.SetCookie(w, &http.Cookie{
512
+ Name: cookieCurrency,
513
+ Value: payload.Currency,
514
+ MaxAge: cookieMaxAge,
515
+ })
516
+ }
517
+ referer := r.Header.Get("referer")
518
+ if referer == "" {
519
+ referer = baseUrl + "/"
520
+ }
521
+ w.Header().Set("Location", referer)
522
+ w.WriteHeader(http.StatusFound)
523
+ }
524
+
525
+ // chooseAd queries for advertisements available and randomly chooses one, if
526
+ // available. It ignores the error retrieving the ad since it is not critical.
527
+ func (fe *frontendServer) chooseAd(ctx context.Context, ctxKeys []string, log logrus.FieldLogger) *pb.Ad {
528
+ ads, err := fe.getAd(ctx, ctxKeys)
529
+ if err != nil {
530
+ log.WithField("error", err).Warn("failed to retrieve ads")
531
+ return nil
532
+ }
533
+ return ads[rand.Intn(len(ads))]
534
+ }
535
+
536
+ func renderHTTPError(log logrus.FieldLogger, r *http.Request, w http.ResponseWriter, err error, code int) {
537
+ log.WithField("error", err).Error("request error")
538
+ errMsg := fmt.Sprintf("%+v", err)
539
+
540
+ w.WriteHeader(code)
541
+
542
+ if templateErr := templates.ExecuteTemplate(w, "error", injectCommonTemplateData(r, map[string]interface{}{
543
+ "error": errMsg,
544
+ "status_code": code,
545
+ "status": http.StatusText(code),
546
+ })); templateErr != nil {
547
+ log.Println(templateErr)
548
+ }
549
+ }
550
+
551
+ func injectCommonTemplateData(r *http.Request, payload map[string]interface{}) map[string]interface{} {
552
+ data := map[string]interface{}{
553
+ "session_id": sessionID(r),
554
+ "request_id": r.Context().Value(ctxKeyRequestID{}),
555
+ "user_currency": currentCurrency(r),
556
+ "platform_css": plat.css,
557
+ "platform_name": plat.provider,
558
+ "is_cymbal_brand": isCymbalBrand,
559
+ "assistant_enabled": assistantEnabled,
560
+ "deploymentDetails": deploymentDetailsMap,
561
+ "frontendMessage": frontendMessage,
562
+ "currentYear": time.Now().Year(),
563
+ "baseUrl": baseUrl,
564
+ }
565
+
566
+ for k, v := range payload {
567
+ data[k] = v
568
+ }
569
+
570
+ return data
571
+ }
572
+
573
+ func currentCurrency(r *http.Request) string {
574
+ c, _ := r.Cookie(cookieCurrency)
575
+ if c != nil {
576
+ return c.Value
577
+ }
578
+ return defaultCurrency
579
+ }
580
+
581
+ func sessionID(r *http.Request) string {
582
+ v := r.Context().Value(ctxKeySessionID{})
583
+ if v != nil {
584
+ return v.(string)
585
+ }
586
+ return ""
587
+ }
588
+
589
+ func cartIDs(c []*pb.CartItem) []string {
590
+ out := make([]string, len(c))
591
+ for i, v := range c {
592
+ out[i] = v.GetProductId()
593
+ }
594
+ return out
595
+ }
596
+
597
+ // get total # of items in cart
598
+ func cartSize(c []*pb.CartItem) int {
599
+ cartSize := 0
600
+ for _, item := range c {
601
+ cartSize += int(item.GetQuantity())
602
+ }
603
+ return cartSize
604
+ }
605
+
606
+ func renderMoney(money pb.Money) string {
607
+ currencyLogo := renderCurrencyLogo(money.GetCurrencyCode())
608
+ return fmt.Sprintf("%s%d.%02d", currencyLogo, money.GetUnits(), money.GetNanos()/10000000)
609
+ }
610
+
611
+ func renderCurrencyLogo(currencyCode string) string {
612
+ logos := map[string]string{
613
+ "USD": "$",
614
+ "CAD": "$",
615
+ "JPY": "¥",
616
+ "EUR": "€",
617
+ "TRY": "₺",
618
+ "GBP": "£",
619
+ }
620
+
621
+ logo := "$" //default
622
+ if val, ok := logos[currencyCode]; ok {
623
+ logo = val
624
+ }
625
+ return logo
626
+ }
627
+
628
+ func stringinSlice(slice []string, val string) bool {
629
+ for _, item := range slice {
630
+ if item == val {
631
+ return true
632
+ }
633
+ }
634
+ return false
635
+ }
benchmark/boutique/runtime/29/code/frontend/main.go ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "fmt"
20
+ "net/http"
21
+ "os"
22
+ "time"
23
+
24
+ "cloud.google.com/go/profiler"
25
+ "github.com/gorilla/mux"
26
+ "github.com/pkg/errors"
27
+ "github.com/sirupsen/logrus"
28
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
29
+ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
30
+ "go.opentelemetry.io/otel"
31
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
32
+ "go.opentelemetry.io/otel/propagation"
33
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
34
+ "google.golang.org/grpc"
35
+ "google.golang.org/grpc/credentials/insecure"
36
+ )
37
+
38
+ const (
39
+ port = "8080"
40
+ defaultCurrency = "USD"
41
+ cookieMaxAge = 60 * 60 * 48
42
+
43
+ cookiePrefix = "shop_"
44
+ cookieSessionID = cookiePrefix + "session-id"
45
+ cookieCurrency = cookiePrefix + "currency"
46
+ )
47
+
48
+ var (
49
+ whitelistedCurrencies = map[string]bool{
50
+ "USD": true,
51
+ "EUR": true,
52
+ "CAD": true,
53
+ "JPY": true,
54
+ "GBP": true,
55
+ "TRY": true,
56
+ }
57
+
58
+ baseUrl = ""
59
+ )
60
+
61
+ type ctxKeySessionID struct{}
62
+
63
+ type frontendServer struct {
64
+ productCatalogSvcAddr string
65
+ productCatalogSvcConn *grpc.ClientConn
66
+
67
+ currencySvcAddr string
68
+ currencySvcConn *grpc.ClientConn
69
+
70
+ cartSvcAddr string
71
+ cartSvcConn *grpc.ClientConn
72
+
73
+ recommendationSvcAddr string
74
+ recommendationSvcConn *grpc.ClientConn
75
+
76
+ checkoutSvcAddr string
77
+ checkoutSvcConn *grpc.ClientConn
78
+
79
+ shippingSvcAddr string
80
+ shippingSvcConn *grpc.ClientConn
81
+
82
+ adSvcAddr string
83
+ adSvcConn *grpc.ClientConn
84
+
85
+ collectorAddr string
86
+ collectorConn *grpc.ClientConn
87
+
88
+ shoppingAssistantSvcAddr string
89
+ }
90
+
91
+ func main() {
92
+ ctx := context.Background()
93
+ log := logrus.New()
94
+ log.Level = logrus.DebugLevel
95
+ log.Formatter = &logrus.JSONFormatter{
96
+ FieldMap: logrus.FieldMap{
97
+ logrus.FieldKeyTime: "timestamp",
98
+ logrus.FieldKeyLevel: "severity",
99
+ logrus.FieldKeyMsg: "message",
100
+ },
101
+ TimestampFormat: time.RFC3339Nano,
102
+ }
103
+ log.Out = os.Stdout
104
+
105
+ svc := new(frontendServer)
106
+
107
+ otel.SetTextMapPropagator(
108
+ propagation.NewCompositeTextMapPropagator(
109
+ propagation.TraceContext{}, propagation.Baggage{}))
110
+
111
+ baseUrl = os.Getenv("BASE_URL")
112
+
113
+ if os.Getenv("ENABLE_TRACING") == "1" {
114
+ log.Info("Tracing enabled.")
115
+ initTracing(log, ctx, svc)
116
+ } else {
117
+ log.Info("Tracing disabled.")
118
+ }
119
+
120
+ if os.Getenv("ENABLE_PROFILER") == "1" {
121
+ log.Info("Profiling enabled.")
122
+ go initProfiling(log, "frontend", "1.0.0")
123
+ } else {
124
+ log.Info("Profiling disabled.")
125
+ }
126
+
127
+ srvPort := port
128
+ if os.Getenv("PORT") != "" {
129
+ srvPort = os.Getenv("PORT")
130
+ }
131
+ addr := os.Getenv("LISTEN_ADDR")
132
+ mustMapEnv(&svc.productCatalogSvcAddr, "PRODUCT_CATALOG_SERVICE_ADDR")
133
+ mustMapEnv(&svc.currencySvcAddr, "CURRENCY_SERVICE_ADDR")
134
+ mustMapEnv(&svc.cartSvcAddr, "CART_SERVICE_ADDR")
135
+ mustMapEnv(&svc.recommendationSvcAddr, "RECOMMENDATION_SERVICE_ADDR")
136
+ mustMapEnv(&svc.checkoutSvcAddr, "CHECKOUT_SERVICE_ADDR")
137
+ mustMapEnv(&svc.shippingSvcAddr, "SHIPPING_SERVICE_ADDR")
138
+ mustMapEnv(&svc.adSvcAddr, "AD_SERVICE_ADDR")
139
+ mustMapEnv(&svc.shoppingAssistantSvcAddr, "SHOPPING_ASSISTANT_SERVICE_ADDR")
140
+
141
+ mustConnGRPC(ctx, &svc.currencySvcConn, svc.currencySvcAddr)
142
+ mustConnGRPC(ctx, &svc.productCatalogSvcConn, svc.productCatalogSvcAddr)
143
+ mustConnGRPC(ctx, &svc.cartSvcConn, svc.cartSvcAddr)
144
+ mustConnGRPC(ctx, &svc.recommendationSvcConn, svc.recommendationSvcAddr)
145
+ mustConnGRPC(ctx, &svc.shippingSvcConn, svc.shippingSvcAddr)
146
+ mustConnGRPC(ctx, &svc.checkoutSvcConn, svc.checkoutSvcAddr)
147
+ mustConnGRPC(ctx, &svc.adSvcConn, svc.adSvcAddr)
148
+
149
+ r := mux.NewRouter()
150
+ r.HandleFunc(baseUrl+"/", svc.homeHandler).Methods(http.MethodGet, http.MethodHead)
151
+ r.HandleFunc(baseUrl+"/product/{id}", svc.productHandler).Methods(http.MethodGet, http.MethodHead)
152
+ r.HandleFunc(baseUrl+"/cart", svc.viewCartHandler).Methods(http.MethodGet, http.MethodHead)
153
+ r.HandleFunc(baseUrl+"/cart", svc.addToCartHandler).Methods(http.MethodPost)
154
+ r.HandleFunc(baseUrl+"/cart/empty", svc.emptyCartHandler).Methods(http.MethodPost)
155
+ r.HandleFunc(baseUrl+"/setCurrency", svc.setCurrencyHandler).Methods(http.MethodPost)
156
+ r.HandleFunc(baseUrl+"/logout", svc.logoutHandler).Methods(http.MethodGet)
157
+ r.HandleFunc(baseUrl+"/cart/checkout", svc.placeOrderHandler).Methods(http.MethodPost)
158
+ r.HandleFunc(baseUrl+"/assistant", svc.assistantHandler).Methods(http.MethodGet)
159
+ r.PathPrefix(baseUrl + "/static/").Handler(http.StripPrefix(baseUrl+"/static/", http.FileServer(http.Dir("./static/"))))
160
+ r.HandleFunc(baseUrl+"/robots.txt", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "User-agent: *\nDisallow: /") })
161
+ r.HandleFunc(baseUrl+"/_healthz", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "ok") })
162
+ r.HandleFunc(baseUrl+"/product-meta/{ids}", svc.getProductByID).Methods(http.MethodGet)
163
+ r.HandleFunc(baseUrl+"/bot", svc.chatBotHandler).Methods(http.MethodPost)
164
+
165
+ var handler http.Handler = r
166
+ handler = &logHandler{log: log, next: handler} // add logging
167
+ handler = ensureSessionID(handler) // add session ID
168
+ handler = otelhttp.NewHandler(handler, "frontend") // add OTel tracing
169
+
170
+ log.Infof("starting server on %s:%s", addr, srvPort)
171
+ log.Fatal(http.ListenAndServe(addr+":"+srvPort, handler))
172
+ }
173
+ func initStats(log logrus.FieldLogger) {
174
+ // TODO(arbrown) Implement OpenTelemtry stats
175
+ }
176
+
177
+ func initTracing(log logrus.FieldLogger, ctx context.Context, svc *frontendServer) (*sdktrace.TracerProvider, error) {
178
+ mustMapEnv(&svc.collectorAddr, "COLLECTOR_SERVICE_ADDR")
179
+ mustConnGRPC(ctx, &svc.collectorConn, svc.collectorAddr)
180
+ exporter, err := otlptracegrpc.New(
181
+ ctx,
182
+ otlptracegrpc.WithGRPCConn(svc.collectorConn))
183
+ if err != nil {
184
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
185
+ }
186
+ tp := sdktrace.NewTracerProvider(
187
+ sdktrace.WithBatcher(exporter),
188
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
189
+ otel.SetTracerProvider(tp)
190
+
191
+ return tp, err
192
+ }
193
+
194
+ func initProfiling(log logrus.FieldLogger, service, version string) {
195
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
196
+ // since they are not sharing packages.
197
+ for i := 1; i <= 3; i++ {
198
+ log = log.WithField("retry", i)
199
+ if err := profiler.Start(profiler.Config{
200
+ Service: service,
201
+ ServiceVersion: version,
202
+ // ProjectID must be set if not running on GCP.
203
+ // ProjectID: "my-project",
204
+ }); err != nil {
205
+ log.Warnf("warn: failed to start profiler: %+v", err)
206
+ } else {
207
+ log.Info("started Stackdriver profiler")
208
+ return
209
+ }
210
+ d := time.Second * 10 * time.Duration(i)
211
+ log.Debugf("sleeping %v to retry initializing Stackdriver profiler", d)
212
+ time.Sleep(d)
213
+ }
214
+ log.Warn("warning: could not initialize Stackdriver profiler after retrying, giving up")
215
+ }
216
+
217
+ func mustMapEnv(target *string, envKey string) {
218
+ v := os.Getenv(envKey)
219
+ if v == "" {
220
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
221
+ }
222
+ *target = v
223
+ }
224
+
225
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
226
+ var err error
227
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
228
+ defer cancel()
229
+ *conn, err = grpc.NewClient(addr,
230
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
231
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
232
+ if err != nil {
233
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
234
+ }
235
+ }
benchmark/boutique/runtime/29/code/frontend/middleware.go ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "net/http"
20
+ "time"
21
+ "os"
22
+
23
+ "github.com/google/uuid"
24
+ "github.com/sirupsen/logrus"
25
+ )
26
+
27
+ type ctxKeyLog struct{}
28
+ type ctxKeyRequestID struct{}
29
+
30
+ type logHandler struct {
31
+ log *logrus.Logger
32
+ next http.Handler
33
+ }
34
+
35
+ type responseRecorder struct {
36
+ b int
37
+ status int
38
+ w http.ResponseWriter
39
+ }
40
+
41
+ func (r *responseRecorder) Header() http.Header { return r.w.Header() }
42
+
43
+ func (r *responseRecorder) Write(p []byte) (int, error) {
44
+ if r.status == 0 {
45
+ r.status = http.StatusOK
46
+ }
47
+ n, err := r.w.Write(p)
48
+ r.b += n
49
+ return n, err
50
+ }
51
+
52
+ func (r *responseRecorder) WriteHeader(statusCode int) {
53
+ r.status = statusCode
54
+ r.w.WriteHeader(statusCode)
55
+ }
56
+
57
+ func (lh *logHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
58
+ ctx := r.Context()
59
+ requestID, _ := uuid.NewRandom()
60
+ ctx = context.WithValue(ctx, ctxKeyRequestID{}, requestID.String())
61
+
62
+ start := time.Now()
63
+ rr := &responseRecorder{w: w}
64
+ log := lh.log.WithFields(logrus.Fields{
65
+ "http.req.path": r.URL.Path,
66
+ "http.req.method": r.Method,
67
+ "http.req.id": requestID.String(),
68
+ })
69
+ if v, ok := r.Context().Value(ctxKeySessionID{}).(string); ok {
70
+ log = log.WithField("session", v)
71
+ }
72
+ log.Debug("request started")
73
+ defer func() {
74
+ log.WithFields(logrus.Fields{
75
+ "http.resp.took_ms": int64(time.Since(start) / time.Millisecond),
76
+ "http.resp.status": rr.status,
77
+ "http.resp.bytes": rr.b}).Debugf("request complete")
78
+ }()
79
+
80
+ ctx = context.WithValue(ctx, ctxKeyLog{}, log)
81
+ r = r.WithContext(ctx)
82
+ lh.next.ServeHTTP(rr, r)
83
+ }
84
+
85
+ func ensureSessionID(next http.Handler) http.HandlerFunc {
86
+ return func(w http.ResponseWriter, r *http.Request) {
87
+ var sessionID string
88
+ c, err := r.Cookie(cookieSessionID)
89
+ if err == http.ErrNoCookie {
90
+ if os.Getenv("ENABLE_SINGLE_SHARED_SESSION") == "true" {
91
+ // Hard coded user id, shared across sessions
92
+ sessionID = "12345678-1234-1234-1234-123456789123"
93
+ } else {
94
+ u, _ := uuid.NewRandom()
95
+ sessionID = u.String()
96
+ }
97
+ http.SetCookie(w, &http.Cookie{
98
+ Name: cookieSessionID,
99
+ Value: sessionID,
100
+ MaxAge: cookieMaxAge,
101
+ })
102
+ } else if err != nil {
103
+ return
104
+ } else {
105
+ sessionID = c.Value
106
+ }
107
+ ctx := context.WithValue(r.Context(), ctxKeySessionID{}, sessionID)
108
+ r = r.WithContext(ctx)
109
+ next.ServeHTTP(w, r)
110
+ }
111
+ }
benchmark/boutique/runtime/29/code/frontend/money/money.go ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package money
16
+
17
+ import (
18
+ "errors"
19
+
20
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/genproto"
21
+ )
22
+
23
+ const (
24
+ nanosMin = -999999999
25
+ nanosMax = +999999999
26
+ nanosMod = 1000000000
27
+ )
28
+
29
+ var (
30
+ ErrInvalidValue = errors.New("one of the specified money values is invalid")
31
+ ErrMismatchingCurrency = errors.New("mismatching currency codes")
32
+ )
33
+
34
+ // IsValid checks if specified value has a valid units/nanos signs and ranges.
35
+ func IsValid(m pb.Money) bool {
36
+ return signMatches(m) && validNanos(m.GetNanos())
37
+ }
38
+
39
+ func signMatches(m pb.Money) bool {
40
+ return m.GetNanos() == 0 || m.GetUnits() == 0 || (m.GetNanos() < 0) == (m.GetUnits() < 0)
41
+ }
42
+
43
+ func validNanos(nanos int32) bool { return nanosMin <= nanos && nanos <= nanosMax }
44
+
45
+ // IsZero returns true if the specified money value is equal to zero.
46
+ func IsZero(m pb.Money) bool { return m.GetUnits() == 0 && m.GetNanos() == 0 }
47
+
48
+ // IsPositive returns true if the specified money value is valid and is
49
+ // positive.
50
+ func IsPositive(m pb.Money) bool {
51
+ return IsValid(m) && m.GetUnits() > 0 || (m.GetUnits() == 0 && m.GetNanos() > 0)
52
+ }
53
+
54
+ // IsNegative returns true if the specified money value is valid and is
55
+ // negative.
56
+ func IsNegative(m pb.Money) bool {
57
+ return IsValid(m) && m.GetUnits() < 0 || (m.GetUnits() == 0 && m.GetNanos() < 0)
58
+ }
59
+
60
+ // AreSameCurrency returns true if values l and r have a currency code and
61
+ // they are the same values.
62
+ func AreSameCurrency(l, r pb.Money) bool {
63
+ return l.GetCurrencyCode() == r.GetCurrencyCode() && l.GetCurrencyCode() != ""
64
+ }
65
+
66
+ // AreEquals returns true if values l and r are the equal, including the
67
+ // currency. This does not check validity of the provided values.
68
+ func AreEquals(l, r pb.Money) bool {
69
+ return l.GetCurrencyCode() == r.GetCurrencyCode() &&
70
+ l.GetUnits() == r.GetUnits() && l.GetNanos() == r.GetNanos()
71
+ }
72
+
73
+ // Negate returns the same amount with the sign negated.
74
+ func Negate(m pb.Money) pb.Money {
75
+ return pb.Money{
76
+ Units: -m.GetUnits(),
77
+ Nanos: -m.GetNanos(),
78
+ CurrencyCode: m.GetCurrencyCode()}
79
+ }
80
+
81
+ // Must panics if the given error is not nil. This can be used with other
82
+ // functions like: "m := Must(Sum(a,b))".
83
+ func Must(v pb.Money, err error) pb.Money {
84
+ if err != nil {
85
+ panic(err)
86
+ }
87
+ return v
88
+ }
89
+
90
+ // Sum adds two values. Returns an error if one of the values are invalid or
91
+ // currency codes are not matching (unless currency code is unspecified for
92
+ // both).
93
+ func Sum(l, r pb.Money) (pb.Money, error) {
94
+ if !IsValid(l) || !IsValid(r) {
95
+ return pb.Money{}, ErrInvalidValue
96
+ } else if l.GetCurrencyCode() != r.GetCurrencyCode() {
97
+ return pb.Money{}, ErrMismatchingCurrency
98
+ }
99
+ units := l.GetUnits() + r.GetUnits()
100
+ nanos := l.GetNanos() + r.GetNanos()
101
+
102
+ if (units == 0 && nanos == 0) || (units > 0 && nanos >= 0) || (units < 0 && nanos <= 0) {
103
+ // same sign <units, nanos>
104
+ units += int64(nanos / nanosMod)
105
+ nanos = nanos % nanosMod
106
+ } else {
107
+ // different sign. nanos guaranteed to not to go over the limit
108
+ if units > 0 {
109
+ units--
110
+ nanos += nanosMod
111
+ } else {
112
+ units++
113
+ nanos -= nanosMod
114
+ }
115
+ }
116
+
117
+ return pb.Money{
118
+ Units: units,
119
+ Nanos: nanos,
120
+ CurrencyCode: l.GetCurrencyCode()}, nil
121
+ }
122
+
123
+ // MultiplySlow is a slow multiplication operation done through adding the value
124
+ // to itself n-1 times.
125
+ func MultiplySlow(m pb.Money, n uint32) pb.Money {
126
+ out := m
127
+ for n > 1 {
128
+ out = Must(Sum(out, m))
129
+ n--
130
+ }
131
+ return out
132
+ }
benchmark/boutique/runtime/29/code/frontend/packaging_info.go ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "encoding/json"
19
+ "fmt"
20
+ "io/ioutil"
21
+ "net/http"
22
+ "os"
23
+ )
24
+
25
+ /*
26
+ As part of an optional Google Cloud demo, you can run an additional "packaging" microservice (HTTP server).
27
+ This file contains code related to the frontend and the "packaging" microservice.
28
+ */
29
+
30
+ var (
31
+ packagingServiceUrl string
32
+ )
33
+
34
+ type PackagingInfo struct {
35
+ Weight float32 `json:"weight"`
36
+ Width float32 `json:"width"`
37
+ Height float32 `json:"height"`
38
+ Depth float32 `json:"depth"`
39
+ }
40
+
41
+ // init() is a special function in Golang that will run when this package is imported.
42
+ func init() {
43
+ packagingServiceUrl = os.Getenv("PACKAGING_SERVICE_URL")
44
+ }
45
+
46
+ func isPackagingServiceConfigured() bool {
47
+ return packagingServiceUrl != ""
48
+ }
49
+
50
+ func httpGetPackagingInfo(productId string) (*PackagingInfo, error) {
51
+ // Make the GET request
52
+ url := packagingServiceUrl + "/" + productId
53
+ fmt.Println("Requesting packaging info from URL: ", url)
54
+ resp, err := http.Get(url)
55
+ if err != nil {
56
+ return nil, err
57
+ }
58
+ defer resp.Body.Close()
59
+
60
+ // Check the response status code
61
+ if resp.StatusCode != http.StatusOK {
62
+ return nil, fmt.Errorf("Unexpected status code: %d", resp.StatusCode)
63
+ }
64
+
65
+ // Read the JSON response body
66
+ responseBody, err := ioutil.ReadAll(resp.Body)
67
+ if err != nil {
68
+ return nil, err
69
+ }
70
+
71
+ // Decode the JSON response into a PackagingInfo struct
72
+ var packagingInfo PackagingInfo
73
+ err = json.Unmarshal(responseBody, &packagingInfo)
74
+ if err != nil {
75
+ return nil, err
76
+ }
77
+
78
+ return &packagingInfo, nil
79
+ }
benchmark/boutique/runtime/29/code/frontend/rpc.go ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "time"
20
+
21
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/frontend/genproto"
22
+
23
+ "github.com/pkg/errors"
24
+ )
25
+
26
+ const (
27
+ avoidNoopCurrencyConversionRPC = false
28
+ )
29
+
30
+ func (fe *frontendServer) getCurrencies(ctx context.Context) ([]string, error) {
31
+ currs, err := pb.NewCurrencyServiceClient(fe.currencySvcConn).
32
+ GetSupportedCurrencies(ctx, &pb.Empty{})
33
+ if err != nil {
34
+ return nil, err
35
+ }
36
+ var out []string
37
+ for _, c := range currs.CurrencyCodes {
38
+ if _, ok := whitelistedCurrencies[c]; ok {
39
+ out = append(out, c)
40
+ }
41
+ }
42
+ return out, nil
43
+ }
44
+
45
+ func (fe *frontendServer) getProducts(ctx context.Context) ([]*pb.Product, error) {
46
+ resp, err := pb.NewProductCatalogServiceClient(fe.productCatalogSvcConn).
47
+ ListProducts(ctx, &pb.Empty{})
48
+ return resp.GetProducts(), err
49
+ }
50
+
51
+ func (fe *frontendServer) getProduct(ctx context.Context, id string) (*pb.Product, error) {
52
+ resp, err := pb.NewProductCatalogServiceClient(fe.productCatalogSvcConn).
53
+ GetProduct(ctx, &pb.GetProductRequest{Id: id})
54
+ return resp, err
55
+ }
56
+
57
+ func (fe *frontendServer) getCart(ctx context.Context, userID string) ([]*pb.CartItem, error) {
58
+ resp, err := pb.NewCartServiceClient(fe.cartSvcConn).GetCart(ctx, &pb.GetCartRequest{UserId: userID})
59
+ return resp.GetItems(), err
60
+ }
61
+
62
+ func (fe *frontendServer) emptyCart(ctx context.Context, userID string) error {
63
+ _, err := pb.NewCartServiceClient(fe.cartSvcConn).EmptyCart(ctx, &pb.EmptyCartRequest{UserId: userID})
64
+ return err
65
+ }
66
+
67
+ func (fe *frontendServer) insertCart(ctx context.Context, userID, productID string, quantity int32) error {
68
+ _, err := pb.NewCartServiceClient(fe.cartSvcConn).AddItem(ctx, &pb.AddItemRequest{
69
+ UserId: userID,
70
+ Item: &pb.CartItem{
71
+ ProductId: productID,
72
+ Quantity: quantity},
73
+ })
74
+ return err
75
+ }
76
+
77
+ func (fe *frontendServer) convertCurrency(ctx context.Context, money *pb.Money, currency string) (*pb.Money, error) {
78
+ if avoidNoopCurrencyConversionRPC && money.GetCurrencyCode() == currency {
79
+ return money, nil
80
+ }
81
+ return pb.NewCurrencyServiceClient(fe.currencySvcConn).
82
+ Convert(ctx, &pb.CurrencyConversionRequest{
83
+ From: money,
84
+ ToCode: currency})
85
+ }
86
+
87
+ func (fe *frontendServer) getShippingQuote(ctx context.Context, items []*pb.CartItem, currency string) (*pb.Money, error) {
88
+ quote, err := pb.NewShippingServiceClient(fe.shippingSvcConn).GetQuote(ctx,
89
+ &pb.GetQuoteRequest{
90
+ Address: nil,
91
+ Items: items})
92
+ if err != nil {
93
+ return nil, err
94
+ }
95
+ localized, err := fe.convertCurrency(ctx, quote.GetCostUsd(), currency)
96
+ return localized, errors.Wrap(err, "failed to convert currency for shipping cost")
97
+ }
98
+
99
+ func (fe *frontendServer) getRecommendations(ctx context.Context, userID string, productIDs []string) ([]*pb.Product, error) {
100
+ resp, err := pb.NewRecommendationServiceClient(fe.recommendationSvcConn).ListRecommendations(ctx,
101
+ &pb.ListRecommendationsRequest{UserId: userID, ProductIds: productIDs})
102
+ if err != nil {
103
+ return nil, err
104
+ }
105
+ out := make([]*pb.Product, len(resp.GetProductIds()))
106
+ for i, v := range resp.GetProductIds() {
107
+ p, err := fe.getProduct(ctx, v)
108
+ if err != nil {
109
+ return nil, errors.Wrapf(err, "failed to get recommended product info (#%s)", v)
110
+ }
111
+ out[i] = p
112
+ }
113
+ if len(out) > 4 {
114
+ out = out[:4] // take only first four to fit the UI
115
+ }
116
+ return out, err
117
+ }
118
+
119
+ func (fe *frontendServer) getAd(ctx context.Context, ctxKeys []string) ([]*pb.Ad, error) {
120
+ ctx, cancel := context.WithTimeout(ctx, time.Millisecond*100)
121
+ defer cancel()
122
+
123
+ resp, err := pb.NewAdServiceClient(fe.adSvcConn).GetAds(ctx, &pb.AdRequest{
124
+ ContextKeys: ctxKeys,
125
+ })
126
+ return resp.GetAds(), errors.Wrap(err, "failed to get ads")
127
+ }
benchmark/boutique/runtime/29/code/frontend/validator/validator.go ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package validator
16
+
17
+ import (
18
+ "errors"
19
+ "fmt"
20
+
21
+ "github.com/go-playground/validator/v10"
22
+ )
23
+
24
+ var validate *validator.Validate
25
+
26
+ // init() is a special function that will run when this package is imported.
27
+ // It instantiates a SINGLE instance of *validator.Validate with the added
28
+ // benefit of caching struct info and validations.
29
+ func init() {
30
+ validate = validator.New(validator.WithRequiredStructEnabled())
31
+ }
32
+
33
+ type Payload interface {
34
+ Validate() error
35
+ }
36
+
37
+ type AddToCartPayload struct {
38
+ Quantity uint64 `validate:"required,gte=1,lte=10"`
39
+ ProductID string `validate:"required"`
40
+ }
41
+
42
+ type PlaceOrderPayload struct {
43
+ Email string `validate:"required,email"`
44
+ StreetAddress string `validate:"required,max=512"`
45
+ ZipCode int64 `validate:"required"`
46
+ City string `validate:"required,max=128"`
47
+ State string `validate:"required,max=128"`
48
+ Country string `validate:"required,max=128"`
49
+ CcNumber string `validate:"required,credit_card"`
50
+ CcMonth int64 `validate:"required,gte=1,lte=12"`
51
+ CcYear int64 `validate:"required"`
52
+ CcCVV int64 `validate:"required"`
53
+ }
54
+
55
+ type SetCurrencyPayload struct {
56
+ Currency string `validate:"required,iso4217"`
57
+ }
58
+
59
+ // Implementations of the 'Payload' interface.
60
+ func (ad *AddToCartPayload) Validate() error {
61
+ return validate.Struct(ad)
62
+ }
63
+
64
+ func (po *PlaceOrderPayload) Validate() error {
65
+ return validate.Struct(po)
66
+ }
67
+
68
+ func (sc *SetCurrencyPayload) Validate() error {
69
+ return validate.Struct(sc)
70
+ }
71
+
72
+ // Reusable error response function.
73
+ func ValidationErrorResponse(err error) error {
74
+ validationErrs, ok := err.(validator.ValidationErrors)
75
+ if !ok {
76
+ return errors.New("invalid validation error format")
77
+ }
78
+ var msg string
79
+ for _, err := range validationErrs {
80
+ msg += fmt.Sprintf("Field '%s' is invalid: %s\n", err.Field(), err.Tag())
81
+ }
82
+ return fmt.Errorf("%s", msg)
83
+ }
benchmark/boutique/runtime/29/code/paymentservice/charge.js ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const cardValidator = require('simple-card-validator');
16
+ const { v4: uuidv4 } = require('uuid');
17
+ const pino = require('pino');
18
+
19
+ const logger = pino({
20
+ name: 'paymentservice-charge',
21
+ messageKey: 'message',
22
+ formatters: {
23
+ level (logLevelString, logLevelNum) {
24
+ return { severity: logLevelString }
25
+ }
26
+ }
27
+ });
28
+
29
+
30
+ class CreditCardError extends Error {
31
+ constructor (message) {
32
+ super(message);
33
+ this.code = 400; // Invalid argument error
34
+ }
35
+ }
36
+
37
+ class InvalidCreditCard extends CreditCardError {
38
+ constructor (cardType) {
39
+ super(`Credit card info is invalid`);
40
+ }
41
+ }
42
+
43
+ class UnacceptedCreditCard extends CreditCardError {
44
+ constructor (cardType) {
45
+ super(`Sorry, we cannot process ${cardType} credit cards. Only VISA or MasterCard is accepted.`);
46
+ }
47
+ }
48
+
49
+ class ExpiredCreditCard extends CreditCardError {
50
+ constructor (number, month, year) {
51
+ super(`Your credit card (ending ${number.substr(-4)}) expired on ${month}/${year}`);
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Verifies the credit card number and (pretend) charges the card.
57
+ *
58
+ * @param {*} request
59
+ * @return transaction_id - a random uuid.
60
+ */
61
+ module.exports = function charge (request) {
62
+ const { amount, credit_card: creditCard } = request;
63
+ const cardNumber = creditCard.credit_card_number;
64
+ const cardInfo = cardValidator(cardNumber);
65
+ const {
66
+ card_type: cardType,
67
+ valid
68
+ } = cardInfo.getCardDetails();
69
+
70
+ if (!valid) { throw new InvalidCreditCard(); }
71
+
72
+ // Only VISA and mastercard is accepted, other card types (AMEX, dinersclub) will
73
+ // throw UnacceptedCreditCard error.
74
+ if (!(cardType === 'visa' || cardType === 'mastercard')) { throw new UnacceptedCreditCard(cardType); }
75
+
76
+ // Also validate expiration is > today.
77
+ const currentMonth = new Date().getMonth() + 1;
78
+ const currentYear = new Date().getFullYear();
79
+ const { credit_card_expiration_year: year, credit_card_expiration_month: month } = creditCard;
80
+ if ((currentYear * 12 + currentMonth) > (year * 12 + month)) { throw new ExpiredCreditCard(cardNumber.replace('-', ''), month, year); }
81
+
82
+ logger.info(`Transaction processed: ${cardType} ending ${cardNumber.substr(-4)} \
83
+ Amount: ${amount.currency_code}${amount.units}.${amount.nanos}`);
84
+
85
+ return { transaction_id: uuidv4() };
86
+ };
benchmark/boutique/runtime/29/code/paymentservice/index.js ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2018 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const logger = require('./logger')
20
+
21
+ if (process.env.DISABLE_PROFILER) {
22
+ logger.info("Profiler disabled.")
23
+ } else {
24
+ logger.info("Profiler enabled.")
25
+ require('@google-cloud/profiler').start({
26
+ serviceContext: {
27
+ service: 'paymentservice',
28
+ version: '1.0.0'
29
+ }
30
+ });
31
+ }
32
+
33
+
34
+ if (process.env.ENABLE_TRACING == "1") {
35
+ logger.info("Tracing enabled.")
36
+
37
+ const { resourceFromAttributes } = require('@opentelemetry/resources');
38
+
39
+ const { ATTR_SERVICE_NAME }= require('@opentelemetry/semantic-conventions');
40
+
41
+ const { GrpcInstrumentation } = require('@opentelemetry/instrumentation-grpc');
42
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
43
+ const opentelemetry = require('@opentelemetry/sdk-node');
44
+
45
+ const { OTLPTraceExporter } = require('@opentelemetry/exporter-otlp-grpc');
46
+
47
+ const collectorUrl = process.env.COLLECTOR_SERVICE_ADDR;
48
+ const traceExporter = new OTLPTraceExporter({url: collectorUrl});
49
+
50
+ const sdk = new opentelemetry.NodeSDK({
51
+ resource: resourceFromAttributes({
52
+ [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'paymentservice',
53
+ }),
54
+ traceExporter: traceExporter,
55
+ });
56
+
57
+ registerInstrumentations({
58
+ instrumentations: [new GrpcInstrumentation()]
59
+ });
60
+
61
+ sdk.start()
62
+ } else {
63
+ logger.info("Tracing disabled.")
64
+ }
65
+
66
+
67
+ const path = require('path');
68
+ const HipsterShopServer = require('./server');
69
+
70
+ const PORT = process.env['PORT'];
71
+ const PROTO_PATH = path.join(__dirname, '/proto/');
72
+
73
+ const server = new HipsterShopServer(PROTO_PATH, PORT);
74
+
75
+ server.listen();
benchmark/boutique/runtime/29/code/paymentservice/logger.js ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2023 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const pino = require('pino');
18
+
19
+ module.exports = pino({
20
+ name: 'paymentservice-server',
21
+ messageKey: 'message',
22
+ formatters: {
23
+ level (logLevelString, logLevelNum) {
24
+ return { severity: logLevelString }
25
+ }
26
+ }
27
+ });
benchmark/boutique/runtime/29/code/paymentservice/server.js ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ const path = require('path');
16
+ const grpc = require('@grpc/grpc-js');
17
+ const protoLoader = require('@grpc/proto-loader');
18
+
19
+ const charge = require('./charge');
20
+
21
+ const logger = require('./logger')
22
+
23
+ class HipsterShopServer {
24
+ constructor(protoRoot, port = HipsterShopServer.PORT) {
25
+ this.port = port;
26
+
27
+ this.packages = {
28
+ hipsterShop: this.loadProto(path.join(protoRoot, 'demo.proto')),
29
+ health: this.loadProto(path.join(protoRoot, 'grpc/health/v1/health.proto'))
30
+ };
31
+
32
+ this.server = new grpc.Server();
33
+ this.loadAllProtos(protoRoot);
34
+ }
35
+
36
+ /**
37
+ * Handler for PaymentService.Charge.
38
+ * @param {*} call { ChargeRequest }
39
+ * @param {*} callback fn(err, ChargeResponse)
40
+ */
41
+ static ChargeServiceHandler(call, callback) {
42
+ try {
43
+ logger.info(`PaymentService#Charge invoked with request ${JSON.stringify(call.request)}`);
44
+ const response = charge(call.request);
45
+ callback(null, response);
46
+ } catch (err) {
47
+ console.warn(err);
48
+ callback(err);
49
+ }
50
+ }
51
+
52
+ static CheckHandler(call, callback) {
53
+ callback(null, { status: 'SERVING' });
54
+ }
55
+
56
+
57
+ listen() {
58
+ const server = this.server
59
+ const port = this.port
60
+ server.bindAsync(
61
+ `[::]:${port}`,
62
+ grpc.ServerCredentials.createInsecure(),
63
+ function () {
64
+ logger.info(`PaymentService gRPC server started on port ${port}`);
65
+ server.start();
66
+ }
67
+ );
68
+ }
69
+
70
+ loadProto(path) {
71
+ const packageDefinition = protoLoader.loadSync(
72
+ path,
73
+ {
74
+ keepCase: true,
75
+ longs: String,
76
+ enums: String,
77
+ defaults: true,
78
+ oneofs: true
79
+ }
80
+ );
81
+ return grpc.loadPackageDefinition(packageDefinition);
82
+ }
83
+
84
+ loadAllProtos(protoRoot) {
85
+ const hipsterShopPackage = this.packages.hipsterShop.hipstershop;
86
+ const healthPackage = this.packages.health.grpc.health.v1;
87
+
88
+ this.server.addService(
89
+ hipsterShopPackage.PaymentService.service,
90
+ {
91
+ charge: HipsterShopServer.ChargeServiceHandler.bind(this)
92
+ }
93
+ );
94
+
95
+ this.server.addService(
96
+ healthPackage.Health.service,
97
+ {
98
+ check: HipsterShopServer.CheckHandler.bind(this)
99
+ }
100
+ );
101
+ }
102
+ }
103
+
104
+ HipsterShopServer.PORT = process.env.PORT;
105
+
106
+ module.exports = HipsterShopServer;
benchmark/boutique/runtime/29/code/productcatalogservice/catalog_loader.go ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // https://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "bytes"
19
+ "context"
20
+ "fmt"
21
+ "net"
22
+ "os"
23
+ "strings"
24
+
25
+ "cloud.google.com/go/alloydbconn"
26
+ secretmanager "cloud.google.com/go/secretmanager/apiv1"
27
+ "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
28
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
29
+ "github.com/golang/protobuf/jsonpb"
30
+ "github.com/jackc/pgx/v5/pgxpool"
31
+ )
32
+
33
+ func loadCatalog(catalog *pb.ListProductsResponse) error {
34
+ catalogMutex.Lock()
35
+ defer catalogMutex.Unlock()
36
+
37
+ if os.Getenv("ALLOYDB_CLUSTER_NAME") != "" {
38
+ return loadCatalogFromAlloyDB(catalog)
39
+ }
40
+
41
+ return loadCatalogFromLocalFile(catalog)
42
+ }
43
+
44
+ func loadCatalogFromLocalFile(catalog *pb.ListProductsResponse) error {
45
+ log.Info("loading catalog from local products.json file...")
46
+
47
+ catalogJSON, err := os.ReadFile("products.json")
48
+ if err != nil {
49
+ log.Warnf("failed to open product catalog json file: %v", err)
50
+ return err
51
+ }
52
+
53
+ if err := jsonpb.Unmarshal(bytes.NewReader(catalogJSON), catalog); err != nil {
54
+ log.Warnf("failed to parse the catalog JSON: %v", err)
55
+ return err
56
+ }
57
+
58
+ log.Info("successfully parsed product catalog json")
59
+ return nil
60
+ }
61
+
62
+ func getSecretPayload(project, secret, version string) (string, error) {
63
+ ctx := context.Background()
64
+ client, err := secretmanager.NewClient(ctx)
65
+ if err != nil {
66
+ log.Warnf("failed to create SecretManager client: %v", err)
67
+ return "", err
68
+ }
69
+ defer client.Close()
70
+
71
+ req := &secretmanagerpb.AccessSecretVersionRequest{
72
+ Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, secret, version),
73
+ }
74
+
75
+ // Call the API.
76
+ result, err := client.AccessSecretVersion(ctx, req)
77
+ if err != nil {
78
+ log.Warnf("failed to access SecretVersion: %v", err)
79
+ return "", err
80
+ }
81
+
82
+ return string(result.Payload.Data), nil
83
+ }
84
+
85
+ func loadCatalogFromAlloyDB(catalog *pb.ListProductsResponse) error {
86
+ log.Info("loading catalog from AlloyDB...")
87
+
88
+ projectID := os.Getenv("PROJECT_ID")
89
+ region := os.Getenv("REGION")
90
+ pgClusterName := os.Getenv("ALLOYDB_CLUSTER_NAME")
91
+ pgInstanceName := os.Getenv("ALLOYDB_INSTANCE_NAME")
92
+ pgDatabaseName := os.Getenv("ALLOYDB_DATABASE_NAME")
93
+ pgTableName := os.Getenv("ALLOYDB_TABLE_NAME")
94
+ pgSecretName := os.Getenv("ALLOYDB_SECRET_NAME")
95
+
96
+ pgPassword, err := getSecretPayload(projectID, pgSecretName, "latest")
97
+ if err != nil {
98
+ return err
99
+ }
100
+
101
+ dialer, err := alloydbconn.NewDialer(context.Background())
102
+ if err != nil {
103
+ log.Warnf("failed to set-up dialer connection: %v", err)
104
+ return err
105
+ }
106
+ cleanup := func() error { return dialer.Close() }
107
+ defer cleanup()
108
+
109
+ dsn := fmt.Sprintf(
110
+ "user=%s password=%s dbname=%s sslmode=disable",
111
+ "postgres", pgPassword, pgDatabaseName,
112
+ )
113
+
114
+ config, err := pgxpool.ParseConfig(dsn)
115
+ if err != nil {
116
+ log.Warnf("failed to parse DSN config: %v", err)
117
+ return err
118
+ }
119
+
120
+ pgInstanceURI := fmt.Sprintf("projects/%s/locations/%s/clusters/%s/instances/%s", projectID, region, pgClusterName, pgInstanceName)
121
+ config.ConnConfig.DialFunc = func(ctx context.Context, _ string, _ string) (net.Conn, error) {
122
+ return dialer.Dial(ctx, pgInstanceURI)
123
+ }
124
+
125
+ pool, err := pgxpool.NewWithConfig(context.Background(), config)
126
+ if err != nil {
127
+ log.Warnf("failed to set-up pgx pool: %v", err)
128
+ return err
129
+ }
130
+ defer pool.Close()
131
+
132
+ query := "SELECT id, name, description, picture, price_usd_currency_code, price_usd_units, price_usd_nanos, categories FROM " + pgTableName
133
+ rows, err := pool.Query(context.Background(), query)
134
+ if err != nil {
135
+ log.Warnf("failed to query database: %v", err)
136
+ return err
137
+ }
138
+ defer rows.Close()
139
+
140
+ catalog.Products = catalog.Products[:0]
141
+ for rows.Next() {
142
+ product := &pb.Product{}
143
+ product.PriceUsd = &pb.Money{}
144
+
145
+ var categories string
146
+ err = rows.Scan(&product.Id, &product.Name, &product.Description,
147
+ &product.Picture, &product.PriceUsd.CurrencyCode, &product.PriceUsd.Units,
148
+ &product.PriceUsd.Nanos, &categories)
149
+ if err != nil {
150
+ log.Warnf("failed to scan query result row: %v", err)
151
+ return err
152
+ }
153
+ categories = strings.ToLower(categories)
154
+ product.Categories = strings.Split(categories, ",")
155
+
156
+ catalog.Products = append(catalog.Products, product)
157
+ }
158
+
159
+ log.Info("successfully parsed product catalog from AlloyDB")
160
+ return nil
161
+ }
benchmark/boutique/runtime/29/code/productcatalogservice/product_catalog.go ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "strings"
20
+ "time"
21
+
22
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
23
+ "google.golang.org/grpc/codes"
24
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
25
+ "google.golang.org/grpc/status"
26
+ )
27
+
28
+ type productCatalog struct {
29
+ pb.UnimplementedProductCatalogServiceServer
30
+ catalog pb.ListProductsResponse
31
+ }
32
+
33
+ func (p *productCatalog) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
34
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
35
+ }
36
+
37
+ func (p *productCatalog) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
38
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
39
+ }
40
+
41
+ func (p *productCatalog) ListProducts(context.Context, *pb.Empty) (*pb.ListProductsResponse, error) {
42
+ time.Sleep(extraLatency)
43
+
44
+ return &pb.ListProductsResponse{Products: p.parseCatalog()}, nil
45
+ }
46
+
47
+ func (p *productCatalog) GetProduct(ctx context.Context, req *pb.GetProductRequest) (*pb.Product, error) {
48
+ time.Sleep(extraLatency)
49
+
50
+ catalog := p.parseCatalog()
51
+ for _, product := range catalog {
52
+ if req.Id == product.Id {
53
+ return product, nil
54
+ }
55
+ }
56
+
57
+ return nil, status.Errorf(codes.NotFound, "no product with ID %s", req.Id)
58
+ }
59
+
60
+ func (p *productCatalog) SearchProducts(ctx context.Context, req *pb.SearchProductsRequest) (*pb.SearchProductsResponse, error) {
61
+ time.Sleep(extraLatency)
62
+
63
+ var ps []*pb.Product
64
+ for _, product := range p.parseCatalog() {
65
+ if strings.Contains(strings.ToLower(product.Name), strings.ToLower(req.Query)) ||
66
+ strings.Contains(strings.ToLower(product.Description), strings.ToLower(req.Query)) {
67
+ ps = append(ps, product)
68
+ }
69
+ }
70
+
71
+ return &pb.SearchProductsResponse{Results: ps}, nil
72
+ }
73
+
74
+ func (p *productCatalog) parseCatalog() []*pb.Product {
75
+ if reloadCatalog || len(p.catalog.Products) == 0 {
76
+ err := loadCatalog(&p.catalog)
77
+ if err != nil {
78
+ return []*pb.Product{}
79
+ }
80
+ }
81
+
82
+ return p.catalog.Products
83
+ }
benchmark/boutique/runtime/29/code/productcatalogservice/server.go ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "context"
19
+ "flag"
20
+ "fmt"
21
+ "net"
22
+ "os"
23
+ "os/signal"
24
+ "sync"
25
+ "syscall"
26
+ "time"
27
+
28
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/productcatalogservice/genproto"
29
+ "google.golang.org/grpc/credentials/insecure"
30
+ "google.golang.org/grpc/health"
31
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
32
+
33
+ "cloud.google.com/go/profiler"
34
+ "github.com/pkg/errors"
35
+ "github.com/sirupsen/logrus"
36
+ "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
37
+ "go.opentelemetry.io/otel"
38
+ "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
39
+ "go.opentelemetry.io/otel/propagation"
40
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
41
+ "google.golang.org/grpc"
42
+ )
43
+
44
+ var (
45
+ catalogMutex *sync.Mutex
46
+ log *logrus.Logger
47
+ extraLatency time.Duration
48
+
49
+ port = "3550"
50
+
51
+ reloadCatalog bool
52
+ )
53
+
54
+ func init() {
55
+ log = logrus.New()
56
+ log.Formatter = &logrus.JSONFormatter{
57
+ FieldMap: logrus.FieldMap{
58
+ logrus.FieldKeyTime: "timestamp",
59
+ logrus.FieldKeyLevel: "severity",
60
+ logrus.FieldKeyMsg: "message",
61
+ },
62
+ TimestampFormat: time.RFC3339Nano,
63
+ }
64
+ log.Out = os.Stdout
65
+ catalogMutex = &sync.Mutex{}
66
+ }
67
+
68
+ func main() {
69
+ if os.Getenv("ENABLE_TRACING") == "1" {
70
+ err := initTracing()
71
+ if err != nil {
72
+ log.Warnf("warn: failed to start tracer: %+v", err)
73
+ }
74
+ } else {
75
+ log.Info("Tracing disabled.")
76
+ }
77
+
78
+ if os.Getenv("DISABLE_PROFILER") == "" {
79
+ log.Info("Profiling enabled.")
80
+ go initProfiling("productcatalogservice", "1.0.0")
81
+ } else {
82
+ log.Info("Profiling disabled.")
83
+ }
84
+
85
+ flag.Parse()
86
+
87
+ // set injected latency
88
+ if s := os.Getenv("EXTRA_LATENCY"); s != "" {
89
+ v, err := time.ParseDuration(s)
90
+ if err != nil {
91
+ log.Fatalf("failed to parse EXTRA_LATENCY (%s) as time.Duration: %+v", v, err)
92
+ }
93
+ extraLatency = v
94
+ log.Infof("extra latency enabled (duration: %v)", extraLatency)
95
+ } else {
96
+ extraLatency = time.Duration(0)
97
+ }
98
+
99
+ sigs := make(chan os.Signal, 1)
100
+ signal.Notify(sigs, syscall.SIGUSR1, syscall.SIGUSR2)
101
+ go func() {
102
+ for {
103
+ sig := <-sigs
104
+ log.Printf("Received signal: %s", sig)
105
+ if sig == syscall.SIGUSR1 {
106
+ reloadCatalog = true
107
+ log.Infof("Enable catalog reloading")
108
+ } else {
109
+ reloadCatalog = false
110
+ log.Infof("Disable catalog reloading")
111
+ }
112
+ }
113
+ }()
114
+
115
+ if os.Getenv("PORT") != "" {
116
+ port = os.Getenv("PORT")
117
+ }
118
+ log.Infof("starting grpc server at :%s", port)
119
+ run(port)
120
+ select {}
121
+ }
122
+
123
+ func run(port string) string {
124
+ listener, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
125
+ if err != nil {
126
+ log.Fatal(err)
127
+ }
128
+
129
+ // Propagate trace context
130
+ otel.SetTextMapPropagator(
131
+ propagation.NewCompositeTextMapPropagator(
132
+ propagation.TraceContext{}, propagation.Baggage{}))
133
+ var srv *grpc.Server
134
+ srv = grpc.NewServer(
135
+ grpc.StatsHandler(otelgrpc.NewServerHandler()))
136
+
137
+ svc := &productCatalog{}
138
+ err = loadCatalog(&svc.catalog)
139
+ if err != nil {
140
+ log.Fatalf("could not parse product catalog: %v", err)
141
+ }
142
+
143
+ pb.RegisterProductCatalogServiceServer(srv, svc)
144
+ healthcheck := health.NewServer()
145
+ healthpb.RegisterHealthServer(srv, healthcheck)
146
+ go srv.Serve(listener)
147
+
148
+ return listener.Addr().String()
149
+ }
150
+
151
+ func initStats() {
152
+ // TODO(drewbr) Implement OpenTelemetry stats
153
+ }
154
+
155
+ func initTracing() error {
156
+ var (
157
+ collectorAddr string
158
+ collectorConn *grpc.ClientConn
159
+ )
160
+
161
+ ctx := context.Background()
162
+
163
+ mustMapEnv(&collectorAddr, "COLLECTOR_SERVICE_ADDR")
164
+ mustConnGRPC(ctx, &collectorConn, collectorAddr)
165
+
166
+ exporter, err := otlptracegrpc.New(
167
+ ctx,
168
+ otlptracegrpc.WithGRPCConn(collectorConn))
169
+ if err != nil {
170
+ log.Warnf("warn: Failed to create trace exporter: %v", err)
171
+ }
172
+ tp := sdktrace.NewTracerProvider(
173
+ sdktrace.WithBatcher(exporter),
174
+ sdktrace.WithSampler(sdktrace.AlwaysSample()))
175
+ otel.SetTracerProvider(tp)
176
+ return err
177
+ }
178
+
179
+ func initProfiling(service, version string) {
180
+ for i := 1; i <= 3; i++ {
181
+ if err := profiler.Start(profiler.Config{
182
+ Service: service,
183
+ ServiceVersion: version,
184
+ // ProjectID must be set if not running on GCP.
185
+ // ProjectID: "my-project",
186
+ }); err != nil {
187
+ log.Warnf("failed to start profiler: %+v", err)
188
+ } else {
189
+ log.Info("started Stackdriver profiler")
190
+ return
191
+ }
192
+ d := time.Second * 10 * time.Duration(i)
193
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
194
+ time.Sleep(d)
195
+ }
196
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
197
+ }
198
+
199
+ func mustMapEnv(target *string, envKey string) {
200
+ v := os.Getenv(envKey)
201
+ if v == "" {
202
+ panic(fmt.Sprintf("environment variable %q not set", envKey))
203
+ }
204
+ *target = v
205
+ }
206
+
207
+ func mustConnGRPC(ctx context.Context, conn **grpc.ClientConn, addr string) {
208
+ var err error
209
+ _, cancel := context.WithTimeout(ctx, time.Second*3)
210
+ defer cancel()
211
+ *conn, err = grpc.NewClient(addr,
212
+ grpc.WithTransportCredentials(insecure.NewCredentials()),
213
+ grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
214
+ if err != nil {
215
+ panic(errors.Wrapf(err, "grpc: failed to connect %s", addr))
216
+ }
217
+ }
benchmark/boutique/runtime/29/code/recommendationservice/client.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import sys
18
+ import grpc
19
+ import demo_pb2
20
+ import demo_pb2_grpc
21
+
22
+ from logger import getJSONLogger
23
+ logger = getJSONLogger('recommendationservice-server')
24
+
25
+ if __name__ == "__main__":
26
+ # get port
27
+ if len(sys.argv) > 1:
28
+ port = sys.argv[1]
29
+ else:
30
+ port = "8080"
31
+
32
+ # set up server stub
33
+ channel = grpc.insecure_channel('localhost:'+port)
34
+ stub = demo_pb2_grpc.RecommendationServiceStub(channel)
35
+ # form request
36
+ request = demo_pb2.ListRecommendationsRequest(user_id="test", product_ids=["test"])
37
+ # make call to server
38
+ response = stub.ListRecommendations(request)
39
+ logger.info(response)
benchmark/boutique/runtime/29/code/recommendationservice/logger.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import sys
19
+ from pythonjsonlogger import jsonlogger
20
+
21
+ # TODO(yoshifumi) this class is duplicated since other Python services are
22
+ # not sharing the modules for logging.
23
+ class CustomJsonFormatter(jsonlogger.JsonFormatter):
24
+ def add_fields(self, log_record, record, message_dict):
25
+ super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
26
+ if not log_record.get('timestamp'):
27
+ log_record['timestamp'] = record.created
28
+ if log_record.get('severity'):
29
+ log_record['severity'] = log_record['severity'].upper()
30
+ else:
31
+ log_record['severity'] = record.levelname
32
+
33
+ def getJSONLogger(name):
34
+ logger = logging.getLogger(name)
35
+ handler = logging.StreamHandler(sys.stdout)
36
+ formatter = CustomJsonFormatter('%(timestamp)s %(severity)s %(name)s %(message)s')
37
+ handler.setFormatter(formatter)
38
+ logger.addHandler(handler)
39
+ logger.setLevel(logging.INFO)
40
+ logger.propagate = False
41
+ return logger
benchmark/boutique/runtime/29/code/recommendationservice/recommendation_server.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2018 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ import random
19
+ import time
20
+ import traceback
21
+ from concurrent import futures
22
+
23
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
24
+ # import googlecloudprofiler
25
+
26
+ from google.auth.exceptions import DefaultCredentialsError
27
+ import grpc
28
+
29
+ import demo_pb2
30
+ import demo_pb2_grpc
31
+ from grpc_health.v1 import health_pb2
32
+ from grpc_health.v1 import health_pb2_grpc
33
+
34
+ from opentelemetry import trace
35
+ from opentelemetry.instrumentation.grpc import GrpcInstrumentorClient, GrpcInstrumentorServer
36
+ from opentelemetry.sdk.trace import TracerProvider
37
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
38
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
39
+
40
+ from logger import getJSONLogger
41
+ logger = getJSONLogger('recommendationservice-server')
42
+
43
+ def initStackdriverProfiling():
44
+ project_id = None
45
+ try:
46
+ project_id = os.environ["GCP_PROJECT_ID"]
47
+ except KeyError:
48
+ # Environment variable not set
49
+ pass
50
+
51
+ # @TODO: Temporarily removed in https://github.com/GoogleCloudPlatform/microservices-demo/pull/3196
52
+ # for retry in range(1,4):
53
+ # try:
54
+ # if project_id:
55
+ # googlecloudprofiler.start(service='recommendation_server', service_version='1.0.0', verbose=0, project_id=project_id)
56
+ # else:
57
+ # googlecloudprofiler.start(service='recommendation_server', service_version='1.0.0', verbose=0)
58
+ # logger.info("Successfully started Stackdriver Profiler.")
59
+ # return
60
+ # except (BaseException) as exc:
61
+ # logger.info("Unable to start Stackdriver Profiler Python agent. " + str(exc))
62
+ # if (retry < 4):
63
+ # logger.info("Sleeping %d seconds to retry Stackdriver Profiler agent initialization"%(retry*10))
64
+ # time.sleep (1)
65
+ # else:
66
+ # logger.warning("Could not initialize Stackdriver Profiler after retrying, giving up")
67
+ return
68
+
69
+ class RecommendationService(demo_pb2_grpc.RecommendationServiceServicer):
70
+ def ListRecommendations(self, request, context):
71
+ max_responses = 5
72
+ # fetch list of products from product catalog stub
73
+ cat_response = product_catalog_stub.ListProducts(demo_pb2.Empty())
74
+ product_ids = [x.id for x in cat_response.products]
75
+ filtered_products = list(set(product_ids)-set(request.product_ids))
76
+ num_products = len(filtered_products)
77
+ num_return = min(max_responses, num_products)
78
+ # sample list of indicies to return
79
+ indices = random.sample(range(num_products), num_return)
80
+ # fetch product ids from indices
81
+ prod_list = [filtered_products[i] for i in indices]
82
+ logger.info("[Recv ListRecommendations] product_ids={}".format(prod_list))
83
+ # build and return response
84
+ response = demo_pb2.ListRecommendationsResponse()
85
+ response.product_ids.extend(prod_list)
86
+ return response
87
+
88
+ def Check(self, request, context):
89
+ return health_pb2.HealthCheckResponse(
90
+ status=health_pb2.HealthCheckResponse.SERVING)
91
+
92
+ def Watch(self, request, context):
93
+ return health_pb2.HealthCheckResponse(
94
+ status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)
95
+
96
+
97
+ if __name__ == "__main__":
98
+ logger.info("initializing recommendationservice")
99
+
100
+ try:
101
+ if "DISABLE_PROFILER" in os.environ:
102
+ raise KeyError()
103
+ else:
104
+ logger.info("Profiler enabled.")
105
+ initStackdriverProfiling()
106
+ except KeyError:
107
+ logger.info("Profiler disabled.")
108
+
109
+ try:
110
+ grpc_client_instrumentor = GrpcInstrumentorClient()
111
+ grpc_client_instrumentor.instrument()
112
+ grpc_server_instrumentor = GrpcInstrumentorServer()
113
+ grpc_server_instrumentor.instrument()
114
+ if os.environ["ENABLE_TRACING"] == "1":
115
+ trace.set_tracer_provider(TracerProvider())
116
+ otel_endpoint = os.getenv("COLLECTOR_SERVICE_ADDR", "localhost:4317")
117
+ trace.get_tracer_provider().add_span_processor(
118
+ BatchSpanProcessor(
119
+ OTLPSpanExporter(
120
+ endpoint = otel_endpoint,
121
+ insecure = True
122
+ )
123
+ )
124
+ )
125
+ except (KeyError, DefaultCredentialsError):
126
+ logger.info("Tracing disabled.")
127
+ except Exception as e:
128
+ logger.warn(f"Exception on Cloud Trace setup: {traceback.format_exc()}, tracing disabled.")
129
+
130
+ port = os.environ.get('PORT', "8080")
131
+ catalog_addr = os.environ.get('PRODUCT_CATALOG_SERVICE_ADDR', '')
132
+ if catalog_addr == "":
133
+ raise Exception('PRODUCT_CATALOG_SERVICE_ADDR environment variable not set')
134
+ logger.info("product catalog address: " + catalog_addr)
135
+ channel = grpc.insecure_channel(catalog_addr)
136
+ product_catalog_stub = demo_pb2_grpc.ProductCatalogServiceStub(channel)
137
+
138
+ # create gRPC server
139
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
140
+
141
+ # add class to gRPC server
142
+ service = RecommendationService()
143
+ demo_pb2_grpc.add_RecommendationServiceServicer_to_server(service, server)
144
+ health_pb2_grpc.add_HealthServicer_to_server(service, server)
145
+
146
+ # start server
147
+ logger.info("listening on port: " + port)
148
+ server.add_insecure_port('[::]:'+port)
149
+ server.start()
150
+
151
+ # keep alive
152
+ try:
153
+ while True:
154
+ time.sleep(10000)
155
+ except KeyboardInterrupt:
156
+ server.stop(0)
benchmark/boutique/runtime/29/code/shippingservice/main.go ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ package main
16
+
17
+ import (
18
+ "fmt"
19
+ "net"
20
+ "os"
21
+ "time"
22
+
23
+ "cloud.google.com/go/profiler"
24
+ "github.com/sirupsen/logrus"
25
+ "golang.org/x/net/context"
26
+ "google.golang.org/grpc"
27
+ "google.golang.org/grpc/codes"
28
+ "google.golang.org/grpc/health"
29
+ "google.golang.org/grpc/reflection"
30
+ "google.golang.org/grpc/status"
31
+
32
+ pb "github.com/GoogleCloudPlatform/microservices-demo/src/shippingservice/genproto"
33
+ healthpb "google.golang.org/grpc/health/grpc_health_v1"
34
+ )
35
+
36
+ const (
37
+ defaultPort = "50051"
38
+ )
39
+
40
+ var log *logrus.Logger
41
+
42
+ func init() {
43
+ log = logrus.New()
44
+ log.Level = logrus.DebugLevel
45
+ log.Formatter = &logrus.JSONFormatter{
46
+ FieldMap: logrus.FieldMap{
47
+ logrus.FieldKeyTime: "timestamp",
48
+ logrus.FieldKeyLevel: "severity",
49
+ logrus.FieldKeyMsg: "message",
50
+ },
51
+ TimestampFormat: time.RFC3339Nano,
52
+ }
53
+ log.Out = os.Stdout
54
+ }
55
+
56
+ func main() {
57
+ if os.Getenv("DISABLE_TRACING") == "" {
58
+ log.Info("Tracing enabled, but temporarily unavailable")
59
+ log.Info("See https://github.com/GoogleCloudPlatform/microservices-demo/issues/422 for more info.")
60
+ go initTracing()
61
+ } else {
62
+ log.Info("Tracing disabled.")
63
+ }
64
+
65
+ if os.Getenv("DISABLE_PROFILER") == "" {
66
+ log.Info("Profiling enabled.")
67
+ go initProfiling("shippingservice", "1.0.0")
68
+ } else {
69
+ log.Info("Profiling disabled.")
70
+ }
71
+
72
+ port := defaultPort
73
+ if value, ok := os.LookupEnv("PORT"); ok {
74
+ port = value
75
+ }
76
+ port = fmt.Sprintf(":%s", port)
77
+
78
+ lis, err := net.Listen("tcp", port)
79
+ if err != nil {
80
+ log.Fatalf("failed to listen: %v", err)
81
+ }
82
+
83
+ var srv *grpc.Server
84
+ if os.Getenv("DISABLE_STATS") == "" {
85
+ log.Info("Stats enabled, but temporarily unavailable")
86
+ srv = grpc.NewServer()
87
+ } else {
88
+ log.Info("Stats disabled.")
89
+ srv = grpc.NewServer()
90
+ }
91
+ svc := &server{}
92
+ pb.RegisterShippingServiceServer(srv, svc)
93
+ healthcheck := health.NewServer()
94
+ healthpb.RegisterHealthServer(srv, healthcheck)
95
+ log.Infof("Shipping Service listening on port %s", port)
96
+
97
+ // Register reflection service on gRPC server.
98
+ reflection.Register(srv)
99
+ if err := srv.Serve(lis); err != nil {
100
+ log.Fatalf("failed to serve: %v", err)
101
+ }
102
+ }
103
+
104
+ // server controls RPC service responses.
105
+ type server struct {
106
+ pb.UnimplementedShippingServiceServer
107
+ }
108
+
109
+ // Check is for health checking.
110
+ func (s *server) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
111
+ return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
112
+ }
113
+
114
+ func (s *server) Watch(req *healthpb.HealthCheckRequest, ws healthpb.Health_WatchServer) error {
115
+ return status.Errorf(codes.Unimplemented, "health check via Watch not implemented")
116
+ }
117
+
118
+ // GetQuote produces a shipping quote (cost) in USD.
119
+ func (s *server) GetQuote(ctx context.Context, in *pb.GetQuoteRequest) (*pb.GetQuoteResponse, error) {
120
+ log.Info("[GetQuote] received request")
121
+ defer log.Info("[GetQuote] completed request")
122
+
123
+ // 1. Generate a quote based on the total number of items to be shipped.
124
+ count := 0
125
+ for _, item := range in.Items {
126
+ count += int(item.Quantity)
127
+ }
128
+ quote := CreateQuoteFromCount(count)
129
+
130
+ // 2. Generate a response.
131
+ return &pb.GetQuoteResponse{
132
+ CostUsd: &pb.Money{
133
+ CurrencyCode: "USD",
134
+ Units: int64(quote.Dollars),
135
+ Nanos: int32(quote.Cents * 10000000)},
136
+ }, nil
137
+
138
+ }
139
+
140
+ // ShipOrder mocks that the requested items will be shipped.
141
+ // It supplies a tracking ID for notional lookup of shipment delivery status.
142
+ func (s *server) ShipOrder(ctx context.Context, in *pb.ShipOrderRequest) (*pb.ShipOrderResponse, error) {
143
+ log.Info("[ShipOrder] received request")
144
+ defer log.Info("[ShipOrder] completed request")
145
+ // 1. Create a Tracking ID
146
+ baseAddress := fmt.Sprintf("%s, %s, %s", in.Address.StreetAddress, in.Address.City, in.Address.State)
147
+ id := CreateTrackingId(baseAddress)
148
+
149
+ // 2. Generate a response.
150
+ return &pb.ShipOrderResponse{
151
+ TrackingId: id,
152
+ }, nil
153
+ }
154
+
155
+ func initStats() {
156
+ //TODO(arbrown) Implement OpenTelemetry stats
157
+ }
158
+
159
+ func initTracing() {
160
+ // TODO(arbrown) Implement OpenTelemetry tracing
161
+ }
162
+
163
+ func initProfiling(service, version string) {
164
+ // TODO(ahmetb) this method is duplicated in other microservices using Go
165
+ // since they are not sharing packages.
166
+ for i := 1; i <= 3; i++ {
167
+ if err := profiler.Start(profiler.Config{
168
+ Service: service,
169
+ ServiceVersion: version,
170
+ // ProjectID must be set if not running on GCP.
171
+ // ProjectID: "my-project",
172
+ }); err != nil {
173
+ log.Warnf("failed to start profiler: %+v", err)
174
+ } else {
175
+ log.Info("started Stackdriver profiler")
176
+ return
177
+ }
178
+ d := time.Second * 10 * time.Duration(i)
179
+ log.Infof("sleeping %v to retry initializing Stackdriver profiler", d)
180
+ time.Sleep(d)
181
+ }
182
+ log.Warn("could not initialize Stackdriver profiler after retrying, giving up")
183
+ }