Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored AppRunner and Console Main to use smaller methods. #280

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 74 additions & 59 deletions project/console/AppRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,54 +27,27 @@ public class AppRunner
/// <returns></returns>
public int Run(string[] args, bool usesShadowCopying)
{
ConsoleRunnerArguments consoleArgs = new ConsoleRunnerArguments();
List<string> extra = new List<string>();

OptionSet opts = new OptionSet();
opts.Add("h|?|help", "display this help screen", delegate(string v) { consoleArgs.ShowHelp = v != null; })
.Add("c|config=", "the configuration file to use (defaults to ccnet.conf)", delegate(string v) { consoleArgs.ConfigFile = v; })
.Add("r|remoting=", "turn remoting on/off (defaults to on)", delegate(string v) { consoleArgs.UseRemoting = v == "on"; })
.Add("p|project=", "the project to integrate (???)", delegate(string v) { consoleArgs.Project = v; })
.Add("v|validate", "validate the configuration file and exit", delegate(string v) { consoleArgs.ValidateConfigOnly = v != null; })
.Add("l|logging=", "turn logging on/off (defaults to on)", delegate(string v) { consoleArgs.Logging = v == "on"; })
.Add("e|errorpause=", "turn pause on error on/off (defaults to on)", delegate(string v) {consoleArgs.PauseOnError = v == "on"; });

try
{
extra = opts.Parse(args);
}
catch (OptionException e)
{
System.Console.WriteLine(e.Message);
System.Console.WriteLine(e.StackTrace);
return 1;
}

if(consoleArgs.ShowHelp)
{
DisplayHelp(opts);
return 0;
}

try
ConsoleRunnerArguments consoleArgs = new ConsoleRunnerArguments();

if (consoleArgs.ShowHelp)
{
runner = new ConsoleRunner(consoleArgs, new CruiseServerFactory());
if (!usesShadowCopying)
{
Log.Warning("Shadow-copying has been turned off - hot-swapping will not work!");
}
DisplayHelp(GetPopulatedOptionSet(consoleArgs));
return 0;
}

runner.Run();
return SetUpConsoleRunner(usesShadowCopying, consoleArgs);
}

private int SetUpConsoleRunner(bool usesShadowCopying, ConsoleRunnerArguments consoleArgs)
{
try
{
StartConsoleRunner(usesShadowCopying, consoleArgs);
return 0;
}
catch (Exception ex)
{
Log.Error(ex);
if (consoleArgs.PauseOnError)
{
System.Console.WriteLine("An unexpected error has caused the console to crash, please press any key to continue...");
System.Console.ReadKey();
}
HandleAppRunnerException(consoleArgs.PauseOnError, ex);
return 1;
}
finally
Expand All @@ -83,6 +56,40 @@ public int Run(string[] args, bool usesShadowCopying)
}
}

private void HandleAppRunnerException(bool pauseOnError, Exception ex)
{
Log.Error(ex);
if (pauseOnError)
{
System.Console.WriteLine("An unexpected error has caused the console to crash, please press any key to continue...");
System.Console.ReadKey();
}
}

private void StartConsoleRunner(bool usesShadowCopying, ConsoleRunnerArguments consoleArgs)
{
runner = new ConsoleRunner(consoleArgs, new CruiseServerFactory());
if (!usesShadowCopying)
{
Log.Warning("Shadow-copying has been turned off - hot-swapping will not work!");
}

runner.Run();
}

private OptionSet GetPopulatedOptionSet(ConsoleRunnerArguments consoleArgs)
{
OptionSet opts = new OptionSet();
opts.Add("h|?|help", "display this help screen", delegate (string v) { consoleArgs.ShowHelp = v != null; })
.Add("c|config=", "the configuration file to use (defaults to ccnet.conf)", delegate (string v) { consoleArgs.ConfigFile = v; })
.Add("r|remoting=", "turn remoting on/off (defaults to on)", delegate (string v) { consoleArgs.UseRemoting = v == "on"; })
.Add("p|project=", "the project to integrate (???)", delegate (string v) { consoleArgs.Project = v; })
.Add("v|validate", "validate the configuration file and exit", delegate (string v) { consoleArgs.ValidateConfigOnly = v != null; })
.Add("l|logging=", "turn logging on/off (defaults to on)", delegate (string v) { consoleArgs.Logging = v == "on"; })
.Add("e|errorpause=", "turn pause on error on/off (defaults to on)", delegate (string v) { consoleArgs.PauseOnError = v == "on"; });
return opts;
}

#region InitializeLifetimeService()
/// <summary>
/// Initialise the lifetime service.
Expand Down Expand Up @@ -113,35 +120,43 @@ public void Stop(string reason)
}
if (stopRunner)
{
// Perform the actual stop
StopAppRunner(reason);
}
}
private void StopAppRunner(string reason)
{
try
{
Log.Info("Stopping console: " + reason);
try
{
runner.Stop();
}
catch (RemotingException)
{
// Sometimes this exception gets thrown and not sure why.
}
runner.Stop();
}
catch (RemotingException)
{
// Sometimes this exception gets thrown and not sure why.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to log the RemotingException errors at debug level.

}
}
private static void DisplayHelp(OptionSet opts)

private void DisplayHelp(OptionSet opts)
{
Assembly thisApp = Assembly.GetExecutingAssembly();
Stream helpStream = thisApp.GetManifestResourceStream("ThoughtWorks.CruiseControl.Console.Help.txt");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @j-cordova-aptera

Some using(Stream sr = ...) would ensure the streams are properly handled in case of an error.
I also see no need for the WriteHelpToConsole method since it's used only here.

try
{
StreamReader reader = new StreamReader(helpStream);
string data = reader.ReadToEnd();
reader.Close();
System.Console.Write(data);
WriteHelpToConsole(helpStream);
}
finally
{
{
helpStream.Close();
}
opts.WriteOptionDescriptions (System.Console.Out);
opts.WriteOptionDescriptions(System.Console.Out);
}

private void WriteHelpToConsole(Stream helpStream)
{
StreamReader reader = new StreamReader(helpStream);
string data = reader.ReadToEnd();
reader.Close();
System.Console.Write(data);
}
}
}
95 changes: 7 additions & 88 deletions project/console/ConsoleMain.cs
Original file line number Diff line number Diff line change
@@ -1,98 +1,17 @@
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Runtime.Remoting;
using System.Configuration;
using ThoughtWorks.CruiseControl.Core;

namespace ThoughtWorks.CruiseControl.Console
{
public class ConsoleMain
{
public class ConsoleMain
{
private static object lockObject = new object();

[STAThread]
internal static int Main(string[] args)
{
bool restart = true;
int result = 0;
DateTime restartTime = DateTime.MinValue;
using (FileSystemWatcher watcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "*.dll"))
{
AppRunner runner = null;

// Start monitoring file changes
watcher.Changed += delegate(object sender, FileSystemEventArgs e)
{
if (!restart)
{
lock (lockObject)
{
try
{
runner.Stop("One or more DLLs have changed");
}
catch (RemotingException)
{
// Sometimes this exception occurs - the lock statement should catch it, but...
}
}
}
restart = true;
restartTime = DateTime.Now.AddSeconds(10);
};
watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.Size;
watcher.EnableRaisingEvents = true;

// Begin the main application loop
while (restart)
{
restart = false;

// Load the domain and start the runner
// Allow the user to turn shadow-copying off
var setting = ConfigurationManager.AppSettings["ShadowCopy"] ?? string.Empty;
var useShadowCopying = !(string.Equals(setting, "off", StringComparison.OrdinalIgnoreCase) ||
string.Equals(setting, "false", StringComparison.OrdinalIgnoreCase));
AppDomain runnerDomain;
try
{
runnerDomain = CreateNewDomain(useShadowCopying);
}
catch (FileLoadException)
{
// Unable to use shadow-copying (no user profile?), therefore turn off shadow-copying
useShadowCopying = false;
runnerDomain = CreateNewDomain(useShadowCopying);
}
runner = runnerDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location,
typeof(AppRunner).FullName) as AppRunner;
result = runner.Run(args, useShadowCopying);
AppDomain.Unload(runnerDomain);

// Allow any change events to finish (i.e. if multiple files are copied)
while (DateTime.Now < restartTime)
{
Thread.Sleep(500);
}
}
}
return result;
}

/// <summary>
/// Creates the new runner domain.
/// </summary>
/// <param name="useShadowCopying">If set to <c>true</c> shadow copying will be used.</param>
/// <returns>The new <see cref="AppDomain"/>.</returns>
private static AppDomain CreateNewDomain(bool useShadowCopying)
[STAThread]
internal static int Main(string[] args)
{
return AppDomain.CreateDomain(
"CC.Net",
null,
AppDomain.CurrentDomain.BaseDirectory,
AppDomain.CurrentDomain.RelativeSearchPath,
useShadowCopying);
MainRunner runner = new MainRunner(args, lockObject);
return runner.Run();
}
}
}
Loading