Main.cs 16 KB

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