ServiceDescriptor.cs 14 KB

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