ServiceDescriptor.cs 19 KB

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