observer.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package observatory
  2. import (
  3. "context"
  4. "net"
  5. "net/http"
  6. "net/url"
  7. "sort"
  8. "sync"
  9. "time"
  10. "github.com/xtls/xray-core/common"
  11. "github.com/xtls/xray-core/common/errors"
  12. v2net "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/session"
  14. "github.com/xtls/xray-core/common/signal/done"
  15. "github.com/xtls/xray-core/common/task"
  16. "github.com/xtls/xray-core/core"
  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. "google.golang.org/protobuf/proto"
  21. )
  22. type Observer struct {
  23. config *Config
  24. ctx context.Context
  25. statusLock sync.Mutex
  26. status []*OutboundStatus
  27. finished *done.Instance
  28. ohm outbound.Manager
  29. }
  30. func (o *Observer) GetObservation(ctx context.Context) (proto.Message, error) {
  31. return &ObservationResult{Status: o.status}, nil
  32. }
  33. func (o *Observer) Type() interface{} {
  34. return extension.ObservatoryType()
  35. }
  36. func (o *Observer) Start() error {
  37. if o.config != nil && len(o.config.SubjectSelector) != 0 {
  38. o.finished = done.New()
  39. go o.background()
  40. }
  41. return nil
  42. }
  43. func (o *Observer) Close() error {
  44. if o.finished != nil {
  45. return o.finished.Close()
  46. }
  47. return nil
  48. }
  49. func (o *Observer) background() {
  50. for !o.finished.Done() {
  51. hs, ok := o.ohm.(outbound.HandlerSelector)
  52. if !ok {
  53. errors.LogInfo(o.ctx, "outbound.Manager is not a HandlerSelector")
  54. return
  55. }
  56. outbounds := hs.Select(o.config.SubjectSelector)
  57. o.updateStatus(outbounds)
  58. sleepTime := time.Second * 10
  59. if o.config.ProbeInterval != 0 {
  60. sleepTime = time.Duration(o.config.ProbeInterval)
  61. }
  62. if !o.config.EnableConcurrency {
  63. sort.Strings(outbounds)
  64. for _, v := range outbounds {
  65. result := o.probe(v)
  66. o.updateStatusForResult(v, &result)
  67. if o.finished.Done() {
  68. return
  69. }
  70. time.Sleep(sleepTime)
  71. }
  72. continue
  73. }
  74. ch := make(chan struct{}, len(outbounds))
  75. for _, v := range outbounds {
  76. go func(v string) {
  77. result := o.probe(v)
  78. o.updateStatusForResult(v, &result)
  79. ch <- struct{}{}
  80. }(v)
  81. }
  82. for range outbounds {
  83. select {
  84. case <-ch:
  85. case <-o.finished.Wait():
  86. return
  87. }
  88. }
  89. time.Sleep(sleepTime)
  90. }
  91. }
  92. func (o *Observer) updateStatus(outbounds []string) {
  93. o.statusLock.Lock()
  94. defer o.statusLock.Unlock()
  95. // TODO should remove old inbound that is removed
  96. _ = outbounds
  97. }
  98. func (o *Observer) probe(outbound string) ProbeResult {
  99. errorCollectorForRequest := newErrorCollector()
  100. httpTransport := http.Transport{
  101. Proxy: func(*http.Request) (*url.URL, error) {
  102. return nil, nil
  103. },
  104. DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
  105. var connection net.Conn
  106. taskErr := task.Run(ctx, func() error {
  107. // MUST use Xray's built in context system
  108. dest, err := v2net.ParseDestination(network + ":" + addr)
  109. if err != nil {
  110. return errors.New("cannot understand address").Base(err)
  111. }
  112. trackedCtx := session.TrackedConnectionError(o.ctx, errorCollectorForRequest)
  113. conn, err := tagged.Dialer(trackedCtx, dest, outbound)
  114. if err != nil {
  115. return errors.New("cannot dial remote address ", dest).Base(err)
  116. }
  117. connection = conn
  118. return nil
  119. })
  120. if taskErr != nil {
  121. return nil, errors.New("cannot finish connection").Base(taskErr)
  122. }
  123. return connection, nil
  124. },
  125. TLSHandshakeTimeout: time.Second * 5,
  126. }
  127. httpClient := &http.Client{
  128. Transport: &httpTransport,
  129. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  130. return http.ErrUseLastResponse
  131. },
  132. Jar: nil,
  133. Timeout: time.Second * 5,
  134. }
  135. var GETTime time.Duration
  136. err := task.Run(o.ctx, func() error {
  137. startTime := time.Now()
  138. probeURL := "https://www.google.com/generate_204"
  139. if o.config.ProbeUrl != "" {
  140. probeURL = o.config.ProbeUrl
  141. }
  142. response, err := httpClient.Get(probeURL)
  143. if err != nil {
  144. return errors.New("outbound failed to relay connection").Base(err)
  145. }
  146. if response.Body != nil {
  147. response.Body.Close()
  148. }
  149. endTime := time.Now()
  150. GETTime = endTime.Sub(startTime)
  151. return nil
  152. })
  153. if err != nil {
  154. var errorMessage = "the outbound " + outbound + " is dead: GET request failed:" + err.Error() + "with outbound handler report underlying connection failed"
  155. errors.LogInfoInner(o.ctx, errorCollectorForRequest.UnderlyingError(), errorMessage)
  156. return ProbeResult{Alive: false, LastErrorReason: errorMessage}
  157. }
  158. errors.LogInfo(o.ctx, "the outbound ", outbound, " is alive:", GETTime.Seconds())
  159. return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
  160. }
  161. func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
  162. o.statusLock.Lock()
  163. defer o.statusLock.Unlock()
  164. var status *OutboundStatus
  165. if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
  166. status = o.status[location]
  167. } else {
  168. status = &OutboundStatus{}
  169. o.status = append(o.status, status)
  170. }
  171. status.LastTryTime = time.Now().Unix()
  172. status.OutboundTag = outbound
  173. status.Alive = result.Alive
  174. if result.Alive {
  175. status.Delay = result.Delay
  176. status.LastSeenTime = status.LastTryTime
  177. status.LastErrorReason = ""
  178. } else {
  179. status.LastErrorReason = result.LastErrorReason
  180. status.Delay = 99999999
  181. }
  182. }
  183. func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
  184. for i, v := range o.status {
  185. if v.OutboundTag == outbound {
  186. return i
  187. }
  188. }
  189. return -1
  190. }
  191. func New(ctx context.Context, config *Config) (*Observer, error) {
  192. var outboundManager outbound.Manager
  193. err := core.RequireFeatures(ctx, func(om outbound.Manager) {
  194. outboundManager = om
  195. })
  196. if err != nil {
  197. return nil, errors.New("Cannot get depended features").Base(err)
  198. }
  199. return &Observer{
  200. config: config,
  201. ctx: ctx,
  202. ohm: outboundManager,
  203. }, nil
  204. }
  205. func init() {
  206. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  207. return New(ctx, config.(*Config))
  208. }))
  209. }