ServiceDescriptor.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.ServiceProcess;
  9. using System.Text;
  10. using System.IO;
  11. using System.Net;
  12. using WMI;
  13. using System.Xml;
  14. using System.Threading;
  15. using Microsoft.Win32;
  16. namespace winsw
  17. {
  18. /// <summary>
  19. /// In-memory representation of the configuration file.
  20. /// </summary>
  21. public class ServiceDescriptor
  22. {
  23. private readonly XmlDocument dom = new XmlDocument();
  24. /// <summary>
  25. /// Where did we find the configuration file?
  26. ///
  27. /// This string is "c:\abc\def\ghi" when the configuration XML is "c:\abc\def\ghi.xml"
  28. /// </summary>
  29. public readonly string BasePath;
  30. /// <summary>
  31. /// The file name portion of the configuration file.
  32. ///
  33. /// In the above example, this would be "ghi".
  34. /// </summary>
  35. public readonly string BaseName;
  36. public static string ExecutablePath
  37. {
  38. get
  39. {
  40. // this returns the executable name as given by the calling process, so
  41. // it needs to be absolutized.
  42. string p = Environment.GetCommandLineArgs()[0];
  43. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p);
  44. }
  45. }
  46. public ServiceDescriptor()
  47. {
  48. // find co-located configuration xml. We search up to the ancestor directories to simplify debugging,
  49. // as well as trimming off ".vshost" suffix (which is used during debugging)
  50. string p = ExecutablePath;
  51. string baseName = Path.GetFileNameWithoutExtension(p);
  52. if (baseName.EndsWith(".vshost")) baseName = baseName.Substring(0, baseName.Length - 7);
  53. while (true)
  54. {
  55. p = Path.GetDirectoryName(p);
  56. if (File.Exists(Path.Combine(p, baseName + ".xml")))
  57. break;
  58. }
  59. // register the base directory as environment variable so that future expansions can refer to this.
  60. Environment.SetEnvironmentVariable("BASE", p);
  61. BaseName = baseName;
  62. BasePath = Path.Combine(p, BaseName);
  63. dom.Load(BasePath + ".xml");
  64. }
  65. private string SingleElement(string tagName)
  66. {
  67. return SingleElement(tagName, false);
  68. }
  69. private string SingleElement(string tagName, Boolean optional)
  70. {
  71. var n = dom.SelectSingleNode("//" + tagName);
  72. if (n == null && !optional) throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  73. return n == null ? null : Environment.ExpandEnvironmentVariables(n.InnerText);
  74. }
  75. private int SingleIntElement(XmlNode parent, string tagName, int defaultValue)
  76. {
  77. var e = parent.SelectSingleNode(tagName);
  78. if (e == null)
  79. {
  80. return defaultValue;
  81. }
  82. else
  83. {
  84. return int.Parse(e.InnerText);
  85. }
  86. }
  87. /// <summary>
  88. /// Path to the executable.
  89. /// </summary>
  90. public string Executable
  91. {
  92. get
  93. {
  94. return SingleElement("executable");
  95. }
  96. }
  97. /// <summary>
  98. /// Optionally specify a different Path to an executable to shutdown the service.
  99. /// </summary>
  100. public string StopExecutable
  101. {
  102. get
  103. {
  104. return SingleElement("stopexecutable");
  105. }
  106. }
  107. /// <summary>
  108. /// Arguments or multiple optional argument elements which overrule the arguments element.
  109. /// </summary>
  110. public string Arguments
  111. {
  112. get
  113. {
  114. string arguments = AppendTags("argument");
  115. if (arguments == null)
  116. {
  117. var tagName = "arguments";
  118. var argumentsNode = dom.SelectSingleNode("//" + tagName);
  119. if (argumentsNode == null)
  120. {
  121. if (AppendTags("startargument") == null)
  122. {
  123. throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  124. }
  125. else
  126. {
  127. return "";
  128. }
  129. }
  130. return Environment.ExpandEnvironmentVariables(argumentsNode.InnerText);
  131. }
  132. else
  133. {
  134. return arguments;
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Multiple optional startargument elements.
  140. /// </summary>
  141. public string Startarguments
  142. {
  143. get
  144. {
  145. return AppendTags("startargument");
  146. }
  147. }
  148. /// <summary>
  149. /// Multiple optional stopargument elements.
  150. /// </summary>
  151. public string Stoparguments
  152. {
  153. get
  154. {
  155. return AppendTags("stopargument");
  156. }
  157. }
  158. /// <summary>
  159. /// Optional working directory.
  160. /// </summary>
  161. public string WorkingDirectory {
  162. get {
  163. var wd = SingleElement("workingdirectory", true);
  164. return String.IsNullOrEmpty(wd) ? Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) : wd;
  165. }
  166. }
  167. /// <summary>
  168. /// Combines the contents of all the elements of the given name,
  169. /// or return null if no element exists. Handles whitespace quotation.
  170. /// </summary>
  171. private string AppendTags(string tagName)
  172. {
  173. XmlNode argumentNode = dom.SelectSingleNode("//" + tagName);
  174. if (argumentNode == null)
  175. {
  176. return null;
  177. }
  178. else
  179. {
  180. string arguments = "";
  181. foreach (XmlElement argument in dom.SelectNodes("//" + tagName))
  182. {
  183. string token = Environment.ExpandEnvironmentVariables(argument.InnerText);
  184. if (token.StartsWith("\"") && token.EndsWith("\""))
  185. {
  186. // for backward compatibility, if the argument is already quoted, leave it as is.
  187. // in earlier versions we didn't handle quotation, so the user might have worked
  188. // around it by themselves
  189. }
  190. else
  191. {
  192. if (token.Contains(" "))
  193. {
  194. token = '"' + token + '"';
  195. }
  196. }
  197. arguments += " " + token;
  198. }
  199. return arguments;
  200. }
  201. }
  202. /// <summary>
  203. /// LogDirectory is the service wrapper executable directory or the optionally specified logpath element.
  204. /// </summary>
  205. public string LogDirectory
  206. {
  207. get
  208. {
  209. XmlNode loggingNode = dom.SelectSingleNode("//logpath");
  210. if (loggingNode != null)
  211. {
  212. return Environment.ExpandEnvironmentVariables(loggingNode.InnerText);
  213. }
  214. else
  215. {
  216. return Path.GetDirectoryName(ExecutablePath);
  217. }
  218. }
  219. }
  220. public LogHandler LogHandler
  221. {
  222. get
  223. {
  224. string mode=null;
  225. // first, backward compatibility with older configuration
  226. XmlElement e = (XmlElement)dom.SelectSingleNode("//logmode");
  227. if (e!=null) {
  228. mode = e.InnerText;
  229. } else {
  230. // this is more modern way, to support nested elements as configuration
  231. e = (XmlElement)dom.SelectSingleNode("//log");
  232. if (e!=null)
  233. mode = e.GetAttribute("mode");
  234. }
  235. if (mode == null) mode = "append";
  236. switch (mode)
  237. {
  238. case "rotate":
  239. return new SizeBasedRollingLogAppender(LogDirectory, BaseName);
  240. case "reset":
  241. return new ResetLogAppender(LogDirectory, BaseName);
  242. case "roll":
  243. return new RollingLogAppender(LogDirectory, BaseName);
  244. case "roll-by-time":
  245. XmlNode patternNode = e.SelectSingleNode("pattern");
  246. if (patternNode == null)
  247. {
  248. throw new InvalidDataException("Time Based rolling policy is specified but no pattern can be found in configuration XML.");
  249. }
  250. string pattern = patternNode.InnerText;
  251. int period = SingleIntElement(e,"period",1);
  252. return new TimeBasedRollingLogAppender(LogDirectory, BaseName, pattern, period);
  253. case "roll-by-size":
  254. int sizeThreshold = SingleIntElement(e,"sizeThreshold",10*1024) * SizeBasedRollingLogAppender.BYTES_PER_KB;
  255. int keepFiles = SingleIntElement(e,"keepFiles",SizeBasedRollingLogAppender.DEFAULT_FILES_TO_KEEP);
  256. return new SizeBasedRollingLogAppender(LogDirectory, BaseName, sizeThreshold, keepFiles);
  257. case "append":
  258. return new DefaultLogAppender(LogDirectory, BaseName);
  259. default:
  260. throw new InvalidDataException("Undefined logging mode: " + mode);
  261. }
  262. }
  263. }
  264. /// <summary>
  265. /// Optionally specified depend services that must start before this service starts.
  266. /// </summary>
  267. public string[] ServiceDependencies
  268. {
  269. get
  270. {
  271. System.Collections.ArrayList serviceDependencies = new System.Collections.ArrayList();
  272. foreach (XmlNode depend in dom.SelectNodes("//depend"))
  273. {
  274. serviceDependencies.Add(depend.InnerText);
  275. }
  276. return (string[])serviceDependencies.ToArray(typeof(string));
  277. }
  278. }
  279. public string Id
  280. {
  281. get
  282. {
  283. return SingleElement("id");
  284. }
  285. }
  286. public string Caption
  287. {
  288. get
  289. {
  290. return SingleElement("name");
  291. }
  292. }
  293. public string Description
  294. {
  295. get
  296. {
  297. return SingleElement("description");
  298. }
  299. }
  300. /// <summary>
  301. /// True if the service should when finished on shutdown.
  302. /// This doesn't work on some OSes. See http://msdn.microsoft.com/en-us/library/ms679277%28VS.85%29.aspx
  303. /// </summary>
  304. public bool BeepOnShutdown
  305. {
  306. get
  307. {
  308. return dom.SelectSingleNode("//beeponshutdown") != null;
  309. }
  310. }
  311. /// <summary>
  312. /// The estimated time required for a pending stop operation, in milliseconds (default 15 secs).
  313. /// Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function
  314. /// with either an incremented checkPoint value or a change in currentState. (see http://msdn.microsoft.com/en-us/library/ms685996.aspx)
  315. /// </summary>
  316. public int WaitHint
  317. {
  318. get
  319. {
  320. return SingleIntElement(dom, "waithint", 15000);
  321. }
  322. }
  323. /// <summary>
  324. /// The time, in milliseconds (default 1 sec), before the service should make its next call to the SetServiceStatus function
  325. /// with an incremented checkPoint value.
  326. /// Do not wait longer than the wait hint. A good interval is one-tenth of the wait hint but not less than 1 second and not more than 10 seconds.
  327. /// </summary>
  328. public int SleepTime
  329. {
  330. get
  331. {
  332. return SingleIntElement(dom, "sleeptime", 15000);
  333. }
  334. }
  335. /// <summary>
  336. /// True if the service can interact with the desktop.
  337. /// </summary>
  338. public bool Interactive
  339. {
  340. get
  341. {
  342. return dom.SelectSingleNode("//interactive") != null;
  343. }
  344. }
  345. /// <summary>
  346. /// Environment variable overrides
  347. /// </summary>
  348. public Dictionary<string, string> EnvironmentVariables
  349. {
  350. get
  351. {
  352. Dictionary<string, string> map = new Dictionary<string, string>();
  353. foreach (XmlNode n in dom.SelectNodes("//env"))
  354. {
  355. string key = n.Attributes["name"].Value;
  356. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  357. map[key] = value;
  358. Environment.SetEnvironmentVariable(key, value);
  359. }
  360. return map;
  361. }
  362. }
  363. /// <summary>
  364. /// List of downloads to be performed by the wrapper before starting
  365. /// a service.
  366. /// </summary>
  367. public List<Download> Downloads
  368. {
  369. get
  370. {
  371. List<Download> r = new List<Download>();
  372. foreach (XmlNode n in dom.SelectNodes("//download"))
  373. {
  374. r.Add(new Download(n));
  375. }
  376. return r;
  377. }
  378. }
  379. }
  380. }