Main.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. EventLog.WriteEntry(message);
  128. }
  129. }
  130. public void LogEvent(String message, EventLogEntryType type)
  131. {
  132. if (systemShuttingdown)
  133. {
  134. /* NOP - cannot call EventLog because of shutdown. */
  135. }
  136. else
  137. {
  138. EventLog.WriteEntry(message, type);
  139. }
  140. }
  141. private void WriteEvent(Exception exception)
  142. {
  143. WriteEvent(exception.Message + "\nStacktrace:" + exception.StackTrace);
  144. }
  145. private void WriteEvent(String message, Exception exception)
  146. {
  147. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  148. }
  149. private void WriteEvent(String message)
  150. {
  151. string logfilename = Path.Combine(descriptor.LogDirectory, descriptor.BaseName + ".wrapper.log");
  152. StreamWriter log = new StreamWriter(logfilename, true);
  153. log.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
  154. log.Flush();
  155. log.Close();
  156. }
  157. protected override void OnStart(string[] _)
  158. {
  159. envs = descriptor.EnvironmentVariables;
  160. foreach (string key in envs.Keys)
  161. {
  162. LogEvent("envar " + key + '=' + envs[key]);
  163. }
  164. HandleFileCopies();
  165. // handle downloads
  166. foreach (Download d in descriptor.Downloads)
  167. {
  168. LogEvent("Downloading: " + d.From+ " to "+d.To);
  169. try
  170. {
  171. d.Perform();
  172. }
  173. catch (Exception e)
  174. {
  175. LogEvent("Failed to download " + d.From + " to " + d.To + "\n" + e.Message);
  176. WriteEvent("Failed to download " + d.From +" to "+d.To, e);
  177. // but just keep going
  178. }
  179. }
  180. string startarguments = descriptor.Startarguments;
  181. if (startarguments == null)
  182. {
  183. startarguments = descriptor.Arguments;
  184. }
  185. else
  186. {
  187. startarguments += " " + descriptor.Arguments;
  188. }
  189. LogEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  190. WriteEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  191. StartProcess(process, startarguments, descriptor.Executable);
  192. // send stdout and stderr to its respective output file.
  193. HandleLogfiles();
  194. process.StandardInput.Close(); // nothing for you to read!
  195. }
  196. protected override void OnShutdown()
  197. {
  198. // WriteEvent("OnShutdown");
  199. try
  200. {
  201. this.systemShuttingdown = true;
  202. StopIt();
  203. }
  204. catch (Exception ex)
  205. {
  206. WriteEvent("Shutdown exception", ex);
  207. }
  208. }
  209. protected override void OnStop()
  210. {
  211. // WriteEvent("OnStop");
  212. try
  213. {
  214. StopIt();
  215. }
  216. catch (Exception ex)
  217. {
  218. WriteEvent("Stop exception", ex);
  219. }
  220. }
  221. /// <summary>
  222. /// Called when we are told by Windows SCM to exit.
  223. /// </summary>
  224. private void StopIt()
  225. {
  226. string stoparguments = descriptor.Stoparguments;
  227. LogEvent("Stopping " + descriptor.Id);
  228. WriteEvent("Stopping " + descriptor.Id);
  229. orderlyShutdown = true;
  230. if (stoparguments == null)
  231. {
  232. try
  233. {
  234. WriteEvent("ProcessKill " + process.Id);
  235. StopProcessAndChildren(process.Id);
  236. }
  237. catch (InvalidOperationException)
  238. {
  239. // already terminated
  240. }
  241. }
  242. else
  243. {
  244. SignalShutdownPending();
  245. stoparguments += " " + descriptor.Arguments;
  246. Process stopProcess = new Process();
  247. String executable = descriptor.StopExecutable;
  248. if (executable == null)
  249. {
  250. executable = descriptor.Executable;
  251. }
  252. StartProcess(stopProcess, stoparguments, executable);
  253. WriteEvent("WaitForProcessToExit "+process.Id+"+"+stopProcess.Id);
  254. WaitForProcessToExit(process);
  255. WaitForProcessToExit(stopProcess);
  256. SignalShutdownComplete();
  257. }
  258. if (systemShuttingdown && descriptor.BeepOnShutdown)
  259. {
  260. Console.Beep();
  261. }
  262. WriteEvent("Finished " + descriptor.Id);
  263. }
  264. private void StopProcessAndChildren(int pid)
  265. {
  266. var searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
  267. foreach (var mo in searcher.Get())
  268. {
  269. StopProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
  270. }
  271. var proc = Process.GetProcessById(pid);
  272. WriteEvent("Send SIGINT " + process.Id);
  273. bool successful = SigIntHelper.SendSIGINTToProcess(proc,descriptor.StopTimeout);
  274. if (successful)
  275. {
  276. WriteEvent("SIGINT to" + process.Id + " successful");
  277. }
  278. else
  279. {
  280. try
  281. {
  282. WriteEvent("SIGINT to " + process.Id + " failed - Killing as fallback");
  283. proc.Kill();
  284. }
  285. catch (ArgumentException)
  286. {
  287. // Process already exited.
  288. }
  289. }
  290. }
  291. private void WaitForProcessToExit(Process process)
  292. {
  293. SignalShutdownPending();
  294. try
  295. {
  296. // WriteEvent("WaitForProcessToExit [start]");
  297. while (!process.WaitForExit(descriptor.SleepTime.Milliseconds))
  298. {
  299. SignalShutdownPending();
  300. // WriteEvent("WaitForProcessToExit [repeat]");
  301. }
  302. }
  303. catch (InvalidOperationException)
  304. {
  305. // already terminated
  306. }
  307. // WriteEvent("WaitForProcessToExit [finished]");
  308. }
  309. private void SignalShutdownPending()
  310. {
  311. IntPtr handle = this.ServiceHandle;
  312. wrapperServiceStatus.checkPoint++;
  313. wrapperServiceStatus.waitHint = descriptor.WaitHint.Milliseconds;
  314. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  315. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  316. Advapi32.SetServiceStatus(handle, ref wrapperServiceStatus);
  317. }
  318. private void SignalShutdownComplete()
  319. {
  320. IntPtr handle = this.ServiceHandle;
  321. wrapperServiceStatus.checkPoint++;
  322. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  323. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  324. Advapi32.SetServiceStatus(handle, ref wrapperServiceStatus);
  325. }
  326. private void StartProcess(Process process, string arguments, String executable)
  327. {
  328. var ps = process.StartInfo;
  329. ps.FileName = executable;
  330. ps.Arguments = arguments;
  331. ps.WorkingDirectory = descriptor.WorkingDirectory;
  332. ps.CreateNoWindow = false;
  333. ps.UseShellExecute = false;
  334. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  335. ps.RedirectStandardOutput = true;
  336. ps.RedirectStandardError = true;
  337. foreach (string key in envs.Keys)
  338. System.Environment.SetEnvironmentVariable(key, envs[key]);
  339. // 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)
  340. process.Start();
  341. WriteEvent("Started " + process.Id);
  342. var priority = descriptor.Priority;
  343. if (priority != ProcessPriorityClass.Normal)
  344. process.PriorityClass = priority;
  345. // monitor the completion of the process
  346. StartThread(delegate()
  347. {
  348. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  349. process.WaitForExit();
  350. try
  351. {
  352. if (orderlyShutdown)
  353. {
  354. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  355. }
  356. else
  357. {
  358. LogEvent("Child process [" + msg + "] finished with " + process.ExitCode, EventLogEntryType.Warning);
  359. // if we finished orderly, report that to SCM.
  360. // by not reporting unclean shutdown, we let Windows SCM to decide if it wants to
  361. // restart the service automatically
  362. if (process.ExitCode == 0)
  363. SignalShutdownComplete();
  364. Environment.Exit(process.ExitCode);
  365. }
  366. }
  367. catch (InvalidOperationException ioe)
  368. {
  369. LogEvent("WaitForExit " + ioe.Message);
  370. }
  371. try
  372. {
  373. process.Dispose();
  374. }
  375. catch (InvalidOperationException ioe)
  376. {
  377. LogEvent("Dispose " + ioe.Message);
  378. }
  379. });
  380. }
  381. public static int Main(string[] args)
  382. {
  383. try
  384. {
  385. Run(args);
  386. return 0;
  387. }
  388. catch (WmiException e)
  389. {
  390. Console.Error.WriteLine(e);
  391. return (int)e.ErrorCode;
  392. }
  393. catch (Exception e)
  394. {
  395. Console.Error.WriteLine(e);
  396. return -1;
  397. }
  398. }
  399. private static void ThrowNoSuchService()
  400. {
  401. throw new WmiException(ReturnValue.NoSuchService);
  402. }
  403. public static void Run(string[] _args)
  404. {
  405. if (_args.Length > 0)
  406. {
  407. var d = new ServiceDescriptor();
  408. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  409. Win32Service s = svc.Select(d.Id);
  410. var args = new List<string>(Array.AsReadOnly(_args));
  411. if (args[0] == "/redirect")
  412. {
  413. // Redirect output
  414. // One might ask why we support this when the caller
  415. // can redirect the output easily. The answer is for supporting UAC.
  416. // On UAC-enabled Windows such as Vista, SCM operation requires
  417. // elevated privileges, thus winsw.exe needs to be launched
  418. // accordingly. This in turn limits what the caller can do,
  419. // and among other things it makes it difficult for the caller
  420. // to read stdout/stderr. Thus redirection becomes handy.
  421. var f = new FileStream(args[1], FileMode.Create);
  422. var w = new StreamWriter(f);
  423. w.AutoFlush = true;
  424. Console.SetOut(w);
  425. Console.SetError(w);
  426. var handle = f.Handle;
  427. Kernel32.SetStdHandle(-11, handle); // set stdout
  428. Kernel32.SetStdHandle(-12, handle); // set stder
  429. args = args.GetRange(2, args.Count - 2);
  430. }
  431. args[0] = args[0].ToLower();
  432. if (args[0] == "install")
  433. {
  434. string username=null, password=null;
  435. if (args.Count > 1 && args[1] == "/p")
  436. {
  437. // we expected username/password on stdin
  438. Console.Write("Username: ");
  439. username = Console.ReadLine();
  440. Console.Write("Password: ");
  441. password = ReadPassword();
  442. }
  443. else
  444. {
  445. if (d.HasServiceAccount())
  446. {
  447. username = d.ServiceAccountUser;
  448. password = d.ServiceAccountPassword;
  449. }
  450. }
  451. svc.Create (
  452. d.Id,
  453. d.Caption,
  454. "\"" + d.ExecutablePath + "\"",
  455. WMI.ServiceType.OwnProcess,
  456. ErrorControl.UserNotified,
  457. StartMode.Automatic,
  458. d.Interactive,
  459. username,
  460. password,
  461. d.ServiceDependencies);
  462. // update the description
  463. /* Somehow this doesn't work, even though it doesn't report an error
  464. Win32Service s = svc.Select(d.Id);
  465. s.Description = d.Description;
  466. s.Commit();
  467. */
  468. // so using a classic method to set the description. Ugly.
  469. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  470. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  471. var actions = d.FailureActions;
  472. if (actions.Count > 0)
  473. {// set the failure actions
  474. using (ServiceManager scm = new ServiceManager())
  475. {
  476. using (Service sc = scm.Open(d.Id))
  477. {
  478. sc.ChangeConfig(d.ResetFailureAfter, actions);
  479. }
  480. }
  481. }
  482. }
  483. if (args[0] == "uninstall")
  484. {
  485. if (s == null)
  486. return; // there's no such service, so consider it already uninstalled
  487. try
  488. {
  489. s.Delete();
  490. }
  491. catch (WmiException e)
  492. {
  493. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  494. return; // it's already uninstalled, so consider it a success
  495. throw e;
  496. }
  497. }
  498. if (args[0] == "start")
  499. {
  500. if (s == null) ThrowNoSuchService();
  501. s.StartService();
  502. }
  503. if (args[0] == "stop")
  504. {
  505. if (s == null) ThrowNoSuchService();
  506. s.StopService();
  507. }
  508. if (args[0] == "restart")
  509. {
  510. if (s == null)
  511. ThrowNoSuchService();
  512. if(s.Started)
  513. s.StopService();
  514. while (s.Started)
  515. {
  516. Thread.Sleep(1000);
  517. s = svc.Select(d.Id);
  518. }
  519. s.StartService();
  520. }
  521. if (args[0] == "restart!")
  522. {
  523. // run restart from another process group. see README.md for why this is useful.
  524. STARTUPINFO si = new STARTUPINFO();
  525. PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
  526. 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);
  527. if (!result)
  528. {
  529. throw new Exception("Failed to invoke restart: "+Marshal.GetLastWin32Error());
  530. }
  531. }
  532. if (args[0] == "status")
  533. {
  534. if (s == null)
  535. Console.WriteLine("NonExistent");
  536. else if (s.Started)
  537. Console.WriteLine("Started");
  538. else
  539. Console.WriteLine("Stopped");
  540. }
  541. if (args[0] == "test")
  542. {
  543. WrapperService wsvc = new WrapperService();
  544. wsvc.OnStart(args.ToArray());
  545. Thread.Sleep(1000);
  546. wsvc.OnStop();
  547. }
  548. return;
  549. }
  550. ServiceBase.Run(new WrapperService());
  551. }
  552. private static string ReadPassword()
  553. {
  554. StringBuilder buf = new StringBuilder();
  555. ConsoleKeyInfo key;
  556. while (true)
  557. {
  558. key = Console.ReadKey(true);
  559. if (key.Key == ConsoleKey.Enter)
  560. {
  561. return buf.ToString();
  562. }
  563. else if (key.Key == ConsoleKey.Backspace)
  564. {
  565. buf.Remove(buf.Length - 1, 1);
  566. Console.Write("\b \b");
  567. }
  568. else
  569. {
  570. Console.Write('*');
  571. buf.Append(key.KeyChar);
  572. }
  573. }
  574. }
  575. }
  576. }