logger.sh: refactor log.py to bash script

This commit is contained in:
Dict Xiong 2022-11-27 00:49:00 +08:00
parent 8c289c8c3c
commit 45d1d1de69
4 changed files with 102 additions and 67 deletions

View File

@ -169,6 +169,7 @@ dfs()
echo 'Done. Please open a new shell to see the changes.'
;;
log ) "$DOTFILES/tools/common.sh" "post_log" "INFO" "dfs" "$2" ;;
beacon ) "$DOTFILES/tools/common.sh" "post_beacon" "$2" ;;
* ) echo "unknown command \"$1\". available: update, force-update, version, reset, cd, log" ;;
esac
}

View File

@ -148,7 +148,12 @@ ask_for_Yn()
post_log()
{
python3 "${DOTFILES}/tools/log.py" "[$1] $2: $3"
"${DOTFILES}/tools/logger.sh" "log" "[$1][$2] $3"
}
post_beacon()
{
"${DOTFILES}/tools/logger.sh" "beacon" "$1"
}
get_os_type() {

View File

@ -1,66 +0,0 @@
#!/usr/bin/env python3
import os, uuid, socket, argparse, logging
namespace = uuid.UUID("cc23b903-1993-44eb-9c90-48bd841eeac3")
logging.basicConfig(level=logging.INFO, format="[%(filename)s:%(lineno)d][%(levelname)s] %(message)s")
try:
import requests
except ImportError:
logging.critical("Please install requests module")
exit(1)
def get_uuid_raw() -> str:
possible_uuid_files = [
"/var/lib/dbus/machine-id",
"/etc/machine-id",
os.path.join(os.path.expanduser('~'), ".config/dotfiles/uuid"),
]
for i in possible_uuid_files:
if os.path.exists(i):
with open(i, "r") as f:
return f.read().strip()
if not os.path.exists(os.path.dirname(possible_uuid_files[-1])):
os.makedirs(os.path.dirname(possible_uuid_files[-1]))
with open(possible_uuid_files[-1], 'w') as f:
ans = str(uuid.uuid4())
f.write(ans)
return ans
def get_uuid() -> str:
return str(uuid.uuid5(namespace, get_uuid_raw()))
def post_log(url:str, hostname:str, uuid:str, content:str):
ans = requests.post(url, params={"hostname": hostname, "uuid": uuid}, data=content)
return ans
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="post log to server")
parser.add_argument("-u", "--url", help="url to post to", default="https://api.beardic.cn/post-log")
parser.add_argument("content")
args = parser.parse_args()
url = args.url
content = args.content
hostname = socket.gethostname()
uuid = get_uuid()
content=content.strip()
if not content:
logging.error("empty log content")
exit(0)
resp = post_log(url, hostname, uuid, content)
if resp.status_code == 200:
logging.info("200 ok")
exit(0)
elif resp.status_code == 403:
logging.warning("403 forbidden")
logging.info("you may need to register your hostname and uuid")
logging.info(f"hostname: {hostname}, uuid: {uuid}")
exit(0)
else:
logging.critical("unknown error")
logging.error(f"{resp.status_code}: {resp.text}")
exit(1)

95
tools/logger.sh Executable file
View File

@ -0,0 +1,95 @@
#!/bin/bash
set -e
THIS_DIR=$( cd "$( dirname "${BASH_SOURCE[0]:-${(%):-%x}}" )" && pwd )
source "$THIS_DIR/common.sh"
if [[ -x $(command -v hostname) ]]; then
hostname=$(hostname)
elif [[ -x $(command -v uname) ]]; then
hostname=$(uname -n)
elif [[ -x $(command -v hostnamectl) ]]; then
hostname=$(hostnamectl --static)
elif [[ -n "$HOSTNAME" ]]; then
hostname=$HOSTNAME
elif [[ -f /proc/sys/kernel/hostname ]]; then
hostname=$(cat /proc/sys/kernel/hostname)
elif [[ -f /etc/hostname ]]; then
hostname=$(cat /etc/hostname)
else
fmt_fatal "unable to get hostname"
fi
init_uuid()
{
local raw_uuid
if [[ -f /var/lib/dbus/machine-id ]]; then
raw_uuid=$(cat /var/lib/dbus/machine-id)
elif [[ -f /etc/machine-id ]]; then
raw_uuid=$(cat /etc/machine-id)
elif [[ -f ~/.config/dotfiles/uuid ]]; then
raw_uuid=$(cat ~/.config/dotfiles/uuid)
else
mkdir -p ~/.config/dotfiles
raw_uuid=$(uuidgen)
echo "$raw_uuid" > ~/.config/dotfiles/uuid
fi
uuid=$(uuidgen -n "cc23b903-1993-44eb-9c90-48bd841eeac3" -s -N "$raw_uuid")
}
post_beacon()
{
local beacon_type=$1
if [[ -z "$beacon_type" ]]; then
fmt_fatal "beacon type is required"
fi
exec 9>&1
resp=$(curl -sSL -X POST "https://api.beardic.cn/post-beacon?hostname=$hostname&beacon=$beacon_type" | tee >(cat - >&9))
(grep -q "200" <<< "$resp") || fmt_fatal "error posting beacon"
}
post_log()
{
local log_content=$1
if [[ -z "$log_content" ]]; then
fmt_fatal "log content is required"
fi
init_uuid
exec 9>&1
resp=$(curl -sSL -X POST -H "Content-Type: text/plain" -d "$1" "https://api.beardic.cn/post-log?hostname=$hostname&uuid=$uuid" | tee >(cat - >&9))
if ! grep -q "200" <<< "$resp"; then
if grep -q "403" <<< "$resp"; then
fmt_error "error posting log: authentification failed"
fmt_info "try to register you hostname and uuid"
fmt_info "hostname: $hostname"
fmt_info "uuid: $uuid"
else
fmt_fatal "error posting log"
fi
fi
}
print_help()
{
fmt_info "usage: $0 <beacon|log> <beacon_type|log_content>"
}
if [[ $# != 2 ]]; then
print_help
exit 1
fi
case "$1" in
-h|--help)
fmt_info "usage: $0 <beacon|log> <beacon_type|log_content>"
;;
beacon)
post_beacon "$2"
;;
log)
post_log "$2"
;;
*)
fmt_fatal "invalid argument"
;;
esac