0

我无法理解如何正确编写一个查询,该查询根据 Azure 活动日志返回 VM 运行了多长时间。下面的查询返回 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
4

1 回答 1

2

假设您有一个表 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))
于 2019-01-27T15:48:22.410 回答