observer.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // +build !confonly
  2. package observatory
  3. import (
  4. "context"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "sync"
  9. "time"
  10. "github.com/golang/protobuf/proto"
  11. core "github.com/v2fly/v2ray-core/v4"
  12. "github.com/v2fly/v2ray-core/v4/common"
  13. v2net "github.com/v2fly/v2ray-core/v4/common/net"
  14. "github.com/v2fly/v2ray-core/v4/common/session"
  15. "github.com/v2fly/v2ray-core/v4/common/signal/done"
  16. "github.com/v2fly/v2ray-core/v4/common/task"
  17. "github.com/v2fly/v2ray-core/v4/features/extension"
  18. "github.com/v2fly/v2ray-core/v4/features/outbound"
  19. "github.com/v2fly/v2ray-core/v4/transport/internet/tagged"
  20. )
  21. type Observer struct {
  22. config *Config
  23. ctx context.Context
  24. statusLock sync.Mutex
  25. status []*OutboundStatus
  26. finished *done.Instance
  27. ohm outbound.Manager
  28. }
  29. func (o *Observer) GetObservation(ctx context.Context) (proto.Message, error) {
  30. return &ObservationResult{Status: o.status}, nil
  31. }
  32. func (o *Observer) Type() interface{} {
  33. return extension.ObservatoryType()
  34. }
  35. func (o *Observer) Start() error {
  36. o.finished = done.New()
  37. go o.background()
  38. return nil
  39. }
  40. func (o *Observer) Close() error {
  41. return o.finished.Close()
  42. }
  43. func (o *Observer) background() {
  44. for !o.finished.Done() {
  45. hs, ok := o.ohm.(outbound.HandlerSelector)
  46. if !ok {
  47. newError("outbound.Manager is not a HandlerSelector").WriteToLog()
  48. return
  49. }
  50. outbounds := hs.Select(o.config.SubjectSelector)
  51. o.updateStatus(outbounds)
  52. for _, v := range outbounds {
  53. result := o.probe(v)
  54. o.updateStatusForResult(v, &result)
  55. if o.finished.Done() {
  56. return
  57. }
  58. time.Sleep(time.Second * 10)
  59. }
  60. }
  61. }
  62. func (o *Observer) updateStatus(outbounds []string) {
  63. o.statusLock.Lock()
  64. defer o.statusLock.Unlock()
  65. // TODO should remove old inbound that is removed
  66. _ = outbounds
  67. }
  68. func (o *Observer) probe(outbound string) ProbeResult {
  69. errorCollectorForRequest := newErrorCollector()
  70. httpTransport := http.Transport{
  71. Proxy: func(*http.Request) (*url.URL, error) {
  72. return nil, nil
  73. },
  74. DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
  75. var connection net.Conn
  76. taskErr := task.Run(ctx, func() error {
  77. // MUST use V2Fly's built in context system
  78. dest, err := v2net.ParseDestination(network + ":" + addr)
  79. if err != nil {
  80. return newError("cannot understand address").Base(err)
  81. }
  82. trackedCtx := session.TrackedConnectionError(o.ctx, errorCollectorForRequest)
  83. conn, err := tagged.Dialer(trackedCtx, dest, outbound)
  84. if err != nil {
  85. return newError("cannot dial remote address", dest).Base(err)
  86. }
  87. connection = conn
  88. return nil
  89. })
  90. if taskErr != nil {
  91. return nil, newError("cannot finish connection").Base(taskErr)
  92. }
  93. return connection, nil
  94. },
  95. TLSHandshakeTimeout: time.Second * 5,
  96. }
  97. httpClient := &http.Client{
  98. Transport: &httpTransport,
  99. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  100. return http.ErrUseLastResponse
  101. },
  102. Jar: nil,
  103. Timeout: time.Second * 5,
  104. }
  105. var GETTime time.Duration
  106. err := task.Run(o.ctx, func() error {
  107. startTime := time.Now()
  108. response, err := httpClient.Get("https://api.v2fly.org/checkConnection.svgz")
  109. if err != nil {
  110. return newError("outbound failed to relay connection").Base(err)
  111. }
  112. if response.Body != nil {
  113. response.Body.Close()
  114. }
  115. endTime := time.Now()
  116. GETTime = endTime.Sub(startTime)
  117. return nil
  118. })
  119. if err != nil {
  120. fullerr := newError("underlying connection failed").Base(errorCollectorForRequest.UnderlyingError())
  121. fullerr = newError("with outbound handler report").Base(fullerr)
  122. fullerr = newError("GET request failed:", err).Base(fullerr)
  123. fullerr = newError("the outbound ", outbound, "is dead:").Base(fullerr)
  124. fullerr = fullerr.AtInfo()
  125. fullerr.WriteToLog()
  126. return ProbeResult{Alive: false, LastErrorReason: fullerr.Error()}
  127. }
  128. newError("the outbound ", outbound, "is alive:", GETTime.Seconds()).AtInfo().WriteToLog()
  129. return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
  130. }
  131. func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
  132. o.statusLock.Lock()
  133. defer o.statusLock.Unlock()
  134. var status *OutboundStatus
  135. if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
  136. status = o.status[location]
  137. } else {
  138. status = &OutboundStatus{}
  139. o.status = append(o.status, status)
  140. }
  141. status.LastTryTime = time.Now().Unix()
  142. status.OutboundTag = outbound
  143. status.Alive = result.Alive
  144. if result.Alive {
  145. status.Delay = result.Delay
  146. status.LastSeenTime = status.LastTryTime
  147. status.LastErrorReason = ""
  148. } else {
  149. status.LastErrorReason = result.LastErrorReason
  150. status.Delay = 99999999
  151. }
  152. }
  153. func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
  154. for i, v := range o.status {
  155. if v.OutboundTag == outbound {
  156. return i
  157. }
  158. }
  159. return -1
  160. }
  161. func New(ctx context.Context, config *Config) (*Observer, error) {
  162. var outboundManager outbound.Manager
  163. err := core.RequireFeatures(ctx, func(om outbound.Manager) {
  164. outboundManager = om
  165. })
  166. if err != nil {
  167. return nil, newError("Cannot get depended features").Base(err)
  168. }
  169. return &Observer{
  170. config: config,
  171. ctx: ctx,
  172. ohm: outboundManager,
  173. }, nil
  174. }
  175. func init() {
  176. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  177. return New(ctx, config.(*Config))
  178. }))
  179. }