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

Commit

Permalink
Added endpoints tor retrieve perf data - IIS and AD configuration req…
Browse files Browse the repository at this point in the history
…uired
  • Loading branch information
ehrnst committed Jan 19, 2018
1 parent 00ca4f0 commit b04c2b8
Show file tree
Hide file tree
Showing 4 changed files with 352 additions and 11 deletions.
342 changes: 342 additions & 0 deletions 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

/// <summary>
/// Get RAW performance data from a specific managedEntity and metric
/// </summary>
/// <example>
/// API/Perf/5f2f477c-3b19-4ce8-b27a-eef59b9dc377?counterName=PercentMemoryUsed
/// </example>
/// <param name="managedEntityId">The guid of your managed entity, ie: windows computer</param>
/// <param name="counterName">The performance counter you want to retrieve data from</param>
/// <param name="startDate">Optionally add your start date. Data will be pulled between start and end dates</param>
/// <param name="endDate">Optionally add your start date. Data will be pulled between start and end dates</param>

[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

/// <summary>
/// Get hourly performance data from a specific managedEntity and metric
/// </summary>
/// <example>
/// API/Perf/5f2f477c-3b19-4ce8-b27a-eef59b9dc377?counterName=PercentMemoryUsed
/// </example>
/// <param name="managedEntityId">The guid of your managed entity, ie: windows computer</param>
/// <param name="counterName">The performance counter you want to retrieve data from</param>
/// <param name="startDate">Optionally add your start date. Data will be pulled between start and end dates</param>
/// <param name="endDate">Optionally add your start date. Data will be pulled between start and end dates</param>

[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

/// <summary>
/// Get daily aggragated performance data from a specific managedEntity and metric
/// </summary>
/// <example>
/// API/Perf/5f2f477c-3b19-4ce8-b27a-eef59b9dc377?counterName=PercentMemoryUsed
/// </example>
/// <param name="managedEntityId">The guid of your managed entity, ie: windows computer</param>
/// <param name="counterName">The performance counter you want to retrieve data from</param>
/// <param name="startDate">Optionally add your start date. Data will be pulled between start and end dates</param>
/// <param name="endDate">Optionally add your start date. Data will be pulled between start and end dates</param>

[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
13 changes: 7 additions & 6 deletions SCOM API/SCOM API.csproj
Expand Up @@ -119,16 +119,16 @@
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.EnterpriseManagement.Core, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>\\distr\users\aa98\PUBLIC\Microsoft.EnterpriseManagement.Core.dll</HintPath>
<HintPath>..\packages\Unofficial.Microsoft.EnterpriseManagement.OperationsManager.7.0.5000\lib\net40\Microsoft.EnterpriseManagement.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.EnterpriseManagement.OperationsManager, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>\\distr\users\aa98\PUBLIC\Microsoft.EnterpriseManagement.OperationsManager.dll</HintPath>
<HintPath>..\packages\Unofficial.Microsoft.EnterpriseManagement.OperationsManager.7.0.5000\lib\net40\Microsoft.EnterpriseManagement.OperationsManager.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.EnterpriseManagement.Runtime, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>\\distr\users\aa98\PUBLIC\Microsoft.EnterpriseManagement.Runtime.dll</HintPath>
<HintPath>..\packages\Unofficial.Microsoft.EnterpriseManagement.OperationsManager.7.0.5000\lib\net40\Microsoft.EnterpriseManagement.Runtime.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Extensions.Configuration.Abstractions.1.0.0\lib\netstandard1.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
Expand Down Expand Up @@ -270,6 +270,7 @@
<Compile Include="Controllers\SCOMComputerController.cs" />
<Compile Include="Controllers\SCOMAlertController.cs" />
<Compile Include="Controllers\SCOMAgentController.cs" />
<Compile Include="Controllers\SCOMPerfController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
Expand Down
7 changes: 2 additions & 5 deletions SCOM API/Web.config
Expand Up @@ -6,6 +6,7 @@
<configuration>
<appSettings>
<add key="ScomSdkServer" value="localhost" />
<add key="ScomDWServer" value="localhost" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
Expand All @@ -22,11 +23,7 @@
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />

<add name="ApiURIs-ISAPI-Integrated-4.0"
path="/API/*"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
<add name="ApiURIs-ISAPI-Integrated-4.0" path="/API/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Expand Down

0 comments on commit b04c2b8

Please sign in to comment.