admin管理员组文章数量:1291143
Can somebody guide me in calculating the uptime of an AWS EC2 instance from the time it entered the "running" state, excluding the time spent in "pending" or "starting" states? After a lot of effort in implementing CloudWatch and other methods, it didn't come to a solution.
Currently, I have this code block which also doesn't work:
export async function retrieveEC2Status(
instance_id: string,
instance_region: string,
credentials: any,
) {
const ec2_client = new EC2Client({
region: instance_region,
credentials: credentials,
});
const command = new DescribeInstancesCommand({
InstanceIds: [instance_id],
});
try {
const response = await ec2_client.send(command);
if (
response.Reservations &&
response.Reservations.length > 0 &&
response.Reservations[0].Instances &&
response.Reservations[0].Instances.length > 0
) {
const instance = response.Reservations[0].Instances[0];
const status = instance.State.Name;
let uptimeSeconds = null;
if (status === 'running') {
const stateTransitionReason = instance.StateTransitionReason;
console.log('stateTransitionReason', stateTransitionReason);
if (
stateTransitionReason &&
stateTransitionReason.includes('User initiated')
) {
const matches = stateTransitionReason.match(/\((.*?)\)/);
const startTime = new Date(matches[1]);
uptimeSeconds = Math.floor((Date.now() - startTime.getTime()) / 1000);
console.log('uptimeSeconds | running', uptimeSeconds);
} else {
const launchTime = new Date(instance.LaunchTime);
uptimeSeconds = Math.floor(
(Date.now() - launchTime.getTime()) / 1000,
);
console.log('uptimeSeconds | launching', uptimeSeconds);
}
}
return {
ec2Status: status,
uptime: uptimeSeconds,
};
} else {
throw new Error('Instance not found');
}
} catch (error) {
throw new Error('Failed to retrieve EC2 status');
}
}
本文标签:
版权声明:本文标题:node.js - How to calculate the uptime of an AWS EC2 instance from the time it entered the "running" state? - S 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741510431a2382575.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论