NewsBlur-viq/utils/tlnb.py

164 lines
5.2 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python
import argparse
import json
import os
2015-06-01 17:50:06 -07:00
import re
import select
import subprocess
import sys
import time
from requests.exceptions import ConnectionError
2024-04-24 09:43:56 -04:00
sys.path.insert(0, "/srv/newsblur")
os.environ["DJANGO_SETTINGS_MODULE"] = "newsblur_web.settings"
2024-04-24 09:43:56 -04:00
NEWSBLUR_USERNAME = "nb"
IGNORE_HOSTS = [
2024-04-24 09:43:56 -04:00
"app-push",
]
2022-02-08 15:32:43 -05:00
# Use this to count the number of times each user shows up in the logs. Good for finding abusive accounts.
# tail -n20000 logs/newsblur.log | sed 's/\x1b\[[0-9;]*m//g' | sed -En 's/.*?[0-9]s\] \[([a-zA-Z0-9]+\*?)\].*/\1/p' | sort | uniq -c | sort
2024-04-24 09:43:56 -04:00
def main(hostnames=None, roles=None, command=None, path=None):
delay = 1
2024-04-24 09:43:56 -04:00
hosts = subprocess.check_output(["ansible-inventory", "--list"])
if not hosts:
print(" ***> Could not load ansible-inventory!")
return
hosts = json.loads(hosts)
if not path:
path = "/srv/newsblur/logs/newsblur.log"
if not command:
command = "tail -f"
2024-04-24 09:43:56 -04:00
if hostnames in ["app", "task", "push"]:
roles = hostnames
hostnames = None
2024-04-24 09:43:56 -04:00
if hostnames:
roles = hosts
2024-04-24 09:43:56 -04:00
hostnames = validate_hostnames(hostnames.split(","), hosts)
2021-03-17 20:53:25 -04:00
if not roles:
2024-04-24 09:43:56 -04:00
roles = ["app"]
2021-07-12 11:46:35 -04:00
if not isinstance(roles, list):
roles = [roles]
2021-03-17 20:53:25 -04:00
while True:
try:
if hostnames:
streams = []
found = set()
for host in hostnames:
follow_host(roles[0], streams, found, host, command, path)
print(" --- Loading %s %s Log Tails ---" % (len(streams), hostnames))
else:
streams = create_streams_for_roles(hosts, roles, command=command, path=path)
print(" --- Loading %s %s Log Tails ---" % (len(streams), roles))
read_streams(streams)
2016-02-04 21:07:28 -08:00
# except UnicodeDecodeError: # unexpected end of data
# print " --- Lost connections - Retrying... ---"
# time.sleep(1)
# continue
except ConnectionError:
2020-06-19 02:27:48 -04:00
print(" --- Retrying in %s seconds... ---" % delay)
time.sleep(delay)
delay += 1
continue
except KeyboardInterrupt:
2020-06-19 02:27:48 -04:00
print(" --- End of Logging ---")
break
2024-04-24 09:43:56 -04:00
def validate_hostnames(hostnames, hosts):
validated_hostnames = []
for hostname in hostnames:
2024-04-24 09:43:56 -04:00
if hostname in hosts["_meta"]["hostvars"]:
validated_hostnames.append(hostname)
else:
print(f"Hostname {hostname} not found in inventory.")
print(f"Validated hostnames: {validated_hostnames}")
return validated_hostnames
2024-04-24 09:43:56 -04:00
2021-03-17 20:53:25 -04:00
def create_streams_for_roles(hosts, roles, command=None, path=None):
streams = list()
found = set()
2021-03-17 20:53:25 -04:00
for role in roles:
if role in hosts:
2024-04-24 09:43:56 -04:00
for hostname in hosts[role]["hosts"]:
if any(h in hostname for h in IGNORE_HOSTS) and role != "push":
continue
follow_host(hosts, streams, found, hostname, command, path)
2021-03-17 20:53:25 -04:00
else:
host = role
2021-07-12 11:46:35 -04:00
follow_host(hosts, streams, found, host, command)
2015-06-01 17:50:06 -07:00
return streams
2024-04-24 09:43:56 -04:00
def follow_host(hosts, streams, found, hostname, command=None, path=None):
2015-06-01 17:50:06 -07:00
if isinstance(hostname, dict):
2024-04-24 09:43:56 -04:00
address = hostname["address"]
hostname = hostname["name"]
elif ":" in hostname:
hostname, address = hostname.split(":", 1)
2015-06-01 17:50:06 -07:00
elif isinstance(hostname, tuple):
hostname, address = hostname[0], hostname[1]
else:
2024-04-24 09:43:56 -04:00
address = hosts["_meta"]["hostvars"][hostname]["ansible_host"]
print(" ---> Following %s \t[%s]" % (hostname, address))
2024-04-24 09:43:56 -04:00
if hostname in found:
return
s = subprocess.Popen(
[
"ssh",
"-l",
NEWSBLUR_USERNAME,
"-i",
os.path.expanduser("/srv/secrets-newsblur/keys/docker.key"),
address,
"%s %s" % (command, path),
],
stdout=subprocess.PIPE,
)
2015-06-01 17:50:06 -07:00
s.name = hostname
streams.append(s)
found.add(hostname)
2024-04-24 09:43:56 -04:00
def read_streams(streams):
while True:
2024-04-24 09:43:56 -04:00
r, _, _ = select.select([stream.stdout.fileno() for stream in streams], [], [])
for fileno in r:
for stream in streams:
if stream.stdout.fileno() != fileno:
continue
data = os.read(fileno, 4096)
if not data:
streams.remove(stream)
break
2016-11-02 22:07:10 -07:00
try:
combination_message = "[%-15s] %s" % (stream.name[:15], data.decode())
2016-11-02 22:07:10 -07:00
except UnicodeDecodeError:
continue
sys.stdout.write(combination_message)
sys.stdout.flush()
break
2024-04-24 09:43:56 -04:00
if __name__ == "__main__":
2024-04-24 09:43:56 -04:00
parser = argparse.ArgumentParser(description="Tail logs from multiple hosts.")
parser.add_argument("hostnames", help="Comma-separated list of hostnames", nargs="?")
parser.add_argument("roles", help="Comma-separated list of roles", nargs="?")
parser.add_argument("--command", help="Command to run on the remote host")
parser.add_argument("--path", help="Path to the log file")
args = parser.parse_args()
main(args.hostnames, command=args.command, path=args.path)