observer.go 5.9 KB

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