Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveStatistics/sources/HeuristicLab.Services.Hive.Statistics/3.3/Controllers/ChartDataController.cs @ 11084

Last change on this file since 11084 was 11084, checked in by mroscoe, 10 years ago
File size: 10.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Collections.Generic;
24using System.Linq;
25using System.Web.Mvc;
26using System.Web.Script.Serialization;
27using HeuristicLab.Services.Hive.DataAccess;
28
29namespace HeuristicLab.Services.Hive.Statistics.Controllers {
30  //[OutputCache(Duration = 60 * 5)]
31  public class ChartDataController : Controller {
32    private static readonly TimeSpan DefaultDuration = new TimeSpan(1, 0, 0, 0);
33
34    public JsonResult AverageCpuUtilization(DateTime? start = null, DateTime? end = null) {
35      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString)) {
36        //If no given start date, get date of most recent record
37        if (start == null) {
38          start = GetRecentDate(db);
39        }
40        var data =
41          from facts in GetClientFacts(db, start, end)
42          select new {
43            Time = facts.Key,
44            CpuUtilization = facts.Average(x => x.CpuUtilization)
45          };
46
47        return Json(
48          CreateSeriesData(data.ToList(), x => x.Time, x => x.CpuUtilization),
49          JsonRequestBehavior.AllowGet);
50      }
51    }
52
53    public JsonResult UsedCores(DateTime? start = null, DateTime? end = null) {
54      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString)) {
55        //If no given start date, get date of most recent record
56        if (start == null) {
57          start = GetRecentDate(db);
58        }
59        var data =
60          from facts in GetClientFacts(db, start, end)
61          select new {
62            Time = facts.Key,
63            UsedCores = facts.Sum(x => x.NumUsedCores),
64            TotalCores = facts.Sum(x => x.NumTotalCores)
65          };
66
67        return Json(
68          CreateSeriesData(data.ToList(), x => x.Time, x => x.UsedCores, x => x.TotalCores),
69          JsonRequestBehavior.AllowGet);
70      }
71    }
72
73    public JsonResult UsedMemory(DateTime? start = null, DateTime? end = null) {
74      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString)) {
75        //If no given start date, get date of most recent record
76        if (start == null) {
77          start = GetRecentDate(db);
78        }
79        var data =
80          from facts in GetClientFacts(db, start, end)
81          select new {
82            Time = facts.Key,
83            UsedMemory = facts.Sum(x => x.UsedMemory),
84            TotalMemory = facts.Sum(x => x.TotalMemory)
85          };
86
87        // Return values in GB
88        return Json(
89          CreateSeriesData(data.ToList(), x => x.Time, x => x.UsedMemory / 1000, x => x.TotalMemory / 1000),
90          JsonRequestBehavior.AllowGet);
91      }
92    }
93
94    public JsonResult CurrentCores()
95    {
96      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString))
97      {
98        var currentCores = (from client in db.FactClientInfos
99                            select new { client.NumTotalCores, client.NumUsedCores })
100                            .ToList();
101
102        List<int> result = new List<int>();
103        result.Add(currentCores.Sum(c => c.NumTotalCores));
104        result.Add(currentCores.Sum(s => s.NumUsedCores));
105
106        return Json(result, JsonRequestBehavior.AllowGet);
107      }
108    }
109
110    public JsonResult CurrentCpuUtilization()
111    {
112      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString))
113      {
114        var currentCpuUtil = (from client in db.FactClientInfos
115                            select new { client.CpuUtilization })
116                            .ToList();
117
118        List<double> result = new List<double>();
119        result.Add(Math.Round(currentCpuUtil.Average(s => s.CpuUtilization), 2));
120
121        return Json(result, JsonRequestBehavior.AllowGet);
122      }
123    }
124
125    public JsonResult CurrentMemory()
126    {
127      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString))
128      {
129        var currentMemory = (from client in db.FactClientInfos
130                            select new { client.TotalMemory, client.UsedMemory })
131                            .ToList();
132
133        List<int> result = new List<int>();
134        result.Add(currentMemory.Sum(c => c.TotalMemory)/1000);
135        result.Add(currentMemory.Sum(s => s.UsedMemory)/1000);
136
137        return Json(result, JsonRequestBehavior.AllowGet);
138      }
139    }
140
141    public JsonResult UserTask(string userName, DateTime? start = null, DateTime? end = null, string jobId = null, string taskState=null)
142    {
143      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString))
144      {
145        TaskState state = GetTaskState(taskState);
146        var data =
147          (from tasks in db.FactTasks
148           join jobs in db.DimJobs
149             on tasks.JobId equals jobs.JobId
150           where jobs.UserName == userName &&
151           (!start.HasValue || tasks.StartTime >= start) &&
152           (!end.HasValue || tasks.EndTime < end) &&
153           (string.IsNullOrEmpty(jobId) || tasks.JobId.ToString() == jobId) &&
154           (string.IsNullOrEmpty(taskState) || tasks.TaskState == state)
155           select new
156           {
157             TaskID = tasks.TaskId,
158             TotalWaiting = tasks.TotalWaitingTime,
159             TotalTransfer = tasks.TotalTransferTime,
160             TotalRuntime = tasks.TotalRuntime,
161             StartDate = tasks.StartTime
162           }).OrderByDescending(s => s.StartDate).ToList();
163
164        List<KeyValuePair<string, List<double>>> results = new List<KeyValuePair<string, List<double>>>();
165
166        for (int i = 0; i < data.Count; i++) {
167          results.Add(
168            new KeyValuePair<string, List<double>>(
169              data[i].TaskID.ToString(),new List<double>{data[i].TotalWaiting,data[i].TotalTransfer,data[i].TotalRuntime}
170            ) 
171          );
172        }
173
174        return Json(results, JsonRequestBehavior.AllowGet);
175      }
176    }
177
178    public JsonResult SlaveInfo(DateTime? start = null, DateTime? end = null, string userName = null, string slaveId=null)
179    {
180      using (var db = new HiveDataContext(Settings.Default.HeuristicLab_Hive_LinqConnectionString))
181      {
182        var data =
183          (from slaves in db.FactClientInfos
184           join users in db.DimUsers
185            on slaves.UserId equals users.UserId
186           where (!start.HasValue || slaves.Time >= start) &&
187           (!end.HasValue || slaves.Time < end) &&
188           (string.IsNullOrEmpty(userName) || users.Name == userName) &&
189           (string.IsNullOrEmpty(slaveId) || slaves.ClientId.ToString() == slaveId)
190           select new
191           {
192             SlaveID = slaves.ClientId,
193             Time = slaves.Time,
194             UsedCores = slaves.NumUsedCores,
195             TotalCores = slaves.NumTotalCores,
196             UsedMemory = slaves.UsedMemory,
197             TotalMemory = slaves.TotalMemory,
198             CPUUtilization = slaves.CpuUtilization
199           }).OrderByDescending(s => s.Time).GroupBy(s => s.SlaveID).ToList();
200
201        return Json(data, JsonRequestBehavior.AllowGet);
202      }
203    }
204
205    private static TaskState GetTaskState(string taskState) {
206      TaskState state = TaskState.Finished;
207      switch (taskState)
208      {
209        case "Aborted":
210          state = TaskState.Aborted;
211          break;
212        case "Calculating":
213          state = TaskState.Calculating;
214          break;
215        case "Failed":
216          state = TaskState.Failed;
217          break;
218        case "Finished":
219          state = TaskState.Finished;
220          break;
221        case "Offline":
222          state = TaskState.Offline;
223          break;
224        case "Paused":
225          state = TaskState.Paused;
226          break;
227        case "Transferring":
228          state = TaskState.Transferring;
229          break;
230        case "Waiting":
231          state = TaskState.Waiting;
232          break;
233      }
234      return state;
235    }
236
237    private static IOrderedQueryable<IGrouping<DateTime, FactClientInfo>> GetClientFacts(HiveDataContext db, DateTime? start = null, DateTime? end = null) {
238      start = start ?? DateTime.Now - DefaultDuration;
239      end = end ?? DateTime.Now;
240
241      return from ci in db.FactClientInfos
242             where ci.Time >= start && ci.Time < end
243             group ci by ci.Time into timeGroup
244             orderby timeGroup.Key
245             select timeGroup;
246    }
247
248    private static IEnumerable<IEnumerable<object[]>> CreateSeriesData<T>(IEnumerable<T> data, Func<T, DateTime> timeSelector, params Func<T, object>[] seriesSelectors) {
249      return seriesSelectors.Select(selector =>
250        data.Select(x => new[] {
251          timeSelector(x).ToUniversalTime().ToUnixTimestamp(),
252          selector(x)
253        })
254      );
255    }
256
257    private static DateTime GetRecentDate(HiveDataContext db)
258    {
259      var mostRecent = from dates in db.FactClientInfos
260        group dates by dates.Time into startDate
261        select startDate.OrderByDescending(t=>t.Time).FirstOrDefault();
262      return mostRecent.Max(t=>t.Time);
263    }
264  }
265
266  public static class DateTimeExtensions {
267    public static long ToUnixTimestamp(this DateTime dateTime) {
268      var duration = dateTime - new DateTime(1970, 1, 1, 0, 0, 0);
269
270      return (long)duration.TotalMilliseconds;
271    }
272  }
273}
Note: See TracBrowser for help on using the repository browser.