using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using AyaNova.Models; using AyaNova.Api.ControllerHelpers; using AyaNova.Biz; namespace AyaNova.Api.Controllers { /// /// Server metrics /// [ApiController] [ApiVersion("8.0")] [Route("api/v{version:apiVersion}/server-metric")] [Authorize] public class ServerMetricsController : ControllerBase { private readonly AyContext ct; private readonly ILogger log; private readonly ApiServerState serverState; /// /// ctor /// /// /// /// public ServerMetricsController(AyContext dbcontext, ILogger logger, ApiServerState apiServerState) { ct = dbcontext; log = logger; serverState = apiServerState; } /// /// Get all server metrics for time period specified /// /// Required value, timespan of hours worth of records to return from current moment backwards /// Optional maximum records to return. If there are more records for the time period selected than this value the result will be downsampled using Largest-Triangle-Three-Buckets algorithm /// Snapshot of metrics [HttpGet] public async Task GetMetrics([FromQuery] int? hours, [FromQuery] int? maxRecords) { if (serverState.IsClosed) return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason)); if (!Authorized.HasReadFullRole(HttpContext.Items, AyaType.Metrics)) { return StatusCode(403, new ApiNotAuthorizedResponse()); } //use specified values or just return all maxRecords ??= int.MaxValue; List MinuteMetrics = new List(); //Query the data and downsample if required if (hours != null) { DateTime maxDate = DateTime.UtcNow.Subtract(new TimeSpan((int)hours, 0, 0, 0)); MinuteMetrics = await ct.MetricMM.AsNoTracking().Where(z => z.t > maxDate).OrderBy(z => z.t).ToListAsync(); } else { MinuteMetrics = await ct.MetricMM.AsNoTracking().OrderBy(z => z.t).ToListAsync(); } var ret = new { MetricMM = new { labels = MinuteMetrics.Select(z => z.t).ToArray(), cpu = MinuteMetrics.Select(z => z.CPU).ToArray(), gen0 = MinuteMetrics.Select(z => z.Gen0).ToArray(), gen1 = MinuteMetrics.Select(z => z.Gen1).ToArray(), gen2 = MinuteMetrics.Select(z => z.Gen2).ToArray(), allocated = MinuteMetrics.Select(z => z.Allocated).ToArray(), workingSet = MinuteMetrics.Select(z => z.WorkingSet).ToArray(), privateBytes = MinuteMetrics.Select(z => z.PrivateBytes).ToArray() } }; //Log await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserIdFromContext.Id(HttpContext.Items), 0, AyaType.Metrics, AyaEvent.Retrieved), ct); return Ok(ApiOkResponse.Response(ret)); } //------------ /* { "chartData": { "labels": [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ], "thisWeek": [ 20000, 14000, 12000, 15000, 18000, 19000, 22000 ], "lastWeek": [ 19000, 10000, 14000, 14000, 15000, 22000, 24000 ] } } */ // //split out into seperate arrays // //10 digits is epoch seconds // //List> cpu=new List>(); // var cpu = MinuteMetrics.Select(z => new Tuple(new DateTimeOffset(z.t).ToUnixTimeSeconds(), z.CPU)).ToList(); // bool DownSampled=false; // if (maxRecords < MinuteMetrics.Count) // { // cpu = Util.DataUtil.LargestTriangleThreeBuckets(cpu, (int)maxRecords) as List>; // //downsample it here // ;//https://github.com/sveinn-steinarsson/flot-downsample/ // DownSampled=true; // } // //convert to efficient array of double pairs // // var v = cpu.Select(z => new double[] { z.Item1, z.Item2 }).ToArray(); // var v = cpu.Select(z => new MetricItem { x= DateTimeOffset.FromUnixTimeSeconds((long)z.Item1), y=z.Item2 }).ToArray(); } }