Main.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. namespace winsw
  16. {
  17. public struct SERVICE_STATUS
  18. {
  19. public int serviceType;
  20. public int currentState;
  21. public int controlsAccepted;
  22. public int win32ExitCode;
  23. public int serviceSpecificExitCode;
  24. public int checkPoint;
  25. public int waitHint;
  26. }
  27. public enum State
  28. {
  29. SERVICE_STOPPED = 0x00000001,
  30. SERVICE_START_PENDING = 0x00000002,
  31. SERVICE_STOP_PENDING = 0x00000003,
  32. SERVICE_RUNNING = 0x00000004,
  33. SERVICE_CONTINUE_PENDING = 0x00000005,
  34. SERVICE_PAUSE_PENDING = 0x00000006,
  35. SERVICE_PAUSED = 0x00000007,
  36. }
  37. public class WrapperService : ServiceBase
  38. {
  39. [DllImport("ADVAPI32.DLL")]
  40. private static extern bool SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
  41. [DllImport("Kernel32.dll", SetLastError = true)]
  42. public static extern int SetStdHandle(int device, IntPtr handle);
  43. private SERVICE_STATUS wrapperServiceStatus;
  44. private Process process = new Process();
  45. private ServiceDescriptor descriptor;
  46. private Dictionary<string, string> envs;
  47. /// <summary>
  48. /// Indicates to the watch dog thread that we are going to terminate the process,
  49. /// so don't try to kill us when the child exits.
  50. /// </summary>
  51. private bool orderlyShutdown;
  52. private bool systemShuttingdown;
  53. public WrapperService()
  54. {
  55. this.descriptor = new ServiceDescriptor();
  56. this.ServiceName = descriptor.Id;
  57. this.CanShutdown = true;
  58. this.CanStop = true;
  59. this.CanPauseAndContinue = false;
  60. this.AutoLog = true;
  61. this.systemShuttingdown = false;
  62. }
  63. /// <summary>
  64. /// Copy stuff from StreamReader to StreamWriter
  65. /// </summary>
  66. private void CopyStream(Stream i, Stream o)
  67. {
  68. byte[] buf = new byte[1024];
  69. while (true)
  70. {
  71. int sz = i.Read(buf, 0, buf.Length);
  72. if (sz == 0) break;
  73. o.Write(buf, 0, sz);
  74. o.Flush();
  75. }
  76. i.Close();
  77. o.Close();
  78. }
  79. /// <summary>
  80. /// Works like the CopyStream method but does a log rotation.
  81. /// </summary>
  82. private void CopyStreamWithRotation(Stream data, string baseName, string ext)
  83. {
  84. int THRESHOLD = 10 * 1024 * 1024; // rotate every 10MB. should be made configurable.
  85. byte[] buf = new byte[1024];
  86. FileStream w = new FileStream(baseName + ext, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
  87. long sz = new FileInfo(baseName + ext).Length;
  88. while (true)
  89. {
  90. int len = data.Read(buf, 0, buf.Length);
  91. if (len == 0) break; // EOF
  92. if (sz + len < THRESHOLD)
  93. {// typical case. write the whole thing into the current file
  94. w.Write(buf, 0, len);
  95. sz += len;
  96. }
  97. else
  98. {
  99. // rotate at the line boundary
  100. int s = 0;
  101. for (int i = 0; i < len; i++)
  102. {
  103. if (buf[i] != 0x0A) continue;
  104. if (sz + i < THRESHOLD) continue;
  105. // at the line boundary and exceeded the rotation unit.
  106. // time to rotate.
  107. w.Write(buf, s, i + 1);
  108. w.Close();
  109. s = i + 1;
  110. try
  111. {
  112. for (int j = 8; j >= 0; j--)
  113. {
  114. string dst = baseName + "." + (j + 1) + ext;
  115. string src = baseName + "." + (j + 0) + ext;
  116. if (File.Exists(dst))
  117. File.Delete(dst);
  118. if (File.Exists(src))
  119. File.Move(src, dst);
  120. }
  121. File.Move(baseName + ext, baseName + ".0" + ext);
  122. }
  123. catch (IOException e)
  124. {
  125. LogEvent("Failed to rotate log: " + e.Message);
  126. }
  127. // even if the log rotation fails, create a new one, or else
  128. // we'll infinitely try to rotate.
  129. w = new FileStream(baseName + ext, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
  130. sz = new FileInfo(baseName + ext).Length;
  131. }
  132. }
  133. w.Flush();
  134. }
  135. data.Close();
  136. w.Close();
  137. }
  138. /// <summary>
  139. /// Process the file copy instructions, so that we can replace files that are always in use while
  140. /// the service runs.
  141. /// </summary>
  142. private void HandleFileCopies()
  143. {
  144. var file = descriptor.BasePath + ".copies";
  145. if (!File.Exists(file))
  146. return; // nothing to handle
  147. try
  148. {
  149. using (var tr = new StreamReader(file,Encoding.UTF8))
  150. {
  151. string line;
  152. while ((line = tr.ReadLine()) != null)
  153. {
  154. LogEvent("Handling copy: " + line);
  155. string[] tokens = line.Split('>');
  156. if (tokens.Length > 2)
  157. {
  158. LogEvent("Too many delimiters in " + line);
  159. continue;
  160. }
  161. CopyFile(tokens[0], tokens[1]);
  162. }
  163. }
  164. }
  165. finally
  166. {
  167. File.Delete(file);
  168. }
  169. }
  170. /// <summary>
  171. /// File replacement.
  172. /// </summary>
  173. private void CopyFile(string sourceFileName, string destFileName)
  174. {
  175. try
  176. {
  177. File.Delete(destFileName);
  178. File.Move(sourceFileName, destFileName);
  179. }
  180. catch (IOException e)
  181. {
  182. LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  183. }
  184. }
  185. /// <summary>
  186. /// Starts a thread that protects the execution with a try/catch block.
  187. /// It appears that in .NET, unhandled exception in any thread causes the app to terminate
  188. /// http://msdn.microsoft.com/en-us/library/ms228965.aspx
  189. /// </summary>
  190. private void StartThread(ThreadStart main)
  191. {
  192. new Thread(delegate() {
  193. try
  194. {
  195. main();
  196. }
  197. catch (Exception e)
  198. {
  199. WriteEvent("Thread failed unexpectedly",e);
  200. }
  201. }).Start();
  202. }
  203. /// <summary>
  204. /// Handle the creation of the logfiles based on the optional logmode setting.
  205. /// </summary>
  206. private void HandleLogfiles()
  207. {
  208. string logDirectory = descriptor.LogDirectory;
  209. if (!Directory.Exists(logDirectory))
  210. {
  211. Directory.CreateDirectory(logDirectory);
  212. }
  213. string baseName = descriptor.BaseName;
  214. string errorLogfilename = Path.Combine(logDirectory, baseName + ".err.log");
  215. string outputLogfilename = Path.Combine(logDirectory, baseName + ".out.log");
  216. if (descriptor.Logmode == "rotate")
  217. {
  218. string logName = Path.Combine(logDirectory, baseName);
  219. StartThread(delegate() { CopyStreamWithRotation(process.StandardOutput.BaseStream, logName, ".out.log"); });
  220. StartThread(delegate() { CopyStreamWithRotation(process.StandardError.BaseStream, logName, ".err.log"); });
  221. return;
  222. }
  223. FileMode fileMode = FileMode.Append;
  224. if (descriptor.Logmode == "reset")
  225. {
  226. fileMode = FileMode.Create;
  227. }
  228. else if (descriptor.Logmode == "roll")
  229. {
  230. CopyFile(outputLogfilename, outputLogfilename + ".old");
  231. CopyFile(errorLogfilename, errorLogfilename + ".old");
  232. }
  233. StartThread(delegate() { CopyStream(process.StandardOutput.BaseStream, new FileStream(outputLogfilename, fileMode, FileAccess.Write, FileShare.ReadWrite)); });
  234. StartThread(delegate() { CopyStream(process.StandardError.BaseStream, new FileStream(errorLogfilename, fileMode, FileAccess.Write, FileShare.ReadWrite)); });
  235. }
  236. private void LogEvent(String message)
  237. {
  238. if (systemShuttingdown)
  239. {
  240. /* NOP - cannot call EventLog because of shutdown. */
  241. }
  242. else
  243. {
  244. EventLog.WriteEntry(message);
  245. }
  246. }
  247. private void LogEvent(String message, EventLogEntryType type)
  248. {
  249. if (systemShuttingdown)
  250. {
  251. /* NOP - cannot call EventLog because of shutdown. */
  252. }
  253. else
  254. {
  255. EventLog.WriteEntry(message, type);
  256. }
  257. }
  258. private void WriteEvent(Exception exception)
  259. {
  260. WriteEvent(exception.Message + "\nStacktrace:" + exception.StackTrace);
  261. }
  262. private void WriteEvent(String message, Exception exception)
  263. {
  264. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  265. }
  266. private void WriteEvent(String message)
  267. {
  268. string logfilename = Path.Combine(descriptor.LogDirectory, descriptor.BaseName + ".wrapper.log");
  269. StreamWriter log = new StreamWriter(logfilename, true);
  270. log.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
  271. log.Flush();
  272. log.Close();
  273. }
  274. protected override void OnStart(string[] _)
  275. {
  276. envs = descriptor.EnvironmentVariables;
  277. foreach (string key in envs.Keys)
  278. {
  279. LogEvent("envar " + key + '=' + envs[key]);
  280. }
  281. HandleFileCopies();
  282. // handle downloads
  283. foreach (Download d in descriptor.Downloads)
  284. {
  285. LogEvent("Downloading: " + d.From+ " to "+d.To);
  286. try
  287. {
  288. d.Perform();
  289. }
  290. catch (Exception e)
  291. {
  292. LogEvent("Failed to download " + d.From + " to " + d.To + "\n" + e.Message);
  293. WriteEvent("Failed to download " + d.From +" to "+d.To, e);
  294. // but just keep going
  295. }
  296. }
  297. string startarguments = descriptor.Startarguments;
  298. if (startarguments == null)
  299. {
  300. startarguments = descriptor.Arguments;
  301. }
  302. else
  303. {
  304. startarguments += " " + descriptor.Arguments;
  305. }
  306. LogEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  307. WriteEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  308. StartProcess(process, startarguments, descriptor.Executable);
  309. // send stdout and stderr to its respective output file.
  310. HandleLogfiles();
  311. process.StandardInput.Close(); // nothing for you to read!
  312. }
  313. protected override void OnShutdown()
  314. {
  315. // WriteEvent("OnShutdown");
  316. try
  317. {
  318. this.systemShuttingdown = true;
  319. StopIt();
  320. }
  321. catch (Exception ex)
  322. {
  323. WriteEvent("Shutdown exception", ex);
  324. }
  325. }
  326. protected override void OnStop()
  327. {
  328. // WriteEvent("OnStop");
  329. try
  330. {
  331. StopIt();
  332. }
  333. catch (Exception ex)
  334. {
  335. WriteEvent("Stop exception", ex);
  336. }
  337. }
  338. private void StopIt()
  339. {
  340. string stoparguments = descriptor.Stoparguments;
  341. LogEvent("Stopping " + descriptor.Id);
  342. WriteEvent("Stopping " + descriptor.Id);
  343. orderlyShutdown = true;
  344. if (stoparguments == null)
  345. {
  346. try
  347. {
  348. WriteEvent("ProcessKill " + process.Id);
  349. process.Kill();
  350. }
  351. catch (InvalidOperationException)
  352. {
  353. // already terminated
  354. }
  355. }
  356. else
  357. {
  358. SignalShutdownPending();
  359. stoparguments += " " + descriptor.Arguments;
  360. Process stopProcess = new Process();
  361. String executable = descriptor.StopExecutable;
  362. if (executable == null)
  363. {
  364. executable = descriptor.Executable;
  365. }
  366. StartProcess(stopProcess, stoparguments, executable);
  367. WriteEvent("WaitForProcessToExit "+process.Id+"+"+stopProcess.Id);
  368. WaitForProcessToExit(process);
  369. WaitForProcessToExit(stopProcess);
  370. SignalShutdownComplete();
  371. }
  372. if (systemShuttingdown && descriptor.BeepOnShutdown)
  373. {
  374. Console.Beep();
  375. }
  376. WriteEvent("Finished " + descriptor.Id);
  377. }
  378. private void WaitForProcessToExit(Process process)
  379. {
  380. SignalShutdownPending();
  381. try
  382. {
  383. // WriteEvent("WaitForProcessToExit [start]");
  384. while (!process.WaitForExit(descriptor.SleepTime))
  385. {
  386. SignalShutdownPending();
  387. // WriteEvent("WaitForProcessToExit [repeat]");
  388. }
  389. }
  390. catch (InvalidOperationException)
  391. {
  392. // already terminated
  393. }
  394. // WriteEvent("WaitForProcessToExit [finished]");
  395. }
  396. private void SignalShutdownPending()
  397. {
  398. IntPtr handle = this.ServiceHandle;
  399. wrapperServiceStatus.checkPoint++;
  400. wrapperServiceStatus.waitHint = descriptor.WaitHint;
  401. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  402. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  403. SetServiceStatus(handle, ref wrapperServiceStatus);
  404. }
  405. private void SignalShutdownComplete()
  406. {
  407. IntPtr handle = this.ServiceHandle;
  408. wrapperServiceStatus.checkPoint++;
  409. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  410. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  411. SetServiceStatus(handle, ref wrapperServiceStatus);
  412. }
  413. private void StartProcess(Process process, string arguments, String executable)
  414. {
  415. var ps = process.StartInfo;
  416. ps.FileName = executable;
  417. ps.Arguments = arguments;
  418. ps.CreateNoWindow = false;
  419. ps.UseShellExecute = false;
  420. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  421. ps.RedirectStandardOutput = true;
  422. ps.RedirectStandardError = true;
  423. foreach (string key in envs.Keys)
  424. System.Environment.SetEnvironmentVariable(key, envs[key]);
  425. // 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)
  426. process.Start();
  427. WriteEvent("Started " + process.Id);
  428. // monitor the completion of the process
  429. StartThread(delegate()
  430. {
  431. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  432. process.WaitForExit();
  433. try
  434. {
  435. if (orderlyShutdown)
  436. {
  437. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  438. }
  439. else
  440. {
  441. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Warning);
  442. Environment.Exit(process.ExitCode);
  443. }
  444. }
  445. catch (InvalidOperationException ioe)
  446. {
  447. LogEvent("WaitForExit " + ioe.Message);
  448. }
  449. try
  450. {
  451. process.Dispose();
  452. }
  453. catch (InvalidOperationException ioe)
  454. {
  455. LogEvent("Dispose " + ioe.Message);
  456. }
  457. });
  458. }
  459. public static int Main(string[] args)
  460. {
  461. try
  462. {
  463. Run(args);
  464. return 0;
  465. }
  466. catch (WmiException e)
  467. {
  468. Console.Error.WriteLine(e);
  469. return (int)e.ErrorCode;
  470. }
  471. catch (Exception e)
  472. {
  473. Console.Error.WriteLine(e);
  474. return -1;
  475. }
  476. }
  477. private static void ThrowNoSuchService()
  478. {
  479. throw new WmiException(ReturnValue.NoSuchService);
  480. }
  481. public static void Run(string[] _args)
  482. {
  483. if (_args.Length > 0)
  484. {
  485. var d = new ServiceDescriptor();
  486. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  487. Win32Service s = svc.Select(d.Id);
  488. var args = new List<string>(Array.AsReadOnly(_args));
  489. if (args[0] == "/redirect")
  490. {
  491. // Redirect output
  492. // One might ask why we support this when the caller
  493. // can redirect the output easily. The answer is for supporting UAC.
  494. // On UAC-enabled Windows such as Vista, SCM operation requires
  495. // elevated privileges, thus winsw.exe needs to be launched
  496. // accordingly. This in turn limits what the caller can do,
  497. // and among other things it makes it difficult for the caller
  498. // to read stdout/stderr. Thus redirection becomes handy.
  499. var f = new FileStream(args[1], FileMode.Create);
  500. var w = new StreamWriter(f);
  501. w.AutoFlush = true;
  502. Console.SetOut(w);
  503. Console.SetError(w);
  504. var handle = f.Handle;
  505. SetStdHandle(-11, handle); // set stdout
  506. SetStdHandle(-12, handle); // set stder
  507. args = args.GetRange(2, args.Count - 2);
  508. }
  509. args[0] = args[0].ToLower();
  510. if (args[0] == "install")
  511. {
  512. svc.Create(
  513. d.Id,
  514. d.Caption,
  515. "\""+ServiceDescriptor.ExecutablePath+"\"",
  516. WMI.ServiceType.OwnProcess,
  517. ErrorControl.UserNotified,
  518. StartMode.Automatic,
  519. d.Interactive,
  520. d.ServiceDependencies);
  521. // update the description
  522. /* Somehow this doesn't work, even though it doesn't report an error
  523. Win32Service s = svc.Select(d.Id);
  524. s.Description = d.Description;
  525. s.Commit();
  526. */
  527. // so using a classic method to set the description. Ugly.
  528. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  529. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  530. }
  531. if (args[0] == "uninstall")
  532. {
  533. if (s == null)
  534. return; // there's no such service, so consider it already uninstalled
  535. try
  536. {
  537. s.Delete();
  538. }
  539. catch (WmiException e)
  540. {
  541. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  542. return; // it's already uninstalled, so consider it a success
  543. throw e;
  544. }
  545. }
  546. if (args[0] == "start")
  547. {
  548. if (s == null) ThrowNoSuchService();
  549. s.StartService();
  550. }
  551. if (args[0] == "stop")
  552. {
  553. if (s == null) ThrowNoSuchService();
  554. s.StopService();
  555. }
  556. if (args[0] == "restart")
  557. {
  558. if (s == null)
  559. ThrowNoSuchService();
  560. if(s.Started)
  561. s.StopService();
  562. while (s.Started)
  563. {
  564. Thread.Sleep(1000);
  565. s = svc.Select(d.Id);
  566. }
  567. s.StartService();
  568. }
  569. if (args[0] == "status")
  570. {
  571. if (s == null)
  572. Console.WriteLine("NonExistent");
  573. else if (s.Started)
  574. Console.WriteLine("Started");
  575. else
  576. Console.WriteLine("Stopped");
  577. }
  578. if (args[0] == "test")
  579. {
  580. WrapperService wsvc = new WrapperService();
  581. wsvc.OnStart(args.ToArray());
  582. Thread.Sleep(1000);
  583. wsvc.OnStop();
  584. }
  585. return;
  586. }
  587. ServiceBase.Run(new WrapperService());
  588. }
  589. }
  590. }