|
| 1 | +/* |
| 2 | + * |
| 3 | + * Copyright 2024 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 | + |
| 19 | +package main |
| 20 | + |
| 21 | +import ( |
| 22 | + "context" |
| 23 | + "flag" |
| 24 | + "fmt" |
| 25 | + "log" |
| 26 | + "net" |
| 27 | + "net/http" |
| 28 | + |
| 29 | + "google.golang.org/grpc" |
| 30 | + pb "google.golang.org/grpc/examples/features/proto/echo" |
| 31 | + "google.golang.org/grpc/stats/opentelemetry" |
| 32 | + |
| 33 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 34 | + "go.opentelemetry.io/otel/exporters/prometheus" |
| 35 | + "go.opentelemetry.io/otel/sdk/metric" |
| 36 | +) |
| 37 | + |
| 38 | +var ( |
| 39 | + addr = flag.String("addr", ":50051", "the server address to connect to") |
| 40 | + prometheusEndpoint = flag.String("prometheus_endpoint", ":9464", "the Prometheus exporter endpoint") |
| 41 | +) |
| 42 | + |
| 43 | +type echoServer struct { |
| 44 | + pb.UnimplementedEchoServer |
| 45 | + addr string |
| 46 | +} |
| 47 | + |
| 48 | +func (s *echoServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) { |
| 49 | + return &pb.EchoResponse{Message: fmt.Sprintf("%s (from %s)", req.Message, s.addr)}, nil |
| 50 | +} |
| 51 | + |
| 52 | +func main() { |
| 53 | + exporter, err := prometheus.New() |
| 54 | + if err != nil { |
| 55 | + log.Fatalf("Failed to start prometheus exporter: %v", err) |
| 56 | + } |
| 57 | + provider := metric.NewMeterProvider(metric.WithReader(exporter)) |
| 58 | + go http.ListenAndServe(*prometheusEndpoint, promhttp.Handler()) |
| 59 | + |
| 60 | + so := opentelemetry.ServerOption(opentelemetry.Options{MetricsOptions: opentelemetry.MetricsOptions{MeterProvider: provider}}) |
| 61 | + |
| 62 | + lis, err := net.Listen("tcp", *addr) |
| 63 | + if err != nil { |
| 64 | + log.Fatalf("Failed to listen: %v", err) |
| 65 | + } |
| 66 | + s := grpc.NewServer(so) |
| 67 | + pb.RegisterEchoServer(s, &echoServer{addr: *addr}) |
| 68 | + |
| 69 | + log.Printf("Serving on %s\n", *addr) |
| 70 | + |
| 71 | + if err := s.Serve(lis); err != nil { |
| 72 | + log.Fatalf("Failed to serve: %v", err) |
| 73 | + } |
| 74 | +} |
0 commit comments