strategy_leastping.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //go:build !confonly
  2. // +build !confonly
  3. package router
  4. import (
  5. "context"
  6. core "github.com/v2fly/v2ray-core/v5"
  7. "github.com/v2fly/v2ray-core/v5/app/observatory"
  8. "github.com/v2fly/v2ray-core/v5/common"
  9. "github.com/v2fly/v2ray-core/v5/features"
  10. "github.com/v2fly/v2ray-core/v5/features/extension"
  11. )
  12. type LeastPingStrategy struct {
  13. ctx context.Context
  14. observatory extension.Observatory
  15. config *StrategyLeastPingConfig
  16. }
  17. func (l *LeastPingStrategy) GetPrincipleTarget(strings []string) []string {
  18. return []string{l.PickOutbound(strings)}
  19. }
  20. func (l *LeastPingStrategy) InjectContext(ctx context.Context) {
  21. l.ctx = ctx
  22. }
  23. func (l *LeastPingStrategy) PickOutbound(strings []string) string {
  24. if l.observatory == nil {
  25. common.Must(core.RequireFeatures(l.ctx, func(observatory extension.Observatory) error {
  26. if l.config.ObserverTag != "" {
  27. l.observatory = common.Must2(observatory.(features.TaggedFeatures).GetFeaturesByTag(l.config.ObserverTag)).(extension.Observatory)
  28. } else {
  29. l.observatory = observatory
  30. }
  31. return nil
  32. }))
  33. }
  34. if l.observatory == nil {
  35. newError("cannot find observatory").WriteToLog()
  36. return ""
  37. }
  38. observeReport, err := l.observatory.GetObservation(l.ctx)
  39. if err != nil {
  40. newError("cannot get observe report").Base(err).WriteToLog()
  41. return ""
  42. }
  43. outboundsList := outboundList(strings)
  44. if result, ok := observeReport.(*observatory.ObservationResult); ok {
  45. status := result.Status
  46. leastPing := int64(99999999)
  47. selectedOutboundName := ""
  48. for _, v := range status {
  49. if outboundsList.contains(v.OutboundTag) && v.Alive && v.Delay < leastPing {
  50. selectedOutboundName = v.OutboundTag
  51. leastPing = v.Delay
  52. }
  53. }
  54. return selectedOutboundName
  55. }
  56. // No way to understand observeReport
  57. return ""
  58. }
  59. type outboundList []string
  60. func (o outboundList) contains(name string) bool {
  61. for _, v := range o {
  62. if v == name {
  63. return true
  64. }
  65. }
  66. return false
  67. }
  68. func init() {
  69. common.Must(common.RegisterConfig((*StrategyLeastPingConfig)(nil), nil))
  70. }