#!/usr/bin/env python3 import json import os import signal import socket import subprocess import sys import websocket ws = websocket.WebSocket() p_list = {} ptable = {} ptable["audio"] = [ "/home/nginx/scripts-snowmix/working-udp-audio.sh"] ptable["video"] = [ "/home/nginx/scripts-snowmix/working-udp-video.sh", "1", "0" ] ptable["rtmp"] = [ "/home/nginx/scripts-snowmix/stream.sh"] log_list = {} DEBUG = False def log(s): if DEBUG == False: return print(s) def conn(target): global ws if ws is None: ws = websocket.WebSocket() try: ws.connect(target) except Exception as e: time.sleep(2) conn(target) #keep trying you basterd def close(): if ws is None: return ws.close() def sighandler(signal,frame): log("\rExiting!") close() log("Bye!") sys.exit(0) def stop(key): if key not in p_list: log("key %s doesn't exist! not killing!" % (key)) return try: os.killpg(os.getpgid(p_list[key].pid), signal.SIGTERM) except Exception as e: log("This process (%d) can't be killed! Why?" % p_list[key].pid) log(e) try: log_list[key].close() except Exception as e: log("ex file: %s" % e) if key in log_list: del log_list[key] del p_list[key] def launch(key,options=None): if key in p_list: log("key %s exist! not running!" % (key)) return if key not in ptable: log("This process (%s) is not on my table!" % key) return tolaunch = ptable[key] if options is not None: tolaunch = tolaunch + options log_list[key]=open("/tmp/%s" % key, "w") proc=subprocess.Popen(tolaunch, preexec_fn=os.setsid, stdout=log_list[key]) #Le doy su propio grupo al subproceso p_list[key]=proc return proc.pid def sendmsg(msg): s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) ret = None try: s.connect(('localhost',9999)) tosend = msg + "\r\n" s.sendall(tosend.encode("ascii")) ret=s.recv(4096) s.close() except Exception as e: log(e) return None log("[nc output] %s " % ret) return ret ip="ws://192.168.1.208:9001" conn(ip) signal.signal(signal.SIGINT, sighandler) signal.signal(signal.SIGCHLD, signal.SIG_IGN) #To kill zombies while True: try: data = ws.recv() except Exception as e: log(e) conn(ip) continue try: j = json.loads(data) except Exception as e: log(e) log("Invalid json?") continue if ("type" not in j or "command" not in j or "key" not in j or j["type"] != "snowmix"): log("Dropping: %s" % j) continue log(j) if j["command"] == "launch": launch(j["key"]) if j["command"] == "kill": stop(j["key"]) if j["command"] == "netcat": sendmsg(j["key"])