strategy_leastping.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //go:build !confonly
  2. // +build !confonly
  3. package router
  4. import (
  5. "context"
  6. "github.com/v2fly/v2ray-core/v4/features"
  7. core "github.com/v2fly/v2ray-core/v4"
  8. "github.com/v2fly/v2ray-core/v4/app/observatory"
  9. "github.com/v2fly/v2ray-core/v4/common"
  10. "github.com/v2fly/v2ray-core/v4/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. observeReport, err := l.observatory.GetObservation(l.ctx)
  35. if err != nil {
  36. newError("cannot get observe report").Base(err).WriteToLog()
  37. return ""
  38. }
  39. outboundsList := outboundList(strings)
  40. if result, ok := observeReport.(*observatory.ObservationResult); ok {
  41. status := result.Status
  42. leastPing := int64(99999999)
  43. selectedOutboundName := ""
  44. for _, v := range status {
  45. if outboundsList.contains(v.OutboundTag) && v.Alive && v.Delay < leastPing {
  46. selectedOutboundName = v.OutboundTag
  47. leastPing = v.Delay
  48. }
  49. }
  50. return selectedOutboundName
  51. }
  52. // No way to understand observeReport
  53. return ""
  54. }
  55. type outboundList []string
  56. func (o outboundList) contains(name string) bool {
  57. for _, v := range o {
  58. if v == name {
  59. return true
  60. }
  61. }
  62. return false
  63. }
  64. func init() {
  65. common.Must(common.RegisterConfig((*StrategyLeastPingConfig)(nil), nil))
  66. }