Main.cs 25 KB

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