Main.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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, EventLogger
  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. /// Process the file copy instructions, so that we can replace files that are always in use while
  65. /// the service runs.
  66. /// </summary>
  67. private void HandleFileCopies()
  68. {
  69. var file = descriptor.BasePath + ".copies";
  70. if (!File.Exists(file))
  71. return; // nothing to handle
  72. try
  73. {
  74. using (var tr = new StreamReader(file,Encoding.UTF8))
  75. {
  76. string line;
  77. while ((line = tr.ReadLine()) != null)
  78. {
  79. LogEvent("Handling copy: " + line);
  80. string[] tokens = line.Split('>');
  81. if (tokens.Length > 2)
  82. {
  83. LogEvent("Too many delimiters in " + line);
  84. continue;
  85. }
  86. CopyFile(tokens[0], tokens[1]);
  87. }
  88. }
  89. }
  90. finally
  91. {
  92. File.Delete(file);
  93. }
  94. }
  95. /// <summary>
  96. /// File replacement.
  97. /// </summary>
  98. private void CopyFile(string sourceFileName, string destFileName)
  99. {
  100. try
  101. {
  102. File.Delete(destFileName);
  103. File.Move(sourceFileName, destFileName);
  104. }
  105. catch (IOException e)
  106. {
  107. LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  108. }
  109. }
  110. /// <summary>
  111. /// Starts a thread that protects the execution with a try/catch block.
  112. /// It appears that in .NET, unhandled exception in any thread causes the app to terminate
  113. /// http://msdn.microsoft.com/en-us/library/ms228965.aspx
  114. /// </summary>
  115. private void StartThread(ThreadStart main)
  116. {
  117. new Thread(delegate() {
  118. try
  119. {
  120. main();
  121. }
  122. catch (Exception e)
  123. {
  124. WriteEvent("Thread failed unexpectedly",e);
  125. }
  126. }).Start();
  127. }
  128. /// <summary>
  129. /// Handle the creation of the logfiles based on the optional logmode setting.
  130. /// </summary>
  131. private void HandleLogfiles()
  132. {
  133. string logDirectory = descriptor.LogDirectory;
  134. if (!Directory.Exists(logDirectory))
  135. {
  136. Directory.CreateDirectory(logDirectory);
  137. }
  138. LogHandler logAppender = descriptor.LogHandler;
  139. logAppender.EventLogger = this;
  140. logAppender.log(process.StandardOutput.BaseStream, process.StandardError.BaseStream);
  141. }
  142. public void LogEvent(String message)
  143. {
  144. if (systemShuttingdown)
  145. {
  146. /* NOP - cannot call EventLog because of shutdown. */
  147. }
  148. else
  149. {
  150. EventLog.WriteEntry(message);
  151. }
  152. }
  153. public void LogEvent(String message, EventLogEntryType type)
  154. {
  155. if (systemShuttingdown)
  156. {
  157. /* NOP - cannot call EventLog because of shutdown. */
  158. }
  159. else
  160. {
  161. EventLog.WriteEntry(message, type);
  162. }
  163. }
  164. private void WriteEvent(Exception exception)
  165. {
  166. WriteEvent(exception.Message + "\nStacktrace:" + exception.StackTrace);
  167. }
  168. private void WriteEvent(String message, Exception exception)
  169. {
  170. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  171. }
  172. private void WriteEvent(String message)
  173. {
  174. string logfilename = Path.Combine(descriptor.LogDirectory, descriptor.BaseName + ".wrapper.log");
  175. StreamWriter log = new StreamWriter(logfilename, true);
  176. log.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + message);
  177. log.Flush();
  178. log.Close();
  179. }
  180. protected override void OnStart(string[] _)
  181. {
  182. envs = descriptor.EnvironmentVariables;
  183. foreach (string key in envs.Keys)
  184. {
  185. LogEvent("envar " + key + '=' + envs[key]);
  186. }
  187. HandleFileCopies();
  188. // handle downloads
  189. foreach (Download d in descriptor.Downloads)
  190. {
  191. LogEvent("Downloading: " + d.From+ " to "+d.To);
  192. try
  193. {
  194. d.Perform();
  195. }
  196. catch (Exception e)
  197. {
  198. LogEvent("Failed to download " + d.From + " to " + d.To + "\n" + e.Message);
  199. WriteEvent("Failed to download " + d.From +" to "+d.To, e);
  200. // but just keep going
  201. }
  202. }
  203. string startarguments = descriptor.Startarguments;
  204. if (startarguments == null)
  205. {
  206. startarguments = descriptor.Arguments;
  207. }
  208. else
  209. {
  210. startarguments += " " + descriptor.Arguments;
  211. }
  212. LogEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  213. WriteEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  214. StartProcess(process, startarguments, descriptor.Executable);
  215. // send stdout and stderr to its respective output file.
  216. HandleLogfiles();
  217. process.StandardInput.Close(); // nothing for you to read!
  218. }
  219. protected override void OnShutdown()
  220. {
  221. // WriteEvent("OnShutdown");
  222. try
  223. {
  224. this.systemShuttingdown = true;
  225. StopIt();
  226. }
  227. catch (Exception ex)
  228. {
  229. WriteEvent("Shutdown exception", ex);
  230. }
  231. }
  232. protected override void OnStop()
  233. {
  234. // WriteEvent("OnStop");
  235. try
  236. {
  237. StopIt();
  238. }
  239. catch (Exception ex)
  240. {
  241. WriteEvent("Stop exception", ex);
  242. }
  243. }
  244. private void StopIt()
  245. {
  246. string stoparguments = descriptor.Stoparguments;
  247. LogEvent("Stopping " + descriptor.Id);
  248. WriteEvent("Stopping " + descriptor.Id);
  249. orderlyShutdown = true;
  250. if (stoparguments == null)
  251. {
  252. try
  253. {
  254. WriteEvent("ProcessKill " + process.Id);
  255. process.Kill();
  256. }
  257. catch (InvalidOperationException)
  258. {
  259. // already terminated
  260. }
  261. }
  262. else
  263. {
  264. SignalShutdownPending();
  265. stoparguments += " " + descriptor.Arguments;
  266. Process stopProcess = new Process();
  267. String executable = descriptor.StopExecutable;
  268. if (executable == null)
  269. {
  270. executable = descriptor.Executable;
  271. }
  272. StartProcess(stopProcess, stoparguments, executable);
  273. WriteEvent("WaitForProcessToExit "+process.Id+"+"+stopProcess.Id);
  274. WaitForProcessToExit(process);
  275. WaitForProcessToExit(stopProcess);
  276. SignalShutdownComplete();
  277. }
  278. if (systemShuttingdown && descriptor.BeepOnShutdown)
  279. {
  280. Console.Beep();
  281. }
  282. WriteEvent("Finished " + descriptor.Id);
  283. }
  284. private void WaitForProcessToExit(Process process)
  285. {
  286. SignalShutdownPending();
  287. try
  288. {
  289. // WriteEvent("WaitForProcessToExit [start]");
  290. while (!process.WaitForExit(descriptor.SleepTime))
  291. {
  292. SignalShutdownPending();
  293. // WriteEvent("WaitForProcessToExit [repeat]");
  294. }
  295. }
  296. catch (InvalidOperationException)
  297. {
  298. // already terminated
  299. }
  300. // WriteEvent("WaitForProcessToExit [finished]");
  301. }
  302. private void SignalShutdownPending()
  303. {
  304. IntPtr handle = this.ServiceHandle;
  305. wrapperServiceStatus.checkPoint++;
  306. wrapperServiceStatus.waitHint = descriptor.WaitHint;
  307. // WriteEvent("SignalShutdownPending " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  308. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  309. SetServiceStatus(handle, ref wrapperServiceStatus);
  310. }
  311. private void SignalShutdownComplete()
  312. {
  313. IntPtr handle = this.ServiceHandle;
  314. wrapperServiceStatus.checkPoint++;
  315. // WriteEvent("SignalShutdownComplete " + wrapperServiceStatus.checkPoint + ":" + wrapperServiceStatus.waitHint);
  316. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  317. SetServiceStatus(handle, ref wrapperServiceStatus);
  318. }
  319. private void StartProcess(Process process, string arguments, String executable)
  320. {
  321. var ps = process.StartInfo;
  322. ps.FileName = executable;
  323. ps.Arguments = arguments;
  324. ps.WorkingDirectory = descriptor.WorkingDirectory;
  325. ps.CreateNoWindow = false;
  326. ps.UseShellExecute = false;
  327. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  328. ps.RedirectStandardOutput = true;
  329. ps.RedirectStandardError = true;
  330. foreach (string key in envs.Keys)
  331. System.Environment.SetEnvironmentVariable(key, envs[key]);
  332. // 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)
  333. process.Start();
  334. WriteEvent("Started " + process.Id);
  335. // monitor the completion of the process
  336. StartThread(delegate()
  337. {
  338. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  339. process.WaitForExit();
  340. try
  341. {
  342. if (orderlyShutdown)
  343. {
  344. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  345. }
  346. else
  347. {
  348. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Warning);
  349. Environment.Exit(process.ExitCode);
  350. }
  351. }
  352. catch (InvalidOperationException ioe)
  353. {
  354. LogEvent("WaitForExit " + ioe.Message);
  355. }
  356. try
  357. {
  358. process.Dispose();
  359. }
  360. catch (InvalidOperationException ioe)
  361. {
  362. LogEvent("Dispose " + ioe.Message);
  363. }
  364. });
  365. }
  366. public static int _Main(string[] args)
  367. {
  368. try
  369. {
  370. Run(args);
  371. return 0;
  372. }
  373. catch (WmiException e)
  374. {
  375. Console.Error.WriteLine(e);
  376. return (int)e.ErrorCode;
  377. }
  378. catch (Exception e)
  379. {
  380. Console.Error.WriteLine(e);
  381. return -1;
  382. }
  383. }
  384. private static void ThrowNoSuchService()
  385. {
  386. throw new WmiException(ReturnValue.NoSuchService);
  387. }
  388. public static void Run(string[] _args)
  389. {
  390. if (_args.Length > 0)
  391. {
  392. var d = new ServiceDescriptor();
  393. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  394. Win32Service s = svc.Select(d.Id);
  395. var args = new List<string>(Array.AsReadOnly(_args));
  396. if (args[0] == "/redirect")
  397. {
  398. // Redirect output
  399. // One might ask why we support this when the caller
  400. // can redirect the output easily. The answer is for supporting UAC.
  401. // On UAC-enabled Windows such as Vista, SCM operation requires
  402. // elevated privileges, thus winsw.exe needs to be launched
  403. // accordingly. This in turn limits what the caller can do,
  404. // and among other things it makes it difficult for the caller
  405. // to read stdout/stderr. Thus redirection becomes handy.
  406. var f = new FileStream(args[1], FileMode.Create);
  407. var w = new StreamWriter(f);
  408. w.AutoFlush = true;
  409. Console.SetOut(w);
  410. Console.SetError(w);
  411. var handle = f.Handle;
  412. SetStdHandle(-11, handle); // set stdout
  413. SetStdHandle(-12, handle); // set stder
  414. args = args.GetRange(2, args.Count - 2);
  415. }
  416. args[0] = args[0].ToLower();
  417. if (args[0] == "install")
  418. {
  419. svc.Create(
  420. d.Id,
  421. d.Caption,
  422. "\""+ServiceDescriptor.ExecutablePath+"\"",
  423. WMI.ServiceType.OwnProcess,
  424. ErrorControl.UserNotified,
  425. StartMode.Automatic,
  426. d.Interactive,
  427. d.ServiceDependencies);
  428. // update the description
  429. /* Somehow this doesn't work, even though it doesn't report an error
  430. Win32Service s = svc.Select(d.Id);
  431. s.Description = d.Description;
  432. s.Commit();
  433. */
  434. // so using a classic method to set the description. Ugly.
  435. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  436. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  437. }
  438. if (args[0] == "uninstall")
  439. {
  440. if (s == null)
  441. return; // there's no such service, so consider it already uninstalled
  442. try
  443. {
  444. s.Delete();
  445. }
  446. catch (WmiException e)
  447. {
  448. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  449. return; // it's already uninstalled, so consider it a success
  450. throw e;
  451. }
  452. }
  453. if (args[0] == "start")
  454. {
  455. if (s == null) ThrowNoSuchService();
  456. s.StartService();
  457. }
  458. if (args[0] == "stop")
  459. {
  460. if (s == null) ThrowNoSuchService();
  461. s.StopService();
  462. }
  463. if (args[0] == "restart")
  464. {
  465. if (s == null)
  466. ThrowNoSuchService();
  467. if(s.Started)
  468. s.StopService();
  469. while (s.Started)
  470. {
  471. Thread.Sleep(1000);
  472. s = svc.Select(d.Id);
  473. }
  474. s.StartService();
  475. }
  476. if (args[0] == "status")
  477. {
  478. if (s == null)
  479. Console.WriteLine("NonExistent");
  480. else if (s.Started)
  481. Console.WriteLine("Started");
  482. else
  483. Console.WriteLine("Stopped");
  484. }
  485. if (args[0] == "autorestart")
  486. {// debug only. to be removed.
  487. using (Advapi32.ServiceManager scm = new Advapi32.ServiceManager())
  488. {
  489. using (Advapi32.Service sc = scm.Open(d.Id))
  490. {
  491. sc.ChangeConfig(TimeSpan.FromHours(48));
  492. }
  493. }
  494. }
  495. if (args[0] == "test")
  496. {
  497. WrapperService wsvc = new WrapperService();
  498. wsvc.OnStart(args.ToArray());
  499. Thread.Sleep(1000);
  500. wsvc.OnStop();
  501. }
  502. return;
  503. }
  504. ServiceBase.Run(new WrapperService());
  505. }
  506. }
  507. }