Main.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. /// <summary>
  160. /// Process the file copy instructions, so that we can replace files that are always in use while
  161. /// the service runs.
  162. /// </summary>
  163. private void HandleFileCopies()
  164. {
  165. var file = descriptor.BasePath + ".copies";
  166. if (!File.Exists(file))
  167. return; // nothing to handle
  168. try
  169. {
  170. using (var tr = new StreamReader(file,Encoding.UTF8))
  171. {
  172. string line;
  173. while ((line = tr.ReadLine()) != null)
  174. {
  175. try
  176. {
  177. EventLog.WriteEntry("Handling copy: " + line);
  178. string[] tokens = line.Split('>');
  179. if (tokens.Length > 2)
  180. {
  181. EventLog.WriteEntry("Too many delimiters in " + line);
  182. continue;
  183. }
  184. File.Delete(tokens[1]);
  185. File.Move(tokens[0], tokens[1]);
  186. }
  187. catch(IOException e)
  188. {
  189. EventLog.WriteEntry("Failed to copy :"+line+" because "+e.Message);
  190. }
  191. }
  192. }
  193. }
  194. finally
  195. {
  196. File.Delete(file);
  197. }
  198. }
  199. protected override void OnStart(string[] args)
  200. {
  201. HandleFileCopies();
  202. EventLog.WriteEntry("Starting "+descriptor.Executable+' '+descriptor.Arguments);
  203. string baseName = descriptor.BasePath;
  204. var ps = process.StartInfo;
  205. ps.FileName = descriptor.Executable;
  206. ps.Arguments = descriptor.Arguments;
  207. ps.CreateNoWindow = false;
  208. ps.UseShellExecute = false;
  209. ps.RedirectStandardInput = true; // this creates a pipe for stdin to the new process, instead of having it inherit our stdin.
  210. ps.RedirectStandardOutput = true;
  211. ps.RedirectStandardError = true;
  212. var envs = descriptor.EnvironmentVariables;
  213. foreach (string key in envs.Keys)
  214. ps.EnvironmentVariables[key] = envs[key];
  215. process.Start();
  216. // send stdout and stderr to its respective output file.
  217. new Thread(delegate() { CopyStream(process.StandardOutput, new StreamWriter(new FileStream(baseName + ".out.log", FileMode.Append))); }).Start();
  218. new Thread(delegate() { CopyStream(process.StandardError, new StreamWriter(new FileStream(baseName + ".err.log", FileMode.Append))); }).Start();
  219. // monitor the completion of the process
  220. new Thread(delegate()
  221. {
  222. process.WaitForExit();
  223. if (!orderlyShutdown)
  224. {
  225. EventLog.WriteEntry("Child process terminated with " + process.ExitCode,EventLogEntryType.Warning);
  226. Environment.Exit(process.ExitCode);
  227. }
  228. }).Start();
  229. process.StandardInput.Close(); // nothing for you to read!
  230. }
  231. protected override void OnStop()
  232. {
  233. try
  234. {
  235. EventLog.WriteEntry("Stopping "+descriptor.Id);
  236. orderlyShutdown = true;
  237. process.Kill();
  238. }
  239. catch (InvalidOperationException)
  240. {
  241. // already terminated
  242. }
  243. process.Dispose();
  244. }
  245. public static int Main(string[] args)
  246. {
  247. try
  248. {
  249. Run(args);
  250. return 0;
  251. }
  252. catch (WmiException e)
  253. {
  254. Console.Error.WriteLine(e);
  255. return (int)e.ErrorCode;
  256. }
  257. catch (Exception e)
  258. {
  259. Console.Error.WriteLine(e);
  260. return -1;
  261. }
  262. }
  263. private static void ThrowNoSuchService()
  264. {
  265. throw new WmiException(ReturnValue.NoSuchService);
  266. }
  267. public static void Run(string[] args)
  268. {
  269. if (args.Length > 0)
  270. {
  271. var d = new ServiceDescriptor();
  272. Win32Services svc = new WmiRoot().GetCollection<Win32Services>();
  273. Win32Service s = svc.Select(d.Id);
  274. args[0] = args[0].ToLower();
  275. if (args[0] == "install")
  276. {
  277. svc.Create(
  278. d.Id,
  279. d.Caption,
  280. ServiceDescriptor.ExecutablePath,
  281. WMI.ServiceType.OwnProcess,
  282. ErrorControl.UserNotified,
  283. StartMode.Automatic,
  284. d.Interactive);
  285. // update the description
  286. /* Somehow this doesn't work, even though it doesn't report an error
  287. Win32Service s = svc.Select(d.Id);
  288. s.Description = d.Description;
  289. s.Commit();
  290. */
  291. // so using a classic method to set the description. Ugly.
  292. Registry.LocalMachine.OpenSubKey("System").OpenSubKey("CurrentControlSet").OpenSubKey("Services")
  293. .OpenSubKey(d.Id, true).SetValue("Description", d.Description);
  294. }
  295. if (args[0] == "uninstall")
  296. {
  297. if (s == null)
  298. return; // there's no such service, so consider it already uninstalled
  299. try
  300. {
  301. s.Delete();
  302. }
  303. catch (WmiException e)
  304. {
  305. if (e.ErrorCode == ReturnValue.ServiceMarkedForDeletion)
  306. return; // it's already uninstalled, so consider it a success
  307. throw e;
  308. }
  309. }
  310. if (args[0] == "start")
  311. {
  312. if (s == null) ThrowNoSuchService();
  313. s.StartService();
  314. }
  315. if (args[0] == "stop")
  316. {
  317. if (s == null) ThrowNoSuchService();
  318. s.StopService();
  319. }
  320. if (args[0] == "restart")
  321. {
  322. if (s == null) ThrowNoSuchService();
  323. if(s.Started)
  324. s.StopService();
  325. s.StartService();
  326. }
  327. if (args[0] == "status")
  328. {
  329. if (s == null)
  330. Console.WriteLine("NonExistent");
  331. else if (s.Started)
  332. Console.WriteLine("Started");
  333. else
  334. Console.WriteLine("Stopped");
  335. }
  336. if (args[0] == "test")
  337. {
  338. WrapperService wsvc = new WrapperService();
  339. wsvc.OnStart(args);
  340. Thread.Sleep(1000);
  341. wsvc.OnStop();
  342. }
  343. return;
  344. }
  345. ServiceBase.Run(new WrapperService());
  346. }
  347. }
  348. }