Mini Shell
#!/opt/imh-python/bin/python3.9
# vim: set ts=4 sw=4 expandtab syntax=python:
"""
ngxutil.util
Utility Functions
@author J. Hipps <jacobh@inmotionhosting.com>
"""
import re
import json
import logging
import traceback
logger = logging.getLogger('ngxutil')
def get_domain_owner(domain):
"""
Determine owner & vhost of @domain
"""
if domain == '*':
return {'owner': "nobody", 'vhost': "*"}
try:
with open("/etc/userdatadomains.json", 'r') as f:
udd = json.load(f)
except Exception as e:
logger.error("Failed to load /etc/userdatadomains.json: %s", str(e))
return None
ddata = udd.get(domain)
if not ddata:
logger.error("Domain '%s' not found on server", domain)
return None
return {'owner': ddata[0], 'vhost': ddata[3]}
def format_uptime(usec):
"""
Format uptime @usec as duration string
"""
oday = int(usec / 86400)
ohour = int((usec - (oday * 86400)) / 3600)
omin = int((usec - (oday * 86400) - (ohour * 3600)) / 60)
osec = float(usec) - float(oday * 86400) - float(ohour * 3600) - float(omin * 60)
ostr = "{:01d}d {:02d}:{:02d}:{:02.02f}".format(oday, ohour, omin, osec)
return ostr
def format_size(insize, rate=False, bits=False):
"""
format human-readable file size and xfer rates
"""
onx = float(abs(insize))
for u in ['B', 'K', 'M', 'G', 'T', 'P']:
if onx < 1024.0:
tunit = u
break
onx /= 1024.0
suffix = ""
if tunit != 'B': suffix = "iB"
if rate:
if bits:
suffix = "bps"
onx *= 8.0
else:
suffix += "/sec"
if tunit == 'B':
ostr = "%3d %s%s" % (onx, tunit, suffix)
else:
ostr = "%3.01f %s%s" % (onx, tunit, suffix)
return ostr
def mkpct(ival, tot):
"""
Make value/percent string
"""
try:
po = "{:d} ({:3.01f}%)".format(ival, (float(ival) / float(tot)) * 100.0)
except:
po = "0 (-.-%)"
return po
def strcolor(color, instr):
"""
ANSI colorify a string @instr with @color (foreground)
"""
cdex = {
'': '\x1b[0m',
'black': '\x1b[30m',
'red': '\x1b[31m',
'green': '\x1b[32m',
'yellow': '\x1b[33m',
'blue': '\x1b[34m',
'magenta': '\x1b[35m',
'cyan': '\x1b[36m',
'white': '\x1b[37m',
}
return "{}{}{}".format(cdex.get(color.lower(), ''), instr, cdex[''])
def strip_colors(instr):
"""
Strip ANSI color codes from input @str
"""
return re.sub(r'\x1b\[[0-9;]*m', '', instr)
def excepthook(etype, evalue, etraceback):
"""
Default exception hook
"""
logger.critical("Unhandled exception caught:\n%s",
'\n'.join(traceback.format_exception(etype, evalue, etraceback)))
Zerion Mini Shell 1.0