stats.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package warden
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "go-common/library/ecode"
  7. nmd "go-common/library/net/metadata"
  8. "go-common/library/stat/summary"
  9. "go-common/library/stat/sys/cpu"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/metadata"
  12. )
  13. func (s *Server) stats() grpc.UnaryServerInterceptor {
  14. errstat := summary.New(time.Second*3, 10)
  15. return func(ctx context.Context, req interface{}, args *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  16. c := int64(0)
  17. if resp, err = handler(ctx, req); err != nil {
  18. if ecode.ServerErr.Equal(err) || ecode.ServiceUnavailable.Equal(err) ||
  19. ecode.Deadline.Equal(err) || ecode.LimitExceed.Equal(err) {
  20. c = 1
  21. }
  22. }
  23. errstat.Add(c)
  24. errors, requests := errstat.Value()
  25. kv := []string{
  26. nmd.Errors, strconv.FormatInt(errors, 10),
  27. nmd.Requests, strconv.FormatInt(requests, 10),
  28. }
  29. var cpustat cpu.Stat
  30. cpu.ReadStat(&cpustat)
  31. if cpustat.Usage != 0 {
  32. kv = append(kv, nmd.CPUUsage, strconv.FormatInt(int64(cpustat.Usage), 10))
  33. }
  34. trailer := metadata.Pairs(kv...)
  35. grpc.SetTrailer(ctx, trailer)
  36. return
  37. }
  38. }