AppServerBase.cs 62 KB

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