Main.cs 24 KB

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