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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.NetworkInformation;
  7. using System.Threading;
  8. using Shadowsocks.Model;
  9. namespace Shadowsocks.Controller.Strategy
  10. {
  11. class StatisticsStrategy : IStrategy
  12. {
  13. private readonly ShadowsocksController _controller;
  14. private Server _currentServer;
  15. private readonly Timer _timer;
  16. private Dictionary<string, StatisticsData> _statistics;
  17. private const int CachedInterval = 30*60*1000; //choose a new server every 30 minutes
  18. private const int RetryInterval = 2*60*1000; //choose a new server every 30 minutes
  19. public class StatisticsData
  20. {
  21. public int SuccessTimes;
  22. public int TimedOutTimes;
  23. public int AverageResponse;
  24. public int MinResponse;
  25. public int MaxResponse;
  26. }
  27. public StatisticsStrategy(ShadowsocksController controller)
  28. {
  29. _controller = controller;
  30. var servers = controller.GetCurrentConfiguration().configs;
  31. var randomIndex = new Random().Next() % servers.Count();
  32. _currentServer = servers[randomIndex]; //choose a server randomly at first
  33. _timer = new Timer(ReloadStatisticsAndChooseAServer);
  34. }
  35. private void ReloadStatisticsAndChooseAServer(object obj)
  36. {
  37. Logging.Debug("Reloading statistics and choose a new server....");
  38. var servers = _controller.GetCurrentConfiguration().configs;
  39. LoadStatistics();
  40. ChooseNewServer(servers);
  41. }
  42. /*
  43. return a dict:
  44. {
  45. 'ServerFriendlyName1':StatisticsData,
  46. 'ServerFriendlyName2':...
  47. }
  48. */
  49. private void LoadStatistics()
  50. {
  51. try
  52. {
  53. var path = AvailabilityStatistics.AvailabilityStatisticsFile;
  54. Logging.Debug($"loading statistics from {path}");
  55. if (!File.Exists(path))
  56. {
  57. LogWhenEnabled($"statistics file does not exist, try to reload {RetryInterval} minutes later");
  58. _timer.Change(RetryInterval, CachedInterval);
  59. return;
  60. }
  61. _statistics = (from l in File.ReadAllLines(path)
  62. .Skip(1)
  63. let strings = l.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
  64. let rawData = new
  65. {
  66. ServerName = strings[1],
  67. IPStatus = strings[2],
  68. RoundtripTime = int.Parse(strings[3])
  69. }
  70. group rawData by rawData.ServerName into server
  71. select new
  72. {
  73. ServerName = server.Key,
  74. data = new StatisticsData
  75. {
  76. SuccessTimes = server.Count(data => IPStatus.Success.ToString().Equals(data.IPStatus)),
  77. TimedOutTimes = server.Count(data => IPStatus.TimedOut.ToString().Equals(data.IPStatus)),
  78. AverageResponse = Convert.ToInt32(server.Average(data => data.RoundtripTime)),
  79. MinResponse = server.Min(data => data.RoundtripTime),
  80. MaxResponse = server.Max(data => data.RoundtripTime)
  81. }
  82. }).ToDictionary(server => server.ServerName, server => server.data);
  83. }
  84. catch (Exception e)
  85. {
  86. Logging.LogUsefulException(e);
  87. }
  88. }
  89. //return the score by data
  90. //server with highest score will be choosen
  91. private static double GetScore(StatisticsData data)
  92. {
  93. return (double)data.SuccessTimes / (data.SuccessTimes + data.TimedOutTimes); //simply choose min package loss
  94. }
  95. private void ChooseNewServer(List<Server> servers)
  96. {
  97. if (_statistics == null || servers.Count == 0)
  98. {
  99. return;
  100. }
  101. try
  102. {
  103. var bestResult = (from server in servers
  104. let name = server.FriendlyName()
  105. where _statistics.ContainsKey(name)
  106. select new
  107. {
  108. server,
  109. score = GetScore(_statistics[name])
  110. }
  111. ).Aggregate((result1, result2) => result1.score > result2.score ? result1 : result2);
  112. if (!_currentServer.Equals(bestResult.server)) //output when enabled
  113. {
  114. LogWhenEnabled($"Switch to server: {bestResult.server.FriendlyName()} by package loss:{1 - bestResult.score}");
  115. }
  116. _currentServer = bestResult.server;
  117. }
  118. catch (Exception e)
  119. {
  120. Logging.LogUsefulException(e);
  121. }
  122. }
  123. private void LogWhenEnabled(string log)
  124. {
  125. if (_controller.GetCurrentStrategy()?.ID == ID) //output when enabled
  126. {
  127. Console.WriteLine(log);
  128. }
  129. }
  130. public string ID => "com.shadowsocks.strategy.statistics";
  131. public string Name => I18N.GetString("Choose By Total Package Loss");
  132. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint)
  133. {
  134. var oldServer = _currentServer;
  135. if (oldServer == null)
  136. {
  137. ChooseNewServer(_controller.GetCurrentConfiguration().configs);
  138. }
  139. return _currentServer; //current server cached for CachedInterval
  140. }
  141. public void ReloadServers()
  142. {
  143. ChooseNewServer(_controller.GetCurrentConfiguration().configs);
  144. _timer?.Change(0, CachedInterval);
  145. }
  146. public void SetFailure(Server server)
  147. {
  148. Logging.Debug($"failure: {server.FriendlyName()}");
  149. }
  150. public void UpdateLastRead(Server server)
  151. {
  152. //TODO: combine this part of data with ICMP statics
  153. }
  154. public void UpdateLastWrite(Server server)
  155. {
  156. //TODO: combine this part of data with ICMP statics
  157. }
  158. public void UpdateLatency(Server server, TimeSpan latency)
  159. {
  160. //TODO: combine this part of data with ICMP statics
  161. }
  162. }
  163. }