File: DomainManager.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (298 lines) | stat: -rw-r--r-- 8,967 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org/?p=license&r=2.4
// ****************************************************************

using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Diagnostics;
using System.Security.Policy;
using NUnit.Core;

namespace NUnit.Util
{
	/// <summary>
	/// The DomainManager class handles the creation and unloading
	/// of domains as needed and keeps track of all existing domains.
	/// </summary>
	public class DomainManager : IService
	{
		#region Properties
		private static string shadowCopyPath;
		public static string ShadowCopyPath
		{
			get
			{
				if ( shadowCopyPath == null )
				{
					shadowCopyPath = ConfigurationSettings.AppSettings["shadowfiles.path"];
					if ( shadowCopyPath == "" || shadowCopyPath== null )
						shadowCopyPath = Path.Combine( Path.GetTempPath(), @"nunit20\ShadowCopyCache" );
					else
						shadowCopyPath = Environment.ExpandEnvironmentVariables(shadowCopyPath);

					// FIXME: we know that in the config file we have %temp%...
					if( shadowCopyPath.IndexOf ( "%temp%\\" ) != -1) {
						shadowCopyPath = shadowCopyPath.Replace( "%temp%\\", Path.GetTempPath() );
						if ( Path.DirectorySeparatorChar == '/' )
							shadowCopyPath = shadowCopyPath.Replace ( '\\', '/' );
					}
				}

				return shadowCopyPath;
			}
		}
		#endregion

		#region Create and Unload Domains
		/// <summary>
		/// Construct an application domain for running a test package
		/// </summary>
		/// <param name="package">The TestPackage to be run</param>
		public AppDomain CreateDomain( TestPackage package )
		{
			FileInfo testFile = new FileInfo( package.FullName );

			AppDomainSetup setup = new AppDomainSetup();

			// We always use the same application name
			setup.ApplicationName = "Tests";

			string appBase = package.BasePath;
			if ( appBase == null || appBase == string.Empty )
				appBase = testFile.DirectoryName;
			setup.ApplicationBase = appBase;

			string configFile = package.ConfigurationFile;
			if ( configFile == null || configFile == string.Empty )
				configFile = NUnitProject.IsProjectFile(testFile.Name) 
					? Path.GetFileNameWithoutExtension( testFile.Name ) + ".config"
					: testFile.Name + ".config";
			// Note: Mono needs full path to config file...
			setup.ConfigurationFile =  Path.Combine( appBase, configFile );

			string binPath = package.PrivateBinPath;
			if ( package.AutoBinPath )
				binPath = GetPrivateBinPath( appBase, package.Assemblies );
			setup.PrivateBinPath = binPath;

			if ( package.GetSetting( "ShadowCopyFiles", true ) )
			{
				setup.ShadowCopyFiles = "true";
				setup.ShadowCopyDirectories = appBase;
				setup.CachePath = GetCachePath();
			}

			string domainName = "domain-" + package.Name;
			Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
			Evidence evidence = new Evidence(baseEvidence);
			AppDomain runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);

			// Inject assembly resolver into remote domain to help locate our assemblies
			AssemblyResolver assemblyResolver = (AssemblyResolver)runnerDomain.CreateInstanceFromAndUnwrap(
				typeof(AssemblyResolver).Assembly.CodeBase,
				typeof(AssemblyResolver).FullName);

			// Tell resolver to use our core assemblies in the test domain
			assemblyResolver.AddFile( typeof( NUnit.Core.RemoteTestRunner ).Assembly.Location );
			assemblyResolver.AddFile( typeof( NUnit.Core.ITest ).Assembly.Location );

// No reference to extensions, so we do it a different way
            string moduleName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            string nunitDirPath = Path.GetDirectoryName(moduleName);
//            string coreExtensions = Path.Combine(nunitDirPath, "nunit.core.extensions.dll");
//			assemblyResolver.AddFile( coreExtensions );
            //assemblyResolver.AddFiles( nunitDirPath, "*.dll" );

            string addinsDirPath = Path.Combine(nunitDirPath, "addins");
            assemblyResolver.AddDirectory( addinsDirPath );

			// HACK: Only pass down our AddinRegistry one level so that tests of NUnit
			// itself start without any addins defined.
			if ( !IsTestDomain( AppDomain.CurrentDomain ) )
				runnerDomain.SetData("AddinRegistry", Services.AddinRegistry);

			return runnerDomain;
		}

		public void Unload( AppDomain domain )
		{
			new DomainUnloader(domain).Unload();
		}
		#endregion

		#region Nested DomainUnloader Class
		class DomainUnloader
		{
			private Thread thread;
			private AppDomain domain;

			public DomainUnloader(AppDomain domain)
			{
				this.domain = domain;
			}

			public void Unload()
			{
				thread = new Thread(new ThreadStart(UnloadOnThread));
				thread.Start();
				if (!thread.Join(20000))
				{
					Trace.WriteLine("Unable to unload AppDomain {0}", domain.FriendlyName);
					Trace.WriteLine("Unload thread timed out");
				}
			}

			private void UnloadOnThread()
			{
				bool shadowCopy = domain.ShadowCopyFiles;
				string cachePath = domain.SetupInformation.CachePath;
				string domainName = domain.FriendlyName;

    	        try
	            {
        	        AppDomain.Unload(domain);
            	}
	            catch (Exception ex)
    	        {
        	        // We assume that the tests did something bad and just leave
            	    // the orphaned AppDomain "out there". 
                	// TODO: Something useful.
	                Trace.WriteLine("Unable to unload AppDomain {0}", domainName);
    	            Trace.WriteLine(ex.ToString());
        	    }
            	finally
	            {
    	            if (shadowCopy)
        	            DeleteCacheDir(new DirectoryInfo(cachePath));
            	}
			}
		}
		#endregion

		#region Helper Methods
		/// <summary>
		/// Get the location for caching and delete any old cache info
		/// </summary>
		private string GetCachePath()
		{
            int processId = Process.GetCurrentProcess().Id;
            long ticks = DateTime.Now.Ticks;
			string cachePath = Path.Combine( ShadowCopyPath, processId.ToString() + "_" + ticks.ToString() ); 
				
			try 
			{
				DirectoryInfo dir = new DirectoryInfo(cachePath);		
				if(dir.Exists) dir.Delete(true);
			}
			catch( Exception ex)
			{
				throw new ApplicationException( 
					string.Format( "Invalid cache path: {0}",cachePath ),
					ex );
			}

			return cachePath;
		}

		/// <summary>
		/// Helper method to delete the cache dir. This method deals 
		/// with a bug that occurs when files are marked read-only
		/// and deletes each file separately in order to give better 
		/// exception information when problems occur.
		/// 
		/// TODO: This entire method is problematic. Should we be doing it?
		/// </summary>
		/// <param name="cacheDir"></param>
		private static void DeleteCacheDir( DirectoryInfo cacheDir )
		{
			//			Debug.WriteLine( "Modules:");
			//			foreach( ProcessModule module in Process.GetCurrentProcess().Modules )
			//				Debug.WriteLine( module.ModuleName );
			

			if(cacheDir.Exists)
			{
				foreach( DirectoryInfo dirInfo in cacheDir.GetDirectories() )
					DeleteCacheDir( dirInfo );

				foreach( FileInfo fileInfo in cacheDir.GetFiles() )
				{
					fileInfo.Attributes = FileAttributes.Normal;
					try 
					{
						fileInfo.Delete();
					}
					catch( Exception ex )
					{
						Debug.WriteLine( string.Format( 
							"Error deleting {0}, {1}", fileInfo.Name, ex.Message ) );
					}
				}

				cacheDir.Attributes = FileAttributes.Normal;

				try
				{
					cacheDir.Delete();
				}
				catch( Exception ex )
				{
					Debug.WriteLine( string.Format( 
						"Error deleting {0}, {1}", cacheDir.Name, ex.Message ) );
				}
			}
		}

		private bool IsTestDomain(AppDomain domain)
		{
			return domain.FriendlyName.StartsWith( "domain-" );
		}

		public static string GetPrivateBinPath( string basePath, IList assemblies )
		{
			StringBuilder sb = new StringBuilder(200);
			ArrayList dirList = new ArrayList();

			foreach( string assembly in assemblies )
			{
				string dir = PathUtils.RelativePath( basePath, Path.GetDirectoryName( assembly ) );
				if ( dir != null && dir != "." && !dirList.Contains( dir ) )
				{
					dirList.Add( dir );
					if ( sb.Length > 0 )
						sb.Append( Path.PathSeparator );
					sb.Append( dir );
				}
			}

			return sb.Length == 0 ? null : sb.ToString();
		}

		public static void DeleteShadowCopyPath()
		{
			if ( Directory.Exists( ShadowCopyPath ) )
				Directory.Delete( ShadowCopyPath, true );
		}
		#endregion

		#region IService Members

		public void UnloadService()
		{
			// TODO:  Add DomainManager.UnloadService implementation
		}

		public void InitializeService()
		{
			// TODO:  Add DomainManager.InitializeService implementation
		}

		#endregion
	}
}