Skip to content
This repository has been archived by the owner on Jan 24, 2022. It is now read-only.

Commit

Permalink
Merge pull request #9 from MindFlavor/netcore/3.1
Browse files Browse the repository at this point in the history
Migration to .net core 3.1
  • Loading branch information
Francesco Cogno authored Feb 26, 2020
2 parents 9a13388 + d975fbb commit 5f61d5a
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 78 deletions.
12 changes: 6 additions & 6 deletions CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,35 @@
public class CommandLineOptions
{
[JsonProperty(PropertyName = "instances")]
public List<SQLServerInstance> Instances { get; set; }
public List<SQLServerInstance> Instances { get; set; } = new List<SQLServerInstance>();

[JsonProperty(PropertyName = "port")]
public int Port { get; set; }

[JsonProperty(PropertyName = "waitStats")]
public WaitStats WaitStats { get; set; }
public WaitStats WaitStats { get; set; } = new WaitStats();

[JsonProperty(PropertyName = "performanceCounters")]
public PerformanceCounters PerformanceCounters { get; set; }
public PerformanceCounters PerformanceCounters { get; set; } = new PerformanceCounters();
}

public class PerformanceCounters
{
[JsonProperty(PropertyName = "templateFiles")]
public string[] TemplateFiles { get; set; }
public string[] TemplateFiles { get; set; } = new string[0];


}

public class SQLServerInstance
{
[JsonProperty(PropertyName = "connectionString")]
public string ConnectionString { get; set; }
public string ConnectionString { get; set; } = string.Empty;
}

public class WaitStats
{
[JsonProperty(PropertyName = "templateFiles")]
public string[] TemplateFiles { get; set; }
public string[] TemplateFiles { get; set; } = new string[0];

}
108 changes: 57 additions & 51 deletions Counters/PerformanceCounters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public override string ToString()

public class PerformanceCounters
{
private static HashSet<string> EnabledCounters { get; set; }
private static HashSet<string>? EnabledCounters { get; set; } = null;
static Dictionary<string, GrafanaPerformanceCounter> _dGraf;

public SQLServerInfo SQLServerInfo;
Expand All @@ -38,9 +38,10 @@ public class PerformanceCounters
static PerformanceCounters()
{
_dGraf = new Dictionary<string, GrafanaPerformanceCounter>();
using (System.IO.StreamReader sr = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MindFlavor.SQLServerExporter.embed.PerformanceCountersMapping.csv")))

using (System.IO.StreamReader sr = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MindFlavor.SQLServerExporter.embed.PerformanceCountersMapping.csv")!))
{
string s;
string? s;
while ((s = sr.ReadLine()) != null)
{
string[] toks = s.Split(',');
Expand Down Expand Up @@ -71,15 +72,15 @@ public PerformanceCounters(HttpContext context, SQLServerInfo sqlServerInfo)
{
EnabledCounters = new HashSet<string>();

foreach (var file in Program.CommandLineOptions.PerformanceCounters.TemplateFiles)
foreach (var file in Program.CommandLineOptions!.PerformanceCounters.TemplateFiles)
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
logger.LogInformation($"Loading performance counter template to include from {fi.FullName}...");

using (System.IO.StreamReader sr = new System.IO.StreamReader(new System.IO.FileStream(fi.FullName,
System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)))
{
string str;
string? str;
while ((str = sr.ReadLine()) != null)
{
if (str.StartsWith("#"))
Expand All @@ -99,71 +100,76 @@ private static string KeyFromObjectNameAndCounterName(string objectName, string

public async Task<string> QueryAndSerializeData()
{
using (SqlConnection conn = new SqlConnection(this.SQLServerInfo.ConnectionString))
if (EnabledCounters == null)
throw new Exception("EnabledCounters must not be null at this phase.");
else
{
logger.LogDebug($"About to open connection to {this.SQLServerInfo.Name}");
await conn.OpenAsync();
using (SqlConnection conn = new SqlConnection(this.SQLServerInfo.ConnectionString))
{
logger.LogDebug($"About to open connection to {this.SQLServerInfo.Name}");
await conn.OpenAsync();

System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Text.StringBuilder sb = new System.Text.StringBuilder();

string tsql = TSQLStore.ProbeTSQL("performance_counters", this.SQLServerInfo);
string tsql = TSQLStore.ProbeTSQL("performance_counters", this.SQLServerInfo);

logger.LogDebug($"Probing performance counters for {this.SQLServerInfo.Name}, version {this.SQLServerInfo.Version} returned {tsql}");
logger.LogDebug($"Probing performance counters for {this.SQLServerInfo.Name}, version {this.SQLServerInfo.Version} returned {tsql}");

using (SqlCommand cmd = new SqlCommand(tsql, conn))
{
using (var reader = await cmd.ExecuteReaderAsync())
using (SqlCommand cmd = new SqlCommand(tsql, conn))
{
while (await reader.ReadAsync())
using (var reader = await cmd.ExecuteReaderAsync())
{
string objectName = reader.GetString(0).Trim();
// this will strip the prefix because is dependent on the instance
// name (like MSSQL$SQL17:Locks, MSSQL$SQL17:Databases etc...)
// and we will store the info in the instance attribute instead
int idx = objectName.IndexOf(":");
if (idx != -1)
objectName = objectName.Substring(idx + 1);

string counterName = reader.GetString(1).Trim();
string instanceName = reader.IsDBNull(2) ? null : reader.GetString(2).Trim();
long cntr_value = reader.GetInt64(3);

string key = KeyFromObjectNameAndCounterName(objectName, counterName);

GrafanaPerformanceCounter gpc;
if (_dGraf.TryGetValue(key, out gpc))
while (await reader.ReadAsync())
{
// skip this is it's not in the enabled performance counters
// as specified by the template files configured.
if (!EnabledCounters.Contains(gpc.name))
string objectName = reader.GetString(0).Trim();
// this will strip the prefix because is dependent on the instance
// name (like MSSQL$SQL17:Locks, MSSQL$SQL17:Databases etc...)
// and we will store the info in the instance attribute instead
int idx = objectName.IndexOf(":");
if (idx != -1)
objectName = objectName.Substring(idx + 1);

string counterName = reader.GetString(1).Trim();
string? instanceName = reader.IsDBNull(2) ? null : reader.GetString(2).Trim();
long cntr_value = reader.GetInt64(3);

string key = KeyFromObjectNameAndCounterName(objectName, counterName);

GrafanaPerformanceCounter gpc;
if (_dGraf.TryGetValue(key, out gpc))
{
logger.LogDebug($"PerformanceCounter {gpc} will be skipped because it's not in any configured template file");
continue;
}
// skip this is it's not in the enabled performance counters
// as specified by the template files configured.
if (!EnabledCounters.Contains(gpc.name))
{
logger.LogDebug($"PerformanceCounter {gpc} will be skipped because it's not in any configured template file");
continue;
}

string gpcName = $"sql_pc_{gpc.name}";

string gpcName = $"sql_pc_{gpc.name}";
sb.Append($"# TYPE {gpcName} {gpc.type}\n");

sb.Append($"# TYPE {gpcName} {gpc.type}\n");
string completeName = $"{gpcName}{{instance=\"{this.SQLServerInfo.Name}\"";

string completeName = $"{gpcName}{{instance=\"{this.SQLServerInfo.Name}\"";
if (!string.IsNullOrEmpty(instanceName))
{
completeName += $", counter_instance=\"{instanceName}\"";
}
completeName += "}";

if (!string.IsNullOrEmpty(instanceName))
sb.Append($"{completeName} {cntr_value.ToString()}\n");
}
else
{
completeName += $", counter_instance=\"{instanceName}\"";
logger.LogWarning($"entry {key} not mapped in the mapping file! Ignored in the output");
}
completeName += "}";

sb.Append($"{completeName} {cntr_value.ToString()}\n");
}
else
{
logger.LogWarning($"entry {key} not mapped in the mapping file! Ignored in the output");
}
}
}
}

return sb.ToString();
return sb.ToString();
}
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions Counters/WaitStats.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ public class WaitStats
public SQLServerInfo SQLServerInfo;
private ILogger<WaitStats> logger;

private static HashSet<string> Waits { get; set; }
private static string TSQLQuery { get; set; }
private static HashSet<string>? Waits { get; set; }
private static string TSQLQuery { get; set; } = string.Empty;

public WaitStats(HttpContext context, SQLServerInfo sqlServerInfo)
{
Expand All @@ -38,15 +38,15 @@ public WaitStats(HttpContext context, SQLServerInfo sqlServerInfo)
{
Waits = new HashSet<string>();

foreach (var file in Program.CommandLineOptions.WaitStats.TemplateFiles)
foreach (var file in Program.CommandLineOptions!.WaitStats.TemplateFiles)
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
logger.LogInformation($"Loading wait stats template to include from {fi.FullName}...");

using (System.IO.StreamReader sr = new System.IO.StreamReader(new System.IO.FileStream(fi.FullName,
System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)))
{
string str;
string? str;
while ((str = sr.ReadLine()) != null)
{
if (str.StartsWith("#"))
Expand Down
2 changes: 1 addition & 1 deletion FileHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static void Handler(IApplicationBuilder app)
return;
}
string s = null;
string s;
using (FileStream fs = new FileInfo("C:\\tmp\\server-metrics-collectd_rev1.json").Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(fs))
Expand Down
13 changes: 8 additions & 5 deletions MindFlavor.SQLServerExporter.csproj
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<Version>0.2.0.0</Version>
<Version>0.3.0.0</Version>
<Authors>Francesco Cogno</Authors>
<Copyright>Apache License Version 2.0</Copyright>
<PackageLicenseUrl>https://raw.githubusercontent.com/MindFlavor/prometheus_sql_server_exporter/master/LICENSE</PackageLicenseUrl>
<PackageProjectUrl>https://mindflavor.github.io/prometheus_sql_server_exporter</PackageProjectUrl>
<RepositoryUrl>https://github.com/MindFlavor/prometheus_sql_server_exporter</RepositoryUrl>
</PropertyGroup>

<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Newtonsoft.JSON" Version="12.0.1" />
<PackageReference Include="Newtonsoft.JSON" Version="12.0.3" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
</ItemGroup>

<ItemGroup>
Expand Down
10 changes: 5 additions & 5 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ namespace MindFlavor.SQLServerExporter
{
public class Program
{
public static CommandLineOptions CommandLineOptions { get; private set; }
public static CommandLineOptions? CommandLineOptions { get; private set; }
public static void Main(string[] args)
{
var assemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
System.Console.WriteLine($"Prometheus SQL Server Exporter v{assemblyVersion.ToString()}");
System.Console.WriteLine($"Prometheus SQL Server Exporter v{assemblyVersion?.ToString() ?? "no version"}");
System.Console.WriteLine($"Licensed under Apache License 2.0\n");

string configFile = null;
string? configFile = null;
for (int i = 0; (i < args.Length - 1 && configFile == null); i++)
if (args[i].ToLower() == "-c")
configFile = args[i + 1];
Expand All @@ -32,7 +32,7 @@ public static void Main(string[] args)
return;
}

string jsonContents = null;
string? jsonContents = null;
using (System.IO.StreamReader sr = new StreamReader(new System.IO.FileStream(configFile, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
jsonContents = sr.ReadToEnd();
Expand All @@ -47,7 +47,7 @@ public static void Main(string[] args)

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls($"http://*:{CommandLineOptions.Port}")
.UseUrls($"http://*:{CommandLineOptions!.Port}")
.UseStartup<Startup>();
}
}
2 changes: 1 addition & 1 deletion SQLServerHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static void Handler(IApplicationBuilder app)
List<Task> lTasks = new List<Task>();
ConcurrentBag<string> bag = new ConcurrentBag<string>();
logger.LogDebug($"Before foreach(... {Program.CommandLineOptions.Instances.Count})");
logger.LogDebug($"Before foreach(... {Program.CommandLineOptions!.Instances.Count})");
try
{
foreach (var instance in Program.CommandLineOptions.Instances)
Expand Down
6 changes: 3 additions & 3 deletions Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ public Startup(IConfiguration configuration, ILogger<Startup> logger)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
if (env.EnvironmentName == "Development")
{
app.UseDeveloperExceptionPage();
}
Expand Down
10 changes: 8 additions & 2 deletions TSQLStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,15 @@ static TSQLStore()
.Select(i =>
{
// extract stream
using (System.IO.StreamReader sr = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(i)))
System.IO.Stream? s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(i);
if (s == null)
throw new Exception($"Resource stream not found ({i})");
else
{
return new Tuple<string, string>(i, sr.ReadToEnd());
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
return new Tuple<string, string>(i, sr.ReadToEnd());
}
}
})
.Select(tuple => new Tuple<string, string>(tuple.Item1.Substring(PREFIX.Length + 1), tuple.Item2));
Expand Down

0 comments on commit 5f61d5a

Please sign in to comment.