Skip to content

Instantly share code, notes, and snippets.

@chuwy
Last active September 29, 2015 15:02
Show Gist options
  • Save chuwy/ba8c27b558c02c509352 to your computer and use it in GitHub Desktop.
Save chuwy/ba8c27b558c02c509352 to your computer and use it in GitHub Desktop.
Stupid EC2 instance info mock
#!/usr/bin/python3
"""
Stupid EC2 meta data instance mock
Save this file as server.py
>>> python server.py 0.0.0.0 8001
serving on 0.0.0.0:8001
or simply
>>> python server.py
Serving on localhost:8000
You can use this to test GET and POST methods.
"""
from http import server
import socketserver
import sys
import time
if len(sys.argv) > 2:
PORT = int(sys.argv[2])
I = sys.argv[1]
elif len(sys.argv) > 1:
PORT = int(sys.argv[1])
I = ""
else:
PORT = 8000
I = ""
root = {
'2013-10-15': None,
'2014-11-15': None,
'latest': {
'dynamic': None,
'meta-data': {
'ami-id': None,
'ami-launch-index': None,
'ami-manifest-path': None,
'block-device-mapping/': {},
'hostname': None,
'instance-action': None,
'instance-id': None,
'instance-type': None,
'local-hostname': None,
'local-ipv4': None,
'mac': '0a:f5:99:89:bb:37',
'metrics/': {},
'network/': {'interfaces/': {'macs': '0a:f5:99:89:bb:37'}},
'placement/': {},
'profile': None,
'public-hostname': None,
'public-ipv4': None,
'public-keys/': {},
'reservation-id': None,
'security-groups': 'launch-wizard-1',
'services/': {}
},
'user-data': None
}
}
def get_content(path, response=(404, root,)):
"""Get content of dict by it's path"""
if path == '/':
return 200, root
path = path.lstrip('/')
if '/' not in path[:-1]:
try:
content = response[1][path]
code = 200
except KeyError:
try:
response[1][path + '/']
content = ''
code = 301
except KeyError:
content = ''
code = 404
return code, content
else:
paths = path.split('/')
cur_path = paths[0]
try:
body = response[1][cur_path] if cur_path in response[1] else response[1][cur_path + '/']
return get_content('/'.join(paths[1:]), (200, body))
except KeyError:
return 404, ''
def get_page(path):
"""Return text content of path"""
code, body = get_content(path)
if type(body) == dict:
page = [p for (p, s) in body.items()]
page.sort()
return code, '\n'.join(page)
else:
return code, body
class ServerHandler(server.SimpleHTTPRequestHandler):
def do_GET(self):
code, page = get_page(self.path)
self.log_request(code)
self.send_response_only(code, None)
self.send_header('Content-type', 'text/plain')
self.send_header('Accept-Ranges', 'bytes')
self.send_header('ETag', '"3376246526"')
self.send_header('Last-Modified', time.strftime('%a, %d %b %Y %H:%M:%S GMT'))
self.send_header('Connection', 'close')
self.send_header('Server', 'EC2ws')
self.end_headers()
self.wfile.write(bytearray(page, 'utf-8'))
if __name__ == '__main__':
Handler = ServerHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("Serving at: http://%(interface)s:%(port)s" % dict(interface=I or "localhost", port=PORT))
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Interrupted")
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment