You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

80 lines
2.2 KiB

  1. // Copyright 2017, OpenCensus Authors
  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. //go:generate protoc -I ../proto --go_out=plugins=grpc:../proto ../proto/helloworld.proto
  15. package main
  16. import (
  17. "log"
  18. "math/rand"
  19. "net"
  20. "net/http"
  21. "time"
  22. "go.opencensus.io/examples/exporter"
  23. pb "go.opencensus.io/examples/grpc/proto"
  24. "go.opencensus.io/plugin/ocgrpc"
  25. "go.opencensus.io/stats/view"
  26. "go.opencensus.io/trace"
  27. "go.opencensus.io/zpages"
  28. "golang.org/x/net/context"
  29. "google.golang.org/grpc"
  30. )
  31. const port = ":50051"
  32. // server is used to implement helloworld.GreeterServer.
  33. type server struct{}
  34. // SayHello implements helloworld.GreeterServer
  35. func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
  36. ctx, span := trace.StartSpan(ctx, "sleep")
  37. time.Sleep(time.Duration(rand.Float64() * float64(time.Second)))
  38. span.End()
  39. return &pb.HelloReply{Message: "Hello " + in.Name}, nil
  40. }
  41. func main() {
  42. // Start z-Pages server.
  43. go func() {
  44. mux := http.NewServeMux()
  45. zpages.Handle(mux, "/debug")
  46. log.Fatal(http.ListenAndServe("127.0.0.1:8081", mux))
  47. }()
  48. // Register stats and trace exporters to export
  49. // the collected data.
  50. view.RegisterExporter(&exporter.PrintExporter{})
  51. // Register the views to collect server request count.
  52. if err := view.Register(ocgrpc.DefaultServerViews...); err != nil {
  53. log.Fatal(err)
  54. }
  55. lis, err := net.Listen("tcp", port)
  56. if err != nil {
  57. log.Fatalf("Failed to listen: %v", err)
  58. }
  59. // Set up a new server with the OpenCensus
  60. // stats handler to enable stats and tracing.
  61. s := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
  62. pb.RegisterGreeterServer(s, &server{})
  63. if err := s.Serve(lis); err != nil {
  64. log.Fatalf("Failed to serve: %v", err)
  65. }
  66. }