strategy_leastping.go 1.8 KB

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