我无法理解如何正确编写查询,该查询根据Azure活动日志返回VM运行了多长时间。 下面的查询返回启动虚拟机和释放虚拟机时的最新值。因此,我需要返回一个值,该值告诉我机器已运行了多长时间,或者对于VM被重新分配时的情况,该值为负值。我该怎么做呢?
AzureActivity | where TimeGenerated >= ago(30d) and OperationName == "Deallocate Virtual Machine" or OperationName == "Start Virtual Machine" and ActivityStatus == "Succeeded"
| summarize arg_max(EventSubmissionTimestamp, *) by OperationName
答案 0 :(得分:1)
假设您有一个表AzureActivity,其中包含OperationName,TimeGenerated,EventSubmissionTimestamp,MachineId,ActivityStatus列(我是从您的问题中导出的列),则可以使用下一个查询:
// Inline data for the purpose of the query demonstration
let AzureActivity = datatable(OperationName:string, TimeGenerated:datetime, EventSubmissionTimestamp:datetime, MachineId:string, ActivityStatus:string)
[
// Machine 1
'Start Virtual Machine', datetime(2019-01-27 00:00), datetime(2019-01-27 00:00), 'Machine1', 'Succeeded',
'Deallocate Virtual Machine', datetime(2019-01-27 00:00), datetime(2019-01-27 01:00), 'Machine1', 'Succeeded',
// Machine 2
'Start Virtual Machine', datetime(2019-01-27 00:00), datetime(2019-01-27 00:00), 'Machine2', 'Succeeded',
];
// Query starts here
let _data = materialize(
AzureActivity
| where TimeGenerated >= ago(30d)
and (OperationName == "Deallocate Virtual Machine" or OperationName == "Start Virtual Machine")
and ActivityStatus == "Succeeded"
| summarize arg_max(EventSubmissionTimestamp, *) by OperationName, MachineId
);
let startEvents = _data | where OperationName == 'Start Virtual Machine' | project StartTime = EventSubmissionTimestamp, MachineId;
let deallocateEvents = _data | where OperationName == 'Deallocate Virtual Machine' | project DeallocateTime = EventSubmissionTimestamp, MachineId;
startEvents | join kind = fullouter (deallocateEvents) on MachineId
| project MachineId, StartTime, DeallocateTime,
UpTime=iif(isnotnull(DeallocateTime),
(DeallocateTime-now()),
(now()-StartTime))