Nantes Université

Skip to content
Extraits de code Groupes Projets
Valider 4d101cb3 rédigé par theovigneron's avatar theovigneron
Parcourir les fichiers

Init Repos Verification et Validation

parent 0f4ad26a
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
using Microsoft.Azure.WebJobs;
using System.Threading.Tasks;
using BoostMyMail.Core.FeatureToggling;
using BoostMyMail.Core.Managers.AppInsight;
using BoostMyMail.Core.Managers.StorageAccountManager;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using CSharpFunctionalExtensions;
using BoostMyMail.Functions.HealthCheckStatus.Models;
using BoostMyMail.Functions.HealthCheckStatus.Service;
using System;
using BoostMyMail.Core;
using BoostMyMail.Entities.Persistence;
using BoostMyMail.Entities.TenantManagement;
using Microsoft.Extensions.Configuration;
namespace BoostMyMail.Functions.HealthCheckStatus
{
public class HealthCheckStatusFunction
{
private readonly ILogger<HealthCheckStatusFunction> _logger;
private readonly FeatureManager _featureManager;
private readonly AppInsightManager _appInsightManager;
private readonly IGlobalContext _globalContext;
private readonly IEmailManager _sendGridManager;
private readonly StorageService _storageService;
private readonly DeliveryService _deliveryService;
private readonly IdentityService _identityService;
private readonly IConfiguration _configuration;
public HealthCheckStatusFunction(ILogger<HealthCheckStatusFunction> logger,
FeatureManager featureManager,
DeliveryService deliveryService,
AppInsightManager appInsightManager,
IGlobalContext globalContext,
IEmailManager sendGridManager,
StorageService storageService,
IdentityService identityService,
IConfiguration configuration
)
{
_logger = logger;
_featureManager = featureManager;
_appInsightManager = appInsightManager;
_globalContext = globalContext;
_sendGridManager = sendGridManager;
_storageService = storageService;
_deliveryService = deliveryService;
_identityService = identityService;
_configuration = configuration;
}
// TODO - trouver le bon trigger
[FunctionName("HealthCheckStatusFunction")]
public async Task<ActionResult> CheckTenantsHealthStatus()
{
Report report = new Report();
int[] arr_array = new int[] { 805, 741, 614 };
List<TenantFeatures> tenantsHavePremiumFeature = new List<TenantFeatures>();
// 1. Get Tenant in Feature Manager
foreach (int tenantId in arr_array)
{
Result<FeatureSet> resultFeature = _featureManager.GetFeatureSetForTenant(tenantId);
if (resultFeature.IsSuccess && resultFeature.Value.Features.Any(feature => feature.Key == "support-premium"))
tenantsHavePremiumFeature.Add(new TenantFeatures(tenantId, resultFeature.Value));
}
tenantsHavePremiumFeature.Where(tenant =>
{
Tenant resultTenant = _globalContext.Tenants.FirstOrDefault(t => t.Id == tenant.TenantId);
return resultTenant.O365 || resultTenant.GSuite;
});
foreach (TenantFeatures tenant in tenantsHavePremiumFeature) {
// 2. Get AppInsight Log Compile Signature
Result<AppInsightResult> appInsight = await _appInsightManager.RequestAppInsight($"traces | project timestamp , message, operation_Id | where message has 'TenantId: {tenant.TenantId}' and message has 'CompileSignatureJob' | sort by timestamp desc | take 1", "1D");
string timestampCompileSignature = appInsight.Value.Tables[0].Rows[0][0];
if (appInsight.Value.Tables[0].Rows.Count == 0)
{
report.addRow(1, "signatures not compiled since 1 day", "", Source.AppInsight, tenant.TenantId);
}
//3. Get Sync Active
Tenant resultTenant = _globalContext.Tenants.FirstOrDefault(t => t.Id == tenant.TenantId);
if (resultTenant.O365)
{
report = await CheckFeature("O365", report, tenant, timestampCompileSignature);
}
if (resultTenant.GSuite)
{
report = await CheckFeature("Gsuite", report, tenant, timestampCompileSignature);
}
}
report.GenerateFileReport();
StorageFile fileUploaded = await _storageService.UploadReportFile("./Report.json");
await _sendGridManager.SendMail(_configuration.GetValue<string>("SendGrid:SenderMail"), _configuration.GetValue<string>("SendGrid:SenderName"), "Report", fileUploaded.Url, _configuration.GetValue<string>("SendGrid:ReceiverMail"));
return new OkResult();
}
public async Task<Report> CheckFeature(string syncname, Report report, TenantFeatures tenant, string timestampCompileSignature)
{
// 2. Get AppInsight Log Sync
Result<AppInsightResult> appInsightSync = await _appInsightManager.RequestAppInsight($"traces | project timestamp , message, operation_Id | where message has 'TenantId: {tenant.TenantId}' and message has 'ISync{syncname}' | sort by timestamp desc | take 1", "1D");
if (appInsightSync.Value.Tables[0].Rows.Count == 0)
{
report.addRow(1, $"Sync{syncname} not launch since 1 day", "", Source.AppInsight, tenant.TenantId);
}
else
{
var file = await _storageService.GetContentLogsFile(tenant.TenantId, $"{syncname}JobResult.json");
foreach (User user in file.UpdatedUsers)
{
// Check if the Compile timestamp match with delivery
if (_deliveryService.hasDeliverySignature(user.UserName, DateTime.Parse(timestampCompileSignature)))
{
report.addRow(2, $"{user.UserName} has not up to date in the delivery base Sync: {syncname}", "", Source.Delivery, tenant.TenantId);
}
if (user.ActiveLicence)
{
// Check if the Sync timestamp match with Identity
if (!_identityService.hasIdentity(user.UserName))
{
report.addRow(3, $"{user.UserName} has not up to date in the identity base Sync: {syncname}", "", Source.Identity, tenant.TenantId);
}
}
}
}
return report;
}
}
}
\ No newline at end of file
using System.Collections.Generic;
namespace BoostMyMail.Functions.HealthCheckStatus.Models
{
public class LogSync
{
public int CountUserSync { get; set; }
public List<User> NewUsers { get; set; }
public List<User> UpdatedUsers { get; set; }
public List<User> FailedSyncedUsers { get; set; }
}
}
namespace BoostMyMail.Functions.HealthCheckStatus.Models
{
public enum Source
{
Identity,
Delivery,
WebJobs,
Service,
AppInsight
}
}
using BoostMyMail.Core.FeatureToggling;
namespace BoostMyMail.Functions.HealthCheckStatus.Models
{
public class TenantFeatures
{
public FeatureSet Value { get; }
public int TenantId { get; }
public TenantFeatures(int tenantId, FeatureSet value)
{
this.TenantId = tenantId;
this.Value = value;
}
}
}
namespace BoostMyMail.Functions.HealthCheckStatus.Models
{
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Origin { get; set; }
public bool ActiveLicence { get; set; }
}
}
using BoostMyMail.Functions.HealthCheckStatus.Models;
using System.Collections.Generic;
using System.Text.Json;
namespace BoostMyMail.Functions.HealthCheckStatus
{
public class Report
{
public IDictionary<int, List<ReportRow>> reportColumn;
public Report()
{
reportColumn = new Dictionary<int, List<ReportRow>>();
}
public void addRow(int Error, string Value, string AppInsightUrl, Source Source, int tenantId)
{
if (reportColumn.ContainsKey(tenantId))
{
List<ReportRow> list = reportColumn[tenantId];
list.Add(new ReportRow(1, Value, AppInsightUrl, Source));
}
else
{
List<ReportRow> list = new List<ReportRow>();
list.Add(new ReportRow(1, Value, AppInsightUrl, Source));
reportColumn.Add(tenantId, list);
}
}
public void GenerateFileReport()
{
var path = "./Report.json";
string json = JsonSerializer.Serialize(reportColumn);
System.IO.File.WriteAllText(path, json);
}
}
}
using BoostMyMail.Functions.HealthCheckStatus.Models;
using System.Runtime.Serialization;
namespace BoostMyMail.Functions.HealthCheckStatus
{
[DataContract]
public class ReportRow
{
public int Error { get; set; }
public string Value { get; set; }
public string AppInsightUrl { get; set; }
public Source Source { get; set; }
public ReportRow(int Error, string Value, string AppInsightUrl, Source Source)
{
this.Error = Error;
this.Value = Value;
this.AppInsightUrl = AppInsightUrl;
this.Source = Source;
}
}
}
using System;
using System.Data.SqlClient;
namespace BoostMyMail.Functions.HealthCheckStatus.Service
{
public class DeliveryService
{
private readonly SqlConnection _connection;
public DeliveryService(string connectionString)
{
_connection = new SqlConnection(connectionString);
_connection.Open();
}
public Boolean hasDeliverySignature(string userName, DateTime lastModify)
{
string query = $"SELECT Modified FROM delivery.BmmUserDelivery WHERE UserName = '{userName}'";
SqlCommand command = new SqlCommand(query, _connection);
using (SqlDataReader reader = command.ExecuteReader())
{
reader.Read();
if (reader.HasRows)
{
return DateTime.Compare(lastModify, DateTime.Parse(reader["Modified"].ToString())) < 0;
}
return false;
}
}
}
}
using System;
using System.Data.SqlClient;
namespace BoostMyMail.Functions.HealthCheckStatus.Service
{
public class IdentityService
{
private readonly SqlConnection _connection;
public IdentityService(string connectionString)
{
_connection = new SqlConnection(connectionString);
_connection.Open();
}
public Boolean hasIdentity(string userName)
{
string query = $"SELECT Created FROM [identity].BmmUserIdentity WHERE UserName = '{userName}'";
SqlCommand command = new SqlCommand(query, _connection);
using (SqlDataReader reader = command.ExecuteReader())
{
reader.Read();
if (reader.HasRows)
{
return true;
}
return false;
}
}
}
}
using BoostMyMail.Core.Managers.StorageAccountManager;
using BoostMyMail.Functions.HealthCheckStatus.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
namespace BoostMyMail.Functions.HealthCheckStatus.Service
{
public class StorageService
{
public readonly StorageManager _storageManager;
public StorageService(string storageUrl)
{
_storageManager = new StorageManager(storageUrl, "");
}
public async Task<LogSync> GetContentLogsFile(int tenantId,string name)
{
_storageManager.SetContainer("logs");
List<StorageFile> files = await _storageManager.GetFiles($"{tenantId}/{name}");
StorageFile file = files.First();
var content = await _storageManager.GetFileContent(file);
using (StreamReader reader = new StreamReader(content.Value))
{
string jsonData = reader.ReadToEnd();
LogSync logFile = JsonSerializer.Deserialize<LogSync>(jsonData);
return logFile;
}
}
public async Task<StorageFile> UploadReportFile(string path)
{
_storageManager.SetContainer("healthcheck");
await using var stream = File.OpenRead(path);
UploadStorageFile file = new UploadStorageFile(stream, "Report.json", "application/json");
var result = await _storageManager.UploadFile(file);
return result.Value;
}
}
}
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter