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');
  }
}

本文标签: