ServiceDescriptor.cs 21 KB

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