AppServerBase.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716
  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. Logger.LogError("Failed to parse '{0}' to SslProtocol!", config.Security);
  672. return false;
  673. }
  674. BasicSecurity = configProtocol;
  675. }
  676. else
  677. {
  678. BasicSecurity = SslProtocols.None;
  679. }
  680. try
  681. {
  682. var certificate = GetCertificate(config.Certificate);
  683. if (certificate != null)
  684. {
  685. Certificate = certificate;
  686. }
  687. else if(BasicSecurity != SslProtocols.None)
  688. {
  689. Logger.LogError("Certificate is required in this security mode!");
  690. return false;
  691. }
  692. }
  693. catch (Exception e)
  694. {
  695. Logger.LogError(e , "Failed to initialize certificate!");
  696. return false;
  697. }
  698. return true;
  699. }
  700. /// <summary>
  701. /// Gets the certificate from server configuguration.
  702. /// </summary>
  703. /// <param name="certificate">The certificate config.</param>
  704. /// <returns></returns>
  705. protected virtual X509Certificate GetCertificate(ICertificateConfig certificate)
  706. {
  707. Logger.LogDebug($"{certificate.StoreName} {certificate.FilePath} {certificate.Password}");
  708. if (certificate == null)
  709. {
  710. if (BasicSecurity != SslProtocols.None)
  711. Logger.LogError("There is no certificate configured!");
  712. return null;
  713. }
  714. if (string.IsNullOrEmpty(certificate.FilePath) && string.IsNullOrEmpty(certificate.Thumbprint))
  715. {
  716. if (BasicSecurity != SslProtocols.None)
  717. Logger.LogError("You should define certificate node and either attribute 'filePath' or 'thumbprint' is required!");
  718. return null;
  719. }
  720. return CertificateManager.Initialize(certificate, GetFilePath);
  721. }
  722. bool IRemoteCertificateValidator.Validate(IAppSession session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  723. {
  724. return ValidateClientCertificate((TAppSession)session, sender, certificate, chain, sslPolicyErrors);
  725. }
  726. /// <summary>
  727. /// Validates the client certificate. This method is only used if the certificate configuration attribute "clientCertificateRequired" is true.
  728. /// </summary>
  729. /// <param name="session">The session.</param>
  730. /// <param name="sender">The sender.</param>
  731. /// <param name="certificate">The certificate.</param>
  732. /// <param name="chain">The chain.</param>
  733. /// <param name="sslPolicyErrors">The SSL policy errors.</param>
  734. /// <returns>return the validation result</returns>
  735. protected virtual bool ValidateClientCertificate(TAppSession session, object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  736. {
  737. return sslPolicyErrors == SslPolicyErrors.None;
  738. }
  739. /// <summary>
  740. /// Setups the socket server.instance
  741. /// </summary>
  742. /// <returns></returns>
  743. private bool SetupSocketServer()
  744. {
  745. try
  746. {
  747. m_SocketServer = m_SocketServerFactory.CreateSocketServer<TRequestInfo>(this, m_Listeners, Config);
  748. return m_SocketServer != null;
  749. }
  750. catch (Exception e)
  751. {
  752. Logger.LogError(e,e.Message);
  753. return false;
  754. }
  755. }
  756. private IPAddress ParseIPAddress(string ip)
  757. {
  758. if (string.IsNullOrEmpty(ip) || "Any".Equals(ip, StringComparison.OrdinalIgnoreCase))
  759. return IPAddress.Any;
  760. else if ("IPv6Any".Equals(ip, StringComparison.OrdinalIgnoreCase))
  761. return IPAddress.IPv6Any;
  762. else
  763. return IPAddress.Parse(ip);
  764. }
  765. /// <summary>
  766. /// Setups the listeners base on server configuration
  767. /// </summary>
  768. /// <param name="config">The config.</param>
  769. /// <returns></returns>
  770. private bool SetupListeners(IServerConfig config)
  771. {
  772. var listeners = new List<ListenerInfo>();
  773. try
  774. {
  775. if (config.Port > 0)
  776. {
  777. listeners.Add(new ListenerInfo
  778. {
  779. EndPoint = new IPEndPoint(ParseIPAddress(config.Ip), config.Port),
  780. BackLog = config.ListenBacklog,
  781. Security = BasicSecurity
  782. });
  783. }
  784. else
  785. {
  786. //Port is not configured, but ip is configured
  787. if (!string.IsNullOrEmpty(config.Ip))
  788. {
  789. Logger.LogError("Port is required in config!");
  790. return false;
  791. }
  792. }
  793. //There are listener defined
  794. if (config.Listeners != null && config.Listeners.Any())
  795. {
  796. //But ip and port were configured in server node
  797. //We don't allow this case
  798. if (listeners.Any())
  799. {
  800. Logger.LogError("If you configured Ip and Port in server node, you cannot defined listener in listeners node any more!");
  801. return false;
  802. }
  803. foreach (var l in config.Listeners)
  804. {
  805. SslProtocols configProtocol;
  806. if (string.IsNullOrEmpty(l.Security))
  807. {
  808. configProtocol = BasicSecurity;
  809. }
  810. else if (!l.Security.TryParseEnum<SslProtocols>(true, out configProtocol))
  811. {
  812. Logger.LogError("Failed to parse '{0}' to SslProtocol!", config.Security);
  813. return false;
  814. }
  815. if (configProtocol != SslProtocols.None && (Certificate == null))
  816. {
  817. Logger.LogError("There is no certificate loaded, but there is a secure listener defined!");
  818. return false;
  819. }
  820. listeners.Add(new ListenerInfo
  821. {
  822. EndPoint = new IPEndPoint(ParseIPAddress(l.Ip), l.Port),
  823. BackLog = l.Backlog,
  824. Security = configProtocol
  825. });
  826. }
  827. }
  828. if (!listeners.Any())
  829. {
  830. Logger.LogError("No listener defined!");
  831. return false;
  832. }
  833. m_Listeners = listeners.ToArray();
  834. return true;
  835. }
  836. catch (Exception e)
  837. {
  838. Logger.LogError(e,e.Message);
  839. return false;
  840. }
  841. }
  842. /// <summary>
  843. /// Gets the name of the server instance.
  844. /// </summary>
  845. public string Name
  846. {
  847. get { return m_Name; }
  848. }
  849. private ISocketServer m_SocketServer;
  850. /// <summary>
  851. /// Gets the socket server.
  852. /// </summary>
  853. /// <value>
  854. /// The socket server.
  855. /// </value>
  856. ISocketServer ISocketServerAccessor.SocketServer
  857. {
  858. get { return m_SocketServer; }
  859. }
  860. /// <summary>
  861. /// Starts this server instance.
  862. /// </summary>
  863. /// <returns>
  864. /// return true if start successfull, else false
  865. /// </returns>
  866. public virtual bool Start()
  867. {
  868. var origStateCode = Interlocked.CompareExchange(ref m_StateCode, ServerStateConst.Starting, ServerStateConst.NotStarted);
  869. if (origStateCode != ServerStateConst.NotStarted)
  870. {
  871. if (origStateCode < ServerStateConst.NotStarted)
  872. throw new Exception("You cannot start a server instance which has not been setup yet.");
  873. Logger.LogError("This server instance is in the state {0}, you cannot start it now.", (ServerState)origStateCode);
  874. return false;
  875. }
  876. if (!m_SocketServer.Start())
  877. {
  878. m_StateCode = ServerStateConst.NotStarted;
  879. return false;
  880. }
  881. StartedTime = DateTime.UtcNow;
  882. m_StateCode = ServerStateConst.Running;
  883. m_ServerStatus[StatusInfoKeys.IsRunning] = true;
  884. m_ServerStatus[StatusInfoKeys.StartedTime] = StartedTime;
  885. try
  886. {
  887. //Will be removed in the next version
  888. #pragma warning disable 0612, 618
  889. OnStartup();
  890. #pragma warning restore 0612, 618
  891. OnStarted();
  892. }
  893. catch (Exception e)
  894. {
  895. Logger.LogError("One exception wa thrown in the method 'OnStartup()'.", e);
  896. }
  897. finally
  898. {
  899. Logger.LogInformation("The server instance {0} has been started!", Name);
  900. }
  901. return true;
  902. }
  903. /// <summary>
  904. /// Called when [startup].
  905. /// </summary>
  906. [Obsolete("Use OnStarted() instead")]
  907. protected virtual void OnStartup()
  908. {
  909. }
  910. /// <summary>
  911. /// Called when [started].
  912. /// </summary>
  913. protected virtual void OnStarted()
  914. {
  915. }
  916. /// <summary>
  917. /// Called when [stopped].
  918. /// </summary>
  919. protected virtual void OnStopped()
  920. {
  921. }
  922. /// <summary>
  923. /// Stops this server instance.
  924. /// </summary>
  925. public virtual void Stop()
  926. {
  927. if (Interlocked.CompareExchange(ref m_StateCode, ServerStateConst.Stopping, ServerStateConst.Running)
  928. != ServerStateConst.Running)
  929. {
  930. return;
  931. }
  932. m_SocketServer.Stop();
  933. m_StateCode = ServerStateConst.NotStarted;
  934. OnStopped();
  935. m_ServerStatus[StatusInfoKeys.IsRunning] = false;
  936. m_ServerStatus[StatusInfoKeys.StartedTime] = null;
  937. Logger.LogInformation("The server instance {0} has been stopped!", Name);
  938. }
  939. /// <summary>
  940. /// Gets command by command name.
  941. /// </summary>
  942. /// <param name="commandName">Name of the command.</param>
  943. /// <returns></returns>
  944. private CommandInfo<ICommand<TAppSession, TRequestInfo>> GetCommandByName(string commandName)
  945. {
  946. CommandInfo<ICommand<TAppSession, TRequestInfo>> commandProxy;
  947. if (m_CommandContainer.TryGetValue(commandName, out commandProxy))
  948. return commandProxy;
  949. else
  950. return null;
  951. }
  952. private Func<TAppSession, byte[], int, int, bool> m_RawDataReceivedHandler;
  953. /// <summary>
  954. /// Gets or sets the raw binary data received event handler.
  955. /// TAppSession: session
  956. /// byte[]: receive buffer
  957. /// int: receive buffer offset
  958. /// int: receive lenght
  959. /// bool: whether process the received data further
  960. /// </summary>
  961. event Func<TAppSession, byte[], int, int, bool> IRawDataProcessor<TAppSession>.RawDataReceived
  962. {
  963. add { m_RawDataReceivedHandler += value; }
  964. remove { m_RawDataReceivedHandler -= value; }
  965. }
  966. /// <summary>
  967. /// Called when [raw data received].
  968. /// </summary>
  969. /// <param name="session">The session.</param>
  970. /// <param name="buffer">The buffer.</param>
  971. /// <param name="offset">The offset.</param>
  972. /// <param name="length">The length.</param>
  973. internal bool OnRawDataReceived(IAppSession session, byte[] buffer, int offset, int length)
  974. {
  975. var handler = m_RawDataReceivedHandler;
  976. if (handler == null)
  977. return true;
  978. return handler((TAppSession)session, buffer, offset, length);
  979. }
  980. private RequestHandler<TAppSession, TRequestInfo> m_RequestHandler;
  981. /// <summary>
  982. /// Occurs when a full request item received.
  983. /// </summary>
  984. public virtual event RequestHandler<TAppSession, TRequestInfo> NewRequestReceived
  985. {
  986. add { m_RequestHandler += value; }
  987. remove { m_RequestHandler -= value; }
  988. }
  989. /// <summary>
  990. /// Executes the command.
  991. /// </summary>
  992. /// <param name="session">The session.</param>
  993. /// <param name="requestInfo">The request info.</param>
  994. protected virtual void ExecuteCommand(TAppSession session, TRequestInfo requestInfo)
  995. {
  996. if (m_RequestHandler == null)
  997. {
  998. var commandProxy = GetCommandByName(requestInfo.Key);
  999. if (commandProxy != null)
  1000. {
  1001. var command = commandProxy.Command;
  1002. var commandFilters = commandProxy.Filters;
  1003. session.CurrentCommand = requestInfo.Key;
  1004. var cancelled = false;
  1005. if (commandFilters == null)
  1006. {
  1007. command.ExecuteCommand(session, requestInfo);
  1008. }
  1009. else
  1010. {
  1011. var commandContext = new CommandExecutingContext();
  1012. commandContext.Initialize(session, requestInfo, command);
  1013. for (var i = 0; i < commandFilters.Length; i++)
  1014. {
  1015. var filter = commandFilters[i];
  1016. filter.OnCommandExecuting(commandContext);
  1017. if (commandContext.Cancel)
  1018. {
  1019. cancelled = true;
  1020. Logger.LogInformation("The executing of the command {0} was cancelled by the command filter {1}.", command.Name, filter.GetType().ToString());
  1021. break;
  1022. }
  1023. }
  1024. if (!cancelled)
  1025. {
  1026. try
  1027. {
  1028. command.ExecuteCommand(session, requestInfo);
  1029. }
  1030. catch (Exception exc)
  1031. {
  1032. commandContext.Exception = exc;
  1033. }
  1034. for (var i = 0; i < commandFilters.Length; i++)
  1035. {
  1036. var filter = commandFilters[i];
  1037. filter.OnCommandExecuted(commandContext);
  1038. }
  1039. if (commandContext.Exception != null && !commandContext.ExceptionHandled)
  1040. {
  1041. try
  1042. {
  1043. session.InternalHandleExcetion(commandContext.Exception);
  1044. }
  1045. catch
  1046. {
  1047. }
  1048. }
  1049. }
  1050. }
  1051. if(!cancelled)
  1052. {
  1053. session.PrevCommand = requestInfo.Key;
  1054. if (Config.LogCommand)
  1055. Logger.LogInformation("Command - {0}", requestInfo.Key);
  1056. }
  1057. }
  1058. else
  1059. {
  1060. session.InternalHandleUnknownRequest(requestInfo);
  1061. }
  1062. session.LastActiveTime = DateTime.UtcNow;
  1063. }
  1064. else
  1065. {
  1066. session.CurrentCommand = requestInfo.Key;
  1067. try
  1068. {
  1069. m_RequestHandler(session, requestInfo);
  1070. }
  1071. catch (Exception e)
  1072. {
  1073. session.InternalHandleExcetion(e);
  1074. }
  1075. session.PrevCommand = requestInfo.Key;
  1076. session.LastActiveTime = DateTime.UtcNow;
  1077. if (Config.LogCommand)
  1078. Logger.LogInformation("Command - {0}", requestInfo.Key);
  1079. }
  1080. Interlocked.Increment(ref m_TotalHandledRequests);
  1081. }
  1082. /// <summary>
  1083. /// Executes the command for the session.
  1084. /// </summary>
  1085. /// <param name="session">The session.</param>
  1086. /// <param name="requestInfo">The request info.</param>
  1087. internal void ExecuteCommand(IAppSession session, TRequestInfo requestInfo)
  1088. {
  1089. this.ExecuteCommand((TAppSession)session, requestInfo);
  1090. }
  1091. /// <summary>
  1092. /// Executes the command.
  1093. /// </summary>
  1094. /// <param name="session">The session.</param>
  1095. /// <param name="requestInfo">The request info.</param>
  1096. void IRequestHandler<TRequestInfo>.ExecuteCommand(IAppSession session, TRequestInfo requestInfo)
  1097. {
  1098. this.ExecuteCommand((TAppSession)session, requestInfo);
  1099. }
  1100. /// <summary>
  1101. /// Gets or sets the server's connection filter
  1102. /// </summary>
  1103. /// <value>
  1104. /// The server's connection filters
  1105. /// </value>
  1106. public IEnumerable<IConnectionFilter> ConnectionFilters
  1107. {
  1108. get { return m_ConnectionFilters; }
  1109. }
  1110. /// <summary>
  1111. /// Executes the connection filters.
  1112. /// </summary>
  1113. /// <param name="remoteAddress">The remote address.</param>
  1114. /// <returns></returns>
  1115. private bool ExecuteConnectionFilters(IPEndPoint remoteAddress)
  1116. {
  1117. if (m_ConnectionFilters == null)
  1118. return true;
  1119. for (var i = 0; i < m_ConnectionFilters.Count; i++)
  1120. {
  1121. var currentFilter = m_ConnectionFilters[i];
  1122. if (!currentFilter.AllowConnect(remoteAddress))
  1123. {
  1124. Logger.LogInformation("A connection from {0} has been refused by filter {1}!", remoteAddress, currentFilter.Name);
  1125. return false;
  1126. }
  1127. }
  1128. return true;
  1129. }
  1130. /// <summary>
  1131. /// Creates the app session.
  1132. /// </summary>
  1133. /// <param name="socketSession">The socket session.</param>
  1134. /// <returns></returns>
  1135. IAppSession IAppServer.CreateAppSession(ISocketSession socketSession)
  1136. {
  1137. if (!ExecuteConnectionFilters(socketSession.RemoteEndPoint))
  1138. return NullAppSession;
  1139. var appSession = CreateAppSession(socketSession);
  1140. appSession.Initialize(this, socketSession);
  1141. return appSession;
  1142. }
  1143. /// <summary>
  1144. /// create a new TAppSession instance, you can override it to create the session instance in your own way
  1145. /// </summary>
  1146. /// <param name="socketSession">the socket session.</param>
  1147. /// <returns>the new created session instance</returns>
  1148. protected virtual TAppSession CreateAppSession(ISocketSession socketSession)
  1149. {
  1150. return new TAppSession();
  1151. }
  1152. /// <summary>
  1153. /// Registers the new created app session into the appserver's session container.
  1154. /// </summary>
  1155. /// <param name="session">The session.</param>
  1156. /// <returns></returns>
  1157. bool IAppServer.RegisterSession(IAppSession session)
  1158. {
  1159. var appSession = session as TAppSession;
  1160. if (!RegisterSession(appSession.SessionID, appSession))
  1161. return false;
  1162. appSession.SocketSession.Closed += OnSocketSessionClosed;
  1163. if (Config.LogBasicSessionActivity)
  1164. Logger.LogInformation("A new session connected! ");
  1165. OnNewSessionConnected(appSession);
  1166. return true;
  1167. }
  1168. /// <summary>
  1169. /// Registers the session into session container.
  1170. /// </summary>
  1171. /// <param name="sessionID">The session ID.</param>
  1172. /// <param name="appSession">The app session.</param>
  1173. /// <returns></returns>
  1174. protected virtual bool RegisterSession(string sessionID, TAppSession appSession)
  1175. {
  1176. return true;
  1177. }
  1178. private SessionHandler<TAppSession> m_NewSessionConnected;
  1179. /// <summary>
  1180. /// The action which will be executed after a new session connect
  1181. /// </summary>
  1182. public event SessionHandler<TAppSession> NewSessionConnected
  1183. {
  1184. add { m_NewSessionConnected += value; }
  1185. remove { m_NewSessionConnected -= value; }
  1186. }
  1187. /// <summary>
  1188. /// Called when [new session connected].
  1189. /// </summary>
  1190. /// <param name="session">The session.</param>
  1191. protected virtual void OnNewSessionConnected(TAppSession session)
  1192. {
  1193. var handler = m_NewSessionConnected;
  1194. if (handler == null)
  1195. return;
  1196. Task task = Task.Run(() => handler(session)).ContinueWith(OnNewSessionConnectedCallback);
  1197. //handler.BeginInvoke(session, OnNewSessionConnectedCallback, handler);
  1198. }
  1199. private void OnNewSessionConnectedCallback(Task task)
  1200. {
  1201. if (task.IsFaulted || task.Exception is not null)
  1202. Logger.LogError(task.Exception, task.Exception.Message);
  1203. }
  1204. /// <summary>
  1205. /// Resets the session's security protocol.
  1206. /// </summary>
  1207. /// <param name="session">The session.</param>
  1208. /// <param name="security">The security protocol.</param>
  1209. public void ResetSessionSecurity(IAppSession session, SslProtocols security)
  1210. {
  1211. m_SocketServer.ResetSessionSecurity(session, security);
  1212. }
  1213. /// <summary>
  1214. /// Called when [socket session closed].
  1215. /// </summary>
  1216. /// <param name="session">The socket session.</param>
  1217. /// <param name="reason">The reason.</param>
  1218. private void OnSocketSessionClosed(ISocketSession session, CloseReason reason)
  1219. {
  1220. //Even if LogBasicSessionActivity is false, we also log the unexpected closing because the close reason probably be useful
  1221. if ((Config.LogBasicSessionActivity || (reason != CloseReason.ServerClosing && reason != CloseReason.ClientClosing && reason != CloseReason.ServerShutdown && reason != CloseReason.SocketError)))
  1222. Logger.LogInformation(string.Format("This session was closed for {0}!", reason));
  1223. var appSession = session.AppSession as TAppSession;
  1224. appSession.Connected = false;
  1225. OnSessionClosed(appSession, reason);
  1226. }
  1227. private SessionHandler<TAppSession, CloseReason> m_SessionClosed;
  1228. /// <summary>
  1229. /// Gets/sets the session closed event handler.
  1230. /// </summary>
  1231. public event SessionHandler<TAppSession, CloseReason> SessionClosed
  1232. {
  1233. add { m_SessionClosed += value; }
  1234. remove { m_SessionClosed -= value; }
  1235. }
  1236. /// <summary>
  1237. /// Called when [session closed].
  1238. /// </summary>
  1239. /// <param name="session">The appSession.</param>
  1240. /// <param name="reason">The reason.</param>
  1241. protected virtual void OnSessionClosed(TAppSession session, CloseReason reason)
  1242. {
  1243. var handler = m_SessionClosed;
  1244. //if (handler != null)
  1245. //{
  1246. // handler.BeginInvoke(session, reason, OnSessionClosedCallback, handler);
  1247. //}
  1248. if (handler != null)
  1249. {
  1250. Task task = Task.Run(() => handler(session, reason)).ContinueWith(OnSessionClosedCallback);
  1251. }
  1252. session.OnSessionClosed(reason);
  1253. }
  1254. private void OnSessionClosedCallback(Task task)
  1255. {
  1256. if (task.IsFaulted || task.Exception is not null)
  1257. Logger.LogError(task.Exception, task.Exception.Message);
  1258. }
  1259. /// <summary>
  1260. /// Gets the app session by ID.
  1261. /// </summary>
  1262. /// <param name="sessionID">The session ID.</param>
  1263. /// <returns></returns>
  1264. public abstract TAppSession GetSessionByID(string sessionID);
  1265. /// <summary>
  1266. /// Gets the app session by ID.
  1267. /// </summary>
  1268. /// <param name="sessionID"></param>
  1269. /// <returns></returns>
  1270. IAppSession IAppServer.GetSessionByID(string sessionID)
  1271. {
  1272. return this.GetSessionByID(sessionID);
  1273. }
  1274. /// <summary>
  1275. /// Gets the matched sessions from sessions snapshot.
  1276. /// </summary>
  1277. /// <param name="critera">The prediction critera.</param>
  1278. public virtual IEnumerable<TAppSession> GetSessions(Func<TAppSession, bool> critera)
  1279. {
  1280. throw new NotSupportedException();
  1281. }
  1282. /// <summary>
  1283. /// Gets all sessions in sessions snapshot.
  1284. /// </summary>
  1285. public virtual IEnumerable<TAppSession> GetAllSessions()
  1286. {
  1287. throw new NotSupportedException();
  1288. }
  1289. /// <summary>
  1290. /// Gets the total session count.
  1291. /// </summary>
  1292. public abstract int SessionCount { get; }
  1293. /// <summary>
  1294. /// Gets the physical file path by the relative file path,
  1295. /// search both in the appserver's root and in the supersocket root dir if the isolation level has been set other than 'None'.
  1296. /// </summary>
  1297. /// <param name="relativeFilePath">The relative file path.</param>
  1298. /// <returns></returns>
  1299. public string GetFilePath(string relativeFilePath)
  1300. {
  1301. var filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativeFilePath);
  1302. if (!System.IO.File.Exists(filePath) && RootConfig != null && RootConfig.Isolation != IsolationMode.None)
  1303. {
  1304. var rootDir = System.IO.Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
  1305. var rootFilePath = System.IO.Path.Combine(rootDir, relativeFilePath);
  1306. if (System.IO.File.Exists(rootFilePath))
  1307. return rootFilePath;
  1308. }
  1309. return filePath;
  1310. }
  1311. #region IActiveConnector
  1312. /// <summary>
  1313. /// Connect the remote endpoint actively.
  1314. /// </summary>
  1315. /// <param name="targetEndPoint">The target end point.</param>
  1316. /// <param name="localEndPoint">The local end point.</param>
  1317. /// <returns></returns>
  1318. /// <exception cref="System.Exception">This server cannot support active connect.</exception>
  1319. Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint, EndPoint localEndPoint)
  1320. {
  1321. var activeConnector = m_SocketServer as IActiveConnector;
  1322. if (activeConnector == null)
  1323. throw new Exception("This server cannot support active connect.");
  1324. return activeConnector.ActiveConnect(targetEndPoint, localEndPoint);
  1325. }
  1326. /// <summary>
  1327. /// Connect the remote endpoint actively.
  1328. /// </summary>
  1329. /// <param name="targetEndPoint">The target end point.</param>
  1330. /// <returns></returns>
  1331. /// <exception cref="System.Exception">This server cannot support active connect.</exception>
  1332. Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint)
  1333. {
  1334. return ((IActiveConnector)this).ActiveConnect(targetEndPoint, null);
  1335. }
  1336. #endregion IActiveConnector
  1337. #region ISystemEndPoint
  1338. /// <summary>
  1339. /// Transfers the system message
  1340. /// </summary>
  1341. /// <param name="messageType">Type of the message.</param>
  1342. /// <param name="messageData">The message data.</param>
  1343. void ISystemEndPoint.TransferSystemMessage(string messageType, object messageData)
  1344. {
  1345. OnSystemMessageReceived(messageType, messageData);
  1346. }
  1347. /// <summary>
  1348. /// Called when [system message received].
  1349. /// </summary>
  1350. /// <param name="messageType">Type of the message.</param>
  1351. /// <param name="messageData">The message data.</param>
  1352. protected virtual void OnSystemMessageReceived(string messageType, object messageData)
  1353. {
  1354. }
  1355. #endregion ISystemEndPoint
  1356. #region IStatusInfoSource
  1357. private StatusInfoCollection m_ServerStatus;
  1358. StatusInfoAttribute[] IStatusInfoSource.GetServerStatusMetadata()
  1359. {
  1360. return this.GetType().GetStatusInfoMetadata();
  1361. }
  1362. StatusInfoCollection IStatusInfoSource.CollectServerStatus(StatusInfoCollection bootstrapStatus)
  1363. {
  1364. UpdateServerStatus(m_ServerStatus);
  1365. this.AsyncRun(() => OnServerStatusCollected(bootstrapStatus, m_ServerStatus), e => Logger.LogError(e,e.Message));
  1366. return m_ServerStatus;
  1367. }
  1368. /// <summary>
  1369. /// Updates the summary of the server.
  1370. /// </summary>
  1371. /// <param name="serverStatus">The server status.</param>
  1372. protected virtual void UpdateServerStatus(StatusInfoCollection serverStatus)
  1373. {
  1374. DateTime now = DateTime.UtcNow;
  1375. serverStatus[StatusInfoKeys.IsRunning] = m_StateCode == ServerStateConst.Running;
  1376. serverStatus[StatusInfoKeys.TotalConnections] = this.SessionCount;
  1377. var totalHandledRequests0 = serverStatus.GetValue<long>(StatusInfoKeys.TotalHandledRequests, 0);
  1378. var totalHandledRequests = this.TotalHandledRequests;
  1379. serverStatus[StatusInfoKeys.RequestHandlingSpeed] = ((totalHandledRequests - totalHandledRequests0) / now.Subtract(serverStatus.CollectedTime).TotalSeconds);
  1380. serverStatus[StatusInfoKeys.TotalHandledRequests] = totalHandledRequests;
  1381. if (State == ServerState.Running)
  1382. {
  1383. var sendingQueuePool = m_SocketServer.SendingQueuePool;
  1384. serverStatus[StatusInfoKeys.AvialableSendingQueueItems] = sendingQueuePool.AvialableItemsCount;
  1385. serverStatus[StatusInfoKeys.TotalSendingQueueItems] = sendingQueuePool.TotalItemsCount;
  1386. }
  1387. else
  1388. {
  1389. serverStatus[StatusInfoKeys.AvialableSendingQueueItems] = 0;
  1390. serverStatus[StatusInfoKeys.TotalSendingQueueItems] = 0;
  1391. }
  1392. serverStatus.CollectedTime = now;
  1393. }
  1394. /// <summary>
  1395. /// Called when [server status collected].
  1396. /// </summary>
  1397. /// <param name="bootstrapStatus">The bootstrapStatus status.</param>
  1398. /// <param name="serverStatus">The server status.</param>
  1399. protected virtual void OnServerStatusCollected(StatusInfoCollection bootstrapStatus, StatusInfoCollection serverStatus)
  1400. {
  1401. }
  1402. #endregion IStatusInfoSource
  1403. #region IDisposable Members
  1404. /// <summary>
  1405. /// Releases unmanaged and - optionally - managed resources
  1406. /// </summary>
  1407. public void Dispose()
  1408. {
  1409. if (m_StateCode == ServerStateConst.Running)
  1410. Stop();
  1411. }
  1412. #endregion
  1413. }
  1414. }