2023-04-13 12:36:17 +00:00
using KubernetesWorkflow ;
2023-04-19 08:42:08 +00:00
using Logging ;
2023-04-13 12:36:17 +00:00
using NUnit.Framework ;
using NUnit.Framework.Constraints ;
using Utils ;
namespace DistTestCore.Metrics
{
public interface IMetricsAccess
{
void AssertThat ( string metricName , IResolveConstraint constraint , string message = "" ) ;
}
public class MetricsAccess : IMetricsAccess
{
2023-04-19 08:42:08 +00:00
private readonly TestLog log ;
2023-05-04 06:55:20 +00:00
private readonly ITimeSet timeSet ;
2023-04-13 12:36:17 +00:00
private readonly MetricsQuery query ;
private readonly RunningContainer node ;
2023-05-04 06:55:20 +00:00
public MetricsAccess ( TestLog log , ITimeSet timeSet , MetricsQuery query , RunningContainer node )
2023-04-13 12:36:17 +00:00
{
2023-04-19 08:42:08 +00:00
this . log = log ;
2023-05-04 06:55:20 +00:00
this . timeSet = timeSet ;
2023-04-13 12:36:17 +00:00
this . query = query ;
this . node = node ;
}
public void AssertThat ( string metricName , IResolveConstraint constraint , string message = "" )
{
2023-06-01 14:09:38 +00:00
Time . Retry ( ( ) = >
{
var metricSet = GetMetricWithTimeout ( metricName ) ;
var metricValue = metricSet . Values [ 0 ] . Value ;
2023-04-19 08:42:08 +00:00
2023-06-01 14:09:38 +00:00
log . Log ( $"{node.Name} metric '{metricName}' = {metricValue}" ) ;
2023-04-19 08:42:08 +00:00
2023-06-01 14:09:38 +00:00
Assert . That ( metricValue , constraint , message ) ;
} , nameof ( AssertThat ) ) ;
2023-04-13 12:36:17 +00:00
}
2023-04-13 13:02:51 +00:00
public Metrics ? GetAllMetrics ( )
{
return query . GetAllMetricsForNode ( node ) ;
}
2023-04-13 12:36:17 +00:00
private MetricsSet GetMetricWithTimeout ( string metricName )
{
var start = DateTime . UtcNow ;
while ( true )
{
var mostRecent = GetMostRecent ( metricName ) ;
if ( mostRecent ! = null ) return mostRecent ;
2023-05-04 06:55:20 +00:00
if ( DateTime . UtcNow - start > timeSet . WaitForMetricTimeout ( ) )
2023-04-13 12:36:17 +00:00
{
Assert . Fail ( $"Timeout: Unable to get metric '{metricName}'." ) ;
throw new TimeoutException ( ) ;
}
Time . Sleep ( TimeSpan . FromSeconds ( 2 ) ) ;
}
}
private MetricsSet ? GetMostRecent ( string metricName )
{
var result = query . GetMostRecent ( metricName , node ) ;
if ( result = = null ) return null ;
return result . Sets . LastOrDefault ( ) ;
}
}
2023-04-19 08:42:08 +00:00
public class MetricsUnavailable : IMetricsAccess
{
public void AssertThat ( string metricName , IResolveConstraint constraint , string message = "" )
{
Assert . Fail ( "Incorrect test setup: Metrics were not enabled for this group of Codex nodes. Add 'EnableMetrics()' after 'SetupCodexNodes()' to enable it." ) ;
throw new InvalidOperationException ( ) ;
}
}
2023-04-13 12:36:17 +00:00
}