Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive-3.4/sources/HeuristicLab.Clients.Hive.Slave.Views/3.3/SlaveView.cs @ 6703

Last change on this file since 6703 was 6456, checked in by ascheibe, 14 years ago

#1233

  • fixed Admin Views plugin dependencies
  • use settings instead of magic numbers and strings
File size: 12.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Diagnostics;
24using System.Runtime.InteropServices;
25using System.Security.Principal;
26using System.ServiceProcess;
27using System.Threading;
28using System.Threading.Tasks;
29using System.Windows.Forms;
30using System.Windows.Forms.DataVisualization.Charting;
31using HeuristicLab.Clients.Hive.SlaveCore.Views.Properties;
32using HeuristicLab.Common;
33using HeuristicLab.Core.Views;
34using HeuristicLab.MainForm;
35
36
37namespace HeuristicLab.Clients.Hive.SlaveCore.Views {
38
39  [View("HeuristicLab Slave View")]
40  [Content(typeof(SlaveItem), IsDefaultView = true)]
41  public partial class SlaveView : ItemView {
42    private SlaveDisplayStat lastSlaveDisplayStat;
43    private const string serviceName = "HeuristicLab.Clients.Hive.SlaveCore.SlaveWindowsService";
44
45    private const UInt32 BCM_SETSHIELD = 0x160C;
46    [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
47    static extern int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);
48
49    public new SlaveItem Content {
50      get { return (SlaveItem)base.Content; }
51      set {
52        if (base.Content != value) {
53          base.Content = value;
54        }
55      }
56    }
57
58    public SlaveView() {
59      InitializeComponent();
60
61      if (CheckRunAsAdmin()) {
62        btnKill.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
63        btnKill.Image = HeuristicLab.Common.Resources.VSImageLibrary.BreakpointActive;
64      } else {
65        this.btnKill.FlatStyle = FlatStyle.System;
66        SendMessage(btnKill.Handle, BCM_SETSHIELD, 0, (IntPtr)1);
67      }
68
69      lblSlaveState.Text = SlaveDisplayStat.NoService.ToString();
70      lastSlaveDisplayStat = SlaveDisplayStat.NoService;
71      Content_SlaveDisplayStateChanged(this, new EventArgs<SlaveDisplayStat>(lastSlaveDisplayStat));
72    }
73
74    #region Register Content Events
75    protected override void DeregisterContentEvents() {
76      Content.SlaveShutdown -= new System.EventHandler(Content_SlaveShutdown);
77      Content.SlaveStatusChanged -= new System.EventHandler<EventArgs<StatusCommons>>(Content_SlaveStatusChanged);
78      Content.SlaveDisplayStateChanged -= new EventHandler<EventArgs<SlaveDisplayStat>>(Content_SlaveDisplayStateChanged);
79      Content.CoreConnectionChanged -= new EventHandler<EventArgs<CoreConnection>>(Content_CoreConnectionChanged);
80
81      base.DeregisterContentEvents();
82    }
83
84    protected override void RegisterContentEvents() {
85      base.RegisterContentEvents();
86
87      Content.SlaveShutdown += new System.EventHandler(Content_SlaveShutdown);
88      Content.SlaveStatusChanged += new System.EventHandler<EventArgs<StatusCommons>>(Content_SlaveStatusChanged);
89      Content.SlaveDisplayStateChanged += new EventHandler<EventArgs<SlaveDisplayStat>>(Content_SlaveDisplayStateChanged);
90      Content.CoreConnectionChanged += new EventHandler<EventArgs<CoreConnection>>(Content_CoreConnectionChanged);
91    }
92    #endregion
93
94    protected override void OnContentChanged() {
95      base.OnContentChanged();
96      btnKill.Enabled = false;
97      btnStart.Enabled = false;
98      btnStop.Enabled = false;
99
100      if (Content == null) {
101        //nothing to do...         
102      } else {
103        //try to establish a connection to the slave service
104        if (base.Content != null) {
105          ((SlaveItem)base.Content).Open();
106          Task.Factory.StartNew(Connector);
107        }
108      }
109    }
110
111    private void Connector() {
112      Content_SlaveDisplayStateChanged(this, new EventArgs<SlaveDisplayStat>(SlaveDisplayStat.NoService));
113      bool connected = false;
114      while (!connected) {
115        this.Invoke(new Func<bool>(() => connected = ((SlaveItem)base.Content).ReconnectToSlaveCore()));
116
117        if (!connected) {
118          Thread.Sleep(1000);
119        }
120      }
121      this.Invoke(new Action(SetEnabledStateOfControls));
122    }
123
124    protected override void SetEnabledStateOfControls() {
125      base.SetEnabledStateOfControls();
126      //do nothing at the moment, we have nothing editable
127    }
128
129    #region Event Handlers
130    void Content_SlaveStatusChanged(object sender, EventArgs<StatusCommons> e) {
131      RenderJobChart(e.Value);
132      RenderCoreChart(e.Value);
133    }
134
135    void Content_SlaveShutdown(object sender, System.EventArgs e) {
136      Task.Factory.StartNew(Connector);
137    }
138
139    void Content_SlaveDisplayStateChanged(object sender, EventArgs<SlaveDisplayStat> e) {
140      lblSlaveState.Text = e.Value.ToString();
141      lastSlaveDisplayStat = e.Value;
142
143      if (e.Value == SlaveDisplayStat.Asleep || e.Value == SlaveDisplayStat.NoService) {
144        btnKill.Enabled = false;
145        btnStart.Enabled = true;
146        btnStop.Enabled = false;
147      }
148
149      if (e.Value == SlaveDisplayStat.Busy || e.Value == SlaveDisplayStat.Idle || e.Value == SlaveDisplayStat.Offline) {
150        btnKill.Enabled = true;
151        btnStart.Enabled = false;
152        btnStop.Enabled = true;
153      }
154    }
155
156    void Content_CoreConnectionChanged(object sender, EventArgs<CoreConnection> e) {
157      if (e.Value == CoreConnection.Offline) {
158        btnKill.Enabled = false;
159        btnStart.Enabled = false;
160        btnStop.Enabled = false;
161      }
162    }
163    #endregion
164
165    private void RenderJobChart(StatusCommons status) {
166      jobChart.Series[0].Points.Clear();
167      jobChart.Series[1].Points.Clear();
168      jobChart.Series[2].Points.Clear();
169      jobChart.Series[3].Points.Clear();
170      jobChart.Series[4].Points.Clear();
171
172
173      DataPoint pJobs = new DataPoint(1, status.Jobs.Count);
174      DataPoint pJobsAborted = new DataPoint(2, status.JobsAborted);
175      DataPoint pJobsDone = new DataPoint(3, status.JobsFinished);
176      DataPoint pJobsFetched = new DataPoint(4, status.JobsFetched);
177      DataPoint pJobsFailed = new DataPoint(5, status.JobsFailed);
178
179      pJobs.LegendText = "Current jobs: " + status.Jobs.Count;
180      pJobs.Color = System.Drawing.Color.Yellow;
181      pJobs.ToolTip = pJobs.LegendText;
182      jobChart.Series[0].Color = System.Drawing.Color.Yellow;
183      jobChart.Series[0].LegendText = pJobs.LegendText;
184      jobChart.Series[0].Points.Add(pJobs);
185
186      pJobsAborted.LegendText = "Aborted jobs: " + status.JobsAborted;
187      pJobsAborted.Color = System.Drawing.Color.Orange;
188      pJobsAborted.ToolTip = pJobsAborted.LegendText;
189      jobChart.Series[1].Color = System.Drawing.Color.Orange;
190      jobChart.Series[1].LegendText = pJobsAborted.LegendText;
191      jobChart.Series[1].Points.Add(pJobsAborted);
192
193      pJobsDone.LegendText = "Finished jobs: " + status.JobsFinished;
194      pJobsDone.Color = System.Drawing.Color.Green;
195      pJobsDone.ToolTip = pJobsDone.LegendText;
196      jobChart.Series[2].Color = System.Drawing.Color.Green;
197      jobChart.Series[2].LegendText = pJobsDone.LegendText;
198      jobChart.Series[2].Points.Add(pJobsDone);
199
200      pJobsFetched.LegendText = "Fetched jobs: " + status.JobsFetched;
201      pJobsFetched.ToolTip = pJobsFetched.LegendText;
202      pJobsFetched.Color = System.Drawing.Color.Blue;
203      jobChart.Series[3].Color = System.Drawing.Color.Blue;
204      jobChart.Series[3].LegendText = pJobsFetched.LegendText;
205      jobChart.Series[3].Points.Add(pJobsFetched);
206
207      pJobsFailed.LegendText = "Failed jobs: " + status.JobsFailed;
208      pJobsFailed.ToolTip = pJobsFailed.LegendText;
209      pJobsFailed.Color = System.Drawing.Color.Red;
210      jobChart.Series[4].Color = System.Drawing.Color.Red;
211      jobChart.Series[4].LegendText = pJobsFailed.LegendText;
212      jobChart.Series[4].Points.Add(pJobsFailed);
213    }
214
215    private void RenderCoreChart(StatusCommons statusCommons) {
216      int usedCores = statusCommons.TotalCores - statusCommons.FreeCores;
217      DataPoint pFreeCores = new DataPoint(statusCommons.FreeCores, statusCommons.FreeCores);
218      DataPoint pUsedCores = new DataPoint(usedCores, usedCores);
219
220      coresChart.Series[0].Points.Clear();
221
222      pFreeCores.LegendText = "Free cores: " + statusCommons.FreeCores;
223      pFreeCores.Color = System.Drawing.Color.Green;
224      pUsedCores.LegendText = "Used cores: " + usedCores;
225      pUsedCores.Color = System.Drawing.Color.Red;
226
227      coresChart.Series[0].Points.Add(pFreeCores);
228      coresChart.Series[0].Points.Add(pUsedCores);
229    }
230
231    private bool CheckRunAsAdmin() {
232      bool isRunAsAdmin = false;
233      WindowsIdentity user = WindowsIdentity.GetCurrent();
234      WindowsPrincipal principal = new WindowsPrincipal(user);
235
236      try {
237        isRunAsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
238      }
239      catch { }
240      return isRunAsAdmin;
241    }
242
243    /// <summary>
244    /// Shows the windows UAC dialog and restarts tray icon app
245    /// </summary>
246    private void ElevateApplication() {
247      // launch itself as administrator
248      ProcessStartInfo proc = new ProcessStartInfo(Application.ExecutablePath, Settings.Default.ShowUICmd);
249      proc.UseShellExecute = true;
250      proc.WorkingDirectory = Environment.CurrentDirectory;
251      proc.FileName = Application.ExecutablePath;
252      proc.Verb = "runas";
253
254      try {
255        Process.Start(proc);
256      }
257      catch {
258        // user refused to allow privileges elevation       
259        return;
260      }
261      Application.Exit();
262    }
263
264    private void StartService() {
265      TimeSpan timeout = TimeSpan.FromMilliseconds(5000);
266
267      ServiceController service = new ServiceController(serviceName);
268      try {
269        if (service.Status == ServiceControllerStatus.Running) {
270          service.Stop();
271          service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
272        }
273
274        service.Start();
275        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
276      }
277      catch (InvalidOperationException ex) {
278        MessageBox.Show("Error starting service: Hive Slave Service not found!" + Environment.NewLine + ex.ToString());
279      }
280      catch (Exception ex) {
281        MessageBox.Show("Error starting service, exception is: " + Environment.NewLine + ex.ToString());
282      }
283    }
284
285    private void StopService() {
286      TimeSpan timeout = TimeSpan.FromMilliseconds(7000);
287
288      ServiceController service = new ServiceController(serviceName);
289      try {
290        if (service.Status == ServiceControllerStatus.Running) {
291          service.Stop();
292          service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
293        }
294      }
295      catch (InvalidOperationException ex) {
296        MessageBox.Show("Error starting service: Hive Slave Service not found!" + Environment.NewLine + ex.ToString());
297      }
298      catch (Exception ex) {
299        MessageBox.Show("Error starting service, exception is: " + Environment.NewLine + ex.ToString());
300      }
301    }
302
303    private void btnKill_Click(object sender, EventArgs e) {
304      if (CheckRunAsAdmin()) {
305        StopService();
306      } else {
307        ElevateApplication();
308      }
309    }
310
311    private void btnStop_Click(object sender, EventArgs e) {
312      if (Content != null) {
313        Content.Sleep();
314      }
315    }
316
317    private void btnStart_Click(object sender, EventArgs e) {
318      if (Content != null) {
319        if (lastSlaveDisplayStat == SlaveDisplayStat.Asleep) {
320          Content.RestartCore();
321        } else if (lastSlaveDisplayStat == SlaveDisplayStat.NoService) {
322          if (CheckRunAsAdmin()) {
323            StartService();
324          } else {
325            ElevateApplication();
326          }
327        }
328      }
329    }
330  }
331}
Note: See TracBrowser for help on using the repository browser.