Beispiel #1
0
        //---------------------------------------
        // Clustering Implementation Note:
        //
        // Note that the one of the application store instances in the cluster needs
        // to be configured as the primary application store.  This is done by setting
        // the following configuration setting:
        //
        //      LillTek.Datacenter.AppStore = Primary
        //
        // The primary application store holds the definitive set of application
        // packages against which the non-primary store instances will synchronize
        // themselves.  Note that the primary application store is not necessarily
        // the cluster master.  These two concepts are independent.  The cluster master
        // will be elected normally from the pool of application store instances and
        // will be responsible for replicating cluster state global and instance state.
        //
        // At this point there is no global cluster state.  Each instance does expose
        // the following properties to the cluster:
        //
        //      Mode        This is set to "Primary" or "Cache" and indicates which
        //                  application store instances are configured to be the
        //                  primary instance (For this implementation, only one
        //                  instance should be configured as the primary).

        /// <summary>
        /// Constructs a application store service handler instance.
        /// </summary>
        public AppStoreHandler()
        {
            this.router   = null;
            this.syncLock = null;
            this.bkTimer  = null;
            this.cluster  = null;
        }
Beispiel #2
0
        /// <summary>
        /// Opens the authenticator using the settings passed.
        /// </summary>
        /// <param name="router">The router to be used for messaging.</param>
        /// <param name="settings">The <see cref="AuthenticatorSettings" /> instance to use.</param>
        public void Open(MsgRouter router, AuthenticatorSettings settings)
        {
            using (TimedLock.Lock(this))
            {
                if (isOpen)
                {
                    throw new AuthenticationException("Authenticator is already open.");
                }

                // Load the configuration settings

                cacheFlushInterval = settings.CacheFlushInterval;
                successTTL         = settings.SuccessTTL;
                failTTL            = settings.FailTTL;

                // Crank this sucker up.

                if (settings.MaxCacheSize > 0)
                {
                    cache          = new TimedLRUCache <string, AuthenticationResult>();
                    cache.MaxItems = settings.MaxCacheSize;
                }
                else
                {
                    cache = null;
                }

                this.router         = router;
                this.bkTimer        = new GatedTimer(new TimerCallback(OnBkTimer), null, settings.BkTaskInterval);
                this.isOpen         = true;
                this.cacheFlushTime = SysTime.Now + cacheFlushInterval;

                router.Dispatcher.AddTarget(this);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Immediately terminates the processing of all client messages.
        /// </summary>
        public void Stop()
        {
            if (router == null)
            {
                return;
            }

            using (TimedLock.Lock(syncLock))
            {
                if (packageFolder != null)
                {
                    packageFolder.Dispose();
                    packageFolder = null;
                }

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }

                if (cluster != null)
                {
                    cluster.Stop();
                    cluster = null;
                }

                if (router != null)
                {
                    router.Dispatcher.RemoveTarget(this);
                    router = null;
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Immediately terminates the processing of all client messages.
        /// </summary>
        public void Stop()
        {
            if (!isRunning)
            {
                return;
            }

            using (TimedLock.Lock(syncLock))
            {
                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }

                if (httpServer != null)
                {
                    httpServer.Stop();
                    httpServer = null;
                }

                router    = null;
                isRunning = false;
            }
        }
Beispiel #5
0
        private void FormServiceHost_Closing(object sender, System.ComponentModel.CancelEventArgs args)
        {
            switch (service.State)
            {
            case ServiceState.Starting:
            case ServiceState.Running:
            case ServiceState.Shutdown:

                try
                {
                    service.Stop();
                }
                catch (Exception e)
                {
                    SysLog.LogException(e);
                }
                break;
            }

            SysLog.LogProvider = null;

            if (timer != null)
            {
                timer.Dispose();
                timer = null;
            }

            Environment.Exit(0);
        }
Beispiel #6
0
        /// <summary>
        /// Opens a RADIUS client using the <see cref="RadiusClientSettings" /> passed.
        /// </summary>
        /// <param name="settings">The client settings.</param>
        /// <remarks>
        /// <note>
        /// Note that all successful calls to <b>Open()</b> must eventually be matched
        /// with a call to <see cref="Close" /> so that system resources will be
        /// released promptly.
        /// </note>
        /// </remarks>
        public void Open(RadiusClientSettings settings)
        {
            using (TimedLock.Lock(this))
            {
                if (IsOpen)
                {
                    throw new RadiusException("RADIUS client is already open.");
                }

                if (settings.PortCount > 1 && settings.NetworkBinding.Port != 0)
                {
                    throw new RadiusException("RADIUS client [NetworkBinding.Port] must be zero if [PortCount] is greater than one.");
                }

                ports = new RadiusClientPort[settings.PortCount];
                for (int i = 0; i < settings.PortCount; i++)
                {
                    ports[i] = new RadiusClientPort();
                    ports[i].Open(settings);
                }

                bkTimer  = new GatedTimer(new TimerCallback(OnBkTimer), null, settings.BkTaskInterval, settings.BkTaskInterval);
                nextPort = 0;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Makes sure that the class is prepared to transmit a query by
        /// ensuring that a socket exists and the background timer is
        /// running.  This method also updates lastQueryTime.
        /// </summary>
        /// <param name="request">The DNS request.</param>
        /// <param name="timeout">The maximum time to wait.</param>
        /// <param name="callback">The delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application state to be passed to the callback (or <c>null</c>).</param>
        /// <returns>An initialized async result.</returns>
        private static DnsAsyncResult PrepareQuery(DnsRequest request, TimeSpan timeout,
                                                   AsyncCallback callback, object state)
        {
            DnsAsyncResult arDns;

            lock (syncLock)
            {
                lastQueryTime = SysTime.Now;

                if (sockets == null)
                {
                    Bind();
                }

                if (bkTimer == null)
                {
                    bkTimer = new GatedTimer(onBkTimer, null, pollTime, pollTime);
                }

                // Randomly select the socket to use

                arDns       = new DnsAsyncResult(sockets[Helper.RandIndex(sockets.Length)], request, timeout, callback, state);
                request.QID = arDns.DnsSocket.NextQID++;

                // Add the async result to the requests table

                requests.Add(GenRequestKey(arDns.DnsSocket.SocketID, request.QID), arDns);
            }

            return(arDns);
        }
Beispiel #8
0
        /// <summary>
        /// Opens the <see cref="AppStoreClient" /> instance so that it is ready to
        /// process requests.
        /// </summary>
        /// <param name="router">The <see cref="MsgRouter" /> to be associated with the client.</param>
        /// <param name="settings">The <see cref="AppStoreClientSettings" /> to be used.</param>
        /// <exception cref="InvalidOperationException">Thrown if the instance is already open.</exception>
        public void Open(MsgRouter router, AppStoreClientSettings settings)
        {
            if (this.syncLock != null)
            {
                throw new InvalidOperationException("AppStoreClient is already open.");
            }

            // Make sure that the LillTek.Datacenter message types have been
            // registered with the LillTek.Messaging subsystem.

            LillTek.Datacenter.Global.RegisterMsgTypes();

            // Initialize

            using (TimedLock.Lock(router.SyncRoot))
            {
                this.syncLock      = router.SyncRoot;
                this.router        = router;
                this.settings      = settings;
                this.bkTimer       = new GatedTimer(new System.Threading.TimerCallback(OnBkTimer), null, settings.BkTaskInterval);
                this.nextPurgeTime = SysTime.Now;

                if (settings.LocalCache)
                {
                    this.packageFolder = new AppPackageFolder(syncLock, settings.PackageFolder);
                }
                else
                {
                    this.packageFolder = null;
                }

                router.Dispatcher.AddTarget(this);
            }
        }
Beispiel #9
0
        private DateTime nextPurgeTime;                     // Next scheduled package folder purge time (SYS)

        /// <summary>
        /// Constructor.
        /// </summary>
        public AppStoreClient()
        {
            this.syncLock      = null;
            this.router        = null;
            this.packageFolder = null;
            this.bkTimer       = null;
        }
Beispiel #10
0
        private static bool sweeping = false;           // True if sweeping for timeouts

        /// <summary>
        /// Static constructor
        /// </summary>
        static HttpStack()
        {
            clientCons    = new Hashtable();
            sweepInterval = TimeSpan.FromSeconds(5.0);
            sweepTimer    = null;
            blockSize     = 4096;
        }
Beispiel #11
0
        /// <summary>
        /// Releases all resources associated with the instance.
        /// </summary>
        public void Close()
        {
            using (TimedLock.Lock(syncLock))
            {
                if (syncLock == null)
                {
                    return;
                }

                router.Dispatcher.RemoveTarget(this);

                if (packageFolder != null)
                {
                    packageFolder.Dispose();
                    packageFolder = null;
                }

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }

                router   = null;
                syncLock = null;
            }
        }
Beispiel #12
0
        public void GatedTimer_Basic()
        {
            count   = 0;
            state   = null;
            wait    = 1000;
            dispose = false;
            change  = 0;
            timer   = new GatedTimer(new TimerCallback(OnTimer), 10, TimeSpan.Zero, TimeSpan.FromMilliseconds(100));

            Thread.Sleep(1000);
            timer.Dispose();
            Assert.AreEqual(1, count);
            Assert.AreEqual(10, (int)state);

            count   = 0;
            state   = null;
            wait    = 0;
            dispose = false;
            change  = 0;
            timer   = new GatedTimer(new TimerCallback(OnTimer), 10, TimeSpan.Zero, TimeSpan.FromMilliseconds(100));

            Thread.Sleep(1000);
            timer.Dispose();
            Assert.AreEqual(10, count);
            Assert.AreEqual(10, (int)state);
        }
Beispiel #13
0
        /// <summary>
        /// Stops the server if it's currently running.
        /// </summary>
        public void Stop()
        {
            using (TimedLock.Lock(this))
            {
                if (sock != null)
                {
                    sock.Close();
                }

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }

                devices           = null;
                deviceMap         = null;
                accounts          = null;
                LogEvent          = null;
                AuthenticateEvent = null;
                GetNasInfoEvent   = null;
                isRunning         = false;
            }

            Thread.Sleep(1000);     // Give any pending authentication event calls a chance
                                    // to unwind.
        }
Beispiel #14
0
        /// <summary>
        /// Stops the service immediately, terminating any user activity.
        /// </summary>
        public void Stop()
        {
            lock (syncLock)
            {
                if (state == ServiceState.Stopped)
                {
                    return;
                }

                SysLog.LogInformation("NeonSwitch Stop");
                SysLog.Flush();

                base.Close();
                state = ServiceState.Stopped;

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }

                if (router != null)
                {
                    router.Stop();
                    router = null;
                }
            }
        }
Beispiel #15
0
 /// <summary>
 /// Stops the agent if it is running.
 /// </summary>
 public void Stop()
 {
     if (queueTimer != null)
     {
         queueTimer.Dispose();
         queueTimer = null;
     }
 }
Beispiel #16
0
        private static AsyncCallback onGetHostByName;       // Async callbacks

        /// <summary>
        /// Initializes the cache.
        /// </summary>
        static EnhancedDns()
        {
            cache           = new Hashtable();
            enableCache     = true;
            ttl             = TimeSpan.FromMinutes(15);
            purgeTimer      = new GatedTimer(new TimerCallback(OnFlush), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
            onGetHostByName = new AsyncCallback(OnGetHostByName);
        }
Beispiel #17
0
        private GatedTimer bkTimer;             // Background task timer

        /// <summary>
        /// Constructor.
        /// </summary>
        public CoreAppService()
        {
            this.router  = null;
            this.state   = ServiceState.Stopped;
            this.bkTimer = null;

            // Prepare the service to accept remote ServiceControl commands.

            base.Open();
        }
Beispiel #18
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public DynDnsClient()
 {
     this.syncLock = this;
     this.isOpen   = false;
     this.router   = null;
     this.cluster  = null;
     this.enabled  = false;
     this.settings = null;
     this.bkTimer  = null;
     this.hosts    = new Dictionary <DynDnsHostEntry, DynDnsHostEntry>();
 }
Beispiel #19
0
        private AsyncCallback onAuth;                                           // Delegate called for received auth results

        // Implementation Note
        // -------------------
        // The cache above is keyed by the credentials formatted as:
        //
        //          <realm> TAB <account> TAB <password>
        //
        // where the realm and account are converted to uppercase.
        //
        // Note that publicKey will be initialized to null.  The first authentication
        // attempt will send a GetPublicKeyMsg to the authentication service
        // endpoint, requesting the service's public key.  The key returned will
        // be stored and the current and subsequent authentication attempts will
        // use the key to encrypt credentials sent to the authentication service.

        /// <summary>
        /// Constructor.
        /// </summary>
        public Authenticator()
        {
            Global.RegisterMsgTypes();

            this.isOpen    = false;
            this.bkTimer   = null;
            this.router    = null;
            this.publicKey = null;
            this.onGetKey  = new AsyncCallback(OnGetKey);
            this.onAuth    = new AsyncCallback(OnAuth);
        }
Beispiel #20
0
 /// <summary>
 /// Stops the cache if it is running.
 /// </summary>
 public void Stop()
 {
     lock (syncLock)
     {
         if (bkTimer != null)
         {
             bkTimer.Dispose();
             bkTimer = null;
         }
     }
 }
Beispiel #21
0
        /// <summary>
        /// Associates the service handler with a message router by registering
        /// the necessary application message handlers.
        /// </summary>
        /// <param name="router">The message router.</param>
        /// <param name="settings">The configuration settings.</param>
        /// <param name="perfCounters">The application's performance counter set (or <c>null</c>).</param>
        /// <param name="perfPrefix">The string to prefix any performance counter names (or <c>null</c>).</param>
        /// <remarks>
        /// <para>
        /// Applications that expose performance counters will pass a non-<c>null</c> <b>perfCounters</b>
        /// instance.  The service handler should add any counters it implements to this set.
        /// If <paramref name="perfPrefix" /> is not <c>null</c> then any counters added should prefix their
        /// names with this parameter.
        /// </para>
        /// </remarks>
        public void Start(MsgRouter router, GeoTrackerServerSettings settings, PerfCounterSet perfCounters, string perfPrefix)
        {
            if (this.isRunning)
            {
                throw new InvalidOperationException("This node has already been started.");
            }

            if (router == null)
            {
                throw new ArgumentNullException("router");
            }

            // Initialize the performance counters

            this.startTime = DateTime.UtcNow;
            this.perf      = new Perf(perfCounters, perfPrefix);

            // General initialization

            this.settings      = settings;
            this.bkTimer       = new GatedTimer(new TimerCallback(OnBkTimer), null, settings.BkInterval);
            this.ipGeocoder    = new IPGeocoder(this);
            this.clusterClient = Helper.CreateInstance <ITopologyProvider>(settings.ClusterTopology);
            this.clusterServer = Helper.CreateInstance <ITopologyProvider>(settings.ClusterTopology);
            this.fixCache      = new GeoFixCache(settings);
            this.archiver      = Helper.CreateInstance <IGeoFixArchiver>(settings.GeoFixArchiver);

            EntityState.MaxEntityFixes = settings.MaxEntityGeoFixes;

            try
            {
                // Initialize the router

                this.router = router;
                this.router.Dispatcher.AddTarget(this, "GeoTrackerServerEP", new SimpleEPMunger(settings.ServerEP), null);

                // Initialize the cluster

                this.clusterClient.OpenClient(router, settings.ClusterEP, settings.ClusterArgs);
                this.clusterServer.OpenServer(router, "GeoTrackerClusterEP", settings.ClusterEP, this, settings.ClusterArgs);

                // Start the archiver.

                archiver.Start(this, settings.GeoFixArchiverArgs);

                this.isRunning = true;
            }
            catch
            {
                Stop();
                throw;
            }
        }
Beispiel #22
0
        // Note: The requests hash table is used to track the outstanding DNS requests.
        //       The table is keyed by a 32-bit integer formed by putting the index of
        //       the socket used in the HIWORD and the DNS QID in the LOWORD.
        //
        //       I'm also using locks pretty heavily in this code but I'm not holding
        //       them for very long so I think that performance will still be pretty good.

        static DnsResolver()
        {
            sockets       = null;
            pollTime      = TimeSpan.FromSeconds(1.0);
            maxIdleTime   = TimeSpan.FromMinutes(1.0);
            onBkTimer     = new TimerCallback(OnBkTimer);
            onReceive     = new AsyncCallback(OnReceive);
            onDnsQuery    = new AsyncCallback(OnDnsQuery);
            bkTimer       = null;
            requests      = new Dictionary <int, DnsAsyncResult>();
            lastQueryTime = DateTime.MinValue;
        }
Beispiel #23
0
        public void Dispose()
        {
            count    = 0;
            maxCount = int.MaxValue;
            state    = null;
            wait     = 0;
            dispose  = true;
            change   = 0;
            timer    = new GatedTimer(new TimerCallback(OnTimer), 10, TimeSpan.Zero, TimeSpan.FromMilliseconds(100));

            Thread.Sleep(1000);
            Assert.Equal(1, count);
            Assert.Equal(10, (int)state);
        }
Beispiel #24
0
        /// <summary>
        /// Adds a connection to the internal collection used to
        /// detect timeout.
        /// </summary>
        /// <param name="con">The connection.</param>
        internal static void AddConnection(HttpConnection con)
        {
            lock (syncLock)
            {
                clientCons.Add(con, con);

                // Crank up the sweep timer if it's not already running.

                if (sweepTimer == null)
                {
                    sweepTimer = new GatedTimer(new TimerCallback(OnSweepTimer), null, sweepInterval, sweepInterval);
                }
            }
        }
Beispiel #25
0
        //---------------------------------------------------------------------
        // Form event handlers

        private void MainForm_Load(object sender, EventArgs args)
        {
            TabPage tab;
            Form    form;

            // QueryServerForm

            tabBox.TabPages.Add(tab = new TabPage());

            form     = new QueryServerForm();
            tab.Text = form.Text;
            tab.Controls.Add(form);
            testForms.Add((ITestForm)form);

            // QueryClientForm

            tabBox.TabPages.Add(tab = new TabPage());

            form     = new QueryClientForm();
            tab.Text = form.Text;
            tab.Controls.Add(form);
            testForms.Add((ITestForm)form);

            // MessageQueueForm

            tabBox.TabPages.Add(tab = new TabPage());

            form     = new MessageQueueForm();
            tab.Text = form.Text;
            tab.Controls.Add(form);
            testForms.Add((ITestForm)form);

            // ReceiveMsgForm

            tabBox.TabPages.Add(tab = new TabPage());

            form     = new MsgReceiveForm();
            tab.Text = form.Text;
            tab.Controls.Add(form);
            testForms.Add((ITestForm)form);

            // Initialize

            SetUIState();
            startButton_Click(null, null);

            timer = new GatedTimer(new TimerCallback(OnTimer), null, TimeSpan.FromSeconds(1));
        }
Beispiel #26
0
        /// <summary>
        /// Immediately terminates the processing of all client messages.
        /// </summary>
        public void Stop()
        {
            if (!isRunning)
            {
                return;
            }

            lock (syncLock)
            {
                router.Dispatcher.RemoveTarget(this);

                if (clusterClient != null)
                {
                    clusterClient.Close();
                }

                if (clusterServer != null)
                {
                    clusterServer.Close();
                }

                if (fixCache != null)
                {
                    fixCache.Stop();
                }

                if (ipGeocoder != null)
                {
                    ipGeocoder.Stop();
                }

                if (archiver != null)
                {
                    archiver.Stop();
                    archiver = null;
                }

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }

                isRunning = false;
            }
        }
Beispiel #27
0
        /// <summary>
        /// Simulates a UDP broadcast client failure by closing the instance without
        /// transmitting <b>Server.Unregister</b> messages.
        /// </summary>
        internal void CloseFail()
        {
            lock (syncLock)
            {
                if (socket != null)
                {
                    socket.Close();
                    socket = null;
                }

                if (bkTimer != null)
                {
                    bkTimer.Dispose();
                    bkTimer = null;
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Constructs and starts the agent.
        /// </summary>
        /// <param name="smtpServer">The <see cref="NetworkBinding" /> for the relay SMTP server.</param>
        /// <param name="account">The relay server account.</param>
        /// <param name="password">The relay server password.</param>
        /// <param name="queueFolder">Path to the folder where email messages should be queued.</param>
        /// <param name="pollInterval">Interval at which the agent will poll the queue folder for messages waiting to be delivered.</param>
        /// <remarks>
        /// <para>
        /// This method initializes and starts the mail agent, creating the mail queue folder if it doesn't already exist.
        /// </para>
        /// <note>
        /// Pass a network binding with the host or port set to <b>Any</b> to disable email transmission.
        /// </note>
        /// </remarks>
        public MailAgent(NetworkBinding smtpServer, string account, string password, string queueFolder, TimeSpan pollInterval)
        {
            queueFolder = Path.GetFullPath(queueFolder);
            Helper.CreateFolderTree(queueFolder);

            this.smtpServer   = smtpServer;
            this.account      = account;
            this.password     = password;
            this.queueFolder  = queueFolder;
            this.pollInterval = pollInterval;

            smtp                = new SmtpClient(smtpServer.HostOrAddress, smtpServer.Port);
            smtp.Credentials    = new SmtpCredentials(account, password);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

            this.queueTimer = new GatedTimer(new TimerCallback(OnQueueTimer), null, pollInterval);
        }
Beispiel #29
0
        /// <summary>
        /// Releases any important resources associated with the instance.
        /// </summary>
        /// <param name="disposing">Pass <c>true</c> if the instance is being disposed as opposed to being finalized.</param>
        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                lock (cache)
                {
                    if (cacheTimer != null)
                    {
                        cacheTimer.Dispose();
                        cacheTimer = null;
                    }
                }

                GC.SuppressFinalize(this);
            }

            cacheTimer = null;
        }
Beispiel #30
0
        /// <summary>
        /// Removes a connection from the internal collection to
        /// detect timeouts.
        /// </summary>
        /// <param name="con">The connections.</param>
        internal static void RemoveConnection(HttpConnection con)
        {
            lock (syncLock)
            {
                if (sweeping)
                {
                    return;     // This is handled below by the sweep handler
                }
                clientCons.Remove(con);

                // If that was the last connection then stop the sweep timer.

                if (clientCons.Count == 0 && sweepTimer != null)
                {
                    sweepTimer.Dispose();
                    sweepTimer = null;
                }
            }
        }