observer.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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/v4"
  14. "github.com/v2fly/v2ray-core/v4/common"
  15. v2net "github.com/v2fly/v2ray-core/v4/common/net"
  16. "github.com/v2fly/v2ray-core/v4/common/session"
  17. "github.com/v2fly/v2ray-core/v4/common/signal/done"
  18. "github.com/v2fly/v2ray-core/v4/common/task"
  19. "github.com/v2fly/v2ray-core/v4/features/extension"
  20. "github.com/v2fly/v2ray-core/v4/features/outbound"
  21. "github.com/v2fly/v2ray-core/v4/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. for _, v := range outbounds {
  61. result := o.probe(v)
  62. o.updateStatusForResult(v, &result)
  63. if o.finished.Done() {
  64. return
  65. }
  66. sleepTime := time.Second * 10
  67. if o.config.ProbeInterval != 0 {
  68. sleepTime = time.Duration(o.config.ProbeInterval)
  69. }
  70. time.Sleep(sleepTime)
  71. }
  72. }
  73. }
  74. func (o *Observer) updateStatus(outbounds []string) {
  75. o.statusLock.Lock()
  76. defer o.statusLock.Unlock()
  77. // TODO should remove old inbound that is removed
  78. _ = outbounds
  79. }
  80. func (o *Observer) probe(outbound string) ProbeResult {
  81. errorCollectorForRequest := newErrorCollector()
  82. httpTransport := http.Transport{
  83. Proxy: func(*http.Request) (*url.URL, error) {
  84. return nil, nil
  85. },
  86. DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
  87. var connection net.Conn
  88. taskErr := task.Run(ctx, func() error {
  89. // MUST use V2Fly's built in context system
  90. dest, err := v2net.ParseDestination(network + ":" + addr)
  91. if err != nil {
  92. return newError("cannot understand address").Base(err)
  93. }
  94. trackedCtx := session.TrackedConnectionError(o.ctx, errorCollectorForRequest)
  95. conn, err := tagged.Dialer(trackedCtx, dest, outbound)
  96. if err != nil {
  97. return newError("cannot dial remote address ", dest).Base(err)
  98. }
  99. connection = conn
  100. return nil
  101. })
  102. if taskErr != nil {
  103. return nil, newError("cannot finish connection").Base(taskErr)
  104. }
  105. return connection, nil
  106. },
  107. TLSHandshakeTimeout: time.Second * 5,
  108. }
  109. httpClient := &http.Client{
  110. Transport: &httpTransport,
  111. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  112. return http.ErrUseLastResponse
  113. },
  114. Jar: nil,
  115. Timeout: time.Second * 5,
  116. }
  117. var GETTime time.Duration
  118. err := task.Run(o.ctx, func() error {
  119. startTime := time.Now()
  120. probeURL := "https://api.v2fly.org/checkConnection.svgz"
  121. if o.config.ProbeUrl != "" {
  122. probeURL = o.config.ProbeUrl
  123. }
  124. response, err := httpClient.Get(probeURL)
  125. if err != nil {
  126. return newError("outbound failed to relay connection").Base(err)
  127. }
  128. if response.Body != nil {
  129. response.Body.Close()
  130. }
  131. endTime := time.Now()
  132. GETTime = endTime.Sub(startTime)
  133. return nil
  134. })
  135. if err != nil {
  136. fullerr := newError("underlying connection failed").Base(errorCollectorForRequest.UnderlyingError())
  137. fullerr = newError("with outbound handler report").Base(fullerr)
  138. fullerr = newError("GET request failed:", err).Base(fullerr)
  139. fullerr = newError("the outbound ", outbound, " is dead:").Base(fullerr)
  140. fullerr = fullerr.AtInfo()
  141. fullerr.WriteToLog()
  142. return ProbeResult{Alive: false, LastErrorReason: fullerr.Error()}
  143. }
  144. newError("the outbound ", outbound, " is alive:", GETTime.Seconds()).AtInfo().WriteToLog()
  145. return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
  146. }
  147. func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
  148. o.statusLock.Lock()
  149. defer o.statusLock.Unlock()
  150. var status *OutboundStatus
  151. if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
  152. status = o.status[location]
  153. } else {
  154. status = &OutboundStatus{}
  155. o.status = append(o.status, status)
  156. }
  157. status.LastTryTime = time.Now().Unix()
  158. status.OutboundTag = outbound
  159. status.Alive = result.Alive
  160. if result.Alive {
  161. status.Delay = result.Delay
  162. status.LastSeenTime = status.LastTryTime
  163. status.LastErrorReason = ""
  164. } else {
  165. status.LastErrorReason = result.LastErrorReason
  166. status.Delay = 99999999
  167. }
  168. }
  169. func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
  170. for i, v := range o.status {
  171. if v.OutboundTag == outbound {
  172. return i
  173. }
  174. }
  175. return -1
  176. }
  177. func New(ctx context.Context, config *Config) (*Observer, error) {
  178. var outboundManager outbound.Manager
  179. err := core.RequireFeatures(ctx, func(om outbound.Manager) {
  180. outboundManager = om
  181. })
  182. if err != nil {
  183. return nil, newError("Cannot get depended features").Base(err)
  184. }
  185. return &Observer{
  186. config: config,
  187. ctx: ctx,
  188. ohm: outboundManager,
  189. }, nil
  190. }
  191. func init() {
  192. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  193. return New(ctx, config.(*Config))
  194. }))
  195. }