Main.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. /// </summary>
  24. public readonly string BasePath;
  25. public static string ExecutablePath
  26. {
  27. get
  28. {
  29. // this returns the executable name as given by the calling process, so
  30. // it needs to be absolutized.
  31. string p = Environment.GetCommandLineArgs()[0];
  32. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p);
  33. }
  34. }
  35. public ServiceDescriptor()
  36. {
  37. // find co-located configuration xml. We search up to the ancestor directories to simplify debugging,
  38. // as well as trimming off ".vshost" suffix (which is used during debugging)
  39. string p = ExecutablePath;
  40. string baseName = Path.GetFileNameWithoutExtension(p);
  41. if (baseName.EndsWith(".vshost")) baseName = baseName.Substring(0, baseName.Length - 7);
  42. while (true)
  43. {
  44. p = Path.GetDirectoryName(p);
  45. if (File.Exists(Path.Combine(p, baseName + ".xml")))
  46. break;
  47. }
  48. // register the base directory as environment variable so that future expansions can refer to this.
  49. Environment.SetEnvironmentVariable("BASE", p);
  50. BasePath = Path.Combine(p, baseName);
  51. dom.Load(BasePath+".xml");
  52. }
  53. private string SingleElement(string tagName)
  54. {
  55. var n = dom.SelectSingleNode("//" + tagName);
  56. if (n == null) throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  57. return Environment.ExpandEnvironmentVariables(n.InnerText);
  58. }
  59. /// <summary>
  60. /// Path to the executable.
  61. /// </summary>
  62. public string Executable
  63. {
  64. get
  65. {
  66. return SingleElement("executable");
  67. }
  68. }
  69. /// <summary>
  70. /// Arguments or multiple optional argument elements which overrule the arguments element.
  71. /// </summary>
  72. public string Arguments
  73. {
  74. get
  75. {
  76. XmlNode argumentNode = dom.SelectSingleNode("//argument");
  77. if (argumentNode == null)
  78. {
  79. return SingleElement("arguments");
  80. }
  81. else
  82. {
  83. string arguments = "";
  84. foreach (XmlNode argument in dom.SelectNodes("//argument"))
  85. {
  86. arguments += " " + argument.InnerText;
  87. }
  88. return Environment.ExpandEnvironmentVariables(arguments);
  89. }
  90. }
  91. }
  92. /// <summary>
  93. /// Logmode to 'reset', 'roll' once or 'append' [default] the out.log and err.log files.
  94. /// </summary>
  95. public string Logmode
  96. {
  97. get
  98. {
  99. XmlNode logmodeNode = dom.SelectSingleNode("//logmode");
  100. if (logmodeNode == null)
  101. {
  102. return "append";
  103. }
  104. else
  105. {
  106. return logmodeNode.InnerText;
  107. }
  108. }
  109. }
  110. public string Id
  111. {
  112. get
  113. {
  114. return SingleElement("id");
  115. }
  116. }
  117. public string Caption
  118. {
  119. get
  120. {
  121. return SingleElement("name");
  122. }
  123. }
  124. public string Description
  125. {
  126. get
  127. {
  128. return SingleElement("description");
  129. }
  130. }
  131. /// <summary>
  132. /// True if the service can interact with the desktop.
  133. /// </summary>
  134. public bool Interactive
  135. {
  136. get
  137. {
  138. return dom.SelectSingleNode("//interactive") != null;
  139. }
  140. }
  141. /// <summary>
  142. /// Environment variable overrides
  143. /// </summary>
  144. public Dictionary<string, string> EnvironmentVariables
  145. {
  146. get
  147. {
  148. Dictionary<string, string> map = new Dictionary<string, string>();
  149. foreach (XmlNode n in dom.SelectNodes("//env"))
  150. {
  151. string key = n.Attributes["name"].Value;
  152. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  153. map[key] = value;
  154. Environment.SetEnvironmentVariable(key, value);
  155. }
  156. return map;
  157. }
  158. }
  159. }
  160. public class WrapperService : ServiceBase
  161. {
  162. private Process process = new Process();
  163. private ServiceDescriptor descriptor;
  164. /// <summary>
  165. /// Indicates to the watch dog thread that we are going to terminate the process,
  166. /// so don't try to kill us when the child exits.
  167. /// </summary>
  168. private bool orderlyShutdown;
  169. public WrapperService()
  170. {
  171. this.descriptor = new ServiceDescriptor();
  172. this.ServiceName = descriptor.Id;
  173. this.CanStop = true;
  174. this.CanPauseAndContinue = false;
  175. this.AutoLog = true;
  176. }
  177. /// <summary>
  178. /// Copy stuff from StreamReader to StreamWriter
  179. /// </summary>
  180. private void CopyStream(StreamReader i, StreamWriter o)
  181. {
  182. char[] buf = new char[1024];
  183. while (true)
  184. {
  185. int sz = i.Read(buf, 0, buf.Length);
  186. if (sz == 0) break;
  187. o.Write(buf, 0, sz);
  188. o.Flush();
  189. }
  190. i.Close();
  191. o.Close();
  192. }
  193. /// <summary>
  194. /// Process the file copy instructions, so that we can replace files that are always in use while
  195. /// the service runs.
  196. /// </summary>
  197. private void HandleFileCopies()
  198. {
  199. var file = descriptor.BasePath + ".copies";
  200. if (!File.Exists(file))
  201. return; // nothing to handle
  202. try
  203. {
  204. using (var tr = new StreamReader(file,Encoding.UTF8))
  205. {
  206. string line;
  207. while ((line = tr.ReadLine()) != null)
  208. {
  209. EventLog.WriteEntry("Handling copy: " + line);
  210. string[] tokens = line.Split('>');
  211. if (tokens.Length > 2)
  212. {
  213. EventLog.WriteEntry("Too many delimiters in " + line);
  214. continue;
  215. }
  216. CopyFile(tokens[0], tokens[1]);
  217. }
  218. }
  219. }
  220. finally
  221. {
  222. File.Delete(file);
  223. }
  224. }
  225. private void CopyFile(string sourceFileName, string destFileName)
  226. {
  227. try
  228. {
  229. File.Delete(destFileName);
  230. File.Move(sourceFileName, destFileName);
  231. }
  232. catch (IOException e)
  233. {
  234. EventLog.WriteEntry("Failed to copy :" + sourceFileName + " to " + destFileName + " because " + e.Message);
  235. }
  236. }
  237. /// <summary>
  238. /// Handle the creation of the logfiles based on the optional logmode setting.
  239. /// </summary>
  240. private void HandleLogfiles()
  241. {
  242. string baseName = descriptor.BasePath;
  243. string errorLogfilename = baseName + ".err.log";
  244. string outputLogfilename = baseName + ".out.log";
  245. System.IO.FileMode fileMode = FileMode.Append;
  246. if (descriptor.Logmode == "reset")
  247. {
  248. fileMode = FileMode.Create;
  249. }
  250. else if (descriptor.Logmode == "roll")
  251. {
  252. CopyFile(outputLogfilename, outputLogfilename + ".old");
  253. CopyFile(errorLogfilename, errorLogfilename + ".old");
  254. }
  255. new Thread(delegate() { CopyStream(process.StandardOutput, new StreamWriter(new FileStream(outputLogfilename, fileMode))); }).Start();
  256. new Thread(delegate() { CopyStream(process.StandardError, new StreamWriter(new FileStream(errorLogfilename, fileMode))); }).Start();
  257. }
  258. protected override void OnStart(string[] args)
  259. {
  260. var envs = descriptor.EnvironmentVariables;
  261. foreach (string key in envs.Keys)
  262. {
  263. EventLog.WriteEntry("envar " + key + '=' + envs[key]);
  264. }
  265. HandleFileCopies();
  266. EventLog.WriteEntry("Starting "+descriptor.Executable+' '+descriptor.Arguments);
  267. string baseName = descriptor.BasePath;
  268. var ps = process.StartInfo;
  269. ps.FileName = descriptor.Executable;
  270. ps.Arguments = descriptor.Arguments;
  271. ps.CreateNoWindow = false;
  272. ps.UseShellExecute = false;
  273. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  274. ps.RedirectStandardOutput = true;
  275. ps.RedirectStandardError = true;
  276. foreach (string key in envs.Keys)
  277. ps.EnvironmentVariables[key] = envs[key];
  278. process.Start();
  279. // send stdout and stderr to its respective output file.
  280. HandleLogfiles();
  281. // monitor the completion of the process
  282. new Thread(delegate()
  283. {
  284. process.WaitForExit();
  285. if (!orderlyShutdown)
  286. {
  287. EventLog.WriteEntry("Child process terminated with " + process.ExitCode,EventLogEntryType.Warning);
  288. Environment.Exit(process.ExitCode);
  289. }
  290. }).Start();
  291. process.StandardInput.Close(); // nothing for you to read!
  292. }
  293. protected override void OnStop()
  294. {
  295. try
  296. {
  297. EventLog.WriteEntry("Stopping "+descriptor.Id);
  298. orderlyShutdown = true;
  299. process.Kill();
  300. }
  301. catch (InvalidOperationException)
  302. {
  303. // already terminated
  304. }
  305. process.Dispose();
  306. }
  307. public static int Main(string[] args)
  308. {
  309. try
  310. {
  311. Run(args);
  312. return 0;
  313. }
  314. catch (WmiException e)
  315. {
  316. Console.Error.WriteLine(e);
  317. return (int)e.ErrorCode;
  318. }
  319. catch (Exception e)
  320. {
  321. Console.Error.WriteLine(e);
  322. return -1;
  323. }
  324. }
  325. private static void ThrowNoSuchService()
  326. {
  327. throw new WmiException(ReturnValue.NoSuchService);
  328. }
  329. public static void Run(string[] args)
  330. {
  331. if (args.Length > 0)
  332. {
  333. var d = new ServiceDescriptor();
  334. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  335. Win32Service s = svc.Select(d.Id);
  336. args[0] = args[0].ToLower();
  337. if (args[0] == "install")
  338. {
  339. svc.Create(
  340. d.Id,
  341. d.Caption,
  342. ServiceDescriptor.ExecutablePath,
  343. WMI.ServiceType.OwnProcess,
  344. ErrorControl.UserNotified,
  345. StartMode.Automatic,
  346. d.Interactive);
  347. // update the description
  348. /* Somehow this doesn't work, even though it doesn't report an error
  349. Win32Service s = svc.Select(d.Id);
  350. s.Description = d.Description;
  351. s.Commit();
  352. */
  353. // so using a classic method to set the description. Ugly.
  354. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  355. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  356. }
  357. if (args[0] == "uninstall")
  358. {
  359. if (s == null)
  360. return; // there's no such service, so consider it already uninstalled
  361. try
  362. {
  363. s.Delete();
  364. }
  365. catch (WmiException e)
  366. {
  367. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  368. return; // it's already uninstalled, so consider it a success
  369. throw e;
  370. }
  371. }
  372. if (args[0] == "start")
  373. {
  374. if (s == null) ThrowNoSuchService();
  375. s.StartService();
  376. }
  377. if (args[0] == "stop")
  378. {
  379. if (s == null) ThrowNoSuchService();
  380. s.StopService();
  381. }
  382. if (args[0] == "restart")
  383. {
  384. if (s == null) ThrowNoSuchService();
  385. if(s.Started)
  386. s.StopService();
  387. s.StartService();
  388. }
  389. if (args[0] == "status")
  390. {
  391. if (s == null)
  392. Console.WriteLine("NonExistent");
  393. else if (s.Started)
  394. Console.WriteLine("Started");
  395. else
  396. Console.WriteLine("Stopped");
  397. }
  398. if (args[0] == "test")
  399. {
  400. WrapperService wsvc = new WrapperService();
  401. wsvc.OnStart(args);
  402. Thread.Sleep(1000);
  403. wsvc.OnStop();
  404. }
  405. return;
  406. }
  407. ServiceBase.Run(new WrapperService());
  408. }
  409. }
  410. }