ServiceDescriptor.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Xml;
  8. namespace winsw
  9. {
  10. /// <summary>
  11. /// In-memory representation of the configuration file.
  12. /// </summary>
  13. public class ServiceDescriptor
  14. {
  15. // ReSharper disable once InconsistentNaming
  16. protected readonly XmlDocument dom = new XmlDocument();
  17. /// <summary>
  18. /// Where did we find the configuration file?
  19. ///
  20. /// This string is "c:\abc\def\ghi" when the configuration XML is "c:\abc\def\ghi.xml"
  21. /// </summary>
  22. public string BasePath { get; set; }
  23. /// <summary>
  24. /// The file name portion of the configuration file.
  25. ///
  26. /// In the above example, this would be "ghi".
  27. /// </summary>
  28. public string BaseName { get; set; }
  29. public virtual string ExecutablePath
  30. {
  31. get
  32. {
  33. // this returns the executable name as given by the calling process, so
  34. // it needs to be absolutized.
  35. string p = Environment.GetCommandLineArgs()[0];
  36. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p);
  37. }
  38. }
  39. public ServiceDescriptor()
  40. {
  41. // find co-located configuration xml. We search up to the ancestor directories to simplify debugging,
  42. // as well as trimming off ".vshost" suffix (which is used during debugging)
  43. string p = ExecutablePath;
  44. string baseName = Path.GetFileNameWithoutExtension(p);
  45. if (baseName.EndsWith(".vshost")) baseName = baseName.Substring(0, baseName.Length - 7);
  46. while (true)
  47. {
  48. p = Path.GetDirectoryName(p);
  49. if (File.Exists(Path.Combine(p, baseName + ".xml")))
  50. break;
  51. }
  52. BaseName = baseName;
  53. BasePath = Path.Combine(p, BaseName);
  54. dom.Load(BasePath + ".xml");
  55. // register the base directory as environment variable so that future expansions can refer to this.
  56. Environment.SetEnvironmentVariable("BASE", p);
  57. // ditto for ID
  58. Environment.SetEnvironmentVariable("SERVICE_ID", Id);
  59. Environment.SetEnvironmentVariable("WINSW_EXECUTABLE", ExecutablePath);
  60. }
  61. /// <summary>
  62. /// Loads descriptor from existing DOM
  63. /// </summary>
  64. public ServiceDescriptor(XmlDocument dom)
  65. {
  66. this.dom = dom;
  67. }
  68. public static ServiceDescriptor FromXML(string xml)
  69. {
  70. var dom = new XmlDocument();
  71. dom.LoadXml(xml);
  72. return new ServiceDescriptor(dom);
  73. }
  74. private string SingleElement(string tagName)
  75. {
  76. return SingleElement(tagName, false);
  77. }
  78. private string SingleElement(string tagName, Boolean optional)
  79. {
  80. var n = dom.SelectSingleNode("//" + tagName);
  81. if (n == null && !optional) throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
  82. return n == null ? null : Environment.ExpandEnvironmentVariables(n.InnerText);
  83. }
  84. private int SingleIntElement(XmlNode parent, string tagName, int defaultValue)
  85. {
  86. var e = parent.SelectSingleNode(tagName);
  87. if (e == null)
  88. {
  89. return defaultValue;
  90. }
  91. else
  92. {
  93. return int.Parse(e.InnerText);
  94. }
  95. }
  96. private TimeSpan SingleTimeSpanElement(XmlNode parent, string tagName, TimeSpan defaultValue)
  97. {
  98. var e = parent.SelectSingleNode(tagName);
  99. if (e == null)
  100. {
  101. return defaultValue;
  102. }
  103. else
  104. {
  105. return ParseTimeSpan(e.InnerText);
  106. }
  107. }
  108. private TimeSpan ParseTimeSpan(string v)
  109. {
  110. v = v.Trim();
  111. foreach (var s in Suffix)
  112. {
  113. if (v.EndsWith(s.Key))
  114. {
  115. return TimeSpan.FromMilliseconds(int.Parse(v.Substring(0, v.Length - s.Key.Length).Trim()) * s.Value);
  116. }
  117. }
  118. return TimeSpan.FromMilliseconds(int.Parse(v));
  119. }
  120. private static readonly Dictionary<string,long> Suffix = new Dictionary<string,long> {
  121. { "ms", 1 },
  122. { "sec", 1000L },
  123. { "secs", 1000L },
  124. { "min", 1000L*60L },
  125. { "mins", 1000L*60L },
  126. { "hr", 1000L*60L*60L },
  127. { "hrs", 1000L*60L*60L },
  128. { "hour", 1000L*60L*60L },
  129. { "hours", 1000L*60L*60L },
  130. { "day", 1000L*60L*60L*24L },
  131. { "days", 1000L*60L*60L*24L }
  132. };
  133. /// <summary>
  134. /// Path to the executable.
  135. /// </summary>
  136. public string Executable
  137. {
  138. get
  139. {
  140. return SingleElement("executable");
  141. }
  142. }
  143. /// <summary>
  144. /// Optionally specify a different Path to an executable to shutdown the service.
  145. /// </summary>
  146. public string StopExecutable
  147. {
  148. get
  149. {
  150. return SingleElement("stopexecutable");
  151. }
  152. }
  153. /// <summary>
  154. /// Arguments or multiple optional argument elements which overrule the arguments element.
  155. /// </summary>
  156. public string Arguments
  157. {
  158. get
  159. {
  160. string arguments = AppendTags("argument");
  161. if (arguments == null)
  162. {
  163. var argumentsNode = dom.SelectSingleNode("//arguments");
  164. if (argumentsNode == null)
  165. {
  166. return "";
  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 "none":
  279. return new IgnoreLogAppender();
  280. case "reset":
  281. return new ResetLogAppender(LogDirectory, BaseName);
  282. case "roll":
  283. return new RollingLogAppender(LogDirectory, BaseName);
  284. case "roll-by-time":
  285. XmlNode patternNode = e.SelectSingleNode("pattern");
  286. if (patternNode == null)
  287. {
  288. throw new InvalidDataException("Time Based rolling policy is specified but no pattern can be found in configuration XML.");
  289. }
  290. string pattern = patternNode.InnerText;
  291. int period = SingleIntElement(e,"period",1);
  292. return new TimeBasedRollingLogAppender(LogDirectory, BaseName, pattern, period);
  293. case "roll-by-size":
  294. int sizeThreshold = SingleIntElement(e,"sizeThreshold",10*1024) * SizeBasedRollingLogAppender.BYTES_PER_KB;
  295. int keepFiles = SingleIntElement(e,"keepFiles",SizeBasedRollingLogAppender.DEFAULT_FILES_TO_KEEP);
  296. return new SizeBasedRollingLogAppender(LogDirectory, BaseName, sizeThreshold, keepFiles);
  297. case "append":
  298. return new DefaultLogAppender(LogDirectory, BaseName);
  299. default:
  300. throw new InvalidDataException("Undefined logging mode: " + mode);
  301. }
  302. }
  303. }
  304. /// <summary>
  305. /// Optionally specified depend services that must start before this service starts.
  306. /// </summary>
  307. public string[] ServiceDependencies
  308. {
  309. get
  310. {
  311. ArrayList serviceDependencies = new ArrayList();
  312. foreach (XmlNode depend in dom.SelectNodes("//depend"))
  313. {
  314. serviceDependencies.Add(depend.InnerText);
  315. }
  316. return (string[])serviceDependencies.ToArray(typeof(string));
  317. }
  318. }
  319. public string Id
  320. {
  321. get
  322. {
  323. return SingleElement("id");
  324. }
  325. }
  326. public string Caption
  327. {
  328. get
  329. {
  330. return SingleElement("name");
  331. }
  332. }
  333. public string Description
  334. {
  335. get
  336. {
  337. return SingleElement("description");
  338. }
  339. }
  340. /// <summary>
  341. /// True if the service should when finished on shutdown.
  342. /// This doesn't work on some OSes. See http://msdn.microsoft.com/en-us/library/ms679277%28VS.85%29.aspx
  343. /// </summary>
  344. public bool BeepOnShutdown
  345. {
  346. get
  347. {
  348. return dom.SelectSingleNode("//beeponshutdown") != null;
  349. }
  350. }
  351. /// <summary>
  352. /// The estimated time required for a pending stop operation (default 15 secs).
  353. /// Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function
  354. /// with either an incremented checkPoint value or a change in currentState. (see http://msdn.microsoft.com/en-us/library/ms685996.aspx)
  355. /// </summary>
  356. public TimeSpan WaitHint
  357. {
  358. get
  359. {
  360. return SingleTimeSpanElement(dom.FirstChild, "waithint", TimeSpan.FromSeconds(15));
  361. }
  362. }
  363. /// <summary>
  364. /// The time before the service should make its next call to the SetServiceStatus function
  365. /// with an incremented checkPoint value (default 1 sec).
  366. /// 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.
  367. /// </summary>
  368. public TimeSpan SleepTime
  369. {
  370. get
  371. {
  372. return SingleTimeSpanElement(dom.FirstChild, "sleeptime", TimeSpan.FromSeconds(1));
  373. }
  374. }
  375. /// <summary>
  376. /// True if the service can interact with the desktop.
  377. /// </summary>
  378. public bool Interactive
  379. {
  380. get
  381. {
  382. return dom.SelectSingleNode("//interactive") != null;
  383. }
  384. }
  385. /// <summary>
  386. /// Environment variable overrides
  387. /// </summary>
  388. public Dictionary<string, string> EnvironmentVariables
  389. {
  390. get
  391. {
  392. Dictionary<string, string> map = new Dictionary<string, string>();
  393. foreach (XmlNode n in dom.SelectNodes("//env"))
  394. {
  395. string key = n.Attributes["name"].Value;
  396. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  397. map[key] = value;
  398. Environment.SetEnvironmentVariable(key, value);
  399. }
  400. return map;
  401. }
  402. }
  403. /// <summary>
  404. /// List of downloads to be performed by the wrapper before starting
  405. /// a service.
  406. /// </summary>
  407. public List<Download> Downloads
  408. {
  409. get
  410. {
  411. List<Download> r = new List<Download>();
  412. foreach (XmlNode n in dom.SelectNodes("//download"))
  413. {
  414. r.Add(new Download(n));
  415. }
  416. return r;
  417. }
  418. }
  419. public List<SC_ACTION> FailureActions
  420. {
  421. get
  422. {
  423. List<SC_ACTION> r = new List<SC_ACTION>();
  424. foreach (XmlNode n in dom.SelectNodes("//onfailure"))
  425. {
  426. SC_ACTION_TYPE type;
  427. string action = n.Attributes["action"].Value;
  428. switch (action)
  429. {
  430. case "restart":
  431. type = SC_ACTION_TYPE.SC_ACTION_RESTART;
  432. break;
  433. case "none":
  434. type = SC_ACTION_TYPE.SC_ACTION_NONE;
  435. break;
  436. case "reboot":
  437. type = SC_ACTION_TYPE.SC_ACTION_REBOOT;
  438. break;
  439. default:
  440. throw new Exception("Invalid failure action: " + action);
  441. }
  442. XmlAttribute delay = n.Attributes["delay"];
  443. r.Add(new SC_ACTION(type, delay != null ? ParseTimeSpan(delay.Value) : TimeSpan.Zero));
  444. }
  445. return r;
  446. }
  447. }
  448. public TimeSpan ResetFailureAfter
  449. {
  450. get
  451. {
  452. return SingleTimeSpanElement(dom.FirstChild, "resetfailure", TimeSpan.FromDays(1));
  453. }
  454. }
  455. protected string GetServiceAccountPart(string subNodeName)
  456. {
  457. var node = dom.SelectSingleNode("//serviceaccount");
  458. if (node != null)
  459. {
  460. var subNode = node.SelectSingleNode(subNodeName);
  461. if (subNode != null)
  462. {
  463. return subNode.InnerText;
  464. }
  465. }
  466. return null;
  467. }
  468. protected string AllowServiceLogon
  469. {
  470. get
  471. {
  472. return GetServiceAccountPart("allowservicelogon");
  473. }
  474. }
  475. // ReSharper disable once InconsistentNaming
  476. protected string serviceAccountDomain
  477. {
  478. get
  479. {
  480. return GetServiceAccountPart("domain");
  481. }
  482. }
  483. // ReSharper disable once InconsistentNaming
  484. protected string serviceAccountName
  485. {
  486. get
  487. {
  488. return GetServiceAccountPart("user");
  489. }
  490. }
  491. public string ServiceAccountPassword
  492. {
  493. get
  494. {
  495. return GetServiceAccountPart("password");
  496. }
  497. }
  498. public string ServiceAccountUser
  499. {
  500. get { return (serviceAccountDomain ?? "NULL") + @"\" + (serviceAccountName ?? "NULL"); }
  501. }
  502. public bool HasServiceAccount()
  503. {
  504. return !string.IsNullOrEmpty(serviceAccountDomain) && !string.IsNullOrEmpty(serviceAccountName);
  505. }
  506. public bool AllowServiceAcountLogonRight
  507. {
  508. get
  509. {
  510. if (AllowServiceLogon != null)
  511. {
  512. bool parsedvalue;
  513. if (Boolean.TryParse(AllowServiceLogon, out parsedvalue))
  514. {
  515. return parsedvalue;
  516. }
  517. }
  518. return false;
  519. }
  520. }
  521. /// <summary>
  522. /// Time to wait for the service to gracefully shutdown before we forcibly kill it
  523. /// </summary>
  524. public TimeSpan StopTimeout
  525. {
  526. get
  527. {
  528. return SingleTimeSpanElement(dom.FirstChild, "stoptimeout", TimeSpan.FromSeconds(15));
  529. }
  530. }
  531. public bool StopParentProcessFirst
  532. {
  533. get
  534. {
  535. var value = SingleElement("stopparentprocessfirst", true);
  536. bool result;
  537. if (bool.TryParse(value, out result))
  538. {
  539. return result;
  540. }
  541. return false;
  542. }
  543. }
  544. /// <summary>
  545. /// Desired process priority or null if not specified.
  546. /// </summary>
  547. public ProcessPriorityClass Priority
  548. {
  549. get
  550. {
  551. var p = SingleElement("priority",true);
  552. if (p == null) return ProcessPriorityClass.Normal; // default value
  553. return (ProcessPriorityClass)Enum.Parse(typeof(ProcessPriorityClass), p, true);
  554. }
  555. }
  556. }
  557. }