observer.go 5.3 KB

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