observer.go 4.8 KB

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