detect.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package collector
  2. import (
  3. "sync"
  4. "go-common/app/service/main/dapper/model"
  5. )
  6. type peerServiceDetect struct {
  7. rmx sync.RWMutex
  8. pair map[string]string
  9. }
  10. func (p *peerServiceDetect) detect(operationName string) (string, bool) {
  11. p.rmx.RLock()
  12. serviceName, ok := p.pair[operationName]
  13. p.rmx.RUnlock()
  14. return serviceName, ok
  15. }
  16. func (p *peerServiceDetect) add(serviceName, operationName string) {
  17. if operationName == "" || serviceName == "" {
  18. // ignored empty
  19. return
  20. }
  21. p.rmx.RLock()
  22. val, ok := p.pair[operationName]
  23. p.rmx.RUnlock()
  24. if !ok || serviceName != val {
  25. p.rmx.Lock()
  26. p.pair[operationName] = serviceName
  27. p.rmx.Unlock()
  28. }
  29. }
  30. func (p *peerServiceDetect) process(span *model.Span) {
  31. if span.IsServer() {
  32. p.add(span.ServiceName, span.OperationName)
  33. return
  34. }
  35. if span.GetTagString("peer.service") != "" {
  36. return
  37. }
  38. peerService, ok := p.detect(span.OperationName)
  39. if ok {
  40. span.SetTag("peer.service", peerService)
  41. span.SetTag("_auto.peer.service", true)
  42. return
  43. }
  44. if peerSign := span.StringTag("_peer.sign"); peerSign != "" {
  45. peerService, ok := p.detect(peerSign)
  46. if ok {
  47. span.SetTag("peer.service", peerService)
  48. span.SetTag("_auto.peer.service", true)
  49. }
  50. }
  51. }
  52. func (p *peerServiceDetect) Process(span *model.Span) error {
  53. p.process(span)
  54. return nil
  55. }
  56. // NewPeerServiceDetectProcesser .
  57. func NewPeerServiceDetectProcesser(data map[string]map[string]struct{}) Processer {
  58. p := &peerServiceDetect{pair: make(map[string]string)}
  59. for serviceName, operationNames := range data {
  60. for operationName := range operationNames {
  61. p.add(serviceName, operationName)
  62. }
  63. }
  64. return p
  65. }