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 5.8 kB

9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 serverName)
  45. {
  46. var config = _controller.StatisticsConfiguration;
  47. List<StatisticsRecord> records;
  48. if (_filteredStatistics == null || !_filteredStatistics.TryGetValue(serverName, out records)) return 0;
  49. float factor;
  50. float score = 0;
  51. var averageRecord = new StatisticsRecord(serverName,
  52. records.FindAll(record => record.MaxInboundSpeed != null).Select(record => record.MaxInboundSpeed.Value),
  53. records.FindAll(record => record.MaxOutboundSpeed != null).Select(record => record.MaxOutboundSpeed.Value),
  54. records.FindAll(record => record.AverageLatency != null).Select(record => record.AverageLatency.Value));
  55. averageRecord.setResponse(records.Select(record => record.AverageResponse));
  56. if (!config.Calculations.TryGetValue("PackageLoss", out factor)) factor = 0;
  57. score += averageRecord.PackageLoss*factor ?? 0;
  58. if (!config.Calculations.TryGetValue("AverageResponse", out factor)) factor = 0;
  59. score += averageRecord.AverageResponse*factor ?? 0;
  60. if (!config.Calculations.TryGetValue("MinResponse", out factor)) factor = 0;
  61. score += averageRecord.MinResponse*factor ?? 0;
  62. if (!config.Calculations.TryGetValue("MaxResponse", out factor)) factor = 0;
  63. score += averageRecord.MaxResponse*factor ?? 0;
  64. Logging.Debug($"{JsonConvert.SerializeObject(averageRecord, Formatting.Indented)}");
  65. return score;
  66. }
  67. private void ChooseNewServer(List<Server> servers)
  68. {
  69. if (_filteredStatistics == null || servers.Count == 0)
  70. {
  71. return;
  72. }
  73. try
  74. {
  75. var bestResult = (from server in servers
  76. let name = server.FriendlyName()
  77. where _filteredStatistics.ContainsKey(name)
  78. select new
  79. {
  80. server,
  81. score = GetScore(name)
  82. }
  83. ).Aggregate((result1, result2) => result1.score > result2.score ? result1 : result2);
  84. LogWhenEnabled($"Switch to server: {bestResult.server.FriendlyName()} by statistics: score {bestResult.score}");
  85. _currentServer = bestResult.server;
  86. }
  87. catch (Exception e)
  88. {
  89. Logging.LogUsefulException(e);
  90. }
  91. }
  92. private void LogWhenEnabled(string log)
  93. {
  94. if (_controller.GetCurrentStrategy()?.ID == ID) //output when enabled
  95. {
  96. Console.WriteLine(log);
  97. }
  98. }
  99. public string ID => "com.shadowsocks.strategy.scbs";
  100. public string Name => I18N.GetString("Choose By Total Package Loss");
  101. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint)
  102. {
  103. if (_currentServer == null)
  104. {
  105. ChooseNewServer(_controller.GetCurrentConfiguration().configs);
  106. }
  107. return _currentServer; //current server cached for CachedInterval
  108. }
  109. public void ReloadServers()
  110. {
  111. ChooseNewServer(_controller.GetCurrentConfiguration().configs);
  112. _timer?.Change(0, ChoiceKeptMilliseconds);
  113. }
  114. public void SetFailure(Server server)
  115. {
  116. Logging.Debug($"failure: {server.FriendlyName()}");
  117. }
  118. public void UpdateLastRead(Server server)
  119. {
  120. }
  121. public void UpdateLastWrite(Server server)
  122. {
  123. }
  124. public void UpdateLatency(Server server, TimeSpan latency)
  125. {
  126. }
  127. public void Dispose()
  128. {
  129. _timer.Dispose();
  130. }
  131. }
  132. }