ServiceDescriptor.cs 19 KB

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