Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package stats
  2. import (
  3. "fmt"
  4. "net"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/9seconds/mtg/config"
  10. "github.com/9seconds/mtg/conntypes"
  11. statsd "github.com/smira/go-statsd"
  12. "go.uber.org/zap"
  13. )
  14. var (
  15. tagTrafficIngress = &statsStatsdTag{
  16. name: "ingress",
  17. tag: statsd.StringTag("type", "ingress"),
  18. }
  19. tagTrafficEgress = &statsStatsdTag{
  20. name: "egress",
  21. tag: statsd.StringTag("type", "egress"),
  22. }
  23. tagConnectionTypeAbridged = &statsStatsdTag{
  24. name: "abridged",
  25. tag: statsd.StringTag("type", "abridged"),
  26. }
  27. tagConnectionTypeIntermediate = &statsStatsdTag{
  28. name: "intermediate",
  29. tag: statsd.StringTag("type", "intermediate"),
  30. }
  31. tagConnectionTypeSecured = &statsStatsdTag{
  32. name: "secured",
  33. tag: statsd.StringTag("type", "secured"),
  34. }
  35. tagConnectionProtocol4 = &statsStatsdTag{
  36. name: "ipv4",
  37. tag: statsd.StringTag("protocol", "ipv4"),
  38. }
  39. tagConnectionProtocol6 = &statsStatsdTag{
  40. name: "ipv6",
  41. tag: statsd.StringTag("protocol", "ipv6"),
  42. }
  43. )
  44. type statsStatsdTag struct {
  45. tag statsd.Tag
  46. name string
  47. }
  48. type statsStatsdLogger struct {
  49. log *zap.SugaredLogger
  50. }
  51. func (s statsStatsdLogger) Printf(msg string, args ...interface{}) {
  52. s.log.Debugw(fmt.Sprintf(msg, args...))
  53. }
  54. type statsStatsd struct {
  55. seen map[string]struct{}
  56. seenMutex sync.RWMutex
  57. client *statsd.Client
  58. }
  59. func (s *statsStatsd) IngressTraffic(traffic int) {
  60. s.gauge("traffic", int64(traffic), tagTrafficIngress)
  61. }
  62. func (s *statsStatsd) EgressTraffic(traffic int) {
  63. s.gauge("traffic", int64(traffic), tagTrafficEgress)
  64. }
  65. func (s *statsStatsd) ClientConnected(connectionType conntypes.ConnectionType, addr *net.TCPAddr) {
  66. s.changeConnections(connectionType, addr, 1)
  67. }
  68. func (s *statsStatsd) ClientDisconnected(connectionType conntypes.ConnectionType, addr *net.TCPAddr) {
  69. s.changeConnections(connectionType, addr, -1)
  70. }
  71. func (s *statsStatsd) changeConnections(connectionType conntypes.ConnectionType, addr *net.TCPAddr, increment int64) {
  72. tags := make([]*statsStatsdTag, 0, 2) //nolint: gomnd
  73. switch connectionType {
  74. case conntypes.ConnectionTypeAbridged:
  75. tags = append(tags, tagConnectionTypeAbridged)
  76. case conntypes.ConnectionTypeIntermediate:
  77. tags = append(tags, tagConnectionTypeIntermediate)
  78. case conntypes.ConnectionTypeSecure:
  79. tags = append(tags, tagConnectionTypeSecured)
  80. case conntypes.ConnectionTypeUnknown:
  81. panic("Unknown connection type")
  82. }
  83. if addr.IP.To4() == nil {
  84. tags = append(tags, tagConnectionProtocol6)
  85. } else {
  86. tags = append(tags, tagConnectionProtocol4)
  87. }
  88. s.gauge("connections", increment, tags...)
  89. }
  90. func (s *statsStatsd) TelegramConnected(dc conntypes.DC, addr *net.TCPAddr) {
  91. s.changeTelegramConnections(dc, addr, 1)
  92. }
  93. func (s *statsStatsd) TelegramDisconnected(dc conntypes.DC, addr *net.TCPAddr) {
  94. s.changeTelegramConnections(dc, addr, -1)
  95. }
  96. func (s *statsStatsd) changeTelegramConnections(dc conntypes.DC, addr *net.TCPAddr, increment int64) {
  97. tags := []*statsStatsdTag{
  98. {
  99. name: "dc" + strconv.Itoa(int(dc)),
  100. tag: statsd.IntTag("dc", int(dc)),
  101. },
  102. }
  103. if addr.IP.To4() == nil {
  104. tags = append(tags, tagConnectionProtocol6)
  105. } else {
  106. tags = append(tags, tagConnectionProtocol4)
  107. }
  108. s.gauge("telegram_connections", increment, tags...)
  109. }
  110. func (s *statsStatsd) Crash() {
  111. s.gauge("crashes", 1)
  112. }
  113. func (s *statsStatsd) ReplayDetected() {
  114. s.gauge("replay_attacks", 1)
  115. }
  116. func (s *statsStatsd) AuthenticationFailed() {
  117. s.gauge("authentication_failed", 1)
  118. }
  119. func (s *statsStatsd) CloakedRequest() {
  120. s.gauge("cloaked_requests", 1)
  121. }
  122. func (s *statsStatsd) gauge(metric string, value int64, tags ...*statsStatsdTag) {
  123. key, tagList := s.prepareVals(metric, tags)
  124. s.initGauge(metric, key, tagList)
  125. s.client.GaugeDelta(metric, value, tagList...)
  126. }
  127. func (s *statsStatsd) prepareVals(metric string, tags []*statsStatsdTag) (string, []statsd.Tag) {
  128. tagList := make([]statsd.Tag, len(tags))
  129. builder := strings.Builder{}
  130. builder.WriteString(metric)
  131. for i, v := range tags {
  132. builder.WriteRune('.')
  133. builder.WriteString(v.name)
  134. tagList[i] = v.tag
  135. }
  136. return builder.String(), tagList
  137. }
  138. func (s *statsStatsd) initGauge(metric, key string, tags []statsd.Tag) {
  139. s.seenMutex.RLock()
  140. if _, ok := s.seen[key]; ok {
  141. s.seenMutex.RUnlock()
  142. return
  143. } else { //nolint: golint,revive
  144. s.seenMutex.RUnlock()
  145. }
  146. s.seenMutex.Lock()
  147. defer s.seenMutex.Unlock()
  148. if _, ok := s.seen[key]; !ok {
  149. s.seen[key] = struct{}{}
  150. s.client.Gauge(metric, 0, tags...)
  151. }
  152. }
  153. func newStatsStatsd() Interface {
  154. prefix := strings.TrimSuffix(config.C.StatsNamespace, ".") + "."
  155. logger := statsStatsdLogger{
  156. log: zap.S().Named("stats").Named("statsd"),
  157. }
  158. return &statsStatsd{
  159. seen: make(map[string]struct{}),
  160. client: statsd.NewClient(config.C.StatsdAddr.String(),
  161. statsd.SendLoopCount(2), //nolint: gomnd
  162. statsd.ReconnectInterval(10*time.Second), //nolint: gomnd
  163. statsd.Logger(logger),
  164. statsd.MetricPrefix(prefix),
  165. statsd.TagStyle(config.C.StatsdTagsFormat),
  166. ),
  167. }
  168. }