observer.go 5.5 KB

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