Main.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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 WMI;
  11. using System.Xml;
  12. using System.Threading;
  13. using Microsoft.Win32;
  14. namespace winsw
  15. {
  16. public struct SERVICE_STATUS
  17. {
  18. public int serviceType;
  19. public int currentState;
  20. public int controlsAccepted;
  21. public int win32ExitCode;
  22. public int serviceSpecificExitCode;
  23. public int checkPoint;
  24. public int waitHint;
  25. }
  26. public enum State
  27. {
  28. SERVICE_STOPPED = 0x00000001,
  29. SERVICE_START_PENDING = 0x00000002,
  30. SERVICE_STOP_PENDING = 0x00000003,
  31. SERVICE_RUNNING = 0x00000004,
  32. SERVICE_CONTINUE_PENDING = 0x00000005,
  33. SERVICE_PAUSE_PENDING = 0x00000006,
  34. SERVICE_PAUSED = 0x00000007,
  35. }
  36. /// <summary>
  37. /// In-memory representation of the configuration file.
  38. /// </summary>
  39. public class ServiceDescriptor
  40. {
  41. private readonly XmlDocument dom = new XmlDocument();
  42. /// <summary>
  43. /// Where did we find the configuration file?
  44. ///
  45. /// This string is "c:\abc\def\ghi" when the configuration XML is "c:\abc\def\ghi.xml"
  46. /// </summary>
  47. public readonly string BasePath;
  48. /// <summary>
  49. /// The file name portion of the configuration file.
  50. ///
  51. /// In the above example, this would be "ghi".
  52. /// </summary>
  53. public readonly string BaseName;
  54. public static string ExecutablePath
  55. {
  56. get
  57. {
  58. // this returns the executable name as given by the calling process, so
  59. // it needs to be absolutized.
  60. string p = Environment.GetCommandLineArgs()[0];
  61. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p);
  62. }
  63. }
  64. public ServiceDescriptor()
  65. {
  66. // find co-located configuration xml. We search up to the ancestor directories to simplify debugging,
  67. // as well as trimming off ".vshost" suffix (which is used during debugging)
  68. string p = ExecutablePath;
  69. string baseName = Path.GetFileNameWithoutExtension(p);
  70. if (baseName.EndsWith(".vshost")) baseName = baseName.Substring(0, baseName.Length - 7);
  71. while (true)
  72. {
  73. p = Path.GetDirectoryName(p);
  74. if (File.Exists(Path.Combine(p, baseName + ".xml")))
  75. break;
  76. }
  77. // register the base directory as environment variable so that future expansions can refer to this.
  78. Environment.SetEnvironmentVariable("BASE", p);
  79. BaseName = baseName;
  80. BasePath = Path.Combine(p, BaseName);
  81. dom.Load(BasePath+".xml");
  82. }
  83. private string SingleElement(string tagName)
  84. {
  85. var n = dom.SelectSingleNode("//" + tagName);
  86. if (n == null) throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  87. return Environment.ExpandEnvironmentVariables(n.InnerText);
  88. }
  89. /// <summary>
  90. /// Path to the executable.
  91. /// </summary>
  92. public string Executable
  93. {
  94. get
  95. {
  96. return SingleElement("executable");
  97. }
  98. }
  99. /// <summary>
  100. /// Optionally specify a different Path to an executable to shutdown the service.
  101. /// </summary>
  102. public string StopExecutable
  103. {
  104. get
  105. {
  106. return AppendTags("stopexecutable");
  107. }
  108. }
  109. /// <summary>
  110. /// Arguments or multiple optional argument elements which overrule the arguments element.
  111. /// </summary>
  112. public string Arguments
  113. {
  114. get
  115. {
  116. string arguments = AppendTags("argument");
  117. if (arguments == null)
  118. {
  119. var tagName = "arguments";
  120. var argumentsNode = dom.SelectSingleNode("//" + tagName);
  121. if (argumentsNode == null)
  122. {
  123. if (AppendTags("startargument") == null)
  124. {
  125. throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  126. }
  127. else
  128. {
  129. return "";
  130. }
  131. }
  132. return Environment.ExpandEnvironmentVariables(argumentsNode.InnerText);
  133. }
  134. else
  135. {
  136. return arguments;
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Multiple optional startargument elements.
  142. /// </summary>
  143. public string Startarguments
  144. {
  145. get
  146. {
  147. return AppendTags("startargument");
  148. }
  149. }
  150. /// <summary>
  151. /// Multiple optional stopargument elements.
  152. /// </summary>
  153. public string Stoparguments
  154. {
  155. get
  156. {
  157. return AppendTags("stopargument");
  158. }
  159. }
  160. /// <summary>
  161. /// Combines the contents of all the elements of the given name,
  162. /// or return null if no element exists.
  163. /// </summary>
  164. private string AppendTags(string tagName)
  165. {
  166. XmlNode argumentNode = dom.SelectSingleNode("//" + tagName);
  167. if (argumentNode == null)
  168. {
  169. return null;
  170. }
  171. else
  172. {
  173. string arguments = "";
  174. foreach (XmlNode argument in dom.SelectNodes("//" + tagName))
  175. {
  176. arguments += " " + argument.InnerText;
  177. }
  178. return Environment.ExpandEnvironmentVariables(arguments);
  179. }
  180. }
  181. /// <summary>
  182. /// LogDirectory is the service wrapper executable directory or the optionally specified logpath element.
  183. /// </summary>
  184. public string LogDirectory
  185. {
  186. get
  187. {
  188. XmlNode loggingNode = dom.SelectSingleNode("//logpath");
  189. if (loggingNode != null)
  190. {
  191. return loggingNode.InnerText;
  192. }
  193. else
  194. {
  195. return Path.GetDirectoryName(ExecutablePath);
  196. }
  197. }
  198. }
  199. /// <summary>
  200. /// Logmode to 'reset', 'roll' once or 'append' [default] the out.log and err.log files.
  201. /// </summary>
  202. public string Logmode
  203. {
  204. get
  205. {
  206. XmlNode logmodeNode = dom.SelectSingleNode("//logmode");
  207. if (logmodeNode == null)
  208. {
  209. return "append";
  210. }
  211. else
  212. {
  213. return logmodeNode.InnerText;
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// Optionally specified depend services that must start before this service starts.
  219. /// </summary>
  220. public string[] ServiceDependencies
  221. {
  222. get
  223. {
  224. System.Collections.ArrayList serviceDependencies = new System.Collections.ArrayList();
  225. foreach (XmlNode depend in dom.SelectNodes("//depend"))
  226. {
  227. serviceDependencies.Add(depend.InnerText);
  228. }
  229. return (string[])serviceDependencies.ToArray(typeof(string));
  230. }
  231. }
  232. public string Id
  233. {
  234. get
  235. {
  236. return SingleElement("id");
  237. }
  238. }
  239. public string Caption
  240. {
  241. get
  242. {
  243. return SingleElement("name");
  244. }
  245. }
  246. public string Description
  247. {
  248. get
  249. {
  250. return SingleElement("description");
  251. }
  252. }
  253. /// <summary>
  254. /// True if the service can interact with the desktop.
  255. /// </summary>
  256. public bool Interactive
  257. {
  258. get
  259. {
  260. return dom.SelectSingleNode("//interactive") != null;
  261. }
  262. }
  263. /// <summary>
  264. /// Environment variable overrides
  265. /// </summary>
  266. public Dictionary<string, string> EnvironmentVariables
  267. {
  268. get
  269. {
  270. Dictionary<string, string> map = new Dictionary<string, string>();
  271. foreach (XmlNode n in dom.SelectNodes("//env"))
  272. {
  273. string key = n.Attributes["name"].Value;
  274. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  275. map[key] = value;
  276. Environment.SetEnvironmentVariable(key, value);
  277. }
  278. return map;
  279. }
  280. }
  281. }
  282. public class WrapperService : ServiceBase
  283. {
  284. [DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
  285. private static extern bool SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus);
  286. private SERVICE_STATUS wrapperServiceStatus;
  287. private Process process = new Process();
  288. private ServiceDescriptor descriptor;
  289. private Dictionary<string, string> envs;
  290. /// <summary>
  291. /// Indicates to the watch dog thread that we are going to terminate the process,
  292. /// so don't try to kill us when the child exits.
  293. /// </summary>
  294. private bool orderlyShutdown;
  295. private bool systemShuttingdown;
  296. public WrapperService()
  297. {
  298. this.descriptor = new ServiceDescriptor();
  299. this.ServiceName = descriptor.Id;
  300. this.CanShutdown = true;
  301. this.CanStop = true;
  302. this.CanPauseAndContinue = false;
  303. this.AutoLog = true;
  304. this.systemShuttingdown = false;
  305. }
  306. /// <summary>
  307. /// Copy stuff from StreamReader to StreamWriter
  308. /// </summary>
  309. private void CopyStream(StreamReader i, StreamWriter o)
  310. {
  311. char[] buf = new char[1024];
  312. while (true)
  313. {
  314. int sz = i.Read(buf, 0, buf.Length);
  315. if (sz == 0) break;
  316. o.Write(buf, 0, sz);
  317. o.Flush();
  318. }
  319. i.Close();
  320. o.Close();
  321. }
  322. /// <summary>
  323. /// Process the file copy instructions, so that we can replace files that are always in use while
  324. /// the service runs.
  325. /// </summary>
  326. private void HandleFileCopies()
  327. {
  328. var file = descriptor.BasePath + ".copies";
  329. if (!File.Exists(file))
  330. return; // nothing to handle
  331. try
  332. {
  333. using (var tr = new StreamReader(file,Encoding.UTF8))
  334. {
  335. string line;
  336. while ((line = tr.ReadLine()) != null)
  337. {
  338. LogEvent("Handling copy: " + line);
  339. string[] tokens = line.Split('>');
  340. if (tokens.Length > 2)
  341. {
  342. LogEvent("Too many delimiters in " + line);
  343. continue;
  344. }
  345. CopyFile(tokens[0], tokens[1]);
  346. }
  347. }
  348. }
  349. finally
  350. {
  351. File.Delete(file);
  352. }
  353. }
  354. private void CopyFile(string sourceFileName, string destFileName)
  355. {
  356. try
  357. {
  358. File.Delete(destFileName);
  359. File.Move(sourceFileName, destFileName);
  360. }
  361. catch (IOException e)
  362. {
  363. LogEvent("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  364. }
  365. }
  366. /// <summary>
  367. /// Handle the creation of the logfiles based on the optional logmode setting.
  368. /// </summary>
  369. private void HandleLogfiles()
  370. {
  371. string logDirectory = descriptor.LogDirectory;
  372. if (!Directory.Exists(logDirectory))
  373. {
  374. Directory.CreateDirectory(logDirectory);
  375. }
  376. string baseName = descriptor.BaseName;
  377. string errorLogfilename = Path.Combine(logDirectory, baseName + ".err.log");
  378. string outputLogfilename = Path.Combine(logDirectory, baseName + ".out.log");
  379. System.IO.FileMode fileMode = FileMode.Append;
  380. if (descriptor.Logmode == "reset")
  381. {
  382. fileMode = FileMode.Create;
  383. }
  384. else if (descriptor.Logmode == "roll")
  385. {
  386. CopyFile(outputLogfilename, outputLogfilename + ".old");
  387. CopyFile(errorLogfilename, errorLogfilename + ".old");
  388. }
  389. new Thread(delegate() { CopyStream(process.StandardOutput, new StreamWriter(new FileStream(outputLogfilename, fileMode))); }).Start();
  390. new Thread(delegate() { CopyStream(process.StandardError, new StreamWriter(new FileStream(errorLogfilename, fileMode))); }).Start();
  391. }
  392. private void LogEvent(String message)
  393. {
  394. if (systemShuttingdown)
  395. {
  396. /* NOP - cannot call EventLog because of shutdown. */
  397. }
  398. else
  399. {
  400. EventLog.WriteEntry(message);
  401. }
  402. }
  403. private void LogEvent(String message, EventLogEntryType type)
  404. {
  405. if (systemShuttingdown)
  406. {
  407. /* NOP - cannot call EventLog because of shutdown. */
  408. }
  409. else
  410. {
  411. EventLog.WriteEntry(message, type);
  412. }
  413. }
  414. private void WriteEvent(String message, Exception exception)
  415. {
  416. WriteEvent(message + "\nMessage:" + exception.Message + "\nStacktrace:" + exception.StackTrace);
  417. }
  418. private void WriteEvent(String message)
  419. {
  420. string logfilename = Path.Combine(descriptor.LogDirectory, descriptor.BaseName + ".wrapper.log");
  421. StreamWriter log = new StreamWriter(logfilename, true);
  422. log.WriteLine(message);
  423. log.Flush();
  424. log.Close();
  425. }
  426. protected override void OnStart(string[] args)
  427. {
  428. envs = descriptor.EnvironmentVariables;
  429. foreach (string key in envs.Keys)
  430. {
  431. LogEvent("envar " + key + '=' + envs[key]);
  432. }
  433. HandleFileCopies();
  434. string startarguments = descriptor.Startarguments;
  435. if (startarguments == null)
  436. {
  437. startarguments = descriptor.Arguments;
  438. }
  439. else
  440. {
  441. startarguments += " " + descriptor.Arguments;
  442. }
  443. LogEvent("Starting " + descriptor.Executable + ' ' + startarguments);
  444. StartProcess(process, startarguments, descriptor.Executable);
  445. // send stdout and stderr to its respective output file.
  446. HandleLogfiles();
  447. process.StandardInput.Close(); // nothing for you to read!
  448. }
  449. protected override void OnShutdown()
  450. {
  451. try
  452. {
  453. this.systemShuttingdown = true;
  454. StopIt();
  455. }
  456. catch (Exception ex)
  457. {
  458. WriteEvent("Shutdown exception", ex);
  459. }
  460. }
  461. protected override void OnStop()
  462. {
  463. try
  464. {
  465. StopIt();
  466. }
  467. catch (Exception ex)
  468. {
  469. WriteEvent("Stop exception", ex);
  470. }
  471. }
  472. private void StopIt()
  473. {
  474. string stoparguments = descriptor.Stoparguments;
  475. LogEvent("Stopping " + descriptor.Id);
  476. orderlyShutdown = true;
  477. if (stoparguments == null)
  478. {
  479. try
  480. {
  481. process.Kill();
  482. }
  483. catch (InvalidOperationException)
  484. {
  485. // already terminated
  486. }
  487. }
  488. else
  489. {
  490. stoparguments += " " + descriptor.Arguments;
  491. Process stopProcess = new Process();
  492. String executable = descriptor.StopExecutable;
  493. if (executable == null)
  494. {
  495. executable = descriptor.Executable;
  496. }
  497. StartProcess(stopProcess, stoparguments, executable);
  498. WaitForProcessToExit(process);
  499. WaitForProcessToExit(stopProcess);
  500. Console.Beep();
  501. }
  502. }
  503. private void WaitForProcessToExit(Process process)
  504. {
  505. SignalShutdownPending();
  506. try
  507. {
  508. while (process.WaitForExit(1000))
  509. {
  510. SignalShutdownPending();
  511. }
  512. }
  513. catch (InvalidOperationException ex)
  514. {
  515. WriteEvent("already terminated", ex);
  516. // already terminated
  517. }
  518. SignalShutdownComplete();
  519. }
  520. private void SignalShutdownPending()
  521. {
  522. IntPtr handle = this.ServiceHandle;
  523. wrapperServiceStatus.checkPoint++;
  524. wrapperServiceStatus.waitHint = 10000;
  525. wrapperServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
  526. SetServiceStatus(handle, ref wrapperServiceStatus);
  527. }
  528. private void SignalShutdownComplete()
  529. {
  530. IntPtr handle = this.ServiceHandle;
  531. wrapperServiceStatus.checkPoint++;
  532. wrapperServiceStatus.currentState = (int)State.SERVICE_STOPPED;
  533. SetServiceStatus(handle, ref wrapperServiceStatus);
  534. }
  535. private void StartProcess(Process process, string arguments, String executable)
  536. {
  537. var ps = process.StartInfo;
  538. ps.FileName = executable;
  539. ps.Arguments = arguments;
  540. ps.CreateNoWindow = false;
  541. ps.UseShellExecute = false;
  542. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  543. ps.RedirectStandardOutput = true;
  544. ps.RedirectStandardError = true;
  545. foreach (string key in envs.Keys)
  546. System.Environment.SetEnvironmentVariable(key, envs[key]);
  547. // 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)
  548. process.Start();
  549. // monitor the completion of the process
  550. new Thread(delegate()
  551. {
  552. string msg = process.Id + " - " + process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  553. process.WaitForExit();
  554. try
  555. {
  556. if (orderlyShutdown)
  557. {
  558. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Information);
  559. }
  560. else
  561. {
  562. LogEvent("Child process [" + msg + "] terminated with " + process.ExitCode, EventLogEntryType.Warning);
  563. Environment.Exit(process.ExitCode);
  564. }
  565. }
  566. catch (InvalidOperationException ioe)
  567. {
  568. LogEvent("WaitForExit " + ioe.Message);
  569. }
  570. try
  571. {
  572. process.Dispose();
  573. }
  574. catch (InvalidOperationException ioe)
  575. {
  576. LogEvent("Dispose " + ioe.Message);
  577. }
  578. }).Start();
  579. }
  580. public static int Main(string[] args)
  581. {
  582. try
  583. {
  584. Run(args);
  585. return 0;
  586. }
  587. catch (WmiException e)
  588. {
  589. Console.Error.WriteLine(e);
  590. return (int)e.ErrorCode;
  591. }
  592. catch (Exception e)
  593. {
  594. Console.Error.WriteLine(e);
  595. return -1;
  596. }
  597. }
  598. private static void ThrowNoSuchService()
  599. {
  600. throw new WmiException(ReturnValue.NoSuchService);
  601. }
  602. public static void Run(string[] args)
  603. {
  604. if (args.Length > 0)
  605. {
  606. var d = new ServiceDescriptor();
  607. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  608. Win32Service s = svc.Select(d.Id);
  609. args[0] = args[0].ToLower();
  610. if (args[0] == "install")
  611. {
  612. svc.Create(
  613. d.Id,
  614. d.Caption,
  615. ServiceDescriptor.ExecutablePath,
  616. WMI.ServiceType.OwnProcess,
  617. ErrorControl.UserNotified,
  618. StartMode.Automatic,
  619. d.Interactive,
  620. d.ServiceDependencies);
  621. // update the description
  622. /* Somehow this doesn't work, even though it doesn't report an error
  623. Win32Service s = svc.Select(d.Id);
  624. s.Description = d.Description;
  625. s.Commit();
  626. */
  627. // so using a classic method to set the description. Ugly.
  628. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  629. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  630. }
  631. if (args[0] == "uninstall")
  632. {
  633. if (s == null)
  634. return; // there's no such service, so consider it already uninstalled
  635. try
  636. {
  637. s.Delete();
  638. }
  639. catch (WmiException e)
  640. {
  641. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  642. return; // it's already uninstalled, so consider it a success
  643. throw e;
  644. }
  645. }
  646. if (args[0] == "start")
  647. {
  648. if (s == null) ThrowNoSuchService();
  649. s.StartService();
  650. }
  651. if (args[0] == "stop")
  652. {
  653. if (s == null) ThrowNoSuchService();
  654. s.StopService();
  655. }
  656. if (args[0] == "restart")
  657. {
  658. if (s == null)
  659. ThrowNoSuchService();
  660. if(s.Started)
  661. s.StopService();
  662. while (s.Started)
  663. {
  664. Thread.Sleep(1000);
  665. s = svc.Select(d.Id);
  666. }
  667. s.StartService();
  668. }
  669. if (args[0] == "status")
  670. {
  671. if (s == null)
  672. Console.WriteLine("NonExistent");
  673. else if (s.Started)
  674. Console.WriteLine("Started");
  675. else
  676. Console.WriteLine("Stopped");
  677. }
  678. if (args[0] == "test")
  679. {
  680. WrapperService wsvc = new WrapperService();
  681. wsvc.OnStart(args);
  682. Thread.Sleep(1000);
  683. wsvc.OnStop();
  684. }
  685. return;
  686. }
  687. ServiceBase.Run(new WrapperService());
  688. }
  689. }
  690. }