util.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package trace
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "math/rand"
  6. "time"
  7. "github.com/pkg/errors"
  8. "go-common/library/conf/env"
  9. "go-common/library/net/metadata"
  10. )
  11. var _hostHash byte
  12. func init() {
  13. rand.Seed(time.Now().UnixNano())
  14. _hostHash = byte(oneAtTimeHash(env.Hostname))
  15. }
  16. func extendTag() (tags []Tag) {
  17. tags = append(tags,
  18. TagString("hostname", env.Hostname),
  19. TagString("ip", env.IP),
  20. TagString("zone", env.Zone),
  21. TagString("region", env.Region),
  22. )
  23. return
  24. }
  25. func serviceNameFromEnv() string {
  26. return env.AppID
  27. }
  28. func isUATEnv() bool {
  29. return env.DeployEnv == env.DeployEnvUat
  30. }
  31. func genID() uint64 {
  32. var b [8]byte
  33. // i think this code will not survive to 2106-02-07
  34. binary.BigEndian.PutUint32(b[4:], uint32(time.Now().Unix())>>8)
  35. b[4] = _hostHash
  36. binary.BigEndian.PutUint32(b[:4], uint32(rand.Int31()))
  37. return binary.BigEndian.Uint64(b[:])
  38. }
  39. type stackTracer interface {
  40. StackTrace() errors.StackTrace
  41. }
  42. type ctxKey string
  43. var _ctxkey ctxKey = "go-common/net/trace.trace"
  44. // FromContext returns the trace bound to the context, if any.
  45. func FromContext(ctx context.Context) (t Trace, ok bool) {
  46. if v := metadata.Value(ctx, metadata.Trace); v != nil {
  47. t, ok = v.(Trace)
  48. return
  49. }
  50. t, ok = ctx.Value(_ctxkey).(Trace)
  51. return
  52. }
  53. // NewContext new a trace context.
  54. // NOTE: This method is not thread safe.
  55. func NewContext(ctx context.Context, t Trace) context.Context {
  56. if md, ok := metadata.FromContext(ctx); ok {
  57. md[metadata.Trace] = t
  58. return ctx
  59. }
  60. return context.WithValue(ctx, _ctxkey, t)
  61. }