observer.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. probeURL := "https://api.v2fly.org/checkConnection.svgz"
  114. if o.config.ProbeUrl != "" {
  115. probeURL = o.config.ProbeUrl
  116. }
  117. response, err := httpClient.Get(probeURL)
  118. if err != nil {
  119. return newError("outbound failed to relay connection").Base(err)
  120. }
  121. if response.Body != nil {
  122. response.Body.Close()
  123. }
  124. endTime := time.Now()
  125. GETTime = endTime.Sub(startTime)
  126. return nil
  127. })
  128. if err != nil {
  129. fullerr := newError("underlying connection failed").Base(errorCollectorForRequest.UnderlyingError())
  130. fullerr = newError("with outbound handler report").Base(fullerr)
  131. fullerr = newError("GET request failed:", err).Base(fullerr)
  132. fullerr = newError("the outbound ", outbound, "is dead:").Base(fullerr)
  133. fullerr = fullerr.AtInfo()
  134. fullerr.WriteToLog()
  135. return ProbeResult{Alive: false, LastErrorReason: fullerr.Error()}
  136. }
  137. newError("the outbound ", outbound, "is alive:", GETTime.Seconds()).AtInfo().WriteToLog()
  138. return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
  139. }
  140. func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
  141. o.statusLock.Lock()
  142. defer o.statusLock.Unlock()
  143. var status *OutboundStatus
  144. if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
  145. status = o.status[location]
  146. } else {
  147. status = &OutboundStatus{}
  148. o.status = append(o.status, status)
  149. }
  150. status.LastTryTime = time.Now().Unix()
  151. status.OutboundTag = outbound
  152. status.Alive = result.Alive
  153. if result.Alive {
  154. status.Delay = result.Delay
  155. status.LastSeenTime = status.LastTryTime
  156. status.LastErrorReason = ""
  157. } else {
  158. status.LastErrorReason = result.LastErrorReason
  159. status.Delay = 99999999
  160. }
  161. }
  162. func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
  163. for i, v := range o.status {
  164. if v.OutboundTag == outbound {
  165. return i
  166. }
  167. }
  168. return -1
  169. }
  170. func New(ctx context.Context, config *Config) (*Observer, error) {
  171. var outboundManager outbound.Manager
  172. err := core.RequireFeatures(ctx, func(om outbound.Manager) {
  173. outboundManager = om
  174. })
  175. if err != nil {
  176. return nil, newError("Cannot get depended features").Base(err)
  177. }
  178. return &Observer{
  179. config: config,
  180. ctx: ctx,
  181. ohm: outboundManager,
  182. }, nil
  183. }
  184. func init() {
  185. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  186. return New(ctx, config.(*Config))
  187. }))
  188. }