Merge ~mitchdz/ubuntu/+source/ec2-hibinit-agent:mitch/bionic-imdsv2 into ubuntu/+source/ec2-hibinit-agent:ubuntu/bionic-devel

Proposed by Mitchell Dzurick
Status: Merged
Merge reported by: Mitchell Dzurick
Merged at revision: ce10da74bcd5dd9eb436d94c0cd807520bb68126
Proposed branch: ~mitchdz/ubuntu/+source/ec2-hibinit-agent:mitch/bionic-imdsv2
Merge into: ubuntu/+source/ec2-hibinit-agent:ubuntu/bionic-devel
Diff against target: 220 lines (+192/-0)
4 files modified
debian/changelog (+10/-0)
debian/patches/lp1941785-Add-support-for-IMDSv2.patch (+161/-0)
debian/patches/lp2023924-remove-quotes-from-state-dir.patch (+19/-0)
debian/patches/series (+2/-0)
Reviewer Review Type Date Requested Status
git-ubuntu import Pending
Review via email: mp+456028@code.launchpad.net
To post a comment you must log in.
08f71e4... by Mitchell Dzurick

d/p/{lp1941785,lp2023924}*: add IMDSv2, fix quotes bug created from IMDSv2 patch

ce10da7... by Mitchell Dzurick

changelog

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/debian/changelog b/debian/changelog
2index 295da2b..2e33734 100644
3--- a/debian/changelog
4+++ b/debian/changelog
5@@ -1,3 +1,13 @@
6+ec2-hibinit-agent (1.0.0-0ubuntu4~18.04.7) bionic; urgency=medium
7+
8+ * d/p/lp2023924-remove-quotes-from-state-dir.patch: fixes an issue where a
9+ weird directory would be created in root. This was created from the IMDSv2
10+ patch (LP: #2023924)
11+ * d/p/lp1941785-Add-support-for-IMDSv2.patch: allow hibernation of
12+ AWS EC2 instances with IMDSv2 (LP: #1941785)
13+
14+ -- Mitchell Dzurick <mitchell.dzurick@canonical.com> Tue, 21 Nov 2023 15:17:59 -0700
15+
16 ec2-hibinit-agent (1.0.0-0ubuntu4~18.04.6) bionic; urgency=medium
17
18 * Swapon with maximum priority right before hibernation. This resolves
19diff --git a/debian/patches/lp1941785-Add-support-for-IMDSv2.patch b/debian/patches/lp1941785-Add-support-for-IMDSv2.patch
20new file mode 100644
21index 0000000..6855eb2
22--- /dev/null
23+++ b/debian/patches/lp1941785-Add-support-for-IMDSv2.patch
24@@ -0,0 +1,161 @@
25+Description: Add support for IMDSv2
26+Author: Frederick Lefebvre <fredlef@amazon.com>
27+Origin: backport, https://github.com/aws/amazon-ec2-hibinit-agent/commit/9d9bca5c61fa9256289e68c88bd3747af2f62e28
28+Bug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/ec2-hibinit-agent/+bug/1941785
29+Last-Update: 2023-05-16
30+---
31+This patch header follows DEP-3: http://dep.debian.net/deps/dep3/
32+--- a/agent/hibinit-agent
33++++ b/agent/hibinit-agent
34+@@ -18,6 +18,7 @@
35+ import sys
36+ import syslog
37+ import math
38++import requests
39+ from subprocess import check_call, check_output, STDOUT
40+ from threading import Thread
41+ from math import ceil
42+@@ -25,11 +26,6 @@
43+
44+
45+ try:
46+- from urllib.request import urlopen, Request
47+-except ImportError:
48+- from urllib2 import urlopen, Request, HTTPError
49+-
50+-try:
51+ from ConfigParser import ConfigParser, NoSectionError, NoOptionError
52+ except:
53+ from configparser import ConfigParser, NoSectionError, NoOptionError
54+@@ -41,7 +37,12 @@
55+ log_to_syslog = True
56+ log_to_stderr = True
57+ SWAP_FILE = '/swap-hibinit'
58+-URL = "http://169.254.169.254/latest/meta-data/hibernation/configured"
59++
60++DEFAULT_STATE_DIR = '/var/lib/hibinit-agent'
61++HIB_ENABLED_FILE = "hibernation-enabled"
62++IMDS_BASEURL = 'http://169.254.169.254'
63++IMDS_API_TOKEN_PATH = 'latest/api/token'
64++IMDS_SPOT_ACTION_PATH = 'latest/meta-data/hibernation/configured'
65+
66+ def log(message):
67+ if log_to_syslog:
68+@@ -314,6 +315,9 @@
69+ get_int('swap', 'percentage-of-ram'), args.swap_ram_percentage, 100)
70+ self.swap_mb = self.merge(
71+ get_int('swap', 'target-size-mb'), args.swap_target_size_mb, 4000)
72++ self.state_dir = get('core', 'state-dir')
73++ if self.state_dir is None:
74++ self.state_dir = DEFAULT_STATE_DIR
75+
76+
77+ def merge(self, cf_value, arg_value, def_val):
78+@@ -337,31 +341,55 @@
79+ def __str__(self):
80+ return str(self.__dict__)
81+
82+-def hibernationEnabled():
83+- """Returns a boolean indicating whether hibernation is enabled or not."""
84+- response = None
85+- try:
86+- response = urlopen(URL)
87+- data = response.read()
88+- if data.lower() in ('false', b'false'):
89+- return False
90+- except:
91+- return False
92+- finally:
93+- if response:
94+- response.close()
95+- return True
96++def get_imds_token(seconds=21600):
97++ """ Get a token to access instance metadata. """
98++ log("Requesting new IMDSv2 token.")
99++ request_header = {'X-aws-ec2-metadata-token-ttl-seconds': str(seconds)}
100++ token_url = '{}/{}'.format(IMDS_BASEURL, IMDS_API_TOKEN_PATH)
101++ response = requests.put(token_url, headers=request_header)
102++ response.close()
103++ if response.status_code != 200:
104++ return None
105++
106++ return response.text
107++
108++def create_state_dir(state_dir):
109++ """ Create agent run dir if it doesn't exists."""
110++ if not os.path.isdir(state_dir):
111++ os.makedirs(state_dir)
112++
113++def hibernation_enabled(state_dir):
114++ """Returns a boolean indicating whether hibernation is enabled or not.
115++ Hibernation can't be enabled/disabled the instance launch. If we find
116++ hibernation to be enabled, we create a semephore file so that we don't
117++ have to probe IMDS again. That is useful when a instance is rebooted
118++ after/if the IMDS http endpoint has been disabled.
119++ """
120++ hib_sem_file = os.path.join(state_dir, HIB_ENABLED_FILE)
121++ if os.path.isfile(hib_sem_file):
122++ log("Found {!r}, configuring hibernation".format(hib_sem_file))
123++ return True
124++
125++ imds_token = get_imds_token()
126++ if imds_token is None:
127++ # IMDS http endpoint is disabled
128++ return False
129++
130++ request_header = {'X-aws-ec2-metadata-token': imds_token}
131++ response = requests.get("{}/{}".format(IMDS_BASEURL, IMDS_SPOT_ACTION_PATH),
132++ headers=request_header)
133++ response.close()
134++ if response.status_code != 200 or response.text.lower() == "false":
135++ return False
136++
137++ log("Hibernation Configured Flag found")
138++ os.mknod(hib_sem_file)
139++
140++ return True
141++
142+
143+ def main():
144+
145+- if not hibernationEnabled():
146+- log("Instance Launch has not enabled Hibernation Configured Flag. hibinit-agent exiting!!")
147+- exit(0)
148+- # Validate if disk space>total RAM
149+- ram_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')
150+- if get_rootfs_size()<=(math.ceil(float(ram_bytes)/(1024*1024*1024))):
151+- log("Insufficient disk space. Cannot create setup for hibernation. Please allocate a larger root device")
152+- exit(1)
153+ # Parse arguments
154+ parser = argparse.ArgumentParser(description="An EC2 background process that creates a setup for instance hibernation "
155+ "at instance launch and also registers ACPI sleep event/actions")
156+@@ -388,6 +416,17 @@
157+ log_to_syslog = config.log_to_syslog
158+
159+ log("Effective config: %s" % config)
160++ create_state_dir(config.state_dir)
161++
162++ # Let's first check if we even need to run
163++ if not hibernation_enabled(config.state_dir):
164++ log("Instance Launch has not enabled Hibernation Configured Flag. hibinit-agent exiting!!")
165++ exit(0)
166++ # Validate if disk space>total RAM
167++ ram_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')
168++ if get_rootfs_size()<=(math.ceil(float(ram_bytes)/(1024*1024*1024))):
169++ log("Insufficient disk space. Cannot create setup for hibernation. Please allocate a larger root device")
170++ exit(1)
171+
172+ target_swap_size = config.swap_mb * 1024 * 1024
173+ swap_percentage_size = ram_bytes * config.swap_percentage // 100
174+--- a/etc/hibinit-config.cfg
175++++ b/etc/hibinit-config.cfg
176+@@ -11,6 +11,9 @@
177+ # filesystems.
178+ touch-swap = False
179+
180++# Location where to create any state files
181++state-dir = "/var/lib/hibinit-agent"
182++
183+ [swap]
184+ # If there's no swap then we create it to be equal to the specified
185+ # percentage of RAM or to the target size, whichever is greater
186diff --git a/debian/patches/lp2023924-remove-quotes-from-state-dir.patch b/debian/patches/lp2023924-remove-quotes-from-state-dir.patch
187new file mode 100644
188index 0000000..d178d21
189--- /dev/null
190+++ b/debian/patches/lp2023924-remove-quotes-from-state-dir.patch
191@@ -0,0 +1,19 @@
192+Description: Remove quotes in config file for state_dir value
193+It creates strange directory /"
194+Author: Anchal Agarwal <anchalag@amazon.com>
195+Origin: backport, https://github.com/aws/amazon-ec2-hibinit-agent/commit/d87d6365009f1663247fd8595b487c59d9b121f1
196+Bug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/ec2-hibinit-agent/+bug/2023924
197+Last-Update: 2023-06-20
198+---
199+This patch header follows DEP-3: http://dep.debian.net/deps/dep3/
200+--- a/etc/hibinit-config.cfg
201++++ b/etc/hibinit-config.cfg
202+@@ -12,7 +12,7 @@
203+ touch-swap = False
204+
205+ # Location where to create any state files
206+-state-dir = "/var/lib/hibinit-agent"
207++state-dir = /var/lib/hibinit-agent
208+
209+ [swap]
210+ # If there's no swap then we create it to be equal to the specified
211diff --git a/debian/patches/series b/debian/patches/series
212index 93ae156..1555533 100644
213--- a/debian/patches/series
214+++ b/debian/patches/series
215@@ -8,3 +8,5 @@ detect-hibernate-cmd-by-default.patch
216 0008-Always-set-resume-device-by-PARTUUID-instead-of-by-d.patch
217 0010-Update-grub-configuration-when-it-needs-an-update.patch
218 lp1968805-Swapon-with-maximum-priority-before-hibernation.patch
219+lp1941785-Add-support-for-IMDSv2.patch
220+lp2023924-remove-quotes-from-state-dir.patch

Subscribers

People subscribed via source and target branches