observer.go 5.4 KB

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