You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

StatisticsStrategy.cs 6.0 kB

10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading;
  6. using Newtonsoft.Json;
  7. using Shadowsocks.Model;
  8. namespace Shadowsocks.Controller.Strategy
  9. {
  10. using Statistics = Dictionary<string, List<StatisticsRecord>>;
  11. internal class StatisticsStrategy : IStrategy, IDisposable
  12. {
  13. private readonly ShadowsocksController _controller;
  14. private Server _currentServer;
  15. private readonly Timer _timer;
  16. private Statistics _filteredStatistics;
  17. private AvailabilityStatistics Service => _controller.availabilityStatistics;
  18. private int ChoiceKeptMilliseconds
  19. => (int)TimeSpan.FromMinutes(_controller.StatisticsConfiguration.ChoiceKeptMinutes).TotalMilliseconds;
  20. public StatisticsStrategy(ShadowsocksController controller)
  21. {
  22. _controller = controller;
  23. var servers = controller.GetCurrentConfiguration().configs;
  24. var randomIndex = new Random().Next() % servers.Count;
  25. _currentServer = servers[randomIndex]; //choose a server randomly at first
  26. _timer = new Timer(ReloadStatisticsAndChooseAServer);
  27. }
  28. private void ReloadStatisticsAndChooseAServer(object obj)
  29. {
  30. Logging.Debug("Reloading statistics and choose a new server....");
  31. var servers = _controller.GetCurrentConfiguration().configs;
  32. LoadStatistics();
  33. ChooseNewServer(servers);
  34. }
  35. private void LoadStatistics()
  36. {
  37. _filteredStatistics =
  38. Service.FilteredStatistics ??
  39. Service.RawStatistics ??
  40. _filteredStatistics;
  41. }
  42. //return the score by data
  43. //server with highest score will be choosen
  44. private float? GetScore(string identifier, List<StatisticsRecord> records)
  45. {
  46. var config = _controller.StatisticsConfiguration;
  47. float? score = null;
  48. var averageRecord = new StatisticsRecord(identifier,
  49. records.Where(record => record.MaxInboundSpeed != null).Select(record => record.MaxInboundSpeed.Value).ToList(),
  50. records.Where(record => record.MaxOutboundSpeed != null).Select(record => record.MaxOutboundSpeed.Value).ToList(),
  51. records.Where(record => record.AverageLatency != null).Select(record => record.AverageLatency.Value).ToList());
  52. averageRecord.SetResponse(records.Select(record => record.AverageResponse).ToList());
  53. foreach (var calculation in config.Calculations)
  54. {
  55. var name = calculation.Key;
  56. var field = typeof (StatisticsRecord).GetField(name);
  57. dynamic value = field?.GetValue(averageRecord);
  58. var factor = calculation.Value;
  59. if (value == null || factor.Equals(0)) continue;
  60. score = score ?? 0;
  61. score += value * factor;
  62. }
  63. if (score != null)
  64. {
  65. Logging.Debug($"Highest score: {score} {JsonConvert.SerializeObject(averageRecord, Formatting.Indented)}");
  66. }
  67. return score;
  68. }
  69. private void ChooseNewServer(List<Server> servers)
  70. {
  71. if (_filteredStatistics == null || servers.Count == 0)
  72. {
  73. return;
  74. }
  75. try
  76. {
  77. var serversWithStatistics = (from server in servers
  78. let id = server.Identifier()
  79. where _filteredStatistics.ContainsKey(id)
  80. let score = GetScore(server.Identifier(), _filteredStatistics[server.Identifier()])
  81. where score != null
  82. select new
  83. {
  84. server,
  85. score
  86. }).ToArray();
  87. if (serversWithStatistics.Length < 2)
  88. {
  89. LogWhenEnabled("no enough statistics data or all factors in calculations are 0");
  90. return;
  91. }
  92. var bestResult = serversWithStatistics
  93. .Aggregate((server1, server2) => server1.score > server2.score ? server1 : server2);
  94. LogWhenEnabled($"Switch to server: {bestResult.server.FriendlyName()} by statistics: score {bestResult.score}");
  95. _currentServer = bestResult.server;
  96. }
  97. catch (Exception e)
  98. {
  99. Logging.LogUsefulException(e);
  100. }
  101. }
  102. private void LogWhenEnabled(string log)
  103. {
  104. if (_controller.GetCurrentStrategy()?.ID == ID) //output when enabled
  105. {
  106. Console.WriteLine(log);
  107. }
  108. }
  109. public string ID => "com.shadowsocks.strategy.scbs";
  110. public string Name => I18N.GetString("Choose by statistics");
  111. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
  112. {
  113. if (_currentServer == null)
  114. {
  115. ChooseNewServer(_controller.GetCurrentConfiguration().configs);
  116. }
  117. return _currentServer; //current server cached for CachedInterval
  118. }
  119. public void ReloadServers()
  120. {
  121. ChooseNewServer(_controller.GetCurrentConfiguration().configs);
  122. _timer?.Change(0, ChoiceKeptMilliseconds);
  123. }
  124. public void SetFailure(Server server)
  125. {
  126. Logging.Debug($"failure: {server.FriendlyName()}");
  127. }
  128. public void UpdateLastRead(Server server)
  129. {
  130. }
  131. public void UpdateLastWrite(Server server)
  132. {
  133. }
  134. public void UpdateLatency(Server server, TimeSpan latency)
  135. {
  136. }
  137. public void Dispose()
  138. {
  139. _timer.Dispose();
  140. }
  141. }
  142. }