Main.cs 20 KB

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