Sunday, November 17, 2019

Exposing system journal to HTTP REST endpoint.

Journal log naturally printing a lot of useful information, ranging from system kernel, critical, information, and etc log. If I would able to expose those log files onto a HTTP rest endpoint, then I could easily query all of the status of server without login to it. How cool, isn't it? Using the Flask and exposing any port(e.g. 5577).

from flask import Response
from flask import Flask
import json
import subprocess
import socket

app = Flask(__name__)

@app.route("/journal.json", methods = ['GET'])
def get_journal():
  journal_dict = {}
  cmd = "sudo journalctl -k -S today -o json"
  (output, _) = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, encoding='utf-8').communicate()
  json_list = [line.strip() for line in output.split("\n") if len(line) != 0]
  journal_dict["journal"] = json_list
  js = json.dumps(journal_dict)
  resp = Response(js, status=200, mimetype='application/json')
  resp.headers['Link'] = 'http://{}'.format(socket.gethostname())
  return resp

def main(port=5577):
  app.run(host='0.0.0.0', port=port)

if __name__ == '__main__':
  main()

No comments: