PageRenderTime 103ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Raven.Server/Program.cs

https://github.com/mikehadlow/ravendb
C# | 286 lines | 262 code | 23 blank | 1 comment | 32 complexity | 294675fce84afc9b1fb722a1559b1065 MD5 | raw file
  1. using System;
  2. using System.Configuration.Install;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Security.Principal;
  8. using System.ServiceProcess;
  9. using log4net.Appender;
  10. using log4net.Config;
  11. using log4net.Filter;
  12. using log4net.Layout;
  13. using Raven.Database;
  14. using Raven.Database.Server;
  15. namespace Raven.Server
  16. {
  17. internal class Program
  18. {
  19. private static void Main(string[] args)
  20. {
  21. if (Environment.UserInteractive)
  22. {
  23. try
  24. {
  25. InteractiveRun(args);
  26. }
  27. catch (ReflectionTypeLoadException e)
  28. {
  29. Console.WriteLine(e);
  30. foreach (var loaderException in e.LoaderExceptions)
  31. {
  32. Console.WriteLine("- - - -");
  33. Console.WriteLine(loaderException);
  34. }
  35. Environment.Exit(-1);
  36. }
  37. catch (Exception e)
  38. {
  39. Console.WriteLine(e);
  40. Environment.Exit(-1);
  41. }
  42. }
  43. else
  44. {
  45. // no try catch here, we want the exception to be logged by Windows
  46. ServiceBase.Run(new RavenService());
  47. }
  48. }
  49. private static void InteractiveRun(string[] args)
  50. {
  51. switch (GetArgument(args))
  52. {
  53. case "install":
  54. AdminRequired(InstallAndStart, "/install");
  55. break;
  56. case "uninstall":
  57. AdminRequired(EnsureStoppedAndUninstall, "/uninstall");
  58. break;
  59. case "start":
  60. AdminRequired(StartService, "/start");
  61. break;
  62. case "restart":
  63. AdminRequired(RestartService, "/restart");
  64. break;
  65. case "stop":
  66. AdminRequired(StopService, "/stop");
  67. break;
  68. case "restore":
  69. if (args.Length != 3)
  70. {
  71. PrintUsage();
  72. break;
  73. }
  74. RunRestoreOperation(args[0], args[1]);
  75. break;
  76. case "debug":
  77. RunInDebugMode(anonymousUserAccessMode: null);
  78. break;
  79. #if DEBUG
  80. case "test":
  81. var dataDirectory = new RavenConfiguration().DataDirectory;
  82. if (Directory.Exists(dataDirectory))
  83. Directory.Delete(dataDirectory, true);
  84. RunInDebugMode(anonymousUserAccessMode: AnonymousUserAccessMode.All);
  85. break;
  86. #endif
  87. default:
  88. PrintUsage();
  89. break;
  90. }
  91. }
  92. private static void RunRestoreOperation(string backupLocation, string databaseLocation)
  93. {
  94. try
  95. {
  96. DocumentDatabase.Restore(new RavenConfiguration(), backupLocation, databaseLocation);
  97. }
  98. catch (Exception e)
  99. {
  100. Console.WriteLine(e);
  101. }
  102. }
  103. private static void AdminRequired(Action actionThatMayRequiresAdminPrivileges, string cmdLine)
  104. {
  105. var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
  106. if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false)
  107. {
  108. if (RunAgainAsAdmin(cmdLine))
  109. return;
  110. }
  111. actionThatMayRequiresAdminPrivileges();
  112. }
  113. private static bool RunAgainAsAdmin(string cmdLine)
  114. {
  115. try
  116. {
  117. var process = Process.Start(new ProcessStartInfo
  118. {
  119. Arguments = cmdLine,
  120. FileName = Assembly.GetExecutingAssembly().Location,
  121. Verb = "runas",
  122. });
  123. if (process != null)
  124. process.WaitForExit();
  125. return true;
  126. }
  127. catch (Exception)
  128. {
  129. return false;
  130. }
  131. }
  132. private static string GetArgument(string[] args)
  133. {
  134. if (args.Length == 0)
  135. return "debug";
  136. if (args[0].StartsWith("/") == false)
  137. return "help";
  138. return args[0].Substring(1);
  139. }
  140. private static void RunInDebugMode(AnonymousUserAccessMode? anonymousUserAccessMode)
  141. {
  142. var consoleAppender = new ConsoleAppender
  143. {
  144. Layout = new PatternLayout(PatternLayout.DefaultConversionPattern),
  145. };
  146. consoleAppender.AddFilter(new LoggerMatchFilter
  147. {
  148. AcceptOnMatch = true,
  149. LoggerToMatch = typeof(HttpServer).FullName
  150. });
  151. consoleAppender.AddFilter(new DenyAllFilter());
  152. BasicConfigurator.Configure(consoleAppender);
  153. var ravenConfiguration = new RavenConfiguration();
  154. NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(ravenConfiguration.Port);
  155. if (anonymousUserAccessMode.HasValue)
  156. ravenConfiguration.AnonymousUserAccessMode = anonymousUserAccessMode.Value;
  157. using (new RavenDbServer(ravenConfiguration))
  158. {
  159. var path = Path.Combine(Environment.CurrentDirectory, "default.raven");
  160. if (File.Exists(path))
  161. {
  162. Console.WriteLine("Loading data from: {0}", path);
  163. Smuggler.Smuggler.ImportData(ravenConfiguration.ServerUrl, path);
  164. }
  165. Console.WriteLine("Raven is ready to process requests.");
  166. Console.WriteLine("Data directory: {0}, HostName: {1} Port: {2}", ravenConfiguration.DataDirectory, ravenConfiguration.HostName ?? "<any>", ravenConfiguration.Port);
  167. Console.WriteLine("Press the enter key to stop the server or enter 'cls' and then enter to clear the log");
  168. while (true)
  169. {
  170. var readLine = Console.ReadLine();
  171. if (!"CLS".Equals(readLine, StringComparison.InvariantCultureIgnoreCase))
  172. break;
  173. Console.Clear();
  174. }
  175. }
  176. }
  177. private static void PrintUsage()
  178. {
  179. Console.WriteLine(
  180. @"
  181. Raven DB
  182. Document Database for the .Net Platform
  183. ----------------------------------------
  184. Copyright (C) 2010 - Hibernating Rhinos
  185. ----------------------------------------
  186. Command line ptions:
  187. RavenDb - with no args, starts Raven in local server mode
  188. RavenDb /install - installs and starts the Raven service
  189. RavenDb /unisntall - stops and uninstalls the Raven service
  190. RavenDb /start - starts the previously installed Raven service
  191. RavenDb /stop - stops the previously installed Raven service
  192. RavenDb /restart - restarts the previously installed Raven service
  193. RavenDB /restore [backup location] [new database location]
  194. - restore a previously backed up database to the new
  195. location
  196. Enjoy...
  197. ");
  198. }
  199. private static void EnsureStoppedAndUninstall()
  200. {
  201. if (ServiceIsInstalled() == false)
  202. {
  203. Console.WriteLine("Service is not installed");
  204. }
  205. else
  206. {
  207. var stopController = new ServiceController(ProjectInstaller.SERVICE_NAME);
  208. if (stopController.Status == ServiceControllerStatus.Running)
  209. stopController.Stop();
  210. ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
  211. }
  212. }
  213. private static void StopService()
  214. {
  215. var stopController = new ServiceController(ProjectInstaller.SERVICE_NAME);
  216. if (stopController.Status == ServiceControllerStatus.Running)
  217. {
  218. stopController.Stop();
  219. stopController.WaitForStatus(ServiceControllerStatus.Stopped);
  220. }
  221. }
  222. private static void StartService()
  223. {
  224. var stopController = new ServiceController(ProjectInstaller.SERVICE_NAME);
  225. if (stopController.Status != ServiceControllerStatus.Running)
  226. {
  227. stopController.Start();
  228. stopController.WaitForStatus(ServiceControllerStatus.Running);
  229. }
  230. }
  231. private static void RestartService()
  232. {
  233. var stopController = new ServiceController(ProjectInstaller.SERVICE_NAME);
  234. if (stopController.Status == ServiceControllerStatus.Running)
  235. {
  236. stopController.Stop();
  237. stopController.WaitForStatus(ServiceControllerStatus.Stopped);
  238. }
  239. if (stopController.Status != ServiceControllerStatus.Running)
  240. {
  241. stopController.Start();
  242. stopController.WaitForStatus(ServiceControllerStatus.Running);
  243. }
  244. }
  245. private static void InstallAndStart()
  246. {
  247. if (ServiceIsInstalled())
  248. {
  249. Console.WriteLine("Service is already installed");
  250. }
  251. else
  252. {
  253. ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
  254. var startController = new ServiceController(ProjectInstaller.SERVICE_NAME);
  255. startController.Start();
  256. }
  257. }
  258. private static bool ServiceIsInstalled()
  259. {
  260. return (ServiceController.GetServices().Count(s => s.ServiceName == ProjectInstaller.SERVICE_NAME) > 0);
  261. }
  262. }
  263. }