ServiceDescriptor.cs 17 KB

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