ServiceDescriptor.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 argumentsNode = dom.SelectSingleNode("//arguments");
  172. if (argumentsNode == null)
  173. {
  174. return "";
  175. }
  176. return Environment.ExpandEnvironmentVariables(argumentsNode.InnerText);
  177. }
  178. else
  179. {
  180. return arguments;
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Multiple optional startargument elements.
  186. /// </summary>
  187. public string Startarguments
  188. {
  189. get
  190. {
  191. return AppendTags("startargument");
  192. }
  193. }
  194. /// <summary>
  195. /// Multiple optional stopargument elements.
  196. /// </summary>
  197. public string Stoparguments
  198. {
  199. get
  200. {
  201. return AppendTags("stopargument");
  202. }
  203. }
  204. /// <summary>
  205. /// Optional working directory.
  206. /// </summary>
  207. public string WorkingDirectory {
  208. get {
  209. var wd = SingleElement("workingdirectory", true);
  210. return String.IsNullOrEmpty(wd) ? Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) : wd;
  211. }
  212. }
  213. /// <summary>
  214. /// Combines the contents of all the elements of the given name,
  215. /// or return null if no element exists. Handles whitespace quotation.
  216. /// </summary>
  217. private string AppendTags(string tagName)
  218. {
  219. XmlNode argumentNode = dom.SelectSingleNode("//" + tagName);
  220. if (argumentNode == null)
  221. {
  222. return null;
  223. }
  224. else
  225. {
  226. string arguments = "";
  227. foreach (XmlElement argument in dom.SelectNodes("//" + tagName))
  228. {
  229. string token = Environment.ExpandEnvironmentVariables(argument.InnerText);
  230. if (token.StartsWith("\"") && token.EndsWith("\""))
  231. {
  232. // for backward compatibility, if the argument is already quoted, leave it as is.
  233. // in earlier versions we didn't handle quotation, so the user might have worked
  234. // around it by themselves
  235. }
  236. else
  237. {
  238. if (token.Contains(" "))
  239. {
  240. token = '"' + token + '"';
  241. }
  242. }
  243. arguments += " " + token;
  244. }
  245. return arguments;
  246. }
  247. }
  248. /// <summary>
  249. /// LogDirectory is the service wrapper executable directory or the optionally specified logpath element.
  250. /// </summary>
  251. public string LogDirectory
  252. {
  253. get
  254. {
  255. XmlNode loggingNode = dom.SelectSingleNode("//logpath");
  256. if (loggingNode != null)
  257. {
  258. return Environment.ExpandEnvironmentVariables(loggingNode.InnerText);
  259. }
  260. else
  261. {
  262. return Path.GetDirectoryName(ExecutablePath);
  263. }
  264. }
  265. }
  266. public LogHandler LogHandler
  267. {
  268. get
  269. {
  270. string mode=null;
  271. // first, backward compatibility with older configuration
  272. XmlElement e = (XmlElement)dom.SelectSingleNode("//logmode");
  273. if (e!=null) {
  274. mode = e.InnerText;
  275. } else {
  276. // this is more modern way, to support nested elements as configuration
  277. e = (XmlElement)dom.SelectSingleNode("//log");
  278. if (e!=null)
  279. mode = e.GetAttribute("mode");
  280. }
  281. if (mode == null) mode = "append";
  282. switch (mode)
  283. {
  284. case "rotate":
  285. return new SizeBasedRollingLogAppender(LogDirectory, BaseName);
  286. case "none":
  287. return new IgnoreLogAppender();
  288. case "reset":
  289. return new ResetLogAppender(LogDirectory, BaseName);
  290. case "roll":
  291. return new RollingLogAppender(LogDirectory, BaseName);
  292. case "roll-by-time":
  293. XmlNode patternNode = e.SelectSingleNode("pattern");
  294. if (patternNode == null)
  295. {
  296. throw new InvalidDataException("Time Based rolling policy is specified but no pattern can be found in configuration XML.");
  297. }
  298. string pattern = patternNode.InnerText;
  299. int period = SingleIntElement(e,"period",1);
  300. return new TimeBasedRollingLogAppender(LogDirectory, BaseName, pattern, period);
  301. case "roll-by-size":
  302. int sizeThreshold = SingleIntElement(e,"sizeThreshold",10*1024) * SizeBasedRollingLogAppender.BYTES_PER_KB;
  303. int keepFiles = SingleIntElement(e,"keepFiles",SizeBasedRollingLogAppender.DEFAULT_FILES_TO_KEEP);
  304. return new SizeBasedRollingLogAppender(LogDirectory, BaseName, sizeThreshold, keepFiles);
  305. case "append":
  306. return new DefaultLogAppender(LogDirectory, BaseName);
  307. default:
  308. throw new InvalidDataException("Undefined logging mode: " + mode);
  309. }
  310. }
  311. }
  312. /// <summary>
  313. /// Optionally specified depend services that must start before this service starts.
  314. /// </summary>
  315. public string[] ServiceDependencies
  316. {
  317. get
  318. {
  319. System.Collections.ArrayList serviceDependencies = new System.Collections.ArrayList();
  320. foreach (XmlNode depend in dom.SelectNodes("//depend"))
  321. {
  322. serviceDependencies.Add(depend.InnerText);
  323. }
  324. return (string[])serviceDependencies.ToArray(typeof(string));
  325. }
  326. }
  327. public string Id
  328. {
  329. get
  330. {
  331. return SingleElement("id");
  332. }
  333. }
  334. public string Caption
  335. {
  336. get
  337. {
  338. return SingleElement("name");
  339. }
  340. }
  341. public string Description
  342. {
  343. get
  344. {
  345. return SingleElement("description");
  346. }
  347. }
  348. /// <summary>
  349. /// True if the service should when finished on shutdown.
  350. /// This doesn't work on some OSes. See http://msdn.microsoft.com/en-us/library/ms679277%28VS.85%29.aspx
  351. /// </summary>
  352. public bool BeepOnShutdown
  353. {
  354. get
  355. {
  356. return dom.SelectSingleNode("//beeponshutdown") != null;
  357. }
  358. }
  359. /// <summary>
  360. /// The estimated time required for a pending stop operation (default 15 secs).
  361. /// Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function
  362. /// with either an incremented checkPoint value or a change in currentState. (see http://msdn.microsoft.com/en-us/library/ms685996.aspx)
  363. /// </summary>
  364. public TimeSpan WaitHint
  365. {
  366. get
  367. {
  368. return SingleTimeSpanElement(dom, "waithint", TimeSpan.FromSeconds(15));
  369. }
  370. }
  371. /// <summary>
  372. /// The time before the service should make its next call to the SetServiceStatus function
  373. /// with an incremented checkPoint value (default 1 sec).
  374. /// 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.
  375. /// </summary>
  376. public TimeSpan SleepTime
  377. {
  378. get
  379. {
  380. return SingleTimeSpanElement(dom, "sleeptime", TimeSpan.FromSeconds(1));
  381. }
  382. }
  383. /// <summary>
  384. /// True if the service can interact with the desktop.
  385. /// </summary>
  386. public bool Interactive
  387. {
  388. get
  389. {
  390. return dom.SelectSingleNode("//interactive") != null;
  391. }
  392. }
  393. /// <summary>
  394. /// Environment variable overrides
  395. /// </summary>
  396. public Dictionary<string, string> EnvironmentVariables
  397. {
  398. get
  399. {
  400. Dictionary<string, string> map = new Dictionary<string, string>();
  401. foreach (XmlNode n in dom.SelectNodes("//env"))
  402. {
  403. string key = n.Attributes["name"].Value;
  404. string value = Environment.ExpandEnvironmentVariables(n.Attributes["value"].Value);
  405. map[key] = value;
  406. Environment.SetEnvironmentVariable(key, value);
  407. }
  408. return map;
  409. }
  410. }
  411. /// <summary>
  412. /// List of downloads to be performed by the wrapper before starting
  413. /// a service.
  414. /// </summary>
  415. public List<Download> Downloads
  416. {
  417. get
  418. {
  419. List<Download> r = new List<Download>();
  420. foreach (XmlNode n in dom.SelectNodes("//download"))
  421. {
  422. r.Add(new Download(n));
  423. }
  424. return r;
  425. }
  426. }
  427. public List<SC_ACTION> FailureActions
  428. {
  429. get
  430. {
  431. List<SC_ACTION> r = new List<SC_ACTION>();
  432. foreach (XmlNode n in dom.SelectNodes("//onfailure"))
  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. return r;
  454. }
  455. }
  456. public TimeSpan ResetFailureAfter
  457. {
  458. get
  459. {
  460. return SingleTimeSpanElement(dom, "resetfailure", TimeSpan.FromDays(1));
  461. }
  462. }
  463. protected string GetServiceAccountPart(string subNodeName)
  464. {
  465. var node = dom.SelectSingleNode("//serviceaccount");
  466. if (node != null)
  467. {
  468. var subNode = node.SelectSingleNode(subNodeName);
  469. if (subNode != null)
  470. {
  471. return subNode.InnerText;
  472. }
  473. }
  474. return null;
  475. }
  476. protected string serviceAccountDomain
  477. {
  478. get{
  479. return GetServiceAccountPart("domain");
  480. }
  481. }
  482. protected string serviceAccountName
  483. {
  484. get
  485. {
  486. return GetServiceAccountPart("user");
  487. }
  488. }
  489. public string ServiceAccountPassword
  490. {
  491. get
  492. {
  493. return GetServiceAccountPart("password");
  494. }
  495. }
  496. public string ServiceAccountUser
  497. {
  498. get { return (serviceAccountDomain ?? "NULL") + @"\" + (serviceAccountName ?? "NULL"); }
  499. }
  500. public bool HasServiceAccount()
  501. {
  502. return !string.IsNullOrEmpty(serviceAccountDomain) && !string.IsNullOrEmpty(serviceAccountName);
  503. }
  504. /// <summary>
  505. /// Time to wait for the service to gracefully shutdown before we forcibly kill it
  506. /// </summary>
  507. public TimeSpan StopTimeout
  508. {
  509. get
  510. {
  511. return SingleTimeSpanElement(dom, "stoptimeout", TimeSpan.FromSeconds(15));
  512. }
  513. }
  514. /// <summary>
  515. /// Desired process priority or null if not specified.
  516. /// </summary>
  517. public ProcessPriorityClass Priority
  518. {
  519. get
  520. {
  521. var p = SingleElement("priority",true);
  522. if (p == null) return ProcessPriorityClass.Normal; // default value
  523. return (ProcessPriorityClass)Enum.Parse(typeof(ProcessPriorityClass), p, true);
  524. }
  525. }
  526. }
  527. }