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.1 kB

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