ServiceDescriptor.cs 19 KB

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