ec2-hibinit-agent-1.0.0/0000775070275600045350000000000013372366631016703 5ustar mockbuildmockbuild00000000000000ec2-hibinit-agent-1.0.0/setup.cfg0000664070275600045350000000004613372366631020524 0ustar mockbuildmockbuild00000000000000[egg_info] tag_build = tag_date = 0 ec2-hibinit-agent-1.0.0/acpid.sleep.conf0000644070275600045350000000025313372366623021740 0ustar mockbuildmockbuild00000000000000# ACPID config to power down machine if powerbutton is pressed, but only if # no gnome-power-manager is running event=button/sleep.* action=/etc/acpi/actions/sleep.sh %e ec2-hibinit-agent-1.0.0/LICENSE.txt0000644070275600045350000002675013372366623020537 0ustar mockbuildmockbuild00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## Runtime Library Exception to the Apache 2.0 License: ## As an exception, if you use this Software to compile your source code and portions of this Software are embedded into the binary product as a result, you may redistribute such product without providing attribution as would otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. ec2-hibinit-agent-1.0.0/README0000644070275600045350000000114713372366623017565 0ustar mockbuildmockbuild00000000000000The Amazon Linux hibernation agent. The purpose of this agent is to create a setup for an instance to support hibernation feature. The setup is created only on supported instance types. This agent does several things: 1. Upon startup it checks for sufficient swap space to allow hibernate and fails if it's present but there's not enough of it. 2. If there's no swap space, it launches a bakcground thread to create it and touch all of its blocks to make sure that EBS volumes are pre-warmed.This is configurable 3. It updates the offset of the swap file in the kernel using SNAPSHOT_SET_SWAP_AREA ioctl. ec2-hibinit-agent-1.0.0/setup.py0000644070275600045350000000141313372366623020413 0ustar mockbuildmockbuild00000000000000#!/usr/bin/python try: from setuptools import setup except ImportError: from distutils.core import setup hib_classifiers = [ "License :: OSI Approved :: APACHE SOFTWARE LICENSE", "Topic :: Utilities", ] with open("README", "r") as fp: hib_long_description = fp.read() setup(name="ec2-hibinit-agent", version='1.0.0', author="Anchal Agarwal", author_email="anchalag@amazon.com", tests_require=["pytest"], scripts=['agent/hibinit-agent'], data_files=[('/etc', ['etc/hibinit-config.cfg']), ('/etc/init.d', ['etc/init.d/hibinit-agent'])], description="Hibernation setup for EC2 Instances", long_description=hib_long_description, license="Apache 2.0", classifiers=hib_classifiers ) ec2-hibinit-agent-1.0.0/MANIFEST.in0000644070275600045350000000021313372366623020434 0ustar mockbuildmockbuild00000000000000include README LICENSE.txt include etc/hibinit-config.cfg include etc/init.d/hibinit-agent include acpid.sleep.conf include acpid.sleep.sh ec2-hibinit-agent-1.0.0/etc/0000775070275600045350000000000013372366631017456 5ustar mockbuildmockbuild00000000000000ec2-hibinit-agent-1.0.0/etc/init.d/0000775070275600045350000000000013372366631020643 5ustar mockbuildmockbuild00000000000000ec2-hibinit-agent-1.0.0/etc/init.d/hibinit-agent0000755070275600045350000000433313372366623023315 0ustar mockbuildmockbuild00000000000000#!/bin/bash # # hibinit-agent # chkconfig: 2345 26 90 # description: EC2 instance hibernation setup agent # processname: hibinit-agent # config: /etc/hibinit-config.cfg ### BEGIN INIT INFO # Provides: hibinit-agent # Required-Start: $all cloud-config # Should-Start: $time # Required-Stop: # Should-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: EC2 instance hibernation setup agent # Description: EC2 instance hibernation setup agent ### END INIT INFO # Source function library. . /etc/rc.d/init.d/functions # pull in sysconfig settings [ -f /etc/sysconfig/hibinit-agent ] && . /etc/sysconfig/hibinit-agent RETVAL=0 prog="hibinit-agent" hibinit="/usr/bin/hibinit-agent" conf="/etc/hibinit-config.cfg" start() { [ -x $hibinit ] || return 5 [ -f $conf ] || return 6 echo -n $"Starting $prog: " $hibinit -c $conf && success || failure RETVAL=$? #Restarting ACPID agent to listem on sleep signal after the installation of sleep action/event scripts echo -n $"Restarting acpid.. " /sbin/service acpid restart return $RETVAL } stop() { echo -n $"Shutting down $prog: " # No-op RETVAL=7 return $RETVAL } restart() { stop start } case "$1" in start) start RETVAL=$? ;; stop) stop RETVAL=$? ;; restart|try-restart|condrestart) ## Stop the service and regardless of whether it was ## running or not, start it again. # ## Note: try-restart is now part of LSB (as of 1.9). ## RH has a similar command named condrestart. restart RETVAL=$? ;; status) echo -n $"Checking for service $prog:" # Return value is slightly different for the status command: # 0 - service up and running # 1 - service dead, but /var/run/ pid file exists # 2 - service dead, but /var/lock/ lock file exists # 3 - service not running (unused) # 4 - service status unknown :-( # 5--199 reserved (5--99 LSB, 100--149 distro, 150--199 appl.) RETVAL=3 ;; *) echo "Usage: $0 {start|stop|status|try-restart|condrestart|restart}" RETVAL=3 ;; esac exit $RETVAL ec2-hibinit-agent-1.0.0/etc/hibinit-config.cfg0000644070275600045350000000134713372366623023034 0ustar mockbuildmockbuild00000000000000[core] log-to-syslog = True log-to-stderr = True # Automatically update GRUB config to include resume_offset for the swap file grub-update = True # Touch swap file to make sure EBS volume is pre-heated or on XFS filesystems that don't support # files with holes. # Leave out commented to automatically detect if swap touching is needed for XFS-based # filesystems. touch-swap = False [swap] # If there's no swap then we create it to be equal to the specified # percentage of RAM or to the target size, whichever is greater percentage-of-ram = 100 target-size-mb = 4000 # The command used to initialize the swap file mkswap = mkswap {swapfile} # The command used to turn on the swap swapon = swapon {swapfile} swapoff = swapoff {swapfile} ec2-hibinit-agent-1.0.0/PKG-INFO0000664070275600045350000000177713372366631020014 0ustar mockbuildmockbuild00000000000000Metadata-Version: 1.1 Name: ec2-hibinit-agent Version: 1.0.0 Summary: Hibernation setup for EC2 Instances Home-page: UNKNOWN Author: Anchal Agarwal Author-email: anchalag@amazon.com License: Apache 2.0 Description: The Amazon Linux hibernation agent. The purpose of this agent is to create a setup for an instance to support hibernation feature. The setup is created only on supported instance types. This agent does several things: 1. Upon startup it checks for sufficient swap space to allow hibernate and fails if it's present but there's not enough of it. 2. If there's no swap space, it launches a bakcground thread to create it and touch all of its blocks to make sure that EBS volumes are pre-warmed.This is configurable 3. It updates the offset of the swap file in the kernel using SNAPSHOT_SET_SWAP_AREA ioctl. Platform: UNKNOWN Classifier: License :: OSI Approved :: APACHE SOFTWARE LICENSE Classifier: Topic :: Utilities ec2-hibinit-agent-1.0.0/agent/0000775070275600045350000000000013372366631020001 5ustar mockbuildmockbuild00000000000000ec2-hibinit-agent-1.0.0/agent/hibinit-agent0000755070275600045350000003627313372366623022463 0ustar mockbuildmockbuild00000000000000#!/usr/bin/python2.7 # AWS EC2 HibInit Agent. This agent does several things: # 1. Upon startup it checks for sufficient swap space to allow hibernate and fails # if it's present but there's not enough of it. # 2. If there's no swap space, it creates it and launches a background thread to # touch all of its blocks to make sure that EBS volumes are pre-warmed. # 3. It updates the offset of the swap file in the kernel using SNAPSHOT_SET_SWAP_AREA ioctl. # # This file is compatible both with Python 2 and Python 3 import argparse import array import atexit import ctypes as ctypes import fcntl import mmap import os, signal import struct import sys import syslog import math from subprocess import check_call, check_output, STDOUT from threading import Thread from math import ceil from time import sleep try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request, HTTPError try: from ConfigParser import ConfigParser, NoSectionError, NoOptionError except: from configparser import ConfigParser, NoSectionError, NoOptionError #space reserved for swap headers SWAP_RESERVED_SIZE = 16384 log_to_syslog = True log_to_stderr = True SWAP_FILE = '/swap' URL = "http://169.254.169.254/latest/meta-data/hibernation/configured" def log(message): if log_to_syslog: syslog.syslog(message) if log_to_stderr: sys.stderr.write("%s\n" % message) def sigterm_handler(signal, frame): #save the state here or do whatever you want log('Process killed cleaning up!') if os.path.isfile(SWAP_FILE) and os.access(SWAP_FILE, os.R_OK): os.remove(SWAP_FILE) exit(0) def fallocate(fl, size): try: _libc = ctypes.CDLL('libc.so.6') _fallocate = _libc.fallocate _fallocate.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong] # (FD, mode, offset, len) res = _fallocate(fl.fileno(), 0, 0, size) if res != 0: raise Exception("Failed to perform fallocate(). Result: %d" % res) except Exception as e: log("Failed to call fallocate(), will use resize. Err: %s" % str(e)) fl.seek(size-1) fl.write(chr(0)) def get_file_block_number(filename): with open(filename, 'r') as handle: buf = array.array('L', [0]) # from linux/fs.h FIBMAP = 0x01 result = fcntl.ioctl(handle.fileno(), FIBMAP, buf) if result < 0: raise Exception("Failed to get the file offset. Error=%d" % result) return buf[0] def get_rootfs_size(): stat=os.statvfs('/') return math.ceil(float(stat.f_bsize * stat.f_blocks)/(1024*1024*1024)) def patch_grub_config(swap_device, offset): log("Updating GRUB to use the device %s with offset %d for resume" % (swap_device, offset)) cmd = "grubby --update-kernel=ALL --args='no_console_suspend resume_offset={offset} resume={swap_device}'" cmd = cmd.format(offset=offset, swap_device=swap_device) check_call(cmd, shell=True) log("GRUB configuration is updated") def update_kernel_swap_offset(swapon, swapoff, filename, grub_update): swapon = swapon.format(swapfile=filename) log("Running: %s" % swapon) check_call(swapon, shell=True) log("Updating the kernel offset for the swapfile: %s" % filename) statbuf = os.stat(filename) dev = statbuf.st_dev offset = get_file_block_number(filename) if grub_update: dev_str = find_device_for_file(filename) patch_grub_config(dev_str, offset) else: log("Skipping GRUB configuration update") log("Setting swap device to %d with offset %d" % (dev, offset)) # Set the kernel swap offset, see https://www.kernel.org/doc/Documentation/power/userland-swsusp.txt # From linux/suspend_ioctls.h SNAPSHOT_SET_SWAP_AREA = 0x400C330D buf = struct.pack('LI', offset, dev) with open('/dev/snapshot', 'r') as snap: fcntl.ioctl(snap, SNAPSHOT_SET_SWAP_AREA, buf) log("Done updating the swap offset. Turning swapoff") swapoff = swapoff.format(swapfile=filename) log("Running: %s" % swapoff) check_call(swapoff, shell=True) def find_device_for_file(filename): # Find the mount point for the swap file ('df -P /swap') df_out = check_output(['df', '-P', filename]).decode('ascii') dev_str = df_out.split("\n")[1].split()[0] return dev_str class SwapInitializer(object): def __init__(self, filename, swap_size, touch_swap, mkswap, swapoff, swapon): self.filename = filename self.swap_size = swap_size self.mkswap = mkswap self.swapoff = swapoff self.swapon = swapon self.touch_swap = touch_swap def do_allocate(self): log("Allocating %d bytes in %s" % (self.swap_size, self.filename)) with open(self.filename, 'w+') as fl: fallocate(fl, self.swap_size) os.chmod(self.filename, 0o600) def init_swap(self): """ Initialize the swap using direct IO to avoid polluting the page cache """ try: cur_swap_size = os.stat(self.filename).st_size if cur_swap_size >= self.swap_size: log("Swap file size (%d bytes) is already large enough" % cur_swap_size) if self.init_mkswap(): return except OSError: try: os.unlink(self.filename) except: pass self.do_allocate() if not self.touch_swap: log("Swap pre-heating is skipped, the swap blocks won't be touched during " "to ensure they are ready") self.init_mkswap() return written = 0 log("Opening %s for direct IO" % self.filename) fd = os.open(self.filename, os.O_RDWR | os.O_DIRECT | os.O_SYNC | os.O_DSYNC) if fd < 0: raise Exception("Failed to initialize the swap. Err: %s" % os.strerror(os.errno)) filler_block = None try: # Create a filler block that is correctly aligned for direct IO filler_block = mmap.mmap(-1, 1024 * 1024) # We're using 'b' to avoid optimizations that might happen for zero-filled pages filler_block.write(b'b' * 1024 * 1024) log("Touching all blocks in %s" % self.filename) while written < self.swap_size: res = os.write(fd, filler_block) if res <= 0: raise Exception("Failed to touch a block. Err: %s" % os.strerror(os.errno)) written += res finally: os.close(fd) if filler_block: filler_block.close() log("Swap file %s is ready" % self.filename) self.init_mkswap() def init_mkswap(self): # Do mkswap try: mkswap = self.mkswap.format(swapfile=self.filename) log("Running: %s" % mkswap) check_call(mkswap, shell=True) return True except Exception as e: log("Failed to initialize swap, reason: %s" % str(e)) return False class BackgroundInitializerRunner(object): def __init__(self, swapper, update_grub): self.swapper = swapper self.thread = None self.error = None self.update_grub = update_grub def start_init(self): try: pid = os.fork() if pid > 0: # Exit parent process sys.exit(0) except OSError, e: print >> sys.stderr, "fork failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # Configure the child processes environment os.chdir("/") os.setsid() os.umask(0022) def do_async_init(self): try: self.swapper.init_swap() update_kernel_swap_offset(self.swapper.swapon, self.swapper.swapoff, self.swapper.filename, self.update_grub) except Exception as ex: log("Failed to initialize swap, reason: %s" % str(ex)) self.error = ex def swap_needs_touch(swapfile): # Walk the parent directories of the swapfile to find on which # filesystem it's mounted swap_place = swapfile dev = None while not dev: swap_place, _ = os.path.split(swap_place) try: dev = find_device_for_file(swap_place) except: pass if swap_place == '/': raise Exception("Failed to find the filesystem type of /") with open("/proc/mounts") as fl: lines = fl.read().split("\n") for ln in lines: if dev in ln and "xfs" in ln: return True return False class Config(object): def __init__(self, config, args): def get(section, name): try: return config.get(section, name) except NoSectionError: return None except NoOptionError: return None def get_int(section, name): v = get(section, name) if v is None: return None return int(v) self.log_to_syslog = self.merge( self.to_bool(get('core', 'log-to-syslog')), self.to_bool(args.log_to_syslog), True) self.log_to_stderr = self.merge( self.to_bool(get('core', 'log-to-stderr')), self.to_bool(args.log_to_stderr), True) self.mkswap = self.merge(get('swap', 'mkswap'), args.mkswap, 'mkswap {swapfile}') self.swapon = self.merge(get('swap', 'swapon'), args.swapon, 'swapon {swapfile}') self.swapoff = self.merge(get('swap', 'swapoff'), args.swapoff, 'swapoff {swapfile}') self.touch_swap = self.merge( self.to_bool(get('core', 'touch-swap')), self.to_bool(args.touch_swap), swap_needs_touch(SWAP_FILE)) self.grub_update = self.merge( self.to_bool(get('core', 'grub-update')), self.to_bool(args.grub_update), True) self.swap_percentage = self.merge( get_int('swap', 'percentage-of-ram'), args.swap_ram_percentage, 100) self.swap_mb = self.merge( get_int('swap', 'target-size-mb'), args.swap_target_size_mb, 4000) def merge(self, cf_value, arg_value, def_val): if arg_value is not None: return arg_value if cf_value is not None: return cf_value return def_val def to_bool(self, bool_str): """Parse the string and return the boolean value encoded or raise an exception""" if bool_str is None: return None if bool_str.lower() in ['true', 't', '1']: return True elif bool_str.lower() in ['false', 'f', '0']: return False # if here we couldn't parse it raise ValueError("%s is not recognized as a boolean value" % bool_str) def __str__(self): return str(self.__dict__) def hibernationEnabled(): """Returns a boolean indicating whether hibernation is enabled or not.""" response = None try: response = urlopen(URL) data = response.read() if data.lower() == 'false': return False except: return False finally: if response: response.close() return True def main(): if not hibernationEnabled(): log("Instance Launch has not enabled Hibernation Configured Flag. hibinit-agent exiting!!") exit(0) # Validate if disk space>total RAM ram_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') if get_rootfs_size()<=(math.ceil(float(ram_bytes)/(1024*1024*1024))): log("Insufficient disk space. Cannot create setup for hibernation. Please allocate a larger root device") exit(1) # Parse arguments parser = argparse.ArgumentParser(description="An EC2 background process that creates a setup for instance hibernation " "at instance launch and also registers ACPI sleep event/actions") parser.add_argument('-c', '--config', help='Configuration file to use', type=str) parser.add_argument("-syslog", "--log-to-syslog", help='Log to syslog', type=str) parser.add_argument("-stderr", "--log-to-stderr", help='Log to stderr', type=str) parser.add_argument("-touch", "--touch-swap", help='Do swap initialization', type=str) parser.add_argument("-grub", "--grub-update", help='Update GRUB config with resume offset', type=str) parser.add_argument("-p", "--swap-ram-percentage", help='The target swap size as a percentage of RAM', type=int) parser.add_argument("-s", "--swap-target-size-mb", help='The target swap size in megabytes', type=int) parser.add_argument('--mkswap', help='The command line utility to set up swap', type=str) parser.add_argument('--swapon', help='The command line utility to turn on swap', type=str) parser.add_argument('--swapoff', help='The command line utility to turn off swap', type=str) args = parser.parse_args() config_file = ConfigParser() if args.config: config_file.read(args.config) config = Config(config_file, args) global log_to_syslog, log_to_stderr log_to_stderr = config.log_to_stderr log_to_syslog = config.log_to_syslog log("Effective config: %s" % config) target_swap_size = config.swap_mb * 1024 * 1024 swap_percentage_size = ram_bytes * config.swap_percentage // 100 if swap_percentage_size > target_swap_size: target_swap_size = int(swap_percentage_size) log("Will check if swap is at least: %d megabytes" % (target_swap_size // (1024*1024))) #Validate if swap file exists cur_swap = 0 if os.path.isfile(SWAP_FILE) and os.access(SWAP_FILE, os.R_OK): cur_swap = os.path.getsize(SWAP_FILE) bi = None if cur_swap >= target_swap_size - SWAP_RESERVED_SIZE: log("There's sufficient swap available (have %d, need %d)" % (cur_swap, target_swap_size)) update_kernel_swap_offset(config.swapon, config.swapoff, SWAP_FILE, config.grub_update) exit() #validate if instance was launched from pre-created image and swap size>=total RAM, if not re-create the swap elif cur_swap > 0 and (cur_swap < target_swap_size - SWAP_RESERVED_SIZE): log("Swap already exists! (have %d, need %d), deleting existing swap file %s" % (cur_swap, target_swap_size, SWAP_FILE)) os.remove(SWAP_FILE) log("Create swap and initialize it") # We need to create swap, but first validate that we have enough free space swap_dev = os.path.dirname(SWAP_FILE) st = os.statvfs(swap_dev) free_bytes = st.f_bavail * st.f_frsize #rounding off to swap_size+10mb for swap headers free_space_needed = target_swap_size + 10 * 1024 * 1024 if free_space_needed >= free_bytes: log("There's not enough space (%d present, %d needed) on the device: %s" % ( free_bytes, free_space_needed, swap_dev)) exit(1) log("There's enough space (%d present, %d needed) on the device: %s" % ( free_bytes, free_space_needed, swap_dev)) sw = SwapInitializer(SWAP_FILE, target_swap_size, config.touch_swap, config.mkswap, config.swapoff, config.swapon) bi = BackgroundInitializerRunner(sw, config.grub_update) signal.signal(signal.SIGTERM, sigterm_handler) if bi: bi.start_init() log("kicking child process to initiate the setup") bi.do_async_init() if __name__ == '__main__': main() ec2-hibinit-agent-1.0.0/ec2_hibinit_agent.egg-info/0000775070275600045350000000000013372366631023732 5ustar mockbuildmockbuild00000000000000ec2-hibinit-agent-1.0.0/ec2_hibinit_agent.egg-info/top_level.txt0000644070275600045350000000000113372366631026451 0ustar mockbuildmockbuild00000000000000 ec2-hibinit-agent-1.0.0/ec2_hibinit_agent.egg-info/dependency_links.txt0000644070275600045350000000000113372366631027776 0ustar mockbuildmockbuild00000000000000 ec2-hibinit-agent-1.0.0/ec2_hibinit_agent.egg-info/PKG-INFO0000644070275600045350000000177713372366631025041 0ustar mockbuildmockbuild00000000000000Metadata-Version: 1.1 Name: ec2-hibinit-agent Version: 1.0.0 Summary: Hibernation setup for EC2 Instances Home-page: UNKNOWN Author: Anchal Agarwal Author-email: anchalag@amazon.com License: Apache 2.0 Description: The Amazon Linux hibernation agent. The purpose of this agent is to create a setup for an instance to support hibernation feature. The setup is created only on supported instance types. This agent does several things: 1. Upon startup it checks for sufficient swap space to allow hibernate and fails if it's present but there's not enough of it. 2. If there's no swap space, it launches a bakcground thread to create it and touch all of its blocks to make sure that EBS volumes are pre-warmed.This is configurable 3. It updates the offset of the swap file in the kernel using SNAPSHOT_SET_SWAP_AREA ioctl. Platform: UNKNOWN Classifier: License :: OSI Approved :: APACHE SOFTWARE LICENSE Classifier: Topic :: Utilities ec2-hibinit-agent-1.0.0/ec2_hibinit_agent.egg-info/SOURCES.txt0000644070275600045350000000045713372366631025622 0ustar mockbuildmockbuild00000000000000LICENSE.txt MANIFEST.in README acpid.sleep.conf acpid.sleep.sh setup.py agent/hibinit-agent ec2_hibinit_agent.egg-info/PKG-INFO ec2_hibinit_agent.egg-info/SOURCES.txt ec2_hibinit_agent.egg-info/dependency_links.txt ec2_hibinit_agent.egg-info/top_level.txt etc/hibinit-config.cfg etc/init.d/hibinit-agentec2-hibinit-agent-1.0.0/acpid.sleep.sh0000755070275600045350000000030513372366623021426 0ustar mockbuildmockbuild00000000000000#!/bin/sh PATH=/sbin:/bin:/usr/bin case "$2" in SBTN) swapon /swap && /usr/sbin/pm-hibernate swapoff /swap ;; *) logger "ACPI action undefined: $2" ;; esac