AppServerBase.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Security;
  6. using System.Security.Authentication;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Microsoft.Extensions.Logging;
  12. using NLog.Extensions.Logging;
  13. using SuperSocket.Common;
  14. using SuperSocket.SocketBase.Command;
  15. using SuperSocket.SocketBase.Config;
  16. using SuperSocket.SocketBase.Logging;
  17. using SuperSocket.SocketBase.Metadata;
  18. using SuperSocket.SocketBase.Protocol;
  19. using SuperSocket.SocketBase.Provider;
  20. using SuperSocket.SocketBase.Security;
  21. namespace SuperSocket.SocketBase
  22. {
  23. /// <summary>
  24. /// AppServer base class
  25. /// </summary>
  26. /// <typeparam name="TAppSession">The type of the app session.</typeparam>
  27. /// <typeparam name="TRequestInfo">The type of the request info.</typeparam>
  28. [AppServerMetadataType(typeof(DefaultAppServerMetadata))]
  29. public abstract partial class AppServerBase<TAppSession, TRequestInfo> : IAppServer<TAppSession, TRequestInfo>, IRawDataProcessor<TAppSession>, IRequestHandler<TRequestInfo>, ISocketServerAccessor, IStatusInfoSource, IRemoteCertificateValidator, IActiveConnector, ISystemEndPoint, IDisposable
  30. where TRequestInfo : class, IRequestInfo
  31. where TAppSession : AppSession<TAppSession, TRequestInfo>, IAppSession, new()
  32. {
  33. /// <summary>
  34. /// Null appSession instance
  35. /// </summary>
  36. protected readonly TAppSession NullAppSession = default(TAppSession);
  37. /// <summary>
  38. /// Gets the server's config.
  39. /// </summary>
  40. public IServerConfig Config { get; private set; }
  41. //Server instance name
  42. private string m_Name;
  43. /// <summary>
  44. /// the current state's code
  45. /// </summary>
  46. private int m_StateCode = ServerStateConst.NotInitialized;
  47. /// <summary>
  48. /// Gets the current state of the work item.
  49. /// </summary>
  50. /// <value>
  51. /// The state.
  52. /// </value>
  53. public ServerState State
  54. {
  55. get
  56. {
  57. return (ServerState)m_StateCode;
  58. }
  59. }
  60. /// <summary>
  61. /// Gets the certificate of current server.
  62. /// </summary>
  63. public X509Certificate Certificate { get; private set; }
  64. /// <summary>
  65. /// Gets or sets the receive filter factory.
  66. /// </summary>
  67. /// <value>
  68. /// The receive filter factory.
  69. /// </value>
  70. public virtual IReceiveFilterFactory<TRequestInfo> ReceiveFilterFactory { get; protected set; }
  71. /// <summary>
  72. /// Gets the Receive filter factory.
  73. /// </summary>
  74. object IAppServer.ReceiveFilterFactory
  75. {
  76. get { return this.ReceiveFilterFactory; }
  77. }
  78. private List<ICommandLoader<ICommand<TAppSession, TRequestInfo>>> m_CommandLoaders = new List<ICommandLoader<ICommand<TAppSession, TRequestInfo>>>();
  79. private Dictionary<string, CommandInfo<ICommand<TAppSession, TRequestInfo>>> m_CommandContainer;
  80. private CommandFilterAttribute[] m_GlobalCommandFilters;
  81. private ISocketServerFactory m_SocketServerFactory;
  82. /// <summary>
  83. /// Gets the basic transfer layer security protocol.
  84. /// </summary>
  85. public SslProtocols BasicSecurity { get; private set; }
  86. /// <summary>
  87. /// Gets the root config.
  88. /// </summary>
  89. protected IRootConfig RootConfig { get; private set; }
  90. /// <summary>
  91. /// Gets the logger assosiated with this object.
  92. /// </summary>
  93. public ILogger Logger { get; private set; }
  94. /// <summary>
  95. /// Gets the bootstrap of this appServer instance.
  96. /// </summary>
  97. protected IBootstrap Bootstrap { get; private set; }
  98. private static bool m_ThreadPoolConfigured = false;
  99. private List<IConnectionFilter> m_ConnectionFilters;
  100. private long m_TotalHandledRequests = 0;
  101. /// <summary>
  102. /// Gets the total handled requests number.
  103. /// </summary>
  104. protected long TotalHandledRequests
  105. {
  106. get { return m_TotalHandledRequests; }
  107. }
  108. private ListenerInfo[] m_Listeners;
  109. /// <summary>
  110. /// Gets or sets the listeners inforamtion.
  111. /// </summary>
  112. /// <value>
  113. /// The listeners.
  114. /// </value>
  115. public ListenerInfo[] Listeners
  116. {
  117. get { return m_Listeners; }
  118. }
  119. /// <summary>
  120. /// Gets the started time of this server instance.
  121. /// </summary>
  122. /// <value>
  123. /// The started time.
  124. /// </value>
  125. public DateTime StartedTime { get; private set; }
  126. /// <summary>
  127. /// Gets or sets the log factory.
  128. /// </summary>
  129. /// <value>
  130. /// The log factory.
  131. /// </value>
  132. public ILoggerFactory LogFactory { get; private set; }
  133. /// <summary>
  134. /// Gets the default text encoding.
  135. /// </summary>
  136. /// <value>
  137. /// The text encoding.
  138. /// </value>
  139. public Encoding TextEncoding { get; private set; }
  140. /// <summary>
  141. /// Initializes a new instance of the <see cref="AppServerBase&lt;TAppSession, TRequestInfo&gt;"/> class.
  142. /// </summary>
  143. public AppServerBase()
  144. {
  145. }
  146. /// <summary>
  147. /// Initializes a new instance of the <see cref="AppServerBase&lt;TAppSession, TRequestInfo&gt;"/> class.
  148. /// </summary>
  149. /// <param name="receiveFilterFactory">The Receive filter factory.</param>
  150. public AppServerBase(IReceiveFilterFactory<TRequestInfo> receiveFilterFactory)
  151. {
  152. this.ReceiveFilterFactory = receiveFilterFactory;
  153. }
  154. /// <summary>
  155. /// Gets the filter attributes.
  156. /// </summary>
  157. /// <param name="type">The type.</param>
  158. /// <returns></returns>
  159. internal static CommandFilterAttribute[] GetCommandFilterAttributes(Type type)
  160. {
  161. var attrs = type.GetCustomAttributes(true);
  162. return attrs.OfType<CommandFilterAttribute>().ToArray();
  163. }
  164. /// <summary>
  165. /// Setups the command into command dictionary
  166. /// </summary>
  167. /// <param name="discoveredCommands">The discovered commands.</param>
  168. /// <returns></returns>
  169. protected virtual bool SetupCommands(Dictionary<string, ICommand<TAppSession, TRequestInfo>> discoveredCommands)
  170. {
  171. foreach (var loader in m_CommandLoaders)
  172. {
  173. loader.Error += new EventHandler<ErrorEventArgs>(CommandLoaderOnError);
  174. loader.Updated += new EventHandler<CommandUpdateEventArgs<ICommand<TAppSession, TRequestInfo>>>(CommandLoaderOnCommandsUpdated);
  175. if (!loader.Initialize(RootConfig, this))
  176. {
  177. Logger.LogError("Failed initialize the command loader {0}.", loader.ToString());
  178. return false;
  179. }
  180. IEnumerable<ICommand<TAppSession, TRequestInfo>> commands;
  181. if (!loader.TryLoadCommands(out commands))
  182. {
  183. Logger.LogError("Failed load commands from the command loader {0}.", loader.ToString());
  184. return false;
  185. }
  186. if (commands != null && commands.Any())
  187. {
  188. foreach (var c in commands)
  189. {
  190. if (discoveredCommands.ContainsKey(c.Name))
  191. {
  192. Logger.LogError("Duplicated name command has been found! Command name: " + c.Name);
  193. return false;
  194. }
  195. var castedCommand = c as ICommand<TAppSession, TRequestInfo>;
  196. if (castedCommand == null)
  197. {
  198. Logger.LogError("Invalid command has been found! Command name: " + c.Name);
  199. return false;
  200. }
  201. Logger.LogDebug("The command {0}({1}) has been discovered", castedCommand.Name, castedCommand.ToString());
  202. discoveredCommands.Add(c.Name, castedCommand);
  203. }
  204. }
  205. }
  206. return true;
  207. }
  208. void CommandLoaderOnCommandsUpdated(object sender, CommandUpdateEventArgs<ICommand<TAppSession, TRequestInfo>> e)
  209. {
  210. var workingDict = m_CommandContainer.Values.ToDictionary(c => c.Command.Name, c => c.Command, StringComparer.OrdinalIgnoreCase);
  211. var updatedCommands = 0;
  212. foreach (var c in e.Commands)
  213. {
  214. if (c == null)
  215. continue;
  216. if (c.UpdateAction == CommandUpdateAction.Remove)
  217. {
  218. workingDict.Remove(c.Command.Name);
  219. Logger.LogInformation("The command '{0}' has been removed from this server!", c.Command.Name);
  220. }
  221. else if (c.UpdateAction == CommandUpdateAction.Add)
  222. {
  223. workingDict.Add(c.Command.Name, c.Command);
  224. Logger.LogInformation("The command '{0}' has been added into this server!", c.Command.Name);
  225. }
  226. else
  227. {
  228. workingDict[c.Command.Name] = c.Command;
  229. Logger.LogInformation("The command '{0}' has been updated!", c.Command.Name);
  230. }
  231. updatedCommands++;
  232. }
  233. if (updatedCommands > 0)
  234. {
  235. OnCommandSetup(workingDict);
  236. }
  237. }
  238. void CommandLoaderOnError(object sender, ErrorEventArgs e)
  239. {
  240. Logger.LogError((EventId)0, e.Exception, e.Exception.Message);
  241. }
  242. /// <summary>
  243. /// Setups the specified root config.
  244. /// </summary>
  245. /// <param name="rootConfig">The root config.</param>
  246. /// <param name="config">The config.</param>
  247. /// <returns></returns>
  248. protected virtual bool Setup(IRootConfig rootConfig, IServerConfig config)
  249. {
  250. return true;
  251. }
  252. partial void SetDefaultCulture(IRootConfig rootConfig, IServerConfig config);
  253. private void SetupBasic(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory)
  254. {
  255. if (rootConfig == null)
  256. throw new ArgumentNullException("rootConfig");
  257. RootConfig = rootConfig;
  258. if (config == null)
  259. throw new ArgumentNullException("config");
  260. if (!string.IsNullOrEmpty(config.Name))
  261. m_Name = config.Name;
  262. else
  263. m_Name = string.Format("{0}-{1}", this.GetType().Name, Math.Abs(this.GetHashCode()));
  264. Config = config;
  265. SetDefaultCulture(rootConfig, config);
  266. if (!m_ThreadPoolConfigured)
  267. {
  268. if (!TheadPoolEx.ResetThreadPool(rootConfig.MaxWorkingThreads >= 0 ? rootConfig.MaxWorkingThreads : new Nullable<int>(),
  269. rootConfig.MaxCompletionPortThreads >= 0 ? rootConfig.MaxCompletionPortThreads : new Nullable<int>(),
  270. rootConfig.MinWorkingThreads >= 0 ? rootConfig.MinWorkingThreads : new Nullable<int>(),
  271. rootConfig.MinCompletionPortThreads >= 0 ? rootConfig.MinCompletionPortThreads : new Nullable<int>()))
  272. {
  273. throw new Exception("Failed to configure thread pool!");
  274. }
  275. m_ThreadPoolConfigured = true;
  276. }
  277. if (socketServerFactory == null)
  278. {
  279. var socketServerFactoryType =
  280. Type.GetType("SuperSocket.SocketEngine.SocketServerFactory, SuperSocket.SocketEngine", true);
  281. socketServerFactory = (ISocketServerFactory)Activator.CreateInstance(socketServerFactoryType);
  282. }
  283. m_SocketServerFactory = socketServerFactory;
  284. //Read text encoding from the configuration
  285. if (!string.IsNullOrEmpty(config.TextEncoding))
  286. TextEncoding = Encoding.GetEncoding(config.TextEncoding);
  287. else
  288. TextEncoding = new ASCIIEncoding();
  289. }
  290. private bool SetupMedium(IReceiveFilterFactory<TRequestInfo> receiveFilterFactory, IEnumerable<IConnectionFilter> connectionFilters, IEnumerable<ICommandLoader<ICommand<TAppSession, TRequestInfo>>> commandLoaders)
  291. {
  292. if (receiveFilterFactory != null)
  293. ReceiveFilterFactory = receiveFilterFactory;
  294. if (connectionFilters != null && connectionFilters.Any())
  295. {
  296. if (m_ConnectionFilters == null)
  297. m_ConnectionFilters = new List<IConnectionFilter>();
  298. m_ConnectionFilters.AddRange(connectionFilters);
  299. }
  300. if (commandLoaders != null && commandLoaders.Any())
  301. m_CommandLoaders.AddRange(commandLoaders);
  302. return SetupCommandLoaders(m_CommandLoaders);
  303. }
  304. private bool SetupAdvanced(IServerConfig config)
  305. {
  306. if (!SetupSecurity(config))
  307. {
  308. Console.WriteLine("SetupSecurity fail");
  309. return false;
  310. }
  311. if (!SetupListeners(config))
  312. {
  313. Console.WriteLine("SetupListeners fail");
  314. return false;
  315. }
  316. m_GlobalCommandFilters = GetCommandFilterAttributes(this.GetType());
  317. var discoveredCommands = new Dictionary<string, ICommand<TAppSession, TRequestInfo>>(StringComparer.OrdinalIgnoreCase);
  318. if (!SetupCommands(discoveredCommands))
  319. {
  320. Console.WriteLine("SetupCommands fail");
  321. return false;
  322. }
  323. OnCommandSetup(discoveredCommands);
  324. return true;
  325. }
  326. private void OnCommandSetup(IDictionary<string, ICommand<TAppSession, TRequestInfo>> discoveredCommands)
  327. {
  328. var commandContainer = new Dictionary<string, CommandInfo<ICommand<TAppSession, TRequestInfo>>>(StringComparer.OrdinalIgnoreCase);
  329. foreach (var command in discoveredCommands.Values)
  330. {
  331. commandContainer.Add(command.Name,
  332. new CommandInfo<ICommand<TAppSession, TRequestInfo>>(command, m_GlobalCommandFilters));
  333. }
  334. Interlocked.Exchange(ref m_CommandContainer, commandContainer);
  335. }
  336. internal abstract IReceiveFilterFactory<TRequestInfo> CreateDefaultReceiveFilterFactory();
  337. private bool SetupFinal()
  338. {
  339. //Check receiveFilterFactory
  340. if (ReceiveFilterFactory == null)
  341. {
  342. ReceiveFilterFactory = CreateDefaultReceiveFilterFactory();
  343. if (ReceiveFilterFactory == null)
  344. {
  345. Logger.LogError("receiveFilterFactory is required!");
  346. return false;
  347. }
  348. }
  349. var plainConfig = Config as ServerConfig;
  350. if (plainConfig == null)
  351. {
  352. //Using plain config model instead of .NET configuration element to improve performance
  353. plainConfig = new ServerConfig(Config);
  354. if (string.IsNullOrEmpty(plainConfig.Name))
  355. plainConfig.Name = Name;
  356. Config = plainConfig;
  357. }
  358. try
  359. {
  360. m_ServerStatus = new StatusInfoCollection();
  361. m_ServerStatus.Name = Name;
  362. m_ServerStatus.Tag = Name;
  363. m_ServerStatus[StatusInfoKeys.MaxConnectionNumber] = Config.MaxConnectionNumber;
  364. m_ServerStatus[StatusInfoKeys.Listeners] = m_Listeners;
  365. }
  366. catch (Exception e)
  367. {
  368. Logger.LogError("Failed to create ServerSummary instance!", e);
  369. return false;
  370. }
  371. return SetupSocketServer();
  372. }
  373. /// <summary>
  374. /// Setups with the specified port.
  375. /// </summary>
  376. /// <param name="port">The port.</param>
  377. /// <returns>return setup result</returns>
  378. public bool Setup(int port)
  379. {
  380. return Setup("Any", port);
  381. }
  382. private void TrySetInitializedState()
  383. {
  384. if (Interlocked.CompareExchange(ref m_StateCode, ServerStateConst.Initializing, ServerStateConst.NotInitialized)
  385. != ServerStateConst.NotInitialized)
  386. {
  387. throw new Exception("The server has been initialized already, you cannot initialize it again!");
  388. }
  389. }
  390. #if NET_35
  391. /// <summary>
  392. /// Setups with the specified ip and port.
  393. /// </summary>
  394. /// <param name="ip">The ip.</param>
  395. /// <param name="port">The port.</param>
  396. /// <param name="providers">The providers.</param>
  397. /// <returns></returns>
  398. public bool Setup(string ip, int port, params object[] providers)
  399. {
  400. return Setup(new ServerConfig
  401. {
  402. Name = string.Format("{0}-{1}", this.GetType().Name, Math.Abs(this.GetHashCode())),
  403. Ip = ip,
  404. Port = port
  405. }, providers);
  406. }
  407. /// <summary>
  408. /// Setups with the specified config, used for programming setup
  409. /// </summary>
  410. /// <param name="config">The server config.</param>
  411. /// <param name="providers">The providers.</param>
  412. /// <returns></returns>
  413. public bool Setup(IServerConfig config, params object[] providers)
  414. {
  415. return Setup(new RootConfig(), config, providers);
  416. }
  417. /// <summary>
  418. /// Setups with the specified root config, used for programming setup
  419. /// </summary>
  420. /// <param name="rootConfig">The root config.</param>
  421. /// <param name="config">The server config.</param>
  422. /// <param name="providers">The providers.</param>
  423. /// <returns></returns>
  424. public bool Setup(IRootConfig rootConfig, IServerConfig config, params object[] providers)
  425. {
  426. TrySetInitializedState();
  427. SetupBasic(rootConfig, config, GetProviderInstance<ISocketServerFactory>(providers));
  428. if (!SetupLogFactory(GetProviderInstance<ILogFactory>(providers)))
  429. return false;
  430. Logger = CreateLogger(this.Name);
  431. if (!SetupMedium(GetProviderInstance<IReceiveFilterFactory<TRequestInfo>>(providers), GetProviderInstance<IEnumerable<IConnectionFilter>>(providers), GetProviderInstance<IEnumerable<ICommandLoader<ICommand<TAppSession, TRequestInfo>>>>(providers)))
  432. return false;
  433. if (!SetupAdvanced(config))
  434. return false;
  435. if (!Setup(rootConfig, config))
  436. return false;
  437. if(!SetupFinal())
  438. return false;
  439. m_StateCode = ServerStateConst.NotStarted;
  440. return true;
  441. }
  442. private T GetProviderInstance<T>(object[] providers)
  443. {
  444. if (providers == null || !providers.Any())
  445. return default(T);
  446. var providerType = typeof(T);
  447. return (T)providers.FirstOrDefault(p => p != null && providerType.IsAssignableFrom(p.GetType()));
  448. }
  449. #else
  450. /// <summary>
  451. /// Setups with the specified config.
  452. /// </summary>
  453. /// <param name="config">The server config.</param>
  454. /// <param name="socketServerFactory">The socket server factory.</param>
  455. /// <param name="receiveFilterFactory">The receive filter factory.</param>
  456. /// <param name="logFactory">The log factory.</param>
  457. /// <param name="connectionFilters">The connection filters.</param>
  458. /// <param name="commandLoaders">The command loaders.</param>
  459. /// <returns></returns>
  460. public bool Setup(IServerConfig config, ISocketServerFactory socketServerFactory = null, IReceiveFilterFactory<TRequestInfo> receiveFilterFactory = null, ILoggerFactory logFactory = null, IEnumerable<IConnectionFilter> connectionFilters = null, IEnumerable<ICommandLoader<ICommand<TAppSession, TRequestInfo>>> commandLoaders = null)
  461. {
  462. return Setup(new RootConfig(), config, socketServerFactory, receiveFilterFactory, logFactory, connectionFilters, commandLoaders);
  463. }
  464. /// <summary>
  465. /// Setups the specified root config, this method used for programming setup
  466. /// </summary>
  467. /// <param name="rootConfig">The root config.</param>
  468. /// <param name="config">The server config.</param>
  469. /// <param name="socketServerFactory">The socket server factory.</param>
  470. /// <param name="receiveFilterFactory">The Receive filter factory.</param>
  471. /// <param name="logFactory">The log factory.</param>
  472. /// <param name="connectionFilters">The connection filters.</param>
  473. /// <param name="commandLoaders">The command loaders.</param>
  474. /// <returns></returns>
  475. public bool Setup(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory = null, IReceiveFilterFactory<TRequestInfo> receiveFilterFactory = null, ILoggerFactory logFactory = null, IEnumerable<IConnectionFilter> connectionFilters = null, IEnumerable<ICommandLoader<ICommand<TAppSession, TRequestInfo>>> commandLoaders = null)
  476. {
  477. TrySetInitializedState();
  478. SetupBasic(rootConfig, config, socketServerFactory);
  479. if (!SetupLogFactory(logFactory))
  480. {
  481. Console.WriteLine("SetupLogFactory Fail");
  482. return false;
  483. }
  484. Logger = CreateLogger(this.Name);
  485. if (!SetupMedium(receiveFilterFactory, connectionFilters, commandLoaders))
  486. {
  487. Console.WriteLine("SetupMedium Fail");
  488. return false;
  489. }
  490. if (!SetupAdvanced(config))
  491. {
  492. Console.WriteLine("SetupAdvanced Fail");
  493. return false;
  494. }
  495. if (!Setup(rootConfig, config))
  496. {
  497. Console.WriteLine("Setup Config Fail");
  498. return false;
  499. }
  500. if (!SetupFinal())
  501. {
  502. Console.WriteLine("SetupFinal Fail");
  503. return false;
  504. }
  505. m_StateCode = ServerStateConst.NotStarted;
  506. return true;
  507. }
  508. /// <summary>
  509. /// Setups with the specified ip and port.
  510. /// </summary>
  511. /// <param name="ip">The ip.</param>
  512. /// <param name="port">The port.</param>
  513. /// <param name="socketServerFactory">The socket server factory.</param>
  514. /// <param name="receiveFilterFactory">The Receive filter factory.</param>
  515. /// <param name="logFactory">The log factory.</param>
  516. /// <param name="connectionFilters">The connection filters.</param>
  517. /// <param name="commandLoaders">The command loaders.</param>
  518. /// <returns>return setup result</returns>
  519. public bool Setup(string ip, int port, ISocketServerFactory socketServerFactory = null, IReceiveFilterFactory<TRequestInfo> receiveFilterFactory = null, ILoggerFactory logFactory = null, IEnumerable<IConnectionFilter> connectionFilters = null, IEnumerable<ICommandLoader<ICommand<TAppSession, TRequestInfo>>> commandLoaders = null)
  520. {
  521. return Setup(new ServerConfig
  522. {
  523. Ip = ip,
  524. Port = port
  525. },
  526. socketServerFactory,
  527. receiveFilterFactory,
  528. logFactory,
  529. connectionFilters,
  530. commandLoaders);
  531. }
  532. #endif
  533. /// <summary>
  534. /// Setups the specified root config.
  535. /// </summary>
  536. /// <param name="bootstrap">The bootstrap.</param>
  537. /// <param name="config">The socket server instance config.</param>
  538. /// <param name="factories">The factories.</param>
  539. /// <returns></returns>
  540. bool IWorkItem.Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories)
  541. {
  542. if (bootstrap == null)
  543. throw new ArgumentNullException("bootstrap");
  544. Bootstrap = bootstrap;
  545. if (factories == null)
  546. throw new ArgumentNullException("factories");
  547. TrySetInitializedState();
  548. var rootConfig = bootstrap.Config;
  549. SetupBasic(rootConfig, config, GetSingleProviderInstance<ISocketServerFactory>(factories, ProviderKey.SocketServerFactory));
  550. if (!SetupLogFactory(GetSingleProviderInstance<ILoggerFactory>(factories, ProviderKey.LogFactory)))
  551. return false;
  552. Logger = CreateLogger(this.Name);
  553. IEnumerable<IConnectionFilter> connectionFilters = null;
  554. if (!TryGetProviderInstances(factories, ProviderKey.ConnectionFilter, null,
  555. (p, f) =>
  556. {
  557. var ret = p.Initialize(f.Name, this);
  558. if(!ret)
  559. {
  560. Logger.LogError("Failed to initialize the connection filter: {0}.", f.Name);
  561. }
  562. return ret;
  563. }, out connectionFilters))
  564. {
  565. return false;
  566. }
  567. if (!SetupMedium(
  568. GetSingleProviderInstance<IReceiveFilterFactory<TRequestInfo>>(factories, ProviderKey.ReceiveFilterFactory),
  569. connectionFilters,
  570. GetProviderInstances<ICommandLoader<ICommand<TAppSession, TRequestInfo>>>(
  571. factories,
  572. ProviderKey.CommandLoader,
  573. (t) => Activator.CreateInstance(t.MakeGenericType(typeof(ICommand<TAppSession, TRequestInfo>))))))
  574. {
  575. return false;
  576. }
  577. if (!SetupAdvanced(config))
  578. return false;
  579. if (!Setup(rootConfig, config))
  580. return false;
  581. if (!SetupFinal())
  582. return false;
  583. m_StateCode = ServerStateConst.NotStarted;
  584. return true;
  585. }
  586. private TProvider GetSingleProviderInstance<TProvider>(ProviderFactoryInfo[] factories, ProviderKey key)
  587. {
  588. var factory = factories.FirstOrDefault(p => p.Key.Name == key.Name);
  589. if (factory == null)
  590. return default(TProvider);
  591. return factory.ExportFactory.CreateExport<TProvider>();
  592. }
  593. private bool TryGetProviderInstances<TProvider>(ProviderFactoryInfo[] factories, ProviderKey key, Func<Type, object> creator, Func<TProvider, ProviderFactoryInfo, bool> initializer, out IEnumerable<TProvider> providers)
  594. where TProvider : class
  595. {
  596. IEnumerable<ProviderFactoryInfo> selectedFactories = factories.Where(p => p.Key.Name == key.Name);
  597. if (!selectedFactories.Any())
  598. {
  599. providers = null;
  600. return true;
  601. }
  602. providers = new List<TProvider>();
  603. var list = (List<TProvider>)providers;
  604. foreach (var f in selectedFactories)
  605. {
  606. var provider = creator == null ? f.ExportFactory.CreateExport<TProvider>() : f.ExportFactory.CreateExport<TProvider>(creator);
  607. if (!initializer(provider, f))
  608. return false;
  609. list.Add(provider);
  610. }
  611. return true;
  612. }
  613. private IEnumerable<TProvider> GetProviderInstances<TProvider>(ProviderFactoryInfo[] factories, ProviderKey key)
  614. where TProvider : class
  615. {
  616. return GetProviderInstances<TProvider>(factories, key, null);
  617. }
  618. private IEnumerable<TProvider> GetProviderInstances<TProvider>(ProviderFactoryInfo[] factories, ProviderKey key, Func<Type, object> creator)
  619. where TProvider : class
  620. {
  621. IEnumerable<TProvider> providers;
  622. TryGetProviderInstances<TProvider>(factories, key, creator, (p, f) => true, out providers);
  623. return providers;
  624. }
  625. private bool SetupLogFactory(ILoggerFactory logFactory)
  626. {
  627. if (logFactory != null)
  628. {
  629. LogFactory = logFactory;
  630. return true;
  631. }
  632. //Log4NetLogFactory is default log factory
  633. if (LogFactory == null)
  634. {
  635. LogFactory = new NLogLoggerFactory();
  636. }
  637. //LogFactory = new Log4NetLogFactory();
  638. return true;
  639. }
  640. /// <summary>
  641. /// Setups the command loaders.
  642. /// </summary>
  643. /// <param name="commandLoaders">The command loaders.</param>
  644. /// <returns></returns>
  645. protected virtual bool SetupCommandLoaders(List<ICommandLoader<ICommand<TAppSession, TRequestInfo>>> commandLoaders)
  646. {
  647. commandLoaders.Add(new ReflectCommandLoader<ICommand<TAppSession, TRequestInfo>>());
  648. return true;
  649. }
  650. /// <summary>
  651. /// Creates the logger for the AppServer.
  652. /// </summary>
  653. /// <param name="loggerName">Name of the logger.</param>
  654. /// <returns></returns>
  655. protected virtual ILogger CreateLogger(string loggerName)
  656. {
  657. return LogFactory.CreateLogger(loggerName);
  658. }
  659. /// <summary>
  660. /// Setups the security option of socket communications.
  661. /// </summary>
  662. /// <param name="config">The config of the server instance.</param>
  663. /// <returns></returns>
  664. private bool SetupSecurity(IServerConfig config)
  665. {
  666. if (!string.IsNullOrEmpty(config.Security))
  667. {
  668. SslProtocols configProtocol;
  669. if (!config.Security.TryParseEnum<SslProtocols>(true, out configProtocol))
  670. {
  671. Console.WriteLine("Failed to parse '{0}' to SslProtocol!", config.Security);
  672. Logger.LogError("Failed to parse '{0}' to SslProtocol!", config.Security);
  673. return false;
  674. }
  675. BasicSecurity = configProtocol;
  676. }
  677. else
  678. {
  679. BasicSecurity = SslProtocols.None;
  680. }
  681. try
  682. {
  683. var certificate = GetCertificate(config.Certificate);
  684. if (certificate != null)
  685. {
  686. Certificate = certificate;
  687. }
  688. else if(BasicSecurity != SslProtocols.None)
  689. {
  690. Console.WriteLine("Certificate is required in this security mode!");
  691. Logger.LogError("Certificate is required in this security mode!");
  692. return false;
  693. }
  694. }
  695. catch (Exception e)
  696. {
  697. Console.WriteLine("Failed to initialize certificate!");
  698. Console.WriteLine(e.Message);
  699. Logger.LogError(e , "Failed to initialize certificate!");
  700. return false;
  701. }
  702. return true;
  703. }
  704. /// <summary>
  705. /// Gets the certificate from server configuguration.
  706. /// </summary>
  707. /// <param name="certificate">The certificate config.</param>
  708. /// <returns></returns>
  709. protected virtual X509Certificate GetCertificate(ICertificateConfig certificate)
  710. {
  711. if (certificate == null)
  712. {
  713. if (BasicSecurity != SslProtocols.None)
  714. Logger.LogError("There is no certificate configured!");
  715. return null;
  716. }
  717. Logger.LogDebug($"{certificate.StoreName} {certificate.FilePath} {certificate.Password}");
  718. if (string.IsNullOrEmpty(certificate.FilePath) && string.IsNullOrEmpty(certificate.Thumbprint))
  719. {
  720. if (BasicSecurity != SslProtocols.None)
  721. Logger.LogError("You should define certificate node and either attribute 'filePath' or 'thumbprint' is required!");
  722. return null;
  723. }
  724. return CertificateManager.Initialize(certificate, GetFilePath);
  725. }
  726. bool IRemoteCertificateValidator.Validate(IAppSession session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  727. {
  728. return ValidateClientCertificate((TAppSession)session, sender, certificate, chain, sslPolicyErrors);
  729. }
  730. /// <summary>
  731. /// Validates the client certificate. This method is only used if the certificate configuration attribute "clientCertificateRequired" is true.
  732. /// </summary>
  733. /// <param name="session">The session.</param>
  734. /// <param name="sender">The sender.</param>
  735. /// <param name="certificate">The certificate.</param>
  736. /// <param name="chain">The chain.</param>
  737. /// <param name="sslPolicyErrors">The SSL policy errors.</param>
  738. /// <returns>return the validation result</returns>
  739. protected virtual bool ValidateClientCertificate(TAppSession session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  740. {
  741. return sslPolicyErrors == SslPolicyErrors.None;
  742. }
  743. /// <summary>
  744. /// Setups the socket server.instance
  745. /// </summary>
  746. /// <returns></returns>
  747. private bool SetupSocketServer()
  748. {
  749. try
  750. {
  751. m_SocketServer = m_SocketServerFactory.CreateSocketServer<TRequestInfo>(this, m_Listeners, Config);
  752. return m_SocketServer != null;
  753. }
  754. catch (Exception e)
  755. {
  756. Logger.LogError(e,e.Message);
  757. return false;
  758. }
  759. }
  760. private IPAddress ParseIPAddress(string ip)
  761. {
  762. if (string.IsNullOrEmpty(ip) || "Any".Equals(ip, StringComparison.OrdinalIgnoreCase))
  763. return IPAddress.Any;
  764. else if ("IPv6Any".Equals(ip, StringComparison.OrdinalIgnoreCase))
  765. return IPAddress.IPv6Any;
  766. else
  767. return IPAddress.Parse(ip);
  768. }
  769. /// <summary>
  770. /// Setups the listeners base on server configuration
  771. /// </summary>
  772. /// <param name="config">The config.</param>
  773. /// <returns></returns>
  774. private bool SetupListeners(IServerConfig config)
  775. {
  776. var listeners = new List<ListenerInfo>();
  777. try
  778. {
  779. if (config.Port > 0)
  780. {
  781. listeners.Add(new ListenerInfo
  782. {
  783. EndPoint = new IPEndPoint(ParseIPAddress(config.Ip), config.Port),
  784. BackLog = config.ListenBacklog,
  785. Security = BasicSecurity
  786. });
  787. }
  788. else
  789. {
  790. //Port is not configured, but ip is configured
  791. if (!string.IsNullOrEmpty(config.Ip))
  792. {
  793. Logger.LogError("Port is required in config!");
  794. return false;
  795. }
  796. }
  797. //There are listener defined
  798. if (config.Listeners != null && config.Listeners.Any())
  799. {
  800. //But ip and port were configured in server node
  801. //We don't allow this case
  802. if (listeners.Any())
  803. {
  804. Logger.LogError("If you configured Ip and Port in server node, you cannot defined listener in listeners node any more!");
  805. return false;
  806. }
  807. foreach (var l in config.Listeners)
  808. {
  809. SslProtocols configProtocol;
  810. if (string.IsNullOrEmpty(l.Security))
  811. {
  812. configProtocol = BasicSecurity;
  813. }
  814. else if (!l.Security.TryParseEnum<SslProtocols>(true, out configProtocol))
  815. {
  816. Logger.LogError("Failed to parse '{0}' to SslProtocol!", config.Security);
  817. return false;
  818. }
  819. if (configProtocol != SslProtocols.None && (Certificate == null))
  820. {
  821. Logger.LogError("There is no certificate loaded, but there is a secure listener defined!");
  822. return false;
  823. }
  824. listeners.Add(new ListenerInfo
  825. {
  826. EndPoint = new IPEndPoint(ParseIPAddress(l.Ip), l.Port),
  827. BackLog = l.Backlog,
  828. Security = configProtocol
  829. });
  830. }
  831. }
  832. if (!listeners.Any())
  833. {
  834. Logger.LogError("No listener defined!");
  835. return false;
  836. }
  837. m_Listeners = listeners.ToArray();
  838. return true;
  839. }
  840. catch (Exception e)
  841. {
  842. Logger.LogError(e,e.Message);
  843. return false;
  844. }
  845. }
  846. /// <summary>
  847. /// Gets the name of the server instance.
  848. /// </summary>
  849. public string Name
  850. {
  851. get { return m_Name; }
  852. }
  853. private ISocketServer m_SocketServer;
  854. /// <summary>
  855. /// Gets the socket server.
  856. /// </summary>
  857. /// <value>
  858. /// The socket server.
  859. /// </value>
  860. ISocketServer ISocketServerAccessor.SocketServer
  861. {
  862. get { return m_SocketServer; }
  863. }
  864. /// <summary>
  865. /// Starts this server instance.
  866. /// </summary>
  867. /// <returns>
  868. /// return true if start successfull, else false
  869. /// </returns>
  870. public virtual bool Start()
  871. {
  872. var origStateCode = Interlocked.CompareExchange(ref m_StateCode, ServerStateConst.Starting, ServerStateConst.NotStarted);
  873. if (origStateCode != ServerStateConst.NotStarted)
  874. {
  875. if (origStateCode < ServerStateConst.NotStarted)
  876. throw new Exception("You cannot start a server instance which has not been setup yet.");
  877. Logger.LogError("This server instance is in the state {0}, you cannot start it now.", (ServerState)origStateCode);
  878. return false;
  879. }
  880. if (!m_SocketServer.Start())
  881. {
  882. m_StateCode = ServerStateConst.NotStarted;
  883. return false;
  884. }
  885. StartedTime = DateTime.UtcNow;
  886. m_StateCode = ServerStateConst.Running;
  887. m_ServerStatus[StatusInfoKeys.IsRunning] = true;
  888. m_ServerStatus[StatusInfoKeys.StartedTime] = StartedTime;
  889. try
  890. {
  891. //Will be removed in the next version
  892. #pragma warning disable 0612, 618
  893. OnStartup();
  894. #pragma warning restore 0612, 618
  895. OnStarted();
  896. }
  897. catch (Exception e)
  898. {
  899. Logger.LogError("One exception wa thrown in the method 'OnStartup()'.", e);
  900. }
  901. finally
  902. {
  903. Logger.LogInformation("The server instance {0} has been started!", Name);
  904. }
  905. return true;
  906. }
  907. /// <summary>
  908. /// Called when [startup].
  909. /// </summary>
  910. [Obsolete("Use OnStarted() instead")]
  911. protected virtual void OnStartup()
  912. {
  913. }
  914. /// <summary>
  915. /// Called when [started].
  916. /// </summary>
  917. protected virtual void OnStarted()
  918. {
  919. }
  920. /// <summary>
  921. /// Called when [stopped].
  922. /// </summary>
  923. protected virtual void OnStopped()
  924. {
  925. }
  926. /// <summary>
  927. /// Stops this server instance.
  928. /// </summary>
  929. public virtual void Stop()
  930. {
  931. if (Interlocked.CompareExchange(ref m_StateCode, ServerStateConst.Stopping, ServerStateConst.Running)
  932. != ServerStateConst.Running)
  933. {
  934. return;
  935. }
  936. m_SocketServer.Stop();
  937. m_StateCode = ServerStateConst.NotStarted;
  938. OnStopped();
  939. m_ServerStatus[StatusInfoKeys.IsRunning] = false;
  940. m_ServerStatus[StatusInfoKeys.StartedTime] = null;
  941. Logger.LogInformation("The server instance {0} has been stopped!", Name);
  942. }
  943. /// <summary>
  944. /// Gets command by command name.
  945. /// </summary>
  946. /// <param name="commandName">Name of the command.</param>
  947. /// <returns></returns>
  948. private CommandInfo<ICommand<TAppSession, TRequestInfo>> GetCommandByName(string commandName)
  949. {
  950. CommandInfo<ICommand<TAppSession, TRequestInfo>> commandProxy;
  951. if (m_CommandContainer.TryGetValue(commandName, out commandProxy))
  952. return commandProxy;
  953. else
  954. return null;
  955. }
  956. private Func<TAppSession, byte[], int, int, bool> m_RawDataReceivedHandler;
  957. /// <summary>
  958. /// Gets or sets the raw binary data received event handler.
  959. /// TAppSession: session
  960. /// byte[]: receive buffer
  961. /// int: receive buffer offset
  962. /// int: receive lenght
  963. /// bool: whether process the received data further
  964. /// </summary>
  965. event Func<TAppSession, byte[], int, int, bool> IRawDataProcessor<TAppSession>.RawDataReceived
  966. {
  967. add { m_RawDataReceivedHandler += value; }
  968. remove { m_RawDataReceivedHandler -= value; }
  969. }
  970. /// <summary>
  971. /// Called when [raw data received].
  972. /// </summary>
  973. /// <param name="session">The session.</param>
  974. /// <param name="buffer">The buffer.</param>
  975. /// <param name="offset">The offset.</param>
  976. /// <param name="length">The length.</param>
  977. internal bool OnRawDataReceived(IAppSession session, byte[] buffer, int offset, int length)
  978. {
  979. var handler = m_RawDataReceivedHandler;
  980. if (handler == null)
  981. return true;
  982. return handler((TAppSession)session, buffer, offset, length);
  983. }
  984. private RequestHandler<TAppSession, TRequestInfo> m_RequestHandler;
  985. /// <summary>
  986. /// Occurs when a full request item received.
  987. /// </summary>
  988. public virtual event RequestHandler<TAppSession, TRequestInfo> NewRequestReceived
  989. {
  990. add { m_RequestHandler += value; }
  991. remove { m_RequestHandler -= value; }
  992. }
  993. /// <summary>
  994. /// Executes the command.
  995. /// </summary>
  996. /// <param name="session">The session.</param>
  997. /// <param name="requestInfo">The request info.</param>
  998. protected virtual void ExecuteCommand(TAppSession session, TRequestInfo requestInfo)
  999. {
  1000. if (m_RequestHandler == null)
  1001. {
  1002. var commandProxy = GetCommandByName(requestInfo.Key);
  1003. if (commandProxy != null)
  1004. {
  1005. var command = commandProxy.Command;
  1006. var commandFilters = commandProxy.Filters;
  1007. session.CurrentCommand = requestInfo.Key;
  1008. var cancelled = false;
  1009. if (commandFilters == null)
  1010. {
  1011. command.ExecuteCommand(session, requestInfo);
  1012. }
  1013. else
  1014. {
  1015. var commandContext = new CommandExecutingContext();
  1016. commandContext.Initialize(session, requestInfo, command);
  1017. for (var i = 0; i < commandFilters.Length; i++)
  1018. {
  1019. var filter = commandFilters[i];
  1020. filter.OnCommandExecuting(commandContext);
  1021. if (commandContext.Cancel)
  1022. {
  1023. cancelled = true;
  1024. Logger.LogInformation("The executing of the command {0} was cancelled by the command filter {1}.", command.Name, filter.GetType().ToString());
  1025. break;
  1026. }
  1027. }
  1028. if (!cancelled)
  1029. {
  1030. try
  1031. {
  1032. command.ExecuteCommand(session, requestInfo);
  1033. }
  1034. catch (Exception exc)
  1035. {
  1036. commandContext.Exception = exc;
  1037. }
  1038. for (var i = 0; i < commandFilters.Length; i++)
  1039. {
  1040. var filter = commandFilters[i];
  1041. filter.OnCommandExecuted(commandContext);
  1042. }
  1043. if (commandContext.Exception != null && !commandContext.ExceptionHandled)
  1044. {
  1045. try
  1046. {
  1047. session.InternalHandleExcetion(commandContext.Exception);
  1048. }
  1049. catch
  1050. {
  1051. }
  1052. }
  1053. }
  1054. }
  1055. if(!cancelled)
  1056. {
  1057. session.PrevCommand = requestInfo.Key;
  1058. if (Config.LogCommand)
  1059. Logger.LogInformation("Command - {0}", requestInfo.Key);
  1060. }
  1061. }
  1062. else
  1063. {
  1064. session.InternalHandleUnknownRequest(requestInfo);
  1065. }
  1066. session.LastActiveTime = DateTime.UtcNow;
  1067. }
  1068. else
  1069. {
  1070. session.CurrentCommand = requestInfo.Key;
  1071. try
  1072. {
  1073. m_RequestHandler(session, requestInfo);
  1074. }
  1075. catch (Exception e)
  1076. {
  1077. session.InternalHandleExcetion(e);
  1078. }
  1079. session.PrevCommand = requestInfo.Key;
  1080. session.LastActiveTime = DateTime.UtcNow;
  1081. if (Config.LogCommand)
  1082. Logger.LogInformation("Command - {0}", requestInfo.Key);
  1083. }
  1084. Interlocked.Increment(ref m_TotalHandledRequests);
  1085. }
  1086. /// <summary>
  1087. /// Executes the command for the session.
  1088. /// </summary>
  1089. /// <param name="session">The session.</param>
  1090. /// <param name="requestInfo">The request info.</param>
  1091. internal void ExecuteCommand(IAppSession session, TRequestInfo requestInfo)
  1092. {
  1093. this.ExecuteCommand((TAppSession)session, requestInfo);
  1094. }
  1095. /// <summary>
  1096. /// Executes the command.
  1097. /// </summary>
  1098. /// <param name="session">The session.</param>
  1099. /// <param name="requestInfo">The request info.</param>
  1100. void IRequestHandler<TRequestInfo>.ExecuteCommand(IAppSession session, TRequestInfo requestInfo)
  1101. {
  1102. this.ExecuteCommand((TAppSession)session, requestInfo);
  1103. }
  1104. /// <summary>
  1105. /// Gets or sets the server's connection filter
  1106. /// </summary>
  1107. /// <value>
  1108. /// The server's connection filters
  1109. /// </value>
  1110. public IEnumerable<IConnectionFilter> ConnectionFilters
  1111. {
  1112. get { return m_ConnectionFilters; }
  1113. }
  1114. /// <summary>
  1115. /// Executes the connection filters.
  1116. /// </summary>
  1117. /// <param name="remoteAddress">The remote address.</param>
  1118. /// <returns></returns>
  1119. private bool ExecuteConnectionFilters(IPEndPoint remoteAddress)
  1120. {
  1121. if (m_ConnectionFilters == null)
  1122. return true;
  1123. for (var i = 0; i < m_ConnectionFilters.Count; i++)
  1124. {
  1125. var currentFilter = m_ConnectionFilters[i];
  1126. if (!currentFilter.AllowConnect(remoteAddress))
  1127. {
  1128. Logger.LogInformation("A connection from {0} has been refused by filter {1}!", remoteAddress, currentFilter.Name);
  1129. return false;
  1130. }
  1131. }
  1132. return true;
  1133. }
  1134. /// <summary>
  1135. /// Creates the app session.
  1136. /// </summary>
  1137. /// <param name="socketSession">The socket session.</param>
  1138. /// <returns></returns>
  1139. IAppSession IAppServer.CreateAppSession(ISocketSession socketSession)
  1140. {
  1141. if (!ExecuteConnectionFilters(socketSession.RemoteEndPoint))
  1142. return NullAppSession;
  1143. var appSession = CreateAppSession(socketSession);
  1144. appSession.Initialize(this, socketSession);
  1145. return appSession;
  1146. }
  1147. /// <summary>
  1148. /// create a new TAppSession instance, you can override it to create the session instance in your own way
  1149. /// </summary>
  1150. /// <param name="socketSession">the socket session.</param>
  1151. /// <returns>the new created session instance</returns>
  1152. protected virtual TAppSession CreateAppSession(ISocketSession socketSession)
  1153. {
  1154. return new TAppSession();
  1155. }
  1156. /// <summary>
  1157. /// Registers the new created app session into the appserver's session container.
  1158. /// </summary>
  1159. /// <param name="session">The session.</param>
  1160. /// <returns></returns>
  1161. bool IAppServer.RegisterSession(IAppSession session)
  1162. {
  1163. var appSession = session as TAppSession;
  1164. if (!RegisterSession(appSession.SessionID, appSession))
  1165. return false;
  1166. appSession.SocketSession.Closed += OnSocketSessionClosed;
  1167. if (Config.LogBasicSessionActivity)
  1168. Logger.LogInformation("A new session connected! ");
  1169. OnNewSessionConnected(appSession);
  1170. return true;
  1171. }
  1172. /// <summary>
  1173. /// Registers the session into session container.
  1174. /// </summary>
  1175. /// <param name="sessionID">The session ID.</param>
  1176. /// <param name="appSession">The app session.</param>
  1177. /// <returns></returns>
  1178. protected virtual bool RegisterSession(string sessionID, TAppSession appSession)
  1179. {
  1180. return true;
  1181. }
  1182. private SessionHandler<TAppSession> m_NewSessionConnected;
  1183. /// <summary>
  1184. /// The action which will be executed after a new session connect
  1185. /// </summary>
  1186. public event SessionHandler<TAppSession> NewSessionConnected
  1187. {
  1188. add { m_NewSessionConnected += value; }
  1189. remove { m_NewSessionConnected -= value; }
  1190. }
  1191. /// <summary>
  1192. /// Called when [new session connected].
  1193. /// </summary>
  1194. /// <param name="session">The session.</param>
  1195. protected virtual void OnNewSessionConnected(TAppSession session)
  1196. {
  1197. var handler = m_NewSessionConnected;
  1198. if (handler == null)
  1199. return;
  1200. Task task = Task.Run(() => handler(session)).ContinueWith(OnNewSessionConnectedCallback);
  1201. //handler.BeginInvoke(session, OnNewSessionConnectedCallback, handler);
  1202. }
  1203. private void OnNewSessionConnectedCallback(Task task)
  1204. {
  1205. if (task.IsFaulted || task.Exception is not null)
  1206. Logger.LogError(task.Exception, task.Exception.Message);
  1207. }
  1208. /// <summary>
  1209. /// Resets the session's security protocol.
  1210. /// </summary>
  1211. /// <param name="session">The session.</param>
  1212. /// <param name="security">The security protocol.</param>
  1213. public void ResetSessionSecurity(IAppSession session, SslProtocols security)
  1214. {
  1215. m_SocketServer.ResetSessionSecurity(session, security);
  1216. }
  1217. /// <summary>
  1218. /// Called when [socket session closed].
  1219. /// </summary>
  1220. /// <param name="session">The socket session.</param>
  1221. /// <param name="reason">The reason.</param>
  1222. private void OnSocketSessionClosed(ISocketSession session, CloseReason reason)
  1223. {
  1224. //Even if LogBasicSessionActivity is false, we also log the unexpected closing because the close reason probably be useful
  1225. if ((Config.LogBasicSessionActivity || (reason != CloseReason.ServerClosing && reason != CloseReason.ClientClosing && reason != CloseReason.ServerShutdown && reason != CloseReason.SocketError)))
  1226. Logger.LogInformation(string.Format("This session was closed for {0}!", reason));
  1227. var appSession = session.AppSession as TAppSession;
  1228. appSession.Connected = false;
  1229. OnSessionClosed(appSession, reason);
  1230. }
  1231. private SessionHandler<TAppSession, CloseReason> m_SessionClosed;
  1232. /// <summary>
  1233. /// Gets/sets the session closed event handler.
  1234. /// </summary>
  1235. public event SessionHandler<TAppSession, CloseReason> SessionClosed
  1236. {
  1237. add { m_SessionClosed += value; }
  1238. remove { m_SessionClosed -= value; }
  1239. }
  1240. /// <summary>
  1241. /// Called when [session closed].
  1242. /// </summary>
  1243. /// <param name="session">The appSession.</param>
  1244. /// <param name="reason">The reason.</param>
  1245. protected virtual void OnSessionClosed(TAppSession session, CloseReason reason)
  1246. {
  1247. var handler = m_SessionClosed;
  1248. //if (handler != null)
  1249. //{
  1250. // handler.BeginInvoke(session, reason, OnSessionClosedCallback, handler);
  1251. //}
  1252. if (handler != null)
  1253. {
  1254. Task task = Task.Run(() => handler(session, reason)).ContinueWith(OnSessionClosedCallback);
  1255. }
  1256. session.OnSessionClosed(reason);
  1257. }
  1258. private void OnSessionClosedCallback(Task task)
  1259. {
  1260. if (task.IsFaulted || task.Exception is not null)
  1261. Logger.LogError(task.Exception, task.Exception.Message);
  1262. }
  1263. /// <summary>
  1264. /// Gets the app session by ID.
  1265. /// </summary>
  1266. /// <param name="sessionID">The session ID.</param>
  1267. /// <returns></returns>
  1268. public abstract TAppSession GetSessionByID(string sessionID);
  1269. /// <summary>
  1270. /// Gets the app session by ID.
  1271. /// </summary>
  1272. /// <param name="sessionID"></param>
  1273. /// <returns></returns>
  1274. IAppSession IAppServer.GetSessionByID(string sessionID)
  1275. {
  1276. return this.GetSessionByID(sessionID);
  1277. }
  1278. /// <summary>
  1279. /// Gets the matched sessions from sessions snapshot.
  1280. /// </summary>
  1281. /// <param name="critera">The prediction critera.</param>
  1282. public virtual IEnumerable<TAppSession> GetSessions(Func<TAppSession, bool> critera)
  1283. {
  1284. throw new NotSupportedException();
  1285. }
  1286. /// <summary>
  1287. /// Gets all sessions in sessions snapshot.
  1288. /// </summary>
  1289. public virtual IEnumerable<TAppSession> GetAllSessions()
  1290. {
  1291. throw new NotSupportedException();
  1292. }
  1293. /// <summary>
  1294. /// Gets the total session count.
  1295. /// </summary>
  1296. public abstract int SessionCount { get; }
  1297. /// <summary>
  1298. /// Gets the physical file path by the relative file path,
  1299. /// search both in the appserver's root and in the supersocket root dir if the isolation level has been set other than 'None'.
  1300. /// </summary>
  1301. /// <param name="relativeFilePath">The relative file path.</param>
  1302. /// <returns></returns>
  1303. public string GetFilePath(string relativeFilePath)
  1304. {
  1305. var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativeFilePath);
  1306. if (!System.IO.File.Exists(filePath) && RootConfig != null && RootConfig.Isolation != IsolationMode.None)
  1307. {
  1308. var rootDir = System.IO.Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
  1309. var rootFilePath = System.IO.Path.Combine(rootDir, relativeFilePath);
  1310. if (System.IO.File.Exists(rootFilePath))
  1311. return rootFilePath;
  1312. }
  1313. return filePath;
  1314. }
  1315. #region IActiveConnector
  1316. /// <summary>
  1317. /// Connect the remote endpoint actively.
  1318. /// </summary>
  1319. /// <param name="targetEndPoint">The target end point.</param>
  1320. /// <param name="localEndPoint">The local end point.</param>
  1321. /// <returns></returns>
  1322. /// <exception cref="System.Exception">This server cannot support active connect.</exception>
  1323. Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint, EndPoint localEndPoint)
  1324. {
  1325. var activeConnector = m_SocketServer as IActiveConnector;
  1326. if (activeConnector == null)
  1327. throw new Exception("This server cannot support active connect.");
  1328. return activeConnector.ActiveConnect(targetEndPoint, localEndPoint);
  1329. }
  1330. /// <summary>
  1331. /// Connect the remote endpoint actively.
  1332. /// </summary>
  1333. /// <param name="targetEndPoint">The target end point.</param>
  1334. /// <returns></returns>
  1335. /// <exception cref="System.Exception">This server cannot support active connect.</exception>
  1336. Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
  1337. {
  1338. return ((IActiveConnector)this).ActiveConnect(targetEndPoint, null);
  1339. }
  1340. #endregion IActiveConnector
  1341. #region ISystemEndPoint
  1342. /// <summary>
  1343. /// Transfers the system message
  1344. /// </summary>
  1345. /// <param name="messageType">Type of the message.</param>
  1346. /// <param name="messageData">The message data.</param>
  1347. void ISystemEndPoint.TransferSystemMessage(string messageType, object messageData)
  1348. {
  1349. OnSystemMessageReceived(messageType, messageData);
  1350. }
  1351. /// <summary>
  1352. /// Called when [system message received].
  1353. /// </summary>
  1354. /// <param name="messageType">Type of the message.</param>
  1355. /// <param name="messageData">The message data.</param>
  1356. protected virtual void OnSystemMessageReceived(string messageType, object messageData)
  1357. {
  1358. }
  1359. #endregion ISystemEndPoint
  1360. #region IStatusInfoSource
  1361. private StatusInfoCollection m_ServerStatus;
  1362. StatusInfoAttribute[] IStatusInfoSource.GetServerStatusMetadata()
  1363. {
  1364. return this.GetType().GetStatusInfoMetadata();
  1365. }
  1366. StatusInfoCollection IStatusInfoSource.CollectServerStatus(StatusInfoCollection bootstrapStatus)
  1367. {
  1368. UpdateServerStatus(m_ServerStatus);
  1369. this.AsyncRun(() => OnServerStatusCollected(bootstrapStatus, m_ServerStatus), e => Logger.LogError(e,e.Message));
  1370. return m_ServerStatus;
  1371. }
  1372. /// <summary>
  1373. /// Updates the summary of the server.
  1374. /// </summary>
  1375. /// <param name="serverStatus">The server status.</param>
  1376. protected virtual void UpdateServerStatus(StatusInfoCollection serverStatus)
  1377. {
  1378. DateTime now = DateTime.UtcNow;
  1379. serverStatus[StatusInfoKeys.IsRunning] = m_StateCode == ServerStateConst.Running;
  1380. serverStatus[StatusInfoKeys.TotalConnections] = this.SessionCount;
  1381. var totalHandledRequests0 = serverStatus.GetValue<long>(StatusInfoKeys.TotalHandledRequests, 0);
  1382. var totalHandledRequests = this.TotalHandledRequests;
  1383. serverStatus[StatusInfoKeys.RequestHandlingSpeed] = ((totalHandledRequests - totalHandledRequests0) / now.Subtract(serverStatus.CollectedTime).TotalSeconds);
  1384. serverStatus[StatusInfoKeys.TotalHandledRequests] = totalHandledRequests;
  1385. if (State == ServerState.Running)
  1386. {
  1387. var sendingQueuePool = m_SocketServer.SendingQueuePool;
  1388. serverStatus[StatusInfoKeys.AvialableSendingQueueItems] = sendingQueuePool.AvialableItemsCount;
  1389. serverStatus[StatusInfoKeys.TotalSendingQueueItems] = sendingQueuePool.TotalItemsCount;
  1390. }
  1391. else
  1392. {
  1393. serverStatus[StatusInfoKeys.AvialableSendingQueueItems] = 0;
  1394. serverStatus[StatusInfoKeys.TotalSendingQueueItems] = 0;
  1395. }
  1396. serverStatus.CollectedTime = now;
  1397. }
  1398. /// <summary>
  1399. /// Called when [server status collected].
  1400. /// </summary>
  1401. /// <param name="bootstrapStatus">The bootstrapStatus status.</param>
  1402. /// <param name="serverStatus">The server status.</param>
  1403. protected virtual void OnServerStatusCollected(StatusInfoCollection bootstrapStatus, StatusInfoCollection serverStatus)
  1404. {
  1405. }
  1406. #endregion IStatusInfoSource
  1407. #region IDisposable Members
  1408. /// <summary>
  1409. /// Releases unmanaged and - optionally - managed resources
  1410. /// </summary>
  1411. public void Dispose()
  1412. {
  1413. if (m_StateCode == ServerStateConst.Running)
  1414. Stop();
  1415. }
  1416. #endregion
  1417. }
  1418. }