├── lambda ├── chef │ ├── utils │ │ ├── __init__.py │ │ ├── file.py │ │ └── json.py │ ├── role.py │ ├── permissions.py │ ├── environment.py │ ├── __init__.py │ ├── tests │ │ ├── test_environment.py │ │ ├── test_fabric.py │ │ ├── test_api.py │ │ ├── test_client.py │ │ ├── test_role.py │ │ ├── __init__.py │ │ ├── test_rsa.py │ │ ├── test_search.py │ │ └── test_data_bag.py │ ├── exceptions.py │ ├── client.py │ ├── auth.py │ ├── search.py │ └── data_bag.py ├── pkg_resources │ ├── _vendor │ │ ├── __init__.py │ │ └── packaging │ │ │ ├── __init__.py │ │ │ ├── __about__.py │ │ │ ├── _compat.py │ │ │ └── _structures.py │ └── extern │ │ └── __init__.py ├── PyChef-0.3.0.dist-info │ ├── INSTALLER │ ├── top_level.txt │ ├── WHEEL │ ├── DESCRIPTION.rst │ ├── metadata.json │ ├── METADATA │ └── RECORD ├── setuptools-20.1.1.dist-info │ ├── zip-safe │ ├── INSTALLER │ ├── top_level.txt │ ├── WHEEL │ ├── dependency_links.txt │ ├── entry_points.txt │ └── metadata.json ├── six-1.10.0.dist-info │ ├── INSTALLER │ ├── top_level.txt │ ├── WHEEL │ ├── metadata.json │ ├── RECORD │ ├── DESCRIPTION.rst │ └── METADATA ├── requests-2.10.0.dist-info │ ├── INSTALLER │ ├── top_level.txt │ ├── WHEEL │ └── metadata.json ├── requests │ ├── packages │ │ ├── urllib3 │ │ │ ├── contrib │ │ │ │ ├── __init__.py │ │ │ │ └── ntlmpool.py │ │ │ ├── packages │ │ │ │ ├── __init__.py │ │ │ │ └── ssl_match_hostname │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── _implementation.py │ │ │ ├── util │ │ │ │ ├── __init__.py │ │ │ │ ├── request.py │ │ │ │ ├── response.py │ │ │ │ └── connection.py │ │ │ ├── filepost.py │ │ │ └── __init__.py │ │ ├── chardet │ │ │ ├── compat.py │ │ │ ├── __init__.py │ │ │ ├── constants.py │ │ │ ├── euckrprober.py │ │ │ ├── euctwprober.py │ │ │ ├── gb2312prober.py │ │ │ ├── big5prober.py │ │ │ ├── cp949prober.py │ │ │ ├── charsetprober.py │ │ │ ├── mbcsgroupprober.py │ │ │ ├── codingstatemachine.py │ │ │ ├── chardetect.py │ │ │ ├── utf8prober.py │ │ │ ├── escprober.py │ │ │ ├── sbcsgroupprober.py │ │ │ ├── mbcharsetprober.py │ │ │ ├── eucjpprober.py │ │ │ ├── sjisprober.py │ │ │ └── charsetgroupprober.py │ │ └── __init__.py │ ├── certs.py │ ├── hooks.py │ ├── compat.py │ ├── __init__.py │ ├── exceptions.py │ ├── structures.py │ └── status_codes.py ├── setuptools │ ├── version.py │ ├── cli.exe │ ├── gui.exe │ ├── cli-32.exe │ ├── cli-64.exe │ ├── gui-32.exe │ ├── gui-64.exe │ ├── cli-arm-32.exe │ ├── gui-arm-32.exe │ ├── script.tmpl │ ├── extern │ │ └── __init__.py │ ├── script (dev).tmpl │ ├── command │ │ ├── register.py │ │ ├── __init__.py │ │ ├── launcher manifest.xml │ │ ├── bdist_wininst.py │ │ ├── upload.py │ │ ├── saveopts.py │ │ ├── bdist_rpm.py │ │ ├── rotate.py │ │ ├── install_scripts.py │ │ ├── alias.py │ │ ├── install_lib.py │ │ └── install_egg_info.py │ ├── utils.py │ ├── py27compat.py │ ├── py26compat.py │ ├── windows_support.py │ ├── launch.py │ ├── unicode_utils.py │ ├── py31compat.py │ ├── extension.py │ ├── lib2to3_ex.py │ ├── msvc9_support.py │ └── site-patch.py ├── easy_install.py ├── local_config.py ├── _markerlib │ ├── __init__.py │ └── markers.py ├── main_test.py └── main.py ├── NOTICE.txt ├── requirements.txt ├── .gitignore └── terraform ├── variables.tf └── main.tf /lambda/chef/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambda/pkg_resources/_vendor/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/zip-safe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | chef 2 | -------------------------------------------------------------------------------- /lambda/requests-2.10.0.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | six 2 | -------------------------------------------------------------------------------- /lambda/setuptools/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '20.1.1' 2 | -------------------------------------------------------------------------------- /lambda/requests-2.10.0.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | requests 2 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | _markerlib 2 | easy_install 3 | pkg_resources 4 | setuptools 5 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | lambda-chef-node-cleanup 2 | Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /lambda/setuptools/cli.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/cli.exe -------------------------------------------------------------------------------- /lambda/setuptools/gui.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/gui.exe -------------------------------------------------------------------------------- /lambda/setuptools/cli-32.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/cli-32.exe -------------------------------------------------------------------------------- /lambda/setuptools/cli-64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/cli-64.exe -------------------------------------------------------------------------------- /lambda/setuptools/gui-32.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/gui-32.exe -------------------------------------------------------------------------------- /lambda/setuptools/gui-64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/gui-64.exe -------------------------------------------------------------------------------- /lambda/setuptools/cli-arm-32.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/cli-arm-32.exe -------------------------------------------------------------------------------- /lambda/setuptools/gui-arm-32.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/podio/lambda-chef-node-cleanup/master/lambda/setuptools/gui-arm-32.exe -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.26.0) 3 | Root-Is-Purelib: true 4 | Tag: py2-none-any 5 | 6 | -------------------------------------------------------------------------------- /lambda/easy_install.py: -------------------------------------------------------------------------------- 1 | """Run the EasyInstall command""" 2 | 3 | if __name__ == '__main__': 4 | from setuptools.command.easy_install import main 5 | main() 6 | -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.26.0) 3 | Root-Is-Purelib: true 4 | Tag: py2-none-any 5 | Tag: py3-none-any 6 | 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pytest==2.8.7 2 | pytest-cov==2.2.1 3 | boto3==1.3.1 4 | botocore==1.4.17 5 | mock==1.3.0 6 | aws_lambda_sample_events==1.0.1 7 | pychef==0.3.0 8 | -------------------------------------------------------------------------------- /lambda/requests-2.10.0.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.29.0) 3 | Root-Is-Purelib: true 4 | Tag: py2-none-any 5 | Tag: py3-none-any 6 | 7 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.26.0) 3 | Root-Is-Purelib: true 4 | Tag: py2-none-any 5 | Tag: py3-none-any 6 | 7 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import ssl_match_hostname 4 | 5 | __all__ = ('ssl_match_hostname', ) 6 | -------------------------------------------------------------------------------- /lambda/setuptools/script.tmpl: -------------------------------------------------------------------------------- 1 | # EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r 2 | __requires__ = %(spec)r 3 | __import__('pkg_resources').run_script(%(spec)r, %(script_name)r) 4 | -------------------------------------------------------------------------------- /lambda/setuptools/extern/__init__.py: -------------------------------------------------------------------------------- 1 | from pkg_resources.extern import VendorImporter 2 | 3 | 4 | names = 'six', 5 | VendorImporter(__name__, names, 'pkg_resources._vendor').install() 6 | -------------------------------------------------------------------------------- /lambda/chef/utils/file.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def walk_backwards(path): 4 | while 1: 5 | yield path 6 | next_path = os.path.dirname(path) 7 | if path == next_path: 8 | break 9 | path = next_path 10 | -------------------------------------------------------------------------------- /lambda/setuptools/script (dev).tmpl: -------------------------------------------------------------------------------- 1 | # EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r 2 | __requires__ = %(spec)r 3 | __import__('pkg_resources').require(%(spec)r) 4 | __file__ = %(dev_path)r 5 | exec(compile(open(__file__).read(), __file__, 'exec')) 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **.pyc 2 | **__pycache__ 3 | **.cache 4 | .coverage 5 | **terraform.tfvars 6 | terraform.tfstate 7 | terraform.tfstate.backup 8 | project.json 9 | **.crt 10 | **.DS_STORE 11 | lambda_function_payload.zip 12 | lambda/encrypted_pem.txt 13 | venv/ 14 | .chef/ 15 | -------------------------------------------------------------------------------- /lambda/local_config.py: -------------------------------------------------------------------------------- 1 | # I expect you to replace this file with your local config 2 | REGION= 'us-west-2' # Change to region your AWS Lambda function is in 3 | CHEF_SERVER_URL = 'https://my_server/organizations/thisorg' 4 | USERNAME = 'username' 5 | VERIFY_SSL = False 6 | DEBUG = False 7 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | https://pypi.python.org/packages/source/c/certifi/certifi-2015.11.20.tar.gz#md5=25134646672c695c1ff1593c2dd75d08 2 | https://pypi.python.org/packages/source/w/wincertstore/wincertstore-0.2.zip#md5=ae728f2f007185648d0c7a8679b361e2 3 | -------------------------------------------------------------------------------- /lambda/setuptools/command/register.py: -------------------------------------------------------------------------------- 1 | import distutils.command.register as orig 2 | 3 | 4 | class register(orig.register): 5 | __doc__ = orig.register.__doc__ 6 | 7 | def run(self): 8 | # Make sure that we are using valid current name/version info 9 | self.run_command('egg_info') 10 | orig.register.run(self) 11 | -------------------------------------------------------------------------------- /lambda/setuptools/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | 4 | 5 | def cs_path_exists(fspath): 6 | if not os.path.exists(fspath): 7 | return False 8 | # make absolute so we always have a directory 9 | abspath = os.path.abspath(fspath) 10 | directory, filename = os.path.split(abspath) 11 | return filename in os.listdir(directory) -------------------------------------------------------------------------------- /lambda/chef/role.py: -------------------------------------------------------------------------------- 1 | from chef.base import ChefObject 2 | 3 | class Role(ChefObject): 4 | """A Chef role object.""" 5 | 6 | url = '/roles' 7 | attributes = { 8 | 'description': str, 9 | 'run_list': list, 10 | 'default_attributes': dict, 11 | 'override_attributes': dict, 12 | 'env_run_lists': dict 13 | } 14 | -------------------------------------------------------------------------------- /lambda/setuptools/py27compat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compatibility Support for Python 2.7 and earlier 3 | """ 4 | 5 | import sys 6 | 7 | def get_all_headers(message, key): 8 | """ 9 | Given an HTTPMessage, return all headers matching a given key. 10 | """ 11 | return message.get_all(key) 12 | 13 | if sys.version_info < (3,): 14 | def get_all_headers(message, key): 15 | return message.getheaders(key) 16 | -------------------------------------------------------------------------------- /lambda/chef/permissions.py: -------------------------------------------------------------------------------- 1 | class Permissions(object): 2 | """ Represents single permissions object with list of actors and groups """ 3 | 4 | def __init__(self): 5 | self.actors = [] 6 | self.groups = [] 7 | 8 | def to_dict(self): 9 | d = { 10 | "actors": self.actors, 11 | "groups": self.groups 12 | } 13 | 14 | return d 15 | -------------------------------------------------------------------------------- /lambda/chef/environment.py: -------------------------------------------------------------------------------- 1 | from chef.base import ChefObject 2 | 3 | class Environment(ChefObject): 4 | """A Chef environment object. 5 | 6 | .. versionadded:: 0.2 7 | """ 8 | 9 | url = '/environments' 10 | 11 | api_version = '0.10' 12 | 13 | attributes = { 14 | 'description': str, 15 | 'cookbook_versions': dict, 16 | 'default_attributes': dict, 17 | 'override_attributes': dict, 18 | } 19 | -------------------------------------------------------------------------------- /lambda/chef/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2010 Noah Kantrowitz 2 | 3 | __version__ = (0, 3, 0) 4 | 5 | from chef.api import ChefAPI, autoconfigure 6 | from chef.client import Client 7 | from chef.data_bag import DataBag, DataBagItem 8 | from chef.exceptions import ChefError 9 | from chef.node import Node 10 | from chef.role import Role 11 | from chef.environment import Environment 12 | from chef.search import Search 13 | from chef.acl import Acl 14 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | # Python 3.2+ 3 | from ssl import CertificateError, match_hostname 4 | except ImportError: 5 | try: 6 | # Backport of the function from a pypi module 7 | from backports.ssl_match_hostname import CertificateError, match_hostname 8 | except ImportError: 9 | # Our vendored copy 10 | from ._implementation import CertificateError, match_hostname 11 | 12 | # Not needed, but documenting what we provide. 13 | __all__ = ('CertificateError', 'match_hostname') 14 | -------------------------------------------------------------------------------- /lambda/setuptools/py26compat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compatibility Support for Python 2.6 and earlier 3 | """ 4 | 5 | import sys 6 | 7 | try: 8 | from urllib.parse import splittag 9 | except ImportError: 10 | from urllib import splittag 11 | 12 | def strip_fragment(url): 13 | """ 14 | In `Python 8280 `_, Python 2.7 and 15 | later was patched to disregard the fragment when making URL requests. 16 | Do the same for Python 2.6 and earlier. 17 | """ 18 | url, fragment = splittag(url) 19 | return url 20 | 21 | if sys.version_info >= (2,7): 22 | strip_fragment = lambda x: x 23 | -------------------------------------------------------------------------------- /lambda/_markerlib/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | import ast 3 | from _markerlib.markers import default_environment, compile, interpret 4 | except ImportError: 5 | if 'ast' in globals(): 6 | raise 7 | def default_environment(): 8 | return {} 9 | def compile(marker): 10 | def marker_fn(environment=None, override=None): 11 | # 'empty markers are True' heuristic won't install extra deps. 12 | return not marker.strip() 13 | marker_fn.__doc__ = marker 14 | return marker_fn 15 | def interpret(marker, environment=None, override=None): 16 | return compile(marker)() 17 | -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/DESCRIPTION.rst: -------------------------------------------------------------------------------- 1 | PyChef 2 | ====== 3 | 4 | .. image:: https://secure.travis-ci.org/coderanger/pychef.png?branch=master 5 | :target: http://travis-ci.org/coderanger/pychef 6 | 7 | A Python API for interacting with a Chef server. 8 | 9 | Example 10 | ------- 11 | 12 | :: 13 | 14 | from chef import autoconfigure, Node 15 | 16 | api = autoconfigure() 17 | n = Node('web1') 18 | print n['fqdn'] 19 | n['myapp']['version'] = '1.0' 20 | n.save() 21 | 22 | Further Reading 23 | --------------- 24 | 25 | For more information check out http://pychef.readthedocs.org/en/latest/index.html 26 | 27 | 28 | -------------------------------------------------------------------------------- /lambda/setuptools/command/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = [ 2 | 'alias', 'bdist_egg', 'bdist_rpm', 'build_ext', 'build_py', 'develop', 3 | 'easy_install', 'egg_info', 'install', 'install_lib', 'rotate', 'saveopts', 4 | 'sdist', 'setopt', 'test', 'install_egg_info', 'install_scripts', 5 | 'register', 'bdist_wininst', 'upload_docs', 'upload', 6 | ] 7 | 8 | from distutils.command.bdist import bdist 9 | import sys 10 | 11 | from setuptools.command import install_scripts 12 | 13 | 14 | if 'egg' not in bdist.format_commands: 15 | bdist.format_command['egg'] = ('bdist_egg', "Python .egg file") 16 | bdist.format_commands.append('egg') 17 | 18 | del bdist, sys 19 | -------------------------------------------------------------------------------- /terraform/variables.tf: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file 4 | # except in compliance with the License. A copy of the License is located at 5 | # 6 | # http://aws.amazon.com/apache2.0/ 7 | # 8 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" 9 | # BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations under the License. 11 | variable "region" { 12 | default = "us-west-2" 13 | } 14 | -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/metadata.json: -------------------------------------------------------------------------------- 1 | {"generator": "bdist_wheel (0.26.0)", "summary": "Python 2 and 3 compatibility utilities", "classifiers": ["Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Software Development :: Libraries", "Topic :: Utilities"], "extensions": {"python.details": {"project_urls": {"Home": "http://pypi.python.org/pypi/six/"}, "contacts": [{"email": "benjamin@python.org", "name": "Benjamin Peterson", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}}}, "license": "MIT", "metadata_version": "2.0", "name": "six", "version": "1.10.0"} -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/RECORD: -------------------------------------------------------------------------------- 1 | six.py,sha256=A6hdJZVjI3t_geebZ9BzUvwRrIXo0lfwzQlM2LcKyas,30098 2 | six-1.10.0.dist-info/DESCRIPTION.rst,sha256=QWBtSTT2zzabwJv1NQbTfClSX13m-Qc6tqU4TRL1RLs,774 3 | six-1.10.0.dist-info/METADATA,sha256=5HceJsUnHof2IRamlCKO2MwNjve1eSP4rLzVQDfwpCQ,1283 4 | six-1.10.0.dist-info/RECORD,, 5 | six-1.10.0.dist-info/WHEEL,sha256=GrqQvamwgBV4nLoJe0vhYRSWzWsx7xjlt74FT0SWYfE,110 6 | six-1.10.0.dist-info/metadata.json,sha256=jtOeeTBubYDChl_5Ql5ZPlKoHgg6rdqRIjOz1e5Ek2U,658 7 | six-1.10.0.dist-info/top_level.txt,sha256=_iVH_iYEtEXnD8nYGQYpYFUvkUW9sEO1GYbkeKSAais,4 8 | /tmp/tmp8cR5IK/lib/python/six-1.10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 9 | six.pyc,, 10 | -------------------------------------------------------------------------------- /lambda/setuptools/command/launcher manifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /lambda/requests/certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | certs.py 6 | ~~~~~~~~ 7 | 8 | This module returns the preferred default CA certificate bundle. 9 | 10 | If you are packaging Requests, e.g., for a Linux distribution or a managed 11 | environment, you can change the definition of where() to return a separately 12 | packaged CA bundle. 13 | """ 14 | import os.path 15 | 16 | try: 17 | from certifi import where 18 | except ImportError: 19 | def where(): 20 | """Return the preferred certificate bundle.""" 21 | # vendored bundle inside Requests 22 | return os.path.join(os.path.dirname(__file__), 'cacert.pem') 23 | 24 | if __name__ == '__main__': 25 | print(where()) 26 | -------------------------------------------------------------------------------- /lambda/setuptools/command/bdist_wininst.py: -------------------------------------------------------------------------------- 1 | import distutils.command.bdist_wininst as orig 2 | 3 | 4 | class bdist_wininst(orig.bdist_wininst): 5 | def reinitialize_command(self, command, reinit_subcommands=0): 6 | """ 7 | Supplement reinitialize_command to work around 8 | http://bugs.python.org/issue20819 9 | """ 10 | cmd = self.distribution.reinitialize_command( 11 | command, reinit_subcommands) 12 | if command in ('install', 'install_lib'): 13 | cmd.install_lib = None 14 | return cmd 15 | 16 | def run(self): 17 | self._is_running = True 18 | try: 19 | orig.bdist_wininst.run(self) 20 | finally: 21 | self._is_running = False 22 | -------------------------------------------------------------------------------- /lambda/setuptools/command/upload.py: -------------------------------------------------------------------------------- 1 | from distutils.command import upload as orig 2 | 3 | 4 | class upload(orig.upload): 5 | """ 6 | Override default upload behavior to look up password 7 | in the keyring if available. 8 | """ 9 | 10 | def finalize_options(self): 11 | orig.upload.finalize_options(self) 12 | self.password or self._load_password_from_keyring() 13 | 14 | def _load_password_from_keyring(self): 15 | """ 16 | Attempt to load password from keyring. Suppress Exceptions. 17 | """ 18 | try: 19 | keyring = __import__('keyring') 20 | self.password = keyring.get_password(self.repository, 21 | self.username) 22 | except Exception: 23 | pass 24 | -------------------------------------------------------------------------------- /lambda/setuptools/command/saveopts.py: -------------------------------------------------------------------------------- 1 | from setuptools.command.setopt import edit_config, option_base 2 | 3 | 4 | class saveopts(option_base): 5 | """Save command-line options to a file""" 6 | 7 | description = "save supplied options to setup.cfg or other config file" 8 | 9 | def run(self): 10 | dist = self.distribution 11 | settings = {} 12 | 13 | for cmd in dist.command_options: 14 | 15 | if cmd == 'saveopts': 16 | continue # don't save our own options! 17 | 18 | for opt, (src, val) in dist.get_option_dict(cmd).items(): 19 | if src == "command line": 20 | settings.setdefault(cmd, {})[opt] = val 21 | 22 | edit_config(self.filename, settings, self.dry_run) 23 | -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/metadata.json: -------------------------------------------------------------------------------- 1 | {"generator": "bdist_wheel (0.26.0)", "summary": "Python implementation of a Chef API client.", "classifiers": ["Development Status :: 5 - Production/Stable", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python"], "extensions": {"python.details": {"project_urls": {"Home": "http://github.com/coderanger/pychef"}, "contacts": [{"email": "noah@coderanger.net", "name": "Noah Kantrowitz", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}}}, "license": "BSD", "metadata_version": "2.0", "name": "PyChef", "run_requires": [{"requires": ["requests (>=2.7.0)", "six (>=1.9.0)"]}], "extras": [], "version": "0.3.0", "test_requires": [{"requires": ["mock", "unittest2"]}]} -------------------------------------------------------------------------------- /lambda/chef/tests/test_environment.py: -------------------------------------------------------------------------------- 1 | from chef import Environment 2 | from chef.exceptions import ChefAPIVersionError 3 | from chef.tests import ChefTestCase, test_chef_api 4 | 5 | class EnvironmentTestCase(ChefTestCase): 6 | def test_version_error_list(self): 7 | with test_chef_api(version='0.9.0'): 8 | with self.assertRaises(ChefAPIVersionError): 9 | Environment.list() 10 | 11 | def test_version_error_create(self): 12 | with test_chef_api(version='0.9.0'): 13 | with self.assertRaises(ChefAPIVersionError): 14 | Environment.create(self.random()) 15 | 16 | def test_version_error_init(self): 17 | with test_chef_api(version='0.9.0'): 18 | with self.assertRaises(ChefAPIVersionError): 19 | Environment(self.random()) 20 | -------------------------------------------------------------------------------- /lambda/chef/utils/json.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import types 3 | try: 4 | import json 5 | except ImportError: 6 | import simplejson as json 7 | 8 | def maybe_call(x): 9 | if callable(x): 10 | return x() 11 | return x 12 | 13 | class JSONEncoder(json.JSONEncoder): 14 | """Custom encoder to allow arbitrary classes.""" 15 | 16 | def default(self, obj): 17 | if hasattr(obj, 'to_dict'): 18 | return maybe_call(obj.to_dict) 19 | elif hasattr(obj, 'to_list'): 20 | return maybe_call(obj.to_list) 21 | elif isinstance(obj, types.GeneratorType): 22 | return list(obj) 23 | return super(JSONEncoder, self).default(obj) 24 | 25 | loads = json.loads 26 | dumps = lambda obj, **kwargs: json.dumps(obj, cls=JSONEncoder, **kwargs) 27 | -------------------------------------------------------------------------------- /lambda/setuptools/windows_support.py: -------------------------------------------------------------------------------- 1 | import platform 2 | import ctypes 3 | 4 | 5 | def windows_only(func): 6 | if platform.system() != 'Windows': 7 | return lambda *args, **kwargs: None 8 | return func 9 | 10 | 11 | @windows_only 12 | def hide_file(path): 13 | """ 14 | Set the hidden attribute on a file or directory. 15 | 16 | From http://stackoverflow.com/questions/19622133/ 17 | 18 | `path` must be text. 19 | """ 20 | __import__('ctypes.wintypes') 21 | SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW 22 | SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD 23 | SetFileAttributes.restype = ctypes.wintypes.BOOL 24 | 25 | FILE_ATTRIBUTE_HIDDEN = 0x02 26 | 27 | ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN) 28 | if not ret: 29 | raise ctypes.WinError() 30 | -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/DESCRIPTION.rst: -------------------------------------------------------------------------------- 1 | Six is a Python 2 and 3 compatibility library. It provides utility functions 2 | for smoothing over the differences between the Python versions with the goal of 3 | writing Python code that is compatible on both Python versions. See the 4 | documentation for more information on what is provided. 5 | 6 | Six supports every Python version since 2.6. It is contained in only one Python 7 | file, so it can be easily copied into your project. (The copyright and license 8 | notice must be retained.) 9 | 10 | Online documentation is at https://pythonhosted.org/six/. 11 | 12 | Bugs can be reported to https://bitbucket.org/gutworth/six. The code can also 13 | be found there. 14 | 15 | For questions about six or porting in general, email the python-porting mailing 16 | list: https://mail.python.org/mailman/listinfo/python-porting 17 | 18 | 19 | -------------------------------------------------------------------------------- /lambda/setuptools/launch.py: -------------------------------------------------------------------------------- 1 | """ 2 | Launch the Python script on the command line after 3 | setuptools is bootstrapped via import. 4 | """ 5 | 6 | # Note that setuptools gets imported implicitly by the 7 | # invocation of this script using python -m setuptools.launch 8 | 9 | import tokenize 10 | import sys 11 | 12 | 13 | def run(): 14 | """ 15 | Run the script in sys.argv[1] as if it had 16 | been invoked naturally. 17 | """ 18 | __builtins__ 19 | script_name = sys.argv[1] 20 | namespace = dict( 21 | __file__ = script_name, 22 | __name__ = '__main__', 23 | __doc__ = None, 24 | ) 25 | sys.argv[:] = sys.argv[1:] 26 | 27 | open_ = getattr(tokenize, 'open', open) 28 | script = open_(script_name).read() 29 | norm_script = script.replace('\\r\\n', '\\n') 30 | code = compile(norm_script, script_name, 'exec') 31 | exec(code, namespace) 32 | 33 | 34 | if __name__ == '__main__': 35 | run() 36 | -------------------------------------------------------------------------------- /lambda/requests/hooks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.hooks 5 | ~~~~~~~~~~~~~~ 6 | 7 | This module provides the capabilities for the Requests hooks system. 8 | 9 | Available hooks: 10 | 11 | ``response``: 12 | The response generated from a Request. 13 | 14 | """ 15 | HOOKS = ['response'] 16 | 17 | def default_hooks(): 18 | return dict((event, []) for event in HOOKS) 19 | 20 | # TODO: response is the only one 21 | 22 | 23 | def dispatch_hook(key, hooks, hook_data, **kwargs): 24 | """Dispatches a hook dictionary on a given piece of data.""" 25 | hooks = hooks or dict() 26 | hooks = hooks.get(key) 27 | if hooks: 28 | if hasattr(hooks, '__call__'): 29 | hooks = [hooks] 30 | for hook in hooks: 31 | _hook_data = hook(hook_data, **kwargs) 32 | if _hook_data is not None: 33 | hook_data = _hook_data 34 | return hook_data 35 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_fabric.py: -------------------------------------------------------------------------------- 1 | import mock 2 | 3 | from chef.fabric import chef_roledefs 4 | from chef.tests import ChefTestCase, mockSearch 5 | 6 | class FabricTestCase(ChefTestCase): 7 | @mock.patch('chef.search.Search') 8 | def test_roledef(self, MockSearch): 9 | search_data = { 10 | ('role', '*:*'): {}, 11 | } 12 | search_mock_memo = {} 13 | def search_mock(index, q='*:*', *args, **kwargs): 14 | data = search_data[index, q] 15 | search_mock_inst = search_mock_memo.get((index, q)) 16 | if search_mock_inst is None: 17 | search_mock_inst = search_mock_memo[index, q] = mock.Mock() 18 | search_mock_inst.data = data 19 | return search_mock_inst 20 | MockSearch.side_effect = search_mock 21 | print(MockSearch('role').data) 22 | 23 | 24 | @mockSearch({('role', '*:*'): {1:2}}) 25 | def test_roledef2(self, MockSearch): 26 | print(MockSearch('role').data) 27 | -------------------------------------------------------------------------------- /lambda/pkg_resources/_vendor/packaging/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 Donald Stufft 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from __future__ import absolute_import, division, print_function 15 | 16 | from .__about__ import ( 17 | __author__, __copyright__, __email__, __license__, __summary__, __title__, 18 | __uri__, __version__ 19 | ) 20 | 21 | __all__ = [ 22 | "__title__", "__summary__", "__uri__", "__version__", "__author__", 23 | "__email__", "__license__", "__copyright__", 24 | ] 25 | -------------------------------------------------------------------------------- /lambda/chef/exceptions.py: -------------------------------------------------------------------------------- 1 | # Exception hierarchy for chef 2 | # Copyright (c) 2010 Noah Kantrowitz 3 | 4 | 5 | class ChefError(Exception): 6 | """Top-level Chef error.""" 7 | 8 | 9 | class ChefServerError(ChefError): 10 | """An error from a Chef server. May include a HTTP response code.""" 11 | 12 | def __init__(self, message, code=None): 13 | self.raw_message = message 14 | if isinstance(message, list): 15 | message = ', '.join(m for m in message if m) 16 | super(ChefError, self).__init__(message) 17 | self.code = code 18 | 19 | @staticmethod 20 | def from_error(message, code=None): 21 | cls = { 22 | 404: ChefServerNotFoundError, 23 | }.get(code, ChefServerError) 24 | return cls(message, code) 25 | 26 | 27 | class ChefServerNotFoundError(ChefServerError): 28 | """A 404 Not Found server error.""" 29 | 30 | 31 | class ChefAPIVersionError(ChefError): 32 | """An incompatible API version error""" 33 | 34 | 35 | class ChefObjectTypeError(ChefError): 36 | """An invalid object type error""" 37 | 38 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/util/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | # For backwards compatibility, provide imports that used to be here. 3 | from .connection import is_connection_dropped 4 | from .request import make_headers 5 | from .response import is_fp_closed 6 | from .ssl_ import ( 7 | SSLContext, 8 | HAS_SNI, 9 | IS_PYOPENSSL, 10 | assert_fingerprint, 11 | resolve_cert_reqs, 12 | resolve_ssl_version, 13 | ssl_wrap_socket, 14 | ) 15 | from .timeout import ( 16 | current_time, 17 | Timeout, 18 | ) 19 | 20 | from .retry import Retry 21 | from .url import ( 22 | get_host, 23 | parse_url, 24 | split_first, 25 | Url, 26 | ) 27 | 28 | __all__ = ( 29 | 'HAS_SNI', 30 | 'IS_PYOPENSSL', 31 | 'SSLContext', 32 | 'Retry', 33 | 'Timeout', 34 | 'Url', 35 | 'assert_fingerprint', 36 | 'current_time', 37 | 'is_connection_dropped', 38 | 'is_fp_closed', 39 | 'get_host', 40 | 'parse_url', 41 | 'make_headers', 42 | 'resolve_cert_reqs', 43 | 'resolve_ssl_version', 44 | 'split_first', 45 | 'ssl_wrap_socket', 46 | ) 47 | -------------------------------------------------------------------------------- /lambda/setuptools/unicode_utils.py: -------------------------------------------------------------------------------- 1 | import unicodedata 2 | import sys 3 | 4 | from setuptools.extern import six 5 | 6 | # HFS Plus uses decomposed UTF-8 7 | def decompose(path): 8 | if isinstance(path, six.text_type): 9 | return unicodedata.normalize('NFD', path) 10 | try: 11 | path = path.decode('utf-8') 12 | path = unicodedata.normalize('NFD', path) 13 | path = path.encode('utf-8') 14 | except UnicodeError: 15 | pass # Not UTF-8 16 | return path 17 | 18 | 19 | def filesys_decode(path): 20 | """ 21 | Ensure that the given path is decoded, 22 | NONE when no expected encoding works 23 | """ 24 | 25 | if isinstance(path, six.text_type): 26 | return path 27 | 28 | fs_enc = sys.getfilesystemencoding() or 'utf-8' 29 | candidates = fs_enc, 'utf-8' 30 | 31 | for enc in candidates: 32 | try: 33 | return path.decode(enc) 34 | except UnicodeDecodeError: 35 | continue 36 | 37 | 38 | def try_encode(string, enc): 39 | "turn unicode encoding into a functional routine" 40 | try: 41 | return string.encode(enc) 42 | except UnicodeEncodeError: 43 | return None 44 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_api.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import unittest2 4 | 5 | from chef.api import ChefAPI 6 | 7 | class APITestCase(unittest2.TestCase): 8 | def load(self, path): 9 | path = os.path.join(os.path.dirname(__file__), 'configs', path) 10 | return ChefAPI.from_config_file(path) 11 | 12 | def test_basic(self): 13 | api = self.load('basic.rb') 14 | self.assertEqual(api.url, 'http://chef:4000') 15 | self.assertEqual(api.client, 'test_1') 16 | 17 | def test_current_dir(self): 18 | api = self.load('current_dir.rb') 19 | path = os.path.join(os.path.dirname(__file__), 'configs', 'test_1') 20 | self.assertEqual(os.path.normpath(api.client), path) 21 | 22 | def test_env_variables(self): 23 | try: 24 | os.environ['_PYCHEF_TEST_'] = 'foobar' 25 | api = self.load('env_values.rb') 26 | self.assertEqual(api.client, 'foobar') 27 | finally: 28 | del os.environ['_PYCHEF_TEST_'] 29 | 30 | def test_bad_key_raises(self): 31 | invalids = [None, ''] 32 | for item in invalids: 33 | self.assertRaises( 34 | ValueError, ChefAPI, 'foobar', item, 'user') 35 | -------------------------------------------------------------------------------- /lambda/pkg_resources/_vendor/packaging/__about__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 Donald Stufft 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from __future__ import absolute_import, division, print_function 15 | 16 | __all__ = [ 17 | "__title__", "__summary__", "__uri__", "__version__", "__author__", 18 | "__email__", "__license__", "__copyright__", 19 | ] 20 | 21 | __title__ = "packaging" 22 | __summary__ = "Core utilities for Python packages" 23 | __uri__ = "https://github.com/pypa/packaging" 24 | 25 | __version__ = "15.3" 26 | 27 | __author__ = "Donald Stufft" 28 | __email__ = "donald@stufft.io" 29 | 30 | __license__ = "Apache License, Version 2.0" 31 | __copyright__ = "Copyright 2014 %s" % __author__ 32 | -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/METADATA: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.0 2 | Name: PyChef 3 | Version: 0.3.0 4 | Summary: Python implementation of a Chef API client. 5 | Home-page: http://github.com/coderanger/pychef 6 | Author: Noah Kantrowitz 7 | Author-email: noah@coderanger.net 8 | License: BSD 9 | Platform: UNKNOWN 10 | Classifier: Development Status :: 5 - Production/Stable 11 | Classifier: License :: OSI Approved :: BSD License 12 | Classifier: Natural Language :: English 13 | Classifier: Operating System :: OS Independent 14 | Classifier: Programming Language :: Python 15 | Requires-Dist: requests (>=2.7.0) 16 | Requires-Dist: six (>=1.9.0) 17 | 18 | PyChef 19 | ====== 20 | 21 | .. image:: https://secure.travis-ci.org/coderanger/pychef.png?branch=master 22 | :target: http://travis-ci.org/coderanger/pychef 23 | 24 | A Python API for interacting with a Chef server. 25 | 26 | Example 27 | ------- 28 | 29 | :: 30 | 31 | from chef import autoconfigure, Node 32 | 33 | api = autoconfigure() 34 | n = Node('web1') 35 | print n['fqdn'] 36 | n['myapp']['version'] = '1.0' 37 | n.save() 38 | 39 | Further Reading 40 | --------------- 41 | 42 | For more information check out http://pychef.readthedocs.org/en/latest/index.html 43 | 44 | 45 | -------------------------------------------------------------------------------- /lambda/requests-2.10.0.dist-info/metadata.json: -------------------------------------------------------------------------------- 1 | {"classifiers": ["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy"], "extensions": {"python.details": {"contacts": [{"email": "me@kennethreitz.com", "name": "Kenneth Reitz", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "http://python-requests.org"}}}, "extras": ["security", "socks"], "generator": "bdist_wheel (0.29.0)", "license": "Apache 2.0", "metadata_version": "2.0", "name": "requests", "run_requires": [{"extra": "socks", "requires": ["PySocks (>=1.5.6)"]}, {"extra": "security", "requires": ["ndg-httpsclient", "pyOpenSSL (>=0.13)", "pyasn1"]}], "summary": "Python HTTP for Humans.", "test_requires": [{"requires": ["pytest (>=2.8.0)", "pytest-cov", "pytest-httpbin (==0.0.7)"]}], "version": "2.10.0"} -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/compat.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # Contributor(s): 3 | # Ian Cordasco - port to Python 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 2.1 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | # Lesser General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU Lesser General Public 16 | # License along with this library; if not, write to the Free Software 17 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 18 | # 02110-1301 USA 19 | ######################### END LICENSE BLOCK ######################### 20 | 21 | import sys 22 | 23 | 24 | if sys.version_info < (3, 0): 25 | base_str = (str, unicode) 26 | else: 27 | base_str = (bytes, str) 28 | 29 | 30 | def wrap_ord(a): 31 | if sys.version_info < (3, 0) and isinstance(a, base_str): 32 | return ord(a) 33 | else: 34 | return a 35 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_client.py: -------------------------------------------------------------------------------- 1 | import unittest2 2 | 3 | from chef import Client 4 | from chef.tests import ChefTestCase 5 | 6 | class ClientTestCase(ChefTestCase): 7 | def test_list(self): 8 | self.assertIn('test_1', Client.list()) 9 | 10 | def test_get(self): 11 | client = Client('test_1') 12 | self.assertTrue(client.platform) 13 | self.assertEqual(client.orgname, 'pycheftest') 14 | self.assertTrue(client.public_key) 15 | self.assertTrue(client.certificate) 16 | self.assertEqual(client.private_key, None) 17 | 18 | def test_create(self): 19 | name = self.random() 20 | client = Client.create(name) 21 | self.register(client) 22 | self.assertEqual(client.name, name) 23 | #self.assertEqual(client.orgname, 'pycheftest') # See CHEF-2019 24 | self.assertTrue(client.private_key) 25 | self.assertTrue(client.public_key) 26 | self.assertIn(name, Client.list()) 27 | 28 | client2 = Client(name) 29 | client2.rekey() 30 | self.assertEqual(client.public_key, client2.public_key) 31 | self.assertNotEqual(client.private_key, client2.private_key) 32 | 33 | def test_delete(self): 34 | name = self.random() 35 | client = Client.create(name) 36 | client.delete() 37 | self.assertNotIn(name, Client.list()) 38 | -------------------------------------------------------------------------------- /lambda/six-1.10.0.dist-info/METADATA: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.0 2 | Name: six 3 | Version: 1.10.0 4 | Summary: Python 2 and 3 compatibility utilities 5 | Home-page: http://pypi.python.org/pypi/six/ 6 | Author: Benjamin Peterson 7 | Author-email: benjamin@python.org 8 | License: MIT 9 | Platform: UNKNOWN 10 | Classifier: Programming Language :: Python :: 2 11 | Classifier: Programming Language :: Python :: 3 12 | Classifier: Intended Audience :: Developers 13 | Classifier: License :: OSI Approved :: MIT License 14 | Classifier: Topic :: Software Development :: Libraries 15 | Classifier: Topic :: Utilities 16 | 17 | Six is a Python 2 and 3 compatibility library. It provides utility functions 18 | for smoothing over the differences between the Python versions with the goal of 19 | writing Python code that is compatible on both Python versions. See the 20 | documentation for more information on what is provided. 21 | 22 | Six supports every Python version since 2.6. It is contained in only one Python 23 | file, so it can be easily copied into your project. (The copyright and license 24 | notice must be retained.) 25 | 26 | Online documentation is at https://pythonhosted.org/six/. 27 | 28 | Bugs can be reported to https://bitbucket.org/gutworth/six. The code can also 29 | be found there. 30 | 31 | For questions about six or porting in general, email the python-porting mailing 32 | list: https://mail.python.org/mailman/listinfo/python-porting 33 | 34 | 35 | -------------------------------------------------------------------------------- /lambda/pkg_resources/_vendor/packaging/_compat.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 Donald Stufft 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from __future__ import absolute_import, division, print_function 15 | 16 | import sys 17 | 18 | 19 | PY2 = sys.version_info[0] == 2 20 | PY3 = sys.version_info[0] == 3 21 | 22 | # flake8: noqa 23 | 24 | if PY3: 25 | string_types = str, 26 | else: 27 | string_types = basestring, 28 | 29 | 30 | def with_metaclass(meta, *bases): 31 | """ 32 | Create a base class with a metaclass. 33 | """ 34 | # This requires a bit of explanation: the basic idea is to make a dummy 35 | # metaclass for one level of class instantiation that replaces itself with 36 | # the actual metaclass. 37 | class metaclass(meta): 38 | def __new__(cls, name, this_bases, d): 39 | return meta(name, bases, d) 40 | return type.__new__(metaclass, 'temporary_class', (), {}) 41 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/__init__.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # This library is free software; you can redistribute it and/or 3 | # modify it under the terms of the GNU Lesser General Public 4 | # License as published by the Free Software Foundation; either 5 | # version 2.1 of the License, or (at your option) any later version. 6 | # 7 | # This library is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | # Lesser General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU Lesser General Public 13 | # License along with this library; if not, write to the Free Software 14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 15 | # 02110-1301 USA 16 | ######################### END LICENSE BLOCK ######################### 17 | 18 | __version__ = "2.3.0" 19 | from sys import version_info 20 | 21 | 22 | def detect(aBuf): 23 | if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or 24 | (version_info >= (3, 0) and not isinstance(aBuf, bytes))): 25 | raise ValueError('Expected a bytes object, not a unicode object') 26 | 27 | from . import universaldetector 28 | u = universaldetector.UniversalDetector() 29 | u.reset() 30 | u.feed(aBuf) 31 | u.close() 32 | return u.result 33 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/constants.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | _debug = 0 30 | 31 | eDetecting = 0 32 | eFoundIt = 1 33 | eNotMe = 2 34 | 35 | eStart = 0 36 | eError = 1 37 | eItsMe = 2 38 | 39 | SHORTCUT_THRESHOLD = 0.95 40 | -------------------------------------------------------------------------------- /lambda/requests/packages/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Debian and other distributions "unbundle" requests' vendored dependencies, and 3 | rewrite all imports to use the global versions of ``urllib3`` and ``chardet``. 4 | The problem with this is that not only requests itself imports those 5 | dependencies, but third-party code outside of the distros' control too. 6 | 7 | In reaction to these problems, the distro maintainers replaced 8 | ``requests.packages`` with a magical "stub module" that imports the correct 9 | modules. The implementations were varying in quality and all had severe 10 | problems. For example, a symlink (or hardlink) that links the correct modules 11 | into place introduces problems regarding object identity, since you now have 12 | two modules in `sys.modules` with the same API, but different identities:: 13 | 14 | requests.packages.urllib3 is not urllib3 15 | 16 | With version ``2.5.2``, requests started to maintain its own stub, so that 17 | distro-specific breakage would be reduced to a minimum, even though the whole 18 | issue is not requests' fault in the first place. See 19 | https://github.com/kennethreitz/requests/pull/2375 for the corresponding pull 20 | request. 21 | ''' 22 | 23 | from __future__ import absolute_import 24 | import sys 25 | 26 | try: 27 | from . import urllib3 28 | except ImportError: 29 | import urllib3 30 | sys.modules['%s.urllib3' % __name__] = urllib3 31 | 32 | try: 33 | from . import chardet 34 | except ImportError: 35 | import chardet 36 | sys.modules['%s.chardet' % __name__] = chardet 37 | -------------------------------------------------------------------------------- /lambda/setuptools/command/bdist_rpm.py: -------------------------------------------------------------------------------- 1 | import distutils.command.bdist_rpm as orig 2 | 3 | 4 | class bdist_rpm(orig.bdist_rpm): 5 | """ 6 | Override the default bdist_rpm behavior to do the following: 7 | 8 | 1. Run egg_info to ensure the name and version are properly calculated. 9 | 2. Always run 'install' using --single-version-externally-managed to 10 | disable eggs in RPM distributions. 11 | 3. Replace dash with underscore in the version numbers for better RPM 12 | compatibility. 13 | """ 14 | 15 | def run(self): 16 | # ensure distro name is up-to-date 17 | self.run_command('egg_info') 18 | 19 | orig.bdist_rpm.run(self) 20 | 21 | def _make_spec_file(self): 22 | version = self.distribution.get_version() 23 | rpmversion = version.replace('-', '_') 24 | spec = orig.bdist_rpm._make_spec_file(self) 25 | line23 = '%define version ' + version 26 | line24 = '%define version ' + rpmversion 27 | spec = [ 28 | line.replace( 29 | "Source0: %{name}-%{version}.tar", 30 | "Source0: %{name}-%{unmangled_version}.tar" 31 | ).replace( 32 | "setup.py install ", 33 | "setup.py install --single-version-externally-managed " 34 | ).replace( 35 | "%setup", 36 | "%setup -n %{name}-%{unmangled_version}" 37 | ).replace(line23, line24) 38 | for line in spec 39 | ] 40 | insert_loc = spec.index(line24) + 1 41 | unmangled_version = "%define unmangled_version " + version 42 | spec.insert(insert_loc, unmangled_version) 43 | return spec 44 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_role.py: -------------------------------------------------------------------------------- 1 | from chef import Role 2 | from chef.exceptions import ChefError 3 | from chef.tests import ChefTestCase 4 | 5 | class RoleTestCase(ChefTestCase): 6 | def test_get(self): 7 | r = Role('test_1') 8 | self.assertTrue(r.exists) 9 | self.assertEqual(r.description, 'Static test role 1') 10 | self.assertEqual(r.run_list, []) 11 | self.assertEqual(r.default_attributes['test_attr'], 'default') 12 | self.assertEqual(r.default_attributes['nested']['nested_attr'], 1) 13 | self.assertEqual(r.override_attributes['test_attr'], 'override') 14 | 15 | def test_create(self): 16 | name = self.random() 17 | r = Role.create(name, description='A test role', run_list=['recipe[foo]'], 18 | default_attributes={'attr': 'foo'}, override_attributes={'attr': 'bar'}) 19 | self.register(r) 20 | self.assertEqual(r.description, 'A test role') 21 | self.assertEqual(r.run_list, ['recipe[foo]']) 22 | self.assertEqual(r.default_attributes['attr'], 'foo') 23 | self.assertEqual(r.override_attributes['attr'], 'bar') 24 | 25 | r2 = Role(name) 26 | self.assertTrue(r2.exists) 27 | self.assertEqual(r2.description, 'A test role') 28 | self.assertEqual(r2.run_list, ['recipe[foo]']) 29 | self.assertEqual(r2.default_attributes['attr'], 'foo') 30 | self.assertEqual(r2.override_attributes['attr'], 'bar') 31 | 32 | def test_delete(self): 33 | name = self.random() 34 | r = Role.create(name) 35 | r.delete() 36 | for n in Role.list(): 37 | self.assertNotEqual(n, name) 38 | self.assertFalse(Role(name).exists) 39 | -------------------------------------------------------------------------------- /lambda/requests/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | pythoncompat 5 | """ 6 | 7 | from .packages import chardet 8 | 9 | import sys 10 | 11 | # ------- 12 | # Pythons 13 | # ------- 14 | 15 | # Syntax sugar. 16 | _ver = sys.version_info 17 | 18 | #: Python 2.x? 19 | is_py2 = (_ver[0] == 2) 20 | 21 | #: Python 3.x? 22 | is_py3 = (_ver[0] == 3) 23 | 24 | try: 25 | import simplejson as json 26 | except (ImportError, SyntaxError): 27 | # simplejson does not support Python 3.2, it throws a SyntaxError 28 | # because of u'...' Unicode literals. 29 | import json 30 | 31 | # --------- 32 | # Specifics 33 | # --------- 34 | 35 | if is_py2: 36 | from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass 37 | from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag 38 | from urllib2 import parse_http_list 39 | import cookielib 40 | from Cookie import Morsel 41 | from StringIO import StringIO 42 | from .packages.urllib3.packages.ordered_dict import OrderedDict 43 | 44 | builtin_str = str 45 | bytes = str 46 | str = unicode 47 | basestring = basestring 48 | numeric_types = (int, long, float) 49 | 50 | elif is_py3: 51 | from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag 52 | from urllib.request import parse_http_list, getproxies, proxy_bypass 53 | from http import cookiejar as cookielib 54 | from http.cookies import Morsel 55 | from io import StringIO 56 | from collections import OrderedDict 57 | 58 | builtin_str = str 59 | str = str 60 | bytes = bytes 61 | basestring = (str, bytes) 62 | numeric_types = (int, float) 63 | -------------------------------------------------------------------------------- /lambda/setuptools/py31compat.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import unittest 3 | 4 | __all__ = ['get_config_vars', 'get_path'] 5 | 6 | try: 7 | # Python 2.7 or >=3.2 8 | from sysconfig import get_config_vars, get_path 9 | except ImportError: 10 | from distutils.sysconfig import get_config_vars, get_python_lib 11 | def get_path(name): 12 | if name not in ('platlib', 'purelib'): 13 | raise ValueError("Name must be purelib or platlib") 14 | return get_python_lib(name=='platlib') 15 | 16 | try: 17 | # Python >=3.2 18 | from tempfile import TemporaryDirectory 19 | except ImportError: 20 | import shutil 21 | import tempfile 22 | class TemporaryDirectory(object): 23 | """ 24 | Very simple temporary directory context manager. 25 | Will try to delete afterward, but will also ignore OS and similar 26 | errors on deletion. 27 | """ 28 | def __init__(self): 29 | self.name = None # Handle mkdtemp raising an exception 30 | self.name = tempfile.mkdtemp() 31 | 32 | def __enter__(self): 33 | return self.name 34 | 35 | def __exit__(self, exctype, excvalue, exctrace): 36 | try: 37 | shutil.rmtree(self.name, True) 38 | except OSError: #removal errors are not the only possible 39 | pass 40 | self.name = None 41 | 42 | 43 | unittest_main = unittest.main 44 | 45 | _PY31 = (3, 1) <= sys.version_info[:2] < (3, 2) 46 | if _PY31: 47 | # on Python 3.1, translate testRunner==None to TextTestRunner 48 | # for compatibility with Python 2.6, 2.7, and 3.2+ 49 | def unittest_main(*args, **kwargs): 50 | if 'testRunner' in kwargs and kwargs['testRunner'] is None: 51 | kwargs['testRunner'] = unittest.TextTestRunner 52 | return unittest.main(*args, **kwargs) 53 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/euckrprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import EUCKRSMModel 32 | 33 | 34 | class EUCKRProber(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(EUCKRSMModel) 38 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis() 39 | self.reset() 40 | 41 | def get_charset_name(self): 42 | return "EUC-KR" 43 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/euctwprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCTWDistributionAnalysis 31 | from .mbcssm import EUCTWSMModel 32 | 33 | class EUCTWProber(MultiByteCharSetProber): 34 | def __init__(self): 35 | MultiByteCharSetProber.__init__(self) 36 | self._mCodingSM = CodingStateMachine(EUCTWSMModel) 37 | self._mDistributionAnalyzer = EUCTWDistributionAnalysis() 38 | self.reset() 39 | 40 | def get_charset_name(self): 41 | return "EUC-TW" 42 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/gb2312prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import GB2312DistributionAnalysis 31 | from .mbcssm import GB2312SMModel 32 | 33 | class GB2312Prober(MultiByteCharSetProber): 34 | def __init__(self): 35 | MultiByteCharSetProber.__init__(self) 36 | self._mCodingSM = CodingStateMachine(GB2312SMModel) 37 | self._mDistributionAnalyzer = GB2312DistributionAnalysis() 38 | self.reset() 39 | 40 | def get_charset_name(self): 41 | return "GB2312" 42 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/big5prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import Big5DistributionAnalysis 31 | from .mbcssm import Big5SMModel 32 | 33 | 34 | class Big5Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(Big5SMModel) 38 | self._mDistributionAnalyzer = Big5DistributionAnalysis() 39 | self.reset() 40 | 41 | def get_charset_name(self): 42 | return "Big5" 43 | -------------------------------------------------------------------------------- /lambda/setuptools/extension.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import re 3 | import functools 4 | import distutils.core 5 | import distutils.errors 6 | import distutils.extension 7 | 8 | from setuptools.extern.six.moves import map 9 | 10 | from .dist import _get_unpatched 11 | from . import msvc9_support 12 | 13 | _Extension = _get_unpatched(distutils.core.Extension) 14 | 15 | msvc9_support.patch_for_specialized_compiler() 16 | 17 | def _have_cython(): 18 | """ 19 | Return True if Cython can be imported. 20 | """ 21 | cython_impl = 'Cython.Distutils.build_ext', 22 | try: 23 | # from (cython_impl) import build_ext 24 | __import__(cython_impl, fromlist=['build_ext']).build_ext 25 | return True 26 | except Exception: 27 | pass 28 | return False 29 | 30 | # for compatibility 31 | have_pyrex = _have_cython 32 | 33 | 34 | class Extension(_Extension): 35 | """Extension that uses '.c' files in place of '.pyx' files""" 36 | 37 | def _convert_pyx_sources_to_lang(self): 38 | """ 39 | Replace sources with .pyx extensions to sources with the target 40 | language extension. This mechanism allows language authors to supply 41 | pre-converted sources but to prefer the .pyx sources. 42 | """ 43 | if _have_cython(): 44 | # the build has Cython, so allow it to compile the .pyx files 45 | return 46 | lang = self.language or '' 47 | target_ext = '.cpp' if lang.lower() == 'c++' else '.c' 48 | sub = functools.partial(re.sub, '.pyx$', target_ext) 49 | self.sources = list(map(sub, self.sources)) 50 | 51 | class Library(Extension): 52 | """Just like a regular Extension, but built as a library instead""" 53 | 54 | distutils.core.Extension = Extension 55 | distutils.extension.Extension = Extension 56 | if 'distutils.command.build_ext' in sys.modules: 57 | sys.modules['distutils.command.build_ext'].Extension = Extension 58 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/cp949prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import CP949SMModel 32 | 33 | 34 | class CP949Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(CP949SMModel) 38 | # NOTE: CP949 is a superset of EUC-KR, so the distribution should be 39 | # not different. 40 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis() 41 | self.reset() 42 | 43 | def get_charset_name(self): 44 | return "CP949" 45 | -------------------------------------------------------------------------------- /lambda/chef/client.py: -------------------------------------------------------------------------------- 1 | from chef.api import ChefAPI 2 | from chef.base import ChefObject 3 | 4 | class Client(ChefObject): 5 | """A Chef client object.""" 6 | 7 | url = '/clients' 8 | 9 | def _populate(self, data): 10 | self.platform = self.api and self.api.platform 11 | self.private_key = None 12 | if self.platform: 13 | self.orgname = data.get('orgname') 14 | self.validator = bool(data.get('validator', False)) 15 | self.public_key = data.get('public_key') 16 | self.admin = False 17 | else: 18 | self.admin = bool(data.get('admin', False)) 19 | self.public_key = data.get('public_key') 20 | self.orgname = None 21 | self.validator = False 22 | 23 | @property 24 | def certificate(self): 25 | return self.public_key 26 | 27 | def to_dict(self): 28 | d = super(Client, self).to_dict() 29 | d['json_class'] = 'Chef::ApiClient' 30 | if self.platform: 31 | d.update({ 32 | 'orgname': self.orgname, 33 | 'validator': self.validator, 34 | 'public_key': self.certificate, 35 | 'clientname': self.name, 36 | }) 37 | else: 38 | d.update({ 39 | 'admin': self.admin, 40 | 'public_key': self.public_key, 41 | }) 42 | return d 43 | 44 | @classmethod 45 | def create(cls, name, api=None, admin=False): 46 | api = api or ChefAPI.get_global() 47 | obj = cls(name, api, skip_load=True) 48 | obj.admin = admin 49 | d = api.api_request('POST', cls.url, data=obj) 50 | obj.private_key = d['private_key'] 51 | obj.public_key = d['public_key'] 52 | return obj 53 | 54 | def rekey(self, api=None): 55 | api = api or self.api 56 | d_in = {'name': self.name, 'private_key': True} 57 | d_out = api.api_request('PUT', self.url, data=d_in) 58 | self.private_key = d_out['private_key'] 59 | -------------------------------------------------------------------------------- /lambda/chef/tests/__init__.py: -------------------------------------------------------------------------------- 1 | import six.moves 2 | import os 3 | import random 4 | from functools import wraps 5 | 6 | import mock 7 | from unittest2 import TestCase, skipUnless 8 | 9 | from chef.api import ChefAPI 10 | from chef.exceptions import ChefError 11 | from chef.search import Search 12 | 13 | TEST_ROOT = os.path.dirname(os.path.abspath(__file__)) 14 | 15 | def skipSlowTest(): 16 | return skipUnless(os.environ.get('PYCHEF_SLOW_TESTS'), 'slow tests skipped, set $PYCHEF_SLOW_TESTS=1 to enable') 17 | 18 | class mockSearch(object): 19 | def __init__(self, search_data): 20 | self.search_data = search_data 21 | 22 | def __call__(self, fn): 23 | @wraps(fn) 24 | def wrapper(inner_self): 25 | return mock.patch('chef.search.Search', side_effect=self._search_inst)(fn)(inner_self) 26 | return wrapper 27 | 28 | def _search_inst(self, index, q='*:*', *args, **kwargs): 29 | data = self.search_data[index, q] 30 | if not isinstance(data, dict): 31 | data = {'total': len(data), 'rows': data} 32 | search = Search(index, q, *args, **kwargs) 33 | search._data = data 34 | return search 35 | 36 | 37 | def test_chef_api(**kwargs): 38 | return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests', **kwargs) 39 | 40 | 41 | class ChefTestCase(TestCase): 42 | """Base class for Chef unittests.""" 43 | 44 | def setUp(self): 45 | super(ChefTestCase, self).setUp() 46 | self.api = test_chef_api() 47 | self.api.set_default() 48 | self.objects = [] 49 | 50 | def tearDown(self): 51 | for obj in self.objects: 52 | try: 53 | obj.delete() 54 | except ChefError as e: 55 | print(e) 56 | # Continue running 57 | 58 | def register(self, obj): 59 | self.objects.append(obj) 60 | 61 | def random(self, length=8, alphabet='0123456789abcdef'): 62 | return ''.join(random.choice(alphabet) for _ in six.moves.range(length)) 63 | -------------------------------------------------------------------------------- /lambda/pkg_resources/_vendor/packaging/_structures.py: -------------------------------------------------------------------------------- 1 | # Copyright 2014 Donald Stufft 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from __future__ import absolute_import, division, print_function 15 | 16 | 17 | class Infinity(object): 18 | 19 | def __repr__(self): 20 | return "Infinity" 21 | 22 | def __hash__(self): 23 | return hash(repr(self)) 24 | 25 | def __lt__(self, other): 26 | return False 27 | 28 | def __le__(self, other): 29 | return False 30 | 31 | def __eq__(self, other): 32 | return isinstance(other, self.__class__) 33 | 34 | def __ne__(self, other): 35 | return not isinstance(other, self.__class__) 36 | 37 | def __gt__(self, other): 38 | return True 39 | 40 | def __ge__(self, other): 41 | return True 42 | 43 | def __neg__(self): 44 | return NegativeInfinity 45 | 46 | Infinity = Infinity() 47 | 48 | 49 | class NegativeInfinity(object): 50 | 51 | def __repr__(self): 52 | return "-Infinity" 53 | 54 | def __hash__(self): 55 | return hash(repr(self)) 56 | 57 | def __lt__(self, other): 58 | return True 59 | 60 | def __le__(self, other): 61 | return True 62 | 63 | def __eq__(self, other): 64 | return isinstance(other, self.__class__) 65 | 66 | def __ne__(self, other): 67 | return not isinstance(other, self.__class__) 68 | 69 | def __gt__(self, other): 70 | return False 71 | 72 | def __ge__(self, other): 73 | return False 74 | 75 | def __neg__(self): 76 | return Infinity 77 | 78 | NegativeInfinity = NegativeInfinity() 79 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/charsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from . import constants 30 | import re 31 | 32 | 33 | class CharSetProber: 34 | def __init__(self): 35 | pass 36 | 37 | def reset(self): 38 | self._mState = constants.eDetecting 39 | 40 | def get_charset_name(self): 41 | return None 42 | 43 | def feed(self, aBuf): 44 | pass 45 | 46 | def get_state(self): 47 | return self._mState 48 | 49 | def get_confidence(self): 50 | return 0.0 51 | 52 | def filter_high_bit_only(self, aBuf): 53 | aBuf = re.sub(b'([\x00-\x7F])+', b' ', aBuf) 54 | return aBuf 55 | 56 | def filter_without_english_letters(self, aBuf): 57 | aBuf = re.sub(b'([A-Za-z])+', b' ', aBuf) 58 | return aBuf 59 | 60 | def filter_with_english_letters(self, aBuf): 61 | # TODO 62 | return aBuf 63 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/mbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | from .charsetgroupprober import CharSetGroupProber 31 | from .utf8prober import UTF8Prober 32 | from .sjisprober import SJISProber 33 | from .eucjpprober import EUCJPProber 34 | from .gb2312prober import GB2312Prober 35 | from .euckrprober import EUCKRProber 36 | from .cp949prober import CP949Prober 37 | from .big5prober import Big5Prober 38 | from .euctwprober import EUCTWProber 39 | 40 | 41 | class MBCSGroupProber(CharSetGroupProber): 42 | def __init__(self): 43 | CharSetGroupProber.__init__(self) 44 | self._mProbers = [ 45 | UTF8Prober(), 46 | SJISProber(), 47 | EUCJPProber(), 48 | GB2312Prober(), 49 | EUCKRProber(), 50 | CP949Prober(), 51 | Big5Prober(), 52 | EUCTWProber() 53 | ] 54 | self.reset() 55 | -------------------------------------------------------------------------------- /lambda/setuptools/lib2to3_ex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Customized Mixin2to3 support: 3 | 4 | - adds support for converting doctests 5 | 6 | 7 | This module raises an ImportError on Python 2. 8 | """ 9 | 10 | from distutils.util import Mixin2to3 as _Mixin2to3 11 | from distutils import log 12 | from lib2to3.refactor import RefactoringTool, get_fixers_from_package 13 | import setuptools 14 | 15 | class DistutilsRefactoringTool(RefactoringTool): 16 | def log_error(self, msg, *args, **kw): 17 | log.error(msg, *args) 18 | 19 | def log_message(self, msg, *args): 20 | log.info(msg, *args) 21 | 22 | def log_debug(self, msg, *args): 23 | log.debug(msg, *args) 24 | 25 | class Mixin2to3(_Mixin2to3): 26 | def run_2to3(self, files, doctests = False): 27 | # See of the distribution option has been set, otherwise check the 28 | # setuptools default. 29 | if self.distribution.use_2to3 is not True: 30 | return 31 | if not files: 32 | return 33 | log.info("Fixing "+" ".join(files)) 34 | self.__build_fixer_names() 35 | self.__exclude_fixers() 36 | if doctests: 37 | if setuptools.run_2to3_on_doctests: 38 | r = DistutilsRefactoringTool(self.fixer_names) 39 | r.refactor(files, write=True, doctests_only=True) 40 | else: 41 | _Mixin2to3.run_2to3(self, files) 42 | 43 | def __build_fixer_names(self): 44 | if self.fixer_names: return 45 | self.fixer_names = [] 46 | for p in setuptools.lib2to3_fixer_packages: 47 | self.fixer_names.extend(get_fixers_from_package(p)) 48 | if self.distribution.use_2to3_fixers is not None: 49 | for p in self.distribution.use_2to3_fixers: 50 | self.fixer_names.extend(get_fixers_from_package(p)) 51 | 52 | def __exclude_fixers(self): 53 | excluded_fixers = getattr(self, 'exclude_fixers', []) 54 | if self.distribution.use_2to3_exclude_fixers is not None: 55 | excluded_fixers.extend(self.distribution.use_2to3_exclude_fixers) 56 | for fixer_name in excluded_fixers: 57 | if fixer_name in self.fixer_names: 58 | self.fixer_names.remove(fixer_name) 59 | -------------------------------------------------------------------------------- /lambda/setuptools/command/rotate.py: -------------------------------------------------------------------------------- 1 | from distutils.util import convert_path 2 | from distutils import log 3 | from distutils.errors import DistutilsOptionError 4 | import os 5 | 6 | from setuptools.extern import six 7 | 8 | from setuptools import Command 9 | 10 | 11 | class rotate(Command): 12 | """Delete older distributions""" 13 | 14 | description = "delete older distributions, keeping N newest files" 15 | user_options = [ 16 | ('match=', 'm', "patterns to match (required)"), 17 | ('dist-dir=', 'd', "directory where the distributions are"), 18 | ('keep=', 'k', "number of matching distributions to keep"), 19 | ] 20 | 21 | boolean_options = [] 22 | 23 | def initialize_options(self): 24 | self.match = None 25 | self.dist_dir = None 26 | self.keep = None 27 | 28 | def finalize_options(self): 29 | if self.match is None: 30 | raise DistutilsOptionError( 31 | "Must specify one or more (comma-separated) match patterns " 32 | "(e.g. '.zip' or '.egg')" 33 | ) 34 | if self.keep is None: 35 | raise DistutilsOptionError("Must specify number of files to keep") 36 | try: 37 | self.keep = int(self.keep) 38 | except ValueError: 39 | raise DistutilsOptionError("--keep must be an integer") 40 | if isinstance(self.match, six.string_types): 41 | self.match = [ 42 | convert_path(p.strip()) for p in self.match.split(',') 43 | ] 44 | self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) 45 | 46 | def run(self): 47 | self.run_command("egg_info") 48 | from glob import glob 49 | 50 | for pattern in self.match: 51 | pattern = self.distribution.get_name() + '*' + pattern 52 | files = glob(os.path.join(self.dist_dir, pattern)) 53 | files = [(os.path.getmtime(f), f) for f in files] 54 | files.sort() 55 | files.reverse() 56 | 57 | log.info("%d file(s) matching %s", len(files), pattern) 58 | files = files[self.keep:] 59 | for (t, f) in files: 60 | log.info("Deleting %s", f) 61 | if not self.dry_run: 62 | os.unlink(f) 63 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/util/request.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from base64 import b64encode 3 | 4 | from ..packages.six import b 5 | 6 | ACCEPT_ENCODING = 'gzip,deflate' 7 | 8 | 9 | def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, 10 | basic_auth=None, proxy_basic_auth=None, disable_cache=None): 11 | """ 12 | Shortcuts for generating request headers. 13 | 14 | :param keep_alive: 15 | If ``True``, adds 'connection: keep-alive' header. 16 | 17 | :param accept_encoding: 18 | Can be a boolean, list, or string. 19 | ``True`` translates to 'gzip,deflate'. 20 | List will get joined by comma. 21 | String will be used as provided. 22 | 23 | :param user_agent: 24 | String representing the user-agent you want, such as 25 | "python-urllib3/0.6" 26 | 27 | :param basic_auth: 28 | Colon-separated username:password string for 'authorization: basic ...' 29 | auth header. 30 | 31 | :param proxy_basic_auth: 32 | Colon-separated username:password string for 'proxy-authorization: basic ...' 33 | auth header. 34 | 35 | :param disable_cache: 36 | If ``True``, adds 'cache-control: no-cache' header. 37 | 38 | Example:: 39 | 40 | >>> make_headers(keep_alive=True, user_agent="Batman/1.0") 41 | {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} 42 | >>> make_headers(accept_encoding=True) 43 | {'accept-encoding': 'gzip,deflate'} 44 | """ 45 | headers = {} 46 | if accept_encoding: 47 | if isinstance(accept_encoding, str): 48 | pass 49 | elif isinstance(accept_encoding, list): 50 | accept_encoding = ','.join(accept_encoding) 51 | else: 52 | accept_encoding = ACCEPT_ENCODING 53 | headers['accept-encoding'] = accept_encoding 54 | 55 | if user_agent: 56 | headers['user-agent'] = user_agent 57 | 58 | if keep_alive: 59 | headers['connection'] = 'keep-alive' 60 | 61 | if basic_auth: 62 | headers['authorization'] = 'Basic ' + \ 63 | b64encode(b(basic_auth)).decode('utf-8') 64 | 65 | if proxy_basic_auth: 66 | headers['proxy-authorization'] = 'Basic ' + \ 67 | b64encode(b(proxy_basic_auth)).decode('utf-8') 68 | 69 | if disable_cache: 70 | headers['cache-control'] = 'no-cache' 71 | 72 | return headers 73 | -------------------------------------------------------------------------------- /lambda/setuptools/msvc9_support.py: -------------------------------------------------------------------------------- 1 | try: 2 | import distutils.msvc9compiler 3 | except ImportError: 4 | pass 5 | 6 | unpatched = dict() 7 | 8 | def patch_for_specialized_compiler(): 9 | """ 10 | Patch functions in distutils.msvc9compiler to use the standalone compiler 11 | build for Python (Windows only). Fall back to original behavior when the 12 | standalone compiler is not available. 13 | """ 14 | if 'distutils' not in globals(): 15 | # The module isn't available to be patched 16 | return 17 | 18 | if unpatched: 19 | # Already patched 20 | return 21 | 22 | unpatched.update(vars(distutils.msvc9compiler)) 23 | 24 | distutils.msvc9compiler.find_vcvarsall = find_vcvarsall 25 | distutils.msvc9compiler.query_vcvarsall = query_vcvarsall 26 | 27 | def find_vcvarsall(version): 28 | Reg = distutils.msvc9compiler.Reg 29 | VC_BASE = r'Software\%sMicrosoft\DevDiv\VCForPython\%0.1f' 30 | key = VC_BASE % ('', version) 31 | try: 32 | # Per-user installs register the compiler path here 33 | productdir = Reg.get_value(key, "installdir") 34 | except KeyError: 35 | try: 36 | # All-user installs on a 64-bit system register here 37 | key = VC_BASE % ('Wow6432Node\\', version) 38 | productdir = Reg.get_value(key, "installdir") 39 | except KeyError: 40 | productdir = None 41 | 42 | if productdir: 43 | import os 44 | vcvarsall = os.path.join(productdir, "vcvarsall.bat") 45 | if os.path.isfile(vcvarsall): 46 | return vcvarsall 47 | 48 | return unpatched['find_vcvarsall'](version) 49 | 50 | def query_vcvarsall(version, *args, **kwargs): 51 | try: 52 | return unpatched['query_vcvarsall'](version, *args, **kwargs) 53 | except distutils.errors.DistutilsPlatformError as exc: 54 | if exc and "vcvarsall.bat" in exc.args[0]: 55 | message = 'Microsoft Visual C++ %0.1f is required (%s).' % (version, exc.args[0]) 56 | if int(version) == 9: 57 | # This redirection link is maintained by Microsoft. 58 | # Contact vspython@microsoft.com if it needs updating. 59 | raise distutils.errors.DistutilsPlatformError( 60 | message + ' Get it from http://aka.ms/vcpython27' 61 | ) 62 | raise distutils.errors.DistutilsPlatformError(message) 63 | raise 64 | -------------------------------------------------------------------------------- /lambda/setuptools/command/install_scripts.py: -------------------------------------------------------------------------------- 1 | from distutils import log 2 | import distutils.command.install_scripts as orig 3 | import os 4 | 5 | from pkg_resources import Distribution, PathMetadata, ensure_directory 6 | 7 | 8 | class install_scripts(orig.install_scripts): 9 | """Do normal script install, plus any egg_info wrapper scripts""" 10 | 11 | def initialize_options(self): 12 | orig.install_scripts.initialize_options(self) 13 | self.no_ep = False 14 | 15 | def run(self): 16 | import setuptools.command.easy_install as ei 17 | 18 | self.run_command("egg_info") 19 | if self.distribution.scripts: 20 | orig.install_scripts.run(self) # run first to set up self.outfiles 21 | else: 22 | self.outfiles = [] 23 | if self.no_ep: 24 | # don't install entry point scripts into .egg file! 25 | return 26 | 27 | ei_cmd = self.get_finalized_command("egg_info") 28 | dist = Distribution( 29 | ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info), 30 | ei_cmd.egg_name, ei_cmd.egg_version, 31 | ) 32 | bs_cmd = self.get_finalized_command('build_scripts') 33 | exec_param = getattr(bs_cmd, 'executable', None) 34 | bw_cmd = self.get_finalized_command("bdist_wininst") 35 | is_wininst = getattr(bw_cmd, '_is_running', False) 36 | writer = ei.ScriptWriter 37 | if is_wininst: 38 | exec_param = "python.exe" 39 | writer = ei.WindowsScriptWriter 40 | # resolve the writer to the environment 41 | writer = writer.best() 42 | cmd = writer.command_spec_class.best().from_param(exec_param) 43 | for args in writer.get_args(dist, cmd.as_header()): 44 | self.write_script(*args) 45 | 46 | def write_script(self, script_name, contents, mode="t", *ignored): 47 | """Write an executable file to the scripts directory""" 48 | from setuptools.command.easy_install import chmod, current_umask 49 | 50 | log.info("Installing %s script to %s", script_name, self.install_dir) 51 | target = os.path.join(self.install_dir, script_name) 52 | self.outfiles.append(target) 53 | 54 | mask = current_umask() 55 | if not self.dry_run: 56 | ensure_directory(target) 57 | f = open(target, "w" + mode) 58 | f.write(contents) 59 | f.close() 60 | chmod(target, 0o777 - mask) 61 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/util/response.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from ..packages.six.moves import http_client as httplib 3 | 4 | from ..exceptions import HeaderParsingError 5 | 6 | 7 | def is_fp_closed(obj): 8 | """ 9 | Checks whether a given file-like object is closed. 10 | 11 | :param obj: 12 | The file-like object to check. 13 | """ 14 | 15 | try: 16 | # Check via the official file-like-object way. 17 | return obj.closed 18 | except AttributeError: 19 | pass 20 | 21 | try: 22 | # Check if the object is a container for another file-like object that 23 | # gets released on exhaustion (e.g. HTTPResponse). 24 | return obj.fp is None 25 | except AttributeError: 26 | pass 27 | 28 | raise ValueError("Unable to determine whether fp is closed.") 29 | 30 | 31 | def assert_header_parsing(headers): 32 | """ 33 | Asserts whether all headers have been successfully parsed. 34 | Extracts encountered errors from the result of parsing headers. 35 | 36 | Only works on Python 3. 37 | 38 | :param headers: Headers to verify. 39 | :type headers: `httplib.HTTPMessage`. 40 | 41 | :raises urllib3.exceptions.HeaderParsingError: 42 | If parsing errors are found. 43 | """ 44 | 45 | # This will fail silently if we pass in the wrong kind of parameter. 46 | # To make debugging easier add an explicit check. 47 | if not isinstance(headers, httplib.HTTPMessage): 48 | raise TypeError('expected httplib.Message, got {0}.'.format( 49 | type(headers))) 50 | 51 | defects = getattr(headers, 'defects', None) 52 | get_payload = getattr(headers, 'get_payload', None) 53 | 54 | unparsed_data = None 55 | if get_payload: # Platform-specific: Python 3. 56 | unparsed_data = get_payload() 57 | 58 | if defects or unparsed_data: 59 | raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) 60 | 61 | 62 | def is_response_to_head(response): 63 | """ 64 | Checks whether the request of a response has been a HEAD-request. 65 | Handles the quirks of AppEngine. 66 | 67 | :param conn: 68 | :type conn: :class:`httplib.HTTPResponse` 69 | """ 70 | # FIXME: Can we do this somehow without accessing private httplib _method? 71 | method = response._method 72 | if isinstance(method, int): # Platform-specific: Appengine 73 | return method == 3 74 | return method.upper() == 'HEAD' 75 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/codingstatemachine.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .constants import eStart 29 | from .compat import wrap_ord 30 | 31 | 32 | class CodingStateMachine: 33 | def __init__(self, sm): 34 | self._mModel = sm 35 | self._mCurrentBytePos = 0 36 | self._mCurrentCharLen = 0 37 | self.reset() 38 | 39 | def reset(self): 40 | self._mCurrentState = eStart 41 | 42 | def next_state(self, c): 43 | # for each byte we get its class 44 | # if it is first byte, we also get byte length 45 | # PY3K: aBuf is a byte stream, so c is an int, not a byte 46 | byteCls = self._mModel['classTable'][wrap_ord(c)] 47 | if self._mCurrentState == eStart: 48 | self._mCurrentBytePos = 0 49 | self._mCurrentCharLen = self._mModel['charLenTable'][byteCls] 50 | # from byte's class and stateTable, we get its next state 51 | curr_state = (self._mCurrentState * self._mModel['classFactor'] 52 | + byteCls) 53 | self._mCurrentState = self._mModel['stateTable'][curr_state] 54 | self._mCurrentBytePos += 1 55 | return self._mCurrentState 56 | 57 | def get_current_charlen(self): 58 | return self._mCurrentCharLen 59 | 60 | def get_coding_state_machine(self): 61 | return self._mModel['name'] 62 | -------------------------------------------------------------------------------- /lambda/requests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # __ 4 | # /__) _ _ _ _ _/ _ 5 | # / ( (- (/ (/ (- _) / _) 6 | # / 7 | 8 | """ 9 | Requests HTTP library 10 | ~~~~~~~~~~~~~~~~~~~~~ 11 | 12 | Requests is an HTTP library, written in Python, for human beings. Basic GET 13 | usage: 14 | 15 | >>> import requests 16 | >>> r = requests.get('https://www.python.org') 17 | >>> r.status_code 18 | 200 19 | >>> 'Python is a programming language' in r.content 20 | True 21 | 22 | ... or POST: 23 | 24 | >>> payload = dict(key1='value1', key2='value2') 25 | >>> r = requests.post('http://httpbin.org/post', data=payload) 26 | >>> print(r.text) 27 | { 28 | ... 29 | "form": { 30 | "key2": "value2", 31 | "key1": "value1" 32 | }, 33 | ... 34 | } 35 | 36 | The other HTTP methods are supported - see `requests.api`. Full documentation 37 | is at . 38 | 39 | :copyright: (c) 2016 by Kenneth Reitz. 40 | :license: Apache 2.0, see LICENSE for more details. 41 | 42 | """ 43 | 44 | __title__ = 'requests' 45 | __version__ = '2.10.0' 46 | __build__ = 0x021000 47 | __author__ = 'Kenneth Reitz' 48 | __license__ = 'Apache 2.0' 49 | __copyright__ = 'Copyright 2016 Kenneth Reitz' 50 | 51 | # Attempt to enable urllib3's SNI support, if possible 52 | try: 53 | from .packages.urllib3.contrib import pyopenssl 54 | pyopenssl.inject_into_urllib3() 55 | except ImportError: 56 | pass 57 | 58 | import warnings 59 | 60 | # urllib3's DependencyWarnings should be silenced. 61 | from .packages.urllib3.exceptions import DependencyWarning 62 | warnings.simplefilter('ignore', DependencyWarning) 63 | 64 | from . import utils 65 | from .models import Request, Response, PreparedRequest 66 | from .api import request, get, head, post, patch, put, delete, options 67 | from .sessions import session, Session 68 | from .status_codes import codes 69 | from .exceptions import ( 70 | RequestException, Timeout, URLRequired, 71 | TooManyRedirects, HTTPError, ConnectionError, 72 | FileModeWarning, ConnectTimeout, ReadTimeout 73 | ) 74 | 75 | # Set default logging handler to avoid "No handler found" warnings. 76 | import logging 77 | try: # Python 2.7+ 78 | from logging import NullHandler 79 | except ImportError: 80 | class NullHandler(logging.Handler): 81 | def emit(self, record): 82 | pass 83 | 84 | logging.getLogger(__name__).addHandler(NullHandler()) 85 | 86 | import warnings 87 | 88 | # FileModeWarnings go off per the default. 89 | warnings.simplefilter('default', FileModeWarning, append=True) 90 | -------------------------------------------------------------------------------- /lambda/setuptools/site-patch.py: -------------------------------------------------------------------------------- 1 | def __boot(): 2 | import sys 3 | import os 4 | PYTHONPATH = os.environ.get('PYTHONPATH') 5 | if PYTHONPATH is None or (sys.platform=='win32' and not PYTHONPATH): 6 | PYTHONPATH = [] 7 | else: 8 | PYTHONPATH = PYTHONPATH.split(os.pathsep) 9 | 10 | pic = getattr(sys,'path_importer_cache',{}) 11 | stdpath = sys.path[len(PYTHONPATH):] 12 | mydir = os.path.dirname(__file__) 13 | #print "searching",stdpath,sys.path 14 | 15 | for item in stdpath: 16 | if item==mydir or not item: 17 | continue # skip if current dir. on Windows, or my own directory 18 | importer = pic.get(item) 19 | if importer is not None: 20 | loader = importer.find_module('site') 21 | if loader is not None: 22 | # This should actually reload the current module 23 | loader.load_module('site') 24 | break 25 | else: 26 | try: 27 | import imp # Avoid import loop in Python >= 3.3 28 | stream, path, descr = imp.find_module('site',[item]) 29 | except ImportError: 30 | continue 31 | if stream is None: 32 | continue 33 | try: 34 | # This should actually reload the current module 35 | imp.load_module('site',stream,path,descr) 36 | finally: 37 | stream.close() 38 | break 39 | else: 40 | raise ImportError("Couldn't find the real 'site' module") 41 | 42 | #print "loaded", __file__ 43 | 44 | known_paths = dict([(makepath(item)[1],1) for item in sys.path]) # 2.2 comp 45 | 46 | oldpos = getattr(sys,'__egginsert',0) # save old insertion position 47 | sys.__egginsert = 0 # and reset the current one 48 | 49 | for item in PYTHONPATH: 50 | addsitedir(item) 51 | 52 | sys.__egginsert += oldpos # restore effective old position 53 | 54 | d, nd = makepath(stdpath[0]) 55 | insert_at = None 56 | new_path = [] 57 | 58 | for item in sys.path: 59 | p, np = makepath(item) 60 | 61 | if np==nd and insert_at is None: 62 | # We've hit the first 'system' path entry, so added entries go here 63 | insert_at = len(new_path) 64 | 65 | if np in known_paths or insert_at is None: 66 | new_path.append(item) 67 | else: 68 | # new path after the insert point, back-insert it 69 | new_path.insert(insert_at, item) 70 | insert_at += 1 71 | 72 | sys.path[:] = new_path 73 | 74 | if __name__=='site': 75 | __boot() 76 | del __boot 77 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_rsa.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import unittest2 4 | 5 | from chef.rsa import Key, SSLError 6 | from chef.tests import TEST_ROOT, skipSlowTest 7 | 8 | class RSATestCase(unittest2.TestCase): 9 | def test_load_private(self): 10 | key = Key(os.path.join(TEST_ROOT, 'client.pem')) 11 | self.assertFalse(key.public) 12 | 13 | def test_load_public(self): 14 | key = Key(os.path.join(TEST_ROOT, 'client_pub.pem')) 15 | self.assertTrue(key.public) 16 | 17 | def test_private_export(self): 18 | key = Key(os.path.join(TEST_ROOT, 'client.pem')) 19 | raw = open(os.path.join(TEST_ROOT, 'client.pem'), 'rb').read() 20 | self.assertTrue(key.private_export().strip(), raw.strip()) 21 | 22 | def test_public_export(self): 23 | key = Key(os.path.join(TEST_ROOT, 'client.pem')) 24 | raw = open(os.path.join(TEST_ROOT, 'client_pub.pem'), 'rb').read() 25 | self.assertTrue(key.public_export().strip(), raw.strip()) 26 | 27 | def test_private_export_pubkey(self): 28 | key = Key(os.path.join(TEST_ROOT, 'client_pub.pem')) 29 | with self.assertRaises(SSLError): 30 | key.private_export() 31 | 32 | def test_public_export_pubkey(self): 33 | key = Key(os.path.join(TEST_ROOT, 'client_pub.pem')) 34 | raw = open(os.path.join(TEST_ROOT, 'client_pub.pem'), 'rb').read() 35 | self.assertTrue(key.public_export().strip(), raw.strip()) 36 | 37 | def test_encrypt_decrypt(self): 38 | key = Key(os.path.join(TEST_ROOT, 'client.pem')) 39 | msg = 'Test string!' 40 | self.assertEqual(key.public_decrypt(key.private_encrypt(msg)), msg) 41 | 42 | def test_encrypt_decrypt_pubkey(self): 43 | key = Key(os.path.join(TEST_ROOT, 'client.pem')) 44 | pubkey = Key(os.path.join(TEST_ROOT, 'client_pub.pem')) 45 | msg = 'Test string!' 46 | self.assertEqual(pubkey.public_decrypt(key.private_encrypt(msg)), msg) 47 | 48 | def test_generate(self): 49 | key = Key.generate() 50 | msg = 'Test string!' 51 | self.assertEqual(key.public_decrypt(key.private_encrypt(msg)), msg) 52 | 53 | def test_generate_load(self): 54 | key = Key.generate() 55 | key2 = Key(key.private_export()) 56 | self.assertFalse(key2.public) 57 | key3 = Key(key.public_export()) 58 | self.assertTrue(key3.public) 59 | 60 | def test_load_pem_string(self): 61 | key = Key(open(os.path.join(TEST_ROOT, 'client.pem'), 'rb').read()) 62 | self.assertFalse(key.public) 63 | 64 | def test_load_public_pem_string(self): 65 | key = Key(open(os.path.join(TEST_ROOT, 'client_pub.pem'), 'rb').read()) 66 | self.assertTrue(key.public) 67 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/filepost.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import codecs 3 | 4 | from uuid import uuid4 5 | from io import BytesIO 6 | 7 | from .packages import six 8 | from .packages.six import b 9 | from .fields import RequestField 10 | 11 | writer = codecs.lookup('utf-8')[3] 12 | 13 | 14 | def choose_boundary(): 15 | """ 16 | Our embarassingly-simple replacement for mimetools.choose_boundary. 17 | """ 18 | return uuid4().hex 19 | 20 | 21 | def iter_field_objects(fields): 22 | """ 23 | Iterate over fields. 24 | 25 | Supports list of (k, v) tuples and dicts, and lists of 26 | :class:`~urllib3.fields.RequestField`. 27 | 28 | """ 29 | if isinstance(fields, dict): 30 | i = six.iteritems(fields) 31 | else: 32 | i = iter(fields) 33 | 34 | for field in i: 35 | if isinstance(field, RequestField): 36 | yield field 37 | else: 38 | yield RequestField.from_tuples(*field) 39 | 40 | 41 | def iter_fields(fields): 42 | """ 43 | .. deprecated:: 1.6 44 | 45 | Iterate over fields. 46 | 47 | The addition of :class:`~urllib3.fields.RequestField` makes this function 48 | obsolete. Instead, use :func:`iter_field_objects`, which returns 49 | :class:`~urllib3.fields.RequestField` objects. 50 | 51 | Supports list of (k, v) tuples and dicts. 52 | """ 53 | if isinstance(fields, dict): 54 | return ((k, v) for k, v in six.iteritems(fields)) 55 | 56 | return ((k, v) for k, v in fields) 57 | 58 | 59 | def encode_multipart_formdata(fields, boundary=None): 60 | """ 61 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. 62 | 63 | :param fields: 64 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). 65 | 66 | :param boundary: 67 | If not specified, then a random boundary will be generated using 68 | :func:`mimetools.choose_boundary`. 69 | """ 70 | body = BytesIO() 71 | if boundary is None: 72 | boundary = choose_boundary() 73 | 74 | for field in iter_field_objects(fields): 75 | body.write(b('--%s\r\n' % (boundary))) 76 | 77 | writer(body).write(field.render_headers()) 78 | data = field.data 79 | 80 | if isinstance(data, int): 81 | data = str(data) # Backwards compatibility 82 | 83 | if isinstance(data, six.text_type): 84 | writer(body).write(data) 85 | else: 86 | body.write(data) 87 | 88 | body.write(b'\r\n') 89 | 90 | body.write(b('--%s--\r\n' % (boundary))) 91 | 92 | content_type = str('multipart/form-data; boundary=%s' % boundary) 93 | 94 | return body.getvalue(), content_type 95 | -------------------------------------------------------------------------------- /lambda/pkg_resources/extern/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | class VendorImporter: 5 | """ 6 | A PEP 302 meta path importer for finding optionally-vendored 7 | or otherwise naturally-installed packages from root_name. 8 | """ 9 | def __init__(self, root_name, vendored_names=(), vendor_pkg=None): 10 | self.root_name = root_name 11 | self.vendored_names = set(vendored_names) 12 | self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor') 13 | 14 | @property 15 | def search_path(self): 16 | """ 17 | Search first the vendor package then as a natural package. 18 | """ 19 | yield self.vendor_pkg + '.' 20 | yield '' 21 | 22 | def find_module(self, fullname, path=None): 23 | """ 24 | Return self when fullname starts with root_name and the 25 | target module is one vendored through this importer. 26 | """ 27 | root, base, target = fullname.partition(self.root_name + '.') 28 | if root: 29 | return 30 | if not any(map(target.startswith, self.vendored_names)): 31 | return 32 | return self 33 | 34 | def load_module(self, fullname): 35 | """ 36 | Iterate over the search path to locate and load fullname. 37 | """ 38 | root, base, target = fullname.partition(self.root_name + '.') 39 | for prefix in self.search_path: 40 | try: 41 | extant = prefix + target 42 | __import__(extant) 43 | mod = sys.modules[extant] 44 | sys.modules[fullname] = mod 45 | # mysterious hack: 46 | # Remove the reference to the extant package/module 47 | # on later Python versions to cause relative imports 48 | # in the vendor package to resolve the same modules 49 | # as those going through this importer. 50 | if sys.version_info > (3, 3): 51 | del sys.modules[extant] 52 | return mod 53 | except ImportError: 54 | pass 55 | else: 56 | raise ImportError( 57 | "The '{target}' package is required; " 58 | "normally this is bundled with this package so if you get " 59 | "this warning, consult the packager of your " 60 | "distribution.".format(**locals()) 61 | ) 62 | 63 | def install(self): 64 | """ 65 | Install this importer into sys.meta_path if not already present. 66 | """ 67 | if self not in sys.meta_path: 68 | sys.meta_path.append(self) 69 | 70 | names = 'packaging', 'six' 71 | VendorImporter(__name__, names).install() 72 | -------------------------------------------------------------------------------- /lambda/setuptools/command/alias.py: -------------------------------------------------------------------------------- 1 | from distutils.errors import DistutilsOptionError 2 | 3 | from setuptools.extern.six.moves import map 4 | 5 | from setuptools.command.setopt import edit_config, option_base, config_file 6 | 7 | 8 | def shquote(arg): 9 | """Quote an argument for later parsing by shlex.split()""" 10 | for c in '"', "'", "\\", "#": 11 | if c in arg: 12 | return repr(arg) 13 | if arg.split() != [arg]: 14 | return repr(arg) 15 | return arg 16 | 17 | 18 | class alias(option_base): 19 | """Define a shortcut that invokes one or more commands""" 20 | 21 | description = "define a shortcut to invoke one or more commands" 22 | command_consumes_arguments = True 23 | 24 | user_options = [ 25 | ('remove', 'r', 'remove (unset) the alias'), 26 | ] + option_base.user_options 27 | 28 | boolean_options = option_base.boolean_options + ['remove'] 29 | 30 | def initialize_options(self): 31 | option_base.initialize_options(self) 32 | self.args = None 33 | self.remove = None 34 | 35 | def finalize_options(self): 36 | option_base.finalize_options(self) 37 | if self.remove and len(self.args) != 1: 38 | raise DistutilsOptionError( 39 | "Must specify exactly one argument (the alias name) when " 40 | "using --remove" 41 | ) 42 | 43 | def run(self): 44 | aliases = self.distribution.get_option_dict('aliases') 45 | 46 | if not self.args: 47 | print("Command Aliases") 48 | print("---------------") 49 | for alias in aliases: 50 | print("setup.py alias", format_alias(alias, aliases)) 51 | return 52 | 53 | elif len(self.args) == 1: 54 | alias, = self.args 55 | if self.remove: 56 | command = None 57 | elif alias in aliases: 58 | print("setup.py alias", format_alias(alias, aliases)) 59 | return 60 | else: 61 | print("No alias definition found for %r" % alias) 62 | return 63 | else: 64 | alias = self.args[0] 65 | command = ' '.join(map(shquote, self.args[1:])) 66 | 67 | edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run) 68 | 69 | 70 | def format_alias(name, aliases): 71 | source, command = aliases[name] 72 | if source == config_file('global'): 73 | source = '--global-config ' 74 | elif source == config_file('user'): 75 | source = '--user-config ' 76 | elif source == config_file('local'): 77 | source = '' 78 | else: 79 | source = '--filename=%r' % source 80 | return source + name + ' ' + command 81 | -------------------------------------------------------------------------------- /lambda/chef/auth.py: -------------------------------------------------------------------------------- 1 | import six.moves 2 | import base64 3 | import datetime 4 | import hashlib 5 | import re 6 | 7 | def _ruby_b64encode(value): 8 | """The Ruby function Base64.encode64 automatically breaks things up 9 | into 60-character chunks. 10 | """ 11 | b64 = base64.b64encode(value) 12 | for i in six.moves.range(0, len(b64), 60): 13 | yield b64[i:i + 60].decode() 14 | 15 | def ruby_b64encode(value): 16 | return '\n'.join(_ruby_b64encode(value)) 17 | 18 | def sha1_base64(value): 19 | """An implementation of Mixlib::Authentication::Digester.""" 20 | return ruby_b64encode(hashlib.sha1(value.encode()).digest()) 21 | 22 | class UTC(datetime.tzinfo): 23 | """UTC timezone stub.""" 24 | 25 | ZERO = datetime.timedelta(0) 26 | 27 | def utcoffset(self, dt): 28 | return self.ZERO 29 | 30 | def tzname(self, dt): 31 | return 'UTC' 32 | 33 | def dst(self, dt): 34 | return self.ZERO 35 | 36 | utc = UTC() 37 | 38 | def canonical_time(timestamp): 39 | if timestamp.tzinfo is not None: 40 | timestamp = timestamp.astimezone(utc).replace(tzinfo=None) 41 | return timestamp.replace(microsecond=0).isoformat() + 'Z' 42 | 43 | canonical_path_regex = re.compile(r'/+') 44 | def canonical_path(path): 45 | path = canonical_path_regex.sub('/', path) 46 | if len(path) > 1: 47 | path = path.rstrip('/') 48 | return path 49 | 50 | def canonical_request(http_method, path, hashed_body, timestamp, user_id): 51 | # Canonicalize request parameters 52 | http_method = http_method.upper() 53 | path = canonical_path(path) 54 | if isinstance(timestamp, datetime.datetime): 55 | timestamp = canonical_time(timestamp) 56 | hashed_path = sha1_base64(path) 57 | return ('Method:%(http_method)s\n' 58 | 'Hashed Path:%(hashed_path)s\n' 59 | 'X-Ops-Content-Hash:%(hashed_body)s\n' 60 | 'X-Ops-Timestamp:%(timestamp)s\n' 61 | 'X-Ops-UserId:%(user_id)s' % vars()) 62 | 63 | def sign_request(key, http_method, path, body, host, timestamp, user_id): 64 | """Generate the needed headers for the Opscode authentication protocol.""" 65 | timestamp = canonical_time(timestamp) 66 | hashed_body = sha1_base64(body or '') 67 | 68 | # Simple headers 69 | headers = { 70 | 'x-ops-sign': 'version=1.0', 71 | 'x-ops-userid': user_id, 72 | 'x-ops-timestamp': timestamp, 73 | 'x-ops-content-hash': hashed_body, 74 | } 75 | 76 | # Create RSA signature 77 | req = canonical_request(http_method, path, hashed_body, timestamp, user_id) 78 | sig = _ruby_b64encode(key.private_encrypt(req)) 79 | for i, line in enumerate(sig): 80 | headers['x-ops-authorization-%s'%(i+1)] = line 81 | return headers 82 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/chardetect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Script which takes one or more file paths and reports on their detected 4 | encodings 5 | 6 | Example:: 7 | 8 | % chardetect somefile someotherfile 9 | somefile: windows-1252 with confidence 0.5 10 | someotherfile: ascii with confidence 1.0 11 | 12 | If no paths are provided, it takes its input from stdin. 13 | 14 | """ 15 | 16 | from __future__ import absolute_import, print_function, unicode_literals 17 | 18 | import argparse 19 | import sys 20 | from io import open 21 | 22 | from chardet import __version__ 23 | from chardet.universaldetector import UniversalDetector 24 | 25 | 26 | def description_of(lines, name='stdin'): 27 | """ 28 | Return a string describing the probable encoding of a file or 29 | list of strings. 30 | 31 | :param lines: The lines to get the encoding of. 32 | :type lines: Iterable of bytes 33 | :param name: Name of file or collection of lines 34 | :type name: str 35 | """ 36 | u = UniversalDetector() 37 | for line in lines: 38 | u.feed(line) 39 | u.close() 40 | result = u.result 41 | if result['encoding']: 42 | return '{0}: {1} with confidence {2}'.format(name, result['encoding'], 43 | result['confidence']) 44 | else: 45 | return '{0}: no result'.format(name) 46 | 47 | 48 | def main(argv=None): 49 | ''' 50 | Handles command line arguments and gets things started. 51 | 52 | :param argv: List of arguments, as if specified on the command-line. 53 | If None, ``sys.argv[1:]`` is used instead. 54 | :type argv: list of str 55 | ''' 56 | # Get command line arguments 57 | parser = argparse.ArgumentParser( 58 | description="Takes one or more file paths and reports their detected \ 59 | encodings", 60 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 61 | conflict_handler='resolve') 62 | parser.add_argument('input', 63 | help='File whose encoding we would like to determine.', 64 | type=argparse.FileType('rb'), nargs='*', 65 | default=[sys.stdin]) 66 | parser.add_argument('--version', action='version', 67 | version='%(prog)s {0}'.format(__version__)) 68 | args = parser.parse_args(argv) 69 | 70 | for f in args.input: 71 | if f.isatty(): 72 | print("You are running chardetect interactively. Press " + 73 | "CTRL-D twice at the start of a blank line to signal the " + 74 | "end of your input. If you want help, run chardetect " + 75 | "--help\n", file=sys.stderr) 76 | print(description_of(f, f.name)) 77 | 78 | 79 | if __name__ == '__main__': 80 | main() 81 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_search.py: -------------------------------------------------------------------------------- 1 | from unittest2 import skip 2 | 3 | from chef import Search, Node 4 | from chef.exceptions import ChefError 5 | from chef.tests import ChefTestCase, mockSearch 6 | 7 | class SearchTestCase(ChefTestCase): 8 | def test_search_all(self): 9 | s = Search('node') 10 | self.assertGreaterEqual(len(s), 3) 11 | self.assertIn('test_1', s) 12 | self.assertIn('test_2', s) 13 | self.assertIn('test_3', s) 14 | 15 | def test_search_query(self): 16 | s = Search('node', 'role:test_1') 17 | self.assertGreaterEqual(len(s), 2) 18 | self.assertIn('test_1', s) 19 | self.assertNotIn('test_2', s) 20 | self.assertIn('test_3', s) 21 | 22 | def test_list(self): 23 | searches = Search.list() 24 | self.assertIn('node', searches) 25 | self.assertIn('role', searches) 26 | 27 | def test_search_set_query(self): 28 | s = Search('node').query('role:test_1') 29 | self.assertGreaterEqual(len(s), 2) 30 | self.assertIn('test_1', s) 31 | self.assertNotIn('test_2', s) 32 | self.assertIn('test_3', s) 33 | 34 | def test_search_call(self): 35 | s = Search('node')('role:test_1') 36 | self.assertGreaterEqual(len(s), 2) 37 | self.assertIn('test_1', s) 38 | self.assertNotIn('test_2', s) 39 | self.assertIn('test_3', s) 40 | 41 | def test_rows(self): 42 | s = Search('node', rows=1) 43 | self.assertEqual(len(s), 1) 44 | self.assertGreaterEqual(s.total, 3) 45 | 46 | def test_start(self): 47 | s = Search('node', start=1) 48 | self.assertEqual(len(s), s.total-1) 49 | self.assertGreaterEqual(s.total, 3) 50 | 51 | def test_slice(self): 52 | s = Search('node')[1:2] 53 | self.assertEqual(len(s), 1) 54 | self.assertGreaterEqual(s.total, 3) 55 | 56 | s2 = s[1:2] 57 | self.assertEqual(len(s2), 1) 58 | self.assertGreaterEqual(s2.total, 3) 59 | self.assertNotEqual(s[0]['name'], s2[0]['name']) 60 | 61 | s3 = Search('node')[2:3] 62 | self.assertEqual(len(s3), 1) 63 | self.assertGreaterEqual(s3.total, 3) 64 | self.assertEqual(s2[0]['name'], s3[0]['name']) 65 | 66 | def test_object(self): 67 | s = Search('node', 'name:test_1') 68 | self.assertEqual(len(s), 1) 69 | node = s[0].object 70 | self.assertEqual(node.name, 'test_1') 71 | self.assertEqual(node.run_list, ['role[test_1]']) 72 | 73 | 74 | class MockSearchTestCase(ChefTestCase): 75 | @mockSearch({ 76 | ('node', '*:*'): [Node('fake_1', skip_load=True).to_dict()] 77 | }) 78 | def test_single_node(self, MockSearch): 79 | import chef.search 80 | s = chef.search.Search('node') 81 | self.assertEqual(len(s), 1) 82 | self.assertIn('fake_1', s) 83 | -------------------------------------------------------------------------------- /lambda/chef/tests/test_data_bag.py: -------------------------------------------------------------------------------- 1 | from chef import DataBag, DataBagItem, Search 2 | from chef.exceptions import ChefError 3 | from chef.tests import ChefTestCase 4 | 5 | class DataBagTestCase(ChefTestCase): 6 | def test_list(self): 7 | bags = DataBag.list() 8 | self.assertIn('test_1', bags) 9 | self.assertIsInstance(bags['test_1'], DataBag) 10 | 11 | def test_keys(self): 12 | bag = DataBag('test_1') 13 | self.assertItemsEqual(list(bag.keys()), ['item_1', 'item_2']) 14 | self.assertItemsEqual(iter(bag), ['item_1', 'item_2']) 15 | 16 | def test_item(self): 17 | bag = DataBag('test_1') 18 | item = bag['item_1'] 19 | self.assertEqual(item['test_attr'], 1) 20 | self.assertEqual(item['other'], 'foo') 21 | 22 | def test_search_item(self): 23 | self.assertIn('test_1', Search.list()) 24 | q = Search('test_1') 25 | self.assertIn('item_1', q) 26 | self.assertIn('item_2', q) 27 | self.assertEqual(q['item_1']['raw_data']['test_attr'], 1) 28 | item = q['item_1'].object 29 | self.assertIsInstance(item, DataBagItem) 30 | self.assertEqual(item['test_attr'], 1) 31 | 32 | def test_direct_item(self): 33 | item = DataBagItem('test_1', 'item_1') 34 | self.assertEqual(item['test_attr'], 1) 35 | self.assertEqual(item['other'], 'foo') 36 | 37 | def test_direct_item_bag(self): 38 | bag = DataBag('test_1') 39 | item = DataBagItem(bag, 'item_1') 40 | self.assertEqual(item['test_attr'], 1) 41 | self.assertEqual(item['other'], 'foo') 42 | 43 | def test_create_bag(self): 44 | name = self.random() 45 | bag = DataBag.create(name) 46 | self.register(bag) 47 | self.assertIn(name, DataBag.list()) 48 | 49 | def test_create_item(self): 50 | value = self.random() 51 | bag_name = self.random() 52 | bag = DataBag.create(bag_name) 53 | self.register(bag) 54 | item_name = self.random() 55 | item = DataBagItem.create(bag, item_name, foo=value) 56 | self.assertIn('foo', item) 57 | self.assertEqual(item['foo'], value) 58 | self.assertIn(item_name, bag) 59 | bag2 = DataBag(bag_name) 60 | self.assertIn(item_name, bag2) 61 | item2 = bag2[item_name] 62 | self.assertIn('foo', item) 63 | self.assertEqual(item['foo'], value) 64 | 65 | def test_set_item(self): 66 | value = self.random() 67 | value2 = self.random() 68 | bag_name = self.random() 69 | bag = DataBag.create(bag_name) 70 | self.register(bag) 71 | item_name = self.random() 72 | item = DataBagItem.create(bag, item_name, foo=value) 73 | item['foo'] = value2 74 | item.save() 75 | self.assertEqual(item['foo'], value2) 76 | item2 = DataBagItem(bag, item_name) 77 | self.assertEqual(item2['foo'], value2) 78 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/utf8prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | from .charsetprober import CharSetProber 30 | from .codingstatemachine import CodingStateMachine 31 | from .mbcssm import UTF8SMModel 32 | 33 | ONE_CHAR_PROB = 0.5 34 | 35 | 36 | class UTF8Prober(CharSetProber): 37 | def __init__(self): 38 | CharSetProber.__init__(self) 39 | self._mCodingSM = CodingStateMachine(UTF8SMModel) 40 | self.reset() 41 | 42 | def reset(self): 43 | CharSetProber.reset(self) 44 | self._mCodingSM.reset() 45 | self._mNumOfMBChar = 0 46 | 47 | def get_charset_name(self): 48 | return "utf-8" 49 | 50 | def feed(self, aBuf): 51 | for c in aBuf: 52 | codingState = self._mCodingSM.next_state(c) 53 | if codingState == constants.eError: 54 | self._mState = constants.eNotMe 55 | break 56 | elif codingState == constants.eItsMe: 57 | self._mState = constants.eFoundIt 58 | break 59 | elif codingState == constants.eStart: 60 | if self._mCodingSM.get_current_charlen() >= 2: 61 | self._mNumOfMBChar += 1 62 | 63 | if self.get_state() == constants.eDetecting: 64 | if self.get_confidence() > constants.SHORTCUT_THRESHOLD: 65 | self._mState = constants.eFoundIt 66 | 67 | return self.get_state() 68 | 69 | def get_confidence(self): 70 | unlike = 0.99 71 | if self._mNumOfMBChar < 6: 72 | for i in range(0, self._mNumOfMBChar): 73 | unlike = unlike * ONE_CHAR_PROB 74 | return 1.0 - unlike 75 | else: 76 | return unlike 77 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/entry_points.txt: -------------------------------------------------------------------------------- 1 | [console_scripts] 2 | easy_install = setuptools.command.easy_install:main 3 | easy_install-3.5 = setuptools.command.easy_install:main 4 | 5 | [distutils.commands] 6 | alias = setuptools.command.alias:alias 7 | bdist_egg = setuptools.command.bdist_egg:bdist_egg 8 | bdist_rpm = setuptools.command.bdist_rpm:bdist_rpm 9 | bdist_wininst = setuptools.command.bdist_wininst:bdist_wininst 10 | build_ext = setuptools.command.build_ext:build_ext 11 | build_py = setuptools.command.build_py:build_py 12 | develop = setuptools.command.develop:develop 13 | easy_install = setuptools.command.easy_install:easy_install 14 | egg_info = setuptools.command.egg_info:egg_info 15 | install = setuptools.command.install:install 16 | install_egg_info = setuptools.command.install_egg_info:install_egg_info 17 | install_lib = setuptools.command.install_lib:install_lib 18 | install_scripts = setuptools.command.install_scripts:install_scripts 19 | register = setuptools.command.register:register 20 | rotate = setuptools.command.rotate:rotate 21 | saveopts = setuptools.command.saveopts:saveopts 22 | sdist = setuptools.command.sdist:sdist 23 | setopt = setuptools.command.setopt:setopt 24 | test = setuptools.command.test:test 25 | upload = setuptools.command.upload:upload 26 | upload_docs = setuptools.command.upload_docs:upload_docs 27 | 28 | [distutils.setup_keywords] 29 | convert_2to3_doctests = setuptools.dist:assert_string_list 30 | dependency_links = setuptools.dist:assert_string_list 31 | eager_resources = setuptools.dist:assert_string_list 32 | entry_points = setuptools.dist:check_entry_points 33 | exclude_package_data = setuptools.dist:check_package_data 34 | extras_require = setuptools.dist:check_extras 35 | include_package_data = setuptools.dist:assert_bool 36 | install_requires = setuptools.dist:check_requirements 37 | namespace_packages = setuptools.dist:check_nsp 38 | package_data = setuptools.dist:check_package_data 39 | packages = setuptools.dist:check_packages 40 | setup_requires = setuptools.dist:check_requirements 41 | test_loader = setuptools.dist:check_importable 42 | test_runner = setuptools.dist:check_importable 43 | test_suite = setuptools.dist:check_test_suite 44 | tests_require = setuptools.dist:check_requirements 45 | use_2to3 = setuptools.dist:assert_bool 46 | use_2to3_exclude_fixers = setuptools.dist:assert_string_list 47 | use_2to3_fixers = setuptools.dist:assert_string_list 48 | zip_safe = setuptools.dist:assert_bool 49 | 50 | [egg_info.writers] 51 | PKG-INFO = setuptools.command.egg_info:write_pkg_info 52 | dependency_links.txt = setuptools.command.egg_info:overwrite_arg 53 | depends.txt = setuptools.command.egg_info:warn_depends_obsolete 54 | eager_resources.txt = setuptools.command.egg_info:overwrite_arg 55 | entry_points.txt = setuptools.command.egg_info:write_entries 56 | namespace_packages.txt = setuptools.command.egg_info:overwrite_arg 57 | requires.txt = setuptools.command.egg_info:write_requirements 58 | top_level.txt = setuptools.command.egg_info:write_toplevel_names 59 | 60 | [setuptools.installation] 61 | eggsecutable = setuptools.command.easy_install:bootstrap 62 | 63 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | urllib3 - Thread-safe connection pooling and re-using. 3 | """ 4 | 5 | from __future__ import absolute_import 6 | import warnings 7 | 8 | from .connectionpool import ( 9 | HTTPConnectionPool, 10 | HTTPSConnectionPool, 11 | connection_from_url 12 | ) 13 | 14 | from . import exceptions 15 | from .filepost import encode_multipart_formdata 16 | from .poolmanager import PoolManager, ProxyManager, proxy_from_url 17 | from .response import HTTPResponse 18 | from .util.request import make_headers 19 | from .util.url import get_host 20 | from .util.timeout import Timeout 21 | from .util.retry import Retry 22 | 23 | 24 | # Set default logging handler to avoid "No handler found" warnings. 25 | import logging 26 | try: # Python 2.7+ 27 | from logging import NullHandler 28 | except ImportError: 29 | class NullHandler(logging.Handler): 30 | def emit(self, record): 31 | pass 32 | 33 | __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)' 34 | __license__ = 'MIT' 35 | __version__ = '1.15.1' 36 | 37 | __all__ = ( 38 | 'HTTPConnectionPool', 39 | 'HTTPSConnectionPool', 40 | 'PoolManager', 41 | 'ProxyManager', 42 | 'HTTPResponse', 43 | 'Retry', 44 | 'Timeout', 45 | 'add_stderr_logger', 46 | 'connection_from_url', 47 | 'disable_warnings', 48 | 'encode_multipart_formdata', 49 | 'get_host', 50 | 'make_headers', 51 | 'proxy_from_url', 52 | ) 53 | 54 | logging.getLogger(__name__).addHandler(NullHandler()) 55 | 56 | 57 | def add_stderr_logger(level=logging.DEBUG): 58 | """ 59 | Helper for quickly adding a StreamHandler to the logger. Useful for 60 | debugging. 61 | 62 | Returns the handler after adding it. 63 | """ 64 | # This method needs to be in this __init__.py to get the __name__ correct 65 | # even if urllib3 is vendored within another package. 66 | logger = logging.getLogger(__name__) 67 | handler = logging.StreamHandler() 68 | handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) 69 | logger.addHandler(handler) 70 | logger.setLevel(level) 71 | logger.debug('Added a stderr logging handler to logger: %s', __name__) 72 | return handler 73 | 74 | # ... Clean up. 75 | del NullHandler 76 | 77 | 78 | # All warning filters *must* be appended unless you're really certain that they 79 | # shouldn't be: otherwise, it's very hard for users to use most Python 80 | # mechanisms to silence them. 81 | # SecurityWarning's always go off by default. 82 | warnings.simplefilter('always', exceptions.SecurityWarning, append=True) 83 | # SubjectAltNameWarning's should go off once per host 84 | warnings.simplefilter('default', exceptions.SubjectAltNameWarning, append=True) 85 | # InsecurePlatformWarning's don't vary between requests, so we keep it default. 86 | warnings.simplefilter('default', exceptions.InsecurePlatformWarning, 87 | append=True) 88 | # SNIMissingWarnings should go off only once. 89 | warnings.simplefilter('default', exceptions.SNIMissingWarning, append=True) 90 | 91 | 92 | def disable_warnings(category=exceptions.HTTPWarning): 93 | """ 94 | Helper for quickly disabling all urllib3 warnings. 95 | """ 96 | warnings.simplefilter('ignore', category) 97 | -------------------------------------------------------------------------------- /lambda/requests/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.exceptions 5 | ~~~~~~~~~~~~~~~~~~~ 6 | 7 | This module contains the set of Requests' exceptions. 8 | 9 | """ 10 | from .packages.urllib3.exceptions import HTTPError as BaseHTTPError 11 | 12 | 13 | class RequestException(IOError): 14 | """There was an ambiguous exception that occurred while handling your 15 | request.""" 16 | 17 | def __init__(self, *args, **kwargs): 18 | """ 19 | Initialize RequestException with `request` and `response` objects. 20 | """ 21 | response = kwargs.pop('response', None) 22 | self.response = response 23 | self.request = kwargs.pop('request', None) 24 | if (response is not None and not self.request and 25 | hasattr(response, 'request')): 26 | self.request = self.response.request 27 | super(RequestException, self).__init__(*args, **kwargs) 28 | 29 | 30 | class HTTPError(RequestException): 31 | """An HTTP error occurred.""" 32 | 33 | 34 | class ConnectionError(RequestException): 35 | """A Connection error occurred.""" 36 | 37 | 38 | class ProxyError(ConnectionError): 39 | """A proxy error occurred.""" 40 | 41 | 42 | class SSLError(ConnectionError): 43 | """An SSL error occurred.""" 44 | 45 | 46 | class Timeout(RequestException): 47 | """The request timed out. 48 | 49 | Catching this error will catch both 50 | :exc:`~requests.exceptions.ConnectTimeout` and 51 | :exc:`~requests.exceptions.ReadTimeout` errors. 52 | """ 53 | 54 | 55 | class ConnectTimeout(ConnectionError, Timeout): 56 | """The request timed out while trying to connect to the remote server. 57 | 58 | Requests that produced this error are safe to retry. 59 | """ 60 | 61 | 62 | class ReadTimeout(Timeout): 63 | """The server did not send any data in the allotted amount of time.""" 64 | 65 | 66 | class URLRequired(RequestException): 67 | """A valid URL is required to make a request.""" 68 | 69 | 70 | class TooManyRedirects(RequestException): 71 | """Too many redirects.""" 72 | 73 | 74 | class MissingSchema(RequestException, ValueError): 75 | """The URL schema (e.g. http or https) is missing.""" 76 | 77 | 78 | class InvalidSchema(RequestException, ValueError): 79 | """See defaults.py for valid schemas.""" 80 | 81 | 82 | class InvalidURL(RequestException, ValueError): 83 | """ The URL provided was somehow invalid. """ 84 | 85 | 86 | class ChunkedEncodingError(RequestException): 87 | """The server declared chunked encoding but sent an invalid chunk.""" 88 | 89 | 90 | class ContentDecodingError(RequestException, BaseHTTPError): 91 | """Failed to decode response content""" 92 | 93 | 94 | class StreamConsumedError(RequestException, TypeError): 95 | """The content for this response was already consumed""" 96 | 97 | 98 | class RetryError(RequestException): 99 | """Custom retries logic failed""" 100 | 101 | 102 | # Warnings 103 | 104 | 105 | class RequestsWarning(Warning): 106 | """Base warning for Requests.""" 107 | pass 108 | 109 | 110 | class FileModeWarning(RequestsWarning, DeprecationWarning): 111 | """ 112 | A file was opened in text mode, but Requests determined its binary length. 113 | """ 114 | pass 115 | -------------------------------------------------------------------------------- /terraform/main.tf: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file 4 | # except in compliance with the License. A copy of the License is located at 5 | # 6 | # http://aws.amazon.com/apache2.0/ 7 | # 8 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" 9 | # BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations under the License. 11 | provider "aws" { 12 | region = "${var.region}" 13 | } 14 | 15 | # Lambda Role with Required Policy 16 | resource "aws_iam_role_policy" "lambda_policy" { 17 | name = "chef_node_cleanup_lambda" 18 | role = "${aws_iam_role.lambda_role.id}" 19 | policy = <' % (self.name) 99 | 100 | def __getitem__(self, key): 101 | # We allow fall-through here, so values default to None 102 | 103 | return self.__dict__.get(key, None) 104 | 105 | def get(self, key, default=None): 106 | return self.__dict__.get(key, default) 107 | -------------------------------------------------------------------------------- /lambda/PyChef-0.3.0.dist-info/RECORD: -------------------------------------------------------------------------------- 1 | PyChef-0.3.0.dist-info/DESCRIPTION.rst,sha256=atEJ5hhQBzgteWHAsaQoGjV_ZEiJ_1ulh_bAuR8o-lY,489 2 | PyChef-0.3.0.dist-info/METADATA,sha256=Uk6zGQCanzv9CZZRdQX4KI_IGleKd3ubQpUI-LdzSnc,1029 3 | PyChef-0.3.0.dist-info/RECORD,, 4 | PyChef-0.3.0.dist-info/WHEEL,sha256=JTb7YztR8fkPg6aSjc571Q4eiVHCwmUDlX8PhuuqIIE,92 5 | PyChef-0.3.0.dist-info/metadata.json,sha256=gLylRMVNcoEuEc_eZplnqQzj1Sp8y9mtbpHjYeQlxNM,778 6 | PyChef-0.3.0.dist-info/top_level.txt,sha256=X3rAxskpExweuAjLIvpOddTMbgp_bkUc6OEJEOko_qE,5 7 | chef/__init__.py,sha256=DsuCvOjUj70rxmolzSig-6a3Mu5jkVBjbNNRFh81QTw,396 8 | chef/acl.py,sha256=GMp46zMYJcC8Im0woNVYbGF9ZtEUTsg7fIlyKqye9io,6015 9 | chef/api.py,sha256=c_Hy7sHZvg1anV_NrMRW_pGzRvrJAGigYPPMIG5m5KY,10065 10 | chef/auth.py,sha256=SBYDrkDKOxxQ0yApyevj33LCZ2FE90DHxTscHZB3rUA,2443 11 | chef/base.py,sha256=eG8CKJNbuXpCdTHwlqe2R3p2f-Y-81_EvoW12VdQ_jQ,4473 12 | chef/client.py,sha256=N4KfnJQg9KV4qd9bYFkckj5I11lwh7WNgTY_M4VtlVg,1813 13 | chef/data_bag.py,sha256=uTVF2KaPIW2flRxi2RxLLs2kSOPTLtOZqi6u6WqPcNk,3707 14 | chef/environment.py,sha256=M8Lgx7T_MHiMjKb2VXPEuU7dkVAsUijsdR8IcIQORyo,353 15 | chef/exceptions.py,sha256=pyLuL7s52rGg3CG907zAuiuVtMyRdy9qLnTRFZWotZQ,952 16 | chef/fabric.py,sha256=U1fBNU1aKgSaU-X3ljJbnbb2MEyy0NNsFFzNiv2BhMU,6789 17 | chef/node.py,sha256=g79aeVvvK2FN56mS9npelICF-7edT3QH9tU1VGdPUdk,6699 18 | chef/permissions.py,sha256=M5sbN3jTKmt9vGzeMaod4kCfsYiD-WqpZNk1tkAPRp0,317 19 | chef/role.py,sha256=7kQd0Kvt2_XTjD_uG_mRp7VQnHb-L5PXP1blrOlsiko,290 20 | chef/rsa.py,sha256=rpCjCZja38INg91xG8n5pIQe6g6L_JmLcFcmyrbqBP4,8106 21 | chef/search.py,sha256=_MQxS-yO3IkYhxD2p0_eSshFHsmUhSXFpbbgABabFDE,3640 22 | chef/tests/__init__.py,sha256=ZbuC2UZnGE_FUbHS9eka6OKDRDATH3MwAFjLypuuXps,1820 23 | chef/tests/test_api.py,sha256=Jol94bwBoZo70MxqZDIWJeX5a1nkFG9ds0XBff_wGPU,1062 24 | chef/tests/test_client.py,sha256=t1zCfH13cREKi2tNhft3W-YmN2AU_MpmOtV1Sxw2EuE,1203 25 | chef/tests/test_data_bag.py,sha256=C_K84M8Las2BFAJuWagCHqvPM4DYvTClCW5YfAm0J5E,2629 26 | chef/tests/test_environment.py,sha256=dY9RNh2aaQAOJmcHTf8F2MwPGBViHnU-yiiA1eg5CxM,725 27 | chef/tests/test_fabric.py,sha256=YmXA2blhCpV3kKIDvuGqD-wnGENb10ofngh_GnLEZJ0,888 28 | chef/tests/test_node.py,sha256=6hs5trkk4v2QFJKNHMelph5BNh6iM5tnOU71gb6Dtr4,4464 29 | chef/tests/test_role.py,sha256=jXoIy3rhlFSTWZkyBq2D5WLQGgOA6viwC3_DkJmj0WE,1561 30 | chef/tests/test_rsa.py,sha256=Ja50W2EX2rqsMqmMIyx2zlnJj31gf-i_wQtGvZ1qV3Q,2461 31 | chef/tests/test_search.py,sha256=ydxMCBYwkudvc-joBJwdOUsxio1dffS4M_-aoWx_5K8,2531 32 | chef/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 33 | chef/utils/file.py,sha256=_LNAkKUH8-jWSQI-IY18JEoSmLVJY27JhCaSILUPHp8,184 34 | chef/utils/json.py,sha256=bwtjG91T30Rgfv89FbbUwI1jYJ6U1wkOweQtSKjW1DM,701 35 | /tmp/tmp8cR5IK/lib/python/PyChef-0.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 36 | chef/data_bag.pyc,, 37 | chef/fabric.pyc,, 38 | chef/client.pyc,, 39 | chef/search.pyc,, 40 | chef/tests/test_environment.pyc,, 41 | chef/auth.pyc,, 42 | chef/utils/__init__.pyc,, 43 | chef/__init__.pyc,, 44 | chef/acl.pyc,, 45 | chef/role.pyc,, 46 | chef/tests/test_api.pyc,, 47 | chef/tests/test_data_bag.pyc,, 48 | chef/permissions.pyc,, 49 | chef/tests/test_client.pyc,, 50 | chef/api.pyc,, 51 | chef/environment.pyc,, 52 | chef/tests/test_rsa.pyc,, 53 | chef/node.pyc,, 54 | chef/rsa.pyc,, 55 | chef/utils/file.pyc,, 56 | chef/tests/test_node.pyc,, 57 | chef/exceptions.pyc,, 58 | chef/tests/test_role.pyc,, 59 | chef/tests/test_fabric.pyc,, 60 | chef/base.pyc,, 61 | chef/tests/test_search.pyc,, 62 | chef/tests/__init__.pyc,, 63 | chef/utils/json.pyc,, 64 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/mbcharsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | import sys 31 | from . import constants 32 | from .charsetprober import CharSetProber 33 | 34 | 35 | class MultiByteCharSetProber(CharSetProber): 36 | def __init__(self): 37 | CharSetProber.__init__(self) 38 | self._mDistributionAnalyzer = None 39 | self._mCodingSM = None 40 | self._mLastChar = [0, 0] 41 | 42 | def reset(self): 43 | CharSetProber.reset(self) 44 | if self._mCodingSM: 45 | self._mCodingSM.reset() 46 | if self._mDistributionAnalyzer: 47 | self._mDistributionAnalyzer.reset() 48 | self._mLastChar = [0, 0] 49 | 50 | def get_charset_name(self): 51 | pass 52 | 53 | def feed(self, aBuf): 54 | aLen = len(aBuf) 55 | for i in range(0, aLen): 56 | codingState = self._mCodingSM.next_state(aBuf[i]) 57 | if codingState == constants.eError: 58 | if constants._debug: 59 | sys.stderr.write(self.get_charset_name() 60 | + ' prober hit error at byte ' + str(i) 61 | + '\n') 62 | self._mState = constants.eNotMe 63 | break 64 | elif codingState == constants.eItsMe: 65 | self._mState = constants.eFoundIt 66 | break 67 | elif codingState == constants.eStart: 68 | charLen = self._mCodingSM.get_current_charlen() 69 | if i == 0: 70 | self._mLastChar[1] = aBuf[0] 71 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 72 | else: 73 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 74 | charLen) 75 | 76 | self._mLastChar[0] = aBuf[aLen - 1] 77 | 78 | if self.get_state() == constants.eDetecting: 79 | if (self._mDistributionAnalyzer.got_enough_data() and 80 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 81 | self._mState = constants.eFoundIt 82 | 83 | return self.get_state() 84 | 85 | def get_confidence(self): 86 | return self._mDistributionAnalyzer.get_confidence() 87 | -------------------------------------------------------------------------------- /lambda/main_test.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file 4 | # except in compliance with the License. A copy of the License is located at 5 | # 6 | # http://aws.amazon.com/apache2.0/ 7 | # 8 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" 9 | # BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations under the License. 11 | """ 12 | Unit Tests for chef_node_cleanup Lambda function 13 | """ 14 | from botocore.exceptions import ClientError 15 | from mock import MagicMock, patch 16 | from main import log_event 17 | from main import get_instance_id 18 | from main import get_pem 19 | from main import handle 20 | from aws_lambda_sample_events import SampleEvent 21 | from chef.exceptions import ChefServerNotFoundError 22 | 23 | def test_log_event(): 24 | """ 25 | Test the log_event function 26 | """ 27 | assert log_event 28 | 29 | def test_get_instance_id(): 30 | """ 31 | Test the get_instance_id function with valid event 32 | """ 33 | event = {'detail': {'instance-id': 'i-abcde123'}} 34 | assert get_instance_id(event) == 'i-abcde123' 35 | 36 | def test_get_instance_id_with_invalid_event(): 37 | """ 38 | Test the get_instance_id function with invalid event 39 | """ 40 | event = {} 41 | assert get_instance_id(event) is False 42 | 43 | @patch('__builtin__.open') 44 | @patch('boto3.client') 45 | def test_get_pem(mock_client, mock_open): 46 | """ 47 | Test the get_pem function with valid data 48 | """ 49 | kms = MagicMock() 50 | mock_client.return_value = kms 51 | 52 | mock_open.return_value.__enter__ = lambda s: s 53 | mock_open.return_value.__exit__ = MagicMock() 54 | mock_open.return_value.read.return_value = 'blah' 55 | 56 | decrypted_blob = {'Plaintext': 'super_secret_key'} 57 | kms.decrypt.return_value = decrypted_blob 58 | assert get_pem() == 'super_secret_key' 59 | 60 | @patch('boto3.client') 61 | def test_get_pem_with_boto_failure(mock_client): 62 | """ 63 | Test the get_pem function when a boto exception occurs 64 | """ 65 | kms = MagicMock() 66 | mock_client.return_value = kms 67 | err_msg = { 68 | 'Error': { 69 | 'Code': 400, 70 | 'Message': 'Boom!' 71 | } 72 | } 73 | kms.decrypt.side_effect = ClientError(err_msg, 'Test') 74 | assert get_pem() is False 75 | 76 | @patch('chef.Client') 77 | @patch('chef.Node') 78 | @patch('chef.Search') 79 | @patch('chef.ChefAPI') 80 | def test_handle(mock_chefapi, mock_search, mock_node, mock_client): 81 | """ 82 | Tests the handle function with no errors and valid input 83 | """ 84 | cloudwatch = SampleEvent('cloudwatch_events') 85 | node = MagicMock() 86 | mock_search.return_value = node 87 | mock_node.delete.return_value = True 88 | mock_client.delete.return_value = True 89 | assert handle(cloudwatch.event, 'blah') is True 90 | 91 | @patch('chef.Search') 92 | @patch('chef.ChefAPI') 93 | def test_handle_with_chefservernotfounderror_on_search(mock_chefapi, mock_search): 94 | """ 95 | Tests the handle function with ChefServerNotFoundError on search 96 | """ 97 | cloudwatch = SampleEvent('cloudwatch_events') 98 | mock_search.side_effect = ChefServerNotFoundError('boom') 99 | assert handle(cloudwatch.event, 'blah') is False 100 | -------------------------------------------------------------------------------- /lambda/requests/status_codes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .structures import LookupDict 4 | 5 | _codes = { 6 | 7 | # Informational. 8 | 100: ('continue',), 9 | 101: ('switching_protocols',), 10 | 102: ('processing',), 11 | 103: ('checkpoint',), 12 | 122: ('uri_too_long', 'request_uri_too_long'), 13 | 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 14 | 201: ('created',), 15 | 202: ('accepted',), 16 | 203: ('non_authoritative_info', 'non_authoritative_information'), 17 | 204: ('no_content',), 18 | 205: ('reset_content', 'reset'), 19 | 206: ('partial_content', 'partial'), 20 | 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 21 | 208: ('already_reported',), 22 | 226: ('im_used',), 23 | 24 | # Redirection. 25 | 300: ('multiple_choices',), 26 | 301: ('moved_permanently', 'moved', '\\o-'), 27 | 302: ('found',), 28 | 303: ('see_other', 'other'), 29 | 304: ('not_modified',), 30 | 305: ('use_proxy',), 31 | 306: ('switch_proxy',), 32 | 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 33 | 308: ('permanent_redirect', 34 | 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 35 | 36 | # Client Error. 37 | 400: ('bad_request', 'bad'), 38 | 401: ('unauthorized',), 39 | 402: ('payment_required', 'payment'), 40 | 403: ('forbidden',), 41 | 404: ('not_found', '-o-'), 42 | 405: ('method_not_allowed', 'not_allowed'), 43 | 406: ('not_acceptable',), 44 | 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 45 | 408: ('request_timeout', 'timeout'), 46 | 409: ('conflict',), 47 | 410: ('gone',), 48 | 411: ('length_required',), 49 | 412: ('precondition_failed', 'precondition'), 50 | 413: ('request_entity_too_large',), 51 | 414: ('request_uri_too_large',), 52 | 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 53 | 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 54 | 417: ('expectation_failed',), 55 | 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 56 | 421: ('misdirected_request',), 57 | 422: ('unprocessable_entity', 'unprocessable'), 58 | 423: ('locked',), 59 | 424: ('failed_dependency', 'dependency'), 60 | 425: ('unordered_collection', 'unordered'), 61 | 426: ('upgrade_required', 'upgrade'), 62 | 428: ('precondition_required', 'precondition'), 63 | 429: ('too_many_requests', 'too_many'), 64 | 431: ('header_fields_too_large', 'fields_too_large'), 65 | 444: ('no_response', 'none'), 66 | 449: ('retry_with', 'retry'), 67 | 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 68 | 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 69 | 499: ('client_closed_request',), 70 | 71 | # Server Error. 72 | 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 73 | 501: ('not_implemented',), 74 | 502: ('bad_gateway',), 75 | 503: ('service_unavailable', 'unavailable'), 76 | 504: ('gateway_timeout',), 77 | 505: ('http_version_not_supported', 'http_version'), 78 | 506: ('variant_also_negotiates',), 79 | 507: ('insufficient_storage',), 80 | 509: ('bandwidth_limit_exceeded', 'bandwidth'), 81 | 510: ('not_extended',), 82 | 511: ('network_authentication_required', 'network_auth', 'network_authentication'), 83 | } 84 | 85 | codes = LookupDict(name='status_codes') 86 | 87 | for code, titles in _codes.items(): 88 | for title in titles: 89 | setattr(codes, title, code) 90 | if not title.startswith('\\'): 91 | setattr(codes, title.upper(), code) 92 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/util/connection.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import socket 3 | try: 4 | from select import poll, POLLIN 5 | except ImportError: # `poll` doesn't exist on OSX and other platforms 6 | poll = False 7 | try: 8 | from select import select 9 | except ImportError: # `select` doesn't exist on AppEngine. 10 | select = False 11 | 12 | 13 | def is_connection_dropped(conn): # Platform-specific 14 | """ 15 | Returns True if the connection is dropped and should be closed. 16 | 17 | :param conn: 18 | :class:`httplib.HTTPConnection` object. 19 | 20 | Note: For platforms like AppEngine, this will always return ``False`` to 21 | let the platform handle connection recycling transparently for us. 22 | """ 23 | sock = getattr(conn, 'sock', False) 24 | if sock is False: # Platform-specific: AppEngine 25 | return False 26 | if sock is None: # Connection already closed (such as by httplib). 27 | return True 28 | 29 | if not poll: 30 | if not select: # Platform-specific: AppEngine 31 | return False 32 | 33 | try: 34 | return select([sock], [], [], 0.0)[0] 35 | except socket.error: 36 | return True 37 | 38 | # This version is better on platforms that support it. 39 | p = poll() 40 | p.register(sock, POLLIN) 41 | for (fno, ev) in p.poll(0.0): 42 | if fno == sock.fileno(): 43 | # Either data is buffered (bad), or the connection is dropped. 44 | return True 45 | 46 | 47 | # This function is copied from socket.py in the Python 2.7 standard 48 | # library test suite. Added to its signature is only `socket_options`. 49 | def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, 50 | source_address=None, socket_options=None): 51 | """Connect to *address* and return the socket object. 52 | 53 | Convenience function. Connect to *address* (a 2-tuple ``(host, 54 | port)``) and return the socket object. Passing the optional 55 | *timeout* parameter will set the timeout on the socket instance 56 | before attempting to connect. If no *timeout* is supplied, the 57 | global default timeout setting returned by :func:`getdefaulttimeout` 58 | is used. If *source_address* is set it must be a tuple of (host, port) 59 | for the socket to bind as a source address before making the connection. 60 | An host of '' or port 0 tells the OS to use the default. 61 | """ 62 | 63 | host, port = address 64 | if host.startswith('['): 65 | host = host.strip('[]') 66 | err = None 67 | for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): 68 | af, socktype, proto, canonname, sa = res 69 | sock = None 70 | try: 71 | sock = socket.socket(af, socktype, proto) 72 | 73 | # If provided, set socket level options before connecting. 74 | # This is the only addition urllib3 makes to this function. 75 | _set_socket_options(sock, socket_options) 76 | 77 | if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: 78 | sock.settimeout(timeout) 79 | if source_address: 80 | sock.bind(source_address) 81 | sock.connect(sa) 82 | return sock 83 | 84 | except socket.error as e: 85 | err = e 86 | if sock is not None: 87 | sock.close() 88 | sock = None 89 | 90 | if err is not None: 91 | raise err 92 | 93 | raise socket.error("getaddrinfo returns an empty list") 94 | 95 | 96 | def _set_socket_options(sock, options): 97 | if options is None: 98 | return 99 | 100 | for opt in options: 101 | sock.setsockopt(*opt) 102 | -------------------------------------------------------------------------------- /lambda/main.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file 4 | # except in compliance with the License. A copy of the License is located at 5 | # 6 | # http://aws.amazon.com/apache2.0/ 7 | # 8 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" 9 | # BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | # License for the specific language governing permissions and limitations under the License. 11 | """ 12 | Remove a node from Chef server when a termination event is received 13 | joshcb@amazon.com 14 | v1.2.0 15 | """ 16 | from __future__ import print_function 17 | import logging 18 | from base64 import b64decode 19 | from botocore.exceptions import ClientError 20 | import boto3 21 | import chef 22 | from chef.exceptions import ChefServerNotFoundError 23 | 24 | import local_config 25 | 26 | LOGGER = logging.getLogger() 27 | LOGGER.setLevel(logging.INFO) 28 | REGION= local_config.REGION 29 | CHEF_SERVER_URL = local_config.CHEF_SERVER_URL 30 | USERNAME = local_config.USERNAME 31 | VERIFY_SSL = local_config.VERIFY_SSL 32 | DEBUG = local_config.DEBUG 33 | 34 | def log_event(event): 35 | """Logs event information for debugging""" 36 | LOGGER.info("====================================================") 37 | LOGGER.info(event) 38 | LOGGER.info("====================================================") 39 | 40 | def get_instance_id(event): 41 | """Parses InstanceID from the event dict and gets the FQDN from EC2 API""" 42 | try: 43 | return event['detail']['instance-id'] 44 | except KeyError as err: 45 | LOGGER.error(err) 46 | return False 47 | 48 | def get_pem(): 49 | """Decrypt the Ciphertext Blob to get USERNAME's pem file""" 50 | try: 51 | with open('encrypted_pem.txt', 'r') as encrypted_pem: 52 | pem_file = encrypted_pem.read() 53 | 54 | kms = boto3.client('kms', region_name=REGION) 55 | return kms.decrypt(CiphertextBlob=b64decode(pem_file))['Plaintext'] 56 | except (IOError, ClientError, KeyError) as err: 57 | LOGGER.error(err) 58 | return False 59 | 60 | def handle(event, _context): 61 | """Lambda Handler""" 62 | log_event(event) 63 | 64 | # If you're using a self signed certificate change 65 | # the ssl_verify argument to False 66 | with chef.ChefAPI(CHEF_SERVER_URL, get_pem(), USERNAME, ssl_verify=VERIFY_SSL): 67 | instance_id = get_instance_id(event) 68 | try: 69 | search = chef.Search('node', 'ec2_instance_id:' + instance_id) 70 | except ChefServerNotFoundError as err: 71 | LOGGER.error(err) 72 | return False 73 | 74 | if len(search) != 0: 75 | for instance in search: 76 | node = chef.Node(instance.object.name) 77 | client = chef.Client(instance.object.name) 78 | try: 79 | LOGGER.info('About to delete the node named - ' + node.name) 80 | LOGGER.info('About to delete the client named - ' + client.name) 81 | if not DEBUG: 82 | node.delete() 83 | LOGGER.info('===Node Delete: SUCCESS===') 84 | client.delete() 85 | LOGGER.info('===Client Delete: SUCCESS===') 86 | else: 87 | LOGGER.info('Would have deleted the node named - ' + node.name + ' here, but we are in DEBUG mode') 88 | LOGGER.info('Would have deleted the client named - ' + client.name + ' here, but we are in DEBUG mode') 89 | return True 90 | except ChefServerNotFoundError as err: 91 | LOGGER.error(err) 92 | return False 93 | else: 94 | LOGGER.info('=Instance does not appear to be Chef Server managed.=') 95 | return True 96 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/eucjpprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | import sys 29 | from . import constants 30 | from .mbcharsetprober import MultiByteCharSetProber 31 | from .codingstatemachine import CodingStateMachine 32 | from .chardistribution import EUCJPDistributionAnalysis 33 | from .jpcntx import EUCJPContextAnalysis 34 | from .mbcssm import EUCJPSMModel 35 | 36 | 37 | class EUCJPProber(MultiByteCharSetProber): 38 | def __init__(self): 39 | MultiByteCharSetProber.__init__(self) 40 | self._mCodingSM = CodingStateMachine(EUCJPSMModel) 41 | self._mDistributionAnalyzer = EUCJPDistributionAnalysis() 42 | self._mContextAnalyzer = EUCJPContextAnalysis() 43 | self.reset() 44 | 45 | def reset(self): 46 | MultiByteCharSetProber.reset(self) 47 | self._mContextAnalyzer.reset() 48 | 49 | def get_charset_name(self): 50 | return "EUC-JP" 51 | 52 | def feed(self, aBuf): 53 | aLen = len(aBuf) 54 | for i in range(0, aLen): 55 | # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte 56 | codingState = self._mCodingSM.next_state(aBuf[i]) 57 | if codingState == constants.eError: 58 | if constants._debug: 59 | sys.stderr.write(self.get_charset_name() 60 | + ' prober hit error at byte ' + str(i) 61 | + '\n') 62 | self._mState = constants.eNotMe 63 | break 64 | elif codingState == constants.eItsMe: 65 | self._mState = constants.eFoundIt 66 | break 67 | elif codingState == constants.eStart: 68 | charLen = self._mCodingSM.get_current_charlen() 69 | if i == 0: 70 | self._mLastChar[1] = aBuf[0] 71 | self._mContextAnalyzer.feed(self._mLastChar, charLen) 72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 73 | else: 74 | self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen) 75 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 76 | charLen) 77 | 78 | self._mLastChar[0] = aBuf[aLen - 1] 79 | 80 | if self.get_state() == constants.eDetecting: 81 | if (self._mContextAnalyzer.got_enough_data() and 82 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 83 | self._mState = constants.eFoundIt 84 | 85 | return self.get_state() 86 | 87 | def get_confidence(self): 88 | contxtCf = self._mContextAnalyzer.get_confidence() 89 | distribCf = self._mDistributionAnalyzer.get_confidence() 90 | return max(contxtCf, distribCf) 91 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/sjisprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | import sys 29 | from .mbcharsetprober import MultiByteCharSetProber 30 | from .codingstatemachine import CodingStateMachine 31 | from .chardistribution import SJISDistributionAnalysis 32 | from .jpcntx import SJISContextAnalysis 33 | from .mbcssm import SJISSMModel 34 | from . import constants 35 | 36 | 37 | class SJISProber(MultiByteCharSetProber): 38 | def __init__(self): 39 | MultiByteCharSetProber.__init__(self) 40 | self._mCodingSM = CodingStateMachine(SJISSMModel) 41 | self._mDistributionAnalyzer = SJISDistributionAnalysis() 42 | self._mContextAnalyzer = SJISContextAnalysis() 43 | self.reset() 44 | 45 | def reset(self): 46 | MultiByteCharSetProber.reset(self) 47 | self._mContextAnalyzer.reset() 48 | 49 | def get_charset_name(self): 50 | return self._mContextAnalyzer.get_charset_name() 51 | 52 | def feed(self, aBuf): 53 | aLen = len(aBuf) 54 | for i in range(0, aLen): 55 | codingState = self._mCodingSM.next_state(aBuf[i]) 56 | if codingState == constants.eError: 57 | if constants._debug: 58 | sys.stderr.write(self.get_charset_name() 59 | + ' prober hit error at byte ' + str(i) 60 | + '\n') 61 | self._mState = constants.eNotMe 62 | break 63 | elif codingState == constants.eItsMe: 64 | self._mState = constants.eFoundIt 65 | break 66 | elif codingState == constants.eStart: 67 | charLen = self._mCodingSM.get_current_charlen() 68 | if i == 0: 69 | self._mLastChar[1] = aBuf[0] 70 | self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:], 71 | charLen) 72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 73 | else: 74 | self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3 75 | - charLen], charLen) 76 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 77 | charLen) 78 | 79 | self._mLastChar[0] = aBuf[aLen - 1] 80 | 81 | if self.get_state() == constants.eDetecting: 82 | if (self._mContextAnalyzer.got_enough_data() and 83 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 84 | self._mState = constants.eFoundIt 85 | 86 | return self.get_state() 87 | 88 | def get_confidence(self): 89 | contxtCf = self._mContextAnalyzer.get_confidence() 90 | distribCf = self._mDistributionAnalyzer.get_confidence() 91 | return max(contxtCf, distribCf) 92 | -------------------------------------------------------------------------------- /lambda/chef/search.py: -------------------------------------------------------------------------------- 1 | import six 2 | import collections 3 | import copy 4 | import six.moves.urllib.parse 5 | 6 | from chef.api import ChefAPI 7 | from chef.base import ChefQuery, ChefObject 8 | 9 | class SearchRow(dict): 10 | """A single row in a search result.""" 11 | 12 | def __init__(self, row, api): 13 | super(SearchRow, self).__init__(row) 14 | self.api = api 15 | self._object = None 16 | 17 | @property 18 | def object(self): 19 | if self._object is None: 20 | # Decode Chef class name 21 | chef_class = self.get('json_class', '') 22 | if chef_class.startswith('Chef::'): 23 | chef_class = chef_class[6:] 24 | if chef_class == 'ApiClient': 25 | chef_class = 'Client' # Special case since I don't match the Ruby name. 26 | cls = ChefObject.types.get(chef_class.lower()) 27 | if not cls: 28 | raise ValueError('Unknown class %s'%chef_class) 29 | self._object = cls.from_search(self, api=self.api) 30 | return self._object 31 | 32 | 33 | class Search(collections.Sequence): 34 | """A search of the Chef index. 35 | 36 | The only required argument is the index name to search (eg. node, role, etc). 37 | The second, optional argument can be any Solr search query, with the same semantics 38 | as Chef. 39 | 40 | Example:: 41 | 42 | for row in Search('node', 'roles:app'): 43 | print row['roles'] 44 | print row.object.name 45 | 46 | .. versionadded:: 0.1 47 | """ 48 | 49 | url = '/search' 50 | 51 | def __init__(self, index, q='*:*', rows=1000, start=0, api=None): 52 | self.name = index 53 | self.api = api or ChefAPI.get_global() 54 | self._args = dict(q=q, rows=rows, start=start) 55 | self.url = self.__class__.url + '/' + self.name + '?' + six.moves.urllib.parse.urlencode(self._args) 56 | 57 | @property 58 | def data(self): 59 | if not hasattr(self, '_data'): 60 | self._data = self.api[self.url] 61 | return self._data 62 | 63 | @property 64 | def total(self): 65 | return self.data['total'] 66 | 67 | def query(self, query): 68 | args = copy.copy(self._args) 69 | args['q'] = query 70 | return self.__class__(self.name, api=self.api, **args) 71 | 72 | def rows(self, rows): 73 | args = copy.copy(self._args) 74 | args['rows'] = rows 75 | return self.__class__(self.name, api=self.api, **args) 76 | 77 | def start(self, start): 78 | args = copy.copy(self._args) 79 | args['start'] = start 80 | return self.__class__(self.name, api=self.api, **args) 81 | 82 | def __len__(self): 83 | return len(self.data['rows']) 84 | 85 | def __getitem__(self, value): 86 | if isinstance(value, slice): 87 | if value.step is not None and value.step != 1: 88 | raise ValueError('Cannot use a step other than 1') 89 | return self.start(self._args['start']+value.start).rows(value.stop-value.start) 90 | if isinstance(value, six.string_types): 91 | return self[self.index(value)] 92 | row_value = self.data['rows'][value] 93 | # Check for null rows, just in case 94 | if row_value is None: 95 | return None 96 | return SearchRow(row_value, self.api) 97 | 98 | def __contains__(self, name): 99 | for row in self: 100 | if row.object.name == name: 101 | return True 102 | return False 103 | 104 | def index(self, name): 105 | for i, row in enumerate(self): 106 | if row.object.name == name: 107 | return i 108 | raise ValueError('%s not in search'%name) 109 | 110 | def __call__(self, query): 111 | return self.query(query) 112 | 113 | @classmethod 114 | def list(cls, api=None): 115 | api = api or ChefAPI.get_global() 116 | names = [name for name, url in six.iteritems(api[cls.url])] 117 | return ChefQuery(cls, names, api) 118 | -------------------------------------------------------------------------------- /lambda/chef/data_bag.py: -------------------------------------------------------------------------------- 1 | import six 2 | import abc 3 | import collections 4 | 5 | from chef.api import ChefAPI 6 | from chef.base import ChefObject, ChefQuery, ChefObjectMeta 7 | from chef.exceptions import ChefError, ChefServerNotFoundError 8 | 9 | class DataBagMeta(ChefObjectMeta, abc.ABCMeta): 10 | """A metaclass to allow DataBag to use multiple inheritance.""" 11 | 12 | 13 | class DataBag(six.with_metaclass(DataBagMeta, ChefObject, ChefQuery)): 14 | """A Chef data bag object. 15 | 16 | Data bag items are available via the mapping API. Evaluation works in the 17 | same way as :class:`ChefQuery`, so requesting only the names will not 18 | cause the items to be loaded:: 19 | 20 | bag = DataBag('versions') 21 | item = bag['web'] 22 | for name, item in six.iteritems(bag): 23 | print item['qa_version'] 24 | """ 25 | 26 | url = '/data' 27 | 28 | def _populate(self, data): 29 | self.names = list(data.keys()) 30 | 31 | def obj_class(self, name, api): 32 | return DataBagItem(self, name, api=api) 33 | 34 | 35 | class DataBagItem(six.with_metaclass(DataBagMeta, ChefObject, collections.MutableMapping)): 36 | """A Chef data bag item object. 37 | 38 | Data bag items act as normal dicts and can contain arbitrary data. 39 | """ 40 | 41 | url = '/data' 42 | attributes = { 43 | 'raw_data': dict, 44 | } 45 | 46 | def __init__(self, bag, name, api=None, skip_load=False): 47 | self._bag = bag 48 | super(DataBagItem, self).__init__(str(bag)+'/'+name, api=api, skip_load=skip_load) 49 | self.name = name 50 | 51 | @property 52 | def bag(self): 53 | """The :class:`DataBag` this item is a member of.""" 54 | if not isinstance(self._bag, DataBag): 55 | self._bag = DataBag(self._bag, api=self.api) 56 | return self._bag 57 | 58 | @classmethod 59 | def from_search(cls, data, api): 60 | bag = data.get('data_bag') 61 | if not bag: 62 | raise ChefError('No data_bag key in data bag item information') 63 | name = data.get('name') 64 | if not name: 65 | raise ChefError('No name key in the data bag item information') 66 | item = name[len('data_bag_item_' + bag + '_'):] 67 | obj = cls(bag, item, api=api, skip_load=True) 68 | obj.exists = True 69 | obj._populate(data) 70 | return obj 71 | 72 | def _populate(self, data): 73 | if 'json_class' in data: 74 | self.raw_data = data['raw_data'] 75 | else: 76 | self.raw_data = data 77 | 78 | def __len__(self): 79 | return len(self.raw_data) 80 | 81 | def __iter__(self): 82 | return iter(self.raw_data) 83 | 84 | def __getitem__(self, key): 85 | return self.raw_data[key] 86 | 87 | def __setitem__(self, key, value): 88 | self.raw_data[key] = value 89 | 90 | def __delitem__(self, key): 91 | del self.raw_data[key] 92 | 93 | @classmethod 94 | def create(cls, bag, name, api=None, **kwargs): 95 | """Create a new data bag item. Pass the initial value for any keys as 96 | keyword arguments.""" 97 | api = api or ChefAPI.get_global() 98 | obj = cls(bag, name, api, skip_load=True) 99 | for key, value in six.iteritems(kwargs): 100 | obj[key] = value 101 | obj['id'] = name 102 | api.api_request('POST', cls.url+'/'+str(bag), data=obj.raw_data) 103 | if isinstance(bag, DataBag) and name not in bag.names: 104 | # Mutate the bag in-place if possible, so it will return the new 105 | # item instantly 106 | bag.names.append(name) 107 | return obj 108 | 109 | def save(self, api=None): 110 | """Save this object to the server. If the object does not exist it 111 | will be created. 112 | """ 113 | api = api or self.api 114 | self['id'] = self.name 115 | try: 116 | api.api_request('PUT', self.url, data=self.raw_data) 117 | except ChefServerNotFoundError as e: 118 | api.api_request('POST', self.__class__.url+'/'+str(self._bag), data=self.raw_data) 119 | -------------------------------------------------------------------------------- /lambda/requests/packages/chardet/charsetgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | import sys 30 | from .charsetprober import CharSetProber 31 | 32 | 33 | class CharSetGroupProber(CharSetProber): 34 | def __init__(self): 35 | CharSetProber.__init__(self) 36 | self._mActiveNum = 0 37 | self._mProbers = [] 38 | self._mBestGuessProber = None 39 | 40 | def reset(self): 41 | CharSetProber.reset(self) 42 | self._mActiveNum = 0 43 | for prober in self._mProbers: 44 | if prober: 45 | prober.reset() 46 | prober.active = True 47 | self._mActiveNum += 1 48 | self._mBestGuessProber = None 49 | 50 | def get_charset_name(self): 51 | if not self._mBestGuessProber: 52 | self.get_confidence() 53 | if not self._mBestGuessProber: 54 | return None 55 | # self._mBestGuessProber = self._mProbers[0] 56 | return self._mBestGuessProber.get_charset_name() 57 | 58 | def feed(self, aBuf): 59 | for prober in self._mProbers: 60 | if not prober: 61 | continue 62 | if not prober.active: 63 | continue 64 | st = prober.feed(aBuf) 65 | if not st: 66 | continue 67 | if st == constants.eFoundIt: 68 | self._mBestGuessProber = prober 69 | return self.get_state() 70 | elif st == constants.eNotMe: 71 | prober.active = False 72 | self._mActiveNum -= 1 73 | if self._mActiveNum <= 0: 74 | self._mState = constants.eNotMe 75 | return self.get_state() 76 | return self.get_state() 77 | 78 | def get_confidence(self): 79 | st = self.get_state() 80 | if st == constants.eFoundIt: 81 | return 0.99 82 | elif st == constants.eNotMe: 83 | return 0.01 84 | bestConf = 0.0 85 | self._mBestGuessProber = None 86 | for prober in self._mProbers: 87 | if not prober: 88 | continue 89 | if not prober.active: 90 | if constants._debug: 91 | sys.stderr.write(prober.get_charset_name() 92 | + ' not active\n') 93 | continue 94 | cf = prober.get_confidence() 95 | if constants._debug: 96 | sys.stderr.write('%s confidence = %s\n' % 97 | (prober.get_charset_name(), cf)) 98 | if bestConf < cf: 99 | bestConf = cf 100 | self._mBestGuessProber = prober 101 | if not self._mBestGuessProber: 102 | return 0.0 103 | return bestConf 104 | # else: 105 | # self._mBestGuessProber = self._mProbers[0] 106 | # return self._mBestGuessProber.get_confidence() 107 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py: -------------------------------------------------------------------------------- 1 | """The match_hostname() function from Python 3.3.3, essential when using SSL.""" 2 | 3 | # Note: This file is under the PSF license as the code comes from the python 4 | # stdlib. http://docs.python.org/3/license.html 5 | 6 | import re 7 | 8 | __version__ = '3.4.0.2' 9 | 10 | class CertificateError(ValueError): 11 | pass 12 | 13 | 14 | def _dnsname_match(dn, hostname, max_wildcards=1): 15 | """Matching according to RFC 6125, section 6.4.3 16 | 17 | http://tools.ietf.org/html/rfc6125#section-6.4.3 18 | """ 19 | pats = [] 20 | if not dn: 21 | return False 22 | 23 | # Ported from python3-syntax: 24 | # leftmost, *remainder = dn.split(r'.') 25 | parts = dn.split(r'.') 26 | leftmost = parts[0] 27 | remainder = parts[1:] 28 | 29 | wildcards = leftmost.count('*') 30 | if wildcards > max_wildcards: 31 | # Issue #17980: avoid denials of service by refusing more 32 | # than one wildcard per fragment. A survey of established 33 | # policy among SSL implementations showed it to be a 34 | # reasonable choice. 35 | raise CertificateError( 36 | "too many wildcards in certificate DNS name: " + repr(dn)) 37 | 38 | # speed up common case w/o wildcards 39 | if not wildcards: 40 | return dn.lower() == hostname.lower() 41 | 42 | # RFC 6125, section 6.4.3, subitem 1. 43 | # The client SHOULD NOT attempt to match a presented identifier in which 44 | # the wildcard character comprises a label other than the left-most label. 45 | if leftmost == '*': 46 | # When '*' is a fragment by itself, it matches a non-empty dotless 47 | # fragment. 48 | pats.append('[^.]+') 49 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): 50 | # RFC 6125, section 6.4.3, subitem 3. 51 | # The client SHOULD NOT attempt to match a presented identifier 52 | # where the wildcard character is embedded within an A-label or 53 | # U-label of an internationalized domain name. 54 | pats.append(re.escape(leftmost)) 55 | else: 56 | # Otherwise, '*' matches any dotless string, e.g. www* 57 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) 58 | 59 | # add the remaining fragments, ignore any wildcards 60 | for frag in remainder: 61 | pats.append(re.escape(frag)) 62 | 63 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) 64 | return pat.match(hostname) 65 | 66 | 67 | def match_hostname(cert, hostname): 68 | """Verify that *cert* (in decoded format as returned by 69 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 70 | rules are followed, but IP addresses are not accepted for *hostname*. 71 | 72 | CertificateError is raised on failure. On success, the function 73 | returns nothing. 74 | """ 75 | if not cert: 76 | raise ValueError("empty or no certificate") 77 | dnsnames = [] 78 | san = cert.get('subjectAltName', ()) 79 | for key, value in san: 80 | if key == 'DNS': 81 | if _dnsname_match(value, hostname): 82 | return 83 | dnsnames.append(value) 84 | if not dnsnames: 85 | # The subject is only checked when there is no dNSName entry 86 | # in subjectAltName 87 | for sub in cert.get('subject', ()): 88 | for key, value in sub: 89 | # XXX according to RFC 2818, the most specific Common Name 90 | # must be used. 91 | if key == 'commonName': 92 | if _dnsname_match(value, hostname): 93 | return 94 | dnsnames.append(value) 95 | if len(dnsnames) > 1: 96 | raise CertificateError("hostname %r " 97 | "doesn't match either of %s" 98 | % (hostname, ', '.join(map(repr, dnsnames)))) 99 | elif len(dnsnames) == 1: 100 | raise CertificateError("hostname %r " 101 | "doesn't match %r" 102 | % (hostname, dnsnames[0])) 103 | else: 104 | raise CertificateError("no appropriate commonName or " 105 | "subjectAltName fields were found") 106 | -------------------------------------------------------------------------------- /lambda/setuptools/command/install_lib.py: -------------------------------------------------------------------------------- 1 | import os 2 | import imp 3 | from itertools import product, starmap 4 | import distutils.command.install_lib as orig 5 | 6 | class install_lib(orig.install_lib): 7 | """Don't add compiled flags to filenames of non-Python files""" 8 | 9 | def run(self): 10 | self.build() 11 | outfiles = self.install() 12 | if outfiles is not None: 13 | # always compile, in case we have any extension stubs to deal with 14 | self.byte_compile(outfiles) 15 | 16 | def get_exclusions(self): 17 | """ 18 | Return a collections.Sized collections.Container of paths to be 19 | excluded for single_version_externally_managed installations. 20 | """ 21 | all_packages = ( 22 | pkg 23 | for ns_pkg in self._get_SVEM_NSPs() 24 | for pkg in self._all_packages(ns_pkg) 25 | ) 26 | 27 | excl_specs = product(all_packages, self._gen_exclusion_paths()) 28 | return set(starmap(self._exclude_pkg_path, excl_specs)) 29 | 30 | def _exclude_pkg_path(self, pkg, exclusion_path): 31 | """ 32 | Given a package name and exclusion path within that package, 33 | compute the full exclusion path. 34 | """ 35 | parts = pkg.split('.') + [exclusion_path] 36 | return os.path.join(self.install_dir, *parts) 37 | 38 | @staticmethod 39 | def _all_packages(pkg_name): 40 | """ 41 | >>> list(install_lib._all_packages('foo.bar.baz')) 42 | ['foo.bar.baz', 'foo.bar', 'foo'] 43 | """ 44 | while pkg_name: 45 | yield pkg_name 46 | pkg_name, sep, child = pkg_name.rpartition('.') 47 | 48 | def _get_SVEM_NSPs(self): 49 | """ 50 | Get namespace packages (list) but only for 51 | single_version_externally_managed installations and empty otherwise. 52 | """ 53 | # TODO: is it necessary to short-circuit here? i.e. what's the cost 54 | # if get_finalized_command is called even when namespace_packages is 55 | # False? 56 | if not self.distribution.namespace_packages: 57 | return [] 58 | 59 | install_cmd = self.get_finalized_command('install') 60 | svem = install_cmd.single_version_externally_managed 61 | 62 | return self.distribution.namespace_packages if svem else [] 63 | 64 | @staticmethod 65 | def _gen_exclusion_paths(): 66 | """ 67 | Generate file paths to be excluded for namespace packages (bytecode 68 | cache files). 69 | """ 70 | # always exclude the package module itself 71 | yield '__init__.py' 72 | 73 | yield '__init__.pyc' 74 | yield '__init__.pyo' 75 | 76 | if not hasattr(imp, 'get_tag'): 77 | return 78 | 79 | base = os.path.join('__pycache__', '__init__.' + imp.get_tag()) 80 | yield base + '.pyc' 81 | yield base + '.pyo' 82 | yield base + '.opt-1.pyc' 83 | yield base + '.opt-2.pyc' 84 | 85 | def copy_tree( 86 | self, infile, outfile, 87 | preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1 88 | ): 89 | assert preserve_mode and preserve_times and not preserve_symlinks 90 | exclude = self.get_exclusions() 91 | 92 | if not exclude: 93 | return orig.install_lib.copy_tree(self, infile, outfile) 94 | 95 | # Exclude namespace package __init__.py* files from the output 96 | 97 | from setuptools.archive_util import unpack_directory 98 | from distutils import log 99 | 100 | outfiles = [] 101 | 102 | def pf(src, dst): 103 | if dst in exclude: 104 | log.warn("Skipping installation of %s (namespace package)", 105 | dst) 106 | return False 107 | 108 | log.info("copying %s -> %s", src, os.path.dirname(dst)) 109 | outfiles.append(dst) 110 | return dst 111 | 112 | unpack_directory(infile, outfile, pf) 113 | return outfiles 114 | 115 | def get_outputs(self): 116 | outputs = orig.install_lib.get_outputs(self) 117 | exclude = self.get_exclusions() 118 | if exclude: 119 | return [f for f in outputs if f not in exclude] 120 | return outputs 121 | -------------------------------------------------------------------------------- /lambda/setuptools-20.1.1.dist-info/metadata.json: -------------------------------------------------------------------------------- 1 | {"generator": "bdist_wheel (0.26.0)", "summary": "Easily download, build, install, upgrade, and uninstall Python packages", "classifiers": ["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Archiving :: Packaging", "Topic :: System :: Systems Administration", "Topic :: Utilities"], "extensions": {"python.details": {"project_urls": {"Home": "https://bitbucket.org/pypa/setuptools"}, "contacts": [{"email": "distutils-sig@python.org", "name": "Python Packaging Authority", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}}, "python.exports": {"console_scripts": {"easy_install": "setuptools.command.easy_install:main", "easy_install-3.5": "setuptools.command.easy_install:main"}, "distutils.commands": {"alias": "setuptools.command.alias:alias", "bdist_egg": "setuptools.command.bdist_egg:bdist_egg", "bdist_rpm": "setuptools.command.bdist_rpm:bdist_rpm", "bdist_wininst": "setuptools.command.bdist_wininst:bdist_wininst", "build_ext": "setuptools.command.build_ext:build_ext", "build_py": "setuptools.command.build_py:build_py", "develop": "setuptools.command.develop:develop", "easy_install": "setuptools.command.easy_install:easy_install", "egg_info": "setuptools.command.egg_info:egg_info", "install": "setuptools.command.install:install", "install_egg_info": "setuptools.command.install_egg_info:install_egg_info", "install_lib": "setuptools.command.install_lib:install_lib", "install_scripts": "setuptools.command.install_scripts:install_scripts", "register": "setuptools.command.register:register", "rotate": "setuptools.command.rotate:rotate", "saveopts": "setuptools.command.saveopts:saveopts", "sdist": "setuptools.command.sdist:sdist", "setopt": "setuptools.command.setopt:setopt", "test": "setuptools.command.test:test", "upload": "setuptools.command.upload:upload", "upload_docs": "setuptools.command.upload_docs:upload_docs"}, "distutils.setup_keywords": {"convert_2to3_doctests": "setuptools.dist:assert_string_list", "dependency_links": "setuptools.dist:assert_string_list", "eager_resources": "setuptools.dist:assert_string_list", "entry_points": "setuptools.dist:check_entry_points", "exclude_package_data": "setuptools.dist:check_package_data", "extras_require": "setuptools.dist:check_extras", "include_package_data": "setuptools.dist:assert_bool", "install_requires": "setuptools.dist:check_requirements", "namespace_packages": "setuptools.dist:check_nsp", "package_data": "setuptools.dist:check_package_data", "packages": "setuptools.dist:check_packages", "setup_requires": "setuptools.dist:check_requirements", "test_loader": "setuptools.dist:check_importable", "test_runner": "setuptools.dist:check_importable", "test_suite": "setuptools.dist:check_test_suite", "tests_require": "setuptools.dist:check_requirements", "use_2to3": "setuptools.dist:assert_bool", "use_2to3_exclude_fixers": "setuptools.dist:assert_string_list", "use_2to3_fixers": "setuptools.dist:assert_string_list", "zip_safe": "setuptools.dist:assert_bool"}, "egg_info.writers": {"PKG-INFO": "setuptools.command.egg_info:write_pkg_info", "dependency_links.txt": "setuptools.command.egg_info:overwrite_arg", "depends.txt": "setuptools.command.egg_info:warn_depends_obsolete", "eager_resources.txt": "setuptools.command.egg_info:overwrite_arg", "entry_points.txt": "setuptools.command.egg_info:write_entries", "namespace_packages.txt": "setuptools.command.egg_info:overwrite_arg", "requires.txt": "setuptools.command.egg_info:write_requirements", "top_level.txt": "setuptools.command.egg_info:write_toplevel_names"}, "setuptools.installation": {"eggsecutable": "setuptools.command.easy_install:bootstrap"}}, "python.commands": {"wrap_console": {"easy_install": "setuptools.command.easy_install:main", "easy_install-3.5": "setuptools.command.easy_install:main"}}}, "keywords": ["CPAN", "PyPI", "distutils", "eggs", "package", "management"], "metadata_version": "2.0", "name": "setuptools", "extras": ["certs", "ssl"], "run_requires": [{"requires": ["certifi (==2015.11.20)"], "extra": "certs"}, {"requires": ["wincertstore (==0.2)"], "extra": "ssl", "environment": "sys_platform=='win32'"}], "version": "20.1.1", "test_requires": [{"requires": ["pytest (>=2.8)", "setuptools[ssl]"]}]} -------------------------------------------------------------------------------- /lambda/_markerlib/markers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Interpret PEP 345 environment markers. 3 | 4 | EXPR [in|==|!=|not in] EXPR [or|and] ... 5 | 6 | where EXPR belongs to any of those: 7 | 8 | python_version = '%s.%s' % (sys.version_info[0], sys.version_info[1]) 9 | python_full_version = sys.version.split()[0] 10 | os.name = os.name 11 | sys.platform = sys.platform 12 | platform.version = platform.version() 13 | platform.machine = platform.machine() 14 | platform.python_implementation = platform.python_implementation() 15 | a free string, like '2.6', or 'win32' 16 | """ 17 | 18 | __all__ = ['default_environment', 'compile', 'interpret'] 19 | 20 | import ast 21 | import os 22 | import platform 23 | import sys 24 | import weakref 25 | 26 | _builtin_compile = compile 27 | 28 | try: 29 | from platform import python_implementation 30 | except ImportError: 31 | if os.name == "java": 32 | # Jython 2.5 has ast module, but not platform.python_implementation() function. 33 | def python_implementation(): 34 | return "Jython" 35 | else: 36 | raise 37 | 38 | 39 | # restricted set of variables 40 | _VARS = {'sys.platform': sys.platform, 41 | 'python_version': '%s.%s' % sys.version_info[:2], 42 | # FIXME parsing sys.platform is not reliable, but there is no other 43 | # way to get e.g. 2.7.2+, and the PEP is defined with sys.version 44 | 'python_full_version': sys.version.split(' ', 1)[0], 45 | 'os.name': os.name, 46 | 'platform.version': platform.version(), 47 | 'platform.machine': platform.machine(), 48 | 'platform.python_implementation': python_implementation(), 49 | 'extra': None # wheel extension 50 | } 51 | 52 | for var in list(_VARS.keys()): 53 | if '.' in var: 54 | _VARS[var.replace('.', '_')] = _VARS[var] 55 | 56 | def default_environment(): 57 | """Return copy of default PEP 385 globals dictionary.""" 58 | return dict(_VARS) 59 | 60 | class ASTWhitelist(ast.NodeTransformer): 61 | def __init__(self, statement): 62 | self.statement = statement # for error messages 63 | 64 | ALLOWED = (ast.Compare, ast.BoolOp, ast.Attribute, ast.Name, ast.Load, ast.Str) 65 | # Bool operations 66 | ALLOWED += (ast.And, ast.Or) 67 | # Comparison operations 68 | ALLOWED += (ast.Eq, ast.Gt, ast.GtE, ast.In, ast.Is, ast.IsNot, ast.Lt, ast.LtE, ast.NotEq, ast.NotIn) 69 | 70 | def visit(self, node): 71 | """Ensure statement only contains allowed nodes.""" 72 | if not isinstance(node, self.ALLOWED): 73 | raise SyntaxError('Not allowed in environment markers.\n%s\n%s' % 74 | (self.statement, 75 | (' ' * node.col_offset) + '^')) 76 | return ast.NodeTransformer.visit(self, node) 77 | 78 | def visit_Attribute(self, node): 79 | """Flatten one level of attribute access.""" 80 | new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx) 81 | return ast.copy_location(new_node, node) 82 | 83 | def parse_marker(marker): 84 | tree = ast.parse(marker, mode='eval') 85 | new_tree = ASTWhitelist(marker).generic_visit(tree) 86 | return new_tree 87 | 88 | def compile_marker(parsed_marker): 89 | return _builtin_compile(parsed_marker, '', 'eval', 90 | dont_inherit=True) 91 | 92 | _cache = weakref.WeakValueDictionary() 93 | 94 | def compile(marker): 95 | """Return compiled marker as a function accepting an environment dict.""" 96 | try: 97 | return _cache[marker] 98 | except KeyError: 99 | pass 100 | if not marker.strip(): 101 | def marker_fn(environment=None, override=None): 102 | """""" 103 | return True 104 | else: 105 | compiled_marker = compile_marker(parse_marker(marker)) 106 | def marker_fn(environment=None, override=None): 107 | """override updates environment""" 108 | if override is None: 109 | override = {} 110 | if environment is None: 111 | environment = default_environment() 112 | environment.update(override) 113 | return eval(compiled_marker, environment) 114 | marker_fn.__doc__ = marker 115 | _cache[marker] = marker_fn 116 | return _cache[marker] 117 | 118 | def interpret(marker, environment=None): 119 | return compile(marker)(environment) 120 | -------------------------------------------------------------------------------- /lambda/setuptools/command/install_egg_info.py: -------------------------------------------------------------------------------- 1 | from distutils import log, dir_util 2 | import os 3 | 4 | from setuptools.extern.six.moves import map 5 | 6 | from setuptools import Command 7 | from setuptools.archive_util import unpack_archive 8 | import pkg_resources 9 | 10 | 11 | class install_egg_info(Command): 12 | """Install an .egg-info directory for the package""" 13 | 14 | description = "Install an .egg-info directory for the package" 15 | 16 | user_options = [ 17 | ('install-dir=', 'd', "directory to install to"), 18 | ] 19 | 20 | def initialize_options(self): 21 | self.install_dir = None 22 | 23 | def finalize_options(self): 24 | self.set_undefined_options('install_lib', 25 | ('install_dir', 'install_dir')) 26 | ei_cmd = self.get_finalized_command("egg_info") 27 | basename = pkg_resources.Distribution( 28 | None, None, ei_cmd.egg_name, ei_cmd.egg_version 29 | ).egg_name() + '.egg-info' 30 | self.source = ei_cmd.egg_info 31 | self.target = os.path.join(self.install_dir, basename) 32 | self.outputs = [] 33 | 34 | def run(self): 35 | self.run_command('egg_info') 36 | if os.path.isdir(self.target) and not os.path.islink(self.target): 37 | dir_util.remove_tree(self.target, dry_run=self.dry_run) 38 | elif os.path.exists(self.target): 39 | self.execute(os.unlink, (self.target,), "Removing " + self.target) 40 | if not self.dry_run: 41 | pkg_resources.ensure_directory(self.target) 42 | self.execute( 43 | self.copytree, (), "Copying %s to %s" % (self.source, self.target) 44 | ) 45 | self.install_namespaces() 46 | 47 | def get_outputs(self): 48 | return self.outputs 49 | 50 | def copytree(self): 51 | # Copy the .egg-info tree to site-packages 52 | def skimmer(src, dst): 53 | # filter out source-control directories; note that 'src' is always 54 | # a '/'-separated path, regardless of platform. 'dst' is a 55 | # platform-specific path. 56 | for skip in '.svn/', 'CVS/': 57 | if src.startswith(skip) or '/' + skip in src: 58 | return None 59 | self.outputs.append(dst) 60 | log.debug("Copying %s to %s", src, dst) 61 | return dst 62 | 63 | unpack_archive(self.source, self.target, skimmer) 64 | 65 | def install_namespaces(self): 66 | nsp = self._get_all_ns_packages() 67 | if not nsp: 68 | return 69 | filename, ext = os.path.splitext(self.target) 70 | filename += '-nspkg.pth' 71 | self.outputs.append(filename) 72 | log.info("Installing %s", filename) 73 | lines = map(self._gen_nspkg_line, nsp) 74 | 75 | if self.dry_run: 76 | # always generate the lines, even in dry run 77 | list(lines) 78 | return 79 | 80 | with open(filename, 'wt') as f: 81 | f.writelines(lines) 82 | 83 | _nspkg_tmpl = ( 84 | "import sys, types, os", 85 | "p = os.path.join(sys._getframe(1).f_locals['sitedir'], *%(pth)r)", 86 | "ie = os.path.exists(os.path.join(p,'__init__.py'))", 87 | "m = not ie and " 88 | "sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))", 89 | "mp = (m or []) and m.__dict__.setdefault('__path__',[])", 90 | "(p not in mp) and mp.append(p)", 91 | ) 92 | "lines for the namespace installer" 93 | 94 | _nspkg_tmpl_multi = ( 95 | 'm and setattr(sys.modules[%(parent)r], %(child)r, m)', 96 | ) 97 | "additional line(s) when a parent package is indicated" 98 | 99 | @classmethod 100 | def _gen_nspkg_line(cls, pkg): 101 | # ensure pkg is not a unicode string under Python 2.7 102 | pkg = str(pkg) 103 | pth = tuple(pkg.split('.')) 104 | tmpl_lines = cls._nspkg_tmpl 105 | parent, sep, child = pkg.rpartition('.') 106 | if parent: 107 | tmpl_lines += cls._nspkg_tmpl_multi 108 | return ';'.join(tmpl_lines) % locals() + '\n' 109 | 110 | def _get_all_ns_packages(self): 111 | """Return sorted list of all package namespaces""" 112 | nsp = set() 113 | for pkg in self.distribution.namespace_packages or []: 114 | pkg = pkg.split('.') 115 | while pkg: 116 | nsp.add('.'.join(pkg)) 117 | pkg.pop() 118 | return sorted(nsp) 119 | -------------------------------------------------------------------------------- /lambda/requests/packages/urllib3/contrib/ntlmpool.py: -------------------------------------------------------------------------------- 1 | """ 2 | NTLM authenticating pool, contributed by erikcederstran 3 | 4 | Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 5 | """ 6 | from __future__ import absolute_import 7 | 8 | try: 9 | from http.client import HTTPSConnection 10 | except ImportError: 11 | from httplib import HTTPSConnection 12 | from logging import getLogger 13 | from ntlm import ntlm 14 | 15 | from urllib3 import HTTPSConnectionPool 16 | 17 | 18 | log = getLogger(__name__) 19 | 20 | 21 | class NTLMConnectionPool(HTTPSConnectionPool): 22 | """ 23 | Implements an NTLM authentication version of an urllib3 connection pool 24 | """ 25 | 26 | scheme = 'https' 27 | 28 | def __init__(self, user, pw, authurl, *args, **kwargs): 29 | """ 30 | authurl is a random URL on the server that is protected by NTLM. 31 | user is the Windows user, probably in the DOMAIN\\username format. 32 | pw is the password for the user. 33 | """ 34 | super(NTLMConnectionPool, self).__init__(*args, **kwargs) 35 | self.authurl = authurl 36 | self.rawuser = user 37 | user_parts = user.split('\\', 1) 38 | self.domain = user_parts[0].upper() 39 | self.user = user_parts[1] 40 | self.pw = pw 41 | 42 | def _new_conn(self): 43 | # Performs the NTLM handshake that secures the connection. The socket 44 | # must be kept open while requests are performed. 45 | self.num_connections += 1 46 | log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s', 47 | self.num_connections, self.host, self.authurl) 48 | 49 | headers = {} 50 | headers['Connection'] = 'Keep-Alive' 51 | req_header = 'Authorization' 52 | resp_header = 'www-authenticate' 53 | 54 | conn = HTTPSConnection(host=self.host, port=self.port) 55 | 56 | # Send negotiation message 57 | headers[req_header] = ( 58 | 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) 59 | log.debug('Request headers: %s', headers) 60 | conn.request('GET', self.authurl, None, headers) 61 | res = conn.getresponse() 62 | reshdr = dict(res.getheaders()) 63 | log.debug('Response status: %s %s', res.status, res.reason) 64 | log.debug('Response headers: %s', reshdr) 65 | log.debug('Response data: %s [...]', res.read(100)) 66 | 67 | # Remove the reference to the socket, so that it can not be closed by 68 | # the response object (we want to keep the socket open) 69 | res.fp = None 70 | 71 | # Server should respond with a challenge message 72 | auth_header_values = reshdr[resp_header].split(', ') 73 | auth_header_value = None 74 | for s in auth_header_values: 75 | if s[:5] == 'NTLM ': 76 | auth_header_value = s[5:] 77 | if auth_header_value is None: 78 | raise Exception('Unexpected %s response header: %s' % 79 | (resp_header, reshdr[resp_header])) 80 | 81 | # Send authentication message 82 | ServerChallenge, NegotiateFlags = \ 83 | ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) 84 | auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, 85 | self.user, 86 | self.domain, 87 | self.pw, 88 | NegotiateFlags) 89 | headers[req_header] = 'NTLM %s' % auth_msg 90 | log.debug('Request headers: %s', headers) 91 | conn.request('GET', self.authurl, None, headers) 92 | res = conn.getresponse() 93 | log.debug('Response status: %s %s', res.status, res.reason) 94 | log.debug('Response headers: %s', dict(res.getheaders())) 95 | log.debug('Response data: %s [...]', res.read()[:100]) 96 | if res.status != 200: 97 | if res.status == 401: 98 | raise Exception('Server rejected request: wrong ' 99 | 'username or password') 100 | raise Exception('Wrong server response: %s %s' % 101 | (res.status, res.reason)) 102 | 103 | res.fp = None 104 | log.debug('Connection established') 105 | return conn 106 | 107 | def urlopen(self, method, url, body=None, headers=None, retries=3, 108 | redirect=True, assert_same_host=True): 109 | if headers is None: 110 | headers = {} 111 | headers['Connection'] = 'Keep-Alive' 112 | return super(NTLMConnectionPool, self).urlopen(method, url, body, 113 | headers, retries, 114 | redirect, 115 | assert_same_host) 116 | --------------------------------------------------------------------------------