freelance-project-34-market.../dotfiles/.local/bin/commands
2022-01-17 15:13:11 +03:00

211 lines
6.4 KiB
Python
Executable File

#!/usr/bin/python3
import traceback
import time
import sys
import subprocess
import logging
msg = None
def player_metadata():
for k in range(20):
try:
time.sleep(1.0)
return subprocess.check_output(['playerctl', 'metadata']).decode('utf-8').strip()
except:
continue
def eternal_oom():
import signal
import os
import re
import time
import io
import pandas
import numpy
import subprocess
import pprint
self_pid = os.getpid()
while True:
with io.BytesIO(subprocess.check_output('ps -e -o pid,rss,user', shell=True)) as f:
t1 = pandas.read_csv(f, sep='\s+', header=0)
with io.BytesIO(subprocess.check_output('free', shell=True)) as f:
t2 = pandas.read_csv(f, sep='\s+')
t5 = subprocess.check_output('ps -e -o pid,args', shell=True).decode('utf-8').splitlines()
t6 = pandas.DataFrame(
[
re.compile(r'^\s*(\d+)\s(.*)$').search(o).groups() for o in t5[1:]
],
columns=tuple(t5[0].split())
).assign(PID=lambda x: x.PID.values.astype(numpy.int32))
t7 = pandas.merge(t1, t6, on='PID')
t8 = t7.sort_values(by=['RSS'], ascending=False).assign(used=lambda x: (x.RSS / 1024).cumsum())
t11 = numpy.where(
numpy.stack([
t8.PID.values != self_pid,
t8.COMMAND.str.contains('freelancer').isin([False])
], axis=0).prod(0)
)[0]
t9 = t8.iloc[t11]
t4 = lambda : os.kill(t9.PID.iloc[0], signal.SIGKILL)
t10 = lambda : t2.loc['Mem:', 'used'] > 3 * 1024 * 1024
if t10():
pprint.pprint(['Killing', t9.iloc[0], t2, t9])
t4()
time.sleep(1)
def resilient_vlc(stream=None):
if stream is None:
streams_path = os.path.join(
os.environ['CACHE_PATH'],
'resilient-vlc-streams.json'
)
if os.path.exists(streams_path):
with io.open(
streams_path,
'r'
) as f:
stream = json.load(f)
else:
raise RuntimeError(
'not found, %s' % streams_path
)
if isinstance(stream, str):
stream = [stream]
if len(stream) == 0:
raise RuntimeError('no streams')
import subprocess
import time
while True:
print('new start')
with subprocess.Popen([
'cvlc', '--verbose', '2', *stream,
], stderr=subprocess.PIPE) as p:
while p.returncode is None:
t1 = p.stderr.readline().decode('utf-8')
if len(t1) > 0:
print(t1)
if not all([
o in t1
for o in [
'prefetch stream error',
'terror',
'main interface error',
]
]) and any([
o in t1
for o in [
'pulse audio output debug: underflow'
]
]):
print('shit')
p.kill()
while True:
try:
t2 = p.wait(timeout=1)
print(t2)
break
except:
print('shit')
pass
time.sleep(1.0)
def status():
return ' | '.join([
subprocess.check_output(o, shell=True).decode('utf-8').strip()
for o in [
r'''
free -h | \
grep -P Mem: | grep -Po '[\w\.\d]+' | tail -n +2 | head -n 3 | xargs echo -n;
''',
r'''
sensors | \
grep -Po '[\\\+\\\-\\\w][^\\\s]+C ' | head -n 5 | xargs echo -n
''',
r'''
ssh nartes@pizcool3070 free -h | \
grep -P Mem: | grep -Po '[\w\.\d]+' | tail -n +2 | head -n 3 | xargs echo -n;
''',
r'''
ssh nartes@pizcool3070 sensors | \
grep -Po '[\\\+\\\-\.0-9]+\s+C ' | head -n 1
''',
r'''
date +'%Y-%m-%d %l:%M:%S %p';
''',
]
]).replace('\n\r', '')
try:
if sys.argv[1] == 'media-play-pause':
subprocess.check_call(['playerctl', 'play-pause'])
msg = player_metadata()
elif sys.argv[1] == 'media-next':
subprocess.check_call(['playerctl', 'next'])
msg = player_metadata()
elif sys.argv[1] == 'media-prev':
subprocess.check_call(['playerctl', 'previous'])
msg = player_metadata()
elif sys.argv[1] == 'media-lower-volume':
subprocess.check_call([
'pactl',
'set-sink-volume',
'@DEFAULT_SINK@',
'-5%'
])
msg = subprocess.check_output([
'pactl',
'get-sink-volume',
'@DEFAULT_SINK@'
]).decode('utf-8').strip()
elif sys.argv[1] == 'media-raise-volume':
subprocess.check_call([
'pactl',
'set-sink-volume',
'@DEFAULT_SINK@',
'+5%'
])
msg = subprocess.check_output([
'pactl',
'get-sink-volume',
'@DEFAULT_SINK@'
]).decode('utf-8').strip()
elif sys.argv[1] == 'status':
sys.stdout.write(status())
sys.stdout.flush()
elif sys.argv[1] == 'http-server':
subprocess.check_call(r'''
sudo docker run \
-p 80:80 \
-u root \
-it --entrypoint=/bin/bash \
-v $PWD:/app:ro \
nginx:latest \
-c 'echo "server{listen 80; root /app; location / {autoindex on;}}" > /etc/nginx/conf.d/default.conf; nginx -g "daemon off;"'
''', shell=True)
elif sys.argv[1] == 'wl-screenshot':
subprocess.check_call(r'''
grim -g "$(slurp)" - | wl-copy
''', shell=True)
elif sys.argv[1] == 'eternal-oom':
eternal_oom()
elif sys.argv[1] == 'resilient-vlc':
resilient_vlc(sys.argv[2:])
else:
raise NotImplementedError
except:
msg = 'not implemented\n%s' % traceback.format_exc()
logging.error(msg)
if not msg is None:
subprocess.check_call([
'notify-send',
'commands',
msg[-128:]
])