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.

SimplyChooseByStatisticsStrategy.cs 6.7 kB

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