]> git.immae.eu Git - perso/Immae/Projets/Puppet.git/blob - modules/role/templates/cryptoportfolio/api_logger.py.erb
wait for journal rather than polling
[perso/Immae/Projets/Puppet.git] / modules / role / templates / cryptoportfolio / api_logger.py.erb
1 #!/usr/bin/python
2
3 import time
4 import urllib3
5 import json
6 from systemd import journal
7
8 urllib3.disable_warnings()
9 http = urllib3.PoolManager()
10
11 webhook_url = "<%= @slack_logger %>"
12 webhook_username = "<%= @slack_logger_username %>"
13 webhook_icon = "https://git.immae.eu/releases/logger.png"
14
15 def send_to_discord(message):
16 def send_chunk(chunk):
17 data = {
18 "avatar_url": webhook_icon,
19 "username": webhook_username,
20 "content": "```\n{}\n```".format(chunk),
21 }
22 encoded = json.dumps(data).encode('utf-8')
23
24 r = http.request("POST", webhook_url,
25 headers={'Content-Type': 'application/json'},
26 body=encoded)
27 if r.status == 429:
28 b = json.loads(r.data)
29 time.sleep(b["retry_after"] / 900)
30 r = http.request("POST", webhook_url,
31 headers={'Content-Type': 'application/json'},
32 body=encoded)
33 assert r.status < 299
34
35 chunk = ""
36 for line in message.split("\n"):
37 if len(line) + len(chunk) > 2000 - 17:
38 send_chunk(chunk)
39 chunk = line
40 else:
41 chunk += "\n" + line
42 send_chunk(chunk)
43
44 j = journal.Reader()
45 j.add_match(_SYSTEMD_UNIT="cryptoportfolio-app.service")
46 j.seek_tail()
47 list(j)
48
49 while True:
50 lines = [entry["MESSAGE"] for entry in list(j)]
51 if len(lines) > 0:
52 send_to_discord("\n".join(lines))
53 j.wait()