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

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