Main.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Management;
  6. using System.Runtime.InteropServices;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.Threading;
  10. using Microsoft.Win32;
  11. using WMI;
  12. using ServiceType = WMI.ServiceType;
  13. using System.Reflection;
  14. namespace winsw
  15. {
  16. public class WrapperService : ServiceBase, EventLogger
  17. {
  18. private SERVICE_STATUS _wrapperServiceStatus;
  19. private readonly Process _process = new Process();
  20. private readonly ServiceDescriptor _descriptor;
  21. private Dictionary<string, string> _envs;
  22. /// <summary>
  23. /// Indicates to the watch dog thread that we are going to terminate the process,
  24. /// so don't try to kill us when the child exits.
  25. /// </summary>
  26. private bool _orderlyShutdown;
  27. private bool _systemShuttingdown;
  28. /// <summary>
  29. /// Version of Windows service wrapper
  30. /// </summary>
  31. /// <remarks>
  32. /// The version will be taken from <see cref="AssemblyInfo"/>
  33. /// </remarks>
  34. public static Version Version
  35. {
  36. get { return Assembly.GetExecutingAssembly().GetName().Version; }
  37. }
  38. public WrapperService(ServiceDescriptor descriptor)
  39. {
  40. _descriptor = descriptor;
  41. ServiceName = _descriptor.Id;
  42. CanShutdown = true;
  43. CanStop = true;
  44. CanPauseAndContinue = false;
  45. AutoLog = true;
  46. _systemShuttingdown = false;
  47. }
  48. public WrapperService() : this (new ServiceDescriptor())
  49. {
  50. }
  51. /// <summary>
  52. /// Process the file copy instructions, so that we can replace files that are always in use while
  53. /// the service runs.
  54. /// </summary>
  55. private void HandleFileCopies()
  56. {
  57. var file = _descriptor.BasePath + ".copies";
  58. if (!File.Exists(file))
  59. return; // nothing to handle
  60. try
  61. {
  62. using (var tr = new StreamReader(file,Encoding.UTF8))
  63. {
  64. string line;
  65. while ((line = tr.ReadLine()) != null)
  66. {
  67. LogEvent("Handling copy: " + line);
  68. string[] tokens = line.Split('>');
  69. if (tokens.Length > 2)
  70. {
  71. LogEvent("Too many delimiters in " + line);
  72. continue;
  73. }
  74. CopyFile(tokens[0], tokens[1]);
  75. }
  76. }
  77. }
  78. finally
  79. {
  80. File.Delete(file);
  81. }
  82. }
  83. /// <summary>
  84. /// File replacement.
  85. /// </summary>
  86. private void CopyFile(string sourceFileName, string destFileName)
  87. {
  88. try
  89. {
  90. File.Delete(destFileName);
  91. File.Move(sourceFileName, destFileName);
  92. }
  93. catch (IOException e)
  94. {
  95. LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  96. }
  97. }
  98. /// <summary>
  99. /// Starts a thread that protects the execution with a try/catch block.
  100. /// It appears that in .NET, unhandled exception in any thread causes the app to terminate
  101. /// http://msdn.microsoft.com/en-us/library/ms228965.aspx
  102. /// </summary>
  103. private void StartThread(ThreadStart main)
  104. {
  105. new Thread(delegate() {
  106. try
  107. {
  108. main();
  109. }
  110. catch (Exception e)
  111. {
  112. WriteEvent("Thread failed unexpectedly",e);
  113. }
  114. }).Start();
  115. }
  116. /// <summary>
  117. /// Handle the creation of the logfiles based on the optional logmode setting.
  118. /// </summary>
  119. private void HandleLogfiles()
  120. {
  121. string logDirectory = _descriptor.LogDirectory;
  122. if (!Directory.Exists(logDirectory))
  123. {
  124. Directory.CreateDirectory(logDirectory);
  125. }
  126. LogHandler logAppender = _descriptor.LogHandler;
  127. logAppender.EventLogger = this;
  128. logAppender.log(_process.StandardOutput.BaseStream, _process.StandardError.BaseStream);
  129. }
  130. public void LogEvent(String message)
  131. {
  132. if (_systemShuttingdown)
  133. {
  134. /* NOP - cannot call EventLog because of shutdown. */
  135. }
  136. else
  137. {
  138. try
  139. {
  140. EventLog.WriteEntry(message);
  141. }
  142. catch (Exception e)
  143. {
  144. WriteEvent("Failed to log event in Windows Event Log: " + message + "; Reason: ", e);
  145. }
  146. }
  147. }
  148. public void LogEvent(String message, EventLogEntryType type)
  149. {
  150. if (_systemShuttingdown)
  151. {
  152. /* NOP - cannot call EventLog because of shutdown. */
  153. }
  154. else
  155. {
  156. try
  157. {
  158. EventLog.WriteEntry(message, type);
  159. }
  160. catch (Exception e)
  161. {
  162. WriteEvent("Failed to log event in Windows Event Log. Reason: ", e);
  163. }
  164. }
  165. }
  166. private void WriteEvent(Exception exception)
  167. {
  168. WriteEvent(exception.Message + "\nStacktrace:" + exception.StackTrace);
  169. }
  170. private void WriteEvent(String message, Exception exception)
  171. {
  172. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  173. }
  174. private void WriteEvent(String message)
  175. {
  176. string logfilename = Path.Combine(_descriptor.LogDirectory, _descriptor.BaseName + ".wrapper.log");
  177. StreamWriter log = new StreamWriter(logfilename, true);
  178. log.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
  179. log.Flush();
  180. log.Close();
  181. }
  182. protected override void OnStart(string[] _)
  183. {
  184. _envs = _descriptor.EnvironmentVariables;
  185. foreach (string key in _envs.Keys)
  186. {
  187. LogEvent("envar " + key + '=' + _envs[key]);
  188. }
  189. HandleFileCopies();
  190. // handle downloads
  191. foreach (Download d in _descriptor.Downloads)
  192. {
  193. LogEvent("Downloading: " + d.From+ " to "+d.To);
  194. try
  195. {
  196. d.Perform();
  197. }
  198. catch (Exception e)
  199. {
  200. LogEvent("Failed to download " + d.From + " to " + d.To + "\n" + e.Message);
  201. WriteEvent("Failed to download " + d.From +" to "+d.To, e);
  202. // but just keep going
  203. }
  204. }
  205. string startarguments = _descriptor.Startarguments;
  206. if (startarguments == null)
  207. {
  208. startarguments = _descriptor.Arguments;
  209. }
  210. else
  211. {
  212. startarguments += " " + _descriptor.Arguments;
  213. }
  214. LogEvent("Starting " + _descriptor.Executable + ' ' + startarguments);
  215. WriteEvent("Starting " + _descriptor.Executable + ' ' + startarguments);
  216. StartProcess(_process, startarguments, _descriptor.Executable);
  217. // send stdout and stderr to its respective output file.
  218. HandleLogfiles();
  219. _process.StandardInput.Close(); // nothing for you to read!
  220. }
  221. protected override void OnShutdown()
  222. {
  223. // WriteEvent("OnShutdown");
  224. try
  225. {
  226. _systemShuttingdown = true;
  227. StopIt();
  228. }
  229. catch (Exception ex)
  230. {
  231. WriteEvent("Shutdown exception", ex);
  232. }
  233. }
  234. protected override void OnStop()
  235. {
  236. // WriteEvent("OnStop");
  237. try
  238. {
  239. StopIt();
  240. }
  241. catch (Exception ex)
  242. {
  243. WriteEvent("Stop exception", ex);
  244. }
  245. }
  246. /// <summary>
  247. /// Called when we are told by Windows SCM to exit.
  248. /// </summary>
  249. private void StopIt()
  250. {
  251. string stoparguments = _descriptor.Stoparguments;
  252. LogEvent("Stopping " + _descriptor.Id);
  253. WriteEvent("Stopping " + _descriptor.Id);
  254. _orderlyShutdown = true;
  255. if (stoparguments == null)
  256. {
  257. try
  258. {
  259. WriteEvent("ProcessKill " + _process.Id);
  260. StopProcessAndChildren(_process.Id);
  261. }
  262. catch (InvalidOperationException)
  263. {
  264. // already terminated
  265. }
  266. }
  267. else
  268. {
  269. SignalShutdownPending();
  270. stoparguments += " " + _descriptor.Arguments;
  271. Process stopProcess = new Process();
  272. String executable = _descriptor.StopExecutable;
  273. if (executable == null)
  274. {
  275. executable = _descriptor.Executable;
  276. }
  277. StartProcess(stopProcess, stoparguments, executable);
  278. WriteEvent("WaitForProcessToExit "+_process.Id+"+"+stopProcess.Id);
  279. WaitForProcessToExit(_process);
  280. WaitForProcessToExit(stopProcess);
  281. SignalShutdownComplete();
  282. }
  283. if (_systemShuttingdown && _descriptor.BeepOnShutdown)
  284. {
  285. Console.Beep();
  286. }
  287. WriteEvent("Finished " + _descriptor.Id);
  288. }
  289. private void StopProcessAndChildren(int pid)
  290. {
  291. var childPids = GetChildPids(pid);
  292. if (_descriptor.StopParentProcessFirst)
  293. {
  294. StopProcess(pid);
  295. foreach (var childPid in childPids)
  296. {
  297. StopProcessAndChildren(childPid);
  298. }
  299. }
  300. else
  301. {
  302. foreach (var childPid in childPids)
  303. {
  304. StopProcessAndChildren(childPid);
  305. }
  306. StopProcess(pid);
  307. }
  308. }
  309. private List<int> GetChildPids(int pid)
  310. {
  311. var searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
  312. var childPids = new List<int>();
  313. foreach (var mo in searcher.Get())
  314. {
  315. var childProcessId = mo["ProcessID"];
  316. WriteEvent("Found child process: " + childProcessId + " Name: " + mo["Name"]);
  317. childPids.Add(Convert.ToInt32(childProcessId));
  318. }
  319. return childPids;
  320. }
  321. private void StopProcess(int pid)
  322. {
  323. WriteEvent("Stopping process " + pid);
  324. Process proc;
  325. try
  326. {
  327. proc = Process.GetProcessById(pid);
  328. }
  329. catch (ArgumentException)
  330. {
  331. WriteEvent("Process " + pid + " is already stopped");
  332. return;
  333. }
  334. WriteEvent("Send SIGINT " + pid);
  335. bool successful = SigIntHelper.SendSIGINTToProcess(proc, _descriptor.StopTimeout);
  336. if (successful)
  337. {
  338. WriteEvent("SIGINT to" + pid + " successful");
  339. }
  340. else
  341. {
  342. try
  343. {
  344. WriteEvent("SIGINT to " + pid + " failed - Killing as fallback");
  345. proc.Kill();
  346. }
  347. catch (ArgumentException)
  348. {
  349. // Process already exited.
  350. }
  351. }
  352. }
  353. private void WaitForProcessToExit(Process processoWait)
  354. {
  355. SignalShutdownPending();
  356. try
  357. {
  358. // WriteEvent("WaitForProcessToExit [start]");
  359. while (!processoWait.WaitForExit(_descriptor.SleepTime.Milliseconds))
  360. {
  361. SignalShutdownPending();
  362. // WriteEvent("WaitForProcessToExit [repeat]");
  363. }
  364. }
  365. catch (InvalidOperationException)
  366. {
  367. // already terminated
  368. }
  369. // WriteEvent("WaitForProcessToExit [finished]");
  370. }
  371. private void SignalShutdownPending()
  372. {
  373. IntPtr handle = ServiceHandle;
  374. _wrapperServiceStatus.checkPoint++;
  375. _wrapperServiceStatus.waitHint = _descriptor.WaitHint.Milliseconds;
  376. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  377. _wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  378. Advapi32.SetServiceStatus(handle, ref _wrapperServiceStatus);
  379. }
  380. private void SignalShutdownComplete()
  381. {
  382. IntPtr handle = ServiceHandle;
  383. _wrapperServiceStatus.checkPoint++;
  384. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  385. _wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  386. Advapi32.SetServiceStatus(handle, ref _wrapperServiceStatus);
  387. }
  388. private void StartProcess(Process processToStart, string arguments, String executable)
  389. {
  390. var ps = processToStart.StartInfo;
  391. ps.FileName = executable;
  392. ps.Arguments = arguments;
  393. ps.WorkingDirectory = _descriptor.WorkingDirectory;
  394. ps.CreateNoWindow = false;
  395. ps.UseShellExecute = false;
  396. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  397. ps.RedirectStandardOutput = true;
  398. ps.RedirectStandardError = true;
  399. foreach (string key in _envs.Keys)
  400. Environment.SetEnvironmentVariable(key, _envs[key]);
  401. // ps.EnvironmentVariables[key] = envs[key]; // bugged (lower cases all variable names due to StringDictionary being used, see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=326163)
  402. processToStart.Start();
  403. WriteEvent("Started " + processToStart.Id);
  404. var priority = _descriptor.Priority;
  405. if (priority != ProcessPriorityClass.Normal)
  406. processToStart.PriorityClass = priority;
  407. // monitor the completion of the process
  408. StartThread(delegate
  409. {
  410. string msg = processToStart.Id + " - " + processToStart.StartInfo.FileName + " " + processToStart.StartInfo.Arguments;
  411. processToStart.WaitForExit();
  412. try
  413. {
  414. if (_orderlyShutdown)
  415. {
  416. LogEvent("Child process [" + msg + "] terminated with " + processToStart.ExitCode, EventLogEntryType.Information);
  417. }
  418. else
  419. {
  420. LogEvent("Child process [" + msg + "] finished with " + processToStart.ExitCode, EventLogEntryType.Warning);
  421. // if we finished orderly, report that to SCM.
  422. // by not reporting unclean shutdown, we let Windows SCM to decide if it wants to
  423. // restart the service automatically
  424. if (processToStart.ExitCode == 0)
  425. SignalShutdownComplete();
  426. Environment.Exit(processToStart.ExitCode);
  427. }
  428. }
  429. catch (InvalidOperationException ioe)
  430. {
  431. LogEvent("WaitForExit " + ioe.Message);
  432. }
  433. try
  434. {
  435. processToStart.Dispose();
  436. }
  437. catch (InvalidOperationException ioe)
  438. {
  439. LogEvent("Dispose " + ioe.Message);
  440. }
  441. });
  442. }
  443. public static int Main(string[] args)
  444. {
  445. try
  446. {
  447. Run(args);
  448. return 0;
  449. }
  450. catch (WmiException e)
  451. {
  452. Console.Error.WriteLine(e);
  453. return (int)e.ErrorCode;
  454. }
  455. catch (Exception e)
  456. {
  457. Console.Error.WriteLine(e);
  458. return -1;
  459. }
  460. }
  461. private static void ThrowNoSuchService()
  462. {
  463. throw new WmiException(ReturnValue.NoSuchService);
  464. }
  465. // ReSharper disable once InconsistentNaming
  466. public static void Run(string[] _args, ServiceDescriptor descriptor = null)
  467. {
  468. if (_args.Length > 0)
  469. {
  470. var d = descriptor ?? new ServiceDescriptor();
  471. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  472. Win32Service s = svc.Select(d.Id);
  473. var args = new List<string>(Array.AsReadOnly(_args));
  474. if (args[0] == "/redirect")
  475. {
  476. // Redirect output
  477. // One might ask why we support this when the caller
  478. // can redirect the output easily. The answer is for supporting UAC.
  479. // On UAC-enabled Windows such as Vista, SCM operation requires
  480. // elevated privileges, thus winsw.exe needs to be launched
  481. // accordingly. This in turn limits what the caller can do,
  482. // and among other things it makes it difficult for the caller
  483. // to read stdout/stderr. Thus redirection becomes handy.
  484. var f = new FileStream(args[1], FileMode.Create);
  485. var w = new StreamWriter(f) {AutoFlush = true};
  486. Console.SetOut(w);
  487. Console.SetError(w);
  488. var handle = f.Handle;
  489. Kernel32.SetStdHandle(-11, handle); // set stdout
  490. Kernel32.SetStdHandle(-12, handle); // set stder
  491. args = args.GetRange(2, args.Count - 2);
  492. }
  493. args[0] = args[0].ToLower();
  494. if (args[0] == "install")
  495. {
  496. string username=null, password=null;
  497. bool setallowlogonasaserviceright = false;
  498. if (args.Count > 1 && args[1] == "/p")
  499. {
  500. // we expected username/password on stdin
  501. Console.Write("Username: ");
  502. username = Console.ReadLine();
  503. Console.Write("Password: ");
  504. password = ReadPassword();
  505. Console.WriteLine();
  506. Console.Write("Set Account rights to allow log on as a service (y/n)?: ");
  507. var keypressed = Console.ReadKey();
  508. Console.WriteLine();
  509. if (keypressed.Key == ConsoleKey.Y)
  510. {
  511. setallowlogonasaserviceright = true;
  512. }
  513. }
  514. else
  515. {
  516. if (d.HasServiceAccount())
  517. {
  518. username = d.ServiceAccountUser;
  519. password = d.ServiceAccountPassword;
  520. setallowlogonasaserviceright = d.AllowServiceAcountLogonRight;
  521. }
  522. }
  523. if (setallowlogonasaserviceright)
  524. {
  525. LogonAsAService.AddLogonAsAServiceRight(username);
  526. }
  527. svc.Create (
  528. d.Id,
  529. d.Caption,
  530. "\"" + d.ExecutablePath + "\"",
  531. ServiceType.OwnProcess,
  532. ErrorControl.UserNotified,
  533. StartMode.Automatic,
  534. d.Interactive,
  535. username,
  536. password,
  537. d.ServiceDependencies);
  538. // update the description
  539. /* Somehow this doesn't work, even though it doesn't report an error
  540. Win32Service s = svc.Select(d.Id);
  541. s.Description = d.Description;
  542. s.Commit();
  543. */
  544. // so using a classic method to set the description. Ugly.
  545. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  546. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  547. var actions = d.FailureActions;
  548. if (actions.Count > 0)
  549. {// set the failure actions
  550. using (ServiceManager scm = new ServiceManager())
  551. {
  552. using (Service sc = scm.Open(d.Id))
  553. {
  554. sc.ChangeConfig(d.ResetFailureAfter, actions);
  555. }
  556. }
  557. }
  558. return;
  559. }
  560. if (args[0] == "uninstall")
  561. {
  562. if (s == null)
  563. return; // there's no such service, so consider it already uninstalled
  564. try
  565. {
  566. s.Delete();
  567. }
  568. catch (WmiException e)
  569. {
  570. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  571. return; // it's already uninstalled, so consider it a success
  572. throw e;
  573. }
  574. return;
  575. }
  576. if (args[0] == "start")
  577. {
  578. if (s == null) ThrowNoSuchService();
  579. s.StartService();
  580. return;
  581. }
  582. if (args[0] == "stop")
  583. {
  584. if (s == null) ThrowNoSuchService();
  585. s.StopService();
  586. return;
  587. }
  588. if (args[0] == "restart")
  589. {
  590. if (s == null)
  591. ThrowNoSuchService();
  592. if(s.Started)
  593. s.StopService();
  594. while (s.Started)
  595. {
  596. Thread.Sleep(1000);
  597. s = svc.Select(d.Id);
  598. }
  599. s.StartService();
  600. return;
  601. }
  602. if (args[0] == "restart!")
  603. {
  604. // run restart from another process group. see README.md for why this is useful.
  605. STARTUPINFO si = new STARTUPINFO();
  606. PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
  607. bool result = Kernel32.CreateProcess(null, d.ExecutablePath+" restart", IntPtr.Zero, IntPtr.Zero, false, 0x200/*CREATE_NEW_PROCESS_GROUP*/, IntPtr.Zero, null, ref si, out pi);
  608. if (!result)
  609. {
  610. throw new Exception("Failed to invoke restart: "+Marshal.GetLastWin32Error());
  611. }
  612. return;
  613. }
  614. if (args[0] == "status")
  615. {
  616. if (s == null)
  617. Console.WriteLine("NonExistent");
  618. else if (s.Started)
  619. Console.WriteLine("Started");
  620. else
  621. Console.WriteLine("Stopped");
  622. return;
  623. }
  624. if (args[0] == "test")
  625. {
  626. WrapperService wsvc = new WrapperService();
  627. wsvc.OnStart(args.ToArray());
  628. Thread.Sleep(1000);
  629. wsvc.OnStop();
  630. return;
  631. }
  632. if (args[0] == "help" || args[0] == "--help" || args[0] == "-h"
  633. || args[0] == "-?" || args[0] == "/?")
  634. {
  635. printHelp();
  636. return;
  637. }
  638. if (args[0] == "version")
  639. {
  640. printVersion();
  641. return;
  642. }
  643. Console.WriteLine("Unknown command: " + args[0]);
  644. printAvailableCommandsInfo();
  645. throw new Exception("Unknown command: " + args[0]);
  646. }
  647. Run(new WrapperService());
  648. }
  649. private static string ReadPassword()
  650. {
  651. StringBuilder buf = new StringBuilder();
  652. ConsoleKeyInfo key;
  653. while (true)
  654. {
  655. key = Console.ReadKey(true);
  656. if (key.Key == ConsoleKey.Enter)
  657. {
  658. return buf.ToString();
  659. }
  660. else if (key.Key == ConsoleKey.Backspace)
  661. {
  662. buf.Remove(buf.Length - 1, 1);
  663. Console.Write("\b \b");
  664. }
  665. else
  666. {
  667. Console.Write('*');
  668. buf.Append(key.KeyChar);
  669. }
  670. }
  671. }
  672. private static void printHelp()
  673. {
  674. Console.WriteLine("A wrapper binary that can be used to host executables as Windows services");
  675. Console.WriteLine("");
  676. Console.WriteLine("Usage: winsw [/redirect file] <command> [<args>]");
  677. Console.WriteLine(" Missing arguments trigger the service mode");
  678. Console.WriteLine("");
  679. printAvailableCommandsInfo();
  680. Console.WriteLine("");
  681. Console.WriteLine("Extra options:");
  682. Console.WriteLine("- '/redirect' - redirect the wrapper's STDOUT and STDERR to the specified file");
  683. Console.WriteLine("");
  684. printVersion();
  685. Console.WriteLine("More info: https://github.com/kohsuke/winsw");
  686. Console.WriteLine("Bug tracker: https://github.com/kohsuke/winsw/issues");
  687. }
  688. //TODO: Rework to enum in winsw-2.0
  689. private static void printAvailableCommandsInfo()
  690. {
  691. Console.WriteLine("Available commands:");
  692. Console.WriteLine("- 'install' - install the service to Windows Service Controller");
  693. Console.WriteLine("- 'uninstall' - uninstall the service");
  694. Console.WriteLine("- 'start' - start the service (must be installed before)");
  695. Console.WriteLine("- 'stop' - stop the service");
  696. Console.WriteLine("- 'restart' - restart the service");
  697. Console.WriteLine("- 'restart!' - self-restart (can be called from child processes)");
  698. Console.WriteLine("- 'status' - check the current status of the service");
  699. Console.WriteLine("- 'test' - check if the service can be started and then stopped");
  700. Console.WriteLine("- 'version' - print the version info");
  701. Console.WriteLine("- 'help' - print the help info (aliases: -h,--help,-?,/?)");
  702. }
  703. private static void printVersion()
  704. {
  705. Console.WriteLine("WinSW " + Version);
  706. }
  707. }
  708. }