Welcome to mirror list, hosted at ThFree Co, Russian Federation.

InstrumentationService.cs « MonoDevelop.Core.Instrumentation « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0cbe2dccbbef0378fc49d82c9bf9807e120a302a (plain)
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// 
// InstrumentationService.cs
//  
// Author:
//       Lluis Sanchez Gual <lluis@novell.com>
// 
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.IO;
using System.Collections.Generic;
using MonoDevelop.Core.ProgressMonitoring;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Threading;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using MonoDevelop.Core.Execution;
using Mono.Addins;

namespace MonoDevelop.Core.Instrumentation
{
	public static class InstrumentationService
	{
		static Dictionary <string, Counter> counters;
		static List<CounterCategory> categories;
		static bool enabled = true;
		static DateTime startTime;
		static int publicPort = -1;
		static Thread autoSaveThread;
		static bool stopping;
		static int autoSaveInterval;
		static List<IInstrumentationConsumer> handlers = new List<IInstrumentationConsumer> ();
		static bool handlersLoaded;
		
		static InstrumentationService ()
		{
			counters = new Dictionary <string, Counter> ();
			categories = new List<CounterCategory> ();
			startTime = DateTime.Now;
		}
		
		static void InitializeHandlers ()
		{
			if (!handlersLoaded && AddinManager.IsInitialized) {
				lock (counters) {
					handlersLoaded = true;
					AddinManager.AddExtensionNodeHandler (typeof(IInstrumentationConsumer), HandleInstrumentationHandlerExtension);
				}
			}
		}
		
		static void UpdateCounterStatus ()
		{
			lock (counters) {
				foreach (var c in counters.Values)
					c.UpdateStatus ();
			}
		}
		
		static void HandleInstrumentationHandlerExtension (object sender, ExtensionNodeEventArgs args)
		{
			var handler = (IInstrumentationConsumer)args.ExtensionObject;
			if (args.Change == ExtensionChange.Add) {
				handlers.Add (handler);
				lock (counters) {
					foreach (var c in counters.Values) {
						if (handler.SupportsCounter (c))
							c.Handlers.Add (handler);
					}
				}
			}
			else {
				handlers.Remove (handler);
				lock (counters) {
					foreach (var c in counters.Values)
						c.Handlers.Remove (handler);
				}
			}
			UpdateCounterStatus ();
		}
		
		public static int PublishService ()
		{
			RemotingService.RegisterRemotingChannel ();
			TcpChannel ch = (TcpChannel) ChannelServices.GetChannel ("tcp");
			Uri u = new Uri (ch.GetUrlsForUri ("test")[0]);
			publicPort = u.Port;
			
			InstrumentationServiceBackend backend = new InstrumentationServiceBackend ();
			System.Runtime.Remoting.RemotingServices.Marshal (backend, "InstrumentationService");
			
			return publicPort;
		}
		
		public static void StartMonitor ()
		{
			if (publicPort == -1)
				throw new InvalidOperationException ("Service not published");
			
			if (Platform.IsMac) {
				var macOSDir = PropertyService.EntryAssemblyPath.ParentDirectory.ParentDirectory.ParentDirectory;
				var app = macOSDir.Combine ("MDMonitor.app");
				if (Directory.Exists (app)) {
					var psi = new ProcessStartInfo ("open", string.Format ("-n '{0}' --args -c localhost:{1} ", app, publicPort)) {
						UseShellExecute = false,
					};
					Process.Start (psi);
					return;
				}
			}	
			
			string exe = Path.Combine (Path.GetDirectoryName (Assembly.GetEntryAssembly ().Location), "mdmonitor.exe");
			string args = "-c localhost:" + publicPort;
			Runtime.SystemAssemblyService.CurrentRuntime.ExecuteAssembly (exe, args);
		}
		
		public static void StartAutoSave (string file, int interval)
		{
			autoSaveInterval = interval;
			autoSaveThread = new Thread (delegate () {
				AutoSave (file, interval);
			});
			autoSaveThread.IsBackground = true;
			autoSaveThread.Start ();
		}
		
		public static void Stop ()
		{
			stopping = true;
			if (autoSaveThread != null)
				autoSaveThread.Join (autoSaveInterval*3);
		}
		
		static void AutoSave (string file, int interval)
		{
			while (!stopping) {
				Thread.Sleep (interval);
				try {
					lock (counters) {
						InstrumentationServiceData data = new InstrumentationServiceData ();
						data.EndTime = DateTime.Now;
						data.StartTime = StartTime;
						data.Counters = counters;
						data.Categories = categories;
						FilePath path = file + ".tmp";
						using (Stream fs = File.OpenWrite (path)) {
							BinaryFormatter f = new BinaryFormatter ();
							f.Serialize (fs, data);
						}
						FileService.SystemRename (path, file);
					}
				} catch (Exception ex) {
					LoggingService.LogError ("Instrumentation service data could not be saved", ex);
				}
			}
			autoSaveThread = null;
		}
		
		public static IInstrumentationService GetRemoteService (string hostAndPort)
		{
			return (IInstrumentationService) Activator.GetObject (typeof(IInstrumentationService), "tcp://" + hostAndPort + "/InstrumentationService");
		}
		
		public static IInstrumentationService LoadServiceDataFromFile (string file)
		{
			using (Stream s = File.OpenRead (file)) {
				BinaryFormatter f = new BinaryFormatter ();
				IInstrumentationService data = f.Deserialize (s) as IInstrumentationService;
				if (data == null)
					throw new Exception ("Invalid instrumentation service data file");
				return data;
			}
		}
		
		public static bool Enabled {
			get { return enabled; }
			set {
				if (enabled == value)
					return;
				enabled = value;
				UpdateCounterStatus ();
			}
		}
		
		public static DateTime StartTime {
			get { return startTime; }
		}
		
		public static Counter CreateCounter (string name)
		{
			return CreateCounter (name, null);
		}
		
		public static Counter CreateCounter (string name, string category)
		{
			return CreateCounter (name, category, false);
		}
		
		public static Counter CreateCounter (string name, string category, bool logMessages)
		{
			return CreateCounter (name, category, logMessages, false);
		}
		
		static Counter CreateCounter (string name, string category, bool logMessages, bool isTimer)
		{
			InitializeHandlers ();
			
			if (category == null)
				category = "Global";
				
			lock (counters) {
				CounterCategory cat = GetCategory (category);
				if (cat == null) {
					cat = new CounterCategory (category);
					categories.Add (cat);
				}
				
				Counter c = isTimer ? new TimerCounter (name, cat) : new Counter (name, cat);
				c.LogMessages = logMessages;
				cat.AddCounter (c);
				
				Counter old;
				if (counters.TryGetValue (name, out old))
					old.Disposed = true;
				counters [name] = c;
				
				foreach (var h in handlers) {
					if (h.SupportsCounter (c))
						c.Handlers.Add (h);
				}
				c.UpdateStatus ();
				
				return c;
			}
		}
		
		public static MemoryProbe CreateMemoryProbe (string name)
		{
			return CreateMemoryProbe (name, null);
		}
		
		public static MemoryProbe CreateMemoryProbe (string name, string category)
		{
			if (!enabled)
				return null;
			
			Counter c;
			lock (counters) {
				if (!counters.TryGetValue (name, out c))
					c = CreateCounter (name, category);
			}
			return new MemoryProbe (c);
		}
		
		public static TimerCounter CreateTimerCounter (string name)
		{
			return CreateTimerCounter (name, null);
		}
		
		public static TimerCounter CreateTimerCounter (string name, string category)
		{
			return CreateTimerCounter (name, category, 0, false);
		}
		
		public static TimerCounter CreateTimerCounter (string name, string category, double minSeconds, bool logMessages)
		{
			TimerCounter c = (TimerCounter) CreateCounter (name, category, logMessages, true);
			c.DisplayMode = CounterDisplayMode.Line;
			c.LogMessages = logMessages;
			c.MinSeconds = minSeconds;
			return c;
		}
		
		public static IEnumerable<Counter> GetCounters ()
		{
			lock (counters) {
				return new List<Counter> (counters.Values);
			}
		}
		
		public static Counter GetCounter (string name)
		{
			lock (counters) {
				Counter c;
				if (counters.TryGetValue (name, out c))
					return c;
				c = new Counter (name, null);
				counters [name] = c;
				return c;
			}
		}
		
		public static CounterCategory GetCategory (string name)
		{
			lock (counters) {
				foreach (CounterCategory cat in categories)
					if (cat.Name == name)
						return cat;
				return null;
			}
		}
		
		public static IEnumerable<CounterCategory> GetCategories ()
		{
			lock (counters) {
				return new List<CounterCategory> (categories);
			}
		}

		[ThreadStatic]
		internal static bool IsLoggingMessage;
		
		internal static void LogMessage (string message)
		{
			IsLoggingMessage = true;
			try {
				LoggingService.LogInfo (message);
			} finally {
				IsLoggingMessage = false;
			}
		}
		
		public static void Dump ()
		{
			foreach (CounterCategory cat in categories) {
				Console.WriteLine (cat.Name);
				Console.WriteLine (new string ('-', cat.Name.Length));
				Console.WriteLine ();
				foreach (Counter c in cat.Counters)
					Console.WriteLine ("{0,-6} {1,-6} : {2}", c.Count, c.TotalCount, c.Name);
				Console.WriteLine ();
			}
		}
		
		public static IProgressMonitor GetInstrumentedMonitor (IProgressMonitor monitor, TimerCounter counter)
		{
			if (enabled) {
				AggregatedProgressMonitor mon = new AggregatedProgressMonitor (monitor);
				mon.AddSlaveMonitor (new IntrumentationMonitor (counter), MonitorAction.Tasks | MonitorAction.WriteLog);
				return mon;
			} else
				return monitor;
		}
	}
	
	class IntrumentationMonitor: NullProgressMonitor
	{
		TimerCounter counter;
		Stack<ITimeTracker> timers = new Stack<ITimeTracker> ();
		LogTextWriter logger = new LogTextWriter ();
		
		public IntrumentationMonitor (TimerCounter counter)
		{
			this.counter = counter;
			logger.TextWritten += HandleLoggerTextWritten;
		}

		void HandleLoggerTextWritten (string writtenText)
		{
			if (timers.Count > 0)
				timers.Peek ().Trace (writtenText);
		}
		
		public override void BeginTask (string name, int totalWork)
		{
			if (!string.IsNullOrEmpty (name)) {
				ITimeTracker c = counter.BeginTiming (name);
				c.Trace (name);
				timers.Push (c);
			} else {
				timers.Push (null);
			}
			base.BeginTask (name, totalWork);
		}
		
		public override void BeginStepTask (string name, int totalWork, int stepSize)
		{
			if (!string.IsNullOrEmpty (name)) {
				ITimeTracker c = counter.BeginTiming (name);
				c.Trace (name);
				timers.Push (c);
			} else {
				timers.Push (null);
			}
			base.BeginStepTask (name, totalWork, stepSize);
		}

		public override void EndTask ()
		{
			if (timers.Count > 0) {
				ITimeTracker c = timers.Pop ();
				if (c != null)
					c.End ();
			}
			base.EndTask ();
		}
		
		public override System.IO.TextWriter Log {
			get {
				return logger;
			}
		}
	}
	
	public interface IInstrumentationService
	{
		DateTime StartTime { get; }
		DateTime EndTime { get; }
		IEnumerable<Counter> GetCounters ();
		Counter GetCounter (string name);
		CounterCategory GetCategory (string name);
		IEnumerable<CounterCategory> GetCategories ();
	}
	
	class InstrumentationServiceBackend: MarshalByRefObject, IInstrumentationService
	{
		public DateTime StartTime {
			get {
				return InstrumentationService.StartTime;
			}
		}
		
		public DateTime EndTime {
			get {
				return DateTime.Now;
			}
		}

		public IEnumerable<Counter> GetCounters ()
		{
			return InstrumentationService.GetCounters ();
		}
		
		public Counter GetCounter (string name)
		{
			return InstrumentationService.GetCounter (name);
		}
		
		public CounterCategory GetCategory (string name)
		{
			return InstrumentationService.GetCategory (name);
		}
		
		public IEnumerable<CounterCategory> GetCategories ()
		{
			return InstrumentationService.GetCategories ();
		}
		
		public override object InitializeLifetimeService ()
		{
			return null;
		}
	}
	
	[Serializable]
	class InstrumentationServiceData: IInstrumentationService
	{
		public DateTime StartTime { get; set; }
		public DateTime EndTime { get; set; }
		public Dictionary <string, Counter> Counters { get; set; }
		public List<CounterCategory> Categories { get; set; }
		
		public IEnumerable<Counter> GetCounters ()
		{
			return Counters.Values;
		}
		
		public Counter GetCounter (string name)
		{
			Counter c;
			if (Counters.TryGetValue (name, out c))
				return c;
			c = new Counter (name, null);
			Counters [name] = c;
			return c;
		}
		
		public CounterCategory GetCategory (string name)
		{
			return Categories.FirstOrDefault (c => c.Name == name);
		}
		
		public IEnumerable<CounterCategory> GetCategories ()
		{
			return Categories;
		}
	}
}