server_stats_handler.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. //
  15. package ocgrpc
  16. import (
  17. "time"
  18. "context"
  19. "go.opencensus.io/tag"
  20. "google.golang.org/grpc/grpclog"
  21. "google.golang.org/grpc/stats"
  22. )
  23. // statsTagRPC gets the metadata from gRPC context, extracts the encoded tags from
  24. // it and creates a new tag.Map and puts them into the returned context.
  25. func (h *ServerHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
  26. startTime := time.Now()
  27. if info == nil {
  28. if grpclog.V(2) {
  29. grpclog.Infof("opencensus: TagRPC called with nil info.")
  30. }
  31. return ctx
  32. }
  33. d := &rpcData{
  34. startTime: startTime,
  35. method: info.FullMethodName,
  36. }
  37. propagated := h.extractPropagatedTags(ctx)
  38. ctx = tag.NewContext(ctx, propagated)
  39. ctx, _ = tag.New(ctx, tag.Upsert(KeyServerMethod, methodName(info.FullMethodName)))
  40. return context.WithValue(ctx, rpcDataKey, d)
  41. }
  42. // extractPropagatedTags creates a new tag map containing the tags extracted from the
  43. // gRPC metadata.
  44. func (h *ServerHandler) extractPropagatedTags(ctx context.Context) *tag.Map {
  45. buf := stats.Tags(ctx)
  46. if buf == nil {
  47. return nil
  48. }
  49. propagated, err := tag.Decode(buf)
  50. if err != nil {
  51. if grpclog.V(2) {
  52. grpclog.Warningf("opencensus: Failed to decode tags from gRPC metadata failed to decode: %v", err)
  53. }
  54. return nil
  55. }
  56. return propagated
  57. }