示例#1
0
        /// <summary>
        /// Stops the service immediately, terminating any user activity.
        /// </summary>
        public void Stop()
        {
            lock (syncLock)
            {
                if (state == ServiceState.Stopped)
                {
                    return;
                }

                SysLog.LogInformation("Dynamic DNS Client Stop");
                SysLog.Flush();

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

            if (router != null)
            {
                client.Close();
                client = null;

                router.Stop();
                router = null;
            }

            Program.PerfCounters.Zero();
        }
示例#2
0
        public void FlightRecorder_PassThru_SysLogProvider()
        {
            // Verify that the ISysLogProvider implementation works.

            Queue <FlightEvent> queue       = new Queue <FlightEvent>();
            ISysLogProvider     orgProvider = SysLog.LogProvider;

            try
            {
                FlightEvent flightEvent;

                using (var recorder = new FlightRecorder(evt => queue.Enqueue(evt)))
                {
                    SysLog.LogProvider = recorder;

                    SysLog.LogError("Test Error");
                    SysLog.LogWarning("Test Warning");
                    SysLog.LogInformation("Test Information");
                    SysLog.Flush();

                    Assert.AreEqual(3, queue.Count);

                    flightEvent = queue.Dequeue();
                    Assert.AreEqual("SysLog:Error", flightEvent.Operation);
                    Assert.IsTrue(flightEvent.Details.Contains("Test Error"));
                    Assert.IsTrue(flightEvent.IsError);

                    flightEvent = queue.Dequeue();
                    Assert.AreEqual("SysLog:Warning", flightEvent.Operation);
                    Assert.IsTrue(flightEvent.Details.Contains("Test Warning"));
                    Assert.IsFalse(flightEvent.IsError);

                    flightEvent = queue.Dequeue();
                    Assert.AreEqual("SysLog:Information", flightEvent.Operation);
                    Assert.IsTrue(flightEvent.Details.Contains("Test Information"));
                    Assert.IsFalse(flightEvent.IsError);

                    // Verify that system events actually serialize exception
                    // and stack trace related information.

                    try
                    {
                        throw new AssertException();
                    }
                    catch (Exception e)
                    {
                        SysLog.LogException(e);
                        SysLog.Flush();

                        flightEvent = queue.Dequeue();
                        Assert.AreEqual("SysLog:Exception", flightEvent.Operation);
                        Assert.IsTrue(flightEvent.Details.Contains("AssertException"));
                    }
                }
            }
            finally
            {
                SysLog.LogProvider = orgProvider;
            }
        }
示例#3
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;
                }
            }
        }
示例#4
0
        /// <summary>
        /// Stops the service immediately, terminating any user activity.
        /// </summary>
        public void Stop()
        {
            lock (syncLock)
            {
                if (state == ServiceState.Stopped)
                {
                    return;
                }

                SysLog.LogInformation("Config Service Stop");
                SysLog.Flush();

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

                if (router != null)
                {
                    handler.Stop();
                    handler = null;

                    router.Stop();
                    router = null;
                }
            }
        }
示例#5
0
        /// <summary>
        /// Stops the service immediately, terminating any user activity.
        /// </summary>
        public void Stop()
        {
            lock (syncLock)
            {
                if (state == ServiceState.Stopped)
                {
                    return;
                }

                SysLog.LogInformation("Authentication Service Stop");
                SysLog.Flush();

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

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

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

                Program.PerfCounters.Zero();
            }
        }
示例#6
0
        /// <summary>
        /// Stops the service immediately, terminating any user activity.
        /// </summary>
        public void Stop()
        {
            lock (syncLock) {
                if (state == ServiceState.Stopped)
                {
                    return;
                }

                SysLog.LogInformation("GeoTracker Service Stop");
                SysLog.Flush();

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

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

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

            Program.PerfCounters.Zero();
        }
示例#7
0
        private void startButton_Click(object sender, System.EventArgs args)
        {
            try
            {
                SysLog.LogInformation("Starting...");

                try
                {
                    service.Start(this, this.args);
                }
                catch (Exception e)
                {
                    SysLog.LogException(e);
                }

                SetStatus(service.State.ToString());
                SysLog.LogInformation("Status: {0}", service.State);
            }
            catch (Exception e)
            {
                SysLog.LogException(e);
            }

            startButton.Enabled    = false;
            shutDownButton.Enabled = true;
            stopButton.Enabled     = true;
        }
示例#8
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock)
            {
                if (router != null)
                {
                    return;     // Already started
                }
                // Global initialization

                NetTrace.Start();
                Program.Config       = new Config("LillTek.Datacenter.RouterService");
                Program.PerfCounters = null;    // $todo(jeff.lill): new PerfCounterSet(true,Const.RouterServicePerf,Const.RouterServiceName);

                // Service initialization

                this.serviceHost = serviceHost;

                try
                {
                    RootRouter rootRouter;
                    HubRouter  hubRouter;

                    switch (Program.Config.Get("Mode", "HUB").ToUpper())
                    {
                    case "ROOT":

                        SysLog.LogInformation("Router Service v{0}: Starting as ROOT", Helper.GetVersionString());
                        router = rootRouter = new RootRouter();
                        rootRouter.Start();
                        break;

                    case "HUB":
                    default:

                        SysLog.LogInformation("Router Service v{0}: Starting as HUB", Helper.GetVersionString());
                        router = hubRouter = new HubRouter();
                        hubRouter.Start();
                        break;
                    }

                    state = ServiceState.Running;
                }
                catch (Exception e)
                {
                    if (router != null)
                    {
                        router.Stop();
                        router = null;
                    }

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#9
0
 private void shutDownButton_Click(object sender, System.EventArgs args)
 {
     try
     {
         SysLog.LogInformation("Shutdown...");
         service.Shutdown();
         SetStatus(service.State.ToString());
         SysLog.LogInformation("Status: {0}", service.State);
     }
     catch (Exception e)
     {
         SysLog.LogException(e);
     }
 }
示例#10
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock)
            {
                if (router != null)
                {
                    return;     // Already started
                }
                // Global initialization

                NetTrace.Start();

                Program.Config = new Config(MsgQueueHandler.ConfigPrefix);
                Program.InstallPerfCounters();

                // Service initialization

                this.serviceHost = serviceHost;
                SysLog.LogInformation("Message Queue v{0} Start", Helper.GetVersionString());

                try
                {
                    router = new LeafRouter();
                    router.Start();

                    handler = new MsgQueueHandler();
                    handler.Start(router, null, Program.PerfCounters, null);

                    state = ServiceState.Running;
                }
                catch (Exception e)
                {
                    if (handler != null)
                    {
                        handler.Stop();
                        handler = null;
                    }

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

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#11
0
        /// <summary>
        /// Called by a service in ServiceState.Shutdown mode when the last
        /// user disconnects from the service.  The service host will then
        /// typically call the service's <see cref="IService.Stop" /> method.
        /// </summary>
        /// <param name="service">The service completing shutdown.</param>
        public void OnShutdown(IService service)
        {
            SysLog.LogInformation("Shutdown complete.  Now stopping...");

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

            SysLog.LogInformation("Status: {0}", service.State);
        }
示例#12
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock)
            {
                if (router != null)
                {
                    return;     // Already started
                }
                // Global initialization

                NetTrace.Start();
                Program.Config = new Config("LillTek.Datacenter.DynDNSClient");
                Program.InstallPerfCounters();

                // Service initialization

                this.serviceHost = serviceHost;
                SysLog.LogInformation("Dynamic DNS Client v{0} Start", Helper.GetVersionString());

                try
                {
                    router = new LeafRouter();
                    router.Start();

                    client = new DynDnsClient();
                    client.Open(router, new DynDnsClientSettings("LillTek.Datacenter.DynDNSClient"));

                    state = ServiceState.Running;
                }
                catch (Exception e)
                {
                    if (client != null)
                    {
                        client.Close();
                        client = null;
                    }

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

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#13
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock)
            {
                if (router != null)
                {
                    return;     // Already started
                }
                // Global initialization

                NetTrace.Start();
                Program.Config       = new Config(ConfigServiceHandler.ConfigPrefix);
                Program.PerfCounters = null;    // $todo(jeff.lill): new PerfCounterSet(true,Const.ConfigServicePerf,Const.ConfigServiceName);

                // Service initialization

                this.serviceHost = serviceHost;
                SysLog.LogInformation("Config Service v{0} Start", Helper.GetVersionString());

                try
                {
                    router = new LeafRouter();
                    router.Start();

                    handler = new ConfigServiceHandler();
                    handler.Start(router, null, null, null);

                    state = ServiceState.Running;
                }
                catch (Exception e)
                {
                    if (handler != null)
                    {
                        handler.Stop();
                        handler = null;
                    }

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

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#14
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock) {
                if (router != null)
                {
                    return;     // Already started
                }
                // Global initialization

                NetTrace.Start();
                Program.Config = new Config("LillTek.GeoTracker.Service");
                Program.InstallPerfCounters();

                // Service initialization

                this.serviceHost = serviceHost;
                SysLog.LogInformation("GeoTracker Service v{0} Start", Helper.GetVersionString());

                try {
                    router = new LeafRouter();
                    router.Start();

                    node = new GeoTrackerNode();
                    node.Start(router, GeoTrackerNode.ConfigPrefix, Program.PerfCounters, null);

                    state = ServiceState.Running;
                }
                catch (Exception e) {
                    if (node != null)
                    {
                        node.Stop();
                        node = null;
                    }

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

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#15
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock)
            {
                if (udpServer != null)
                {
                    return;     // Already started
                }
                // Global initialization

                NetTrace.Start();
                Program.Config = new Config("LillTek.Datacenter.BroadcastServer");
                Program.InstallPerfCounters();

                // Service initialization

                this.serviceHost = serviceHost;
                SysLog.LogInformation("Broadcast Server v{0} Start", Helper.GetVersionString());

                try
                {
                    udpServer = new UdpBroadcastServer("LillTek.Datacenter.BroadcastServer", Program.PerfCounters, null);

                    state = ServiceState.Running;
                }
                catch (Exception e)
                {
                    if (udpServer != null)
                    {
                        udpServer.Close();
                        udpServer = null;
                    }

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#16
0
        /// <summary>
        /// Stops the service immediately, terminating any user activity.
        /// </summary>
        public void Stop()
        {
            lock (syncLock)
            {
                if (state == ServiceState.Stopped)
                {
                    return;
                }

                SysLog.LogInformation("Broadcast Server Stop");
                SysLog.Flush();

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

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

                Program.PerfCounters.Zero();
            }
        }
示例#17
0
        /// <summary>
        /// Starts the service, associating it with an <see cref="IServiceHost" /> instance.
        /// </summary>
        /// <param name="serviceHost">The service user interface.</param>
        /// <param name="args">Command line arguments.</param>
        public void Start(IServiceHost serviceHost, string[] args)
        {
            lock (syncLock)
            {
                if (router != null)
                {
                    return;     // Already started
                }
                // Global initialization

                startTime = DateTime.UtcNow;

                NetTrace.Start();
                CoreApp.InstallPerfCounters();

                // Service initialization

                this.serviceHost = serviceHost;

                try
                {
                    SysLog.LogInformation("NeonSwitch v{0} Start", Helper.GetVersionString());

                    router = new LeafRouter();
                    router.Start();

                    state = ServiceState.Running;

                    bkTimer = new GatedTimer(OnBkTimer, null, CoreApp.BkTaskInterval);
                    SpeechEngine.Start(SpeechEngineSettings.LoadConfig("NeonSwitch.Speech"));
#if DEBUG
                    // $todo(jeff.lill): Delete this.

                    SwitchTest.Test();
#endif
                    // Indicate that the switch core service is open for business.  NeonSwitch
                    // application instance loaders will spin, waiting for this to be set before
                    // calling the application's main function.

                    Switch.SetGlobal(SwitchGlobal.NeonSwitchReady, "true");
                }
                catch (Exception e)
                {
                    SpeechEngine.Stop();

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

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

                    SysLog.LogException(e);
                    throw;
                }
            }
        }
示例#18
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("GeoTracker Service Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#19
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("NeonSwitch Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#20
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("Authentication Service Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#21
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("Heartbeat Service Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#22
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("Config Service Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#23
0
        /// <summary>
        /// Implements the background tasks.
        /// </summary>
        /// <param name="state">Not used.</param>
        private void OnBkTask(object state)
        {
            if (!isRunning)
            {
                return;
            }

            try
            {
                // Update the service run time.

                perf.Runtime.RawValue = (int)(DateTime.UtcNow - startTime).TotalMinutes;

                if (pollTimer.HasFired)
                {
                    // Execute HTTP requests for all of the configured monitor URIs
                    // and then wait for them to return or timeout before setting the health status.
                    // Note that I'm configuring the request so the Host header will be set to
                    // the header in the URI but the request will actually be submitted to the
                    // local host.

                    try
                    {
                        if (services.Count == 0)
                        {
                            isHealthy = true;
                        }
                        else
                        {
                            bool fail = false;

                            for (int i = 0; i < this.services.Count; i++)
                            {
                                var site = services[i];

                                try
                                {
                                    using (var httpConnection = new HttpConnection(HttpOption.None))
                                    {
                                        HttpRequest  request;
                                        HttpResponse response;

                                        request = new HttpRequest("GET", site.Service.Uri, null);
                                        request["X-Health-Check"] = "true";

                                        httpConnection.Connect(new IPEndPoint(IPAddress.Loopback, site.Service.Uri.Port));
                                        response = httpConnection.Query(request, SysTime.Now + TimeSpan.FromSeconds(5));

                                        if (response.Status != HttpStatus.OK)
                                        {
                                            if (site.IsHealthy)
                                            {
                                                if (site.Service.IsCritical)
                                                {
                                                    SysLog.LogError("Critical local service [{0}] transitioned to unhealthy status with code [{1}={2}].", site.Service.Uri, response.Status, (int)response.Status);
                                                }
                                                else
                                                {
                                                    SysLog.LogWarning("Noncritical local service [{0}] transitioned to unhealthy status with code [{1}={2}].", site.Service.Uri, response.Status, (int)response.Status);
                                                }
                                            }

                                            if (site.Service.IsCritical)
                                            {
                                                fail = true;
                                            }

                                            site.IsHealthy  = false;
                                            site.StatusCode = (int)response.Status;
                                        }
                                        else
                                        {
                                            if (!site.IsHealthy)
                                            {
                                                if (site.Service.IsCritical)
                                                {
                                                    SysLog.LogInformation("Critical local service [{0}] transitioned to healthy status.", site.Service.Uri);
                                                }
                                                else
                                                {
                                                    SysLog.LogInformation("Noncritical local service [{0}] transitioned to healthy status.", site.Service.Uri);
                                                }
                                            }

                                            site.IsHealthy  = true;
                                            site.StatusCode = (int)response.Status;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (site.IsHealthy)
                                    {
                                        if (site.Service.IsCritical)
                                        {
                                            SysLog.LogError("Critical local service [{0}] transitioned to unhealthy status with exception [{1}]: {2}.", site.Service.Uri, e.GetType().Name, e.Message);
                                        }
                                        else
                                        {
                                            SysLog.LogWarning("Noncritical local service [{0}] transitioned to unhealthy status with exception [{1}]: {2}.", site.Service.Uri, e.GetType().Name, e.Message);
                                        }
                                    }

                                    if (site.Service.IsCritical)
                                    {
                                        fail = true;
                                    }

                                    site.IsHealthy  = false;
                                    site.StatusCode = 0;
                                }
                            }

                            isHealthy = !fail;
                        }
                    }
                    finally
                    {
                        pollTimer.Reset();
                    }
                }
            }
            catch (Exception e)
            {
                SysLog.LogException(e);
                isHealthy = false;
            }
            finally
            {
                // Update the status performance counter.

                this.perf.Status.RawValue = isHealthy ? 1 : 0;
            }
        }
示例#24
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("Dynamic DNS Client Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#25
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("Broadcast Server Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#26
0
        /// <summary>
        /// Implements the background thread.
        /// </summary>
        private void DownloadThread()
        {
            DateTime    lastWarningTime = DateTime.MinValue;
            PolledTimer pollTimer;
            bool        resetTimer;

            try
            {
                // Initialize the GeoTracker file folder

                try
                {
                    Helper.CreateFileTree(dataPath);

                    if (File.Exists(downloadPath))
                    {
                        SysLog.LogWarning("GeoTracker: Deleting existing temporary [{0}] file on startup.", downloadPath);
                        Helper.DeleteFile(downloadPath);
                    }

                    if (File.Exists(decryptedPath))
                    {
                        SysLog.LogWarning("GeoTracker: Deleting existing temporary [{0}] file on startup.", decryptedPath);
                        Helper.DeleteFile(decryptedPath);
                    }
                }
                catch (Exception e)
                {
                    SysLog.LogException(e);
                }

                // Initalize the poll timer.  We'll schedule an immediate download if the data file does
                // not exist, otherwise we'll delay the polling for a random period of time between
                // 0 and 15 minutes in the hope that we'll end up staggering the polling times across
                // the server cluster (so we won't hammer the source website).

                pollTimer  = new PolledTimer(settings.IPGeocodeSourcePollInterval, false);
                resetTimer = false;

                if (!File.Exists(dataPath))
                {
                    pollTimer.FireNow();
                }
                else
                {
                    pollTimer.ResetRandomTemporary(TimeSpan.Zero, TimeSpan.FromMinutes(15));
                }

                // The polling loop.

                while (true)
                {
                    if (stopPending)
                    {
                        return;
                    }

                    try
                    {
                        if (pollDataNow)
                        {
                            pollTimer.FireNow();
                            pollDataNow = false;
                        }

                        if (pollTimer.HasFired)
                        {
                            DateTime        fileDateUtc = DateTime.UtcNow;
                            bool            isUpdate    = false;
                            double          fileSize    = 0;
                            ElapsedTimer    downloadTimer;
                            HttpWebRequest  request;
                            HttpWebResponse response;
                            HttpStatusCode  statusCode;

                            resetTimer = true;

                            // If a database file already exists then extract its last modify
                            // date and use this in an If-Modified-Since request to the source
                            // website to see if there's an updated file.

                            if (File.Exists(dataPath))
                            {
                                request         = (HttpWebRequest)WebRequest.Create(settings.IPGeocodeSourceUri);
                                request.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;

                                isUpdate    = true;
                                fileDateUtc = File.GetLastWriteTimeUtc(dataPath);

                                request.Method          = "HEAD";
                                request.IfModifiedSince = fileDateUtc;

                                try
                                {
                                    using (response = (HttpWebResponse)request.GetResponse())
                                        statusCode = response.StatusCode;
                                }
                                catch (WebException e)
                                {
                                    statusCode = ((HttpWebResponse)e.Response).StatusCode;
                                }

                                if (statusCode == HttpStatusCode.NotModified)
                                {
                                    // The source website does not have an updated file.  I'm going to
                                    // do one extra check to see if the file we have is more than 45
                                    // days old and log a warning.  Note that we're going to issue this
                                    // warning only once a week while the service is running.

                                    if (DateTime.UtcNow - fileDateUtc < TimeSpan.FromDays(45) || DateTime.UtcNow - lastWarningTime >= TimeSpan.FromDays(7))
                                    {
                                        continue;
                                    }

                                    lastWarningTime = DateTime.UtcNow;

                                    const string warning =
                                        @"GeoTracker: The local copy of the MaxMind GeoIP City or GeoLite City database is [{0}] days old 
and should be updated.  You may need to download a new copy of the database from http://maxmind.com,
decompress it and upload it to the source website at [{1}].

Note: Make sure that the website is configured with the [.DAT=application/octet-stream] MIME mapping.";

                                    SysLog.LogWarning(warning, (int)(DateTime.UtcNow - fileDateUtc).TotalDays, settings.IPGeocodeSourceUri);
                                    continue;
                                }
                            }

                            // Download the database to the temporary download file.

                            Helper.DeleteFile(downloadPath);

                            downloadTimer = new ElapsedTimer(true);
                            fileSize      = Helper.WebDownload(settings.IPGeocodeSourceUri, downloadPath, settings.IPGeocodeSourceTimeout, out response);
                            downloadTimer.Stop();

                            // Set the file times to match the Last-Modified header received from the website (it any).

                            string lastModified = response.Headers["Last-Modified"];

                            if (lastModified != null)
                            {
                                try
                                {
                                    fileDateUtc = Helper.ParseInternetDate(lastModified);
                                    File.SetCreationTimeUtc(downloadPath, fileDateUtc);
                                    File.SetLastWriteTimeUtc(downloadPath, fileDateUtc);
                                }
                                catch (Exception e)
                                {
                                    SysLog.LogException(e, "GeoTracker: Website for [{0}] returned invalid Last-Modified header [{1}].",
                                                        settings.IPGeocodeSourceUri, lastModified);
                                }
                            }

                            // Decrypt the file and set its file dates.

                            var keyChain = new KeyChain(settings.IPGeocodeSourceRsaKey);

                            using (var secureFile = new SecureFile(downloadPath, keyChain))
                            {
                                secureFile.DecryptTo(decryptedPath);
                            }

                            File.SetCreationTimeUtc(decryptedPath, fileDateUtc);
                            File.SetLastWriteTimeUtc(decryptedPath, fileDateUtc);

                            // Verify the decrypted data file and then swap in new file.

                            const string info =
                                @"GeoTracker: {0} of IP-to-location database from [{1}] completed.
Downloaded [{2:#.#}MB] bytes in [{3}].";

                            SysLog.LogInformation(info, isUpdate ? "Update download" : "Initial download", settings.IPGeocodeSourceUri, fileSize / (1024 * 1024), downloadTimer.ElapsedTime);

                            // Create a new MaxMind lookup intance and then swap it in without interrupting
                            // any queries in progress.

                            try
                            {
                                LookupService newMaxMind;

                                newMaxMind = new LookupService(decryptedPath, LookupService.GEOIP_MEMORY_CACHE);
                                newMaxMind.close();

                                maxMind = newMaxMind;
                                UpdateCount++;
                            }
                            catch (Exception e)
                            {
                                SysLog.LogException(e);
                                SysLog.LogError("GeoTracker: The MaxMind downloaded database file [{0}] appears to be corrupted.  This will be deleted so the downloader can get a fresh copy.", downloadPath);
                            }

                            lock (syncLock)
                            {
                                Helper.DeleteFile(dataPath);
                                File.Copy(decryptedPath, dataPath);
                                File.SetCreationTimeUtc(dataPath, fileDateUtc);
                                File.SetLastWriteTimeUtc(dataPath, fileDateUtc);
                            }

                            // Delete the temporary files.

                            Helper.DeleteFile(decryptedPath);
                            Helper.DeleteFile(downloadPath);
                        }
                    }
                    catch (WebException e)
                    {
                        SysLog.LogException(e);
                        SysLog.LogWarning("GeoTracker: The download of the MaxMind database file has failed. The service will try again in 1 minute.");

                        pollTimer.ResetTemporary(TimeSpan.FromMinutes(1));
                        resetTimer = false;
                    }
                    catch (ThreadAbortException e)
                    {
                        SysLog.LogException(e);
                        throw;
                    }
                    catch (Exception e)
                    {
                        SysLog.LogException(e);
                    }
                    finally
                    {
                        if (resetTimer)
                        {
                            resetTimer = false;
                            pollTimer.Reset();
                        }
                    }

                    Thread.Sleep(settings.BkInterval);
                }
            }
            finally
            {
                running = false;
            }
        }
示例#27
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("AppStore Service Shutdown");
     serviceHost.OnShutdown(this);
 }
示例#28
0
 /// <summary>
 /// Begins a graceful shut down process by disallowing any new user
 /// connections and monitoring the users still using the system.
 /// Once the last user has disconnected, the service will call the
 /// associated service host's OnShutdown() method.
 /// </summary>
 public void Shutdown()
 {
     SysLog.LogInformation("Message Queue Service Shutdown");
     serviceHost.OnShutdown(this);
 }