Main.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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(Environment.CurrentDirectory, 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
  71. /// </summary>
  72. public string Arguments
  73. {
  74. get
  75. {
  76. return SingleElement("arguments");
  77. }
  78. }
  79. public string Id
  80. {
  81. get
  82. {
  83. return SingleElement("id");
  84. }
  85. }
  86. public string Caption
  87. {
  88. get
  89. {
  90. return SingleElement("name");
  91. }
  92. }
  93. public string Description
  94. {
  95. get
  96. {
  97. return SingleElement("description");
  98. }
  99. }
  100. /// <summary>
  101. /// True if the service can interact with the desktop.
  102. /// </summary>
  103. public bool Interactive
  104. {
  105. get
  106. {
  107. return dom.SelectSingleNode("//interactive") != null;
  108. }
  109. }
  110. /// <summary>
  111. /// Environment variable overrides
  112. /// </summary>
  113. public Dictionary<string, string> EnvironmentVariables
  114. {
  115. get
  116. {
  117. Dictionary<string, string> map = new Dictionary<string, string>();
  118. foreach (XmlNode n in dom.SelectNodes("//env"))
  119. {
  120. map[n.Attributes["name"].Value] = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  121. }
  122. return map;
  123. }
  124. }
  125. }
  126. public class WrapperService : ServiceBase
  127. {
  128. private Process process = new Process();
  129. private ServiceDescriptor descriptor;
  130. /// <summary>
  131. /// Indicates to the watch dog thread that we are going to terminate the process,
  132. /// so don't try to kill us when the child exits.
  133. /// </summary>
  134. private bool orderlyShutdown;
  135. public WrapperService()
  136. {
  137. this.descriptor = new ServiceDescriptor();
  138. this.ServiceName = descriptor.Id;
  139. this.CanStop = true;
  140. this.CanPauseAndContinue = false;
  141. this.AutoLog = true;
  142. }
  143. /// <summary>
  144. /// Copy stuff from StreamReader to StreamWriter
  145. /// </summary>
  146. private void CopyStream(StreamReader i, StreamWriter o)
  147. {
  148. char[] buf = new char[1024];
  149. while (true)
  150. {
  151. int sz = i.Read(buf, 0, buf.Length);
  152. if (sz == 0) break;
  153. o.Write(buf, 0, sz);
  154. o.Flush();
  155. }
  156. i.Close();
  157. o.Close();
  158. }
  159. protected override void OnStart(string[] args)
  160. {
  161. EventLog.WriteEntry("Starting "+descriptor.Executable+' '+descriptor.Arguments);
  162. string baseName = descriptor.BasePath;
  163. var ps = process.StartInfo;
  164. ps.FileName = descriptor.Executable;
  165. ps.Arguments = descriptor.Arguments;
  166. ps.CreateNoWindow = false;
  167. ps.UseShellExecute = false;
  168. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  169. ps.RedirectStandardOutput = true;
  170. ps.RedirectStandardError = true;
  171. var envs = descriptor.EnvironmentVariables;
  172. foreach (string key in envs.Keys)
  173. ps.EnvironmentVariables[key] = envs[key];
  174. process.Start();
  175. // send stdout and stderr to its respective output file.
  176. new Thread(delegate() { CopyStream(process.StandardOutput, new StreamWriter(new FileStream(baseName + ".out.log", FileMode.Append))); }).Start();
  177. new Thread(delegate() { CopyStream(process.StandardError, new StreamWriter(new FileStream(baseName + ".err.log", FileMode.Append))); }).Start();
  178. // monitor the completion of the process
  179. new Thread(delegate()
  180. {
  181. process.WaitForExit();
  182. if (!orderlyShutdown)
  183. {
  184. EventLog.WriteEntry("Child process terminated with " + process.ExitCode,EventLogEntryType.Warning);
  185. Environment.Exit(process.ExitCode);
  186. }
  187. }).Start();
  188. process.StandardInput.Close(); // nothing for you to read!
  189. }
  190. protected override void OnStop()
  191. {
  192. try
  193. {
  194. EventLog.WriteEntry("Stopping "+descriptor.Id);
  195. orderlyShutdown = true;
  196. process.Kill();
  197. }
  198. catch (InvalidOperationException)
  199. {
  200. // already terminated
  201. }
  202. process.Dispose();
  203. }
  204. public static int Main(string[] args)
  205. {
  206. try
  207. {
  208. Run(args);
  209. return 0;
  210. }
  211. catch (WmiException e)
  212. {
  213. Console.Error.WriteLine(e);
  214. return (int)e.ErrorCode;
  215. }
  216. catch (Exception e)
  217. {
  218. Console.Error.WriteLine(e);
  219. return -1;
  220. }
  221. }
  222. private static void ThrowNoSuchService()
  223. {
  224. throw new WmiException(ReturnValue.NoSuchService);
  225. }
  226. public static void Run(string[] args)
  227. {
  228. if (args.Length > 0)
  229. {
  230. var d = new ServiceDescriptor();
  231. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  232. Win32Service s = svc.Select(d.Id);
  233. args[0] = args[0].ToLower();
  234. if (args[0] == "install")
  235. {
  236. svc.Create(
  237. d.Id,
  238. d.Caption,
  239. ServiceDescriptor.ExecutablePath,
  240. WMI.ServiceType.OwnProcess,
  241. ErrorControl.UserNotified,
  242. StartMode.Automatic,
  243. d.Interactive);
  244. // update the description
  245. /* Somehow this doesn't work, even though it doesn't report an error
  246. Win32Service s = svc.Select(d.Id);
  247. s.Description = d.Description;
  248. s.Commit();
  249. */
  250. // so using a classic method to set the description. Ugly.
  251. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  252. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  253. }
  254. if (args[0] == "uninstall")
  255. {
  256. if (s == null)
  257. return; // there's no such service, so consider it already uninstalled
  258. try
  259. {
  260. s.Delete();
  261. }
  262. catch (WmiException e)
  263. {
  264. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  265. return; // it's already uninstalled, so consider it a success
  266. throw e;
  267. }
  268. }
  269. if (args[0] == "start")
  270. {
  271. if (s == null) ThrowNoSuchService();
  272. s.StartService();
  273. }
  274. if (args[0] == "stop")
  275. {
  276. if (s == null) ThrowNoSuchService();
  277. s.StopService();
  278. }
  279. if (args[0] == "status")
  280. {
  281. if (s == null)
  282. Console.WriteLine("NonExistent");
  283. else if (s.Started)
  284. Console.WriteLine("Started");
  285. else
  286. Console.WriteLine("Stopped");
  287. }
  288. if (args[0] == "test")
  289. {
  290. WrapperService wsvc = new WrapperService();
  291. wsvc.OnStart(args);
  292. Thread.Sleep(1000);
  293. wsvc.OnStop();
  294. }
  295. return;
  296. }
  297. ServiceBase.Run(new WrapperService());
  298. }
  299. }
  300. }