Main.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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 searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
  281. foreach (var mo in searcher.Get())
  282. {
  283. StopProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
  284. }
  285. var proc = Process.GetProcessById(pid);
  286. WriteEvent("Send SIGINT " + pid);
  287. bool successful = SigIntHelper.SendSIGINTToProcess(proc,descriptor.StopTimeout);
  288. if (successful)
  289. {
  290. WriteEvent("SIGINT to" + pid + " successful");
  291. }
  292. else
  293. {
  294. try
  295. {
  296. WriteEvent("SIGINT to " + pid + " failed - Killing as fallback");
  297. proc.Kill();
  298. }
  299. catch (ArgumentException)
  300. {
  301. // Process already exited.
  302. }
  303. }
  304. }
  305. private void WaitForProcessToExit(Process process)
  306. {
  307. SignalShutdownPending();
  308. try
  309. {
  310. // WriteEvent("WaitForProcessToExit [start]");
  311. while (!process.WaitForExit(descriptor.SleepTime.Milliseconds))
  312. {
  313. SignalShutdownPending();
  314. // WriteEvent("WaitForProcessToExit [repeat]");
  315. }
  316. }
  317. catch (InvalidOperationException)
  318. {
  319. // already terminated
  320. }
  321. // WriteEvent("WaitForProcessToExit [finished]");
  322. }
  323. private void SignalShutdownPending()
  324. {
  325. IntPtr handle = this.ServiceHandle;
  326. wrapperServiceStatus.checkPoint++;
  327. wrapperServiceStatus.waitHint = descriptor.WaitHint.Milliseconds;
  328. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  329. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  330. Advapi32.SetServiceStatus(handle, ref wrapperServiceStatus);
  331. }
  332. private void SignalShutdownComplete()
  333. {
  334. IntPtr handle = this.ServiceHandle;
  335. wrapperServiceStatus.checkPoint++;
  336. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  337. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  338. Advapi32.SetServiceStatus(handle, ref wrapperServiceStatus);
  339. }
  340. private void StartProcess(Process process, string arguments, String executable)
  341. {
  342. var ps = process.StartInfo;
  343. ps.FileName = executable;
  344. ps.Arguments = arguments;
  345. ps.WorkingDirectory = descriptor.WorkingDirectory;
  346. ps.CreateNoWindow = false;
  347. ps.UseShellExecute = false;
  348. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  349. ps.RedirectStandardOutput = true;
  350. ps.RedirectStandardError = true;
  351. foreach (string key in envs.Keys)
  352. System.Environment.SetEnvironmentVariable(key, envs[key]);
  353. // 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)
  354. process.Start();
  355. WriteEvent("Started " + process.Id);
  356. var priority = descriptor.Priority;
  357. if (priority != ProcessPriorityClass.Normal)
  358. process.PriorityClass = priority;
  359. // monitor the completion of the process
  360. StartThread(delegate()
  361. {
  362. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  363. process.WaitForExit();
  364. try
  365. {
  366. if (orderlyShutdown)
  367. {
  368. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  369. }
  370. else
  371. {
  372. LogEvent("Child process [" + msg + "] finished with " + process.ExitCode, EventLogEntryType.Warning);
  373. // if we finished orderly, report that to SCM.
  374. // by not reporting unclean shutdown, we let Windows SCM to decide if it wants to
  375. // restart the service automatically
  376. if (process.ExitCode == 0)
  377. SignalShutdownComplete();
  378. Environment.Exit(process.ExitCode);
  379. }
  380. }
  381. catch (InvalidOperationException ioe)
  382. {
  383. LogEvent("WaitForExit " + ioe.Message);
  384. }
  385. try
  386. {
  387. process.Dispose();
  388. }
  389. catch (InvalidOperationException ioe)
  390. {
  391. LogEvent("Dispose " + ioe.Message);
  392. }
  393. });
  394. }
  395. public static int Main(string[] args)
  396. {
  397. try
  398. {
  399. Run(args);
  400. return 0;
  401. }
  402. catch (WmiException e)
  403. {
  404. Console.Error.WriteLine(e);
  405. return (int)e.ErrorCode;
  406. }
  407. catch (Exception e)
  408. {
  409. Console.Error.WriteLine(e);
  410. return -1;
  411. }
  412. }
  413. private static void ThrowNoSuchService()
  414. {
  415. throw new WmiException(ReturnValue.NoSuchService);
  416. }
  417. public static void Run(string[] _args)
  418. {
  419. if (_args.Length > 0)
  420. {
  421. var d = new ServiceDescriptor();
  422. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  423. Win32Service s = svc.Select(d.Id);
  424. var args = new List<string>(Array.AsReadOnly(_args));
  425. if (args[0] == "/redirect")
  426. {
  427. // Redirect output
  428. // One might ask why we support this when the caller
  429. // can redirect the output easily. The answer is for supporting UAC.
  430. // On UAC-enabled Windows such as Vista, SCM operation requires
  431. // elevated privileges, thus winsw.exe needs to be launched
  432. // accordingly. This in turn limits what the caller can do,
  433. // and among other things it makes it difficult for the caller
  434. // to read stdout/stderr. Thus redirection becomes handy.
  435. var f = new FileStream(args[1], FileMode.Create);
  436. var w = new StreamWriter(f);
  437. w.AutoFlush = true;
  438. Console.SetOut(w);
  439. Console.SetError(w);
  440. var handle = f.Handle;
  441. Kernel32.SetStdHandle(-11, handle); // set stdout
  442. Kernel32.SetStdHandle(-12, handle); // set stder
  443. args = args.GetRange(2, args.Count - 2);
  444. }
  445. args[0] = args[0].ToLower();
  446. if (args[0] == "install")
  447. {
  448. string username=null, password=null;
  449. if (args.Count > 1 && args[1] == "/p")
  450. {
  451. // we expected username/password on stdin
  452. Console.Write("Username: ");
  453. username = Console.ReadLine();
  454. Console.Write("Password: ");
  455. password = ReadPassword();
  456. }
  457. else
  458. {
  459. if (d.HasServiceAccount())
  460. {
  461. username = d.ServiceAccountUser;
  462. password = d.ServiceAccountPassword;
  463. }
  464. }
  465. svc.Create (
  466. d.Id,
  467. d.Caption,
  468. "\"" + d.ExecutablePath + "\"",
  469. WMI.ServiceType.OwnProcess,
  470. ErrorControl.UserNotified,
  471. StartMode.Automatic,
  472. d.Interactive,
  473. username,
  474. password,
  475. d.ServiceDependencies);
  476. // update the description
  477. /* Somehow this doesn't work, even though it doesn't report an error
  478. Win32Service s = svc.Select(d.Id);
  479. s.Description = d.Description;
  480. s.Commit();
  481. */
  482. // so using a classic method to set the description. Ugly.
  483. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  484. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  485. var actions = d.FailureActions;
  486. if (actions.Count > 0)
  487. {// set the failure actions
  488. using (ServiceManager scm = new ServiceManager())
  489. {
  490. using (Service sc = scm.Open(d.Id))
  491. {
  492. sc.ChangeConfig(d.ResetFailureAfter, actions);
  493. }
  494. }
  495. }
  496. }
  497. if (args[0] == "uninstall")
  498. {
  499. if (s == null)
  500. return; // there's no such service, so consider it already uninstalled
  501. try
  502. {
  503. s.Delete();
  504. }
  505. catch (WmiException e)
  506. {
  507. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  508. return; // it's already uninstalled, so consider it a success
  509. throw e;
  510. }
  511. }
  512. if (args[0] == "start")
  513. {
  514. if (s == null) ThrowNoSuchService();
  515. s.StartService();
  516. }
  517. if (args[0] == "stop")
  518. {
  519. if (s == null) ThrowNoSuchService();
  520. s.StopService();
  521. }
  522. if (args[0] == "restart")
  523. {
  524. if (s == null)
  525. ThrowNoSuchService();
  526. if(s.Started)
  527. s.StopService();
  528. while (s.Started)
  529. {
  530. Thread.Sleep(1000);
  531. s = svc.Select(d.Id);
  532. }
  533. s.StartService();
  534. }
  535. if (args[0] == "restart!")
  536. {
  537. // run restart from another process group. see README.md for why this is useful.
  538. STARTUPINFO si = new STARTUPINFO();
  539. PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
  540. 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);
  541. if (!result)
  542. {
  543. throw new Exception("Failed to invoke restart: "+Marshal.GetLastWin32Error());
  544. }
  545. }
  546. if (args[0] == "status")
  547. {
  548. if (s == null)
  549. Console.WriteLine("NonExistent");
  550. else if (s.Started)
  551. Console.WriteLine("Started");
  552. else
  553. Console.WriteLine("Stopped");
  554. }
  555. if (args[0] == "test")
  556. {
  557. WrapperService wsvc = new WrapperService();
  558. wsvc.OnStart(args.ToArray());
  559. Thread.Sleep(1000);
  560. wsvc.OnStop();
  561. }
  562. return;
  563. }
  564. ServiceBase.Run(new WrapperService());
  565. }
  566. private static string ReadPassword()
  567. {
  568. StringBuilder buf = new StringBuilder();
  569. ConsoleKeyInfo key;
  570. while (true)
  571. {
  572. key = Console.ReadKey(true);
  573. if (key.Key == ConsoleKey.Enter)
  574. {
  575. return buf.ToString();
  576. }
  577. else if (key.Key == ConsoleKey.Backspace)
  578. {
  579. buf.Remove(buf.Length - 1, 1);
  580. Console.Write("\b \b");
  581. }
  582. else
  583. {
  584. Console.Write('*');
  585. buf.Append(key.KeyChar);
  586. }
  587. }
  588. }
  589. }
  590. }