cloud-init-cherrypy/main.py
Peter Surda bfc4dbecb6
Fixes
- Also delete sample data
2021-02-10 17:13:31 +01:00

102 lines
2.8 KiB
Python

import os
import sys
import cherrypy
from cherrypy.lib.static import serve_file
import yaml
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:
def _init_ip(self):
"""
Get remote IP
"""
try:
self.remoteip = cherrypy.request.headers.get(
'X-Real-Ip',
cherrypy.request.remote.ip
)
except:
self.remoteip = cherrypy.request.remote.ip
try:
self.hostinfo = socket.gethostbyaddr(self.remoteip)
except socket.herror:
self.hostinfo = ('localhost', )
@cherrypy.expose
def user_data(self):
"""
Serves a static file
"""
self._init_ip()
filepath = os.path.join(PATH, "data", self.hostinfo[0],
user_data_filename)
if not os.path.exists(filepath):
filepath = os.path.join(PATH, "data", user_data_filename)
return serve_file(filepath, "application/x-download", "attachment")
@cherrypy.expose
def meta_data(self):
"""
Return meta-data in YAML
"""
self._init_ip()
hostname =self.hostinfo[0]
data = {"instance-id": hostname.split(".")[0], "local-hostname": hostname}
filepath = os.path.join(PATH, "data", hostname, meta_data_filename)
if os.path.exists(filepath):
with open(filepath, "r") as f:
line = f.readlines()[0]
ls = list(map(lambda k: k.strip(), line.split(":")))
data[ls[0]] = ls[1]
return yaml.dump(data)
@cherrypy.expose
def finished(self, data):
"""
Saves additional meta-data
:param data: meta-data to be added
"""
self._init_ip()
folder = os.path.join(PATH, "data", self.hostinfo[0])
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()