strategy_leastping.go 1.4 KB

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