ServiceDescriptor.cs 17 KB

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