From b04c2b8f50c7f593cefd8b441993dbd3a4f5d1ec Mon Sep 17 00:00:00 2001 From: Martin Ehrnst Date: Fri, 19 Jan 2018 19:49:37 +0100 Subject: [PATCH] Added endpoints tor retrieve perf data - IIS and AD configuration required --- SCOM API/Controllers/SCOMPerfController.cs | 342 +++++++++++++++++++++ SCOM API/SCOM API.csproj | 13 +- SCOM API/Web.config | 7 +- SCOM API/packages.config | 1 + 4 files changed, 352 insertions(+), 11 deletions(-) create mode 100644 SCOM API/Controllers/SCOMPerfController.cs diff --git a/SCOM API/Controllers/SCOMPerfController.cs b/SCOM API/Controllers/SCOMPerfController.cs new file mode 100644 index 0000000..cc724d2 --- /dev/null +++ b/SCOM API/Controllers/SCOMPerfController.cs @@ -0,0 +1,342 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Web.Http; +using System.Data.SqlClient; +using System.Configuration; +using System.Data; +using System.Text; +using Newtonsoft.Json; +using System.Data.SqlTypes; +using Microsoft.SqlServer.Server; +using System.Security.Principal; + +namespace SCOM_API.Controllers +{ + + public class SCOMPerfController : ApiController + { + SqlConnection DWConnection = new SqlConnection(); + public SCOMPerfController() + { + System.Security.Principal.WindowsImpersonationContext impersonationContext; + impersonationContext = + ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate(); + + SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); + var SCOMDW = ConfigurationManager.AppSettings["ScomDWServer"]; + builder["Data Source"] = SCOMDW; + builder["Integrated Security"] = "SSPI"; + builder["Initial Catalog"] = "OperationsManagerDW"; + + + + DWConnection.ConnectionString = builder.ConnectionString; + } + + private DataTable dataTable = new DataTable(); + + #region rawData + + /// + /// Get RAW performance data from a specific managedEntity and metric + /// + /// + /// API/Perf/5f2f477c-3b19-4ce8-b27a-eef59b9dc377?counterName=PercentMemoryUsed + /// + /// The guid of your managed entity, ie: windows computer + /// The performance counter you want to retrieve data from + /// Optionally add your start date. Data will be pulled between start and end dates + /// Optionally add your start date. Data will be pulled between start and end dates + + [HttpGet] + [Route("API/Perf/{managedEntityId:Guid}")] + public IHttpActionResult GetPerformanceData(Guid managedEntityId, string counterName, DateTime? startDate = null, DateTime? endDate = null) + { + using (WindowsImpersonationContext context = (WindowsIdentity.GetCurrent()).Impersonate()) + { + if (managedEntityId == Guid.Empty && string.IsNullOrEmpty(counterName)) + { + throw new HttpResponseException(Request + .CreateResponse(HttpStatusCode.BadRequest)); + } + + + else + { + + if (!endDate.HasValue) + { + endDate = DateTime.UtcNow; + } + + if (!startDate.HasValue) + { + startDate = (DateTime)SqlDateTime.MinValue; + } + + // Construct the actual DW sql query + string sqlQuery = @" + USE OperationsManagerDW + SELECT DateTime, SampleValue, ObjectName, InstanceName, CounterName + FROM + Perf.vPerfRaw INNER JOIN + vPerformanceRuleInstance ON Perf.vPerfRaw.PerformanceRuleInstanceRowId = vPerformanceRuleInstance.PerformanceRuleInstanceRowId INNER JOIN + vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId INNER JOIN + vRelationship ON Perf.vPerfRaw.ManagedEntityRowId = vRelationship.TargetManagedEntityRowId INNER JOIN + vManagedEntity ON vRelationship.SourceManagedEntityRowId = vManagedEntity.ManagedEntityRowId + WHERE ManagedEntityGuid = @entity + AND vPerformanceRule.CounterName = @counter + AND DateTime between @startDate and @endDate + ORDER BY Perf.vPerfRaw.DateTime DESC"; + + try + { + + // Initiate command and add parameters + + SqlCommand sqlCmd = new SqlCommand(); + sqlCmd.CommandType = CommandType.Text; + SqlParameter counter = sqlCmd.Parameters.Add("@counter", SqlDbType.VarChar, 256); + counter.Value = counterName; + sqlCmd.Parameters.AddWithValue("@entity", managedEntityId); + sqlCmd.Parameters.AddWithValue("@startDate", startDate); + sqlCmd.Parameters.AddWithValue("@endDate", endDate); + + sqlCmd.CommandText = sqlQuery; + sqlCmd.Connection = DWConnection; + + + // Connect SQL + DWConnection.Open(); + // Fill datatable with result from SQL query + SqlDataAdapter da = new SqlDataAdapter(sqlCmd); + da.Fill(dataTable); + + string jsonString = string.Empty; + jsonString = JsonConvert.SerializeObject(dataTable, Formatting.Indented); + + // Close connections and reurn data + da.Dispose(); + DWConnection.Close(); + return Ok(jsonString); + } + + catch (Exception Ex) + { + + HttpResponseMessage exeption = new HttpResponseMessage(HttpStatusCode.InternalServerError); + exeption.Content = new StringContent(Ex.ToString()); + throw new HttpResponseException(exeption); + } + } + + } + + } + + #endregion + + #region hourlyData + + /// + /// Get hourly performance data from a specific managedEntity and metric + /// + /// + /// API/Perf/5f2f477c-3b19-4ce8-b27a-eef59b9dc377?counterName=PercentMemoryUsed + /// + /// The guid of your managed entity, ie: windows computer + /// The performance counter you want to retrieve data from + /// Optionally add your start date. Data will be pulled between start and end dates + /// Optionally add your start date. Data will be pulled between start and end dates + + [HttpGet] + [Route("API/Perf/Hourly/{managedEntityId:Guid}")] + public IHttpActionResult GetHourlyPerformanceData(Guid managedEntityId, string counterName, DateTime? startDate = null, DateTime? endDate = null) + { + using (WindowsImpersonationContext context = (WindowsIdentity.GetCurrent()).Impersonate()) + { + if (managedEntityId == Guid.Empty && string.IsNullOrEmpty(counterName)) + { + throw new HttpResponseException(Request + .CreateResponse(HttpStatusCode.BadRequest)); + } + + + else + { + + if (!endDate.HasValue) + { + endDate = DateTime.UtcNow; + } + + if (!startDate.HasValue) + { + startDate = (DateTime)SqlDateTime.MinValue; + } + + // Construct the actual DW sql query + string sqlQuery = @" + USE OperationsManagerDW + SELECT DateTime, MaxValue, AverageValue, MinValue, StandardDeviation, ObjectName, InstanceName, CounterName + FROM + Perf.vPerfHourly INNER JOIN + vPerformanceRuleInstance ON Perf.vPerfHourly.PerformanceRuleInstanceRowId = vPerformanceRuleInstance.PerformanceRuleInstanceRowId INNER JOIN + vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId INNER JOIN + vRelationship ON Perf.vPerfHourly.ManagedEntityRowId = vRelationship.TargetManagedEntityRowId INNER JOIN + vManagedEntity ON vRelationship.SourceManagedEntityRowId = vManagedEntity.ManagedEntityRowId + WHERE ManagedEntityGuid = @entity + AND vPerformanceRule.CounterName = @counter + AND DateTime between @startDate and @endDate + ORDER BY Perf.vPerfHourly.DateTime DESC"; + + try + { + // Initiate command and add parameters + SqlCommand sqlCmd = new SqlCommand(); + sqlCmd.CommandType = CommandType.Text; + SqlParameter counter = sqlCmd.Parameters.Add("@counter", SqlDbType.VarChar, 256); + counter.Value = counterName; + sqlCmd.Parameters.AddWithValue("@entity", managedEntityId); + sqlCmd.Parameters.AddWithValue("@startDate", startDate); + sqlCmd.Parameters.AddWithValue("@endDate", endDate); + + sqlCmd.CommandText = sqlQuery; + sqlCmd.Connection = DWConnection; + + + // Connect SQL + DWConnection.Open(); + // Fill datatable with result from SQL query + SqlDataAdapter da = new SqlDataAdapter(sqlCmd); + da.Fill(dataTable); + + string jsonString = string.Empty; + jsonString = JsonConvert.SerializeObject(dataTable, Formatting.Indented); + + // Close connections and reurn data + da.Dispose(); + DWConnection.Close(); + return Ok(jsonString); + } + + catch (Exception Ex) + { + + HttpResponseMessage exeption = new HttpResponseMessage(HttpStatusCode.InternalServerError); + exeption.Content = new StringContent(Ex.ToString()); + throw new HttpResponseException(exeption); + } + } + + } + } + #endregion + + #region dailyData + + /// + /// Get daily aggragated performance data from a specific managedEntity and metric + /// + /// + /// API/Perf/5f2f477c-3b19-4ce8-b27a-eef59b9dc377?counterName=PercentMemoryUsed + /// + /// The guid of your managed entity, ie: windows computer + /// The performance counter you want to retrieve data from + /// Optionally add your start date. Data will be pulled between start and end dates + /// Optionally add your start date. Data will be pulled between start and end dates + + [HttpGet] + [Route("API/Perf/Daily/{managedEntityId:Guid}")] + public IHttpActionResult GetDailyPerformanceData(Guid managedEntityId, string counterName, DateTime? startDate = null, DateTime? endDate = null) + { + using (WindowsImpersonationContext context = (WindowsIdentity.GetCurrent()).Impersonate()) + { + if (managedEntityId == Guid.Empty && string.IsNullOrEmpty(counterName)) + { + throw new HttpResponseException(Request + .CreateResponse(HttpStatusCode.BadRequest)); + } + + + else + { + + if (!endDate.HasValue) + { + endDate = DateTime.UtcNow; + } + + if (!startDate.HasValue) + { + startDate = (DateTime)SqlDateTime.MinValue; + } + + // Construct the actual DW sql query + string sqlQuery = @" + USE OperationsManagerDW + SELECT DateTime, MaxValue, AverageValue, MinValue, StandardDeviation, ObjectName, InstanceName, CounterName + FROM + Perf.vPerfDaily INNER JOIN + vPerformanceRuleInstance ON Perf.vPerfDaily.PerformanceRuleInstanceRowId = vPerformanceRuleInstance.PerformanceRuleInstanceRowId INNER JOIN + vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId INNER JOIN + vRelationship ON Perf.vPerfDaily.ManagedEntityRowId = vRelationship.TargetManagedEntityRowId INNER JOIN + vManagedEntity ON vRelationship.SourceManagedEntityRowId = vManagedEntity.ManagedEntityRowId + WHERE ManagedEntityGuid = @entity + AND vPerformanceRule.CounterName = @counter + AND DateTime between @startDate and @endDate + ORDER BY Perf.vPerfDaily.DateTime DESC"; + + try + { + // Initiate command and add parameters + SqlCommand sqlCmd = new SqlCommand(); + sqlCmd.CommandType = CommandType.Text; + SqlParameter counter = sqlCmd.Parameters.Add("@counter", SqlDbType.VarChar, 256); + counter.Value = counterName; + sqlCmd.Parameters.AddWithValue("@entity", managedEntityId); + sqlCmd.Parameters.AddWithValue("@startDate", startDate); + sqlCmd.Parameters.AddWithValue("@endDate", endDate); + + sqlCmd.CommandText = sqlQuery; + sqlCmd.Connection = DWConnection; + + // Connect SQL + DWConnection.Open(); + + if (DWConnection.State == ConnectionState.Closed) + { + throw new HttpResponseException(HttpStatusCode.ServiceUnavailable); + } + + + // Fill datatable with result from SQL query + SqlDataAdapter da = new SqlDataAdapter(sqlCmd); + da.Fill(dataTable); + + string jsonString = string.Empty; + jsonString = JsonConvert.SerializeObject(dataTable, Formatting.Indented); + + // Close connections and reurn data + da.Dispose(); + DWConnection.Close(); + return Ok(jsonString); + } + + catch (Exception Ex) + { + + HttpResponseMessage exeption = new HttpResponseMessage(HttpStatusCode.InternalServerError); + exeption.Content = new StringContent(Ex.ToString()); + throw new HttpResponseException(exeption); + } + } + + } + } + #endregion + + } +} +//END diff --git a/SCOM API/SCOM API.csproj b/SCOM API/SCOM API.csproj index e138bae..a45eef0 100644 --- a/SCOM API/SCOM API.csproj +++ b/SCOM API/SCOM API.csproj @@ -119,16 +119,16 @@ True - False - \\distr\users\aa98\PUBLIC\Microsoft.EnterpriseManagement.Core.dll + ..\packages\Unofficial.Microsoft.EnterpriseManagement.OperationsManager.7.0.5000\lib\net40\Microsoft.EnterpriseManagement.Core.dll + True - False - \\distr\users\aa98\PUBLIC\Microsoft.EnterpriseManagement.OperationsManager.dll + ..\packages\Unofficial.Microsoft.EnterpriseManagement.OperationsManager.7.0.5000\lib\net40\Microsoft.EnterpriseManagement.OperationsManager.dll + True - False - \\distr\users\aa98\PUBLIC\Microsoft.EnterpriseManagement.Runtime.dll + ..\packages\Unofficial.Microsoft.EnterpriseManagement.OperationsManager.7.0.5000\lib\net40\Microsoft.EnterpriseManagement.Runtime.dll + True ..\packages\Microsoft.Extensions.Configuration.Abstractions.1.0.0\lib\netstandard1.0\Microsoft.Extensions.Configuration.Abstractions.dll @@ -270,6 +270,7 @@ + Global.asax diff --git a/SCOM API/Web.config b/SCOM API/Web.config index 5c29591..3e383f9 100644 --- a/SCOM API/Web.config +++ b/SCOM API/Web.config @@ -6,6 +6,7 @@ + @@ -22,11 +23,7 @@ - + diff --git a/SCOM API/packages.config b/SCOM API/packages.config index dea8c35..269e26b 100644 --- a/SCOM API/packages.config +++ b/SCOM API/packages.config @@ -66,5 +66,6 @@ + \ No newline at end of file