Click here to Skip to main content
15,884,237 members
Articles / Web Development / ASP.NET

Legion: Build your own virtual super computer with Silverlight

Rate me:
Please Sign up or sign in to vote.
4.87/5 (139 votes)
27 Oct 2008LGPL321 min read 420.5K   1.1K   335  
Legion is a grid computing framework that uses the Silverlight CLR to execute user definable tasks. It provides grid-wide thread-safe operations for web clients. Client performance metrics, such as bandwidth and processor speed, may be used to tailor jobs. Also includes a WPF Manager application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Decav.Windows.Controls.LineGraph;
using Orpius.Logging;
using Orpius.GridComputing.Management.GridManagementServiceReference;

namespace Orpius.GridComputing.Management
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow
	{
		public delegate void VoidDelegate();
		readonly GridManagementServiceClient serviceClient = new GridManagementServiceClient();
		readonly DispatcherTimer timer = new DispatcherTimer();
		readonly GridAdapter graphAdapter;
		/* Used for the graphAdapter. */
		const string gflopsGraphId = "gigaFLOPS";
		const string bandwidthGraphId = "Bandwidth";
		/* Time to retrieve new graph summary in milliseconds. */
		/* TODO: make the interval time configurable. */
		const int refreshGridMs = 5000;

		public MainWindow()
		{
			InitializeComponent();
			Loaded += MainWindow_Loaded;
			Closed += MainWindow_Closed;

			graphAdapter = new GridAdapter();
			graphAdapter.TickerAdded += graphAdapter_TickerAdded;
			graphAdapter.SecurityAdded += graphAdapter_SecurityAdded;
			graphAdapter.Start();

			graphAdapter.SetBinding(TickerAdapter.GraphDurationProperty,
									new Binding("Value")
				{
					Source = TimeSlider,
					Converter = new DoubleToTimeSpanConverter(),
					ConverterParameter = TimeSpan.FromDays(2000)
				});
		}

		void MainWindow_Closed(object sender, EventArgs e)
		{
			timer.Stop();
		}

		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			Log.Info("Manager started");

			graphAdapter.AddGraph(gflopsGraphId, "gigaFLOPS");
			graphAdapter.AddGraph(bandwidthGraphId, "Bandwidth (MB/sec)");
			
			DisplayMessage("Ready");

			timer.Interval = TimeSpan.FromMilliseconds(refreshGridMs);
			timer.Tick += timer_Tick;
			timer.Start();
		}

		void DisplayMessage(string message)
		{
			listBox_Messages.Items.Add(message);
		}

		void timer_Tick(object sender, EventArgs e)
		{
			RetrieveGridSummary();
		}

		bool retrieveFailed;
		bool retrievingInfo;
		readonly object retrievingInfoLock = new object();
		
		void RetrieveGridSummary()
		{
			/* Prevent calls from backing up. */
			lock (retrievingInfoLock)
			{
				if (retrievingInfo)
				{
					return;
				}

				retrievingInfo = true;
			}

			try
			{
				//Log.Debug("Retrieving grid: " + ++retrievedCount);
				RetrieveGridSummaryAux();
			}
			catch (Exception ex)
			{
				Log.Error("Unable to retrieve GridSummary.", ex);
			}
		}

		void RetrieveGridSummaryAux()
		{
			ThreadPool.QueueUserWorkItem(delegate {
              	try
              	{
              		Client client = new Client();
              		GridSummary gridSummary;

              		try
              		{
              			gridSummary = serviceClient.GetGridSummary(client);
              		}
              		catch (Exception ex)
              		{
              			if (!retrieveFailed)
              			{
              				retrieveFailed = true;
              				string errorMessage = "Unable to retrieve grid info.";
              				Log.Error(errorMessage, ex);
							/* Must be performed on main UI thread. */
              				Dispatcher.Invoke(DispatcherPriority.Normal, 
								new VoidDelegate(() => DisplayMessage(errorMessage + "  " + ex)));
              			}
              			return;
              		}

              		if (gridSummary != null)
              		{
						/* Must be performed on main UI thread. */
              			Dispatcher.Invoke(DispatcherPriority.Normal, 
							new VoidDelegate(() => DisplayGridSummary(gridSummary)));
              		}
              	}
              	finally
              	{
              		lock (retrievingInfoLock)
              		{
              			retrievingInfo = false;
              		}
              	}
			});
		}

		void DisplayGridSummary(GridSummary gridSummary)
		{
			int agentCountTotal = 0;
			double bandwidthKBpsTotal = 0;
			long mflopsTotal = 0;
			long progressTotal = 0;
			long progressGoalTotal = 0;

			foreach (TaskSummary summary in gridSummary.TaskSummaries)
			{
				agentCountTotal += summary.AgentCount;
				bandwidthKBpsTotal += summary.BandwidthKBps > 0 ? summary.BandwidthKBps : 0;
				mflopsTotal += summary.MFlops;
				if (summary.Progress != null)
				{
					progressTotal += summary.Progress.StepsCompleted;
					progressGoalTotal += summary.Progress.StepsGoal;
				}
			}
			
			label_AgentCountTotal.Content = agentCountTotal;

			double percentComplete = 0;
			if (progressGoalTotal != 0)
			{
				percentComplete = (double)progressTotal / (double)progressGoalTotal;
			}
			label_PercentCompleteTotal.Content = string.Format("{0:0%}", percentComplete);

			try
			{
				/* Convert MFLOPS to GFLOPS. */
				graphAdapter.AddValue(gflopsGraphId, mflopsTotal / 1000);
				graphAdapter.AddValue(bandwidthGraphId, (decimal)(bandwidthKBpsTotal/1000f));
			}
			catch (Exception ex)
			{
				Log.Error("Exception thrown by Decav graph.", ex);
			}

			retrieveFailed = false;
		}

		void graphAdapter_SecurityAdded(object sender, SecurityAddedEventArgs e)
		{
			graphAdapter.CreateTicker(e.Security);
		}

		int graphRow = 0;

		void graphAdapter_TickerAdded(object sender, TickerAddedEventArgs e)
		{
			MainGrid.Children.Add(e.Ticker);
			int currentRow = graphRow++;
			int currentColumn = 0;

			e.Ticker.SetValue(Grid.RowProperty, currentRow);
			e.Ticker.SetValue(Grid.ColumnProperty, currentColumn);

			/* Stretch to fill the cell. */
			e.Ticker.Height = Double.NaN;
			e.Ticker.Width = Double.NaN;
			e.Ticker.HorizontalAlignment = HorizontalAlignment.Stretch;
			e.Ticker.VerticalAlignment = VerticalAlignment.Stretch;
			e.Ticker.Margin = new Thickness(10, 10, 10, 10);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Engineer
Switzerland Switzerland
Daniel is a former senior engineer in Technology and Research at the Office of the CTO at Microsoft, working on next generation systems.

Previously Daniel was a nine-time Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company.

Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.

Daniel is the developer behind several acclaimed mobile apps including Surfy Browser for Android and Windows Phone. Daniel is the creator of a number of popular open-source projects, most notably Codon.

Would you like Daniel to bring value to your organisation? Please contact

Blog | Twitter


Xamarin Experts
Windows 10 Experts

Comments and Discussions