cloud-init-cherrypy/main.py

76 lines
2.2 KiB
Python

import os
import sys
import cherrypy
from cherrypy.lib.static import serve_file
import json
import socket
import configparser
PATH = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
config.read("config.ini")
user_data_filename = config["app"].get("user_data", "sample_file.txt")
meta_data_filename = config["app"].get("meta_data", "meta_data_extra.txt")
class MainApp:
@cherrypy.expose
def user_data(self):
hostname = socket.gethostbyaddr(str(cherrypy.request.remote.ip))[0]
filename = user_data_filename
filepath = os.path.join(PATH, "data", hostname, "user-data", filename)
return serve_file(filepath, "application/x-download", "attachment")
@cherrypy.expose
@cherrypy.tools.json_out()
def meta_data(self):
host_info = socket.gethostbyaddr(str(cherrypy.request.remote.ip))
hostname = host_info[0]
data = {"instance-id": hostname.split(".")[0], "local-hostname": hostname}
folder = os.path.join(PATH, "data", hostname, "metadata_extra")
if os.path.exists(folder):
with open(os.path.join(folder, meta_data_filename), "r") as f:
lines = f.readlines()
for line in lines:
ls = list(map(lambda k: k.strip(), line.split(":")))
data[ls[0]] = ls[1]
return data
@cherrypy.expose
def finished(self, data):
hostname = socket.gethostbyaddr(str(cherrypy.request.remote.ip))[0]
folder = os.path.join(PATH, "data", hostname, "metadata_extra")
if not os.path.exists(folder):
os.makedirs(folder)
with open(os.path.join(folder, meta_data_filename), "w") as f:
f.write(data)
ROOT = MainApp()
if __name__ == "__main__":
cherrypy.server.socket_host = config["server"].get("server_host", "127.0.0.1")
cherrypy.server.socket_port = config["server"].getint("server_port", 8081)
ENGINE = cherrypy.engine
cherrypy.tree.mount(ROOT)
if hasattr(ENGINE, "signal_handler"):
ENGINE.signal_handler.subscribe()
if hasattr(ENGINE, "console_control_handler"):
ENGINE.console_control_handler.subscribe()
try:
ENGINE.start()
except Exception:
sys.exit(1)
else:
ENGINE.block()