Main.cs 20 KB

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