如何在c#中获取实例的CPU使用率? 我已经阅读了Amazon EC2 - how to get available ram and cpu usage via AWS API?,但我无法正常工作。
NameValueCollection appConfig = ConfigurationManager.AppSettings;
var client = AWSClientFactory.CreateAmazonCloudWatchClient(
appConfig["AWSAccessKey"],
appConfig["AWSSecretKey"]
);
var dimension = new Dimension
{
Name = "InstanceId",
Value = "<i-ad20b4db>",
};
var request = new GetMetricStatisticsRequest();
request.MetricName = "CPUUtilization";
request.Period = 60;
request.Statistics.Add("Maximum");
request.Dimensions.Add(dimension);
request.Namespace = "AWS/EC2";
request.Unit = "Percent";
var currentTime = DateTime.UtcNow;
var startTime = currentTime.AddSeconds(-5);
string currentTimeString= currentTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
string startTimeString= startTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
request.StartTime = Convert.ToDateTime( startTimeString);
request.EndTime = Convert.ToDateTime(currentTimeString);
var response = client.GetMetricStatistics(request);
if ( response.GetMetricStatisticsResult.Datapoints.Count > 0)
{
var dataPoint = response.GetMetricStatisticsResult.Datapoints[0];
Console.WriteLine( "Instance: {0} CPU Max load: {1}", dimension.Value, dataPoint.Maximum);
}
答案 0 :(得分:3)
这是一个简单的概念证明,用于显示过去两天的CPU利用率。我认为每半小时会有一个数据点,但您可以通过更改GetMetricStatisticsRequest对象中Period属性的值来轻松更改。
AmazonCloudWatch cw = AWSClientFactory.CreateAmazonCloudWatchClient(accessKey, secretKey, new AmazonCloudWatchConfig().WithServiceURL("https://eu-west-1.monitoring.amazonaws.com"));
DataTable data = new DataTable();
try
{
Dimension dim = new Dimension() { Name = "InstanceId", Value = GetInstanceName(amazonInstance) };
System.Collections.Generic.List<Dimension> dimensions = new List<Dimension>() { dim };
string startTime = startTime = DateTimeOffset.Parse(DateTime.Now.AddDays(-2).ToString()).ToUniversalTime().ToString("s"); // "2010-09-29T11:00:00+01:00";
GetMetricStatisticsRequest reg = new GetMetricStatisticsRequest()
{
MeasureName = "CPUUtilization",
Period = 1800
Statistics = new System.Collections.Generic.List<string>() { "Average" },
Dimensions = dimensions,
Namespace = "AWS/EC2",
EndTime = DateTime.Now.ToUniversalTime().ToString("s"), //has to be in this format: 2010-09-29T14:00:00+01:00;
StartTime = startTime
};
var points = cw.GetMetricStatistics(reg).GetMetricStatisticsResult.Datapoints.OrderBy(p => p.Timestamp);
data.Columns.Add("Average");
data.Columns.Add("TimeStamp");
foreach (var p in points)
{
DataRow row = data.NewRow();
row["Average"] = Math.Round(p.Average, 0);
row["TimeStamp"] = DateTimeOffset.Parse(p.Timestamp).LocalDateTime.ToString("yyyy-MM-dd HH:mm");
data.Rows.Add(row);
}
}
catch (AmazonCloudWatchException ex)
{
if (ex.ErrorCode.Equals("OptInRequired"))
throw new Exception("You are not signed in for Amazon EC2.");
else
throw;
}
答案 1 :(得分:1)
这是我的最终代码,对我有用。 我在IAM aws管理控制台中添加了新用户,然后我将新的用户附加CloudWatchfullacess策略,然后我使用了这个用户Accesskey&amp;本守则中的密钥。
var cw =AWSClientFactory.CreateAmazonCloudWatchClient("AccessKey","secretkey",Amazon.RegionEndpoint.USWest2);
DataTable data = new DataTable();
try
{
Dimension dim = new Dimension() { Name = "InstanceId", Value = "InstanceId of you EC2 Server" };
System.Collections.Generic.List<Dimension> dimensions = new List<Dimension>() { dim };
string startTime1 = DateTimeOffset.Parse(DateTime.Now.AddMinutes(-60).ToString()).ToUniversalTime().ToString("s");
GetMetricStatisticsRequest reg = new GetMetricStatisticsRequest()
{
MetricName = "CPUUtilization",
Period = 60,
Statistics = new System.Collections.Generic.List<string>() { "Average","Minimum","Maximum" },
Dimensions = dimensions,
Namespace = "AWS/EC2",
EndTime = DateTime.Now, //Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString("s")), //has to be in this format: 2010-09-29T14:00:00+01:00;
StartTime = DateTime.Now.AddHours(Convert.ToInt32(-15)),// Convert.ToDateTime(startTime1),
};
var points = cw.GetMetricStatistics(reg).GetMetricStatisticsResult.Datapoints.OrderBy(p => p.Timestamp);
data.Columns.Add("Average");
data.Columns.Add("TimeStamp");
foreach (var p in points)
{
DataRow row = data.NewRow();
row["Average"] = Math.Round(p.Average, 0);
row["TimeStamp"] = p.Timestamp; //DateTimeOffset.Parse(Convert.ToDateTime(p.Timestamp)).LocalDateTime.ToString("yyyy-MM-dd HH:mm");
data.Rows.Add(row);
}
dataGridView1.DataSource = data;
}
catch (AmazonCloudWatchException ex)
{
if (ex.ErrorCode.Equals("OptInRequired"))
throw new Exception("You are not signed in for Amazon EC2.");
else
throw;
}
答案 2 :(得分:0)
请注意,当您想获得CPU使用率或任何其他类型的指标时,您应该警惕您在请求中包含的时间戳。这是因为在CloudWatch中可以使用超过48小时的数据(根据亚马逊)。
这就是为什么我个人尝试从大约3-4天前检索数据,因为有时CloudWatch不会返回任何数据,即使请求和代码都是正确的,因为它没有任何数据要从前一天发布或两个。
有关详情,请查看此网址并向下滚动至StartTime:http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html