Created
April 16, 2020 21:08
-
-
Save iamevn/aacc4e37393577838a9962f2e04feb08 to your computer and use it in GitHub Desktop.
cloud function to generate basic status page for my server, it's so bad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import googleapiclient.discovery | |
from google.cloud import logging | |
from google.cloud.logging import DESCENDING | |
def get_instance_info(project, zone, instance): | |
compute = googleapiclient.discovery.build('compute', 'v1') | |
instances = compute.instances() | |
instanceInfo = instances.get(project=project, zone=zone, instance=instance).execute() | |
return instanceInfo | |
def get_logs(log_name, limit=50): | |
# path_prefix = 'projects/basement-minecraft/logs/' | |
client = logging.Client() | |
logger = client.logger(log_name) | |
for n, entry in enumerate(logger.list_entries(order_by=DESCENDING)): | |
if n > limit: | |
break | |
yield entry.timestamp, entry.payload | |
def cleanup_logs(logs): | |
for log in logs: | |
log = re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?', '', log) | |
# 01:45:45.054 | |
match = re.search(r'\[\d\d:\d\d:\d\d(\.\d\d\d\])?', log) | |
if match: | |
yield log[match.start():] | |
else: | |
yield log | |
def main(request): | |
project = 'basement-minecraft' | |
zone = 'us-west1-b' | |
instance = 'instance-1' | |
instanceInfo = get_instance_info(project, zone, instance) | |
links = [ | |
'<a href=https://us-central1-basement-minecraft.cloudfunctions.net/boot>Start</a>', | |
#'<a href=https://us-central1-basement-minecraft.cloudfunctions.net/reboot>Reboot</a>', | |
#'<a href=https://us-central1-basement-minecraft.cloudfunctions.net/stop>Stop</a>', | |
] | |
# monlogs = get_logs('mcmonitor', 100) | |
comimclogs = list(get_logs('minecraft', 100)) | |
mctimestamps = [ts.isoformat(' ', 'seconds') for ts, log in comimclogs] | |
mclogs = [log for ts, log in comimclogs] | |
mclogs = cleanup_logs(mclogs) | |
resp = [ | |
'<div id=status>Basement MC server status: ' + instanceInfo['status'] + '</div>', | |
'', | |
'<div id=links>' + '<br>'.join(links) + '</div>', | |
'<hr>', | |
'Recent (since ' + (mctimestamps[0] if mctimestamps else 'UNDEFINED') + ') server logs (most recent at top):', | |
'', | |
'<div id=mclogs>' + '<br>'.join(mclogs) + '</div>', | |
] | |
return '<br>'.join(resp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment