Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Commit

Permalink
Merge pull request #16 from aws/achojeon1
Browse files Browse the repository at this point in the history
 Update the Spot hibernate agent to do nothing if ODH is configured
  • Loading branch information
achojeon committed Apr 25, 2023
2 parents a2d027b + e347a13 commit 2ee4ae3
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions agent/hibagent
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import os
import struct
import sys
import syslog
import requests
from subprocess import check_call, check_output
from threading import Thread
from math import ceil
Expand All @@ -39,6 +40,9 @@ SWAP_RESERVED_SIZE = 16384
log_to_syslog = True
log_to_stderr = True

IMDS_BASEURL = 'http://169.254.169.254'
IMDS_API_TOKEN_PATH = 'latest/api/token'
IMDS_SPOT_ACTION_PATH = 'latest/meta-data/hibernation/configured'

def log(message):
if log_to_syslog:
Expand Down Expand Up @@ -497,6 +501,37 @@ def adjust_pm_timeout(timeout):
log("Failed to adjust pm_freeze_timeout to %d. Error: %s" % (timeout, str(e)))
exit(1)

def get_imds_token(seconds=21600):
""" Get a token to access instance metadata. """
log("Requesting new IMDSv2 token.")
request_header = {'X-aws-ec2-metadata-token-ttl-seconds': '{}'.format(seconds)}
token_url = '{}/{}'.format(IMDS_BASEURL, IMDS_API_TOKEN_PATH)
response = requests.put(token_url, headers=request_header)
response.close()
if response.status_code != requests.codes.ok:
return None

return response.text

def hibernation_enabled():
"""Returns a boolean indicating whether hibernation-option.configured is enabled or not."""

imds_token = get_imds_token()
if imds_token is None:
log("IMDS_V2 http endpoint is disabled")
# IMDS http endpoint is disabled
return False

request_header = {'X-aws-ec2-metadata-token': imds_token}
response = requests.get("{}/{}".format(IMDS_BASEURL, IMDS_SPOT_ACTION_PATH),
headers=request_header)
response.close()
if response.status_code != requests.codes.ok or response.text.lower() == "false":
return False

log("Hibernation Configured Flag found")

return True

def main():
# Parse arguments
Expand Down Expand Up @@ -536,6 +571,11 @@ def main():

log("Effective config: %s" % config)

# Let's first check if we need to kill the Spot Hibernate Agent
if hibernation_enabled():
log("Spot Instance Launch has enabled Hibernation Configured Flag. hibagent exiting!!")
exit(0)

target_swap_size = config.swap_mb * 1024 * 1024
ram_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')
swap_percentage_size = ram_bytes * config.swap_percentage // 100
Expand Down

0 comments on commit 2ee4ae3

Please sign in to comment.