123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280 |
- using System;
- using System.Collections.Generic;
- using Vinno.IUS.Common.Log;
- using Vinno.vCloud.Protocol.Initializers;
- using vCloud.Server.Configuration;
- using vCloud.Server.Logs;
- using vCloud.Server.ServerProtocol;
- using vCloud.Server.Services;
- using Vinno.IUS.Common.Network.Transfer;
- using Vinno.IUS.Common.Network;
- using vCloud.Server.Bus;
- using System.Threading.Tasks;
- using vCloud.Server.Services.ServerRegistry;
- using vCloud.Server.Services.Management;
- using System.Diagnostics;
- using System.IO;
- using Vinno.IUS.Common.Utilities;
- using vCloud.Server.Services.Database;
- using vCloud.Server.Utilities;
- using System.Configuration;
- namespace vCloud.Server
- {
- public class vCloudServer
- {
- private List<string> _dependencieNames = new List<string>();
- private readonly List<Service> _localServices = new List<Service>();
- private vCloudServiceBus _serviceBus;
- /// <summary>
- /// Gets all local service which be contained by this server.
- /// </summary>
- public IReadOnlyList<Service> LocalServices => _localServices;
- public vCloudServer(out bool isStartSuccess)
- {
- isStartSuccess = false;
- #if DEBUG
- #else
- if (!vCloudLicense.Instance.VerifyLicnese())
- {
- return;
- }
- vCloudLicense.Instance.NotifyLicenseExpirationClosedEvent += OnNotifyLicenseExpirationClosedEvent;
- #endif
- try
- {
- CommonInitializer.Initialize(AppContext.BaseDirectory); //TODO
- ServerTagsInitializer.Initialize();
- vCloudServerInitializer.Initialize();
- InitializeMessagePoolConfig();
- InitializeServiceBus();
- InitializeServices();
- DbMaintenance.SetDbVersion(_serviceBus.LocalHostMode, _serviceBus.IsMaster);
- Logger.WriteLineInfo("vCloud Server started!");
- InitializeAutoClearCache();
- isStartSuccess = true;
- StartDBAutoBackup();
- SetStarted();
- NationalPlatformHelper.Init();
- if (NationalPlatformHelper.IsFisrtSync)
- {
- DataSyncHelper.OrgDatasSync();
- DataSyncHelper.UserDatasSync();
- }
- #if DEBUG
- //NationalPlatformHelper.UploadUserInfo("Loki", "23192", "超声医学科", "NX6401052020000007",new DateTime(2022,04,02)).GetAwaiter().GetResult();
- //NationalPlatformHelper.UploadOrgInfo("YC2024030610005","测试医院-Loki",DateTime.Now).GetAwaiter().GetResult();UploadOrgInfos
- //NationalPlatformHelper.UploadOrgInfos().GetAwaiter().GetResult();
- //NationalPlatformHelper.GetOrgInfo("640000").GetAwaiter().GetResult();
- //NationalPlatformHelper.GetUserInfo("640000", "NX6401052020000007").GetAwaiter().GetResult();
- //NationalPlatformHelper.UploadConsultation(new List<Participateinfo> {new Participateinfo("NX6401052020000007","23192"),new Participateinfo("NX6401052020000009","22896")},
- // "NX6401052020000009", "23192", "2024030601","阵痛", DateTime.Now.Millisecond.ToString(),DateTime.Now.AddHours(1), DateTime.Now.AddHours(3)).GetAwaiter().GetResult();
- //NationalPlatformHelper.GetConsultation("NX6401052020000007", "22192").GetAwaiter().GetResult();
- //NationalPlatformHelper.UploadConsultationSchedule("NX6401052020000007", "22192", Guid.NewGuid().ToString(), DateTime.Now.AddDays(1).AddHours(8), DateTime.Now.AddDays(1).AddHours(10)).GetAwaiter().GetResult();
- #endif
- }
- catch (Exception ex)
- {
- Close();
- throw ex;
- }
- }
- private void SetStarted()
- {
- _serviceBus.SetStartedServer();
- System.Threading.ThreadPool.GetMinThreads(out var minworkThreads, out var minIOThreads);
- Logger.WriteLineInfo($"ThreadPool: minworkThreads:{minworkThreads} minIOThreads:{minIOThreads}");
- }
- private void OnNotifyLicenseExpirationClosedEvent(object sender,bool e)
- {
- Logger.WriteLineInfo("vCloud Server Closing!");
- Close();
- }
- /// <summary>
- /// Close the server.
- /// </summary>
- public void Close()
- {
- if (!_serviceBus.LocalHostMode && _serviceBus.Master != null)
- {
- _serviceBus.Master.UnattachSlave(_serviceBus);
- }
- foreach (var localService in _localServices)
- {
- localService?.Dispose();
- }
- _serviceBus?.Close();
- }
- private void InitializeAutoClearCache()
- {
- Task.Run(async () =>
- {
- await Task.Delay(TimeSpan.FromMinutes(3));
- AutoClearCacheManager.Instance.Enable = true;
- });
- }
- /// <summary>
- /// Initialize the LogEngine,according to the config, it could be a Trace LogEnhine or MSMQ LogEngine.
- /// </summary>
- private void InitializeLoggerEngine()
- {
- UnifyLogEngine engine = new UnifyLogEngine();
- engine.EngineSendMessageDelegate = _serviceBus.SendMessage;
- Logger.RegisterEngine(engine);
- Logger.WriteLineInfo($"{nameof(UnifyLogEngine)} was registered.");
- }
- /// <summary>
- /// Initialize the LogEngine,according to the config. The server may create the ServiceBus or just create the
- /// ClientLeafCreator for creating the NetworkServiceBusAdapter.
- /// </summary>
- private void InitializeServiceBus()
- {
- var url = Config.GetValue("ServiceBus", "Url", "localhost");
- _serviceBus = new vCloudServiceBus(url);
- Logger.WriteLineInfo($"Create ServiceBus at {url}.");
- var masterUrl = Config.GetValue("ServiceBus", "MasterUrl", string.Empty);
- if (!_serviceBus.LocalHostMode)
- {
- var task = Task.Run(() => {
- try
- {
- if (!string.IsNullOrEmpty(masterUrl))
- {
- _serviceBus.Master = new MasterServiceBusAdapter(masterUrl);
- }
- _serviceBus.Start();
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Attach to master server error {ex}");
- Console.WriteLine($"Attach to master server error {ex}");
- }
- });
- task.Wait();
- }
- }
- /// <summary>
- /// Initialize the services.
- /// </summary>
- private void InitializeServices()
- {
- InitializeLoggerEngine();
- foreach (var serviceName in ServiceCreator.ServiceContexts.Keys)
- {
- var serviceEnabled = Config.GetValue("Service", serviceName, false);
- if (serviceEnabled)
- {
- if (_serviceBus != null)
- {
- try
- {
- if (_serviceBus.LocalHostMode && serviceName == ServerRegistryService.ServiceId.Name)
- {
- continue;
- }
- //not starat managerment service for slaver
- if (!_serviceBus.LocalHostMode && !_serviceBus.IsMaster &&
- serviceName == ManagementService.ServiceId.Name)
- {
- continue;
- }
- var service = ServiceCreator.CreateService(serviceName, _serviceBus);
- _localServices.Add(service);
- Logger.WriteLineInfo($"Service:{service.Id} was registered.");
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Service:{serviceName} error {ex}");
- Console.WriteLine($"Service:{serviceName} error {ex}");
- }
- }
- }
- }
- }
- private void InitializeMessagePoolConfig()
- {
- try
- {
- var serverMessagePoolConfig = new ServerMessagePoolConfig();
- var isCachedvalue = Config.GetValue("MessagePool", "IsCached", false);
- serverMessagePoolConfig.SetEnabled(isCachedvalue);
- var maximumMessageOfEachTypeValue = Config.GetValue("MessagePool", "MaximumMessageOfEachType", 10);
- serverMessagePoolConfig.SetMaximumMessageOfEachType(maximumMessageOfEachTypeValue);
- var maximumMessagesOfSpecialTypeList = Config.GetValue("MessagePool", "MaximumMessagesOfSpecialType", new List<string>());
- if (maximumMessagesOfSpecialTypeList != null)
- {
- foreach (var value in maximumMessagesOfSpecialTypeList)
- {
- var array = value.Split(':');
- if (array.Length == 2)
- {
- var messageName = array[0];
- var maximum = Convert.ToInt32(array[1]);
- serverMessagePoolConfig.AddCustomMessageCount(messageName, maximum);
- }
- }
- }
- MessagePool.Initialize(serverMessagePoolConfig);
- }
- catch (Exception e)
- {
- Logger.WriteLineError($"Initialize message pool failed :{e}");
- }
- }
- /// <summary>
- /// 启动 工具
- /// </summary>
- private void StartDBAutoBackup()
- {
- var _dependencies = Config.GetValue("DependenciesTools", "ToolNames", string.Empty);
- if (!string.IsNullOrEmpty(_dependencies))
- {
- var dependenciesApps = _dependencies.Split(',');
- foreach (var item in dependenciesApps)
- {
- if (!string.IsNullOrEmpty(item))
- {
- var appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, item);
- if (File.Exists(appPath))
- {
- StartProcess(appPath);
- var arry = item.Split('.');
- if (arry.Length > 0)
- {
- _dependencieNames.Add(arry[0]);
- }
- else
- {
- _dependencieNames.Add(item);
- }
- }
- }
- }
- }
- }
- /// <summary>
- /// 开始执行工具程序
- /// </summary>
- /// <param name="processName">工具程序名称</param>
- private void StartProcess(string namePath)
- {
- Process process = new Process();
- process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
- process.StartInfo.FileName = namePath;
- process.Start();
- }
- }
- }
|