AppDomainManager.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
  32. {
  33. public class AppDomainManager : iScriptEngineFunctionModule
  34. {
  35. //
  36. // This class does AppDomain handling and loading/unloading of scripts in it.
  37. // It is instanced in "ScriptEngine" and controlled from "ScriptManager"
  38. //
  39. // 1. Create a new AppDomain if old one is full (or doesn't exist)
  40. // 2. Load scripts into AppDomain
  41. // 3. Unload scripts from AppDomain (stopping them and marking them as inactive)
  42. // 4. Unload AppDomain completely when all scripts in it has stopped
  43. //
  44. private int maxScriptsPerAppDomain = 1;
  45. /// <summary>
  46. /// Internal list of all AppDomains
  47. /// </summary>
  48. private List<AppDomainStructure> appDomains = new List<AppDomainStructure>();
  49. /// <summary>
  50. /// Structure to keep track of data around AppDomain
  51. /// </summary>
  52. private class AppDomainStructure
  53. {
  54. /// <summary>
  55. /// The AppDomain itself
  56. /// </summary>
  57. public AppDomain CurrentAppDomain;
  58. /// <summary>
  59. /// Number of scripts loaded into AppDomain
  60. /// </summary>
  61. public int ScriptsLoaded;
  62. /// <summary>
  63. /// Number of dead scripts
  64. /// </summary>
  65. public int ScriptsWaitingUnload;
  66. }
  67. /// <summary>
  68. /// Current AppDomain
  69. /// </summary>
  70. private AppDomainStructure currentAD;
  71. private object getLock = new object(); // Mutex
  72. private object freeLock = new object(); // Mutex
  73. private ScriptEngine m_scriptEngine;
  74. //public AppDomainManager(ScriptEngine scriptEngine)
  75. public AppDomainManager(ScriptEngine scriptEngine)
  76. {
  77. m_scriptEngine = scriptEngine;
  78. ReadConfig();
  79. }
  80. public void ReadConfig()
  81. {
  82. maxScriptsPerAppDomain = m_scriptEngine.ScriptConfigSource.GetInt("ScriptsPerAppDomain", 1);
  83. }
  84. /// <summary>
  85. /// Find a free AppDomain, creating one if necessary
  86. /// </summary>
  87. /// <returns>Free AppDomain</returns>
  88. private AppDomainStructure GetFreeAppDomain()
  89. {
  90. // Console.WriteLine("Finding free AppDomain");
  91. lock (getLock)
  92. {
  93. // Current full?
  94. if (currentAD != null && currentAD.ScriptsLoaded >= maxScriptsPerAppDomain)
  95. {
  96. // Add it to AppDomains list and empty current
  97. appDomains.Add(currentAD);
  98. currentAD = null;
  99. }
  100. // No current
  101. if (currentAD == null)
  102. {
  103. // Create a new current AppDomain
  104. currentAD = new AppDomainStructure();
  105. currentAD.CurrentAppDomain = PrepareNewAppDomain();
  106. }
  107. // Console.WriteLine("Scripts loaded in this Appdomain: " + currentAD.ScriptsLoaded);
  108. return currentAD;
  109. }
  110. }
  111. private int AppDomainNameCount;
  112. /// <summary>
  113. /// Create and prepare a new AppDomain for scripts
  114. /// </summary>
  115. /// <returns>The new AppDomain</returns>
  116. private AppDomain PrepareNewAppDomain()
  117. {
  118. // Create and prepare a new AppDomain
  119. AppDomainNameCount++;
  120. // TODO: Currently security match current appdomain
  121. // Construct and initialize settings for a second AppDomain.
  122. AppDomainSetup ads = new AppDomainSetup();
  123. ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
  124. ads.DisallowBindingRedirects = true;
  125. ads.DisallowCodeDownload = true;
  126. ads.LoaderOptimization = LoaderOptimization.MultiDomainHost;
  127. ads.ShadowCopyFiles = "false"; // Disable shadowing
  128. ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
  129. AppDomain AD = AppDomain.CreateDomain("ScriptAppDomain_" + AppDomainNameCount, null, ads);
  130. m_scriptEngine.Log.Info("[" + m_scriptEngine.ScriptEngineName + "]: AppDomain Loading: " +
  131. AssemblyName.GetAssemblyName("OpenSim.Region.ScriptEngine.Common.dll").ToString());
  132. AD.Load(AssemblyName.GetAssemblyName("OpenSim.Region.ScriptEngine.Common.dll"));
  133. // Return the new AppDomain
  134. return AD;
  135. }
  136. /// <summary>
  137. /// Unload appdomains that are full and have only dead scripts
  138. /// </summary>
  139. private void UnloadAppDomains()
  140. {
  141. lock (freeLock)
  142. {
  143. // Go through all
  144. foreach (AppDomainStructure ads in new ArrayList(appDomains))
  145. {
  146. // Don't process current AppDomain
  147. if (ads.CurrentAppDomain != currentAD.CurrentAppDomain)
  148. {
  149. // Not current AppDomain
  150. // Is number of unloaded bigger or equal to number of loaded?
  151. if (ads.ScriptsLoaded <= ads.ScriptsWaitingUnload)
  152. {
  153. // Remove from internal list
  154. appDomains.Remove(ads);
  155. //#if DEBUG
  156. //Console.WriteLine("Found empty AppDomain, unloading");
  157. //long m = GC.GetTotalMemory(true); // This force a garbage collect that freezes some windows plateforms
  158. //#endif
  159. // Unload
  160. AppDomain.Unload(ads.CurrentAppDomain);
  161. //#if DEBUG
  162. //m_scriptEngine.Log.Info("[" + m_scriptEngine.ScriptEngineName + "]: AppDomain unload freed " + (m - GC.GetTotalMemory(true)) + " bytes of memory");
  163. //#endif
  164. }
  165. }
  166. }
  167. }
  168. }
  169. public IScript LoadScript(string FileName)
  170. {
  171. // Find next available AppDomain to put it in
  172. AppDomainStructure FreeAppDomain = GetFreeAppDomain();
  173. #if DEBUG
  174. m_scriptEngine.Log.Info("[" + m_scriptEngine.ScriptEngineName + "]: Loading into AppDomain: " + FileName);
  175. #endif
  176. IScript mbrt =
  177. (IScript)
  178. FreeAppDomain.CurrentAppDomain.CreateInstanceFromAndUnwrap(FileName, "SecondLife.Script");
  179. //Console.WriteLine("ScriptEngine AppDomainManager: is proxy={0}", RemotingServices.IsTransparentProxy(mbrt));
  180. FreeAppDomain.ScriptsLoaded++;
  181. return mbrt;
  182. }
  183. /// <summary>
  184. /// Increase "dead script" counter for an AppDomain
  185. /// </summary>
  186. /// <param name="ad"></param>
  187. //[Obsolete("Needs fixing, needs a real purpose in life!!!")]
  188. public void StopScript(AppDomain ad)
  189. {
  190. lock (freeLock)
  191. {
  192. #if DEBUG
  193. m_scriptEngine.Log.Info("[" + m_scriptEngine.ScriptEngineName + "]: Stopping script in AppDomain");
  194. #endif
  195. // Check if it is current AppDomain
  196. if (currentAD.CurrentAppDomain == ad)
  197. {
  198. // Yes - increase
  199. currentAD.ScriptsWaitingUnload++;
  200. return;
  201. }
  202. // Lopp through all AppDomains
  203. foreach (AppDomainStructure ads in new ArrayList(appDomains))
  204. {
  205. if (ads.CurrentAppDomain == ad)
  206. {
  207. // Found it
  208. ads.ScriptsWaitingUnload++;
  209. break;
  210. }
  211. }
  212. }
  213. UnloadAppDomains(); // Outsite lock, has its own GetLock
  214. }
  215. /// <summary>
  216. /// If set to true then threads and stuff should try to make a graceful exit
  217. /// </summary>
  218. public bool PleaseShutdown
  219. {
  220. get { return _PleaseShutdown; }
  221. set { _PleaseShutdown = value; }
  222. }
  223. private bool _PleaseShutdown = false;
  224. }
  225. }