observer.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. //go:build !confonly
  2. // +build !confonly
  3. package observatory
  4. import (
  5. "context"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "sort"
  10. "sync"
  11. "time"
  12. "github.com/v2fly/v2ray-core/v5/app/persistentstorage"
  13. "github.com/v2fly/v2ray-core/v5/app/persistentstorage/protostorage"
  14. "github.com/v2fly/v2ray-core/v5/common/environment"
  15. "github.com/v2fly/v2ray-core/v5/common/environment/envctx"
  16. "github.com/golang/protobuf/proto"
  17. core "github.com/v2fly/v2ray-core/v5"
  18. "github.com/v2fly/v2ray-core/v5/common"
  19. v2net "github.com/v2fly/v2ray-core/v5/common/net"
  20. "github.com/v2fly/v2ray-core/v5/common/session"
  21. "github.com/v2fly/v2ray-core/v5/common/signal/done"
  22. "github.com/v2fly/v2ray-core/v5/common/task"
  23. "github.com/v2fly/v2ray-core/v5/features/extension"
  24. "github.com/v2fly/v2ray-core/v5/features/outbound"
  25. "github.com/v2fly/v2ray-core/v5/transport/internet/tagged"
  26. )
  27. type Observer struct {
  28. config *Config
  29. ctx context.Context
  30. statusLock sync.Mutex
  31. status []*OutboundStatus
  32. finished *done.Instance
  33. ohm outbound.Manager
  34. persistStorage persistentstorage.ScopedPersistentStorage
  35. persistOutboundStatusProtoStorage protostorage.ProtoPersistentStorage
  36. }
  37. func (o *Observer) GetObservation(ctx context.Context) (proto.Message, error) {
  38. return &ObservationResult{Status: o.status}, nil
  39. }
  40. func (o *Observer) Type() interface{} {
  41. return extension.ObservatoryType()
  42. }
  43. func (o *Observer) Start() error {
  44. if o.config != nil && len(o.config.SubjectSelector) != 0 {
  45. if o.config.PersistentProbeResult {
  46. appEnvironment := envctx.EnvironmentFromContext(o.ctx).(environment.AppEnvironment)
  47. o.persistStorage = appEnvironment.PersistentStorage()
  48. outboundStatusStorage, err := o.persistStorage.NarrowScope(o.ctx, []byte("outbound_status"))
  49. if err != nil {
  50. return newError("failed to get persistent storage for outbound_status").Base(err)
  51. }
  52. o.persistOutboundStatusProtoStorage = outboundStatusStorage.(protostorage.ProtoPersistentStorage)
  53. list, err := outboundStatusStorage.List(o.ctx, []byte(""))
  54. if err != nil {
  55. newError("failed to list persisted outbound status").Base(err).WriteToLog()
  56. } else {
  57. for _, v := range list {
  58. o.loadOutboundStatus(string(v))
  59. }
  60. }
  61. }
  62. o.finished = done.New()
  63. go o.background()
  64. }
  65. return nil
  66. }
  67. func (o *Observer) Close() error {
  68. if o.finished != nil {
  69. return o.finished.Close()
  70. }
  71. return nil
  72. }
  73. func (o *Observer) background() {
  74. for !o.finished.Done() {
  75. hs, ok := o.ohm.(outbound.HandlerSelector)
  76. if !ok {
  77. newError("outbound.Manager is not a HandlerSelector").WriteToLog()
  78. return
  79. }
  80. outbounds := hs.Select(o.config.SubjectSelector)
  81. sort.Strings(outbounds)
  82. o.updateStatus(outbounds)
  83. slept := false
  84. for _, v := range outbounds {
  85. result := o.probe(v)
  86. o.updateStatusForResult(v, &result)
  87. if o.finished.Done() {
  88. return
  89. }
  90. sleepTime := time.Second * 10
  91. if o.config.ProbeInterval != 0 {
  92. sleepTime = time.Duration(o.config.ProbeInterval)
  93. }
  94. time.Sleep(sleepTime)
  95. slept = true
  96. }
  97. if !slept {
  98. sleepTime := time.Second * 10
  99. if o.config.ProbeInterval != 0 {
  100. sleepTime = time.Duration(o.config.ProbeInterval)
  101. }
  102. time.Sleep(sleepTime)
  103. }
  104. }
  105. }
  106. func (o *Observer) updateStatus(outbounds []string) {
  107. o.statusLock.Lock()
  108. defer o.statusLock.Unlock()
  109. // TODO should remove old inbound that is removed
  110. _ = outbounds
  111. }
  112. func (o *Observer) probe(outbound string) ProbeResult {
  113. errorCollectorForRequest := newErrorCollector()
  114. httpTransport := http.Transport{
  115. Proxy: func(*http.Request) (*url.URL, error) {
  116. return nil, nil
  117. },
  118. DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
  119. var connection net.Conn
  120. taskErr := task.Run(ctx, func() error {
  121. // MUST use V2Fly's built in context system
  122. dest, err := v2net.ParseDestination(network + ":" + addr)
  123. if err != nil {
  124. return newError("cannot understand address").Base(err)
  125. }
  126. trackedCtx := session.TrackedConnectionError(o.ctx, errorCollectorForRequest)
  127. conn, err := tagged.Dialer(trackedCtx, dest, outbound)
  128. if err != nil {
  129. return newError("cannot dial remote address ", dest).Base(err)
  130. }
  131. connection = conn
  132. return nil
  133. })
  134. if taskErr != nil {
  135. return nil, newError("cannot finish connection").Base(taskErr)
  136. }
  137. return connection, nil
  138. },
  139. TLSHandshakeTimeout: time.Second * 5,
  140. }
  141. httpClient := &http.Client{
  142. Transport: &httpTransport,
  143. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  144. return http.ErrUseLastResponse
  145. },
  146. Jar: nil,
  147. Timeout: time.Second * 5,
  148. }
  149. var GETTime time.Duration
  150. err := task.Run(o.ctx, func() error {
  151. startTime := time.Now()
  152. probeURL := "https://api.v2fly.org/checkConnection.svgz"
  153. if o.config.ProbeUrl != "" {
  154. probeURL = o.config.ProbeUrl
  155. }
  156. response, err := httpClient.Get(probeURL)
  157. if err != nil {
  158. return newError("outbound failed to relay connection").Base(err)
  159. }
  160. if response.Body != nil {
  161. response.Body.Close()
  162. }
  163. endTime := time.Now()
  164. GETTime = endTime.Sub(startTime)
  165. return nil
  166. })
  167. if err != nil {
  168. fullerr := newError("underlying connection failed").Base(errorCollectorForRequest.UnderlyingError())
  169. fullerr = newError("with outbound handler report").Base(fullerr)
  170. fullerr = newError("GET request failed:", err).Base(fullerr)
  171. fullerr = newError("the outbound ", outbound, " is dead:").Base(fullerr)
  172. fullerr = fullerr.AtInfo()
  173. fullerr.WriteToLog()
  174. return ProbeResult{Alive: false, LastErrorReason: fullerr.Error()}
  175. }
  176. newError("the outbound ", outbound, " is alive:", GETTime.Seconds()).AtInfo().WriteToLog()
  177. return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
  178. }
  179. func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
  180. o.statusLock.Lock()
  181. defer o.statusLock.Unlock()
  182. var status *OutboundStatus
  183. if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
  184. status = o.status[location]
  185. } else {
  186. status = &OutboundStatus{}
  187. o.status = append(o.status, status)
  188. }
  189. status.LastTryTime = time.Now().Unix()
  190. status.OutboundTag = outbound
  191. status.Alive = result.Alive
  192. if result.Alive {
  193. status.Delay = result.Delay
  194. status.LastSeenTime = status.LastTryTime
  195. status.LastErrorReason = ""
  196. } else {
  197. status.LastErrorReason = result.LastErrorReason
  198. status.Delay = 99999999
  199. }
  200. if o.config.PersistentProbeResult {
  201. err := o.persistOutboundStatusProtoStorage.PutProto(o.ctx, outbound, status)
  202. if err != nil {
  203. newError("failed to persist outbound status").Base(err).WriteToLog()
  204. }
  205. }
  206. }
  207. func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
  208. for i, v := range o.status {
  209. if v.OutboundTag == outbound {
  210. return i
  211. }
  212. }
  213. return -1
  214. }
  215. func (o *Observer) loadOutboundStatus(name string) {
  216. if o.persistOutboundStatusProtoStorage == nil {
  217. return
  218. }
  219. status := &OutboundStatus{}
  220. err := o.persistOutboundStatusProtoStorage.GetProto(o.ctx, name, status)
  221. if err != nil {
  222. newError("failed to load outbound status").Base(err).WriteToLog()
  223. return
  224. }
  225. o.status = append(o.status, status)
  226. }
  227. func New(ctx context.Context, config *Config) (*Observer, error) {
  228. obs := &Observer{
  229. config: config,
  230. ctx: ctx,
  231. }
  232. err := core.RequireFeatures(ctx, func(om outbound.Manager) {
  233. obs.ohm = om
  234. })
  235. if err != nil {
  236. return nil, newError("Cannot get depended features").Base(err)
  237. }
  238. return obs, nil
  239. }
  240. func init() {
  241. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  242. return New(ctx, config.(*Config))
  243. }))
  244. }