observer.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package observatory
  2. import (
  3. "context"
  4. "github.com/golang/protobuf/proto"
  5. core "github.com/v2fly/v2ray-core/v4"
  6. "github.com/v2fly/v2ray-core/v4/common"
  7. v2net "github.com/v2fly/v2ray-core/v4/common/net"
  8. "github.com/v2fly/v2ray-core/v4/common/signal/done"
  9. "github.com/v2fly/v2ray-core/v4/common/task"
  10. "github.com/v2fly/v2ray-core/v4/features/extension"
  11. "github.com/v2fly/v2ray-core/v4/features/outbound"
  12. "github.com/v2fly/v2ray-core/v4/transport/internet/tagged"
  13. "net"
  14. "net/http"
  15. "net/url"
  16. "sync"
  17. "time"
  18. )
  19. type Observer struct {
  20. config *Config
  21. ctx context.Context
  22. statusLock sync.Mutex
  23. status []*OutboundStatus
  24. finished *done.Instance
  25. ohm outbound.Manager
  26. }
  27. func (o *Observer) GetObservation(ctx context.Context) (proto.Message, error) {
  28. return &ObservationResult{Status: o.status}, nil
  29. }
  30. func (o *Observer) Type() interface{} {
  31. return extension.ObservatoryType()
  32. }
  33. func (o *Observer) Start() error {
  34. o.finished = done.New()
  35. go o.background()
  36. return nil
  37. }
  38. func (o *Observer) Close() error {
  39. return o.finished.Close()
  40. }
  41. func (o *Observer) background() {
  42. for !o.finished.Done() {
  43. hs, ok := o.ohm.(outbound.HandlerSelector)
  44. if !ok {
  45. newError("outbound.Manager is not a HandlerSelector").WriteToLog()
  46. return
  47. }
  48. outbounds := hs.Select(o.config.SubjectSelector)
  49. o.updateStatus(outbounds)
  50. for _, v := range outbounds {
  51. result := o.probe(v)
  52. o.updateStatusForResult(v, &result)
  53. if o.finished.Done() {
  54. return
  55. }
  56. time.Sleep(time.Second * 10)
  57. }
  58. }
  59. }
  60. func (o *Observer) updateStatus(outbounds []string) {
  61. o.statusLock.Lock()
  62. defer o.statusLock.Unlock()
  63. //TODO should remove old inbound that is removed
  64. }
  65. func (o *Observer) probe(outbound string) ProbeResult {
  66. httpTransport := http.Transport{
  67. Proxy: func(*http.Request) (*url.URL, error) {
  68. return nil, nil
  69. },
  70. DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
  71. var connection net.Conn
  72. taskErr := task.Run(ctx, func() error {
  73. //MUST use V2Fly's built in context system
  74. dest, err := v2net.ParseDestination(network + ":" + addr)
  75. if err != nil {
  76. return newError("cannot understand address").Base(err)
  77. }
  78. conn, err := tagged.Dialer(o.ctx, dest, outbound)
  79. if err != nil {
  80. return newError("cannot dial remote address", dest).Base(err)
  81. }
  82. connection = conn
  83. return nil
  84. })
  85. if taskErr != nil {
  86. return nil, newError("cannot finish connection").Base(taskErr)
  87. }
  88. return connection, nil
  89. },
  90. TLSHandshakeTimeout: time.Duration(time.Second * 5),
  91. }
  92. httpClient := &http.Client{
  93. Transport: &httpTransport,
  94. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  95. return http.ErrUseLastResponse
  96. },
  97. Jar: nil,
  98. Timeout: time.Duration(time.Second * 5),
  99. }
  100. var GETTime time.Duration
  101. err := task.Run(o.ctx, func() error {
  102. startTime := time.Now()
  103. response, err := httpClient.Get("https://api.v2fly.org/checkConnection.svgz")
  104. if err != nil {
  105. return newError("outbound failed to relay connection").Base(err)
  106. }
  107. if response.Body != nil {
  108. response.Body.Close()
  109. }
  110. endTime := time.Now()
  111. GETTime = endTime.Sub(startTime)
  112. return nil
  113. })
  114. if err != nil {
  115. newError("the outbound ", outbound, "is dead:").Base(err).AtInfo().WriteToLog()
  116. return ProbeResult{Alive: false, LastErrorReason: err.Error()}
  117. }
  118. newError("the outbound ", outbound, "is alive:", GETTime.Seconds()).AtInfo().WriteToLog()
  119. return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
  120. }
  121. func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
  122. o.statusLock.Lock()
  123. defer o.statusLock.Unlock()
  124. var status *OutboundStatus
  125. if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
  126. status = o.status[location]
  127. } else {
  128. status = &OutboundStatus{}
  129. o.status = append(o.status, status)
  130. }
  131. status.LastTryTime = time.Now().Unix()
  132. status.OutboundTag = outbound
  133. status.Alive = result.Alive
  134. if result.Alive {
  135. status.Delay = result.Delay
  136. status.LastSeenTime = status.LastTryTime
  137. status.LastErrorReason = ""
  138. } else {
  139. status.LastErrorReason = result.LastErrorReason
  140. status.Delay = 99999999
  141. }
  142. }
  143. func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
  144. for i, v := range o.status {
  145. if v.OutboundTag == outbound {
  146. return i
  147. }
  148. }
  149. return -1
  150. }
  151. func New(ctx context.Context, config *Config) (*Observer, error) {
  152. var outboundManager outbound.Manager
  153. err := core.RequireFeatures(ctx, func(om outbound.Manager) {
  154. outboundManager = om
  155. })
  156. if err != nil {
  157. return nil, newError("Cannot get depended features").Base(err)
  158. }
  159. return &Observer{
  160. config: config,
  161. ctx: ctx,
  162. ohm: outboundManager,
  163. }, nil
  164. }
  165. func init() {
  166. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  167. return New(ctx, config.(*Config))
  168. }))
  169. }