observer.go 6.0 KB

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