observer.go 5.6 KB

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