コード例 #1
0
ファイル: Launcher.cs プロジェクト: zfzfzf/CommunityServer
        private static void StartPing()
        {
            Thread.Sleep(PingInterval);

            webSocket = new WebSocket(string.Format("ws://127.0.0.1:{0}/socket.io/?EIO=3&transport=websocket", startInfo.EnvironmentVariables["port"]));
            webSocket.SetCookie(new WebSocketSharp.Net.Cookie("authorization", SignalrServiceClient.CreateAuthToken()));
            webSocket.OnMessage += (sender, e) =>
            {
                if (e.Data.Contains("error"))
                {
                    Logger.Error("Auth error");
                    cancellationTokenSource.Cancel();
                }
            };
            webSocket.Connect();

            Task.Run(() =>
            {
                while (webSocket.Ping())
                {
                    Logger.Debug("Ping");
                    Thread.Sleep(PingInterval);
                }

                Logger.Debug("Reconnect");
                if (retries < maxretries)
                {
                    StartNode();
                    retries++;
                }
            }, cancellationTokenSource.Token);
        }
コード例 #2
0
ファイル: BaseWorker.cs プロジェクト: xjsaber/CommunityServer
        protected BaseWorker(MailBoxManager mailBoxManager, MailBox mailBox, TasksConfig tasksConfig,
                             CancellationToken cancelToken, ILogger log = null)
        {
            this.mailBoxManager    = mailBoxManager;
            _mailBox               = mailBox;
            this.log               = log ?? new NullLogger();
            _lastTimeItemChecked   = DateTime.UtcNow;
            _maxMessagesPerSession = tasksConfig.MaxMessagesPerSession;
            this.tasksConfig       = tasksConfig;
            _signalrServiceClient  = new SignalrServiceClient();

            _needSignal = false;

            this.cancelToken = cancelToken;

            if (tasksConfig.ShowActiveUpLogs)
            {
                Logger.Log4NetLogger = LogManager.GetLogger(string.Format("Task_{0}->ActiveUp", Task.CurrentId));
                Logger.Disabled      = false;
            }
            else
            {
                Logger.Log4NetLogger = null;
                Logger.Disabled      = true;
            }
        }
コード例 #3
0
        public SocketServiceLauncher(IOptionsMonitor <ILog> options, IConfiguration configuration, CoreBaseSettings coreBaseSettings, SignalrServiceClient signalrServiceClient, IHostEnvironment hostEnvironment, IConfigureNamedOptions <SignalrServiceClient> configureOptions)
        {
            Logger = options.CurrentValue;
            CancellationTokenSource = new CancellationTokenSource();
            Configuration           = configuration;
            CoreBaseSettings        = coreBaseSettings;
            SignalrServiceClient    = signalrServiceClient;
            HostEnvironment         = hostEnvironment;

            configureOptions.Configure(SignalrServiceClient);
        }
コード例 #4
0
        private const string EMPTY_HTML_BODY = "<div dir=\"ltr\"><br></div>"; // GMail style

        public MailSendQueue(MailBoxManager manager, ILogger log)
        {
            this.manager = manager;
            this.log     = log;
            if (_signalrServiceClient != null)
            {
                return;
            }
            var enableSignalr = string.IsNullOrEmpty(ConfigurationManager.AppSettings["web.hub"]) ? "false" : "true";

            _signalrServiceClient = new SignalrServiceClient(enableSignalr);
        }
コード例 #5
0
        public DraftManager(MailBoxManager manager, ILogger log, DeliveryFailureMessageTranslates daemonLabels = null)
        {
            DaemonLabels = daemonLabels ?? DeliveryFailureMessageTranslates.Defauilt;
            this.manager = manager;
            this.log     = log;
            if (_signalrServiceClient != null)
            {
                return;
            }
            var enableSignalr = string.IsNullOrEmpty(ConfigurationManager.AppSettings["web.hub"]) ? "false" : "true";

            _signalrServiceClient = new SignalrServiceClient(enableSignalr);
        }
コード例 #6
0
 public FeedAggregatorService(
     IConfiguration configuration,
     IServiceProvider serviceProvider,
     IContainer container,
     IOptionsMonitor <ILog> optionsMonitor,
     SignalrServiceClient signalrServiceClient,
     IConfigureNamedOptions <SignalrServiceClient> configureOptions)
 {
     Configuration        = configuration;
     ServiceProvider      = serviceProvider;
     Container            = container;
     Log                  = optionsMonitor.Get("ASC.Feed.Agregator");
     SignalrServiceClient = signalrServiceClient;
     configureOptions.Configure("counters", SignalrServiceClient);
 }
コード例 #7
0
        public SignalrWorker(bool startImmediately = true)
        {
            _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "SignalrWorker");
            _workerTerminateSignal = false;
            _signalrServiceClient  = new SignalrServiceClient("mail");
            _processingQueue       = new Queue <MailBox>();
            _waitHandle            = new EventWaitHandle(false, EventResetMode.AutoReset);
            _timeSpan = TimeSpan.FromSeconds(10);

            _worker = new Thread(ProcessQueue);

            if (startImmediately)
            {
                _worker.Start();
            }
        }
コード例 #8
0
        public DraftManager(MailBoxManager manager, ILogger log, DeliveryFailureMessageTranslates daemonLabels = null,
                            bool isAutoreply = false)
        {
            DaemonLabels          = daemonLabels ?? DeliveryFailureMessageTranslates.Defauilt;
            this.manager          = manager;
            this.log              = log;
            _isAutoreply          = isAutoreply;
            _sslCertificatePermit = ConfigurationManager.AppSettings["mail.certificate-permit"] != null &&
                                    Convert.ToBoolean(ConfigurationManager.AppSettings["mail.certificate-permit"]);

            if (_signalrServiceClient != null)
            {
                return;
            }
            _signalrServiceClient = new SignalrServiceClient("mail");
        }
コード例 #9
0
        public ComposeEngineBase(int tenant, string user, DeliveryFailureMessageTranslates daemonLabels = null, ILog log = null)
        {
            Tenant = tenant;
            User   = user;

            Log = log ?? LogManager.GetLogger("ASC.Mail.ComposeEngineBase");

            DaemonLabels = daemonLabels ?? DeliveryFailureMessageTranslates.Defauilt;

            _sslCertificatePermit = Defines.SslCertificatesErrorPermit;

            if (_signalrServiceClient != null)
            {
                return;
            }
            _signalrServiceClient = new SignalrServiceClient("mail");
        }
コード例 #10
0
 public VoIPController(CrmSecurity crmSecurity,
                       DaoFactory daoFactory,
                       Global global,
                       ContactPhotoManager contactPhotoManager,
                       StorageFactory storageFactory,
                       CommonLinkUtility commonLinkUtility,
                       SecurityContext securityContext,
                       TenantUtil tenantUtil,
                       VoipEngine voipEngine,
                       ApiContext apiContext,
                       SignalrServiceClient signalrServiceClient,
                       IMapper mapper)
     : base(daoFactory, crmSecurity, mapper)
 {
     _global = global;
     _contactPhotoManager  = contactPhotoManager;
     _storageFactory       = storageFactory;
     _commonLinkUtility    = commonLinkUtility;
     _securityContext      = securityContext;
     _tenantUtil           = tenantUtil;
     _voipEngine           = voipEngine;
     _apiContext           = apiContext;
     _signalrServiceClient = signalrServiceClient;
 }
コード例 #11
0
        public AggregatorService(Options options)
        {
            ServiceName  = AscMailCollectionServiceName;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent         = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue         = false;
            CanShutdown = true;
            CanStop     = true;
            try
            {
                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MainThread");

                Environment.SetEnvironmentVariable("MONO_TLS_SESSION_CACHE_TIMEOUT", "0");

                _tasksConfig = TasksConfig.FromConfig;

                if (options.OnlyUsers != null)
                {
                    _tasksConfig.WorkOnUsersOnly.AddRange(options.OnlyUsers.ToList());
                }

                if (options.NoMessagesLimit)
                {
                    _tasksConfig.MaxMessagesPerSession = -1;
                }

                _taskSecondsLifetime =
                    TimeSpan.FromSeconds(ConfigurationManager.AppSettings["mail.task-process-lifetime-seconds"] != null
                        ? Convert.ToInt32(ConfigurationManager.AppSettings["mail.task-process-lifetime-seconds"])
                        : 300);

                _queueManager = new QueueManager(_tasksConfig, _log);

                _resetEvent = new ManualResetEvent(false);

                _cancelTokenSource = new CancellationTokenSource();

                _taskFactory = new TaskFactory();

                _tsTaskStateCheckInterval = ConfigurationManager.AppSettings["mail.task-check-state-seconds"] != null
                        ? TimeSpan.FromSeconds(
                    Convert.ToInt32(ConfigurationManager.AppSettings["mail.task-check-state-seconds"]))
                        : TimeSpan.FromSeconds(30);

                if (_tasksConfig.EnableSignalr)
                {
                    _signalrServiceClient = new SignalrServiceClient();
                }

                _workTimer = new Timer(workTimer_Elapsed, _cancelTokenSource.Token, Timeout.Infinite, Timeout.Infinite);

                _gcCleanerTimer = new Timer(gcCleanerTimer_Elapsed, _cancelTokenSource.Token, _gcCleanTimerInterval, _gcCleanTimerInterval);

                _log.Info("Service is ready.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under construct: {0}", ex.ToString());
            }
        }
コード例 #12
0
        private void StartPing()
        {
            Thread.Sleep(PingInterval);

            var error = false;

            WebSocket = new WebSocket(string.Format("ws://127.0.0.1:{0}/socket.io/?EIO=3&transport=websocket", StartInfo.EnvironmentVariables["port"]));
            WebSocket.SetCookie(new WebSocketSharp.Net.Cookie("authorization", SignalrServiceClient.CreateAuthToken()));
            WebSocket.EmitOnPing = true;

            WebSocket.Log.Level = WebSocketSharp.LogLevel.Trace;

            WebSocket.Log.Output = (logData, filePath) =>
            {
                if (logData.Message.Contains("SocketException"))
                {
                    error = true;
                }

                Logger.Debug(logData.Message);
            };

            WebSocket.OnOpen += (sender, e) =>
            {
                Logger.Info("Open");
                error = false;

                Thread.Sleep(PingInterval);

                Task.Run(() =>
                {
                    while (WebSocket.Ping())
                    {
                        Logger.Debug("Ping " + WebSocket.ReadyState);
                        Thread.Sleep(PingInterval);
                    }
                    Logger.Debug("Reconnect" + WebSocket.ReadyState);
                }, CancellationTokenSource.Token);
            };

            WebSocket.OnClose += (sender, e) =>
            {
                Logger.Info("Close");
                if (CancellationTokenSource.IsCancellationRequested)
                {
                    return;
                }

                if (error)
                {
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    WebSocket.Connect();
                }
            };

            WebSocket.OnMessage += (sender, e) =>
            {
                if (e.Data.Contains("error"))
                {
                    Logger.Error("Auth error");
                    CancellationTokenSource.Cancel();
                }
            };

            WebSocket.OnError += (sender, e) =>
            {
                Logger.Error("Error", e.Exception);
            };

            WebSocket.Connect();
        }
コード例 #13
0
 public SignalRHelper(string numberId,
                      SignalrServiceClient signalrServiceClient)
 {
     _signalrServiceClient = signalrServiceClient;
     this.numberId         = numberId.TrimStart('+');
 }
コード例 #14
0
ファイル: JabberService.cs プロジェクト: dolunay/XMPPServer
 public JabberService(XmppServer xmppServer)
 {
     _xmppServer          = xmppServer;
     signalrServiceClient = new SignalrServiceClient("chat");
 }
コード例 #15
0
 public SocketManager()
 {
     _signalrServiceClient = new SignalrServiceClient("files");
 }
コード例 #16
0
 public SignalRHelper(string numberId)
 {
     signalrServiceClient = new SignalrServiceClient("voip");
     this.numberId        = numberId.TrimStart('+');
 }
コード例 #17
0
        public AggregatorService(Options options)
        {
            ServiceName  = ASC_MAIL_COLLECTION_SERVICE_NAME;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent         = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue         = false;
            CanShutdown = true;
            CanStop     = true;
            try
            {
                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MainThread");

                _logStat = LogManager.GetLogger("ASC.MAIL.STAT");

                _tasksConfig = TasksConfig.FromConfig;

                _tasksConfig.DefaultFolders = MailQueueItemSettings.DefaultFolders;

                _tasksConfig.ImapFlags = MailQueueItemSettings.ImapFlags;

                _tasksConfig.PopUnorderedDomains = MailQueueItemSettings.PopUnorderedDomains;

                _tasksConfig.SkipImapFlags = MailQueueItemSettings.SkipImapFlags;

                _tasksConfig.SpecialDomainFolders = MailQueueItemSettings.SpecialDomainFolders;

                if (options.OnlyUsers != null)
                {
                    _tasksConfig.WorkOnUsersOnly.AddRange(options.OnlyUsers.ToList());
                }

                if (options.NoMessagesLimit)
                {
                    _tasksConfig.MaxMessagesPerSession = -1;
                }

                _taskSecondsLifetime =
                    TimeSpan.FromSeconds(ConfigurationManager.AppSettings["mail.task-process-lifetime-seconds"] != null
                        ? Convert.ToInt32(ConfigurationManager.AppSettings["mail.task-process-lifetime-seconds"])
                        : 300);

                _queueManager = new QueueManager(_tasksConfig, _log);

                _resetEvent = new ManualResetEvent(false);

                _cancelTokenSource = new CancellationTokenSource();

                _taskFactory = new TaskFactory();

                _tsTaskStateCheckInterval = ConfigurationManager.AppSettings["mail.task-check-state-seconds"] != null
                        ? TimeSpan.FromSeconds(
                    Convert.ToInt32(ConfigurationManager.AppSettings["mail.task-check-state-seconds"]))
                        : TimeSpan.FromSeconds(30);

                if (_tasksConfig.EnableSignalr)
                {
                    _signalrServiceClient = new SignalrServiceClient();
                }

                _workTimer = new Timer(workTimer_Elapsed, _cancelTokenSource.Token, Timeout.Infinite, Timeout.Infinite);

                _log.Info("Service is ready.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under construct: {0}", ex.ToString());
            }
        }
コード例 #18
0
ファイル: SocketManager.cs プロジェクト: zltwork/AppServer
 public SocketManager(IOptionsSnapshot <SignalrServiceClient> optionsSnapshot, TenantManager tenantManager)
 {
     _signalrServiceClient = optionsSnapshot.Get("files");
     TenantManager         = tenantManager;
 }
コード例 #19
0
        private void AggregateFeeds(object interval)
        {
            if (!Monitor.TryEnter(aggregateLock))
            {
                return;
            }

            try
            {
                var cfg = FeedSettings.GetInstance(Configuration);
                using var scope = ServiceProvider.CreateScope();
                var scopeClass = scope.ServiceProvider.GetService <FeedAggregatorServiceScope>();
                var cache      = scope.ServiceProvider.GetService <ICache>();
                var(baseCommonLinkUtility, tenantManager, feedAggregateDataProvider, userManager, securityContext, authManager) = scopeClass;
                baseCommonLinkUtility.Initialize(cfg.ServerRoot);

                var start = DateTime.UtcNow;
                Log.DebugFormat("Start of collecting feeds...");

                var unreadUsers = new Dictionary <int, Dictionary <Guid, int> >();
                var modules     = scope.ServiceProvider.GetService <IEnumerable <IFeedModule> >();

                foreach (var module in modules)
                {
                    var result   = new List <FeedRow>();
                    var fromTime = feedAggregateDataProvider.GetLastTimeAggregate(module.GetType().Name);
                    if (fromTime == default)
                    {
                        fromTime = DateTime.UtcNow.Subtract((TimeSpan)interval);
                    }
                    var toTime = DateTime.UtcNow;

                    var tenants = Attempt(10, () => module.GetTenantsWithFeeds(fromTime)).ToList();
                    Log.DebugFormat("Find {1} tenants for module {0}.", module.GetType().Name, tenants.Count());

                    foreach (var tenant in tenants)
                    {
                        // Warning! There is hack here!
                        // clearing the cache to get the correct acl
                        cache.Remove("acl" + tenant);
                        cache.Remove("/webitemsecurity/" + tenant);
                        //cache.Remove(string.Format("sub/{0}/{1}/{2}", tenant, "6045b68c-2c2e-42db-9e53-c272e814c4ad", NotifyConstants.Event_NewCommentForMessage.ID));

                        try
                        {
                            if (tenantManager.GetTenant(tenant) == null)
                            {
                                continue;
                            }

                            tenantManager.SetCurrentTenant(tenant);
                            var users = userManager.GetUsers();

                            var feeds = Attempt(10, () => module.GetFeeds(new FeedFilter(fromTime, toTime)
                            {
                                Tenant = tenant
                            }).Where(r => r.Item1 != null).ToList());
                            Log.DebugFormat("{0} feeds in {1} tenant.", feeds.Count, tenant);

                            var tenant1  = tenant;
                            var module1  = module;
                            var feedsRow = feeds
                                           .Select(tuple => new Tuple <FeedRow, object>(new FeedRow(tuple.Item1)
                            {
                                Tenant    = tenant1,
                                ProductId = module1.Product
                            }, tuple.Item2))
                                           .ToList();

                            foreach (var u in users)
                            {
                                if (isStopped)
                                {
                                    return;
                                }
                                if (!TryAuthenticate(securityContext, authManager, tenant1, u.ID))
                                {
                                    continue;
                                }

                                module.VisibleFor(feedsRow, u.ID);
                            }

                            result.AddRange(feedsRow.Select(r => r.Item1));
                        }
                        catch (Exception ex)
                        {
                            Log.ErrorFormat("Tenant: {0}, {1}", tenant, ex);
                        }
                    }

                    feedAggregateDataProvider.SaveFeeds(result, module.GetType().Name, toTime);

                    foreach (var res in result)
                    {
                        foreach (var userGuid in res.Users.Where(userGuid => !userGuid.Equals(res.ModifiedById)))
                        {
                            if (!unreadUsers.TryGetValue(res.Tenant, out var dictionary))
                            {
                                dictionary = new Dictionary <Guid, int>();
                            }
                            if (dictionary.ContainsKey(userGuid))
                            {
                                ++dictionary[userGuid];
                            }
                            else
                            {
                                dictionary.Add(userGuid, 1);
                            }

                            unreadUsers[res.Tenant] = dictionary;
                        }
                    }
                }

                SignalrServiceClient.SendUnreadUsers(unreadUsers);

                Log.DebugFormat("Time of collecting news: {0}", DateTime.UtcNow - start);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            finally
            {
                Monitor.Exit(aggregateLock);
            }
        }