├── tests ├── __init__.py ├── yum_test.yml ├── test_chef_node.json ├── test_yum_provisioner_plugin.py ├── util.py └── TestAptProvisionerPlugin.py ├── OSSMETADATA ├── aminator ├── plugins │ ├── cloud │ │ ├── __init__.py │ │ ├── default_conf │ │ │ └── aminator.plugins.cloud.ec2.yml │ │ ├── manager.py │ │ └── base.py │ ├── distro │ │ ├── __init__.py │ │ ├── default_conf │ │ │ ├── aminator.plugins.distro.redhat.yml │ │ │ └── aminator.plugins.distro.debian.yml │ │ ├── redhat.py │ │ ├── manager.py │ │ ├── base.py │ │ ├── debian.py │ │ └── linux.py │ ├── finalizer │ │ ├── __init__.py │ │ ├── default_conf │ │ │ ├── aminator.plugins.finalizer.tagging_ebs.yml │ │ │ └── aminator.plugins.finalizer.tagging_s3.yml │ │ ├── manager.py │ │ ├── base.py │ │ ├── tagging_ebs.py │ │ ├── tagging_base.py │ │ └── tagging_s3.py │ ├── metrics │ │ ├── __init__.py │ │ ├── default_conf │ │ │ └── aminator.plugins.metrics.logger.yml │ │ ├── manager.py │ │ ├── logger.py │ │ └── base.py │ ├── volume │ │ ├── __init__.py │ │ ├── default_conf │ │ │ └── aminator.plugins.volume.linux.yml │ │ ├── manager.py │ │ ├── base.py │ │ └── linux.py │ ├── blockdevice │ │ ├── __init__.py │ │ ├── default_conf │ │ │ ├── aminator.plugins.blockdevice.null.yml │ │ │ └── aminator.plugins.blockdevice.linux.yml │ │ ├── manager.py │ │ ├── null.py │ │ ├── base.py │ │ └── linux.py │ ├── provisioner │ │ ├── __init__.py │ │ ├── default_conf │ │ │ ├── aminator.plugins.provisioner.yum.yml │ │ │ ├── aminator.plugins.provisioner.apt.yml │ │ │ └── aminator.plugins.provisioner.aptitude.yml │ │ ├── manager.py │ │ ├── yum.py │ │ ├── aptitude.py │ │ ├── apt.py │ │ └── base.py │ ├── manager.py │ ├── __init__.py │ └── base.py ├── default_conf │ ├── environments.yml │ ├── aminator.yml │ └── logging.yml ├── __init__.py ├── exceptions.py ├── core.py ├── util │ ├── __init__.py │ └── metrics.py ├── environment.py ├── cli.py └── config.py ├── MANIFEST.in ├── requirements.txt ├── GNUmakefile ├── requirements-locked.txt ├── docs ├── index.rst ├── make.bat ├── Makefile └── conf.py ├── .gitignore ├── setup.py ├── CONTRIBUTING.md ├── setup.cfg ├── README.rst └── LICENSE.txt /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /OSSMETADATA: -------------------------------------------------------------------------------- 1 | osslifecycle=active 2 | -------------------------------------------------------------------------------- /aminator/plugins/cloud/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/distro/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/metrics/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/volume/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /aminator/plugins/metrics/default_conf/aminator.plugins.metrics.logger.yml: -------------------------------------------------------------------------------- 1 | enabled: true -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/default_conf/aminator.plugins.blockdevice.null.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE.txt README.rst requirements.txt distribute_setup.py 2 | global-include *.yml 3 | -------------------------------------------------------------------------------- /aminator/plugins/volume/default_conf/aminator.plugins.volume.linux.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | resize_volume: true 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto>=2.7 2 | boto3>=1.4.4 3 | bunch 4 | decorator 5 | logutils 6 | pyyaml 7 | requests 8 | stevedore 9 | simplejson 10 | dill 11 | 12 | -------------------------------------------------------------------------------- /GNUmakefile: -------------------------------------------------------------------------------- 1 | validate: 2 | @rm -rf flake8; \ 3 | virtualenv --no-site-packages flake8; \ 4 | flake8/bin/pip install flake8; \ 5 | export PATH=$$(pwd)/flake8/bin:$$PATH; \ 6 | flake8 -v aminator 7 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/default_conf/aminator.plugins.provisioner.yum.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | 3 | pkg_query_format: "name:%{N}\\nversion:%{V}\\nrelease:%{R}\\n" 4 | pkg_attributes: [name, version, release] 5 | 6 | pkg_extension: rpm 7 | 8 | scripts_dir: /var/local -------------------------------------------------------------------------------- /aminator/plugins/provisioner/default_conf/aminator.plugins.provisioner.apt.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | scripts_dir: /var/local 3 | 4 | pkg_query_format: "name:${Package}\\nversion:${Version}\\nrelease:${Release}" 5 | pkg_attributes: [name, version, release] 6 | 7 | pkg_extension: deb 8 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/default_conf/aminator.plugins.provisioner.aptitude.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | scripts_dir: /var/local 3 | 4 | pkg_query_format: "name:${Package}\\nversion:${Version}\\nrelease:${Release}" 5 | pkg_attributes: [name, version, release] 6 | 7 | pkg_extension: deb 8 | -------------------------------------------------------------------------------- /requirements-locked.txt: -------------------------------------------------------------------------------- 1 | PyYAML==3.10 2 | -e git+git@github.com:Netflix/aminator.git@916e270e2ad0750b6165e064c76c6035c1369b34#egg=aminator-origin/testing 3 | argparse==1.2.1 4 | boto==2.22.1 5 | bunch==1.0.1 6 | decorator==3.4.0 7 | envoy==0.0.2 8 | logutils==0.3.3 9 | requests==2.2.0 10 | simplejson==3.3.2 11 | stevedore==0.13 12 | wsgiref==0.1.2 13 | -------------------------------------------------------------------------------- /aminator/plugins/cloud/default_conf/aminator.plugins.cloud.ec2.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | base_ami_id: 3 | base_ami_name: 4 | boto_debug: false 5 | ephemeral_devices: 6 | - /dev/sdb 7 | - /dev/sdc 8 | - /dev/sdd 9 | - /dev/sde 10 | is_secure: true 11 | root_device: /dev/sda1 12 | provisioner_ebs_type: standard 13 | register_ebs_type: standard 14 | root_volume_size: 15 | #region: 16 | -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/default_conf/aminator.plugins.blockdevice.linux.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | # possible OS device prefixes 3 | device_prefixes: [xvd, sd] 4 | # think device_prefix + device letter (sda, sdb, xvda, etc) 5 | device_letters: 'fghijklmnop' 6 | # if aminating on a HVM instance, one cannot use minor device numbers for EBS 7 | # volumes. Set this to False to avoid using minor device numbers 8 | use_minor_device_numbers: true 9 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. aminator documentation master file, created by 2 | sphinx-quickstart on Thu Mar 14 18:38:34 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to aminator's documentation! 7 | ==================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | 23 | -------------------------------------------------------------------------------- /tests/yum_test.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | 3 | short_circuit: true 4 | short_circuit_files: 5 | - /tmp/sbin/service 6 | 7 | # fstab-esque list of mounts for a chroot environment. ordered. 8 | # [device, type, mount point, options] 9 | chroot_mounts: 10 | - [proc, proc, /proc, null] 11 | - [sysfs, sysfs, /sys, null] 12 | - [/dev, bind, /dev, null] 13 | - [devpts, devpts, /dev/pts, null] 14 | - [binfmt_misc, binfmt_misc, /proc/sys/fs/binfmt_misc, null] 15 | 16 | 17 | provision_configs: true 18 | provision_config_files: 19 | - /etc/resolv.conf 20 | -------------------------------------------------------------------------------- /aminator/plugins/distro/default_conf/aminator.plugins.distro.redhat.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | 3 | short_circuit: true 4 | short_circuit_files: 5 | - /sbin/service 6 | 7 | # fstab-esque list of mounts for a chroot environment. ordered. 8 | # [device, type, mount point, options] 9 | chroot_mounts: 10 | - [proc, proc, /proc, null] 11 | - [sysfs, sysfs, /sys, null] 12 | - [/dev, bind, /dev, null] 13 | - [devpts, devpts, /dev/pts, null] 14 | - [binfmt_misc, binfmt_misc, /proc/sys/fs/binfmt_misc, null] 15 | 16 | recursive_unmount: false 17 | 18 | provision_configs: true 19 | provision_config_files: 20 | - /etc/resolv.conf 21 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/default_conf/aminator.plugins.finalizer.tagging_ebs.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | description_format: 'name={name}, arch={arch}, ancestor_name={base_ami_name}, ancestor_id={base_ami_id}, ancestor_version={base_ami_version}' 3 | name_format: '{name}-{version}-{release}-{arch}-{suffix}' 4 | tag_formats: 5 | appversion: '{name}-{version}-{release}' 6 | base_ami_version: '{base_ami_version}' 7 | suffix_format: '{0:%Y%m%d%H%M}' 8 | creator: aminator 9 | default_root_device: /dev/sda1 10 | default_block_device_map: 11 | - [/dev/sdb, ephemeral0] 12 | - [/dev/sdc, ephemeral1] 13 | - [/dev/sdd, ephemeral2] 14 | - [/dev/sde, ephemeral3] 15 | default_architecture: x86_64 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | __pycache__ 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer and Eclipse 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | .settings 38 | 39 | # SublimeRope 40 | .ropeproject 41 | 42 | *.sublime-project 43 | *.sublime-workspace 44 | .idea 45 | 46 | # Vim 47 | *.swp 48 | 49 | .*.pylint 50 | pylint/ 51 | 52 | flake8/ 53 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Copyright 2013 Netflix, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # 18 | 19 | import setuptools 20 | 21 | setuptools.setup(setup_requires=['pbr'], pbr=True) 22 | -------------------------------------------------------------------------------- /tests/test_chef_node.json: -------------------------------------------------------------------------------- 1 | { 2 | "__type__": "ChefNode", 3 | "name": "helloworld", 4 | "description": "Hello World", 5 | "version": "1.0", 6 | "release": "277", 7 | "change": "33a9d1cac7686c8a46c1f330add2e8d36850fd15", 8 | "bug_id": "", 9 | "build_job": "APP-helloworld", 10 | "built_by": "builds", 11 | "build_date": "2013-06-14_16:22:24", 12 | "build_number": "277", 13 | "build_id": "2013-06-12_09-22-21", 14 | "run_list": [ 15 | "recipe[helloworld]" 16 | ], 17 | "default_attributes": { 18 | "helloworld": { 19 | "server": { 20 | "home": "/var/lib/helloworld", 21 | "war_checksum": "7e676062231f6b80b60e53dc982eb89c36759bdd2da7f82ad8b35a002a36da9a" 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /aminator/plugins/distro/default_conf/aminator.plugins.distro.debian.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | short_circuit: true 3 | short_circuit_files: 4 | - /usr/sbin/service 5 | 6 | # fstab-esque list of mounts for a chroot environment. ordered. 7 | # [device, type, mount point, options] 8 | chroot_mounts: 9 | - [proc, proc, /proc, null] 10 | - [sysfs, sysfs, /sys, null] 11 | # Note: on Ubuntu 16.04 and later, bind mounts need the 'private' option 12 | # - [/dev, bind, /dev, 'private'] 13 | - [/dev, bind, /dev, null] 14 | - [devpts, devpts, /dev/pts, null] 15 | - [binfmt_misc, binfmt_misc, /proc/sys/fs/binfmt_misc, null] 16 | 17 | recursive_unmount: false 18 | 19 | provision_configs: true 20 | provision_config_files: 21 | - /etc/resolv.conf 22 | 23 | policy_file_path: /usr/sbin 24 | policy_file: policy-rc.d 25 | policy_file_mode: 0755 26 | policy_file_content: | 27 | #!/bin/sh 28 | exit 101 29 | 30 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/default_conf/aminator.plugins.finalizer.tagging_s3.yml: -------------------------------------------------------------------------------- 1 | enabled: true 2 | description_format: 'name={name}, arch={arch}, ancestor_name={base_ami_name}, ancestor_id={base_ami_id}, ancestor_version={base_ami_version}' 3 | name_format: '{name}-{version}-{release}-{arch}-{suffix}' 4 | tag_formats: 5 | appversion: '{name}-{version}-{release}' 6 | base_ami_version: '{base_ami_version}' 7 | suffix_format: '{0:%Y%m%d%H%M}' 8 | creator: aminator 9 | # this is where the images are bundles, make sure you have at least 15G free on the device 10 | default_tmpdir: /tmp 11 | default_cert: /root/certificate.pem 12 | default_privatekey: /root/private-key.pem 13 | # this need to be your aws user number (a 12 digit number) 14 | default_ec2_user: -1 15 | default_root_device: /dev/sda1 16 | default_block_device_map: 17 | - [/dev/sdb, ephemeral0] 18 | - [/dev/sdc, ephemeral1] 19 | - [/dev/sdd, ephemeral2] 20 | - [/dev/sde, ephemeral3] 21 | default_architecture: x86_64 22 | max_root_volume_size: 10 23 | -------------------------------------------------------------------------------- /aminator/default_conf/environments.yml: -------------------------------------------------------------------------------- 1 | default: ec2_yum_linux 2 | ec2_yum_linux: 3 | cloud: ec2 4 | distro: redhat 5 | provisioner: yum 6 | volume: linux 7 | blockdevice: linux 8 | finalizer: tagging_ebs 9 | ec2_apt_linux: 10 | cloud: ec2 11 | distro: debian 12 | provisioner: apt 13 | volume: linux 14 | blockdevice: linux 15 | finalizer: tagging_ebs 16 | ec2_aptitude_linux: 17 | cloud: ec2 18 | distro: debian 19 | provisioner: aptitude 20 | volume: linux 21 | blockdevice: linux 22 | finalizer: tagging_ebs 23 | ec2_yum_linux_s3: 24 | cloud: ec2 25 | distro: redhat 26 | provisioner: yum 27 | volume: linux 28 | blockdevice: linux 29 | finalizer: tagging_s3 30 | ec2_apt_linux_s3: 31 | cloud: ec2 32 | distro: debian 33 | provisioner: apt 34 | volume: linux 35 | blockdevice: linux 36 | finalizer: tagging_s3 37 | ec2_aptitude_linux_s3: 38 | cloud: ec2 39 | distro: debian 40 | provisioner: aptitude 41 | volume: linux 42 | blockdevice: linux 43 | finalizer: tagging_s3 44 | -------------------------------------------------------------------------------- /aminator/plugins/cloud/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.cloud.manager 23 | ============================== 24 | Cloud plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class CloudPluginManager(BasePluginManager): 35 | """ Cloud Plugin Manager """ 36 | _entry_point = 'aminator.plugins.cloud' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.finalizer.manager 23 | ================================== 24 | Finalizer plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class FinalizerPluginManager(BasePluginManager): 35 | """ Finalizer Plugin Manager """ 36 | _entry_point = 'aminator.plugins.finalizer' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | -------------------------------------------------------------------------------- /aminator/plugins/distro/redhat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.distro.redhat 23 | ================================ 24 | basic redhat distro 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.distro.linux import BaseLinuxDistroPlugin 29 | 30 | __all__ = ('RedHatDistroPlugin',) 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class RedHatDistroPlugin(BaseLinuxDistroPlugin): 35 | """ 36 | RedHatDistroPlugin takes the majority of its behavior from BaseLinuxDistroPlugin 37 | See BaseLinuxDistroPlugin for details 38 | """ 39 | _name = 'redhat' 40 | -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.blockdevice.manager 23 | ==================================== 24 | Block device plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class BlockDevicePluginManager(BasePluginManager): 35 | """ BlockDevice Plugin Manager """ 36 | _entry_point = 'aminator.plugins.blockdevice' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | -------------------------------------------------------------------------------- /aminator/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator 23 | ======== 24 | Create images from packages for deployment in various cloud formations 25 | """ 26 | import logging 27 | try: 28 | from logging import NullHandler 29 | except ImportError: 30 | # py26 31 | try: 32 | from logutils import NullHandler 33 | except ImportError: 34 | class NullHandler(logging.Handler): 35 | def emit(self, record): 36 | pass 37 | 38 | __version__ = '2.2.1.dev' 39 | __versioninfo__ = __version__.split('.') 40 | __all__ = () 41 | 42 | logging.getLogger(__name__).addHandler(NullHandler()) 43 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to aminator 2 | 3 | If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request (against the `testing` branch). 4 | 5 | When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. 6 | 7 | ## License 8 | 9 | By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/Netflix/aminator/blob/testing/LICENSE.txt 10 | 11 | All files are released with the Apache 2.0 license. 12 | 13 | If you are adding a new file it should have a header like this: 14 | 15 | ``` 16 | /** 17 | * Copyright 2013 Netflix, Inc. 18 | * 19 | * Licensed under the Apache License, Version 2.0 (the "License"); 20 | * you may not use this file except in compliance with the License. 21 | * You may obtain a copy of the License at 22 | * 23 | * http://www.apache.org/licenses/LICENSE-2.0 24 | * 25 | * Unless required by applicable law or agreed to in writing, software 26 | * distributed under the License is distributed on an "AS IS" BASIS, 27 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | * See the License for the specific language governing permissions and 29 | * limitations under the License. 30 | */ 31 | ``` 32 | -------------------------------------------------------------------------------- /aminator/plugins/volume/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.volume.manager 23 | =============================== 24 | Volume plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class VolumePluginManager(BasePluginManager): 35 | """ Volume Plugin Manager """ 36 | _entry_point = 'aminator.plugins.volume' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | 42 | @staticmethod 43 | def check_func(plugin): # pylint: disable=method-hidden 44 | return True 45 | -------------------------------------------------------------------------------- /aminator/plugins/metrics/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2014 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.metrics.manager 23 | =============================== 24 | Metrics plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class MetricsPluginManager(BasePluginManager): 35 | """ Metrics Plugin Manager """ 36 | _entry_point = 'aminator.plugins.metrics' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | 42 | @staticmethod 43 | def check_func(plugin): # pylint: disable=method-hidden 44 | return True 45 | -------------------------------------------------------------------------------- /aminator/plugins/distro/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.distro.manager 23 | ==================================== 24 | Provisioner plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class DistroPluginManager(BasePluginManager): 35 | """OS Distribution Plugin Manager """ 36 | _entry_point = 'aminator.plugins.distro' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | 42 | @staticmethod 43 | def check_func(plugin): # pylint: disable=method-hidden 44 | return True 45 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.provisioner.manager 23 | ==================================== 24 | Provisioner plugin manager(s) and utils 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.manager import BasePluginManager 29 | 30 | 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class ProvisionerPluginManager(BasePluginManager): 35 | """ Provisioner Plugin Manager """ 36 | _entry_point = 'aminator.plugins.provisioner' 37 | 38 | @property 39 | def entry_point(self): 40 | return self._entry_point 41 | 42 | @staticmethod 43 | def check_func(plugin): # pylint: disable=method-hidden 44 | return True 45 | -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/null.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2014 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.blockdevice.null 23 | ================================== 24 | null block device manager 25 | """ 26 | import logging 27 | 28 | from aminator.plugins.blockdevice.base import BaseBlockDevicePlugin 29 | 30 | __all__ = ('NullBlockDevicePlugin',) 31 | log = logging.getLogger(__name__) 32 | 33 | 34 | class NullBlockDevicePlugin(BaseBlockDevicePlugin): 35 | _name = 'null' 36 | 37 | def __enter__(self): 38 | return '/dev/null' 39 | 40 | def __exit__(self, typ, val, trc): 41 | if typ: 42 | log.debug('Exception encountered in Null block device plugin', 43 | exc_info=(typ, val, trc)) 44 | return False 45 | -------------------------------------------------------------------------------- /aminator/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.exceptions 23 | =================== 24 | aminator's exceptions 25 | """ 26 | 27 | 28 | class AminateException(Exception): 29 | """ Base Aminator Exception """ 30 | pass 31 | 32 | 33 | class DeviceException(AminateException): 34 | """ Errors during device allocation """ 35 | pass 36 | 37 | 38 | class VolumeException(AminateException): 39 | """ Errors during volume allocation """ 40 | pass 41 | 42 | 43 | class ArgumentError(AminateException): 44 | """ Errors during argument parsing""" 45 | 46 | 47 | class ProvisionException(AminateException): 48 | """ Errors during provisioning """ 49 | 50 | 51 | class FinalizerException(AminateException): 52 | """ Errors during finalizing """ 53 | -------------------------------------------------------------------------------- /aminator/plugins/distro/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.distro.base 23 | ================================= 24 | Base class(es) for OS distributions plugins 25 | """ 26 | import abc 27 | import logging 28 | 29 | from aminator.plugins.base import BasePlugin 30 | 31 | __all__ = ('BaseDistroPlugin',) 32 | log = logging.getLogger(__name__) 33 | 34 | 35 | class BaseDistroPlugin(BasePlugin): 36 | """ 37 | Distribution plugins take a volume and prepare it for provisioning. 38 | They are context managers to ensure resource cleanup 39 | """ 40 | 41 | __metaclass__ = abc.ABCMeta 42 | _entry_point = 'aminator.plugins.distro' 43 | 44 | @abc.abstractmethod 45 | def __enter__(self): 46 | return self 47 | 48 | @abc.abstractmethod 49 | def __exit__(self, exc_type, exc_value, trace): 50 | if exc_type: 51 | log.debug('Exception encountered in distro plugin context manager', 52 | exc_info=(exc_type, exc_value, trace)) 53 | return False 54 | -------------------------------------------------------------------------------- /aminator/default_conf/aminator.yml: -------------------------------------------------------------------------------- 1 | # aminator default configuration settings 2 | 3 | config_root: /etc/aminator 4 | 5 | # lack of leading ~ or / makes these relative to config_root 6 | config_files: 7 | main: [aminator.yml, ~/.aminator/aminator.yml] 8 | logging: [logging.yml, ~/.aminator/logging.yml] 9 | environments: [environments.yml, ~/.aminator/environments.yml] 10 | 11 | # aminator working dir (state, locks, etc) 12 | aminator_root: /var/aminator 13 | # lack of leading ~ or / makes these relative to aminator_root 14 | volume_dir: volumes 15 | lock_dir: lock 16 | 17 | # thar be logfiles here! 18 | log_root: /var/log/aminator 19 | 20 | plugins: 21 | config_root: /etc/aminator/plugins 22 | entry_points: 23 | blockdevice: 24 | entry_point: aminator.plugins.blockdevice 25 | class: BlockDevicePluginManager 26 | cloud: 27 | entry_point: aminator.plugins.cloud 28 | class: CloudPluginManager 29 | distro: 30 | entry_point: aminator.plugins.distro 31 | class: DistroPluginManager 32 | finalizer: 33 | entry_point: aminator.plugins.finalizer 34 | class: FinalizerPluginManager 35 | metrics: 36 | entry_point: aminator.plugins.metrics 37 | class: MetricsPluginManager 38 | provisioner: 39 | entry_point: aminator.plugins.provisioner 40 | class: ProvisionerPluginManager 41 | volume: 42 | entry_point: aminator.plugins.volume 43 | class: VolumePluginManager 44 | 45 | context: 46 | # used by some plugins when fetching resources 47 | verify_https: false 48 | package: 49 | # AMI directory to store package files 50 | dir: /tmp 51 | # bake package file into AMI 52 | preserve: False 53 | ami: 54 | tags: {} 55 | snapshot: 56 | tags: {} 57 | web_log: {} 58 | cloud: {} 59 | volume: {} 60 | -------------------------------------------------------------------------------- /aminator/default_conf/logging.yml: -------------------------------------------------------------------------------- 1 | # base[config] dict used to initialize logging using logging.config.dictConfig. 2 | # don't change logger or handler names. 3 | base: 4 | enabled: true 5 | config: 6 | version: 1 7 | disable_existing_loggers: false 8 | formatters: 9 | simple: 10 | format: '%(asctime)s [%(levelname)s] %(message)s' 11 | datefmt: '%F %T' 12 | detailed: 13 | format: '%(asctime)s [%(levelname)s] [%(name)s(%(lineno)s):%(funcName)s] %(message)s' 14 | datefmt: '%F %T' 15 | handlers: 16 | console: 17 | class: logging.StreamHandler 18 | formatter: simple 19 | level: INFO 20 | stream: ext://sys.stdout 21 | aminator: 22 | class: logging.FileHandler 23 | filename: /dev/null 24 | formatter: detailed 25 | level: DEBUG 26 | boto: 27 | class: logging.FileHandler 28 | filename: /dev/null 29 | formatter: detailed 30 | level: DEBUG 31 | root: 32 | handlers: [console] 33 | level: INFO 34 | loggers: 35 | boto: 36 | handlers: [boto] 37 | level: DEBUG 38 | aminator: 39 | handlers: [aminator] 40 | level: DEBUG 41 | 42 | # post-dictConfig handler configs 43 | # if you have the means to provide a web interface to your logs, define a template 44 | # here using str.format() style 45 | # The format string will use the dict under the context.web_log config key 46 | # to format the URL. 47 | # context: 48 | # web_log: 49 | # host: {filled in at runtime} 50 | # logfile: {filled in at runtime} 51 | # 52 | # 53 | 54 | aminator: 55 | enabled: true 56 | filename_format: '{0}-{1:%Y%m%d%H%M}.log' 57 | # web_log_url_template: 'http://{host}/log/location/{logfile}' 58 | boto: 59 | enabled: false 60 | filename_format: 'boto-{0}-{1:%Y%m%d%H%M}.log' 61 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.finalizer.base 23 | =============================== 24 | Base class(es) for finalizer plugins 25 | """ 26 | import abc 27 | import logging 28 | 29 | from aminator.plugins.base import BasePlugin 30 | 31 | 32 | __all__ = ('BaseFinalizerPlugin',) 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class BaseFinalizerPlugin(BasePlugin): 37 | """ 38 | Finalizers handle administrivia post-package-provisioning. Think: registration, tagging, snapshotting, etc. 39 | They are context managers to ensure resource cleanup 40 | """ 41 | 42 | __metaclass__ = abc.ABCMeta 43 | _entry_point = 'aminator.plugins.finalizer' 44 | 45 | @abc.abstractmethod 46 | def finalize(self): 47 | """ finalize an image """ 48 | 49 | def __enter__(self): 50 | return self 51 | 52 | def __exit__(self, typ, val, trc): 53 | if typ: 54 | log.debug('Exception encountered in Finalizer plugin context manager', 55 | exc_info=(typ, val, trc)) 56 | return False 57 | 58 | def __call__(self, cloud): 59 | self._cloud = cloud 60 | -------------------------------------------------------------------------------- /aminator/plugins/volume/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.volume.base 23 | ============================ 24 | Base class(es) for volume plugins 25 | """ 26 | import abc 27 | import logging 28 | 29 | from aminator.plugins.base import BasePlugin 30 | 31 | 32 | __all__ = ('BaseVolumePlugin',) 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class BaseVolumePlugin(BasePlugin): 37 | """ 38 | Volume plugins ask blockdevice for an os block device, the cloud for a volume at 39 | that block device, mount it, and return the mount point for the provisioner. How they go about it 40 | is up to the implementor. 41 | The are context managers to ensure they unmount and clean up resources 42 | """ 43 | __metaclass__ = abc.ABCMeta 44 | _entry_point = 'aminator.plugins.volume' 45 | 46 | @abc.abstractmethod 47 | def __enter__(self): 48 | return self 49 | 50 | @abc.abstractmethod 51 | def __exit__(self, exc_type, exc_value, trace): 52 | if exc_type: 53 | log.debug('Exception encountered in volume plugin context manager', 54 | exc_info=(exc_type, exc_value, trace)) 55 | return False 56 | 57 | def __call__(self, cloud, blockdevice): 58 | self._cloud = cloud 59 | self._blockdevice = blockdevice 60 | return self 61 | -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.blockdevice.base 23 | ================================= 24 | Base class(es) for block device manager plugins 25 | """ 26 | import abc 27 | import logging 28 | 29 | from aminator.plugins.base import BasePlugin 30 | 31 | 32 | __all__ = ('BaseBlockDevicePlugin',) 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class BaseBlockDevicePlugin(BasePlugin): 37 | """ 38 | BlockDevicePlugins are context managers and as such, need to implement the context manager protocol 39 | """ 40 | __metaclass__ = abc.ABCMeta 41 | _entry_point = 'aminator.plugins.blockdevice' 42 | 43 | def __init__(self, *args, **kwargs): 44 | super(BaseBlockDevicePlugin, self).__init__(*args, **kwargs) 45 | self.partition = None 46 | 47 | @abc.abstractmethod 48 | def __enter__(self): 49 | return self 50 | 51 | @abc.abstractmethod 52 | def __exit__(self, typ, val, trc): 53 | if typ: 54 | log.debug('Exception encountered in block device plugin', exc_info=(typ, val, trc)) 55 | return False 56 | 57 | def __call__(self, cloud): 58 | """ 59 | By default, BlockDevicePlugins are called using 60 | with blockdeviceplugin(cloud) as device: 61 | pass 62 | Override if need be 63 | """ 64 | self.cloud = cloud 65 | return self 66 | -------------------------------------------------------------------------------- /aminator/plugins/metrics/logger.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2014 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.metrics.logger 23 | ============================= 24 | basic logger metrics collector 25 | """ 26 | import logging 27 | from time import time 28 | 29 | from aminator.plugins.metrics.base import BaseMetricsPlugin 30 | 31 | __all__ = ('LoggerMetricsPlugin',) 32 | log = logging.getLogger(__name__) 33 | 34 | 35 | class LoggerMetricsPlugin(BaseMetricsPlugin): 36 | _name = 'logger' 37 | 38 | def __init__(self): 39 | super(LoggerMetricsPlugin, self).__init__() 40 | self.timers = {} 41 | 42 | def increment(self, name, value=1): 43 | log.debug("Metric {0}: increment {1}, tags: {2}".format(name, value, self.tags)) 44 | 45 | def gauge(self, name, value): 46 | log.debug("Metric {0}: gauge set {1}, tags: {2}".format(name, value, self.tags)) 47 | 48 | def timer(self, name, seconds): 49 | log.debug("Metric {0}: timer {1}s, tags: {2}".format(name, seconds, self.tags)) 50 | 51 | def start_timer(self, name): 52 | log.debug("Metric {0}: start timer, tags: {1}".format(name, self.tags)) 53 | self.timers[name] = time() 54 | 55 | def stop_timer(self, name): 56 | log.debug("Metric {0}: stop timer [{1}s], tags: {2}".format(name, time() - self.timers[name], self.tags)) 57 | del self.timers[name] 58 | 59 | def flush(self): 60 | for name in self.timers: 61 | log.warning("Metric {0}: timer never stopped, started at {1}, tags: {2}".format(name, self.timers[name], self.tags)) 62 | -------------------------------------------------------------------------------- /aminator/plugins/metrics/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2014 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.metrics.base 23 | ============================ 24 | Base class(es) for metrics plugins 25 | """ 26 | import abc 27 | import logging 28 | 29 | from aminator.plugins.base import BasePlugin 30 | 31 | 32 | __all__ = ('BaseMetricsPlugin',) 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class BaseMetricsPlugin(BasePlugin): 37 | """ 38 | """ 39 | __metaclass__ = abc.ABCMeta 40 | _entry_point = 'aminator.plugins.metrics' 41 | 42 | @abc.abstractmethod 43 | def increment(self, name, value=1): 44 | pass 45 | 46 | @abc.abstractmethod 47 | def gauge(self, name, value): 48 | pass 49 | 50 | @abc.abstractmethod 51 | def timer(self, name, seconds): 52 | pass 53 | 54 | @abc.abstractmethod 55 | def start_timer(self, name): 56 | pass 57 | 58 | @abc.abstractmethod 59 | def stop_timer(self, name): 60 | pass 61 | 62 | @abc.abstractmethod 63 | def flush(self): 64 | pass 65 | 66 | def add_tag(self, name, value): 67 | self.tags[name] = value 68 | 69 | def __init__(self): 70 | super(BaseMetricsPlugin, self).__init__() 71 | self.tags = {} 72 | 73 | def __enter__(self): 74 | setattr(self._config, "metrics", self) 75 | return self 76 | 77 | def __exit__(self, exc_type, exc_value, trace): 78 | self.flush() 79 | if exc_type: 80 | log.debug('Exception encountered in metrics plugin context manager', 81 | exc_info=(exc_type, exc_value, trace)) 82 | return False 83 | -------------------------------------------------------------------------------- /aminator/plugins/manager.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.manager 23 | ======================== 24 | Base plugin manager(s) and utils 25 | """ 26 | import abc 27 | import logging 28 | 29 | from stevedore.dispatch import NameDispatchExtensionManager 30 | 31 | 32 | log = logging.getLogger(__name__) 33 | 34 | 35 | class BasePluginManager(NameDispatchExtensionManager): 36 | """ 37 | Base plugin manager from which all managers *should* inherit 38 | Descendents *must* define a _entry_point class attribute 39 | Descendents *may* define a _check_func class attribute holding a function that determines whether a 40 | given plugin should or should not be enabled 41 | """ 42 | __metaclass__ = abc.ABCMeta 43 | _entry_point = None 44 | _check_func = None 45 | 46 | def __init__(self, check_func=None, invoke_on_load=True, invoke_args=None, invoke_kwds=None): 47 | invoke_args = invoke_args or () 48 | invoke_kwds = invoke_kwds or {} 49 | 50 | if self._entry_point is None: 51 | raise AttributeError('Plugin managers must declare their entry point in a class attribute _entry_point') 52 | 53 | check_func = check_func or self._check_func 54 | if check_func is None: 55 | check_func = lambda x: True 56 | 57 | super(BasePluginManager, self).__init__(namespace=self.entry_point, check_func=check_func, invoke_on_load=invoke_on_load, invoke_args=invoke_args, invoke_kwds=invoke_kwds) 58 | 59 | @property 60 | def entry_point(self): 61 | """ 62 | Base plugins for each plugin type must set a _entry_point class attribute to the entry point they 63 | are responsible for 64 | """ 65 | return self._entry_point 66 | -------------------------------------------------------------------------------- /tests/test_yum_provisioner_plugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | import logging 21 | import os 22 | from aminator.plugins.provisioner.yum import YumProvisionerPlugin 23 | from aminator.config import Config 24 | 25 | log = logging.getLogger(__name__) 26 | console = logging.StreamHandler() 27 | # add the handler to the root logger 28 | logging.getLogger('').addHandler(console) 29 | 30 | class TestYumProvisionerPlugin(object): 31 | 32 | def setup_method(self, method): 33 | self.config = Config() 34 | self.config.plugins = Config() 35 | self.config.plugins['aminator.plugins.provisioner.yum'] = self.config.from_file(yaml_file='yum_test.yml') 36 | 37 | self.plugin = YumProvisionerPlugin() 38 | self.plugin._config = self.config 39 | 40 | def test_deactivate_active_services(self): 41 | 42 | files = self.plugin._config.plugins['aminator.plugins.provisioner.yum'].get('short_circuit_files', []) 43 | 44 | if len(files) != 1: 45 | raise AttributeError("incorrect number of files specified. found %d expected 1", len(files)) 46 | 47 | filename = files[0] 48 | 49 | if not os.path.isdir(os.path.dirname(filename)): 50 | os.makedirs(os.path.dirname(filename)) 51 | 52 | # cleanup 53 | if os.path.islink(filename): 54 | log.debug("removing %s", filename) 55 | os.remove(filename) 56 | 57 | with open(filename, 'w') as f: 58 | log.debug("writing %s", filename) 59 | f.write("test") 60 | log.debug("wrote %s", filename) 61 | 62 | assert self.plugin._deactivate_provisioning_service_block() 63 | assert True == os.path.islink('/tmp/sbin/service') 64 | assert self.plugin._activate_provisioning_service_block() 65 | assert False == os.path.islink('/tmp/sbin/service') 66 | -------------------------------------------------------------------------------- /tests/util.py: -------------------------------------------------------------------------------- 1 | import aminator.util.linux 2 | import unittest 3 | import os 4 | import logging 5 | import shutil 6 | import tempfile 7 | 8 | log = logging.getLogger(__name__) 9 | logging.root.addHandler(logging.StreamHandler()) 10 | logging.root.setLevel(logging.DEBUG) 11 | 12 | 13 | class linux_util(unittest.TestCase): 14 | src_root = tempfile.mkdtemp(dir='/tmp', prefix='src_') 15 | dst_root = tempfile.mkdtemp(dir='/tmp', prefix='dst_') 16 | 17 | files = ['a', 'b', 'c', 'd', 'Da', 'Db', 'Dc', 'Dd'] 18 | 19 | def test_provision_configs(self): 20 | """ test install_provision_configs and remove_provision_configs against 21 | self.files. 22 | Test matrix: 23 | files src_exists dst_exists 24 | a y y 25 | b y n 26 | c n y 27 | d n n 28 | Da y y 29 | Db y n 30 | Dc n y 31 | Dd n n 32 | """ 33 | # create /dst_root/src_root 34 | dst_dir = os.path.join(self.dst_root, self.src_root.lstrip('/')) 35 | os.makedirs(dst_dir) 36 | # /src_root/{a,b} 37 | open(os.path.join(self.src_root, 'a'), 'w').close() 38 | open(os.path.join(self.src_root, 'b'), 'w').close() 39 | 40 | # dirs /src_root/{Da/a,{Db/b} 41 | os.mkdir(os.path.join(self.src_root, 'Da')) 42 | open(os.path.join(self.src_root, 'Da', 'a'), 'w').close() 43 | os.mkdir(os.path.join(self.src_root, 'Db')) 44 | open(os.path.join(self.src_root, 'Db', 'b'), 'w').close() 45 | 46 | # /dst_root/src_root/{a,c} 47 | open(os.path.join(dst_dir, 'a'), 'w').close() 48 | open(os.path.join(dst_dir, 'c'), 'w').close() 49 | 50 | # dirs /dst_root/src_root/{Da/a,{Dc/c} 51 | os.mkdir(os.path.join(dst_dir, 'Da')) 52 | open(os.path.join(dst_dir, 'Da', 'a'), 'w').close() 53 | os.mkdir(os.path.join(dst_dir, 'Dc')) 54 | open(os.path.join(dst_dir, 'Dc', 'c'), 'w').close() 55 | 56 | provision_config_files = [os.path.join(self.src_root, x) for x in self.files] 57 | 58 | install_status = aminator.util.linux.install_provision_configs(provision_config_files, self.dst_root) 59 | remove_status = aminator.util.linux.remove_provision_configs(provision_config_files, self.dst_root) 60 | 61 | shutil.rmtree(self.src_root) 62 | shutil.rmtree(self.dst_root) 63 | 64 | assert install_status & remove_status 65 | 66 | 67 | if __name__ == "__main__": 68 | unittest.main() 69 | -------------------------------------------------------------------------------- /aminator/core.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.core 23 | ============= 24 | aminator core amination logic 25 | """ 26 | import logging 27 | import os 28 | 29 | from aminator.config import init_defaults, configure_datetime_logfile 30 | from aminator.environment import Environment 31 | from aminator.plugins import PluginManager 32 | from aminator.util.linux import mkdir_p 33 | 34 | __all__ = ('Aminator',) 35 | log = logging.getLogger(__name__) 36 | 37 | 38 | class Aminator(object): 39 | def __init__(self, config=None, parser=None, plugin_manager=PluginManager, environment=Environment, debug=False, envname=None): 40 | log.info('Aminator starting...') 41 | if not all((config, parser)): 42 | log.debug('Loading default configuration') 43 | config, parser = init_defaults(debug=debug) 44 | self.config = config 45 | self.parser = parser 46 | log.debug('Configuration loaded') 47 | if not envname: 48 | envname = self.config.environments.default 49 | self.plugin_manager = plugin_manager(self.config, self.parser, plugins=self.config.environments[envname]) 50 | log.debug('Plugins loaded') 51 | self.parser.parse_args() 52 | log.debug('Args parsed') 53 | 54 | os.environ["AMINATOR_PACKAGE"] = self.config.context.package.arg 55 | 56 | log.debug('Creating initial folder structure if needed') 57 | mkdir_p(self.config.log_root) 58 | mkdir_p(os.path.join(self.config.aminator_root, self.config.lock_dir)) 59 | mkdir_p(os.path.join(self.config.aminator_root, self.config.volume_dir)) 60 | 61 | if self.config.logging.aminator.enabled: 62 | log.debug('Configuring per-package logging') 63 | configure_datetime_logfile(self.config, 'aminator') 64 | 65 | self.environment = environment() 66 | 67 | def aminate(self): 68 | with self.environment(self.config, self.plugin_manager) as env: 69 | ok = env.provision() 70 | if ok: 71 | log.info('Amination complete!') 72 | return 0 if ok else 1 73 | -------------------------------------------------------------------------------- /aminator/plugins/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins 23 | ================ 24 | plugin support for aminator 25 | 26 | Aminator currently provides the following major plugin points: 27 | - clouds (interfaces to cloud providers) 28 | - block device allocators (components that reserve and provide OS devices to volume managers) 29 | - volume managers (components that attach cloud volumes and prepare them for amination) 30 | - provisioners (components that deploy applications into the volumes provided by volume managers) 31 | - finalizers (components that tag and register the resultant image) 32 | 33 | Plugins may be discovered through setuptools/distribute's entry_points mechanism 34 | or registered by placing modules on a configurable plugin path for discovery. 35 | """ 36 | import logging 37 | 38 | 39 | log = logging.getLogger(__name__) 40 | 41 | 42 | class PluginManager(object): 43 | """ The plugin manager manager, if you will. Responsible for booting plugins """ 44 | _registry = {} 45 | 46 | def __init__(self, config, parser, plugins=None): 47 | """ 48 | config.plugins.managers is a map of entry points, their kinds, and the actual manager classes 49 | this populates the registry dict, mapping kind and entry_point to an actual instance of the manager 50 | """ 51 | for kind, plugin_info in config.plugins.entry_points.iteritems(): 52 | entry_point = plugin_info.entry_point 53 | classname = plugin_info['class'] 54 | 55 | manager_module = __import__(entry_point + '.manager', globals=globals(), locals=locals(), fromlist=(classname,)) 56 | manager = getattr(manager_module, classname) 57 | 58 | self._registry[entry_point] = manager() 59 | self._registry[kind] = self._registry[entry_point] 60 | 61 | for name, plugin in self._registry[entry_point].by_name.iteritems(): 62 | if not plugins or plugins[entry_point.split('.')[-1]] == name: 63 | plugin.obj.configure(config, parser) 64 | log.debug('Loaded plugin {0}.{1}'.format(entry_point, name)) 65 | 66 | def find_by_entry_point(self, entry_point, name): 67 | return self._registry[entry_point].by_name[name] 68 | 69 | def find_by_kind(self, kind, name): 70 | return self._registry[kind].by_name[name] 71 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # Copyright 2013 Netflix, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # 18 | 19 | [metadata] 20 | name = aminator 21 | description-file = README.rst 22 | author = Netflix Engineering Tools 23 | author_email = talent@netflix.com 24 | url = https://github.com/netflix/aminator 25 | packages = find_packages(exclude=exclude_packages) 26 | package_data = package_data 27 | package_dir = {'aminator': 'aminator'} 28 | include_package_data = True 29 | zip_safe = False 30 | install_requires = requires 31 | entry_points = entry_points 32 | license = ASL 2.0 33 | classifiers= 34 | 'Development Status :: 4 - Beta 35 | 'Environment :: Console 36 | 'Intended Audience :: Developers 37 | 'Intended Audience :: Information Technology 38 | 'Intended Audience :: System Administrators 39 | 'License :: OSI Approved :: Apache Software License 40 | 'Natural Language :: English 41 | 'Programming Language :: Python :: 2.6 42 | 'Programming Language :: Python :: 2.7 43 | 'Topic :: System :: Installation/Setup 44 | 'Topic :: Utilities 45 | 46 | 47 | [files] 48 | packages = 49 | aminator 50 | 51 | [entry_points] 52 | console_scripts = 53 | aminate = aminator.cli:run 54 | aminator-plugin = aminator.cli:plugin_manager 55 | 56 | aminator.plugins.cloud = 57 | ec2 = aminator.plugins.cloud.ec2:EC2CloudPlugin 58 | 59 | aminator.plugins.distro = 60 | debian = aminator.plugins.distro.debian:DebianDistroPlugin 61 | redhat = aminator.plugins.distro.redhat:RedHatDistroPlugin 62 | 63 | aminator.plugins.provisioner = 64 | yum = aminator.plugins.provisioner.yum:YumProvisionerPlugin 65 | apt = aminator.plugins.provisioner.apt:AptProvisionerPlugin 66 | aptitude = aminator.plugins.provisioner.aptitude:AptitudeProvisionerPlugin 67 | 68 | aminator.plugins.volume = 69 | linux = aminator.plugins.volume.linux:LinuxVolumePlugin 70 | 71 | aminator.plugins.blockdevice = 72 | linux = aminator.plugins.blockdevice.linux:LinuxBlockDevicePlugin 73 | null = aminator.plugins.blockdevice.null:NullBlockDevicePlugin 74 | 75 | aminator.plugins.finalizer = 76 | tagging_ebs = aminator.plugins.finalizer.tagging_ebs:TaggingEBSFinalizerPlugin 77 | tagging_s3 = aminator.plugins.finalizer.tagging_s3:TaggingS3FinalizerPlugin 78 | 79 | aminator.plugins.metrics = 80 | logger = aminator.plugins.metrics.logger:LoggerMetricsPlugin 81 | 82 | [bdist_rpm] 83 | requires = python-boto >= 2.7 python-bunch python-decorator python-logutils python-pyyaml python-requests python-stevedore python-simplejson 84 | 85 | [flake8] 86 | ignore = E501, E731 87 | -------------------------------------------------------------------------------- /aminator/plugins/distro/debian.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.distro.debian 23 | ================================ 24 | basic debian distro 25 | """ 26 | import logging 27 | import os.path 28 | 29 | from aminator.plugins.distro.linux import BaseLinuxDistroPlugin 30 | 31 | 32 | __all__ = ('DebianDistroPlugin',) 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class DebianDistroPlugin(BaseLinuxDistroPlugin): 37 | """ 38 | DebianDistroPlugin takes the majority of its behavior from BaseLinuxDistroPlugin 39 | See BaseLinuxDistroPlugin for details 40 | """ 41 | _name = 'debian' 42 | 43 | def _deactivate_provisioning_service_block(self): 44 | """ 45 | Prevent packages installing in the chroot from starting 46 | For debian based distros, we add /usr/sbin/policy-rc.d 47 | """ 48 | if not super(DebianDistroPlugin, self)._deactivate_provisioning_service_block(): 49 | return False 50 | 51 | config = self.plugin_config 52 | path = os.path.join( 53 | self.root_mountspec.mountpoint, config.get('policy_file_path', '')) 54 | filename = os.path.join(path, config.get('policy_file')) 55 | 56 | if not os.path.isdir(path): 57 | log.debug("creating %s", path) 58 | os.makedirs(path) 59 | log.debug("created %s", path) 60 | 61 | with open(filename, 'w') as f: 62 | log.debug("writing %s", filename) 63 | f.write(config.get('policy_file_content')) 64 | log.debug("wrote %s", filename) 65 | 66 | os.chmod(filename, config.get('policy_file_mode', '')) 67 | 68 | return True 69 | 70 | def _activate_provisioning_service_block(self): 71 | """ 72 | Remove policy-rc.d file so that things start when the AMI launches 73 | """ 74 | if not super(DebianDistroPlugin, self)._activate_provisioning_service_block(): 75 | return False 76 | 77 | config = self.plugin_config 78 | 79 | policy_file = os.path.join( 80 | self.root_mountspec.mountpoint, 81 | config.get('policy_file_path', ''), 82 | config.get('policy_file', '')) 83 | 84 | if os.path.isfile(policy_file): 85 | log.debug("removing %s", policy_file) 86 | os.remove(policy_file) 87 | else: 88 | log.debug("The %s was missing, this is unexpected as the DebianDistroPlugin should manage this file", policy_file) 89 | 90 | return True 91 | -------------------------------------------------------------------------------- /aminator/plugins/cloud/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.cloud.base 23 | =========================== 24 | Base class(es) for cloud plugins 25 | """ 26 | import abc 27 | import logging 28 | 29 | from aminator.plugins.base import BasePlugin 30 | 31 | 32 | __all__ = ('BaseCloudPlugin',) 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class BaseCloudPlugin(BasePlugin): 37 | """ 38 | Cloud plugins are context managers to ensure cleanup. They are the interface to cloud objects and operations. 39 | """ 40 | 41 | __metaclass__ = abc.ABCMeta 42 | _entry_point = 'aminator.plugins.cloud' 43 | 44 | _connection = None 45 | 46 | @abc.abstractmethod 47 | def connect(self): 48 | """ Store the resultant connection in the _connection class attribute """ 49 | 50 | @abc.abstractmethod 51 | def allocate_base_volume(self, tag=True): 52 | """ create a volume object from the base/foundation volume """ 53 | 54 | @abc.abstractmethod 55 | def attach_volume(self, blockdevice, tag=True): 56 | """ Instructs the cloud provider to attach some sort of volume to the instance """ 57 | 58 | @abc.abstractmethod 59 | def detach_volume(self, blockdevice): 60 | """ Instructs the cloud provider to detach a given volume from the instance """ 61 | 62 | @abc.abstractmethod 63 | def delete_volume(self): 64 | """ destroys a volume """ 65 | 66 | @abc.abstractmethod 67 | def snapshot_volume(self, description=None): 68 | """ creates a snapshot from the attached volume """ 69 | 70 | @abc.abstractmethod 71 | def is_volume_attached(self, blockdevice): 72 | """ volume attachment status """ 73 | 74 | @abc.abstractmethod 75 | def is_stale_attachment(self, dev, prefix): 76 | """ checks to see if a given device is a stale attachment """ 77 | 78 | @abc.abstractmethod 79 | def attached_block_devices(self, prefix): 80 | """ 81 | list any block devices attached to the aminator instance. 82 | helps blockdevice plugins allocate an os device node 83 | """ 84 | 85 | @abc.abstractmethod 86 | def add_tags(self, resource_type): 87 | """ consumes tags and applies them to objects """ 88 | 89 | @abc.abstractmethod 90 | def register_image(self, *args, **kwargs): 91 | """ Instructs the cloud provider to register a finalized image for launching """ 92 | 93 | def __enter__(self): 94 | self.connect() 95 | return self 96 | 97 | def __exit__(self, typ, val, trc): 98 | if typ: 99 | log.debug('Exception encountered in Cloud plugin context manager', 100 | exc_info=(typ, val, trc)) 101 | return False 102 | -------------------------------------------------------------------------------- /aminator/plugins/volume/linux.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.volume.linux 23 | ============================= 24 | basic linux volume allocator 25 | """ 26 | import logging 27 | 28 | from aminator.util.linux import resize2fs, fsck, growpart 29 | from aminator.exceptions import VolumeException 30 | from aminator.plugins.volume.base import BaseVolumePlugin 31 | 32 | 33 | __all__ = ('LinuxVolumePlugin',) 34 | log = logging.getLogger(__name__) 35 | 36 | 37 | class LinuxVolumePlugin(BaseVolumePlugin): 38 | _name = 'linux' 39 | 40 | def _attach(self, blockdevice): 41 | with blockdevice(self._cloud) as dev: 42 | self._dev = dev 43 | if blockdevice.partition is not None: 44 | devpart = '{0}{1}'.format(dev, blockdevice.partition) 45 | self.context.volume['dev'] = devpart 46 | else: 47 | self.context.volume['dev'] = self._dev 48 | self._cloud.attach_volume(self._dev) 49 | 50 | def _detach(self): 51 | self._cloud.detach_volume(self._dev) 52 | 53 | def _resize(self): 54 | log.info('Checking and repairing root volume as necessary') 55 | fsck_op = fsck(self.context.volume.dev) 56 | if not fsck_op.success: 57 | raise VolumeException( 58 | 'fsck of {} failed: {}'.format(self.context.volume.dev, fsck_op.result.std_err)) 59 | log.info('Attempting to resize root fs to fill volume') 60 | if self._blockdevice.partition is not None: 61 | log.info('Growing partition if necessary') 62 | growpart_op = growpart(self._dev, self._blockdevice.partition) 63 | if not growpart_op.success: 64 | volmsg = 'growpart of {} partition {} failed: {}' 65 | raise VolumeException( 66 | volmsg.format( 67 | self._dev, self._blockdevice.partition, growpart_op.result.std_err)) 68 | resize_op = resize2fs(self.context.volume.dev) 69 | if not resize_op.success: 70 | raise VolumeException( 71 | 'resize of {} failed: {}'.format(self.context.volume.dev, resize_op.result.std_err)) 72 | 73 | def _delete(self): 74 | self._cloud.delete_volume() 75 | 76 | def __enter__(self): 77 | self._attach(self._blockdevice) 78 | if self.plugin_config.get('resize_volume', False): 79 | self._resize() 80 | return self 81 | 82 | def __exit__(self, exc_type, exc_value, trace): 83 | if exc_type: 84 | log.debug('Exception encountered in linux volume plugin context manager', 85 | exc_info=(exc_type, exc_value, trace)) 86 | if exc_type and self._config.context.get("preserve_on_error", False): 87 | return False 88 | self._detach() 89 | self._delete() 90 | return False 91 | -------------------------------------------------------------------------------- /aminator/util/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.util 23 | ============= 24 | Utilities 25 | """ 26 | import functools 27 | import logging 28 | import requests 29 | from time import sleep 30 | 31 | from decorator import decorator 32 | 33 | 34 | log = logging.getLogger(__name__) 35 | 36 | 37 | def retry(ExceptionToCheck=None, tries=3, delay=0.5, backoff=1, logger=None, maxdelay=None): 38 | """ 39 | Retries a function or method until it returns True. 40 | 41 | delay sets the initial delay in seconds, and backoff sets the factor by which 42 | the delay should lengthen after each failure. backoff must be greater than 1, 43 | or else it isn't really a backoff. tries must be at least 0, and delay 44 | greater than 0. 45 | http://wiki.python.org/moin/PythonDecoratorLibrary#Retry 46 | """ 47 | if logger is None: 48 | logger = log 49 | 50 | @decorator 51 | def _retry(f, *args, **kwargs): 52 | _tries, _delay = tries, delay 53 | 54 | while _tries > 0: 55 | try: 56 | return f(*args, **kwargs) 57 | except ExceptionToCheck as e: 58 | logger.debug(e) 59 | sleep(_delay) 60 | _tries -= 1 61 | _delay *= backoff 62 | if maxdelay and _delay > maxdelay: 63 | _delay = maxdelay 64 | return f(*args, **kwargs) 65 | return _retry 66 | 67 | 68 | def memoize(obj=None): 69 | """ 70 | http://wiki.python.org/moin/PythonDecoratorLibrary#Alternate_memoize_as_nested_functions 71 | """ 72 | cache = obj.cache = {} 73 | 74 | @functools.wraps(obj) 75 | def memoizer(*args, **kwargs): 76 | if args not in cache: 77 | cache[args] = obj(*args, **kwargs) 78 | return cache[args] 79 | return memoizer 80 | 81 | 82 | @retry(requests.HTTPError, tries=5, delay=1, backoff=2) 83 | def download_file(url, dst, timeout=1, verify_https=False): 84 | try: 85 | response = requests.get(url, timeout=timeout, verify=verify_https) 86 | except requests.RequestException as e: 87 | if isinstance(e, requests.Timeout): 88 | # Retry timeouts 89 | raise requests.HTTPError('Timeout exceeded.') 90 | else: 91 | raise e 92 | 93 | if response.status_code >= 500: 94 | # retry service errors 95 | raise requests.HTTPError('{0.status_code} {0.reason}'.format(response)) 96 | 97 | if response.status_code != 200: 98 | return False 99 | 100 | with open(dst, 'w') as dst_fp: 101 | dst_fp.write(response.content) 102 | 103 | return True 104 | 105 | 106 | def randword(length): 107 | import random 108 | import string 109 | return ''.join(random.choice(string.lowercase) for _ in xrange(length)) 110 | -------------------------------------------------------------------------------- /aminator/environment.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.environment 23 | ==================== 24 | The orchestrator 25 | """ 26 | import logging 27 | import yaml 28 | 29 | log = logging.getLogger(__name__) 30 | 31 | 32 | class Environment(object): 33 | """ The environment and orchetrator for amination """ 34 | # TODO: given that this represents a workflow, this should possibly be an entry point 35 | 36 | def _attach_plugins(self): 37 | log.debug('Attaching plugins to environment {0}'.format(self._name)) 38 | env_config = self._config.environments[self._name] 39 | for kind, name in env_config.iteritems(): 40 | log.debug('Attaching plugin {0} for {1}'.format(name, kind)) 41 | plugin = self._plugin_manager.find_by_kind(kind, name) 42 | setattr(self, kind, plugin.obj) 43 | log.debug('Attached: {0}'.format(getattr(self, kind))) 44 | 45 | kind = "metrics" 46 | if not getattr(self, kind, None): 47 | name = self._config.environments.get(kind, "logger") 48 | plugin = self._plugin_manager.find_by_kind(kind, name) 49 | setattr(self, kind, plugin.obj) 50 | 51 | log.debug("============= BEGIN YAML representation of loaded configs ===============") 52 | log.debug(yaml.dump(self._config)) 53 | log.debug("============== END YAML representation of loaded configs ================") 54 | 55 | def provision(self): 56 | log.info('Beginning amination! Package: {0}'.format(self._config.context.package.arg)) 57 | with self.metrics: # pylint: disable=no-member 58 | with self.cloud as cloud: # pylint: disable=no-member 59 | with self.finalizer(cloud) as finalizer: # pylint: disable=no-member 60 | with self.volume(self.cloud, self.blockdevice): # pylint: disable=no-member 61 | with self.distro as distro: # pylint: disable=no-member 62 | success = self.provisioner(distro).provision() # pylint: disable=no-member 63 | if not success: 64 | log.critical('Provisioning failed!') 65 | return False 66 | success = finalizer.finalize() 67 | if not success: 68 | log.critical('Finalizing failed!') 69 | return False 70 | return True 71 | 72 | def __enter__(self): 73 | return self 74 | 75 | def __exit__(self, exc_type, exc_value, trc): 76 | if exc_type: 77 | log.debug('Exception encountered in environment context manager', exc_info=(exc_type, exc_value, trc)) 78 | return False 79 | 80 | def __call__(self, config, plugin_manager): 81 | self._config = config 82 | self._plugin_manager = plugin_manager 83 | self._name = self._config.context.get('environment', self._config.environments.default) 84 | self._config.context['environment'] = self._name 85 | self._attach_plugins() 86 | return self 87 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/yum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.provisioner.yum 23 | ================================ 24 | basic yum provisioner 25 | """ 26 | import logging 27 | import os 28 | 29 | from aminator.plugins.provisioner.base import BaseProvisionerPlugin 30 | from aminator.util.linux import monitor_command, result_to_dict 31 | from aminator.util.metrics import cmdsucceeds, cmdfails, lapse 32 | 33 | __all__ = ('YumProvisionerPlugin',) 34 | log = logging.getLogger(__name__) 35 | 36 | 37 | class YumProvisionerPlugin(BaseProvisionerPlugin): 38 | """ 39 | YumProvisionerPlugin takes the majority of its behavior from BaseProvisionerPlugin 40 | See BaseProvisionerPlugin for details 41 | """ 42 | _name = 'yum' 43 | 44 | def _refresh_repo_metadata(self): 45 | config = self._config.plugins[self.full_name] 46 | return yum_clean_metadata(config.get('clean_repos', [])) 47 | 48 | @cmdsucceeds("aminator.provisioner.yum.provision_package.count") 49 | @cmdfails("aminator.provisioner.yum.provision_package.error") 50 | @lapse("aminator.provisioner.yum.provision_package.duration") 51 | def _provision_package(self): 52 | result = self._refresh_repo_metadata() 53 | if not result.success: 54 | log.critical('Repo metadata refresh failed: {0.std_err}'.format(result.result)) 55 | return result 56 | context = self._config.context 57 | if context.package.get('local_install', False): 58 | return yum_localinstall(context.package.arg) 59 | else: 60 | return yum_install(context.package.arg) 61 | 62 | def _store_package_metadata(self): 63 | context = self._config.context 64 | config = self._config.plugins[self.full_name] 65 | metadata = rpm_package_metadata(context.package.arg, config.get('pkg_query_format', ''), context.package.get('local_install', False)) 66 | for x in config.pkg_attributes: 67 | metadata.setdefault(x, None) 68 | context.package.attributes = metadata 69 | 70 | 71 | def yum_install(package): 72 | return monitor_command(['yum', '--nogpgcheck', '-y', 'install', package]) 73 | 74 | 75 | def yum_localinstall(path): 76 | if not os.path.isfile(path): 77 | log.critical('Package {0} not found'.format(path)) 78 | return None 79 | return monitor_command(['yum', '--nogpgcheck', '-y', 'localinstall', path]) 80 | 81 | 82 | def yum_clean_metadata(repos=None): 83 | clean = ['yum', 'clean', 'metadata'] 84 | if repos: 85 | clean.extend(['--disablerepo', '*', '--enablerepo', ','.join(repos)]) 86 | return monitor_command(clean) 87 | 88 | 89 | def rpm_query(package, queryformat, local=False): 90 | cmd = 'rpm -q --qf'.split() 91 | cmd.append(queryformat) 92 | if local: 93 | cmd.append('-p') 94 | cmd.append(package) 95 | return monitor_command(cmd) 96 | 97 | 98 | def rpm_package_metadata(package, queryformat, local=False): 99 | return result_to_dict(rpm_query(package, queryformat, local)) 100 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/tagging_ebs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.finalizer.tagging_ebs 23 | ====================================== 24 | ebs tagging image finalizer 25 | """ 26 | import logging 27 | 28 | from os import environ 29 | from aminator.config import conf_action 30 | from aminator.plugins.finalizer.tagging_base import TaggingBaseFinalizerPlugin 31 | from aminator.util.linux import sanitize_metadata 32 | 33 | 34 | __all__ = ('TaggingEBSFinalizerPlugin',) 35 | log = logging.getLogger(__name__) 36 | 37 | 38 | class TaggingEBSFinalizerPlugin(TaggingBaseFinalizerPlugin): 39 | _name = 'tagging_ebs' 40 | 41 | def add_plugin_args(self): 42 | tagging = super(TaggingEBSFinalizerPlugin, self).add_plugin_args() 43 | 44 | context = self._config.context 45 | tagging.add_argument('-n', '--name', dest='name', action=conf_action(context.ami), help='name of resultant AMI (default package_name-version-release-arch-yyyymmddHHMM-ebs') 46 | 47 | def _set_metadata(self): 48 | super(TaggingEBSFinalizerPlugin, self)._set_metadata() 49 | context = self._config.context 50 | config = self._config.plugins[self.full_name] 51 | metadata = context.package.attributes 52 | ami_name = context.ami.get('name', None) 53 | if not ami_name: 54 | ami_name = config.name_format.format(**metadata) 55 | 56 | context.ami.name = sanitize_metadata('{0}-ebs'.format(ami_name)) 57 | 58 | def _snapshot_volume(self): 59 | log.info('Taking a snapshot of the target volume') 60 | if not self._cloud.snapshot_volume(): 61 | return False 62 | log.info('Snapshot success') 63 | return True 64 | 65 | def _register_image(self, block_device_map=None, root_device=None): 66 | log.info('Registering image') 67 | config = self._config.plugins[self.full_name] 68 | if block_device_map is None: 69 | block_device_map = config.default_block_device_map 70 | if root_device is None: 71 | root_device = config.default_root_device 72 | if not self._cloud.register_image(block_device_map, root_device): 73 | return False 74 | log.info('Registration success') 75 | return True 76 | 77 | def finalize(self): 78 | log.info('Finalizing image') 79 | self._set_metadata() 80 | 81 | if not self._snapshot_volume(): 82 | log.critical('Error snapshotting volume') 83 | return False 84 | 85 | if not self._register_image(): 86 | log.critical('Error registering image') 87 | return False 88 | 89 | if not self._add_tags(['snapshot', 'ami']): 90 | log.critical('Error adding tags') 91 | return False 92 | 93 | log.info('Image registered and tagged') 94 | self._log_ami_metadata() 95 | return True 96 | 97 | def __enter__(self): 98 | context = self._config.context 99 | environ["AMINATOR_STORE_TYPE"] = "ebs" 100 | if context.ami.get("name", None): 101 | environ["AMINATOR_AMI_NAME"] = context.ami.name 102 | return super(TaggingEBSFinalizerPlugin, self).__enter__() 103 | -------------------------------------------------------------------------------- /aminator/plugins/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.base 23 | ===================== 24 | Base class(es) for plugin implementations 25 | """ 26 | import logging 27 | import os 28 | 29 | from aminator.config import PluginConfig 30 | 31 | 32 | __all__ = () 33 | log = logging.getLogger(__name__) 34 | 35 | 36 | class BasePlugin(object): 37 | """ Base class for plugins """ 38 | _entry_point = None 39 | _name = None 40 | _enabled = True 41 | 42 | def __init__(self): 43 | if self._entry_point is None: 44 | raise AttributeError('Plugins must declare their entry point namespace in a _entry_point class attribute') 45 | if self._name is None: 46 | raise AttributeError('Plugins must declare their entry point name in a _name class attribute') 47 | 48 | @property 49 | def enabled(self): 50 | return self._enabled 51 | 52 | @enabled.setter 53 | def enabled(self, enable): 54 | self._enabled = enable 55 | 56 | @property 57 | def entry_point(self): 58 | return self._entry_point 59 | 60 | @property 61 | def name(self): 62 | return self._name 63 | 64 | @property 65 | def full_name(self): 66 | return '{0}.{1}'.format(self.entry_point, self.name) 67 | 68 | @property 69 | def full_config(self): 70 | return self._config 71 | 72 | @property 73 | def plugin_config(self): 74 | config = self.full_config.get('plugins', {}) 75 | plugin_config = config.get(self.full_name, {}) 76 | return plugin_config 77 | 78 | @property 79 | def context(self): 80 | return self.full_config.get('context', {}) 81 | 82 | def configure(self, config, parser): 83 | """ Configure the plugin and contribute to command line args """ 84 | log.debug("Configuring plugin {0} for entry point {1}".format(self.name, self.entry_point)) 85 | self._config = config 86 | self._parser = parser 87 | self.load_plugin_config() 88 | if self.enabled: 89 | self.add_plugin_args() 90 | 91 | def add_plugin_args(self): 92 | pass 93 | 94 | def load_plugin_config(self): 95 | entry_point = self.entry_point 96 | name = self.name 97 | key = self.full_name 98 | 99 | if self._config.plugins.config_root.startswith('~'): 100 | plugin_conf_dir = os.path.expanduser(self._config.plugins.config_root) 101 | 102 | elif self._config.plugins.config_root.startswith('/'): 103 | plugin_conf_dir = self._config.plugins.config_root 104 | 105 | else: 106 | plugin_conf_dir = os.path.join(self._config.config_root, self._config.plugins.config_root) 107 | 108 | plugin_conf_files = ( 109 | os.path.join(plugin_conf_dir, '.'.join((key, 'yml'))), 110 | ) 111 | 112 | self._config.plugins[key] = PluginConfig.from_defaults(entry_point, name) 113 | self._config.plugins[key] = PluginConfig.dict_merge(self._config.plugins[key], PluginConfig.from_files(plugin_conf_files)) 114 | # allow plugins to be disabled by configuration. Especially important in cases where command line args conflict 115 | self.enabled = self._config.plugins[key].get('enabled', True) 116 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | aminator - Easily create application-specific custom AMIs 2 | ========================================= 3 | 4 | Aminator creates a custom AMI from just: 5 | 6 | * A base ami ID 7 | * A link to a deb or rpm package that installs your application. 8 | 9 | This is useful for many AWS workflows, particularly ones that take advantage of auto-scaling groups. 10 | 11 | Requirements 12 | ------------ 13 | 14 | * Python 2.7 (Python 3.x support not yet available) 15 | * Linux or UNIX cloud instance (EC2 currently supported) 16 | 17 | Installation 18 | ------------ 19 | Clone this repository and run: 20 | 21 | .. code-block:: bash 22 | 23 | # python setup.py install 24 | 25 | *or* 26 | 27 | .. code-block:: bash 28 | 29 | # pip install git+https://github.com/Netflix/aminator.git#egg=aminator 30 | 31 | Usage 32 | ----- 33 | :: 34 | 35 | usage: aminate [-h] [-e ENVIRONMENT] [--version] [--debug] [-n NAME] 36 | [-s SUFFIX] [-c CREATOR] (-b BASE_AMI_NAME | -B BASE_AMI_ID) 37 | [--ec2-region REGION] [--boto-secure] [--boto-debug] 38 | package 39 | 40 | positional arguments: 41 | package package to aminate. A string resolvable by the native 42 | package manager or a file system path or http url to 43 | the package file. 44 | 45 | optional arguments: 46 | -h, --help show this help message and exit 47 | -e ENVIRONMENT, --environment ENVIRONMENT 48 | The environment configuration for amination 49 | --version show program's version number and exit 50 | --debug Verbose debugging output 51 | 52 | AMI Tagging and Naming: 53 | Tagging and naming options for the resultant AMI 54 | 55 | -n NAME, --name NAME name of resultant AMI (default package_name-version- 56 | release-arch-yyyymmddHHMM-ebs 57 | -s SUFFIX, --suffix SUFFIX 58 | suffix of ami name, (default yyyymmddHHMM) 59 | -c CREATOR, --creator CREATOR 60 | The user who is aminating. The resultant AMI will 61 | receive a creator tag w/ this user 62 | 63 | Base AMI: 64 | EITHER AMI id OR name, not both! 65 | 66 | -b BASE_AMI_NAME, --base-ami-name BASE_AMI_NAME 67 | The name of the base AMI used in provisioning 68 | -B BASE_AMI_ID, --base-ami-id BASE_AMI_ID 69 | The id of the base AMI used in provisioning 70 | 71 | EC2 Options: 72 | EC2 Connection Information 73 | 74 | --ec2-region REGION EC2 region (default: us-east-1) 75 | --boto-secure Connect via https 76 | --boto-debug Boto debug output 77 | 78 | Details 79 | ------- 80 | The rough amination workflow: 81 | 82 | #. Create a volume from the snapshot of the base AMI 83 | #. Attach and mount the volume 84 | #. Chroot into mounted volume 85 | #. Provision application onto mounted volume using rpm or deb package 86 | #. Unmount the volume and create a snapshot 87 | #. Register the snapshot as an AMI 88 | 89 | Support 90 | ------- 91 | * `Aminator Google Group `_ 92 | 93 | Documentation 94 | ------------- 95 | See the `aminator wiki `_ for documentation 96 | 97 | 98 | License 99 | ------- 100 | Copyright 2013 Netflix, Inc. 101 | 102 | 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 103 | 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. 104 | -------------------------------------------------------------------------------- /aminator/util/metrics.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2014 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.util.metrics 23 | =================== 24 | Metrics utility functions 25 | """ 26 | 27 | from time import time 28 | 29 | 30 | def timer(metric_name, context_obj=None): 31 | def func_1(func): 32 | def func_2(obj, *args, **kwargs): 33 | start = time() 34 | try: 35 | retval = func(obj, *args, **kwargs) 36 | (context_obj or obj)._config.metrics.timer(metric_name, time() - start) 37 | except: 38 | (context_obj or obj)._config.metrics.timer(metric_name, time() - start) 39 | raise 40 | return retval 41 | return func_2 42 | return func_1 43 | 44 | 45 | def lapse(metric_name, context_obj=None): 46 | def func_1(func): 47 | def func_2(obj, *args, **kwargs): 48 | (context_obj or obj)._config.metrics.start_timer(metric_name) 49 | try: 50 | retval = func(obj, *args, **kwargs) 51 | (context_obj or obj)._config.metrics.stop_timer(metric_name) 52 | except: 53 | (context_obj or obj)._config.metrics.stop_timer(metric_name) 54 | raise 55 | return retval 56 | return func_2 57 | return func_1 58 | 59 | 60 | def fails(metric_name, context_obj=None): 61 | def func_1(func): 62 | def func_2(obj, *args, **kwargs): 63 | try: 64 | retval = func(obj, *args, **kwargs) 65 | except: 66 | (context_obj or obj)._config.metrics.increment(metric_name) 67 | raise 68 | if not retval: 69 | (context_obj or obj)._config.metrics.increment(metric_name) 70 | return retval 71 | return func_2 72 | return func_1 73 | 74 | 75 | def cmdfails(metric_name, context_obj=None): 76 | def func_1(func): 77 | def func_2(obj, *args, **kwargs): 78 | try: 79 | retval = func(obj, *args, **kwargs) 80 | except: 81 | (context_obj or obj)._config.metrics.increment(metric_name) 82 | raise 83 | if not retval or not retval.success: 84 | (context_obj or obj)._config.metrics.increment(metric_name) 85 | return retval 86 | return func_2 87 | return func_1 88 | 89 | 90 | def cmdsucceeds(metric_name, context_obj=None): 91 | def func_1(func): 92 | def func_2(obj, *args, **kwargs): 93 | retval = func(obj, *args, **kwargs) 94 | if retval and retval.success: 95 | (context_obj or obj)._config.metrics.increment(metric_name) 96 | return retval 97 | return func_2 98 | return func_1 99 | 100 | 101 | def succeeds(metric_name, context_obj=None): 102 | def func_1(func): 103 | def func_2(obj, *args, **kwargs): 104 | retval = func(obj, *args, **kwargs) 105 | if retval: 106 | (context_obj or obj)._config.metrics.increment(metric_name) 107 | return retval 108 | return func_2 109 | return func_1 110 | 111 | 112 | def raises(metric_name, context_obj=None): 113 | def func_1(func): 114 | def func_2(obj, *args, **kwargs): 115 | try: 116 | return func(obj, *args, **kwargs) 117 | except: 118 | (context_obj or obj)._config.metrics.increment(metric_name) 119 | raise 120 | return func_2 121 | return func_1 122 | -------------------------------------------------------------------------------- /tests/TestAptProvisionerPlugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | import logging 21 | import os.path 22 | 23 | from aminator.util.linux import keyval_parse, Response, CommandResult 24 | 25 | from aminator.plugins.provisioner.apt import AptProvisionerPlugin 26 | from aminator.config import Config 27 | from aminator.util.linux import MountSpec 28 | 29 | 30 | log = logging.getLogger(__name__) 31 | console = logging.StreamHandler() 32 | # add the handler to the root logger 33 | logging.getLogger('').addHandler(console) 34 | 35 | 36 | class TestAptProvisionerPlugin(object): 37 | 38 | def setup_method(self, method): 39 | self.config = Config() 40 | self.config.plugins = Config() 41 | 42 | # TODO: this is fragile as it may depend on the dir the tests were run from 43 | self.config.plugins['aminator.plugins.provisioner.apt'] = self.config.from_file(yaml_file='aminator/plugins/provisioner/default_conf/aminator.plugins.provisioner.apt.yml') 44 | 45 | log.info(self.config.plugins) 46 | self.plugin = AptProvisionerPlugin() 47 | 48 | self.plugin._config = self.config 49 | 50 | config = self.plugin._config.plugins['aminator.plugins.provisioner.apt'] 51 | 52 | # use /tmp if not configured, ideally to use tempfile, but needs C build 53 | self.full_path = os.path.join( 54 | config.get('mountpoint', '/tmp'), 55 | config.get('policy_file_path', '/usr/sbin'), 56 | config.get('policy_file', 'policy-rc.d')) 57 | 58 | self.plugin._root_mountspec = MountSpec(None, None, config.get('mountpoint', '/tmp'), None) 59 | 60 | # cleanup 61 | if os.path.isfile(self.full_path): 62 | os.remove(self.full_path) 63 | 64 | def test_disable_enable_service_startup(self): 65 | assert self.plugin._deactivate_provisioning_service_block() 66 | assert os.path.isfile(self.full_path) 67 | 68 | with open(self.full_path) as f: 69 | content = f.readlines() 70 | 71 | # remove whitespace and newlines 72 | content = map(lambda s: s.strip(), content) 73 | # also remove whitespace and newlines 74 | original_content = self.config.plugins['aminator.plugins.provisioner.apt'].get('policy_file_content').splitlines() 75 | 76 | assert original_content == content 77 | 78 | assert self.plugin._activate_provisioning_service_block() 79 | assert os.path.isfile(self.full_path) 80 | 81 | def test_metadata(self): 82 | """ test that given we get back the metadata we expect 83 | this first was a problem when the deb Description field had leading whitespace 84 | which caused the keys to contain leading whitespace 85 | """ 86 | 87 | response = Response() 88 | response.std_out = """ 89 | Package: helloWorld 90 | Source: helloWorld 91 | Version: 1374197704:1.0.0-h357.6ea8a16 92 | Section: None 93 | Priority: optional 94 | Architecture: all 95 | Provides: helloWorld 96 | Installed-Size: 102704 97 | Maintainer: someone@somewhere.org 98 | Description: helloWorld 99 | ---------- 100 | Manifest-Version: 1.1 101 | Implementation-Vendor: Hello, Inc. 102 | Implementation-Title: helloWorld;1.0.0 103 | Implementation-Version: 1.0.0 104 | Label: helloWorld-1.0.0 105 | Built-By: builder 106 | Build-Job: JOB-helloWorld 107 | Build-Date: 2013-07-19_01:33:52 108 | Build-Number: 357 109 | Build-Id: 2013-07-18_18-24-53 110 | Change: 6ea8a16 111 | """ 112 | package_query_result = CommandResult(True, response) 113 | result = parse_command_result(package_query_result) 114 | 115 | assert result['Build-Number'] == '357' 116 | assert result['Build-Job'] == 'JOB-helloWorld' 117 | 118 | 119 | @keyval_parse() 120 | def parse_command_result(data): 121 | return data 122 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/aptitude.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2014 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.provisioner.aptitude 23 | ================================ 24 | basic aptitude provisioner 25 | 26 | Note: 27 | 28 | Aptitude resolvers by default are a bit crazy. The "best" solution it finds is often to remove what 29 | you asked it to install. To make Aptitude resolvers sane create a config file like: 30 | $ cat /etc/apt/apt.conf.d/00aptitude-sane-resolve.conf 31 | Aptitude { 32 | ProblemResolver { 33 | SolutionCost "priority, removals, canceled-actions"; 34 | }; 35 | }; 36 | 37 | For futher reading checkout: 38 | http://www.proulx.com/~bob/debian/hints/jessie-new.html 39 | https://lists.debian.org/debian-devel/2014/10/msg00424.html 40 | """ 41 | import logging 42 | 43 | from os.path import basename 44 | 45 | from aminator.exceptions import ProvisionException 46 | from aminator.plugins.provisioner.apt import AptProvisionerPlugin 47 | from aminator.util.linux import monitor_command 48 | 49 | __all__ = ('AptitudeProvisionerPlugin',) 50 | log = logging.getLogger(__name__) 51 | 52 | 53 | class AptitudeInstallException(ProvisionException): 54 | pass 55 | 56 | 57 | class AptitudeProvisionerPlugin(AptProvisionerPlugin): 58 | """ 59 | AptitudeProvisionerPlugin takes the majority of its behavior from AptProvisionerPlugin 60 | See AptProvisionerPlugin for details 61 | """ 62 | _name = 'aptitude' 63 | 64 | # overload this method to call aptitude instead. 65 | def _fix_localinstall_deps(self, package): 66 | # use aptitude and its solver to resolve dependencies after a dpkg -i 67 | pkgname, _, _ = basename(package).split('_') 68 | 69 | # figure out the version via dpkg rather than parsing it out of the file name 70 | # in case there is an epoch in the version 71 | version_query_ret = self.deb_query(package, "${Version}", local=True) 72 | if not version_query_ret.success: 73 | log.critical("Unable to query version for package {0}".format(package)) 74 | return version_query_ret 75 | pkgver = version_query_ret.result.std_out 76 | 77 | aptitude_ret = self.aptitude("install", "{0}={1}".format(pkgname, pkgver)) 78 | if not aptitude_ret.success: 79 | log.critical("Error encountered resolving dependencies for package {0}: " 80 | "{1.std_err}".format(package, aptitude_ret.result)) 81 | return aptitude_ret 82 | 83 | install_query_ret = self.deb_query(pkgname, "${Status} ${Version}", local=False) 84 | if not install_query_ret.success: 85 | log.critical("Error querying installation status for package {0}: " 86 | "{1.std_err}".format(package, install_query_ret.result)) 87 | return install_query_ret 88 | 89 | if "install ok installed" not in install_query_ret.result.std_out: 90 | errmsg = "package {0} failed to be installed. dpkg status: {1.std_out}" 91 | errmsg = errmsg.format(package, install_query_ret.result) 92 | raise AptitudeInstallException(errmsg) 93 | 94 | installed_version = install_query_ret.result.std_out.split()[-1].strip() 95 | if installed_version != pkgver: 96 | errmsg = "package {0} failed to be installed. requested {1}, installed {2}" 97 | errmsg = errmsg.format(pkgname, pkgver, installed_version) 98 | raise AptitudeInstallException(errmsg) 99 | 100 | return install_query_ret 101 | 102 | @staticmethod 103 | def aptitude(operation, package): 104 | aptitude_result = monitor_command(["aptitude", "--no-gui", "-y", operation, package]) 105 | if not aptitude_result.success: 106 | log.debug('failure:{0.command} :{0.std_err}'.format(aptitude_result.result)) 107 | return aptitude_result 108 | 109 | # overload this method to call aptitude instead. But aptitude will not exit with 110 | # an error code if it failed to install, so we double check that the package installed 111 | # with the dpkg-query command 112 | def _install(self, package): 113 | self.aptitude("install", package) 114 | query_ret = self.deb_query(package, '${Package}-${Version}') 115 | if not query_ret.success: 116 | errmsg = "Error installing package {0}: {1.std_err}" 117 | errmsg = errmsg.format(package, query_ret.result) 118 | log.critical(errmsg) 119 | return query_ret 120 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\aminator.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\aminator.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /aminator/plugins/blockdevice/linux.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.blockdevice.linux 23 | ================================== 24 | basic linux block device manager 25 | """ 26 | import fcntl 27 | import os 28 | import logging 29 | from collections import namedtuple 30 | 31 | from aminator.config import conf_action 32 | from aminator.exceptions import DeviceException 33 | from aminator.plugins.blockdevice.base import BaseBlockDevicePlugin 34 | from aminator.util.linux import flock, locked, native_device_prefix 35 | from aminator.util.metrics import raises 36 | 37 | __all__ = ('LinuxBlockDevicePlugin',) 38 | log = logging.getLogger(__name__) 39 | 40 | 41 | BlockDevice = namedtuple('BlockDevice', 'node handle') 42 | 43 | 44 | class LinuxBlockDevicePlugin(BaseBlockDevicePlugin): 45 | _name = 'linux' 46 | 47 | def configure(self, config, parser): 48 | super(LinuxBlockDevicePlugin, self).configure(config, parser) 49 | 50 | if self._config.lock_dir.startswith(('/', '~')): 51 | self._lock_dir = os.path.expanduser(self._config.lock_dir) 52 | else: 53 | self._lock_dir = os.path.join(self._config.aminator_root, self._config.lock_dir) 54 | 55 | self._lock_file = self.__class__.__name__ 56 | 57 | self._allowed_devices = None 58 | self._device_prefix = None 59 | 60 | def add_plugin_args(self, *args, **kwargs): 61 | context = self._config.context 62 | bd_group_desc = 'Block device allocator configuration' 63 | blockdevice = self._parser.add_argument_group(title='Blockdevice', 64 | description=bd_group_desc) 65 | blockdevice.add_argument("--block-device", dest='block_device', 66 | action=conf_action(config=context.ami), 67 | help='Block device path to use') 68 | blockdevice.add_argument("--partition", dest='partition', 69 | action=conf_action(config=context.ami), 70 | help='Parition number containing the root file system.') 71 | 72 | def __enter__(self): 73 | self._dev = self.allocate_dev() 74 | return self._dev.node 75 | 76 | def __exit__(self, typ, val, trc): 77 | if typ: 78 | log.debug('Exception encountered in Linux block device plugin context manager', 79 | exc_info=(typ, val, trc)) 80 | self.release_dev(self._dev) 81 | return False 82 | 83 | def _setup_allowed_devices(self): 84 | if all((self._device_prefix, self._allowed_devices)): 85 | return 86 | 87 | block_config = self._config.plugins[self.full_name] 88 | majors = block_config.device_letters 89 | 90 | self._device_prefix = native_device_prefix(block_config.device_prefixes) 91 | 92 | context = self._config.context 93 | 94 | if 'partition' in context.ami: 95 | block_config.use_minor_device_numbers = False 96 | self.partition = context.ami.partition 97 | 98 | if block_config.use_minor_device_numbers: 99 | device_format = '/dev/{0}{1}{2}' 100 | self._allowed_devices = [device_format.format(self._device_prefix, major, minor) 101 | for major in majors 102 | for minor in xrange(1, 16)] 103 | else: 104 | device_format = '/dev/{0}{1}' 105 | self._allowed_devices = [device_format.format(self._device_prefix, major) 106 | for major in majors] 107 | 108 | def allocate_dev(self): 109 | context = self._config.context 110 | if "block_device" in context.ami: 111 | return BlockDevice(context.ami.block_device, None) 112 | 113 | with flock(self._lock_file): 114 | return self.find_available_dev() 115 | 116 | def release_dev(self, dev): 117 | if dev.handle: 118 | fcntl.flock(dev.handle, fcntl.LOCK_UN) 119 | dev.handle.close() 120 | 121 | @raises("aminator.blockdevice.linux.find_available_dev.error") 122 | def find_available_dev(self): 123 | log.info('Searching for an available block device') 124 | self._setup_allowed_devices() 125 | for dev in self._allowed_devices: 126 | log.debug('checking if device {0} is available'.format(dev)) 127 | device_lock = os.path.join(self._lock_dir, os.path.basename(dev)) 128 | if os.path.exists(dev): 129 | log.debug('{0} exists, skipping'.format(dev)) 130 | continue 131 | elif locked(device_lock): 132 | log.debug('{0} is locked, skipping'.format(dev)) 133 | continue 134 | elif self.cloud.is_stale_attachment(dev, self._device_prefix): 135 | log.debug('{0} is stale, skipping'.format(dev)) 136 | continue 137 | else: 138 | log.debug('Device {0} looks good, attempting to lock.'.format(dev)) 139 | fh = open(device_lock, 'a') 140 | fcntl.flock(fh, fcntl.LOCK_EX) 141 | log.debug('device locked. fh = {0}, dev = {1}'.format(str(fh), dev)) 142 | log.info('Block device {0} allocated'.format(dev)) 143 | return BlockDevice(dev, fh) 144 | raise DeviceException('Exhausted all devices, none free') 145 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aminator.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aminator.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/aminator" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aminator" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/tagging_base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.finalizer.tagging_base 23 | ====================================== 24 | base tagging image finalizer 25 | """ 26 | import logging 27 | from datetime import datetime 28 | import abc 29 | 30 | from os import environ 31 | from aminator.config import conf_action 32 | from aminator.exceptions import FinalizerException 33 | from aminator.plugins.finalizer.base import BaseFinalizerPlugin 34 | 35 | __all__ = ('TaggingBaseFinalizerPlugin',) 36 | log = logging.getLogger(__name__) 37 | 38 | 39 | class TaggingBaseFinalizerPlugin(BaseFinalizerPlugin): 40 | _name = 'tagging_base' 41 | 42 | def add_plugin_args(self): 43 | context = self._config.context 44 | tagging = self._parser.add_argument_group(title='AMI Tagging and Naming', description='Tagging and naming options for the resultant AMI') 45 | tagging.add_argument('-s', '--suffix', dest='suffix', action=conf_action(context.ami), help='suffix of ami name, (default yyyymmddHHMM)') 46 | creator_help = 'The user who is aminating. The resultant AMI will receive a creator tag w/ this user' 47 | tagging.add_argument('-c', '--creator', dest='creator', action=conf_action(context.ami), help=creator_help) 48 | tagging.add_argument('--vm-type', dest='vm_type', choices=["paravirtual", "hvm"], action=conf_action(context.ami), help='virtualization type to register image as') 49 | tagging.add_argument('--enhanced-networking', dest='enhanced_networking', action=conf_action(context.ami, action='store_true'), help='enable enhanced networking (SR-IOV)') 50 | tagging.add_argument('--ena-networking', dest='ena_networking', action=conf_action(context.ami, action='store_true'), help='enable elastic network adapter support (ENA)') 51 | tagging.add_argument('--arch', dest='architecture', choices=["i386", "x86_64"], action=conf_action(context.ami), help='architecture to register image as') 52 | return tagging 53 | 54 | def _set_metadata(self): 55 | context = self._config.context 56 | config = self._config.plugins[self.full_name] 57 | 58 | log.debug('Populating snapshot and ami metadata for tagging and naming') 59 | creator = context.ami.get('creator', config.get('creator', 'aminator')) 60 | context.ami.tags.creator = creator 61 | context.snapshot.tags.creator = creator 62 | 63 | metadata = context.package.attributes 64 | metadata['arch'] = context.base_ami.architecture 65 | metadata['base_ami_name'] = context.base_ami.name 66 | metadata['base_ami_id'] = context.base_ami.id 67 | metadata['base_ami_version'] = context.base_ami.tags.get('base_ami_version', '') 68 | 69 | suffix = context.ami.get('suffix', None) 70 | if not suffix: 71 | suffix = config.suffix_format.format(datetime.utcnow()) 72 | 73 | metadata['suffix'] = suffix 74 | 75 | for tag in config.tag_formats: 76 | try: 77 | context.ami.tags[tag] = config.tag_formats[tag].format(**metadata) 78 | context.snapshot.tags[tag] = config.tag_formats[tag].format(**metadata) 79 | except KeyError as e: 80 | errstr = 'Tag format requires information not available in package metadata: {0}'.format(e.message) 81 | log.warn(errstr) 82 | log.debug(errstr, exc_info=True) 83 | # in case someone uses a tag format based on metadata not available 84 | # in this package 85 | continue 86 | 87 | default_description = config.description_format.format(**metadata) 88 | description = context.snapshot.get('description', default_description) 89 | context.ami.description = description 90 | context.snapshot.description = description 91 | 92 | def _add_tags(self, resources): 93 | context = self._config.context 94 | context.ami.tags.creation_time = '{0:%F %T UTC}'.format(datetime.utcnow()) 95 | for resource in resources: 96 | try: 97 | self._cloud.add_tags(resource) 98 | except FinalizerException: 99 | errstr = 'Error adding tags to {0}'.format(resource) 100 | log.error(errstr) 101 | log.debug(errstr, exc_info=True) 102 | return False 103 | log.info('Successfully tagged {0}'.format(resource)) 104 | log.info('Successfully tagged objects') 105 | return True 106 | 107 | def _log_ami_metadata(self): 108 | context = self._config.context 109 | for attr in ('id', 'name', 'description', 'kernel_id', 'ramdisk_id', 'virtualization_type',): 110 | log.info('{0}: {1}'.format(attr, getattr(context.ami.image, attr))) 111 | for tag_name, tag_value in context.ami.image.tags.iteritems(): 112 | log.info('Tag {0} = {1}'.format(tag_name, tag_value)) 113 | 114 | @abc.abstractmethod 115 | def finalize(self): 116 | """ finalize an image """ 117 | 118 | def __enter__(self): 119 | context = self._config.context 120 | if context.ami.get("suffix", None): 121 | environ["AMINATOR_AMI_SUFFIX"] = context.ami.suffix 122 | if context.ami.get("creator", None): 123 | environ["AMINATOR_CREATOR"] = context.ami.creator 124 | if context.ami.get("vm_type", None): 125 | environ["AMINATOR_VM_TYPE"] = context.ami.vm_type 126 | if context.ami.get("enhanced_networking", None): 127 | environ["AMINATOR_ENHANCED_NETWORKING"] = str(int(context.ami.enhanced_networking)) 128 | if context.ami.get("ena_networking", None): 129 | environ["AMINATOR_ENA_NETWORKING"] = str(int(context.ami.ena_networking)) 130 | 131 | if context.ami.get("enhanced_networking", False): 132 | if context.ami.get("vm_type", "paravirtual") != "hvm": 133 | raise ValueError("--enhanced-networking requires --vm-type hvm") 134 | 135 | if context.ami.get("ena_networking", False): 136 | if context.ami.get("vm_type", "paravirtual") != "hvm": 137 | raise ValueError("--ena-networking requires --vm-type hvm") 138 | 139 | return self 140 | 141 | def __exit__(self, exc_type, exc_value, trace): 142 | if exc_type: 143 | log.debug('Exception encountered in tagging base finalizer context manager', 144 | exc_info=True) 145 | return False 146 | 147 | def __call__(self, cloud): 148 | self._cloud = cloud 149 | return self 150 | -------------------------------------------------------------------------------- /aminator/cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.cli 23 | ============ 24 | command-line entry 25 | """ 26 | import logging 27 | import sys 28 | 29 | from aminator.config import Argparser 30 | from aminator.core import Aminator 31 | 32 | 33 | __all__ = ('run',) 34 | log = logging.getLogger(__name__) 35 | 36 | 37 | def run(): 38 | import os 39 | # we throw this one away, real parsing happens later 40 | # this is just for getting a debug flag for verbose logging. 41 | # to be extra sneaky, we add a --debug to the REAL parsers so it shows up in help 42 | # but we don't touch it there :P 43 | bootstrap_parser = Argparser(add_help=False) 44 | bootstrap_parser.add_argument('--debug', action='store_true') 45 | bootstrap_parser.add_argument('-e', "--environment", dest="env") 46 | args, argv = bootstrap_parser.parse_known_args() 47 | sys.argv = [sys.argv[0]] + argv 48 | # add -e argument back argv for when we parse the args again 49 | if args.env: 50 | sys.argv.extend(["-e", args.env]) 51 | os.environ["AMINATOR_ENVIRONMENT"] = args.env 52 | 53 | if args.debug: 54 | logging.basicConfig(level=logging.DEBUG) 55 | else: 56 | logging.basicConfig() 57 | sys.exit(Aminator(debug=args.debug, envname=args.env).aminate()) 58 | 59 | 60 | def plugin_manager(): 61 | import subprocess 62 | import requests 63 | import argparse 64 | import tempfile 65 | import tarfile 66 | import shutil 67 | import yaml 68 | import re 69 | import os 70 | 71 | from cStringIO import StringIO 72 | 73 | parser = argparse.ArgumentParser(description='Aminator plugin install utility') 74 | 75 | parser.add_argument('--branch', help='Which branch to pull the plugin list from. Valid options: production, testing, alpha. Default value: production', default='production', choices=['production', 'testing', 'alpha'], dest='branch', metavar='branch') 76 | parser.add_argument('--type', help='The type of plugin to search for. Valid options: cloud, volume, blockdevice, provision, distro, finalizer, metrics', choices=['cloud', 'volume', 'blockdevice', 'provision', 'distro', 'finalizer', 'metrics'], dest='type', metavar='plugin-type') 77 | parser.add_argument('command', help='Command to run. Valid commands: search install list', choices=['search', 'install', 'list'], metavar='command') 78 | parser.add_argument('name', help='Name of the plugin', metavar='name', nargs='?') 79 | args = parser.parse_args() 80 | 81 | req = requests.get('https://raw.github.com/aminator-plugins/metadata/%s/plugins.yml' % (args.branch)) 82 | plugins = yaml.load(req.text) 83 | 84 | if args.command == 'search': 85 | if not args.name: 86 | print "ERROR: You must supply a keyword to search for" 87 | sys.exit() 88 | 89 | results = [] 90 | rgx = re.compile(args.name, re.I) 91 | for name, data in plugins.items(): 92 | m = rgx.search(name) 93 | if not m: 94 | for alias in data['aliases']: 95 | m = rgx.search(alias) 96 | if m: 97 | break 98 | 99 | if m: 100 | if args.type and args.type != data['type']: 101 | continue 102 | results.append("Name: %s\nAliases: %s\nType: %s\nDescription: %s" % (name, ", ".join(data['aliases']), data['type'], data['description'])) 103 | 104 | if len(results) == 0: 105 | print "No plugins found for keyword %s" % args.name 106 | else: 107 | print "\n----------\n".join(results) 108 | 109 | elif args.command == 'list': 110 | results = [] 111 | for name, data in plugins.items(): 112 | if args.type and args.type != data['type']: 113 | continue 114 | results.append("Name: %s\nAliases: %s\nType: %s\nDescription: %s" % (name, ", ".join(data['aliases']), data['type'], data['description'])) 115 | 116 | if len(results) == 0: 117 | print "No plugins found" 118 | else: 119 | print "\n----------\n".join(results) 120 | 121 | elif args.command == 'install': 122 | if not args.name: 123 | print "ERROR: You must supply a plugin name to install" 124 | sys.exit() 125 | 126 | if os.geteuid() != 0: 127 | print "ERROR: You must run installs as root (or through sudo)" 128 | sys.exit() 129 | 130 | rgx = re.compile('^%s$' % args.name, re.I) 131 | plugin = None 132 | 133 | for name, data in plugins.items(): 134 | m = rgx.match(name) 135 | if not m: 136 | for alias in data['aliases']: 137 | m = rgx.match(alias) 138 | if m: 139 | plugin = data 140 | break 141 | else: 142 | plugin = data 143 | 144 | if not plugin: 145 | print "Unable to find a plugin named %s. You should use the search to find the correct name or alias for the plugin you want to install" % args.name 146 | sys.exit() 147 | else: 148 | url = 'https://github.com/aminator-plugins/%s/archive/%s.tar.gz' % (plugin['repo_name'], plugin['branch']) 149 | print "Downloading latest version of %s from %s" % (args.name, url) 150 | req = requests.get(url, stream=True) 151 | 152 | tar = tarfile.open(mode="r:*", fileobj=StringIO(req.raw.read())) 153 | 154 | tmpdir = tempfile.mkdtemp() 155 | tar.extractall(path=tmpdir) 156 | 157 | install_path = os.path.join(tmpdir, "%s-%s" % (plugin['repo_name'], plugin['branch'])) 158 | exe = subprocess.Popen([sys.executable, 'setup.py', 'install'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=install_path) 159 | out, err = exe.communicate() 160 | if exe.returncode > 0: 161 | outf = open(os.path.join(tmpdir, "install.log"), 'w') 162 | outf.write(out) 163 | outf.close() 164 | 165 | errf = open(os.path.join(tmpdir, "install.err"), 'w') 166 | errf.write(err) 167 | errf.close() 168 | 169 | print "Plugin installation failed. You should look at install.log and install.err in the installation folder, %s, for the cause of the failure" % tmpdir 170 | else: 171 | print "%s plugin installed successfully, removing temp dir %s" % (args.name, tmpdir) 172 | shutil.rmtree(tmpdir) 173 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/apt.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.provisioner.apt 23 | ================================ 24 | basic apt provisioner 25 | """ 26 | import logging 27 | import os 28 | 29 | from aminator.exceptions import ProvisionException 30 | from aminator.plugins.provisioner.base import BaseProvisionerPlugin 31 | from aminator.util import retry 32 | from aminator.util.linux import monitor_command, result_to_dict 33 | from aminator.util.metrics import cmdsucceeds, cmdfails, timer, lapse 34 | 35 | __all__ = ('AptProvisionerPlugin',) 36 | log = logging.getLogger(__name__) 37 | 38 | 39 | class AptProvisionerUpdateException(ProvisionException): 40 | pass 41 | 42 | 43 | class AptProvisionerPlugin(BaseProvisionerPlugin): 44 | """ 45 | AptProvisionerPlugin takes the majority of its behavior from BaseProvisionerPlugin 46 | See BaseProvisionerPlugin for details 47 | """ 48 | _name = 'apt' 49 | 50 | @cmdsucceeds("aminator.provisioner.apt.provision_package.count") 51 | @cmdfails("aminator.provisioner.apt.provision_package.error") 52 | @lapse("aminator.provisioner.apt.provision_package.duration") 53 | def _provision_package(self): 54 | context = self._config.context 55 | os.environ['DEBIAN_FRONTEND'] = 'noninteractive' 56 | return self.install(context.package.arg, 57 | local_install=context.package.get('local_install', False)) 58 | 59 | def _store_package_metadata(self): 60 | context = self._config.context 61 | config = self._config.plugins[self.full_name] 62 | metadata = self.deb_package_metadata(context.package.arg, config.get('pkg_query_format', ''), context.package.get('local_install', False)) 63 | for x in config.pkg_attributes: 64 | if x == 'version' and x in metadata: 65 | if ':' in metadata[x]: 66 | # strip epoch element from version 67 | vers = metadata[x] 68 | metadata[x] = vers[vers.index(':') + 1:] 69 | if '-' in metadata[x]: 70 | # debs include release in version so split 71 | # version into version-release to compat w/rpm 72 | vers, rel = metadata[x].split('-', 1) 73 | metadata[x] = vers 74 | metadata['release'] = rel 75 | else: 76 | metadata['release'] = 0 77 | # this is probably not necessary given above 78 | metadata.setdefault(x, None) 79 | context.package.attributes = metadata 80 | 81 | @staticmethod 82 | def dpkg_install(package): 83 | dpkg_result = monitor_command(['dpkg', '-i', package]) 84 | if not dpkg_result.success: 85 | log.debug('failure:{0.command} :{0.std_err}'.format(dpkg_result.result)) 86 | return dpkg_result 87 | 88 | def _fix_localinstall_deps(self, package): 89 | # use apt-get to resolve dependencies after a dpkg -i 90 | fix_deps_result = self.apt_get_install('--fix-missing') 91 | if not fix_deps_result.success: 92 | log.debug('failure:{0.command} :{0.std_err}'.format(fix_deps_result.result)) 93 | return fix_deps_result 94 | 95 | def _localinstall(self, package): 96 | """install deb file with dpkg then resolve dependencies 97 | """ 98 | dpkg_ret = self.dpkg_install(package) 99 | if not dpkg_ret.success: 100 | # expected when package has dependencies that are not installed 101 | update_metadata_result = self.apt_get_update() 102 | if not update_metadata_result.success: 103 | errmsg = 'Repo metadata refresh failed: {0.std_err}' 104 | errmsg = errmsg.format(update_metadata_result.result) 105 | return update_metadata_result 106 | log.info("Installing dependencies for package {0}".format(package)) 107 | fix_deps_result = self._fix_localinstall_deps(package) 108 | if not fix_deps_result.success: 109 | log.critical("Error encountered installing dependencies: " 110 | "{0.std_err}".format(fix_deps_result.result)) 111 | return fix_deps_result 112 | return dpkg_ret 113 | 114 | @staticmethod 115 | def deb_query(package, queryformat, local=False): 116 | if local: 117 | cmd = 'dpkg-deb -W'.split() 118 | cmd.append('--showformat={0}'.format(queryformat)) 119 | else: 120 | cmd = 'dpkg-query -W'.split() 121 | cmd.append('-f={0}'.format(queryformat)) 122 | cmd.append(package) 123 | deb_query_result = monitor_command(cmd) 124 | if not deb_query_result.success: 125 | log.debug('failure:{0.command} :{0.std_err}'.format(deb_query_result.result)) 126 | return deb_query_result 127 | 128 | @cmdsucceeds("aminator.provisioner.apt.apt_get_update.count") 129 | @cmdfails("aminator.provisioner.apt.apt_get_update.error") 130 | @timer("aminator.provisioner.apt.apt_get_update.duration") 131 | @retry(ExceptionToCheck=AptProvisionerUpdateException, tries=5, delay=1, backoff=0.5, logger=log) 132 | def apt_get_update(self): 133 | self.apt_get_clean() 134 | dpkg_update = monitor_command(['apt-get', 'update']) 135 | if not dpkg_update.success: 136 | log.debug('failure: {0.command} :{0.std_err}'.format(dpkg_update.result)) 137 | # trigger retry. expiring retries should fail the bake as this 138 | # exception will propagate out to the provisioning context handler 139 | raise AptProvisionerUpdateException('apt-get update failed') 140 | return dpkg_update 141 | 142 | @staticmethod 143 | def apt_get_clean(): 144 | return monitor_command(['apt-get', 'clean']) 145 | 146 | @staticmethod 147 | def apt_get_install(*options): 148 | cmd = ['apt-get', '-y', 'install'] 149 | cmd.extend(options) 150 | install_result = monitor_command(cmd) 151 | if not install_result.success: 152 | log.debug('failure:{0.command} :{0.std_err}'.format(install_result.result)) 153 | return install_result 154 | 155 | def _install(self, package): 156 | return self.apt_get_install(package) 157 | 158 | def install(self, package, local_install=False): 159 | if local_install: 160 | install_result = self._localinstall(package) 161 | else: 162 | update_metadata_result = self.apt_get_update() 163 | if not update_metadata_result.success: 164 | errmsg = 'Repo metadata refresh failed: {0.std_err}' 165 | errmsg = errmsg.format(update_metadata_result.result) 166 | return update_metadata_result 167 | install_result = self._install(package) 168 | if not install_result.success: 169 | errmsg = 'Error installing package {0}: {1.std_err}' 170 | errmsg = errmsg.format(package, install_result.result) 171 | log.critical(errmsg) 172 | return install_result 173 | 174 | @classmethod 175 | def deb_package_metadata(cls, package, queryformat, local=False): 176 | return result_to_dict(cls.deb_query(package, queryformat, local)) 177 | -------------------------------------------------------------------------------- /aminator/plugins/provisioner/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.provisioner.base 23 | ================================== 24 | Simple base class for cases where there are small distro-specific corner cases 25 | """ 26 | import abc 27 | import logging 28 | import os 29 | import shutil 30 | 31 | from glob import glob 32 | 33 | from aminator.config import conf_action 34 | from aminator.plugins.base import BasePlugin 35 | from aminator.util import download_file 36 | from aminator.util.linux import Chroot, monitor_command 37 | from aminator.util.metrics import fails, lapse 38 | 39 | __all__ = ('BaseProvisionerPlugin',) 40 | log = logging.getLogger(__name__) 41 | 42 | 43 | class BaseProvisionerPlugin(BasePlugin): 44 | """ 45 | Most of what goes on between apt and yum provisioning is the same, so we factored that out, 46 | leaving the differences in the actual implementations 47 | """ 48 | __metaclass__ = abc.ABCMeta 49 | _entry_point = 'aminator.plugins.provisioner' 50 | 51 | @abc.abstractmethod 52 | def _provision_package(self): 53 | """ subclasses must implement package provisioning logic """ 54 | 55 | @abc.abstractmethod 56 | def _store_package_metadata(self): 57 | """ stuff name, version, release into context """ 58 | 59 | def _pre_chroot_block(self): 60 | """ run commands before entering chroot""" 61 | pass 62 | 63 | def _post_chroot_block(self): 64 | """ commands to run after the exiting the chroot""" 65 | pass 66 | 67 | def add_plugin_args(self, *args, **kwargs): 68 | context = self._config.context 69 | prov = self._parser.add_argument_group(title='Provisioning') 70 | prov.add_argument("-i", "--interactive", dest='interactive', help="interactive session after provivioning", action=conf_action(config=context.package, action="store_true")) 71 | 72 | def provision(self): 73 | context = self._config.context 74 | 75 | if self._local_install(): 76 | log.info('performing a local install of {0}'.format(context.package.arg)) 77 | context.package.local_install = True 78 | if not self._stage_pkg(): 79 | log.critical('failed to stage {0}'.format(context.package.arg)) 80 | return False 81 | else: 82 | log.info('performing a repo install of {0}'.format(context.package.arg)) 83 | context.package.local_install = False 84 | 85 | log.debug('Pre chroot command block') 86 | self._pre_chroot_block() 87 | 88 | log.debug('Entering chroot at {0}'.format(self._distro.root_mountspec.mountpoint)) 89 | 90 | with Chroot(self._distro.root_mountspec.mountpoint): 91 | log.debug('Inside chroot') 92 | 93 | result = self._provision_package() 94 | 95 | if context.package.get('interactive', False): 96 | os.system("bash") 97 | 98 | if not result.success: 99 | log.critical('Installation of {0} failed: {1.std_err}'.format(context.package.arg, result.result)) 100 | return False 101 | self._store_package_metadata() 102 | if context.package.local_install and not context.package.get('preserve', False): 103 | os.remove(context.package.arg) 104 | 105 | # run scripts that may have been delivered in the package 106 | scripts_dir = self._config.plugins[self.full_name].get('scripts_dir', '/var/local') 107 | log.debug('scripts_dir = {0}'.format(scripts_dir)) 108 | 109 | if scripts_dir: 110 | if not self._run_provision_scripts(scripts_dir): 111 | return False 112 | 113 | log.debug('Exited chroot') 114 | 115 | log.debug('Post chroot command block') 116 | self._post_chroot_block() 117 | 118 | log.info('Provisioning succeeded!') 119 | return True 120 | 121 | @fails("aminator.provisioner.provision_scripts.error") 122 | @lapse("aminator.provisioner.provision_scripts.duration") 123 | def _run_provision_scripts(self, scripts_dir): 124 | """ 125 | execute every python or shell script found in scripts_dir 126 | 1. run python or shell scripts in lexical order 127 | 128 | :param scripts_dir: path in chroot to look for python and shell scripts 129 | :return: None 130 | """ 131 | 132 | script_files = sorted(glob(scripts_dir + '/*.py') + glob(scripts_dir + '/*.sh')) 133 | if not script_files: 134 | log.debug("no python or shell scripts found in {0}".format(scripts_dir)) 135 | else: 136 | log.debug('found scripts {0} in {1}'.format(script_files, scripts_dir)) 137 | for script in script_files: 138 | log.debug('executing script {0}'.format(script)) 139 | if os.access(script, os.X_OK): 140 | # script is executable, so just run it 141 | result = run_script(script) 142 | else: 143 | if script.endswith('.py'): 144 | result = run_script(['python', script]) 145 | else: 146 | result = run_script(['sh', script]) 147 | if not result.success: 148 | log.critical("script failed: {0}: {1.std_err}".format(script, result.result)) 149 | return False 150 | return True 151 | 152 | def _local_install(self): 153 | """True if context.package.arg ends with a package extension 154 | """ 155 | config = self._config 156 | ext = config.plugins[self.full_name].get('pkg_extension', '') 157 | if not ext: 158 | return False 159 | 160 | # ensure extension begins with a dot 161 | ext = '.{0}'.format(ext.lstrip('.')) 162 | 163 | return config.context.package.arg.endswith(ext) 164 | 165 | def _stage_pkg(self): 166 | """copy package file into AMI volume. 167 | """ 168 | context = self._config.context 169 | context.package.file = os.path.basename(context.package.arg) 170 | root_path = self._distro.root_mountspec.mountpoint 171 | stage_path = os.path.join(root_path, context.package.dir.lstrip('/')) 172 | context.package.full_path = os.path.join(stage_path, context.package.file) 173 | try: 174 | if any(protocol in context.package.arg for protocol in ['http://', 'https://']): 175 | self._download_pkg(context) 176 | else: 177 | self._move_pkg(context) 178 | except Exception: 179 | errstr = 'Exception encountered while staging package' 180 | log.critical(errstr) 181 | log.debug(errstr, exc_info=True) 182 | return False 183 | # reset to chrooted file path 184 | context.package.arg = os.path.join(context.package.dir, context.package.file) 185 | return True 186 | 187 | def _download_pkg(self, context): 188 | """dowload url to context.package.dir 189 | """ 190 | pkg_url = context.package.arg 191 | dst_file_path = context.package.full_path 192 | log.debug('downloading {0} to {1}'.format(pkg_url, dst_file_path)) 193 | download_file(pkg_url, dst_file_path, context.package.get('timeout', 1), verify_https=context.get('verify_https', False)) 194 | 195 | def _move_pkg(self, context): 196 | src_file = context.package.arg.replace('file://', '') 197 | dst_file_path = context.package.full_path 198 | shutil.move(src_file, dst_file_path) 199 | 200 | def __call__(self, distro): 201 | self._distro = distro 202 | return self 203 | 204 | 205 | def run_script(script): 206 | return monitor_command(script) 207 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # aminator documentation build configuration file, created by 4 | # sphinx-quickstart on Thu Mar 14 18:38:34 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'aminator' 44 | copyright = u'2013, Netflix, Inc.' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '1.0' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '1.0' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = ['_build'] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'aminatordoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | latex_elements = { 173 | # The paper size ('letterpaper' or 'a4paper'). 174 | #'papersize': 'letterpaper', 175 | 176 | # The font size ('10pt', '11pt' or '12pt'). 177 | #'pointsize': '10pt', 178 | 179 | # Additional stuff for the LaTeX preamble. 180 | #'preamble': '', 181 | } 182 | 183 | # Grouping the document tree into LaTeX files. List of tuples 184 | # (source start file, target name, title, author, documentclass [howto/manual]). 185 | latex_documents = [ 186 | ('index', 'aminator.tex', u'aminator Documentation', 187 | u'Netflix, Inc.', 'manual'), 188 | ] 189 | 190 | # The name of an image file (relative to this directory) to place at the top of 191 | # the title page. 192 | #latex_logo = None 193 | 194 | # For "manual" documents, if this is true, then toplevel headings are parts, 195 | # not chapters. 196 | #latex_use_parts = False 197 | 198 | # If true, show page references after internal links. 199 | #latex_show_pagerefs = False 200 | 201 | # If true, show URL addresses after external links. 202 | #latex_show_urls = False 203 | 204 | # Documents to append as an appendix to all manuals. 205 | #latex_appendices = [] 206 | 207 | # If false, no module index is generated. 208 | #latex_domain_indices = True 209 | 210 | 211 | # -- Options for manual page output -------------------------------------------- 212 | 213 | # One entry per manual page. List of tuples 214 | # (source start file, name, description, authors, manual section). 215 | man_pages = [ 216 | ('index', 'aminator', u'aminator Documentation', 217 | [u'Netflix, Inc.'], 1) 218 | ] 219 | 220 | # If true, show URL addresses after external links. 221 | #man_show_urls = False 222 | 223 | 224 | # -- Options for Texinfo output ------------------------------------------------ 225 | 226 | # Grouping the document tree into Texinfo files. List of tuples 227 | # (source start file, target name, title, author, 228 | # dir menu entry, description, category) 229 | texinfo_documents = [ 230 | ('index', 'aminator', u'aminator Documentation', 231 | u'Netflix, Inc.', 'aminator', 'One line description of project.', 232 | 'Miscellaneous'), 233 | ] 234 | 235 | # Documents to append as an appendix to all manuals. 236 | #texinfo_appendices = [] 237 | 238 | # If false, no module index is generated. 239 | #texinfo_domain_indices = True 240 | 241 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 242 | #texinfo_show_urls = 'footnote' 243 | -------------------------------------------------------------------------------- /aminator/plugins/finalizer/tagging_s3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.finalizer.tagging_s3 23 | ====================================== 24 | s3 tagging image finalizer 25 | """ 26 | import logging 27 | from shutil import rmtree 28 | from os.path import isdir 29 | from os import makedirs, system 30 | 31 | from os import environ 32 | from aminator.config import conf_action 33 | from aminator.exceptions import VolumeException 34 | from aminator.plugins.finalizer.tagging_base import TaggingBaseFinalizerPlugin 35 | from aminator.util import randword 36 | from aminator.util.linux import sanitize_metadata, monitor_command 37 | from aminator.util.metrics import cmdsucceeds, cmdfails, timer 38 | 39 | __all__ = ('TaggingS3FinalizerPlugin',) 40 | log = logging.getLogger(__name__) 41 | 42 | 43 | class TaggingS3FinalizerPlugin(TaggingBaseFinalizerPlugin): 44 | _name = 'tagging_s3' 45 | 46 | def add_plugin_args(self): 47 | tagging = super(TaggingS3FinalizerPlugin, self).add_plugin_args() 48 | 49 | context = self._config.context 50 | tagging.add_argument('-n', '--name', dest='name', action=conf_action(context.ami), help='name of resultant AMI (default package_name-version-release-arch-yyyymmddHHMM-s3') 51 | 52 | tagging.add_argument('--cert', dest='cert', action=conf_action(context.ami), help='The path to the PEM encoded RSA public key certificate file for ec2-bundle-volume') 53 | tagging.add_argument('--privatekey', dest='privatekey', action=conf_action(context.ami), help='The path to the PEM encoded RSA private key file for ec2-bundle-vol') 54 | tagging.add_argument('--ec2-user', dest='ec2_user', action=conf_action(context.ami), help='ec2 user id for ec2-bundle-vol') 55 | tagging.add_argument('--tmpdir', dest='tmpdir', action=conf_action(context.ami), help='temp directory used by ec2-bundle-vol') 56 | tagging.add_argument('--bucket', dest='bucket', action=conf_action(context.ami), help='the S3 bucket to use for ec2-upload-bundle') 57 | tagging.add_argument('--break-copy-volume', dest='break_copy_volume', action=conf_action(context.ami, action='store_true'), help='break into shell after copying the volume, for debugging') 58 | 59 | def _set_metadata(self): 60 | super(TaggingS3FinalizerPlugin, self)._set_metadata() 61 | context = self._config.context 62 | config = self._config.plugins[self.full_name] 63 | metadata = context.package.attributes 64 | ami_name = context.ami.get('name', None) 65 | if not ami_name: 66 | ami_name = config.name_format.format(**metadata) 67 | 68 | context.ami.name = sanitize_metadata('{0}-s3'.format(ami_name)) 69 | 70 | def tmpdir(self): 71 | config = self._config.plugins[self.full_name] 72 | ami = self._config.context.ami 73 | return "{0}/{1}".format(ami.get("tmpdir", config.get("default_tmpdir", "/tmp")), ami.name) 74 | 75 | # pylint: disable=access-member-before-definition 76 | def unique_name(self): 77 | context = self._config.context 78 | if hasattr(self, "_unique_name"): 79 | return self._unique_name 80 | self._unique_name = "{0}-{1}".format(context.ami.name, randword(6)) 81 | return self._unique_name 82 | 83 | def image_location(self): 84 | return "{0}/{1}".format(self.tmpdir(), self.unique_name()) 85 | 86 | @cmdsucceeds("aminator.finalizer.tagging_s3.copy_volume.count") 87 | @cmdfails("aminator.finalizer.tagging_s3.copy_volume.error") 88 | @timer("aminator.finalizer.tagging_s3.copy_volume.duration") 89 | def _copy_volume(self): 90 | context = self._config.context 91 | tmpdir = self.tmpdir() 92 | if not isdir(tmpdir): 93 | makedirs(tmpdir) 94 | return monitor_command(["dd", "bs=65536", "if={0}".format(context.volume.dev), "of={0}".format(self.image_location())]) 95 | 96 | @cmdsucceeds("aminator.finalizer.tagging_s3.bundle_image.count") 97 | @cmdfails("aminator.finalizer.tagging_s3.bundle_image.error") 98 | @timer("aminator.finalizer.tagging_s3.bundle_image.duration") 99 | def _bundle_image(self): 100 | context = self._config.context 101 | 102 | config = self._config.plugins[self.full_name] 103 | block_device_map = config.default_block_device_map 104 | root_device = config.default_root_device 105 | 106 | bdm = "root={0}".format(root_device) 107 | for bd in block_device_map: 108 | bdm += ",{0}={1}".format(bd[1], bd[0]) 109 | bdm += ",ami={0}".format(root_device) 110 | 111 | cmd = ['ec2-bundle-image'] 112 | cmd.extend(['-c', context.ami.get("cert", config.default_cert)]) 113 | cmd.extend(['-k', context.ami.get("privatekey", config.default_privatekey)]) 114 | cmd.extend(['-u', context.ami.get("ec2_user", str(config.default_ec2_user))]) 115 | cmd.extend(['-i', self.image_location()]) 116 | cmd.extend(['-d', self.tmpdir()]) 117 | if context.base_ami.architecture: 118 | cmd.extend(['-r', context.base_ami.architecture]) 119 | 120 | vm_type = context.ami.get("vm_type", "paravirtual") 121 | if vm_type == "paravirtual": 122 | if context.base_ami.kernel_id: 123 | cmd.extend(['--kernel', context.base_ami.kernel_id]) 124 | if context.base_ami.ramdisk_id: 125 | cmd.extend(['--ramdisk', context.base_ami.ramdisk_id]) 126 | cmd.extend(['-B', bdm]) 127 | return monitor_command(cmd) 128 | 129 | @cmdsucceeds("aminator.finalizer.tagging_s3.upload_bundle.count") 130 | @cmdfails("aminator.finalizer.tagging_s3.upload_bundle.error") 131 | @timer("aminator.finalizer.tagging_s3.upload_bundle.duration") 132 | def _upload_bundle(self): 133 | context = self._config.context 134 | 135 | provider = self._cloud._connection.provider 136 | ak = provider.get_access_key() 137 | sk = provider.get_secret_key() 138 | tk = provider.get_security_token() 139 | 140 | cmd = ['ec2-upload-bundle'] 141 | cmd.extend(['-b', context.ami.bucket]) 142 | cmd.extend(['-a', ak]) 143 | cmd.extend(['-s', sk]) 144 | if tk: 145 | cmd.extend(['-t', tk]) 146 | cmd.extend(['-m', "{0}.manifest.xml".format(self.image_location())]) 147 | cmd.extend(['--retry']) 148 | return monitor_command(cmd) 149 | 150 | def _register_image(self): 151 | context = self._config.context 152 | log.info('Registering image') 153 | if not self._cloud.register_image(manifest="{0}/{1}.manifest.xml".format(context.ami.bucket, self.unique_name())): 154 | return False 155 | log.info('Registration success') 156 | return True 157 | 158 | def finalize(self): 159 | log.info('Finalizing image') 160 | context = self._config.context 161 | 162 | self._set_metadata() 163 | 164 | ret = self._copy_volume() 165 | if not ret.success: 166 | log.debug('Error copying volume, failure:{0.command} :{0.std_err}'.format(ret.result)) 167 | return False 168 | 169 | if context.ami.get('break_copy_volume', False): 170 | system("bash") 171 | 172 | ret = self._bundle_image() 173 | if not ret.success: 174 | log.debug('Error bundling image, failure:{0.command} :{0.std_err}'.format(ret.result)) 175 | return False 176 | 177 | ret = self._upload_bundle() 178 | if not ret.success: 179 | log.debug('Error uploading bundled volume, failure:{0.command} :{0.std_err}'.format(ret.result)) 180 | return False 181 | 182 | if not self._register_image(): 183 | log.critical('Error registering image') 184 | return False 185 | 186 | if not self._add_tags(['ami']): 187 | log.critical('Error adding tags') 188 | return False 189 | 190 | log.info('Image registered and tagged') 191 | self._log_ami_metadata() 192 | return True 193 | 194 | def __enter__(self): 195 | context = self._config.context 196 | volume_size = context.ami.get('root_volume_size', None) 197 | if volume_size is None: 198 | volume_size = self._cloud.plugin_config.get('root_volume_size', None) 199 | if volume_size is not None: 200 | volume_size = int(volume_size) 201 | if volume_size > int(self.plugin_config.max_root_volume_size): 202 | raise VolumeException( 203 | 'Requested root volume size {} exceeds 10G maximum for ' 204 | 'S3-backed AMIs'.format(volume_size)) 205 | 206 | environ["AMINATOR_STORE_TYPE"] = "s3" 207 | if context.ami.get("name", None): 208 | environ["AMINATOR_AMI_NAME"] = context.ami.name 209 | if context.ami.get("cert", None): 210 | environ["AMINATOR_CERT"] = context.ami.cert 211 | if context.ami.get("privatekey", None): 212 | environ["AMINATOR_PRIVATEKEY"] = context.ami.privatekey 213 | if context.ami.get("ec2_user", None): 214 | environ["AMINATOR_EC2_USER"] = context.ami.ec2_user 215 | if context.ami.get("tmpdir", None): 216 | environ["AMINATOR_TMPDIR"] = context.ami.tmpdir 217 | if context.ami.get("bucket", None): 218 | environ["AMINATOR_BUCKET"] = context.ami.bucket 219 | 220 | return super(TaggingS3FinalizerPlugin, self).__enter__() 221 | 222 | def __exit__(self, exc_type, exc_value, trace): 223 | if exc_type: 224 | log.debug('Exception encountered in tagging s3 finalizer context manager', 225 | exc_info=(exc_type, exc_value, trace)) 226 | # delete tmpdir used by ec2-bundle-vol 227 | try: 228 | td = self.tmpdir() 229 | if isdir(td): 230 | rmtree(td) 231 | except Exception: 232 | log.debug('Exception encountered attempting to clean s3 bundle tmpdir', 233 | exc_info=True) 234 | return False 235 | -------------------------------------------------------------------------------- /aminator/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.config 23 | =============== 24 | aminator configuration, argument handling, and logging setup 25 | """ 26 | import argparse 27 | import logging 28 | import os 29 | import sys 30 | from copy import deepcopy 31 | from datetime import datetime 32 | 33 | from aminator.util import randword 34 | try: 35 | from logging.config import dictConfig 36 | except ImportError: 37 | # py26 38 | from logutils.dictconfig import dictConfig 39 | 40 | import bunch 41 | from pkg_resources import resource_string, resource_exists 42 | 43 | try: 44 | from yaml import CLoader as Loader # pylint: disable=redefined-outer-name 45 | except ImportError: 46 | from yaml import Loader 47 | 48 | import aminator 49 | 50 | 51 | __all__ = () 52 | log = logging.getLogger(__name__) 53 | _action_registries = argparse.ArgumentParser()._registries['action'] 54 | 55 | RSRC_PKG = 'aminator' 56 | RSRC_DEFAULT_CONF_DIR = 'default_conf' 57 | RSRC_DEFAULT_CONFS = { 58 | 'main': os.path.join(RSRC_DEFAULT_CONF_DIR, 'aminator.yml'), 59 | 'logging': os.path.join(RSRC_DEFAULT_CONF_DIR, 'logging.yml'), 60 | 'environments': os.path.join(RSRC_DEFAULT_CONF_DIR, 'environments.yml'), 61 | } 62 | 63 | 64 | def init_defaults(argv=None, debug=False): 65 | argv = argv or sys.argv[1:] 66 | config = Config.from_defaults() 67 | config = config.dict_merge(config, Config.from_files(config.config_files.main, config.config_root)) 68 | main_parser = Argparser(argv=argv, description='Aminator: bringing AMIs to life', add_help=False, argument_default=argparse.SUPPRESS) 69 | config.logging = LoggingConfig.from_defaults() 70 | config.logging = config.dict_merge(config.logging, LoggingConfig.from_files(config.config_files.logging, config.config_root)) 71 | config.environments = EnvironmentConfig.from_defaults() 72 | config.environments = config.dict_merge(config.environments, EnvironmentConfig.from_files(config.config_files.environments, config.config_root)) 73 | default_metrics = getattr(config.environments, "metrics", "logger") 74 | for env in config.environments: 75 | if isinstance(config.environments[env], dict): 76 | if "metrics" not in config.environments[env]: 77 | config.environments[env]["metrics"] = default_metrics 78 | 79 | if config.logging.base.enabled: 80 | dictConfig(config.logging.base.config.toDict()) 81 | if debug: 82 | logging.getLogger().setLevel(logging.DEBUG) 83 | for handler in logging.getLogger().handlers: 84 | handler.setLevel(logging.DEBUG) 85 | 86 | add_base_arguments(parser=main_parser, config=config) 87 | plugin_parser = Argparser(argv=argv, add_help=True, argument_default=argparse.SUPPRESS, parents=[main_parser]) 88 | log.info('Aminator {0} default configuration loaded'.format(aminator.__version__)) 89 | return config, plugin_parser 90 | 91 | 92 | class Config(bunch.Bunch): 93 | """ Base config class """ 94 | resource_package = RSRC_PKG 95 | resource_default = RSRC_DEFAULT_CONFS['main'] 96 | 97 | @classmethod 98 | def from_yaml(cls, yaml_data, Loader=Loader, *args, **kwargs): # pylint: disable=redefined-outer-name 99 | return cls(cls.fromYAML(yaml_data, Loader=Loader, *args, **kwargs)) 100 | 101 | @classmethod 102 | def from_pkg_resource(cls, namespace, name, *args, **kwargs): 103 | config = resource_string(namespace, name) 104 | if len(config): 105 | return cls.from_yaml(config, *args, **kwargs) 106 | else: 107 | log.warn('Resource for {0}.{1} is empty, returning empty config'.format(namespace, name)) 108 | 109 | @classmethod 110 | def from_file(cls, yaml_file, *args, **kwargs): 111 | if not os.path.exists(yaml_file): 112 | log.warn('File {0} not found, returning empty config'.format(yaml_file)) 113 | return cls() 114 | with open(yaml_file) as f: 115 | _config = cls.from_yaml(f, *args, **kwargs) 116 | return _config 117 | 118 | @classmethod 119 | def from_files(cls, files, config_root="", *args, **kwargs): 120 | _files = [os.path.expanduser(filename) for filename in files] 121 | _files = [(x if x.startswith('/') else os.path.join(config_root, x)) for x in _files] 122 | _files = [filename for filename in _files if os.path.exists(filename)] 123 | _config = cls() 124 | for filename in _files: 125 | _new = cls.from_file(filename, *args, **kwargs) 126 | _config = cls.dict_merge(_config, _new) 127 | return _config 128 | 129 | @classmethod 130 | def from_defaults(cls, namespace=None, name=None, *args, **kwargs): 131 | if namespace and name and resource_exists(namespace, name): 132 | _namespace = namespace 133 | _name = name 134 | elif (cls.resource_package and cls.resource_default and resource_exists(cls.resource_package, cls.resource_default)): 135 | _namespace = cls.resource_package 136 | _name = cls.resource_default 137 | else: 138 | log.warn('No class resource attributes and no namespace info, returning empty config') 139 | return cls(*args, **kwargs) 140 | return cls.from_pkg_resource(_namespace, _name, *args, **kwargs) 141 | 142 | @staticmethod 143 | def dict_merge(old, new): 144 | res = deepcopy(old) 145 | for k, v in new.iteritems(): 146 | if k in res and isinstance(res[k], dict): 147 | res[k] = Config.dict_merge(res[k], v) 148 | else: 149 | res[k] = deepcopy(v) 150 | return res 151 | 152 | def __call__(self): 153 | return 154 | 155 | 156 | class LoggingConfig(Config): 157 | """ Logging config class """ 158 | resource_default = RSRC_DEFAULT_CONFS['logging'] 159 | 160 | 161 | def configure_datetime_logfile(config, handler): 162 | try: 163 | filename_format = config.logging[handler]['filename_format'] 164 | except KeyError: 165 | log.error('filename_format not configured for handler {0}'.format(handler)) 166 | return 167 | 168 | try: 169 | pkg = "{0}-{1}".format(os.path.basename(config.context.package.arg), randword(6)) 170 | filename = os.path.join(config.log_root, filename_format.format(pkg, datetime.utcnow())) 171 | except IndexError: 172 | errstr = 'Missing replacement fields in filename_format for handler {0}'.format(handler) 173 | log.error(errstr) 174 | log.debug(errstr, exc_info=True) 175 | 176 | # find handler amongst all the loggers and reassign the filename/stream 177 | for h in [x for l in logging.root.manager.loggerDict for x in logging.getLogger(l).handlers] + logging.root.handlers: 178 | if getattr(h, 'name', '') == handler: 179 | assert isinstance(h, logging.FileHandler) 180 | h.stream.close() 181 | h.baseFilename = filename 182 | h.stream = open(filename, 'a') 183 | url_template = config.logging[handler].get('web_log_url_template', False) 184 | if url_template: 185 | url_attrs = config.context.web_log.toDict() 186 | url_attrs['logfile'] = os.path.basename(filename) 187 | url = url_template.format(**url_attrs) 188 | log.info('Detailed {0} output to {1}'.format(handler, url)) 189 | else: 190 | log.info('Detailed {0} output to {1}'.format(handler, filename)) 191 | break 192 | else: 193 | log.error('{0} handler not found.'.format(handler)) 194 | 195 | 196 | class EnvironmentConfig(Config): 197 | """ Environment config class """ 198 | resource_default = RSRC_DEFAULT_CONFS['environments'] 199 | 200 | 201 | class PluginConfig(Config): 202 | """ Plugin config class """ 203 | resource_package = resource_default = None 204 | 205 | @classmethod 206 | def from_defaults(cls, namespace=None, name=None, *args, **kwargs): 207 | if not all((namespace, name)): 208 | raise ValueError('Plugins must specify a namespace and name') 209 | resource_file = '.'.join((namespace, name, 'yml')) 210 | resource_path = os.path.join(RSRC_DEFAULT_CONF_DIR, resource_file) 211 | return super(PluginConfig, cls).from_defaults(namespace=namespace, name=resource_path, *args, **kwargs) 212 | 213 | 214 | class Argparser(object): 215 | """ Argument parser class. Holds the keys to argparse """ 216 | 217 | def __init__(self, argv=None, *args, **kwargs): 218 | self._argv = argv or sys.argv[1:] 219 | self._parser = argparse.ArgumentParser(*args, **kwargs) 220 | 221 | def add_config_arg(self, *args, **kwargs): 222 | config = kwargs.pop('config', Config()) 223 | _action = kwargs.pop('action', None) 224 | action = conf_action(config, _action) 225 | kwargs['action'] = action 226 | return self.add_argument(*args, **kwargs) 227 | 228 | def __getattr__(self, attr): 229 | return getattr(self._parser, attr) 230 | 231 | 232 | def add_base_arguments(parser, config): 233 | parser.add_config_arg('arg', metavar='package_spec', config=config.context.package, help='package to aminate. A string resolvable by the native package manager or a file system path or http url to the package file.') 234 | parser.add_config_arg('-e', '--environment', config=config.context, help='The environment configuration for amination') 235 | parser.add_config_arg('--preserve-on-error', action='store_true', config=config.context, help='For Debugging. Preserve build chroot on error') 236 | parser.add_config_arg('--verify-https', action='store_true', config=config.context, help='Specify if one wishes for plugins to verify SSL certs when hitting https URLs') 237 | parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(aminator.__version__)) 238 | parser.add_argument('--debug', action='store_true', help='Verbose debugging output') 239 | 240 | 241 | def conf_action(config, action=None): 242 | """ 243 | class factory function that dynamically creates special ConfigAction 244 | forms of argparse actions, injecting a config object into the namespace 245 | """ 246 | action_subclass = _action_registries[action] 247 | action_class_name = 'ConfigAction_{0}'.format(action_subclass.__name__) 248 | 249 | def _action_call(self, parser, namespace, values, option_string=None): 250 | return super(self.__class__, self).__call__(parser, config, values, option_string) 251 | 252 | action_class = type(action_class_name, (action_subclass,), {'__call__': _action_call}) 253 | return action_class 254 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012 Netflix 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /aminator/plugins/distro/linux.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # 4 | # 5 | # Copyright 2013 Netflix, Inc. 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | 21 | """ 22 | aminator.plugins.distro.linux 23 | ================================== 24 | Simple base class for cases where there are small distro-specific corner cases 25 | """ 26 | import abc 27 | import logging 28 | import os.path 29 | 30 | from aminator.exceptions import VolumeException 31 | from aminator.plugins.distro.base import BaseDistroPlugin 32 | from aminator.util import retry 33 | from aminator.util.linux import ( 34 | lifo_mounts, mount, mounted, MountSpec, unmount, busy_mount) 35 | from aminator.util.linux import install_provision_configs, remove_provision_configs 36 | from aminator.util.linux import short_circuit_files, rewire_files 37 | from aminator.util.metrics import fails, timer, raises 38 | 39 | __all__ = ('BaseLinuxDistroPlugin',) 40 | log = logging.getLogger(__name__) 41 | 42 | 43 | class BaseLinuxDistroPlugin(BaseDistroPlugin): 44 | """ 45 | Most of what goes on between apt and yum provisioning is the same, so we factored that out, 46 | leaving the differences in the actual implementations 47 | """ 48 | __metaclass__ = abc.ABCMeta 49 | 50 | def _activate_provisioning_service_block(self): 51 | """ 52 | Enable service startup so that things work when the AMI starts 53 | For RHEL-like systems, we undo the short_circuit 54 | """ 55 | config = self._config.plugins[self.full_name] 56 | files = config.get('short_circuit_files', []) 57 | if files: 58 | if not rewire_files(self.root_mountspec.mountpoint, files): 59 | log.warning("Unable to rewire some files") 60 | return True 61 | else: 62 | log.debug('Files rewired successfully') 63 | return True 64 | else: 65 | log.debug('No short circuit files configured, no rewiring done') 66 | return True 67 | 68 | def _deactivate_provisioning_service_block(self): 69 | """ 70 | Prevent packages installing the chroot from starting 71 | For RHEL-like systems, we can use short_circuit which replaces the service call with /bin/true 72 | """ 73 | config = self._config.plugins[self.full_name] 74 | files = config.get('short_circuit_files', []) 75 | if files: 76 | if not short_circuit_files(self.root_mountspec.mountpoint, files): 77 | log.warning('Unable to short circuit some files') 78 | return True 79 | else: 80 | log.debug('Files short-circuited successfully') 81 | return True 82 | else: 83 | log.debug('No short circuit files configured') 84 | return True 85 | 86 | @fails("aminator.distro.linux.mount.error") 87 | def _mount(self, mountspec): 88 | if not mounted(mountspec): 89 | result = mount(mountspec) 90 | if not result.success: 91 | msg = 'Unable to mount {0.dev} at {0.mountpoint}: {1}'.format(mountspec, result.result.std_err) 92 | log.critical(msg) 93 | return False 94 | log.debug('Device {0.dev} mounted at {0.mountpoint}'.format(mountspec)) 95 | return True 96 | 97 | @raises("aminator.distro.linux.umount.error") 98 | @retry(VolumeException, tries=10, delay=1, backoff=1, logger=log, maxdelay=1) 99 | def _unmount(self, mountspec): 100 | recursive_unmount = self.plugin_config.get('recursive_unmount', False) 101 | if mounted(mountspec): 102 | result = unmount(mountspec, recursive=recursive_unmount) 103 | if not result.success: 104 | err = 'Failed to unmount {0}: {1}' 105 | err = err.format(mountspec.mountpoint, result.result.std_err) 106 | open_files = busy_mount(mountspec.mountpoint) 107 | if open_files.success: 108 | err = '{0}. Device has open files:\n{1}'.format(err, open_files.result.std_out) 109 | raise VolumeException(err) 110 | log.debug('Unmounted {0.mountpoint}'.format(mountspec)) 111 | 112 | @fails("aminator.distro.linux.configure_chroot.error") 113 | @timer("aminator.distro.linux.configure_chroot.duration") 114 | def _configure_chroot(self): 115 | config = self.plugin_config 116 | log.debug('Configuring chroot at {0.mountpoint}'.format(self.root_mountspec)) 117 | if not self._configure_chroot_mounts(): 118 | log.critical('Configuration of chroot mounts failed') 119 | return False 120 | if config.get('provision_configs', True): 121 | if not self._install_provision_configs(): 122 | log.critical('Installation of provisioning config failed') 123 | return False 124 | 125 | log.debug("starting short_circuit ") 126 | # TODO: kvick we should rename 'short_circuit' to something like 'disable_service_start' 127 | if config.get('short_circuit', False): 128 | if not self._deactivate_provisioning_service_block(): 129 | log.critical('Failure short-circuiting files') 130 | return False 131 | 132 | log.debug("finished short_circuit") 133 | 134 | log.debug('Chroot environment ready') 135 | return True 136 | 137 | def _configure_chroot_mounts(self): 138 | log.debug('Attempting to mount root volume: {0}'.format(self.root_mountspec)) 139 | if not self._mount(self.root_mountspec): 140 | log.critical('Failed to mount root volume') 141 | return False 142 | if self.plugin_config.get('configure_mounts', True): 143 | for mountdef in self.plugin_config.chroot_mounts: 144 | dev, fstype, mountpoint, options = mountdef 145 | mountpoint = mountpoint.lstrip('/') 146 | mountpoint = os.path.join(self.root_mountspec.mountpoint, mountpoint) 147 | mountspec = MountSpec(dev, fstype, mountpoint, options) 148 | log.debug('Attempting to mount {0}'.format(mountspec)) 149 | if not self._mount(mountspec): 150 | log.critical('Mount failure, unable to configure chroot') 151 | return False 152 | log.debug('Mounts configured') 153 | return True 154 | 155 | def _install_provision_configs(self): 156 | config = self.plugin_config 157 | files = config.get('provision_config_files', []) 158 | if files: 159 | if not install_provision_configs(files, self.root_mountspec.mountpoint): 160 | log.critical('Error installing provisioning configs') 161 | return False 162 | else: 163 | log.debug('Provision config files successfully installed') 164 | return True 165 | else: 166 | log.debug('No provision config files configured') 167 | return True 168 | 169 | def _unmount_root(self): 170 | try: 171 | self._unmount(self.root_mountspec) 172 | except VolumeException as ve: 173 | return False 174 | else: 175 | return True 176 | 177 | @fails("aminator.distro.linux.teardown_chroot.error") 178 | @timer("aminator.distro.linux.teardown_chroot.duration") 179 | def _teardown_chroot(self): 180 | log.debug('Tearing down chroot at {0.mountpoint}'.format(self.root_mountspec)) 181 | # TODO: kvick we should rename 'short_circuit' to something like 'disable_service_start' 182 | if self.plugin_config.get('short_circuit', True): 183 | if not self._activate_provisioning_service_block(): 184 | log.critical('Failure during re-enabling service startup') 185 | return False 186 | if self.plugin_config.get('provision_configs', True): 187 | if not self._remove_provision_configs(): 188 | log.critical('Removal of provisioning config failed') 189 | return False 190 | if not self._teardown_chroot_mounts(): 191 | log.critical('Teardown of chroot mounts failed') 192 | return False 193 | 194 | log.debug('Chroot environment cleaned') 195 | return True 196 | 197 | def _teardown_chroot_mounts(self): 198 | if not self.plugin_config.get('recursive_unmount', False): 199 | if self.plugin_config.get('configure_mounts', True): 200 | for mountdef in reversed(self.plugin_config.chroot_mounts): 201 | dev, fstype, mountpoint, options = mountdef 202 | mountpoint = mountpoint.lstrip('/') 203 | mountpoint = os.path.join(self.root_mountspec.mountpoint, mountpoint) 204 | mountspec = MountSpec(dev, fstype, mountpoint, options) 205 | log.debug('Attempting to unmount {0.mountpoint}'.format(mountspec)) 206 | try: 207 | self._unmount(mountspec) 208 | except VolumeException as ve: 209 | log.critical('Unable to unmount {0.mountpoint}'.format(mountspec)) 210 | return False 211 | log.debug('Checking for stray mounts') 212 | for mountpoint in lifo_mounts(self.root_mountspec.mountpoint): 213 | log.debug('Stray mount found: {0}, attempting to unmount'.format(mountpoint)) 214 | try: 215 | self._unmount(mountpoint) 216 | except VolumeException as ve: 217 | log.critical('Unable to unmount {0}'.format(mountpoint)) 218 | return False 219 | if not self._unmount_root(): 220 | err = 'Unable to unmount root volume at {0.mountpoint)' 221 | err = err.format(self.root_mountspec) 222 | log.critical(err) 223 | return False 224 | log.debug('Teardown of chroot mounts succeeded!') 225 | return True 226 | 227 | def _remove_provision_configs(self): 228 | config = self.plugin_config 229 | files = config.get('provision_config_files', []) 230 | if files: 231 | if not remove_provision_configs(files, self.root_mountspec.mountpoint): 232 | log.critical('Error removing provisioning configs') 233 | return False 234 | else: 235 | log.debug('Provision config files successfully removed') 236 | return True 237 | else: 238 | log.debug('No provision config files configured') 239 | return True 240 | 241 | @property 242 | def root_mountspec(self): 243 | return self._root_mountspec 244 | 245 | def __enter__(self): 246 | if self._config.volume_dir.startswith(('~', '/')): 247 | root_base = os.path.expanduser(self._config.volume_dir) 248 | else: 249 | root_base = os.path.join(self._config.aminator_root, self._config.volume_dir) 250 | root_mountpoint = os.path.join(root_base, os.path.basename(self.context.volume.dev)) 251 | self._root_mountspec = MountSpec(self.context.volume.dev, None, root_mountpoint, None) 252 | 253 | try: 254 | chroot_setup = self._configure_chroot() 255 | except Exception as e: 256 | chroot_setup = False 257 | log.critical('Error encountered during chroot setup. Attempting to clean up volumes.') 258 | self._teardown_chroot_mounts() 259 | if not chroot_setup: 260 | raise VolumeException('Error configuring chroot') 261 | return self 262 | 263 | def __exit__(self, exc_type, exc_value, trace): 264 | if exc_type: 265 | log.debug('Exception encountered in Linux distro plugin context manager', 266 | exc_info=(exc_type, exc_value, trace)) 267 | if exc_type and self._config.context.get("preserve_on_error", False): 268 | return False 269 | if not self._teardown_chroot(): 270 | raise VolumeException('Error tearing down chroot') 271 | return False 272 | --------------------------------------------------------------------------------