How to use launch_hub method in fMBT

Best Python code snippet using fMBT_python

webrtccourse_job.py

Source:webrtccourse_job.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import configparser4import sys,os,time5import code6import argparse7import re, datetime8import inspect9# sys.path.append(os.path.realpath('/TiledViz/TVConnections/'))10# from connect import sock11import json12import csv13if (os.path.exists("config.tar")):14 os.system("tar xf config.tar")15SITE_config='site_config.ini'16CASE_config="case_config.ini"17#def job(globals,locals)18actions_file=open("/home/myuser/actions.json",'r')19tiles_actions=json.load(actions_file)20config = configparser.ConfigParser()21config.optionxform = str22config.read(SITE_config)23NOVNC_URL=config['SITE']['NOVNC_URL']24HTTP_FRONTEND=config['SITE']['HTTP_FRONTEND']25HTTP_IP=config['SITE']['HTTP_IP']26init_IP=config['SITE']['init_IP']27TILEDOCKERS_path=config['SITE']['TILEDOCKER_DIR']28DOCKERSPACE_DIR=config['SITE']['DOCKERSPACE_DIR']29GPU_FILE=config['SITE']['GPU_FILE']30SERVER_JITSI=config['SITE']['SERVER_JITSI']31# Must v4l2loopback mount on /dev/video${VideoDeviceNumber} device.32# Please Read INSTALL doc for modprobe v4l2loopback command.33VideoDeviceNumber=config['SITE']['VideoDeviceNumber']34config.read(CASE_config)35CASE=config['CASE']['CASE_NAME']36# network=config['CASE']['network']37# nethost=config['CASE']['nethost']38# domain=config['CASE']['domain']39CONFIGPATH=config['CASE']['CONFIGPATH'] 40# OriginalList=${DATA[0]}41# IdClassroom=${DATA[1]} # Identifiant de la classe42# TeacherFirstname=${DATA[2]}43# TeacherLastname=${DATA[3]}44# TeacherEmail=${DATA[4]}45# DateDMY=${DATA[5]} # Jour du cours46# DateHM=${DATA[6]} # Heure du cours47# JitsiServer=${DATA[7]} # Adresse Jitsi sans https://48# SchoolName=${DATA[8]} # Nom de l'ecole49# SenderName=${DATA[9]} # Nom de l'emetteur50# SenderEmail=${DATA[10]} # Adresse email de l'emetteur51SOCKETdomain=config['CASE']['SOCKETdomain']52DOCKER_NAME=config['CASE']['DOCKER_NAME']53HTTP_LOGIN=config['CASE']['HTTP_LOGIN']54OPTIONS=config['CASE']['OPTIONS'].replace("$","").replace('"','')55print("\nOPTIONS from CASE_CONFIG : "+OPTIONS)56def replaceconf(x):57 if (re.search('}',x)):58 varname=x.replace("{","").replace("}","")59 return config['CASE'][varname]60 else:61 return x62OPTIONS=OPTIONS.replace("JOBPath",JOBPath)63OPTIONS=OPTIONS.replace('{','|{').replace('}','}|').split('|')64OPTIONS="".join(list(map( replaceconf,OPTIONS)))65#TODO : classroom.config must be an output from case_config.ini!66# cf SERVER_JITSI var67# reader csv sur le configpath68dataclass=[]69with open(CONFIGPATH) as csv_file:70 csv_reader = csv.reader(csv_file, delimiter=';')71 count_lines=072 for row in csv_reader:73 dataclass.append(row)74 print(", ".join(row))75 count_lines=count_lines+176FILEPATH=dataclass[0][0]77IdClassroom=dataclass[0][1]78TeacherFirstname=dataclass[0][2]79TeacherLastname=dataclass[0][3]80TeacherEmail=dataclass[0][4]81DateDMY=dataclass[0][5] # Jour du cours82DateHM=dataclass[0][6] # Heure du cours83def countlines(filename):84 f = open(filename) 85 lines = 086 buf_size = 1024 * 102487 read_f = f.read # loop optimization88 buf = read_f(buf_size)89 while buf:90 lines += buf.count('\n')91 buf = read_f(buf_size)92 return lines93NUM_STUDENTS=countlines(FILEPATH)94print("Number of students :"+str(NUM_STUDENTS))95CreateTS='create TS='+TileSet+' Nb='+str(NUM_STUDENTS)96client.send_server(CreateTS)97NOM_FICHIER_ETUDIANT_GENERE=IdClassroom+"_classroom.list"98# TODO : detect RTM free PORT on what machine ? 99# IdClassroom < 65 ! car num port < 65535100RTMPPORT=SOCKETdomain+"000"101# Global commands102# Execute on each/a set of tiles103ExecuteTS='execute TS='+TileSet+" "104# Launch a command on the frontend105LaunchTS='launch TS='+TileSet+" "+JOBPath+' '106# get TiledCourse package from Github107COMMAND_GIT="git clone https://github.com/mmancip/TiledCourse.git"108print("command_git : "+COMMAND_GIT)109os.system(COMMAND_GIT)110os.system('cp '+CONFIGPATH+' TiledCourse/webrtcconnect')111os.system('cp '+FILEPATH+' TiledCourse/webrtcconnect')112COMMAND_MAIL="cd TiledCourse/webrtcconnect; ./fastGenerateMail.sh "+CONFIGPATH113print("command_mail :"+COMMAND_MAIL)114#TODO randomize roomname (not always login) => before sendmail115os.system(COMMAND_MAIL)116# Send CASE and SITE files117try:118 client.send_server(LaunchTS+' chmod og-rxw '+JOBPath)119 print("Out of chmod JOBPath : "+ str(client.get_OK()))120 121 send_file_server(client,TileSet,".", CASE_config, JOBPath)122 CASE_config=os.path.join(JOBPath,os.path.basename(CASE_config))123 send_file_server(client,TileSet,".", SITE_config, JOBPath)124 SITE_config=os.path.join(JOBPath,os.path.basename(SITE_config))125 send_file_server(client,TileSet,".", CONFIGPATH, JOBPath)126 send_file_server(client,TileSet,".", FILEPATH, JOBPath)127 send_file_server(client,TileSet,".", "list_hostsgpu", JOBPath)128 send_file_server(client,TileSet,"TiledCourse/webrtcconnect/", NOM_FICHIER_ETUDIANT_GENERE, JOBPath)129except:130 print("Error sending files !")131 traceback.print_exc(file=sys.stdout)132 try:133 code.interact(banner="Try sending files by yourself :",local=dict(globals(), **locals()))134 except SystemExit:135 pass136COMMAND_TiledCourse=LaunchTS+COMMAND_GIT137client.send_server(COMMAND_TiledCourse)138print("Out of git clone TiledCourse : "+ str(client.get_OK()))139COMMAND_copy=LaunchTS+"cp -r TiledCourse/webrtcconnect/DockerHub/dockerRunHub.sh "+\140 "TiledCourse/webrtcconnect/DockerHub/dockerStop.sh "+\141 "./"142client.send_server(COMMAND_copy)143print("Out of copy scripts from TiledCourse : "+ str(client.get_OK()))144 145network="classroom"+IdClassroom146# "X" for no swarm !147domain="11.0.0"148# Client for teacher must be the HTTP_FRONTEND (in site_config.ini) from TVConnection (detect Frontend IP ?)149CLIENT=HTTP_FRONTEND+":"+HTTP_IP150HUBName='HUB-CR'+IdClassroom 151ID="id_rsa_"+HTTP_IP 152TileSetHUB=TileSet+'HUB'153CreateTSHUB='create TS='+TileSetHUB+' Nb=1'154client.send_server(CreateTSHUB)155# Execute on each/a set of tiles156ExecuteTSHUB='execute TS='+TileSetHUB+" "157# Launch a command on the frontend158LaunchTSHUB='launch TS='+TileSetHUB+" "+JOBPath+' '159HTTP=HTTP_LOGIN+"@"+HTTP_IP160ExecuteHTTP=ExecuteTSHUB+" ssh -fT "+HTTP+" "161print("LaunchTSHUB: %s "%(LaunchTSHUB))162def Run_Hub():163 # DEBUG : don't delete Hub on exit164 # COMMAND=LaunchTSHUB+' sed -e \'s&--rm&&\' -i dockerRunHub.sh '165 # client.send_server(COMMAND)166 # print("Out of launch Hub : "+ str(client.get_OK()))167 global LaunchTSHUB168 COMMAND=LaunchTSHUB+' ./dockerRunHub.sh '+\169 NOM_FICHIER_ETUDIANT_GENERE+' '+\170 RTMPPORT+' '+SERVER_JITSI+' '+VideoDeviceNumber+' '+\171 GPU_FILE+" "+network+" "+domain+" "+init_IP+" "+CLIENT+" TileSetPort "+Frontend+" "+DOCKER_NAME+" "+DATE172 173 print("\nCommand RunHub : "+COMMAND)174 client.send_server(COMMAND)175 print("Out of launch Hub : "+ str(client.get_OK()))176 sys.stdout.flush()177 178 COMMAND_TiledCourse=ExecuteTSHUB+COMMAND_GIT179 client.send_server(COMMAND_TiledCourse)180 print("Out of git clone TiledCourse in HUB : "+ str(client.get_OK()))181 182 COMMAND_LS_TiledCourse=ExecuteTSHUB+' bash -c "ls -la TiledCourse > .vnc/ls_TiledCourse "'183 client.send_server(COMMAND_LS_TiledCourse)184 print("Out of ls TiledCourse on HUB: "+ str(client.get_OK()))185 186 COMMAND_SEND_HTTP=ExecuteTSHUB+' scp -rp TiledCourse/webrtcconnect/get_DISPLAY.sh '+\187 'TiledCourse/webrtcconnect/launch_obs.sh '+\188 'TiledCourse/webrtcconnect/obs '+HTTP+':\$HOME/tmp/ '189 client.send_server(COMMAND_SEND_HTTP)190 print("Out of send TiledCourse files on HTTP_FRONTEND : "+ str(client.get_OK()))191 192 # global HUB_Host193 # with open("list_hostsgpu","r") as hostfile :194 # HUB_Host=hostfile.readline().split(" ")[0]195 196 # global DOCKER_HUB197 # DOCKER_HUB='ssh '+HUB_Host+' docker'198 199 # ID est une clé pour le HHTP_IP200 # Hors dans TVConnection.py, la clé est pour la Frontend201 # cmdgen="ssh-keygen -b 1024 -t rsa -N '' -f /home/"+user+"/.ssh/id_rsa_"+Frontend202 # Donc ça va pas.203 # L'idée ne serait pas de créer la clé depuis le HUB avec les mêmes commandes204 # et de copier cette clé dans le HTTP_IP? bof...205 206 # Copy ssh key to frontend from connection to HUB :207 # try:208 # send_file_server(client,TileSetHUB,".ssh", ID, JOBPath)209 # send_file_server(client,TileSetHUB,".ssh", ID+".pub", JOBPath)210 # COMMAND=LaunchTSHUB+' chmod 400 '+ID211 # client.send_server(COMMAND)212 # print("Out of chmod key : "+ str(client.get_OK()))213 # COMMAND=LaunchTSHUB+' scp -p '+ID+'* '+HUB_Host+":/tmp"214 # client.send_server(COMMAND)215 # print("Out of send key : "+ str(client.get_OK()))216 # # COMMAND=LaunchTSHUB+' ssh '+HUB_Host+' chmod 400 /tmp/'+ID217 # # client.send_server(COMMAND)218 # # print("Out of chmod key on Hub : "+ str(client.get_OK()))219 # # sys.stdout.flush()220 # COMMAND=LaunchTSHUB+' '+DOCKER_HUB+' cp -a /tmp/'+ID+' '+HUBName+':/home/myuser/.ssh/'221 # client.send_server(COMMAND)222 # print("Out of put key on Hub : "+ str(client.get_OK()))223 # sys.stdout.flush()224 # COMMAND=LaunchTSHUB+' '+DOCKER_HUB+' cp -a /tmp/'+ID+'.pub '+HUBName+':/home/myuser/.ssh/'225 # client.send_server(COMMAND)226 # print("Out of put pub key on Hub : "+ str(client.get_OK()))227 # COMMAND=LaunchTSHUB+' bash -c " rm -f '+ID+'* ; ssh '+HUB_Host+" rm -f /tmp/"+ID+'* "'228 # client.send_server(COMMAND)229 # print("Out of rm key : "+ str(client.get_OK()))230 # sys.stdout.flush()231 # except Exception as err:232 # traceback.print_exc(file=sys.stderr)233 # print("Error ssh ID %s for HTTP %s : %s" % (ID,HTTP_IP,err))234 # client.send_server(ExecuteTSHUB+' chmod 400 /home/myuser/.ssh/'+ID)235 # print("Out of chmod "+ID+" : "+ str(client.get_OK()))236 237 # client.send_server(ExecuteTSHUB+' chmod 700 /home/myuser/.ssh')238 # print("Out of chmod .ssh : "+ str(client.get_OK()))239 240 # COMMAND=LaunchTSHUB+' '+DOCKER_HUB+\241 # ' exec '+HUBName+' bash -c \'"chown myuser:myuser /home/myuser/.ssh/'+ID+'* ;'+\242 # ' chmod 600 /home/myuser/.ssh/'+ID+'* "\''243 # client.send_server(COMMAND)244 # print("Out of chmod key on Hub : "+ str(client.get_OK()))245Run_Hub()246IP_Hub=domain+"."+str(int(init_IP)-1)247sys.stdout.flush()248def launch_Hub(C):249 outpactl=True250 while (outpactl):251 time.sleep(1)252 COMMAND='bash -c "'+C+'"'253 client.send_server(ExecuteTSHUB+COMMAND)254 outpactl=client.get_OK()255 print("Out of "+C+" :"+str(outpactl))256 outpactl=bool(outpactl)257 258def wakeup():259 # Wait for server to start pactl access to Hub260 launch_Hub("pactl info > /dev/null")261 262pulsedir=""263def Kill_Hub():264 global pulsedir265 266 COMMAND=ExecuteHTTP+' killall obs'267 client.send_server(COMMAND)268 print("Out of kill obs : "+ str(client.get_OK()))269 COMMAND_DISPLAY=ExecuteHTTP+" bash -c \"'XDG_RUNTIME_DIR="+pulsedir+" pulseaudio -k '\"" 270 client.send_server(COMMAND_DISPLAY)271 print("Out of reinitialize pulseaudio on HTTP_Frontend : "+ str(client.get_OK()))272 273 COMMAND=LaunchTSHUB+' ./dockerStop.sh '+NOM_FICHIER_ETUDIANT_GENERE+' '+GPU_FILE274 print("\nCommand stop Hub : "+COMMAND)275 client.send_server(COMMAND)276 print("Out of stop Hub : "+ str(client.get_OK()))277REF_CAS=str(NUM_STUDENTS)+" "+DATE+" "+DOCKERSPACE_DIR+" "+DOCKER_NAME278COMMANDStop=os.path.join(TILEDOCKERS_path,"stop_dockers")+" "+REF_CAS+" "+os.path.join(JOBPath,GPU_FILE)279print("\n"+COMMANDStop)280sys.stdout.flush()281nethost="VM"282OPTIONS=OPTIONS+" -e ID_CLASSROOM="+IdClassroom+" --device=/dev/video"+VideoDeviceNumber283def Run_Vm():284 # Launch containers HERE285 COMMAND=os.path.join(TILEDOCKERS_path,"launch_dockers")+" "+REF_CAS+" "+GPU_FILE+" "+CLIENT+\286 " "+network+" "+nethost+" "+domain+" "+init_IP+" TileSetPort "+UserFront+"@"+Frontend+" "+OPTIONS287 print("\nCommand RunVm : "+COMMAND)288 client.send_server(LaunchTS+' '+COMMAND)289 print("Out of launch Vm : "+ str(client.get_OK()))290 sys.stdout.flush()291Run_Vm()292sys.stdout.flush()293NUM_DOCKERS=NUM_STUDENTS294# Build nodes.json file from new dockers list295def build_nodes_file():296 print("Build nodes.json file from new dockers list.")297 COMMAND=LaunchTS+' TiledCourse/webrtcconnect/build_nodes_file '+CASE_config+' '+SITE_config+' '+TileSet298 print("\nCommand dockers : "+COMMAND)299 client.send_server(COMMAND)300 print("Out of build_nodes_file : "+ str(client.get_OK()))301 time.sleep(2)302 303build_nodes_file()304sys.stdout.flush()305time.sleep(2)306# Launch docker tools307def launch_resize(RESOL="1440x900"):308 client.send_server(ExecuteTS+' xrandr --fb '+RESOL)309 print("Out of xrandr : "+ str(client.get_OK()))310launch_resize()311def launch_tunnel():312 client.send_server(ExecuteTS+' /opt/tunnel_ssh '+HTTP_FRONTEND+' '+HTTP_LOGIN)313 print("Out of tunnel_ssh : "+ str(client.get_OK()))314 # Get back PORT315 for i in range(NUM_DOCKERS):316 i0="%0.3d" % (i+1)317 client.send_server(ExecuteTS+' Tiles=('+containerId(i+1)+') '+318 'bash -c "scp .vnc/port '+UserFront+'@'+Frontend+':'+JOBPath+'/port'+i0+'"')319 print("Out of change port %s : " % (i0) + str(client.get_OK()))320 COMMAND="find . -name \"port*\" -exec bash -c 'FILE={}; echo $FILE; i0=$( echo $FILE|sed -e \"sA./portAA\" ); echo $i0; "+\321 "port=$(cat $FILE); sed -e \"sBport="+SOCKETdomain+"${i0}Bport=${port}B\" -i ./nodes.json' \\; "322 print("\nCommand change ports : "+COMMAND)323 client.send_server(LaunchTS+' '+COMMAND)324 print("Out of change ports : "+ str(client.get_OK()))325 sys.stdout.flush()326 launch_nodes_json()327launch_tunnel()328def launch_vnc():329 client.send_server(ExecuteTS+' /opt/vnccommand')330 print("Out of vnccommand : "+ str(client.get_OK()))331launch_vnc()332pactl_call=""333dev_source="alsa_input.pci-0000_00_1b.0.analog-stereo"334dev_sink="alsa_output.pci-0000_00_1b.0.analog-stereo"335sourceindex=-1336sinkindex=-1337sourcemodule=-1338sinkmodule=-1339sourceVMindex=[]340sinkVMindex=[]341def launch_sound():342 global pactl_call, pulsedir, dev_source, dev_sink, sourceindex, sinkdex343 344 # Get pulseaudio socket on HTTP_FRONTEND through DockerHub :345 COMMAND=ExecuteHTTP+' bash -c "\'/sbin/lsof -c pulseaudio 2>/dev/null |grep \\\"/native\\\" '+\346 '| tail -1 | sed -e \\\"s@.* \\\([a-zA-Z0-9_/]*/native\\\) .*@\\1@\\\" > tmp/out_native\'"'347 if (args.debug):348 print("COMMAND for socket native detection : "+ COMMAND)349 sys.stdout.flush()350 client.send_server(COMMAND)351 print("Out of socket native detection : "+ str(client.get_OK()))352 # TODO: This may not work if HTTP_FRONTEND and Frontend ssh keys are different.353 COMMAND=ExecuteTSHUB+' scp '+HTTP+':\$HOME/tmp/out_native '+UserFront+'@'+Frontend+':'+JOBPath354 if (args.debug):355 print("COMMAND for scp out_native : "+ COMMAND)356 sys.stdout.flush()357 client.send_server(COMMAND)358 print("Out of scp out_native : " + str(client.get_OK()))359 get_file_client(client,TileSet,JOBPath,"out_native",".")360 with open("out_native","r") as native :361 pulsesocket=native.readline().replace('\n','')362 print("pulsesocket : "+pulsesocket)363 pulsedir=pulsesocket.replace("pulse/native","")364 print("pulsedir : "+pulsedir)365 366 pactl_call='XDG_RUNTIME_DIR='+pulsedir+' pactl'367 #pactl_call='pactl'368 369 # Add pulseaudio tunnel on Hub to HTTP_FRONTEND :370 client.send_server(ExecuteTSHUB+' /opt/launch_sound.sh '+pulsesocket+' '+HTTP_IP+' '+HTTP_LOGIN)371 print("Out of launch_sound HUB : "+ str(client.get_OK()))372 COMMAND=' scp \''+HTTP+':\$HOME/.config/pulse/cookie\' .config/pulse/'373 launch_Hub(COMMAND)374 375 # detect default source/sink376 launch_Hub('pactl info |grep Default > .vnc/out_default')377 client.send_server(ExecuteTSHUB+'scp .vnc/out_default '+UserFront+'@'+Frontend+':'+JOBPath)378 print("Out of scp out_default : " + str(client.get_OK()))379 380 get_file_client(client,TileSet,JOBPath,"out_default",".")381 382 with open("out_default","r") as fdefault :383 for line in fdefault:384 line=line.replace('\n','')385 if (re.search('Default Sink:',line)):386 dev_sink=line.replace("Default Sink: ","")387 if (re.search('Default Source:',line)):388 dev_source=line.replace("Default Source: ","")389 # Pulse VM :390 COMMAND_Pulse="ssh -4 -c aes128-ctr -fNT -i .ssh/id_rsa_hub -L4000:localhost:4000 "+IP_Hub+" &"391 CommandTS=ExecuteTS+" "+COMMAND_Pulse392 client.send_server(CommandTS)393 print("Out of ssh Hub : "+ str(client.get_OK()))394 # All pulseaudio in container listen to 4000395 client.send_server(ExecuteTS+' /opt/launch_sound.sh')396 print("Out of launch_sound VM : "+ str(client.get_OK()))397 # client.send_server(ExecuteTS+' nohup bash -c "killall pulseaudio" </dev/null > /dev/null 2>&1 &')398 # print("Out of kill pulseaudio VM : "+ str(client.get_OK()))399 sys.stdout.flush()400 401 COMMAND_cookie='bash -c "scp -i .ssh/id_rsa_hub \''+IP_Hub+':$HOME/.config/pulse/cookie\' .config/pulse/"'402 if (args.debug):403 print("COMMAND for scp VM cookie : "+ COMMAND_cookie)404 sys.stdout.flush()405 client.send_server(ExecuteTS+COMMAND_cookie)406 print("Out of scp VM cookie : " + str(client.get_OK()))407 408 # Add sound modules on pulseaudio of HTTP_FRONTEND :409 launch_Hub('pactl load-module module-null-sink sink_name=stu_sink'+410 ' sink_properties=device.description=\"GlobalSink\" > .vnc/index_stu_sink')411 launch_Hub('pactl list short sinks |grep stu_sink >> .vnc/index_stu_sink')412 launch_Hub('pactl load-module module-null-sink sink_name=stu_source'+413 ' sink_properties=device.description=\"GlobalSource\" > .vnc/index_stu_source')414 launch_Hub('pactl list short sinks |grep stu_source >> .vnc/index_stu_source')415 COMMAND=ExecuteTSHUB+'scp .vnc/index_stu_* '+UserFront+'@'+Frontend+':'+JOBPath416 if (args.debug):417 print("COMMAND for scp index_stu_sink/source : "+ COMMAND)418 sys.stdout.flush()419 client.send_server(COMMAND)420 print("Out of scp index_stu_sink/source : " + str(client.get_OK()))421 get_file_client(client,TileSet,JOBPath,"index_stu_sink",".")422 get_file_client(client,TileSet,JOBPath,"index_stu_source",".")423 with open("index_stu_source","r") as fsource :424 sourcemodule=fsource.readline().replace('\n','')425 print("sourcemodule : "+sourcemodule)426 sourcemodule=int(sourcemodule)427 sourceindex=re.sub('\t.*','',fsource.readline().replace('\n',''))428 print("sourceindex : "+sourceindex)429 sourceindex=int(sourceindex)430 431 with open("index_stu_sink","r") as fsink :432 sinkmodule=fsink.readline().replace('\n','')433 print("sinkmodule : "+sinkmodule)434 sinkmodule=int(sinkmodule)435 sinkindex=re.sub('\t.*','',fsink.readline().replace('\n',''))436 print("sinkindex : "+sinkindex)437 sinkindex=int(sinkindex)438 time.sleep(2)439 # Le son des étudiants sort sur les haut-parleurs du prof440 launch_Hub('pactl load-module module-loopback source=stu_sink.monitor sink='+dev_sink)441 # Son du micro du prof va dans les inputs des étudiants442 launch_Hub('pactl load-module module-loopback source='+dev_source+' sink=stu_source')443 444 # Le son des étudiants va dans les inputs des étudiants445 launch_Hub('pactl load-module module-loopback source=stu_sink.monitor sink=stu_source')446 447 # Un seul étudiant parle à la fois comme ça son son ne peut pas re-rentrer. 448 #launch_Hub('pactl set-default-sink stu_sink')449 # TODO : considering local docker network is safe, one can only connect from VM to HUB with socat and open 4000 port. 450 # only HUB to HTTP_FRONTEND may be encrypted. 451 wakeup()452 for i in range(NUM_DOCKERS):453 VM=containerId(i+1)454 launch_Hub('pactl load-module module-null-sink sink_name=fake_source'+VM+455 ' sink_properties=device.description=fake_source'+VM)456 launch_Hub('pactl load-module module-remap-source master=fake_source'+VM+'.monitor '+457 ' source_name=stu_source'+VM+' source_properties=device.description=Virtual_Mic'+VM+458 ' > .vnc/index_source'+VM)459 launch_Hub('pactl load-module module-null-sink sink_name=stu_sink'+VM+460 ' sink_properties=device.description=sink'+VM+' > .vnc/index_sink'+VM)461 COMMAND=ExecuteTSHUB+'scp .vnc/index_s*'+VM+' '+UserFront+'@'+Frontend+':'+JOBPath462 if (args.debug):463 print("COMMAND for scp index_sink/source_%s : %s" % (VM,COMMAND))464 sys.stdout.flush()465 client.send_server(COMMAND)466 print("Out of scp index_sink/source_%s : %s" % (VM,str(client.get_OK())))467 468 get_file_client(client,TileSet,JOBPath,"index_sink"+VM,".")469 get_file_client(client,TileSet,JOBPath,"index_source"+VM,".")470 with open("index_source"+VM,"r") as fsource :471 soindex=fsource.readline().replace('\n','')472 print("sourceindex%s : %s" % (VM,soindex))473 sourceVMindex.append(int(soindex))474 475 with open("index_sink"+VM,"r") as fsink :476 siindex=fsink.readline().replace('\n','')477 print("sinkindex%s : %s" % (VM,siindex))478 sinkVMindex.append(int(siindex))479 # Connect to global sound480 launch_Hub('pactl load-module module-loopback source=stu_sink'+VM+'.monitor sink=stu_sink')481 launch_Hub('pactl load-module module-loopback source=stu_source.monitor sink=fake_source'+VM)482 483# Launch OBS on the frontend484def launch_OBS():485 COMMAND_DISPLAY=ExecuteHTTP+" bash -c \"' cd tmp; ./get_DISPLAY.sh; ls -la out_DISPLAY '\"" 486 client.send_server(COMMAND_DISPLAY)487 print("Out of get DISPLAY for user : "+ str(client.get_OK()))488 # client.send_server(ExecuteTSHUB+489 # 'bash -c "scp out_DISPLAY '+UserFront+'@'+Frontend+':'+JOBPath+'/"')490 # print("Out of scp out_DISPLAY : " + str(client.get_OK()))491 #get_file_client(client,TileSet,JOBPath,"out_DISPLAY",".")492 COMMAND_OBS=ExecuteHTTP+" bash -c \"' cd tmp; ./launch_obs.sh "+HTTP_FRONTEND+" "+RTMPPORT+" "+IdClassroom+" & '\"" 493 client.send_server(COMMAND_OBS)494 print("Out of execute OBS for user : "+ str(client.get_OK()))495 time.sleep(3)496 launch_ffmpeg()497 498# force only one ffmpeg by node (cf mageiawebrtc/command_ffmpeg)499list_hosts_ffmpeg=[]500def launch_ffmpeg():501 COMMAND_ffmpeg=" /opt/command_ffmpeg "+IdClassroom+" "+VideoDeviceNumber+" "+IP_Hub+" &"502 with open(FILEPATH) as csv_file:503 with open("list_hostsgpu","r") as hostgpu :504 csv_reader = csv.reader(csv_file, delimiter=';')505 count_lines=0506 for row in csv_reader:507 count_lines=count_lines+1508 HubHost=hostgpu.readline().replace('\n','')509 if (not HubHost in list_hosts_ffmpeg):510 TilesStr=' Tiles=('+containerId(count_lines)+') '511 client.send_server(ExecuteTS+TilesStr+COMMAND_ffmpeg)512 print("Out of ffmpeg on %s : %s "% (HubHost, str(client.get_OK())))513 list_hosts_ffmpeg.append(HubHost)514 #time.sleep(2)515 sys.stdout.flush()516# Launch google-chrome517def launch_chrome():518 COMMAND_CHROME="/opt/command_chrome "+' '+SERVER_JITSI+' '+TeacherFirstname+'_'+TeacherLastname+' '+TeacherEmail519 client.send_server(ExecuteTSHUB+' bash -c "pactl list > .vnc/out_sound_0 "')520 #nohup ... </dev/null > /dev/null 2>&1 &521 client.get_OK()522 time.sleep(0.5)523 with open(FILEPATH) as csv_file:524 csv_reader = csv.reader(csv_file, delimiter=';')525 count_lines=0526 for row in csv_reader:527 print(", ".join(row))528 i=count_lines529 count_lines=count_lines+1530 #UserName=row[0]531 #mail=row[1]532 roomName=row[2]533 VM=containerId(count_lines)534 VM_NAME=DOCKER_NAME+"_"+DATE+"_"+VM535 536 wakeup()537 launch_Hub('pactl set-default-sink stu_sink'+VM)538 launch_Hub('pactl set-default-source stu_source'+VM)539 time.sleep(1)540 TilesStr=' Tiles=('+VM+') '541 COMMAND_CHROMEi=COMMAND_CHROME+' '+roomName+' stu_sink'+VM+' stu_source'+VM542 print("%d Chrome command : %s" % (count_lines,COMMAND_CHROMEi))543 CommandTS=ExecuteTS+TilesStr+COMMAND_CHROMEi544 client.send_server(CommandTS)545 client.get_OK()546 547 time.sleep(5)548 wakeup()549 COMMAND='id=$(pactl list sink-inputs |grep -i -B23 \"'+VM_NAME+'\" '+\550 '|head -1 |sed -e \"s/Sink Input #//\"); echo \$id; '+\551 'pactl move-sink-input \$id stu_sink'+VM+' >> .vnc/out_move_sink'+VM+' 2>&1'552 launch_Hub(COMMAND)553 wakeup()554 COMMAND='id=$(pactl list source-outputs |grep -i -B23 \"'+VM_NAME+'\" '+\555 '|head -1 |sed -e \"s/Source Output #//\"); echo \$id; '+\556 'pactl move-source-output \$id stu_source'+VM+' >> .vnc/out_move_source'+VM+' 2>&1'557 launch_Hub(COMMAND)558 mute(tileId=VM)559 client.send_server(ExecuteTSHUB+' bash -c "pactl list > .vnc/out_sound_'+str(count_lines)+'"')560 #nohup ... </dev/null > /dev/null 2>&1 &561 client.get_OK()562 563 sys.stdout.flush()564# Launch google-chrome565def place_chrome_sound():566 for i in range(NUM_DOCKERS):567 VM=containerId(i+1)568 VM_NAME=DOCKER_NAME+"_"+DATE+"_"+VM569 COMMAND='id=$(pactl list sink-inputs |grep -i -B23 \"'+VM_NAME+'\" '+\570 '|head -1 |sed -e \"s/Sink Input #//\"); echo \$id; '+\571 'pactl move-sink-input \$id stu_sink'+VM+' >> .vnc/out_move_sink'+VM+' 2>&1'572 launch_Hub(COMMAND)573 COMMAND='id=$(pactl list source-outputs |grep -i -B23 \"'+VM_NAME+'\" '+\574 '|head -1 |sed -e \"s/Source Output #//\"); echo \$id; '+\575 'pactl move-source-output \$id stu_source'+VM+' >> .vnc/out_move_source'+VM+' 2>&1'576 launch_Hub(COMMAND)577 578Volume_Out=[0]*NUM_DOCKERS579Volume_In=[100]*NUM_DOCKERS580def get_volume_out(tileNum=-1,tileId='001'):581 if ( tileNum > -1 ):582 i=tileNum583 else:584 i=int(tileId)-1585 VM=containerId(i+1)586 VM_NAME=DOCKER_NAME+"_"+DATE+"_"+VM587 COMMAND='volume_out=$(pactl list sinks |grep -i -B8 -A3 stu_sink'+VM+')'+\588 'echo \$volume_out; '+\589 ' > .vnc/out_volume_out'+VM+' 2>&1'590 launch_Hub(COMMAND)591def open_sound(tileNum=-1,tileId='001'):592 if ( tileNum > -1 ):593 i=tileNum594 else:595 i=int(tileId)-1596 VM=containerId(i+1)597 Volume_Out[i]=100598 launch_Hub('pactl set-sink-volume stu_sink'+VM+' 100%%')599def mute(tileNum=-1,tileId='001'):600 if ( tileNum > -1 ):601 i=tileNum602 else:603 i=int(tileId)-1604 VM=containerId(i+1)605 Volume_Out[i]=0606 launch_Hub('pactl set-sink-volume stu_sink'+VM+' %d%%' % Volume_Out[i])607 608def increase_volume(tileNum=-1,tileId='001'):609 if ( tileNum > -1 ):610 i=tileNum611 else:612 i=int(tileId)-1613 VM=containerId(i+1)614 Volume_Out[i]=Volume_Out[i]+10615 launch_Hub('pactl set-sink-volume stu_sink'+VM+' %d%%' % Volume_Out[i])616 617def decrease_volume(tileNum=-1,tileId='001'):618 if ( tileNum > -1 ):619 i=tileNum620 else:621 i=int(tileId)-1622 VM=containerId(i+1)623 Volume_Out[i]=Volume_Out[i]-10624 launch_Hub('pactl set-sink-volume stu_sink'+VM+' %d%%' % Volume_Out[i])625 626# Launch 627# def launch_all(COMMAND):628# with open(FILEPATH) as csv_file:629# csv_reader = csv.reader(csv_file, delimiter=';')630# count_lines=0631# for row in csv_reader:632# print(", ".join(row))633# count_lines=count_lines+1634# #UserName=row[0]635# #mail=row[1]636# #roomName=row[2]637# TilesStr=' Tiles=('+containerId(count_lines)+') '638 639# print("%d command : %s" % (count_lines,COMMAND))640# CommandTS=ExecuteTS+TilesStr+COMMAND641# client.send_server(CommandTS)642# client.get_OK()643 644 645def kill_all_containers():646 647 client.send_server(ExecuteTS+' killall Xvnc')648 print("Out of killall command : "+ str(client.get_OK()))649 client.send_server(LaunchTS+" "+COMMANDStop)650 print("Out of stop command : "+ str(client.get_OK()))651 Kill_Hub()652 client.close()653 654launch_actions_and_interact()655 656kill_all_containers()657 ...

Full Screen

Full Screen

test.py

Source:test.py Github

copy

Full Screen

...36 'NodeFirefoxDebug': 'FirefoxTests',37 'StandaloneFirefox': 'FirefoxTests',38 'StandaloneFirefoxDebug': 'FirefoxTests',39}40def launch_hub():41 """42 Launch the hub43 :return: the hub ID44 """45 logger.info("Launching Hub...")46 existing_hub = None47 try:48 existing_hub = client.containers.get('selenium-hub')49 except NotFound:50 pass51 if existing_hub:52 logger.debug("hub already exists. removing.")53 if existing_hub.status == 'running':54 logger.debug("hub is running. Killing")55 existing_hub.kill()56 logger.debug("hub killed")57 existing_hub.remove()58 logger.debug("hub removed")59 hub_container_id = launch_container('Hub', ports={'4444': 4444})60 logger.info("Hub Launched")61 return hub_container_id62def launch_container(container, **kwargs):63 """64 Launch a specific container65 :param container:66 :return: the container ID67 """68 # Build the container if it doesn't exist69 logger.info("Building %s container..." % container)70 client.images.build(path='../%s' % container,71 tag="%s/%s:%s" % (NAMESPACE, IMAGE_NAME_MAP[container], VERSION),72 rm=True)73 logger.info("Done building %s" % container)74 # Run the container75 logger.info("Running %s container..." % container)76 container_id = client.containers.run("%s/%s:%s" % (NAMESPACE, IMAGE_NAME_MAP[container], VERSION),77 detach=True,78 **kwargs).short_id79 logger.info("%s up and running" % container)80 return container_id81if __name__ == '__main__':82 # The container to test against83 image = sys.argv[1]84 standalone = 'standalone' in image.lower()85 # Flag for failure (for posterity)86 failed = False87 logger.info('========== Starting %s Container ==========' % image)88 if standalone:89 """90 Standalone Configuration91 """92 smoke_test_class = 'StandaloneTest'93 test_container_id = launch_container(image, ports={'4444': 4444})94 else:95 """96 Hub / Node Configuration97 """98 smoke_test_class = 'NodeTest'99 hub_id = launch_hub()100 test_container_id = launch_container(image, links={hub_id: 'hub'}, ports={'5555': 5555})101 logger.info('========== / Containers ready to go ==========')102 try:103 # Smoke tests104 logger.info('*********** Running smoke tests %s Tests **********' % image)105 image_class = "%sTest" % image106 test_class = getattr(__import__('SmokeTests', fromlist=[smoke_test_class]), smoke_test_class)107 suite = unittest.TestLoader().loadTestsFromTestCase(test_class)108 test_runner = unittest.TextTestRunner(verbosity=3)109 failed = not test_runner.run(suite).wasSuccessful()110 except Exception as e:111 logger.fatal(e.message)112 failed = True113 try:...

Full Screen

Full Screen

GuyHub.py

Source:GuyHub.py Github

copy

Full Screen

...23 dot += "."24 time.sleep(t)25 t += 0.0326 print("\n")27def launch_hub():28 while True:29 user_input = str(input("Welcome to guy's Hub!\n\nFor Guy's Math-Center --> enter 'm'\n"+30 "For Guy's Dictionary --> enter 'd'\n\n" +31 "To quit --> enter 'q'\n")) or '0'32 if (user_input == '0'):33 print("\nNot entered any value\n\n")34 elif (user_input == 'm'):35 goto("Math-Center")36 MP.mat_hub()37 elif (user_input == 'q'):38 print("\nClosing, Bye !")39 time.sleep(1)40 break41 elif (user_input == 'd'):42 goto("Guy's Dictionary")43 call_dictionary()44 else:45 print("\nUndefined request\n\n")46if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful