observer.go 5.8 KB

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