1
0

ServiceDescriptor.cs 21 KB

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