This commit is contained in:
2020-05-25 23:34:17 +00:00
parent d5d86cd0fa
commit 446477f20f

View File

@@ -1,9 +1,12 @@
using System.IO;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
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;
@@ -20,14 +23,14 @@ namespace AyaNova.Api.Controllers
/// </summary>
[ApiController]
[ApiVersion("8.0")]
[Route("api/v{version:apiVersion}/metric")]
[Route("api/v{version:apiVersion}/server-metric")]
[Authorize]
public class ServerMetricsController : ControllerBase
{
private readonly AyContext ct;
private readonly ILogger<LogFilesController> log;
private readonly ApiServerState serverState;
/// <summary>
/// ctor
@@ -35,21 +38,24 @@ namespace AyaNova.Api.Controllers
/// <param name="dbcontext"></param>
/// <param name="logger"></param>
/// <param name="apiServerState"></param>
public ServerMetricsController(AyContext dbcontext, ILogger<LogFilesController> logger, ApiServerState apiServerState)
{
ct = dbcontext;
log = logger;
serverState = apiServerState;
serverState = apiServerState;
}
/// <summary>
/// Get metrics as text document
/// </summary>
/// Get all server metrics for time period specified
/// </summary>
/// <param name="hours">Required value, timespan of hours worth of records to return from current moment backwards</param>
/// <param name="maxRecords">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</param>
/// <returns>Snapshot of metrics</returns>
[HttpGet("textsnapshot")]
public async Task<IActionResult> GetMetrics()
[HttpGet]
public async Task<IActionResult> GetMetrics([FromQuery, Required] int hours, [FromQuery] int? maxRecords)
{
if (serverState.IsClosed)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
@@ -59,65 +65,18 @@ namespace AyaNova.Api.Controllers
return StatusCode(403, new ApiNotAuthorizedResponse());
}
string sResult = await GetTheMetrics("plain");
//Query the data and downsample if required
var maxDate = DateTime.UtcNow.Subtract(new TimeSpan(hours, 0, 0, 0));
var MinuteMetrics = await ct.MetricMM.AsNoTracking().Where(z => z.t < maxDate).OrderBy(z => z.t).ToListAsync();
//Log
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserIdFromContext.Id(HttpContext.Items), 0, AyaType.Metrics, AyaEvent.Retrieved), ct);
return Content(sResult);
return Ok(ApiOkResponse.Response(MinuteMetrics));
}
/// <summary>
/// Get metrics as json object
/// </summary>
/// <returns>Snapshot of metrics</returns>
[HttpGet("jsonsnapshot")]
public async Task<IActionResult> GetJsonMetrics()
{
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());
}
string sResult = await GetTheMetrics("json");
JObject json = JObject.Parse(sResult);
//Log
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserIdFromContext.Id(HttpContext.Items), 0, AyaType.Metrics, AyaEvent.Retrieved), ct);
return Ok(ApiOkResponse.Response(json));
}
/// <summary>
/// Get the metrics snapshot
/// </summary>
/// <param name="format">Either "json" for json format or "plain" for plaintext format</param>
/// <returns></returns>
private async Task<string> GetTheMetrics(string format)
{
var snapshot = metrics.Snapshot.Get();
var formatters = ((IMetricsRoot)metrics).OutputMetricsFormatters;
string sResult = $"ERROR GETTING METRICS IN {format} FORMAT";
foreach (var formatter in formatters)
{
if (formatter.MediaType.Format == format)
{
using (var stream = new MemoryStream())
{
await formatter.WriteAsync(stream, snapshot);
sResult = System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
}
}
return sResult;
}
//------------