def execute_new(self):
        self.clean_pids_string="""
for d_p in $(vncserver  -list | grep ^: | cut -d: -f2 | cut -f 1,3 --output-delimiter=@); do
	i=$(echo $d_p | cut -d@ -f2)
	d=$(echo $d_p | cut -d@ -f1)
	a=$(ps -p $i -o comm=)
	if [ "x$a" == "x" ] ; then 
	  vncserver -kill  :$d 1>/dev/null
 	fi
done"""
        if(self.subnet): self.nodelogin = self.pconfig.get_login(self.subnet)
        if(not self.nodelogin):
                raise Exception("Error in finding nodelogin")



        self.load_sessions() 
        sid=self.new_sid()
        self.clean_files(sid)
        udirs=self.get_rcmdirs()
        file='%s/%s.session' % (udirs[0],sid)
    
        #put the 'inactive' lock
        c=rcm.rcm_session(state='init',sessionid=sid)
        c.serialize(file)
        jid='NOT_SUBMITTED'
        self.par_w = self.get_timelimit()
        try:
            #set vncpasswd

            fileout='%s/%s.joblog' % (udirs[0],sid) + '.pwd'
            vncpasswd_command = self.vnc_setup +  "; echo -e " + self.vncpassword + " | vncpasswd -f > " + fileout
	    myprocess = subprocess.Popen([vncpasswd_command],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
            stdout,stderr = myprocess.communicate()
            myprocess.wait()
            jobScript = self.pconfig.get_jobscript(self.queue)

            jid=self.submit_job(sid,udirs,jobScript)
            c=rcm.rcm_session(state='pending', sessionname=self.sessionname, walltime=self.par_w, node='', tunnel='', sessiontype=self.session_tag, nodelogin=self.nodelogin, display='', jobid=jid, sessionid=sid, username=self.username, otp='', vncpassword=self.vncpassword_crypted)
            c.serialize(file)
            #c.write(self.par_f)
            (n,d,otp)=self.wait_jobout(sid,400)
            #here we test if hostname returned by jobout is the same host (ssh case)
            if(n == socket.gethostname()): 
		#print "setto il tunnel a ", self.get_use_tunnel()
                tunnel=self.get_use_tunnel()
            else:
                tunnel='y'
            #n+='ib0'
#        except Exception as e:
        except Exception,inst:
	    sys.stderr.write("%s: %s RCM:EXCEPTION" % (inst, traceback.format_exc()))
		    
            c=rcm.rcm_session(state='invalid',sessionid=sid)
            c.serialize(file)
            if (jid != 'NOT_SUBMITTED'):
                self.kill_job(jid)   
            raise Exception("Error in execute_new:%s" % inst)
    def new(self,
            geometry='',
            queue='',
            sessionname='',
            subnet='',
            vncpassword='',
            vncpassword_crypted='',
            vnc_id='',
            choices_string=''):
        logger.debug("new")
        if choices_string:
            print("choices string:", choices_string, file=sys.stderr)
            choices = json.loads(choices_string)
            res = self.rcm_server.pconfig.gui_composer.substitute(choices)

            for k, v in res.items():
                print(k, ":::>", file=sys.stderr)
                print(v, file=sys.stderr)
            dummy_session = rcm.rcm_session()
            return dummy_session

        print("create new vnc display session")
        if (subnet): self.rcm_server.subnet = subnet
        if (queue): self.rcm_server.queue = queue
        if (sessionname): self.rcm_server.sessionname = sessionname
        if (vncpassword): self.rcm_server.vncpassword = vncpassword
        if (vncpassword_crypted):
            self.rcm_server.vncpassword_crypted = vncpassword_crypted

        self.rcm_server.substitutions['RCM_GEOMETRY'] = geometry
        self.rcm_server.set_vnc_setup(vnc_id)
        new_session = self.rcm_server.execute_new()
        new_session.write()
Esempio n. 3
0
    def new(self,
            queue,
            geometry,
            sessionname='',
            vnc_id='turbovnc_vnc',
            choices=None):
        rcm_cipher = cipher.RCMCipher()
        vncpassword = rcm_cipher.vncpassword
        vncpassword_crypted = rcm_cipher.encrypt()

        if choices:
            choices_string = json.dumps(choices)
            logic_logger.debug("Newconn protocol choices: " + choices_string)

            o = self.protocol.new(geometry=geometry,
                                  queue=queue,
                                  sessionname='\'' + sessionname + '\'',
                                  subnet=self.subnet,
                                  vncpassword=vncpassword,
                                  vncpassword_crypted=vncpassword_crypted,
                                  vnc_id=vnc_id,
                                  choices_string=choices_string)
        else:
            o = self.protocol.new(geometry=geometry,
                                  queue=queue,
                                  sessionname='\'' + sessionname + '\'',
                                  subnet=self.subnet,
                                  vncpassword=vncpassword,
                                  vncpassword_crypted=vncpassword_crypted,
                                  vnc_id=vnc_id)

        session = rcm.rcm_session(o)
        return session
    def fill_sessions_hash(self, U=False):

        udirs=self.get_rcmdirs(U)
        if (U):
            ure='\w+'
        else:
            ure=self.username

        #read sessions files
        r=re.compile(r'(?P<sid>(?P<user>%s)-(?P<tag>\S+)-\d+)\.session$' % ure) 
        self.sessions={}
        for d in udirs:
            if os.path.isdir(d) and os.access(d, os.R_OK):
                for f in os.listdir(d):
                    ro= r.match(f)
                    if ro:
                        file= d + '/' + f
                        user=ro.group(2)
                        sid=ro.group(1)
                        tag=ro.group(3)
                        #print "file-->",file
                        try:
                            self.sessions[sid]=rcm.rcm_session(fromfile=file)
                            #need the following lines to map nodes with different hostname from different subnet
                            originalNodeLogin = self.sessions[sid].hash.get('nodelogin','')
                            if (self.subnet != '' and originalNodeLogin != ''):
                                #originalNodeLogin = self.sessions[sid].hash['nodelogin']
                                self.sessions[sid].hash['nodelogin'] = self.pconfig.confdict.get((self.subnet,originalNodeLogin),originalNodeLogin)

			    self.sessions[sid].hash['timeleft']=self.timeleft_string(sid)
                        except Exception,inst:
                                #print("WARNING: not valid session file %s: %s\n" % (file, e),type(inst),inst.args,file=sys.stderr)
				sys.stderr.write("%s: %s RCM:EXCEPTION" % (inst, traceback.format_exc()))
Esempio n. 5
0
    def kill(self,session_id=''):
	self.rcm_server.load_sessions()
	if(session_id):
           if session_id in self.rcm_server.sids['run']:
                jid=self.rcm_server.sessions[session_id].hash['jobid']
                self.rcm_server.kill_job(jid)
                file='%s/%s.session' % (self.rcm_server.get_rcmdirs()[0],session_id)
                c=rcm.rcm_session(fromfile=file)
                c.hash['state']='killing'
                c.serialize(file)
           else:
		sys.stderr.write("Not running session: %s\n" % (session_id))
		sys.stderr.flush()
                sys.exit(1)
Esempio n. 6
0
    def newconn(self, queue, geometry, sessionname='', vnc_id='turbovnc_vnc'):
        rcm_cipher = cipher.RCMCipher()
        vncpassword = rcm_cipher.vncpassword
        vncpassword_crypted = rcm_cipher.encrypt()

        o = self.protocol.new(geometry=geometry,
                              queue=queue,
                              sessionname='\'' + sessionname + '\'',
                              subnet=self.subnet,
                              vncpassword=vncpassword,
                              vncpassword_crypted=vncpassword_crypted,
                              vnc_id=vnc_id)

        session = rcm.rcm_session(o)
        return session
Esempio n. 7
0
    def sessions(self):
        sessions = {}
        if not os.path.isdir(self.sessions_dir):
            return sessions
        for sess_id in os.listdir(self.sessions_dir):
            sess_file = self.session_file_path(sess_id)
            if os.path.exists(sess_file):
                logger.debug("loading session from file: " + sess_file)
                try:
                    sessions[sess_id] = rcm.rcm_session(fromfile=sess_file)
                except Exception as e:
                    # print("WARNING: not valid session file %s: %s\n" % (file, e),type(inst),inst.args,file=sys.stderr)
                    sys.stderr.write("%s: %s RCM:EXCEPTION" %
                                     (format(e), traceback.format_exc()))

        return sessions
Esempio n. 8
0
    def newconn(self, queue, geometry, sessionname = '',vnc_id='turbovnc_vnc'):
        
        #Create a random vncpassword and encrypt it
        rcm_cipher = rcm_utils.rcm_cipher()
        vncpassword = rcm_cipher.vncpassword
        vncpassword_crypted=rcm_cipher.encrypt()
        
        #new_encoded_param='geometry='+ geometry + ' ' + 'queue='+ queue + ' ' +  'sessionname=' + '\'' + sessionname + '\'' + ' ' \
        # + 'subnet=' + self.subnet + ' ' + 'vncpassword='******' ' + 'vncpassword_crypted=' + '\'' + vncpassword_crypted + '\''
        #o=self.prex('new' + ' ' + new_encoded_param )

        o=self.protocol.new(geometry=geometry, queue=queue, sessionname='\'' + sessionname + '\'', subnet=self.subnet, vncpassword=vncpassword,
        vncpassword_crypted=vncpassword_crypted, vnc_id=vnc_id)
        
        session=rcm.rcm_session(o)
        return session 
Esempio n. 9
0
    def newconn(self, queue, geometry, sessionname = '',vnc_id='turbovnc_vnc'):
        
        #Create a random vncpassword and encrypt it
        rcm_cipher = rcm_utils.rcm_cipher()
        vncpassword = rcm_cipher.vncpassword
        vncpassword_crypted=rcm_cipher.encrypt()
        
        #new_encoded_param='geometry='+ geometry + ' ' + 'queue='+ queue + ' ' +  'sessionname=' + '\'' + sessionname + '\'' + ' ' \
        # + 'subnet=' + self.subnet + ' ' + 'vncpassword='******' ' + 'vncpassword_crypted=' + '\'' + vncpassword_crypted + '\''
        #o=self.prex('new' + ' ' + new_encoded_param )

        o=self.protocol.new(geometry=geometry, queue=queue, sessionname='\'' + sessionname + '\'', subnet=self.subnet, vncpassword=vncpassword,
        vncpassword_crypted=vncpassword_crypted, vnc_id=vnc_id)
        
        session=rcm.rcm_session(o)
        return session 
Esempio n. 10
0
    def askopenfilename(self,filename=None):
        if(not filename):
            file_opt = options = {}
            options['filetypes'] = [('vnc files', '.vnc'), ('all files', '.*')]
            filename = tkFileDialog.askopenfilename(initialdir=self.last_used_dir,**file_opt)

        if filename:
            tunnel = False
            my_rcm_client = rcm_client.rcm_client_connection(pack_info = self.pack_info)
            my_rcm_client.passwd = ''

            #check if session needs tunneling
            file = open(filename, 'r')
            if 'rcm_tunnel' in file.read():
                file.seek(0)
                lines = file.readlines()
                for l in lines:
                    if 'rcm_tunnel' in l:
                        node = l.split('=')[1].rstrip()
                        #check credential for the cluster, not for the specific node
                        if(self.n):
                            credential = self.n.getConnectionInfo(node.split('.',1)[1])
                            if credential != None:
                                user = credential['user']
                                my_rcm_client.login_setup(host=node,remoteuser=user,password=credential['password'])
                            else:
                                tkMessageBox.showwarning("Warning!", "Please login to \"{0}\" to open this shared display.".format(node))
                                return
                        else:
                            module_logger.error("connections with tunnel need to be in GUI mode with a proper connection to login node")
                            return
                        
                    if 'host' in l:
                        hostname = l.split('=')[1].rstrip()
                    if 'port' in l:
                        port = l.split('=')[1].rstrip()
                        display = int(port) - 5900
                    if 'password' in l:
                        password = l.split('=')[1].rstrip()

                c=rcm.rcm_session(node=hostname, tunnel='y', display=display, nodelogin=node, username=user, vncpassword=password)
                my_rcm_client.vncsession(session = c)
            else:
                my_rcm_client.vncsession(configFile = filename)
            self.topFrame.connections.append(my_rcm_client)
            self.last_used_dir=os.path.dirname(filename)
    def fill_sessions_hash(self, U=False):

        logger.debug("fill_sessions_hash")
        udirs = self.get_rcmdirs(U)
        if (U):
            ure = '\w+'
        else:
            ure = self.username

        #read sessions files
        r = re.compile(r'(?P<sid>(?P<user>%s)-(?P<tag>\S+)-\d+)\.session$' %
                       ure)
        self.sessions = {}
        for d in udirs:
            if os.path.isdir(d) and os.access(d, os.R_OK):
                for f in os.listdir(d):
                    ro = r.match(f)
                    if ro:
                        file = d + '/' + f
                        user = ro.group(2)
                        sid = ro.group(1)
                        tag = ro.group(3)
                        logger.debug("session file-- " + file)
                        try:
                            logger.debug("prima di fromfile:" + file)
                            self.sessions[sid] = rcm.rcm_session(fromfile=file)
                            logger.debug("dopo di fromfile:" + file)
                            logger.debug("file:" +
                                         self.sessions[sid].hash['file'])
                            #need the following lines to map nodes with different hostname from different subnet
                            originalNodeLogin = self.sessions[sid].hash.get(
                                'nodelogin', '')
                            if (self.subnet != '' and originalNodeLogin != ''):
                                #originalNodeLogin = self.sessions[sid].hash['nodelogin']
                                self.sessions[sid].hash[
                                    'nodelogin'] = self.pconfig.confdict.get(
                                        (self.subnet, originalNodeLogin),
                                        originalNodeLogin)

                            self.sessions[sid].hash[
                                'timeleft'] = self.timeleft_string(sid)
                        except Exception, inst:
                            #print("WARNING: not valid session file %s: %s\n" % (file, e),type(inst),inst.args,file=sys.stderr)
                            sys.stderr.write("%s: %s RCM:EXCEPTION" %
                                             (inst, traceback.format_exc()))
            if(n == socket.gethostname()): 
		#print "setto il tunnel a ", self.get_use_tunnel()
                tunnel=self.get_use_tunnel()
            else:
                tunnel='y'
            #n+='ib0'
#        except Exception as e:
        except Exception,inst:
	    sys.stderr.write("%s: %s RCM:EXCEPTION" % (inst, traceback.format_exc()))
		    
            c=rcm.rcm_session(state='invalid',sessionid=sid)
            c.serialize(file)
            if (jid != 'NOT_SUBMITTED'):
                self.kill_job(jid)   
            raise Exception("Error in execute_new:%s" % inst)
       
        c=rcm.rcm_session(state='valid', sessionname=self.sessionname, walltime=self.par_w, node=n, tunnel=tunnel, sessiontype=self.session_tag, nodelogin=self.nodelogin, display=d, jobid=jid, sessionid=sid, username=self.username, otp=otp, vncpassword=self.vncpassword_crypted)
        
        c.serialize(file)
        c.write(0)
	sys.stdout.flush()
        #sys.exit(0)

if __name__ == '__main__':
	s=rcm_base_server()
	print "accounts:",s.getUserAccounts()
	print "rcmdirs:",s.get_rcmdirs()
	print "fill_sessions_hash:",s.fill_sessions_hash()
	print "load sessions:",s.load_sessions()
	print "vnc_setup for turbovnc:",s.set_vnc_setup('kde_turbovnc_vnc')
    def execute_new(self):
        logger.debug("execute_new")
        self.clean_pids_string = """
for d_p in $(vncserver  -list | grep ^: | cut -d: -f2 | cut -f 1,3 --output-delimiter=@); do
        i=$(echo $d_p | cut -d@ -f2)
        d=$(echo $d_p | cut -d@ -f1)
        a=$(ps -p $i -o comm=)
        if [ "x$a" == "x" ] ; then 
          vncserver -kill  :$d 1>/dev/null
 	fi
done"""
        if (self.subnet): self.nodelogin = self.pconfig.get_login(self.subnet)
        if (not self.nodelogin):
            raise Exception("Error in finding nodelogin")

        self.load_sessions()
        sid = self.new_sid()
        self.clean_files(sid)
        udirs = self.get_rcmdirs()
        file = '%s/%s.session' % (udirs[0], sid)

        #put the 'inactive' lock
        c = rcm.rcm_session(state='init', sessionid=sid)
        c.serialize(file)
        jid = 'NOT_SUBMITTED'
        self.par_w = self.get_timelimit()
        try:
            #set vncpasswd

            fileout = '%s/%s.joblog' % (udirs[0], sid) + '.pwd'
            #vncpasswd_command = self.vnc_setup +  "; echo -e " + self.vncpassword + " | vncpasswd -f > " + fileout
            vncpasswd_command = "/bin/bash -c '" + self.vnc_setup + "; echo -e " + self.vncpassword + " | vncpasswd -f > " + fileout + "'"
            print vncpasswd_command
            myprocess = subprocess.Popen([vncpasswd_command],
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         shell=True)
            stdout, stderr = myprocess.communicate()
            print "vncpasswd_command stdout" + stdout
            print "vncpasswd_command stderr" + stderr
            myprocess.wait()
            jobScript = self.pconfig.get_jobscript(self.queue)

            jid = self.submit_job(sid, udirs, jobScript)
            c = rcm.rcm_session(state='pending',
                                sessionname=self.sessionname,
                                walltime=self.par_w,
                                node='',
                                tunnel='',
                                sessiontype=self.session_tag,
                                nodelogin=self.nodelogin,
                                display='',
                                jobid=jid,
                                sessionid=sid,
                                username=self.username,
                                otp='',
                                vncpassword=self.vncpassword_crypted)
            c.serialize(file)
            #c.write(self.par_f)
            (n, d, otp) = self.wait_jobout(sid, 240)
            #here we test if hostname returned by jobout is the same host (ssh case)
            if (n == socket.gethostname()):
                #print "setto il tunnel a ", self.get_use_tunnel()
                tunnel = self.get_use_tunnel()
            else:
                tunnel = 'y'
            n += self.pconfig.confdict.get(('platform', 'nodepostfix'), '')


#        except Exception as e:
        except Exception, inst:
            sys.stderr.write("%s: %s RCM:EXCEPTION" %
                             (inst, traceback.format_exc()))

            c = rcm.rcm_session(state='invalid', sessionid=sid)
            c.serialize(file)
            if (jid != 'NOT_SUBMITTED'):
                self.kill_job(jid)
            raise Exception("Error in execute_new:%s" % inst)
            sys.stderr.write("%s: %s RCM:EXCEPTION" %
                             (inst, traceback.format_exc()))

            c = rcm.rcm_session(state='invalid', sessionid=sid)
            c.serialize(file)
            if (jid != 'NOT_SUBMITTED'):
                self.kill_job(jid)
            raise Exception("Error in execute_new:%s" % inst)

        c = rcm.rcm_session(state='valid',
                            sessionname=self.sessionname,
                            walltime=self.par_w,
                            node=n,
                            tunnel=tunnel,
                            sessiontype=self.session_tag,
                            nodelogin=self.nodelogin,
                            display=d,
                            jobid=jid,
                            sessionid=sid,
                            username=self.username,
                            otp=otp,
                            vncpassword=self.vncpassword_crypted)

        c.serialize(file)
        return c

if __name__ == '__main__':
    s = rcm_base_server()
    print "accounts:", s.getUserAccounts()
    print "rcmdirs:", s.get_rcmdirs()
    print "fill_sessions_hash:", s.fill_sessions_hash()
Esempio n. 15
0
    def update_sessions(self, ss):
        self.connection_buttons = dict()
        self.sessions = ss
        if (self.f1):
            for child in self.f1.winfo_children():
                child.destroy()

        if len(self.sessions.array) == 0:
            w = Label(
                self.f1,
                text=
                'No display available. Press \'NEW DISPLAY\' to create a new one.',
                padding=2)
            w.pack()
        else:
            f1 = self.f1
            labelList = [
                'state', 'session name', 'created', 'node', 'display',
                'username', 'timeleft'
            ]
            c = rcm.rcm_session()
            i = 0
            for t in labelList:
                if t in c.hash.keys():
                    w = Label(f1,
                              text=t.upper(),
                              relief=RIDGE,
                              state=ACTIVE,
                              anchor=CENTER,
                              padding=4,
                              font=boldfont)
                    w.grid(row=0, column=i + 3, sticky="we")

                    f1.columnconfigure(i, minsize=80)
                    i = i + 1

            for line, el in enumerate(self.sessions.array):
                if (self.client_connection):

                    def cmd(self=self, session=el):
                        if (self.debug):
                            module_logger.debug("killing session " +
                                                str(sessionid))
                        self.kill(session)

                    #if(el.hash['state'] == 'killed'):
                    #    continue

                    bk = Button(f1,
                                text="KILL",
                                padding=4,
                                style='RCM.TButton',
                                command=cmd)
                    bk.grid(row=line + 1, column=2, pady=0)

                    def cmd_share(self=self, session=el):
                        self.asksaveasfilename(session)

                    bs = Button(f1,
                                text="SHARE",
                                padding=4,
                                style='RCM.TButton',
                                command=cmd_share)
                    bs.grid(row=line + 1, column=1, pady=0)

                    bc = Button(f1,
                                text="CONNECT",
                                padding=4,
                                style='RCM.TButton')
                    bc.grid(row=line + 1, column=0, pady=0)
                    sessionid = el.hash['sessionid']

                    def disable_cmd(self=self,
                                    sessionid=el.hash['sessionid'],
                                    active=True):
                        module_logger.info("changing sessionid->" + sessionid +
                                           "< button to " + str(active))

                        if (active):
                            self.client_connection.activeConnectionsList.append(
                                sessionid)
                        else:
                            if sessionid in self.client_connection.activeConnectionsList:
                                self.client_connection.activeConnectionsList.remove(
                                    sessionid)
                            self.do_list_refresh = True
                        self.do_update_gui = True

                    #if el.hash['state'] == 'valid':
                    self.connection_buttons[sessionid] = (bc, disable_cmd)

                    #    print "self.connection_buttons -------> " + str(self.connection_buttons)

                    def cmd_warn(self=self,
                                 session=el,
                                 disable_cmd=disable_cmd):
                        tkMessageBox.showwarning(
                            "Warning!",
                            "Display created with a previous RCM client version. Can not start the connection."
                        )

                    def cmd(self=self, session=el, disable_cmd=disable_cmd):
                        if (session.hash['sessionid'] in
                                self.client_connection.activeConnectionsList):
                            tkMessageBox.showwarning(
                                "Warning!", "Already connected to session " +
                                session.hash['sessionid'])
                        else:
                            if (self.debug):
                                module_logger.info(
                                    "connecting to sessionid-->" +
                                    str(session.hash['sessionid']) + "<")
                            self.startBusy(
                                "Connecting to the remote display...")
                            self.client_connection.vncsession(
                                session, gui_cmd=disable_cmd)
                            self.after(4000, self.stopBusy)

                    if (el.hash.get('vncpassword', '') == ''):
                        bc.configure(command=cmd_warn)
                    else:
                        bc.configure(command=cmd)
                    if sessionid in self.client_connection.activeConnectionsList:
                        bc.configure(state=DISABLED)
                    if (el.hash['state'] == 'pending'):
                        bc.configure(state=DISABLED)
                        bs.configure(state=DISABLED)

                i = 0
                for t in labelList:
                    if t in c.hash.keys():
                        lab = Label(f1,
                                    text=el.hash[t],
                                    relief=RIDGE,
                                    anchor=CENTER,
                                    padding=6)
                        if t == 'timeleft':
                            try:
                                timeleft = datetime.datetime.strptime(
                                    el.hash[t], "%H:%M:%S")
                                endTime = timeleft.replace(hour=0,
                                                           minute=0,
                                                           second=0)
                                limit = timeleft - endTime
                                if limit < datetime.timedelta(hours=1):
                                    lab.configure(foreground="red")
                            except:
                                pass
                        lab.grid(row=line + 1, column=i + 3, sticky="we")
                        i = i + 1
Esempio n. 16
0
    def askopenfilename(self, filename=None):
        if (not filename):
            file_opt = options = {}
            options['filetypes'] = [('vnc files', '.vnc'), ('all files', '.*')]
            filename = tkFileDialog.askopenfilename(
                initialdir=self.last_used_dir, **file_opt)

        if filename:
            tunnel = False
            my_rcm_client = rcm_client.rcm_client_connection(
                pack_info=self.pack_info)
            my_rcm_client.passwd = ''

            #check if session needs tunneling
            file = open(filename, 'r')
            if 'rcm_tunnel' in file.read():
                file.seek(0)
                lines = file.readlines()
                for l in lines:
                    if 'rcm_tunnel' in l:
                        node = l.split('=')[1].rstrip()
                        #check credential for the cluster, not for the specific node
                        if (self.n):
                            credential = self.n.getConnectionInfo(
                                node.split('.', 1)[1])
                            if credential != None:
                                user = credential['user']
                                my_rcm_client.login_setup(
                                    host=node,
                                    remoteuser=user,
                                    password=credential['password'])
                            else:
                                tkMessageBox.showwarning(
                                    "Warning!",
                                    "Please login to \"{0}\" to open this shared display."
                                    .format(node))
                                return
                        else:
                            module_logger.error(
                                "connections with tunnel need to be in GUI mode with a proper connection to login node"
                            )
                            return

                    if 'host' in l:
                        hostname = l.split('=')[1].rstrip()
                    if 'port' in l:
                        port = l.split('=')[1].rstrip()
                        display = int(port) - 5900
                    if 'password' in l:
                        password = l.split('=')[1].rstrip()

                c = rcm.rcm_session(node=hostname,
                                    tunnel='y',
                                    display=display,
                                    nodelogin=node,
                                    username=user,
                                    vncpassword=password)
                my_rcm_client.vncsession(session=c)
            else:
                my_rcm_client.vncsession(configFile=filename)
            self.topFrame.connections.append(my_rcm_client)
            self.last_used_dir = os.path.dirname(filename)
Esempio n. 17
0
    def create_session(self,
                       sessionname='',
                       subnet='',
                       vncpassword='',
                       vncpassword_crypted=''):
        if self.active_scheduler is None:
            # if there is no active scheduler, return a dummy void sessions, otherwise excepion occur
            logger.error(
                "No active scheduler selected, returning void session")
            return rcm.rcm_session()
        session_id = self.session_manager.allocate_session(
            tag=self.active_scheduler.NAME)
        new_session = rcm.rcm_session(sessionid=session_id,
                                      state='init',
                                      username=self.session_manager.username,
                                      sessionname=sessionname,
                                      nodelogin=self.login_fullname,
                                      vncpassword=vncpassword_crypted)
        logger.debug("session\n---------------\n" +
                     new_session.get_string(format='json_indent') +
                     "\n-------------")
        logger.debug("login_name: " + self.get_login_node_name())
        printout = "submitting "
        if self.active_service:
            printout += "service: " + self.active_service.NAME
        if self.active_scheduler:
            printout += " with scheduler: " + self.active_scheduler.NAME
        logger.info(printout)

        new_session.hash['scheduler'] = self.active_scheduler.NAME
        new_session.hash['service'] = self.active_service.NAME

        new_session.serialize(
            self.session_manager.session_file_path(session_id))

        substitutions = {
            'RCM_SESSIONID': str(session_id),
            'RCM_SESSION_FOLDER':
            self.session_manager.session_folder(session_id),
            'RCM_JOBLOG': self.session_manager.session_jobout_path(session_id)
        }

        # assembly job script
        script = self.top_templates.get('SCRIPT', 'No script in templates')
        script = utils.StringTemplate(script).safe_substitute(substitutions)
        logger.info("job script content:\n--------------start------------\n" +
                    script + "\n-------------end--------------")

        service_logfile = self.top_templates.get('SERVICE.COMMAND.LOGFILE', '')
        service_logfile = utils.StringTemplate(
            service_logfile).safe_substitute(substitutions)
        logger.debug("service_logfile:\n" + service_logfile)

        # here we write the computed script into jobfile
        jobfile = self.session_manager.write_jobscript(session_id, script)

        # here we call the service preload command ( run on login node )
        substitutions = {
            'RCM_SESSION_FOLDER':
            self.session_manager.session_folder(session_id),
            'VNCPASSWORD': vncpassword
        }

        self.active_service.run_preload(substitutions=substitutions)

        # here we effectively submit jobfile
        jobid = self.active_scheduler.submit(jobfile=jobfile)

        # set status and jobid in curent session and write on disk
        new_session.hash['state'] = 'pending'
        new_session.hash['jobid'] = jobid
        new_session.hash['walltime'] = self.top_templates.get(
            'SCHEDULER.ACCOUNT.QUEUE.TIMELIMIT', utils.notimeleft_string)
        new_session.serialize(
            self.session_manager.session_file_path(session_id))
        logger.debug("serialized  session:\n---------------\n" +
                     new_session.get_string(format='json_indent') +
                     "\n-------------")

        try:
            scheduler_timeout = int(
                self.top_templates.get('SCHEDULER.ACCOUNT.QUEUE.QOS.TIMEOUT',
                                       '100'))
        except:
            scheduler_timeout = 100

        try:
            session_dict = self.active_service.search_port(
                service_logfile, timeout=scheduler_timeout)
        except Exception as e:
            self.active_scheduler.kill_job(jobid)
            raise e
        new_session.hash['state'] = 'valid'
        for k in session_dict:
            new_session.hash[k] = session_dict[k]
        new_session.serialize(
            self.session_manager.session_file_path(session_id))
        logger.debug("serialized  session:\n---------------\n" +
                     new_session.get_string(format='json_indent') +
                     "\n-------------")
        logger.info("return valid session job " + jobid + " session_dict: " +
                    str(session_dict))
        return new_session
Esempio n. 18
0
    def update_sessions(self,ss):
        self.connection_buttons=dict()
        self.sessions=ss
        if(self.f1):
            for child in self.f1.winfo_children():
                child.destroy()

        if len(self.sessions.array) == 0:
            w = Label(self.f1, text='No display available. Press \'NEW DISPLAY\' to create a new one.', padding=2)
            w.pack()
        else:
            f1 = self.f1
            labelList = ['state', 'session name', 'created', 'node', 'display', 'username', 'timeleft']
            c=rcm.rcm_session()
            i = 0
            for t in labelList:
                if t in c.hash.keys():
                    w = Label(f1, text=t.upper(), relief=RIDGE, state=ACTIVE, anchor=CENTER, padding=4, font=boldfont)
                    w.grid( row=0,column=i+3, sticky="we")

                    f1.columnconfigure ( i, minsize=80 )
                    i = i + 1
            
            for line, el in  enumerate( self.sessions.array ):
                if(self.client_connection):
                
                    def cmd(self=self, session=el):
                        if(self.debug): module_logger.debug( "killing session "+ str(sessionid))
                        self.kill(session)
                        
                    #if(el.hash['state'] == 'killed'):
                    #    continue

                    bk = Button( f1, text="KILL", padding=4,style='RCM.TButton', command=cmd)
                    bk.grid( row=line+1, column=2, pady=0)

                    def cmd_share(self=self, session=el):
                        self.asksaveasfilename(session)

                    bs = Button( f1, text="SHARE", padding=4,style='RCM.TButton', command=cmd_share)
                    bs.grid( row=line+1, column=1, pady=0)

                    bc = Button( f1, text="CONNECT", padding=4,style='RCM.TButton')
                    bc.grid( row=line+1, column=0, pady=0 )
                    sessionid = el.hash['sessionid']


                    def disable_cmd(self=self, sessionid=el.hash['sessionid'],active=True):
                        module_logger.info( "changing sessionid->"+sessionid+"< button to "+str(active))

                        if(active):
                            self.client_connection.activeConnectionsList.append(sessionid)
                        else:
                            if sessionid in self.client_connection.activeConnectionsList : self.client_connection.activeConnectionsList.remove(sessionid)
                            self.do_list_refresh=True
                        self.do_update_gui=True

                    #if el.hash['state'] == 'valid':
                    self.connection_buttons[sessionid]=(bc,disable_cmd)
                    #    print "self.connection_buttons -------> " + str(self.connection_buttons)

                    
                    def cmd_warn(self=self, session=el,disable_cmd=disable_cmd):
                            tkMessageBox.showwarning("Warning!", "Display created with a previous RCM client version. Can not start the connection.")
                    def cmd(self=self, session=el,disable_cmd=disable_cmd):
                        if(session.hash['sessionid'] in self.client_connection.activeConnectionsList):
                            tkMessageBox.showwarning("Warning!", "Already connected to session " +session.hash['sessionid'])
                        else:
                            if(self.debug): module_logger.info( "connecting to sessionid-->"+ str(session.hash['sessionid'])+"<")
                            self.startBusy("Connecting to the remote display...")
                            self.client_connection.vncsession(session,gui_cmd=disable_cmd)
                            self.after(4000,self.stopBusy)

                    if (el.hash.get('vncpassword','') == ''):
                        bc.configure( command=cmd_warn )
                    else:
                        bc.configure( command=cmd )
                    if sessionid in self.client_connection.activeConnectionsList:
                        bc.configure(state=DISABLED)
                    if (el.hash['state'] == 'pending'):
                        bc.configure(state=DISABLED)
                        bs.configure(state=DISABLED)

                i = 0
                for t in labelList:
                    if t in c.hash.keys():
                        lab = Label(f1, text=el.hash[t], relief=RIDGE, anchor=CENTER, padding=6)
                        if t == 'timeleft':
                            try:
                                timeleft = datetime.datetime.strptime(el.hash[t],"%H:%M:%S")
                                endTime = timeleft.replace(hour=0,minute=0,second=0)
                                limit = timeleft - endTime
                                if limit < datetime.timedelta(hours=1):
                                    lab.configure(foreground="red")
                            except:
                                pass
                        lab.grid( row=line+1, column=i+3,sticky="we" )
                        i = i + 1