def updateMaster(self, master): ''' Updates the information of the ros master. If the ROS master not exists, it will be added. @param master: the ROS master to update @type master: L{master_discovery_fkie.msg.ROSMaster} ''' # remove master, if his name was changed but not the ROS master URI root = self.invisibleRootItem() for i in reversed(range(root.rowCount())): masterItem = root.child(i) if masterItem.master.uri == master.uri and masterItem.master.name != master.name: root.removeRow(i) break # update or add a the item root = self.invisibleRootItem() doAddItem = True for i in range(root.rowCount()): masterItem = root.child(i) if (masterItem == master.name): # update item masterItem.master = master masterItem.updateMasterView(root) doAddItem = False break elif (masterItem > master.name): root.insertRow(i, MasterItem.getItemList(master, (nm.is_local(nm.nameres().getHostname(master.uri))))) doAddItem = False break if doAddItem: root.appendRow(MasterItem.getItemList(master, (nm.is_local(nm.nameres().getHostname(master.uri)))))
def updateMaster(self, master): ''' Updates the information of the ros master. If the ROS master not exists, it will be added. @param master: the ROS master to update @type master: L{master_discovery_fkie.msg.ROSMaster} ''' # remove master, if his name was changed but not the ROS master URI root = self.invisibleRootItem() for i in reversed(range(root.rowCount())): masterItem = root.child(i) if masterItem.master.uri == master.uri and masterItem.master.name != master.name: root.removeRow(i) try: del self.pyqt_workaround[masterItem.master.name] except: pass break # update or add a the item root = self.invisibleRootItem() doAddItem = True for i in range(root.rowCount()): masterItem = root.child(i, self.COL_NAME) if (masterItem == master.name): # update item masterItem.master = master masterItem.updateMasterView(root) doAddItem = False break elif (masterItem > master.name): mitem = MasterItem.getItemList( master, (nm.is_local(nm.nameres().getHostname(master.uri)))) self.pyqt_workaround[ master. name] = mitem # workaround for using with PyQt: store the python object to keep the defined attributes in the MasterItem subclass root.insertRow(i, mitem) mitem[self.COL_NAME].parent_item = root doAddItem = False break if doAddItem: mitem = MasterItem.getItemList( master, (nm.is_local(nm.nameres().getHostname(master.uri)))) self.pyqt_workaround[ master. name] = mitem # workaround for using with PyQt: store the python object to keep the defined attributes in the MasterItem subclass root.appendRow(mitem) mitem[self.COL_NAME].parent_item = root
def _resolve_abs_paths(cls, value, host, user, pw, auto_pw_request): ''' Replaces the local absolute path by remote absolute path. Only valid ROS package paths are resolved. @return: value, is absolute path, remote package found (ignore it on local host or if is not absolute path!), package name (if absolute path and remote package NOT found) ''' if isinstance(value, types.StringTypes) and value.startswith('/') and (os.path.isfile(value) or os.path.isdir(value)): if nm.is_local(host): return value, True, True, '' else: path = os.path.dirname(value) if os.path.isfile(value) else value package, package_path = package_name(path) if package: _, stdout, _, ok = nm.ssh().ssh_exec(host, ['rospack', 'find', package], user, pw, auto_pw_request, close_stdin=True, close_stderr=True) output = stdout.read() stdout.close() if ok: if output: value.replace(package_path, output) return value.replace(package_path, output.strip()), True, True, package else: # package on remote host not found! # TODO add error message # error = stderr.read() pass return value, True, False, '' else: return value, False, False, ''
def openLog(cls, nodename, host): ''' Opens the log file associated with the given node in a new terminal. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are @type host: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' title_opt = ' '.join(['"LOG', nodename, 'on', host, '"']) if nm.is_local(host): found = False screenLog = nm.screen().getScreenLogFile(node=nodename) if os.path.isfile(screenLog): cmd = nm.terminal_cmd([nm.LESS, screenLog], title_opt) rospy.loginfo("open log: %s", cmd) subprocess.Popen(shlex.split(cmd)) found = True #open roslog file roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(roslog): title_opt = title_opt.replace('LOG', 'ROSLOG') cmd = nm.terminal_cmd([nm.LESS, roslog], title_opt) rospy.loginfo("open ROS log: %s", cmd) subprocess.Popen(shlex.split(cmd)) found = True return found else: nm.ssh().ssh_x11_exec(host, [nm.STARTER_SCRIPT, '--show_screen_log', nodename], title_opt) nm.ssh().ssh_x11_exec(host, [nm.STARTER_SCRIPT, '--show_ros_log', nodename], title_opt.replace('LOG', 'ROSLOG')) return False
def getActiveScreens(cls, host, session='', user=None, pwd=None): ''' Returns the list with all compatible screen names. If the session is set to an empty string all screens will be returned. @param host: the host name or IP to search for the screen session. @type host: C{str} @param session: the name or the suffix of the screen session @type session: C{str} (Default: C{''}) @return: the list with session names @rtype: C{[str(session name), ...]} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' output = None result = [] if nm.is_local(host): out, out_err = cls.getLocalOutput([cls.SCREEN, '-ls']) output = out else: (stdin, stdout, stderr), ok = nm.ssh().ssh_exec(host, [cls.SCREEN, ' -ls']) if ok: stdin.close() # error = stderr.read() output = stdout.read() if not (output is None): splits = output.split() for i in splits: if i.count('.') > 0 and i.endswith(session): result.append(i) return result
def copylogPath2Clipboards(self, host, nodes=[], auto_pw_request=True, user=None, pw=None): if nm.is_local(host): if len(nodes) == 1: return nm.screen().getScreenLogFile(node=nodes[0]) else: return nm.screen().LOG_PATH else: request = '[]' if len(nodes) != 1 else nodes[0] try: output, error, ok = nm.ssh().ssh_exec( host, [nm.STARTER_SCRIPT, '--ros_log_path', request], user, pw, auto_pw_request) if ok: return output else: raise StartException( str(''.join([ 'Get log path from "', host, '" failed:\n', error ]))) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError( e, cls.deleteLog, (nodename, host, auto_pw_request))
def _resolve_abs_paths(cls, value, host): ''' Replaces the local absolute path by remote absolute path. Only valid ROS package paths are resolved. @return: value, is absolute path, remote package found (ignore it on local host or if is not absolute path!), package name (if absolute path and remote package NOT found) ''' if isinstance(value, types.StringTypes) and value.startswith('/') and ( os.path.isfile(value) or os.path.isdir(value)): if nm.is_local(host): return value, True, True, '' else: # print "ABS PATH:", value, os.path.dirname(value) dir = os.path.dirname(value) if os.path.isfile( value) else value package, package_path = LaunchConfig.packageName(dir) if package: output, error, ok = nm.ssh().ssh_exec( host, ['rospack', 'find', package]) if ok: if output: # print " RESOLVED:", output # print " PACK_PATH:", package_path value.replace(package_path, output) # print " RENAMED:", value.replace(package_path, output.strip()) return value.replace( package_path, output.strip()), True, True, package else: # package on remote host not found! # TODO add error message # error = stderr.read() pass return value, True, False, '' else: return value, False, False, ''
def openScreenTerminal(cls, host, screen_name, nodename, user=None): ''' Open the screen output in a new terminal. @param host: the host name or ip where the screen is running. @type host: C{str} @param screen_name: the name of the screen to show @type screen_name: C{str} @param nodename: the name of the node is used for the title of the terminal @type nodename: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' #create a title of the terminal # pid, session_name = cls.splitSessionName(screen_name) title_opt = 'SCREEN %s on %s' % (nodename, host) if nm.is_local(host): cmd = nm.settings().terminal_cmd([cls.SCREEN, '-x', screen_name], title_opt) rospy.loginfo("Open screen terminal: %s", cmd) ps = subprocess.Popen(shlex.split(cmd)) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: ps = nm.ssh().ssh_x11_exec(host, [cls.SCREEN, '-x', screen_name], title_opt, user) rospy.loginfo("Open remote screen terminal: %s", ps) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start()
def _getActiveScreens(cls, host, session='', auto_pw_request=True, user=None, pwd=None): ''' Returns the list with all compatible screen names. If the session is set to an empty string all screens will be returned. @param host: the host name or IP to search for the screen session. @type host: C{str} @param session: the name or the suffix of the screen session @type session: C{str} (Default: C{''}) @return: the list with session names @rtype: C{[str(session name), ...]} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' output = None result = [] if nm.is_local(host): output = cls.getLocalOutput([cls.SCREEN, '-ls']) else: _, stdout, _, _ = nm.ssh().ssh_exec(host, [cls.SCREEN, ' -ls'], user, pwd, auto_pw_request, close_stdin=True, close_stderr=True) output = stdout.read() stdout.close() if output: splits = output.split() for i in splits: if i.count('.') > 0 and i.endswith(session) and i.find('._') >= 0: result.append(i) return result
def deleteLog(cls, nodename, host, auto_pw_request=False, user=None, pw=None): ''' Deletes the log file associated with the given node. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are to delete @type host: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' rospy.loginfo("delete log for '%s' on '%s'", str(nodename), str(host)) if nm.is_local(host): screenLog = nm.screen().getScreenLogFile(node=nodename) pidFile = nm.screen().getScreenPidFile(node=nodename) roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(screenLog): os.remove(screenLog) if os.path.isfile(pidFile): os.remove(pidFile) if os.path.isfile(roslog): os.remove(roslog) else: try: # output ignored: output, error, ok nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--delete_logs', nodename], user, pw, auto_pw_request, close_stdin=True, close_stdout=True, close_stderr=True) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.deleteLog, (nodename, host, auto_pw_request))
def openScreenTerminal(cls, host, screen_name, nodename, user=None): ''' Open the screen output in a new terminal. @param host: the host name or ip where the screen is running. @type host: C{str} @param screen_name: the name of the screen to show @type screen_name: C{str} @param nodename: the name of the node is used for the title of the terminal @type nodename: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' #create a title of the terminal # pid, session_name = cls.splitSessionName(screen_name) title_opt = ' '.join(['"SCREEN', nodename, 'on', host, '"']) if nm.is_local(host): cmd = nm.terminal_cmd([cls.SCREEN, '-x', screen_name], title_opt) rospy.loginfo("Open screen terminal: %s", cmd) ps = subprocess.Popen(shlex.split(cmd)) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: ps = nm.ssh().ssh_x11_exec(host, [cls.SCREEN, '-x', screen_name], title_opt) rospy.loginfo("Open remote screen terminal: %s", ps) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start()
def _resolve_abs_paths(cls, value, host): ''' Replaces the local absolute path by remote absolute path. Only valid ROS package paths are resolved. @return: value, is absolute path, remote package found (ignore it on local host or if is not absolute path!), package name (if absolute path and remote package NOT found) ''' if isinstance(value, types.StringTypes) and value.startswith('/') and (os.path.isfile(value) or os.path.isdir(value)): if nm.is_local(host): return value, True, True, '' else: # print "ABS PATH:", value, os.path.dirname(value) dir = os.path.dirname(value) if os.path.isfile(value) else value package, package_path = LaunchConfig.packageName(dir) if package: (stdin, stdout, stderr), ok = nm.ssh().ssh_exec(host, ['rospack', 'find', package]) if ok: stdin.close() output = stdout.read() if output: # print " RESOLVED:", output # print " PACK_PATH:", package_path value.replace(package_path, output) # print " RENAMED:", value.replace(package_path, output.strip()) return value.replace(package_path, output.strip()), True, True, package else: # package on remote host not found! # TODO add error message # error = stderr.read() pass return value, True, False, '' else: return value, False, False, ''
def kill(self, host, pid): ''' Kills the process with given process id on given host. @param host: the name or address of the host, where the process must be killed. @type host: C{str} @param pid: the process id @type pid: C{int} @raise StartException: on error @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' if nm.is_local(host): import signal os.kill(pid, signal.SIGKILL) rospy.loginfo("kill: %s", str(pid)) else: # kill on a remote machine cmd = ['kill -9', str(pid)] rospy.loginfo("kill remote: %s", ' '.join(cmd)) (stdin, stdout, stderr), ok = nm.ssh().ssh_exec(host, cmd) if ok: stdin.close() error = stderr.read() if error: rospy.logwarn("ERROR while kill %s: %s", str(pid), error) raise nm.StartException( str(''.join( ['The host "', host, '" reports:\n', error]))) output = stdout.read() if output: rospy.logdebug("STDOUT while kill %s: %s", str(pid), output)
def killScreens(cls, node, host, auto_ok_request=True, user=None, pw=None): ''' Searches for the screen associated with the given node and kill this screens. @param node: the name of the node those screen output to show @type node: C{str} @param host: the host name or ip where the screen is running @type host: C{str} ''' if node is None or len(node) == 0: return False try: # get the available screens screens = cls._getActiveScreens(host, cls.createSessionName(node), auto_ok_request, user=user, pwd=pw) # user=user, pwd=pwd if screens: do_kill = True if auto_ok_request: from node_manager_fkie.detailed_msg_box import MessageBox result = MessageBox.question(None, "Kill SCREENs?", '\n'.join(screens), buttons=MessageBox.Ok | MessageBox.Cancel) if result == MessageBox.Ok: do_kill = True if do_kill: for s in screens: pid, _, _ = s.partition('.') if pid: try: nm.starter()._kill_wo(host, int(pid), auto_ok_request, user, pw) except: import traceback rospy.logwarn("Error while kill screen (PID: %s) on host '%s': %s", utf8(pid), utf8(host), traceback.format_exc(1)) if nm.is_local(host): SupervisedPopen([cls.SCREEN, '-wipe'], object_id='screen -wipe', description="screen: clean up the socket with -wipe") else: nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe'], close_stdin=True, close_stdout=True, close_stderr=True) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.killScreens, (node, host, auto_ok_request))
def load(self, argv): ''' @param argv: the list with argv parameter needed to load the launch file. The name and value are separated by C{:=} @type argv: C{[str]} @return True, if the launch file was loaded @rtype boolean @raise LaunchConfigException: on load errors ''' try: roscfg = roslaunch.ROSLaunchConfig() loader = roslaunch.XmlLoader() self.argv = self.resolveArgs(argv) loader.load(self.Filename, roscfg, verbose=False, argv=self.argv) self.__roscfg = roscfg nm.file_watcher().add_launch(self.__masteruri, self.__launchFile, self.__launch_id, self.getIncludedFiles(self.Filename)) if not nm.is_local(nm.nameres().getHostname(self.__masteruri)): files = self.getIncludedFiles(self.Filename, regexp_list=[QRegExp("\\bdefault\\b"), QRegExp("\\bvalue=.*pkg:\/\/\\b"), QRegExp("\\bvalue=.*package:\/\/\\b"), QRegExp("\\bvalue=.*\$\(find\\b")]) nm.file_watcher_param().add_launch(self.__masteruri, self.__launchFile, self.__launch_id, files) except roslaunch.XmlParseException, e: test = list(re.finditer(r"environment variable '\w+' is not set", str(e))) message = str(e) if test: message = ''.join([message, '\n', 'environment substitution is not supported, use "arg" instead!']) raise LaunchConfigException(message)
def openLog(cls, nodename, host, user=None): ''' Opens the log file associated with the given node in a new terminal. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are @type host: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' rospy.loginfo("show log for '%s' on '%s'", str(nodename), str(host)) title_opt = 'LOG %s on %s'%(nodename, host) if nm.is_local(host): found = False screenLog = nm.screen().getScreenLogFile(node=nodename) if os.path.isfile(screenLog): cmd = nm.settings().terminal_cmd([nm.settings().log_viewer, screenLog], title_opt) rospy.loginfo("open log: %s", cmd) SupervisedPopen(shlex.split(cmd), id="Open log", description="Open log for '%s' on '%s'"%(str(nodename), str(host))) found = True #open roslog file roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(roslog): title_opt = title_opt.replace('LOG', 'ROSLOG') cmd = nm.settings().terminal_cmd([nm.settings().log_viewer, roslog], title_opt) rospy.loginfo("open ROS log: %s", cmd) SupervisedPopen(shlex.split(cmd), id="Open log", description="Open log for '%s' on '%s'"%(str(nodename), str(host))) found = True return found else: ps = nm.ssh().ssh_x11_exec(host, [nm.settings().start_remote_script, '--show_screen_log', nodename], title_opt, user) ps = nm.ssh().ssh_x11_exec(host, [nm.settings().start_remote_script, '--show_ros_log', nodename], title_opt.replace('LOG', 'ROSLOG'), user) return False
def updateTypeView(cls, service, item): ''' Updates the representation of the column contains the type of the service. @param service: the service data @type service: L{master_discovery_fkie.ServiceInfo} @param item: corresponding item in the model @type item: L{ServiceItem} ''' try: if service.isLocal and service.type: service_class = service.get_service_class(nm.is_local(nm.nameres().getHostname(service.uri))) item.setText(service_class._type) elif service.type: item.setText(service.type) else: item.setText('unknown type') # removed tooltip for clarity !!! # tooltip = '' # tooltip = ''.join([tooltip, '<h4>', service_class._type, '</h4>']) # tooltip = ''.join([tooltip, '<b><u>', 'Request', ':</u></b>']) # tooltip = ''.join([tooltip, '<dl><dt>', str(service_class._request_class.__slots__), '</dt></dl>']) # # tooltip = ''.join([tooltip, '<b><u>', 'Response', ':</u></b>']) # tooltip = ''.join([tooltip, '<dl><dt>', str(service_class._response_class.__slots__), '</dt></dl>']) # # item.setToolTip(''.join(['<div>', tooltip, '</div>'])) item.setToolTip('') except: if not service.isLocal: tooltip = ''.join(['<h4>', 'Service type is not available due to he running on another host.', '</h4>']) item.setToolTip(''.join(['<div>', tooltip, '</div>']))
def deleteLog(cls, nodename, host, auto_pw_request=False, user=None, pw=None): ''' Deletes the log file associated with the given node. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are to delete @type host: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' rospy.loginfo("delete log for '%s' on '%s'", utf8(nodename), utf8(host)) if nm.is_local(host): screenLog = nm.screen().getScreenLogFile(node=nodename) pidFile = nm.screen().getScreenPidFile(node=nodename) roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(screenLog): os.remove(screenLog) if os.path.isfile(pidFile): os.remove(pidFile) if os.path.isfile(roslog): os.remove(roslog) else: try: # output ignored: output, error, ok _, stdout, _, ok = nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--delete_logs', nodename], user, pw, auto_pw_request, close_stdin=True, close_stdout=False, close_stderr=True) if ok: stdout.readlines() stdout.close() except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.deleteLog, (nodename, host, auto_pw_request))
def deleteLog(cls, nodename, host): ''' Deletes the log file associated with the given node. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are to delete @type host: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' if nm.is_local(host): screenLog = nm.screen().getScreenLogFile(node=nodename) pidFile = nm.screen().getScreenPidFile(node=nodename) roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(screenLog): os.remove(screenLog) if os.path.isfile(pidFile): os.remove(pidFile) if os.path.isfile(roslog): os.remove(roslog) else: (stdin, stdout, stderr), ok = nm.ssh().ssh_exec( host, [nm.STARTER_SCRIPT, '--delete_logs', nodename]) if ok: stdin.close()
def _kill_wo(self, host, pid, auto_pw_request=False, user=None, pw=None): rospy.loginfo("kill %s on %s", str(pid), host) if nm.is_local(host): os.kill(pid, signal.SIGKILL) rospy.loginfo("kill: %s", str(pid)) else: # kill on a remote machine cmd = ['kill -9', str(pid)] _, stdout, stderr, ok = nm.ssh().ssh_exec(host, cmd, user, pw, False, close_stdin=True) if ok: output = stdout.read() error = stderr.read() stdout.close() stderr.close() if error: rospy.logwarn("ERROR while kill %s: %s", str(pid), error) raise StartException( str(''.join( ['The host "', host, '" reports:\n', error]))) if output: rospy.logdebug("STDOUT while kill %s on %s: %s", str(pid), host, output)
def killScreens(cls, host, node, user=None, parent=None): ''' Searches for the screen associated with the given node and kill this screens. @param host: the host name or ip where the screen is running @type host: C{str} @param node: the name of the node those screen output to show @type node: C{str} @param parent: the parent widget to show a message box, if a user input is required. @type parent: L{PySide.QtGui.QWidget} ''' if node is None or len(node) == 0: return False # get the available screens screens = cls.getActiveScreens(host, cls.createSessionName(node), user=user) #user=user, pwd=pwd if screens: from PySide import QtGui result = QtGui.QMessageBox.question(parent, "Kill SCREENs?", '\n'.join(screens), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok) if result & QtGui.QMessageBox.Ok: for s in screens: pid, sep, name = s.partition('.') if pid: try: nm.starter().kill(host, int(pid)) except: import traceback rospy.logwarn("Error while kill screen (PID: %s) on host '%s': %s", str(pid), str(host), str(traceback.format_exc())) if nm.is_local(host): ps = subprocess.Popen([cls.SCREEN, '-wipe']) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe'])
def openScreenTerminal(cls, host, screen_name, nodename, user=None): ''' Open the screen output in a new terminal. @param host: the host name or ip where the screen is running. @type host: C{str} @param screen_name: the name of the screen to show @type screen_name: C{str} @param nodename: the name of the node is used for the title of the terminal @type nodename: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' #create a title of the terminal # pid, session_name = cls.splitSessionName(screen_name) title_opt = 'SCREEN %s on %s' % (nodename, host) if nm.is_local(host): cmd = nm.settings().terminal_cmd([cls.SCREEN, '-x', screen_name], title_opt) rospy.loginfo("Open screen terminal: %s", cmd) SupervisedPopen(shlex.split(cmd), object_id=title_opt, description="Open screen terminal: %s" % title_opt) else: ps = nm.ssh().ssh_x11_exec(host, [cls.SCREEN, '-x', screen_name], title_opt, user) rospy.loginfo("Open remote screen terminal: %s", ps)
def kill(self, host, pid): ''' Kills the process with given process id on given host. @param host: the name or address of the host, where the process must be killed. @type host: C{str} @param pid: the process id @type pid: C{int} @raise StartException: on error @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' if nm.is_local(host): import signal os.kill(pid, signal.SIGKILL) rospy.loginfo("kill: %s", str(pid)) else: # kill on a remote machine cmd = ['kill -9', str(pid)] rospy.loginfo("kill remote on %s: %s", host, ' '.join(cmd)) (stdin, stdout, stderr), ok = nm.ssh().ssh_exec(host, cmd) if ok: stdin.close() error = stderr.read() if error: rospy.logwarn("ERROR while kill %s: %s", str(pid), error) raise nm.StartException(str(''.join(['The host "', host, '" reports:\n', error]))) output = stdout.read() if output: rospy.logdebug("STDOUT while kill %s on %s: %s", str(pid), host, output)
def killScreens(cls, node, host, auto_ok_request=True, user=None, pw=None): ''' Searches for the screen associated with the given node and kill this screens. @param node: the name of the node those screen output to show @type node: C{str} @param host: the host name or ip where the screen is running @type host: C{str} ''' if node is None or len(node) == 0: return False try: # get the available screens screens = cls._getActiveScreens(host, cls.createSessionName(node), auto_ok_request, user=user, pwd=pw) # user=user, pwd=pwd if screens: do_kill = True if auto_ok_request: try: from python_qt_binding.QtGui import QMessageBox except: from python_qt_binding.QtWidgets import QMessageBox result = QMessageBox.question( None, "Kill SCREENs?", '\n'.join(screens), QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Ok) if result & QMessageBox.Ok: do_kill = True if do_kill: for s in screens: pid, _, _ = s.partition('.') if pid: try: nm.starter()._kill_wo(host, int(pid), auto_ok_request, user, pw) except: import traceback rospy.logwarn( "Error while kill screen (PID: %s) on host '%s': %s", str(pid), str(host), traceback.format_exc(1)) if nm.is_local(host): SupervisedPopen( [cls.SCREEN, '-wipe'], object_id='screen -wipe', description="screen: clean up the socket with -wipe" ) else: nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe'], close_stdin=True, close_stdout=True, close_stderr=True) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.killScreens, (node, host, auto_ok_request))
def updateMaster(self, master): ''' Updates the information of the ros master. If the ROS master not exists, it will be added. @param master: the ROS master to update @type master: L{master_discovery_fkie.msg.ROSMaster} ''' # remove master, if his name was changed but not the ROS master URI root = self.invisibleRootItem() for i in reversed(range(root.rowCount())): masterItem = root.child(i) if masterItem.master.uri == master.uri and masterItem.master.name != master.name: root.removeRow(i) try: del self.pyqt_workaround[masterItem.master.name] except: pass break # update or add a the item root = self.invisibleRootItem() doAddItem = True for i in range(root.rowCount()): masterItem = root.child(i, self.COL_NAME) if (masterItem == master.name): # update item masterItem.master = master masterItem.updateMasterView(root) doAddItem = False break elif (masterItem > master.name): mitem = MasterItem.getItemList(master, (nm.is_local(nm.nameres().getHostname(master.uri)))) self.pyqt_workaround[master.name] = mitem # workaround for using with PyQt: store the python object to keep the defined attributes in the MasterItem subclass root.insertRow(i, mitem) mitem[self.COL_NAME].parent_item = root doAddItem = False break if doAddItem: mitem = MasterItem.getItemList(master, (nm.is_local(nm.nameres().getHostname(master.uri)))) self.pyqt_workaround[master.name] = mitem # workaround for using with PyQt: store the python object to keep the defined attributes in the MasterItem subclass root.appendRow(mitem) mitem[self.COL_NAME].parent_item = root
def _poweroff_wo(self, host, auto_pw_request=False, user=None, pw=None): if nm.is_local(host): rospy.logwarn("shutdown localhost localhost!") cmd = nm.settings().terminal_cmd(['sudo poweroff'], "poweroff") SupervisedPopen(shlex.split(cmd), object_id="poweroff", description="poweroff") else: rospy.loginfo("poweroff %s", host) # kill on a remote machine cmd = ['sudo poweroff'] _ = nm.ssh().ssh_exec(host, cmd, 'Shutdown %s' % host, user)
def _rosclean_wo(self, host, auto_pw_request=False, user=None, pw=None): if nm.is_local(host): rospy.loginfo("rosclean purge on localhost!") cmd = nm.settings().terminal_cmd(['rosclean purge -y'], "rosclean") SupervisedPopen(shlex.split(cmd), object_id="rosclean", description="rosclean") else: rospy.loginfo("rosclean %s", host) # kill on a remote machine cmd = ['rosclean purge -y'] _ = nm.ssh().ssh_x11_exec(host, cmd, 'rosclean purge on %s' % host, user)
def _poweroff_wo(self, host, auto_pw_request=False, user=None, pw=None): if nm.is_local(host): rospy.logwarn("shutdown localhost localhost!") cmd = nm.settings().terminal_cmd(['sudo poweroff'], "poweroff") SupervisedPopen(shlex.split(cmd), object_id="poweroff", description="poweroff") else: rospy.loginfo("poweroff %s", host) # kill on a remote machine cmd = ['sudo poweroff'] _ = nm.ssh().ssh_x11_exec(host, cmd, 'Shutdown %s' % host, user)
def openLog(cls, nodename, host): ''' Opens the log file associated with the given node in a new terminal. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are @type host: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' rospy.loginfo("show log for '%s' on '%s'", str(nodename), str(host)) title_opt = ' '.join(['"LOG', nodename, 'on', host, '"']) if nm.is_local(host): found = False screenLog = nm.screen().getScreenLogFile(node=nodename) if os.path.isfile(screenLog): cmd = nm.terminal_cmd([nm.LESS, screenLog], title_opt) rospy.loginfo("open log: %s", cmd) ps = subprocess.Popen(shlex.split(cmd)) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() found = True #open roslog file roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(roslog): title_opt = title_opt.replace('LOG', 'ROSLOG') cmd = nm.terminal_cmd([nm.LESS, roslog], title_opt) rospy.loginfo("open ROS log: %s", cmd) ps = subprocess.Popen(shlex.split(cmd)) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() found = True return found else: ps = nm.ssh().ssh_x11_exec( host, [nm.STARTER_SCRIPT, '--show_screen_log', nodename], title_opt) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() ps = nm.ssh().ssh_x11_exec( host, [nm.STARTER_SCRIPT, '--show_ros_log', nodename], title_opt.replace('LOG', 'ROSLOG')) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() return False
def _prepareROSMaster(cls, masteruri): if not masteruri: masteruri = roslib.rosenv.get_master_uri() #start roscore, if needed try: if not os.path.isdir(nm.ScreenHandler.LOG_PATH): os.makedirs(nm.ScreenHandler.LOG_PATH) socket.setdefaulttimeout(3) master = xmlrpclib.ServerProxy(masteruri) master.getUri(rospy.get_name()) except: # socket.setdefaulttimeout(None) # import traceback # print traceback.format_exc(1) # run a roscore from urlparse import urlparse master_host = urlparse(masteruri).hostname if nm.is_local(master_host, True): print "Start ROS-Master with", masteruri, "..." master_port = urlparse(masteruri).port new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri cmd_args = '%s roscore --port %d' % ( nm.ScreenHandler.getSceenCmd( '/roscore--%d' % master_port), master_port) print " %s" % cmd_args try: SupervisedPopen(shlex.split(cmd_args), env=new_env, id="ROSCORE", description="Start roscore") # wait for roscore to avoid connection problems while init_node result = -1 count = 1 while result == -1 and count < 11: try: print " retry connect to ROS master", count, '/', 10 master = xmlrpclib.ServerProxy(masteruri) result, _, _ = master.getUri( rospy.get_name()) #_:=uri, msg except: time.sleep(1) count += 1 if count >= 11: raise StartException( 'Cannot connect to the ROS-Master: ' + str(masteruri)) except Exception as e: import sys print >> sys.stderr, e raise else: raise Exception("ROS master '%s' is not reachable" % masteruri) finally: socket.setdefaulttimeout(None)
def _prepareROSMaster(cls, masteruri): if masteruri is None: masteruri = masteruri_from_ros() # start roscore, if needed try: if not os.path.isdir(nm.ScreenHandler.LOG_PATH): os.makedirs(nm.ScreenHandler.LOG_PATH) socket.setdefaulttimeout(3) master = xmlrpclib.ServerProxy(masteruri) master.getUri(rospy.get_name()) # restart ROSCORE on different masteruri?, not now... # master_uri = master.getUri(rospy.get_name()) # if masteruri != master_uri[2]: # # kill the local roscore... # raise except: # run a roscore master_host = get_hostname(masteruri) if nm.is_local(master_host, True): master_port = get_port(masteruri) new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri ros_hostname = NameResolution.get_ros_hostname(masteruri) if ros_hostname: new_env['ROS_HOSTNAME'] = ros_hostname cmd_args = '%s roscore --port %d' % (nm.ScreenHandler.getSceenCmd('/roscore--%d' % master_port), master_port) for n in [1, 2, 3, 4]: try: if n == 1: print("Launch ROS Master in screen ...") SupervisedPopen(shlex.split(cmd_args), env=new_env, object_id="ROSCORE", description="Start roscore") elif n == 2: print("ROS Master takes too long for start, wait for next 10 sec ...") elif n == 3: print("A really slow start, wait for last 10 sec ...") # wait for roscore to avoid connection problems while init_node result = -1 count = 1 while result == -1 and count < 11: try: master = xmlrpclib.ServerProxy(masteruri) result, _, _ = master.getUri(rospy.get_name()) # _:=uri, msg return except Exception: time.sleep(1) count += 1 if n == 4 and count >= 11: raise StartException('Cannot connect to ROS-Master: %s\n--> please run "roscore" manually!' % utf8(masteruri)) except Exception as e: raise Exception("Error while call '%s': %s" % (cmd_args, utf8(e))) else: raise Exception("ROS master '%s' is not reachable" % masteruri) finally: socket.setdefaulttimeout(None)
def updateMaster(self, master): ''' Updates the information of the ros master. If the ROS master not exists, it will be added. @param master: the ROS master to update @type master: L{master_discovery_fkie.msg.ROSMaster} ''' # remove master, if his name was changed but not the ROS master URI root = self.invisibleRootItem() for i in reversed(range(root.rowCount())): masterItem = root.child(i) if masterItem.master.uri == master.uri and masterItem.master.name != master.name: root.removeRow(i) break # update or add a the item root = self.invisibleRootItem() doAddItem = True for i in range(root.rowCount()): masterItem = root.child(i) if (masterItem == master.name): # update item masterItem.master = master masterItem.updateMasterView(root) doAddItem = False break elif (masterItem > master.name): mitem = MasterItem.getItemList( master, (nm.is_local(nm.nameres().getHostname(master.uri)))) root.insertRow(i, mitem) mitem[0].parent_item = root doAddItem = False break if doAddItem: mitem = MasterItem.getItemList( master, (nm.is_local(nm.nameres().getHostname(master.uri)))) root.appendRow(mitem) mitem[0].parent_item = root
def _prepareROSMaster(cls, masteruri): if masteruri is None: masteruri = masteruri_from_ros() #start roscore, if needed try: if not os.path.isdir(nm.ScreenHandler.LOG_PATH): os.makedirs(nm.ScreenHandler.LOG_PATH) socket.setdefaulttimeout(3) master = xmlrpclib.ServerProxy(masteruri) master.getUri(rospy.get_name()) # restart ROSCORE on different masteruri?, not now... # master_uri = master.getUri(rospy.get_name()) # if masteruri != master_uri[2]: # # kill the local roscore... # raise except: # socket.setdefaulttimeout(None) # import traceback # print traceback.format_exc(3) # run a roscore from urlparse import urlparse master_host = urlparse(masteruri).hostname if nm.is_local(master_host, True): master_port = urlparse(masteruri).port new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri ros_hostname = NameResolution.get_ros_hostname(masteruri) if ros_hostname: new_env['ROS_HOSTNAME'] = ros_hostname cmd_args = '%s roscore --port %d'%(nm.ScreenHandler.getSceenCmd('/roscore--%d'%master_port), master_port) try: SupervisedPopen(shlex.split(cmd_args), env=new_env, object_id="ROSCORE", description="Start roscore") # wait for roscore to avoid connection problems while init_node result = -1 count = 1 while result == -1 and count < 11: try: master = xmlrpclib.ServerProxy(masteruri) result, _, _ = master.getUri(rospy.get_name())#_:=uri, msg except: time.sleep(1) count += 1 if count >= 11: raise StartException('Cannot connect to the ROS-Master: '+ str(masteruri)) except Exception as e: import sys print >> sys.stderr, e raise else: raise Exception("ROS master '%s' is not reachable"%masteruri) finally: socket.setdefaulttimeout(None)
def killScreens(cls, node, host, auto_ok_request=True, user=None, pw=None): ''' Searches for the screen associated with the given node and kill this screens. @param node: the name of the node those screen output to show @type node: C{str} @param host: the host name or ip where the screen is running @type host: C{str} ''' if node is None or len(node) == 0: return False try: # get the available screens screens = cls.getActiveScreens(host, cls.createSessionName(node), user=user) #user=user, pwd=pwd if screens: do_kill = True if auto_ok_request: from python_qt_binding import QtGui result = QtGui.QMessageBox.question( None, "Kill SCREENs?", '\n'.join(screens), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok) if result & QtGui.QMessageBox.Ok: do_kill = True if do_kill: for s in screens: pid, _, _ = s.partition('.') if pid: try: nm.starter()._kill_wo(host, int(pid), auto_ok_request, user, pw) except: import traceback rospy.logwarn( "Error while kill screen (PID: %s) on host '%s': %s", str(pid), str(host), traceback.format_exc()) if nm.is_local(host): ps = subprocess.Popen([cls.SCREEN, '-wipe']) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: # output, error, ok = nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe']) nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe']) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.killScreens, (node, host, auto_ok_request))
def openLog(cls, nodename, host, user=None): ''' Opens the log file associated with the given node in a new terminal. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are @type host: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' rospy.loginfo("show log for '%s' on '%s'", str(nodename), str(host)) title_opt = ' '.join(['"LOG', nodename, 'on', host, '"']) if nm.is_local(host): found = False screenLog = nm.screen().getScreenLogFile(node=nodename) if os.path.isfile(screenLog): cmd = nm.terminal_cmd([nm.LESS, screenLog], title_opt) rospy.loginfo("open log: %s", cmd) ps = subprocess.Popen(shlex.split(cmd)) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() found = True #open roslog file roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(roslog): title_opt = title_opt.replace('LOG', 'ROSLOG') cmd = nm.terminal_cmd([nm.LESS, roslog], title_opt) rospy.loginfo("open ROS log: %s", cmd) ps = subprocess.Popen(shlex.split(cmd)) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() found = True return found else: ps = nm.ssh().ssh_x11_exec(host, [nm.STARTER_SCRIPT, '--show_screen_log', nodename], title_opt, user) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() ps = nm.ssh().ssh_x11_exec(host, [nm.STARTER_SCRIPT, '--show_ros_log', nodename], title_opt.replace('LOG', 'ROSLOG'), user) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() return False
def _kill_wo(self, host, pid, auto_pw_request=False, user=None, pw=None): rospy.loginfo("kill %s on %s", str(pid), host) if nm.is_local(host): os.kill(pid, signal.SIGKILL) rospy.loginfo("kill: %s", str(pid)) else: # kill on a remote machine cmd = ['kill -9', str(pid)] output, error, ok = nm.ssh().ssh_exec(host, cmd, user, pw, False) if ok: if error: rospy.logwarn("ERROR while kill %s: %s", str(pid), error) raise StartException(str(''.join(['The host "', host, '" reports:\n', error]))) if output: rospy.logdebug("STDOUT while kill %s on %s: %s", str(pid), host, output)
def __gt__(self, item): if isinstance(item, str) or isinstance(item, unicode): local = False try: local = nm.is_local(item) except: pass if self.local and not local: # local hosts are at the top return False return self.master.name.lower() > item.lower() elif not (item is None): if self.local and not item.local: # local hosts are at the top return False return self.master.name.lower() > item.master.name.lower() return False
def openLog(cls, nodename, host, user=None): ''' Opens the log file associated with the given node in a new terminal. @param nodename: the name of the node (with name space) @type nodename: C{str} @param host: the host name or ip where the log file are @type host: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' rospy.loginfo("show log for '%s' on '%s'", str(nodename), str(host)) title_opt = 'LOG %s on %s' % (nodename, host) if nm.is_local(host): found = False screenLog = nm.screen().getScreenLogFile(node=nodename) if os.path.isfile(screenLog): cmd = nm.settings().terminal_cmd( [nm.settings().log_viewer, screenLog], title_opt) rospy.loginfo("open log: %s", cmd) SupervisedPopen(shlex.split(cmd), id="Open log", description="Open log for '%s' on '%s'" % (str(nodename), str(host))) found = True #open roslog file roslog = nm.screen().getROSLogFile(nodename) if os.path.isfile(roslog): title_opt = title_opt.replace('LOG', 'ROSLOG') cmd = nm.settings().terminal_cmd( [nm.settings().log_viewer, roslog], title_opt) rospy.loginfo("open ROS log: %s", cmd) SupervisedPopen(shlex.split(cmd), id="Open log", description="Open log for '%s' on '%s'" % (str(nodename), str(host))) found = True return found else: ps = nm.ssh().ssh_x11_exec(host, [ nm.settings().start_remote_script, '--show_screen_log', nodename ], title_opt, user) ps = nm.ssh().ssh_x11_exec(host, [ nm.settings().start_remote_script, '--show_ros_log', nodename ], title_opt.replace('LOG', 'ROSLOG'), user) return False
def copylogPath2Clipboards(self, host, nodes=[], auto_pw_request=True, user=None, pw=None): if nm.is_local(host): if len(nodes) == 1: return nm.screen().getScreenLogFile(node=nodes[0]) else: return nm.screen().LOG_PATH else: request = '[]' if len(nodes) != 1 else nodes[0] try: output, error, ok = nm.ssh().ssh_exec(host, [nm.STARTER_SCRIPT, '--ros_log_path', request], user, pw, auto_pw_request) if ok: return output else: raise StartException(str(''.join(['Get log path from "', host, '" failed:\n', error]))) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.deleteLog, (nodename, host, auto_pw_request))
def _prepareROSMaster(cls, masteruri): if not masteruri: masteruri = roslib.rosenv.get_master_uri() #start roscore, if needed try: if not os.path.isdir(nm.ScreenHandler.LOG_PATH): os.makedirs(nm.ScreenHandler.LOG_PATH) socket.setdefaulttimeout(3) master = xmlrpclib.ServerProxy(masteruri) master.getUri(rospy.get_name()) except: # socket.setdefaulttimeout(None) # import traceback # print traceback.format_exc(1) # run a roscore from urlparse import urlparse master_host = urlparse(masteruri).hostname if nm.is_local(master_host, True): print "Start ROS-Master with", masteruri, "..." master_port = urlparse(masteruri).port new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri cmd_args = '%s roscore --port %d'%(nm.ScreenHandler.getSceenCmd('/roscore--%d'%master_port), master_port) print " %s"%cmd_args try: SupervisedPopen(shlex.split(cmd_args), env=new_env, id="ROSCORE", description="Start roscore") # wait for roscore to avoid connection problems while init_node result = -1 count = 1 while result == -1 and count < 11: try: print " retry connect to ROS master", count, '/', 10 master = xmlrpclib.ServerProxy(masteruri) result, _, _ = master.getUri(rospy.get_name())#_:=uri, msg except: time.sleep(1) count += 1 if count >= 11: raise StartException('Cannot connect to the ROS-Master: '+ str(masteruri)) except Exception as e: import sys print >> sys.stderr, e raise else: raise Exception("ROS master '%s' is not reachable"%masteruri) finally: socket.setdefaulttimeout(None)
def _killall_roscore_wo(self, host, auto_pw_request=False, user=None, pw=None): rospy.loginfo("killall roscore on %s", host) cmd = ['killall', 'roscore'] if nm.is_local(host): SupervisedPopen(cmd, object_id="killall roscore", description="killall roscore") else: # kill on a remote machine _, stdout, stderr, ok = nm.ssh().ssh_exec(host, cmd, user, pw, False, close_stdin=True) if ok: output = stdout.read() error = stderr.read() stdout.close() stderr.close() if error: rospy.logwarn("ERROR while killall roscore on %s: %s" % (host, error)) raise StartException('The host "%s" reports:\n%s' % (host, error)) if output: rospy.logdebug("STDOUT while killall roscore on %s: %s" % (host, output))
def copylogPath2Clipboards(cls, host, nodes=[], auto_pw_request=False, user=None, pw=None): if nm.is_local(host): if len(nodes) == 1: return nm.screen().getScreenLogFile(node=nodes[0]) else: return nm.screen().LOG_PATH else: request = '[]' if len(nodes) != 1 else nodes[0] try: socket.setdefaulttimeout(3) output, error, ok = nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--ros_log_path', request], user, pw, auto_pw_request) if ok: return output else: raise StartException(str(''.join(['Get log path from "', host, '" failed:\n', error]))) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.copylogPath2Clipboards, (host, nodes, auto_pw_request)) finally: socket.setdefaulttimeout(None)
def get_log_path(cls, host, nodes=[], auto_pw_request=False, user=None, pw=None): if nm.is_local(host): if len(nodes) == 1: return nm.screen().getScreenLogFile(node=nodes[0]) else: return nm.screen().LOG_PATH else: request = '[]' if len(nodes) != 1 else nodes[0] try: socket.setdefaulttimeout(3) _, stdout, _, ok = nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--ros_log_path', request], user, pw, auto_pw_request, close_stdin=True, close_stderr=True) if ok: output = stdout.read() stdout.close() return output.strip() else: raise StartException(utf8(''.join(['Get log path from "', host, '" failed']))) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.get_log_path, (host, nodes, auto_pw_request)) finally: socket.setdefaulttimeout(None)
def get_log_path(cls, host, nodes=[], auto_pw_request=False, user=None, pw=None): if nm.is_local(host): if len(nodes) == 1: return nm.screen().getScreenLogFile(node=nodes[0]) else: return nm.screen().LOG_PATH else: request = '[]' if len(nodes) != 1 else nodes[0] try: socket.setdefaulttimeout(3) _, stdout, _, ok = nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--ros_log_path', request], user, pw, auto_pw_request, close_stdin=True, close_stderr=True) if ok: output = stdout.read() stdout.close() return output.strip() else: raise StartException(str(''.join(['Get log path from "', host, '" failed']))) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.get_log_path, (host, nodes, auto_pw_request)) finally: socket.setdefaulttimeout(None)
def transfer_files(cls, host, path, auto_pw_request=False, user=None, pw=None): ''' Copies the given file to the remote host. Uses caching of remote paths. ''' # get package of the file if nm.is_local(host): # it's local -> no copy needed return (pkg_name, pkg_path) = package_name(os.path.dirname(path)) if pkg_name is not None: # get the subpath of the file subfile_path = path.replace(pkg_path, '') # get the path of the package on the remote machine try: output = '' error = '' ok = True if host in CACHED_PKG_PATH and pkg_name in CACHED_PKG_PATH[host]: output = CACHED_PKG_PATH[host][pkg_name] else: if host not in CACHED_PKG_PATH: CACHED_PKG_PATH[host] = dict() _, stdout, stderr, ok = nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--package', pkg_name], user, pw, auto_pw_request, close_stdin=True) output = stdout.read() error = stderr.read() stdout.close() stderr.close() if ok: if error: rospy.logwarn("ERROR while transfer %s to %s: %s", path, host, error) raise StartException(utf8(''.join(['The host "', host, '" reports:\n', error]))) if output: CACHED_PKG_PATH[host][pkg_name] = output nm.ssh().transfer(host, path, os.path.join(output.strip(), subfile_path.strip(os.sep)), user) else: raise StartException("Remote host no returned any answer. Is there the new version of node_manager installed?") else: raise StartException("Can't get path from remote host. Is there the new version of node_manager installed?") except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.transfer_files, (host, path, auto_pw_request))
def transfer_files(cls, host, path, auto_pw_request=False, user=None, pw=None): ''' Copies the given file to the remote host. Uses caching of remote paths. ''' # get package of the file if nm.is_local(host): # it's local -> no copy needed return (pkg_name, pkg_path) = package_name(os.path.dirname(path)) if pkg_name is not None: # get the subpath of the file subfile_path = path.replace(pkg_path, '') # get the path of the package on the remote machine try: output = '' error = '' ok = True if host in CACHED_PKG_PATH and pkg_name in CACHED_PKG_PATH[host]: output = CACHED_PKG_PATH[host][pkg_name] else: if host not in CACHED_PKG_PATH: CACHED_PKG_PATH[host] = dict() _, stdout, stderr, ok = nm.ssh().ssh_exec(host, [nm.settings().start_remote_script, '--package', pkg_name], user, pw, auto_pw_request, close_stdin=True) output = stdout.read() error = stderr.read() stdout.close() stderr.close() if ok: if error: rospy.logwarn("ERROR while transfer %s to %s: %s", path, host, error) raise StartException(str(''.join(['The host "', host, '" reports:\n', error]))) if output: CACHED_PKG_PATH[host][pkg_name] = output nm.ssh().transfer(host, path, os.path.join(output.strip(), subfile_path.strip(os.sep)), user) else: raise StartException("Remote host no returned any answer. Is there the new version of node_manager installed?") else: raise StartException("Can't get path from remote host. Is there the new version of node_manager installed?") except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.transfer_files, (host, path, auto_pw_request))
def killScreens(cls, node, host, auto_ok_request=True, user=None, pw=None): ''' Searches for the screen associated with the given node and kill this screens. @param node: the name of the node those screen output to show @type node: C{str} @param host: the host name or ip where the screen is running @type host: C{str} ''' if node is None or len(node) == 0: return False try: # get the available screens screens = cls.getActiveScreens(host, cls.createSessionName(node), user=user) #user=user, pwd=pwd if screens: do_kill = True if auto_ok_request: from python_qt_binding import QtGui result = QtGui.QMessageBox.question(None, "Kill SCREENs?", '\n'.join(screens), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok) if result & QtGui.QMessageBox.Ok: do_kill = True if do_kill: for s in screens: pid, sep, name = s.partition('.') if pid: try: nm.starter()._kill_wo(host, int(pid), auto_ok_request, user, pw) except: import traceback rospy.logwarn("Error while kill screen (PID: %s) on host '%s': %s", str(pid), str(host), str(traceback.format_exc())) if nm.is_local(host): ps = subprocess.Popen([cls.SCREEN, '-wipe']) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: output, error, ok = nm.ssh().ssh_exec(host, [cls.SCREEN, '-wipe']) except nm.AuthenticationRequest as e: raise nm.InteractionNeededError(e, cls.killScreens, (node, host, auto_ok_request))
def openScreenTerminal(cls, host, screen_name, nodename, user=None): ''' Open the screen output in a new terminal. @param host: the host name or ip where the screen is running. @type host: C{str} @param screen_name: the name of the screen to show @type screen_name: C{str} @param nodename: the name of the node is used for the title of the terminal @type nodename: C{str} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' #create a title of the terminal # pid, session_name = cls.splitSessionName(screen_name) title_opt = 'SCREEN %s on %s'%(nodename, host) if nm.is_local(host): cmd = nm.settings().terminal_cmd([cls.SCREEN, '-x', screen_name], title_opt) rospy.loginfo("Open screen terminal: %s", cmd) SupervisedPopen(shlex.split(cmd), id=title_opt, description="Open screen terminal: %s"%title_opt) else: ps = nm.ssh().ssh_x11_exec(host, [cls.SCREEN, '-x', screen_name], title_opt, user) rospy.loginfo("Open remote screen terminal: %s", ps)
def ntpdate(cls, host, cmd, user=None, pw=None): ''' Opens the log file associated with the given node in a new terminal. @param host: the host name or ip where the log file are @type host: C{str} @param cmd: command to set the time @type cmd: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' mesg = "synchronize time on '%s' using '%s'" % (utf8(host), cmd) rospy.loginfo(mesg) title_opt = "ntpdate on %s" % str(host) # '%s on %s' % (cmd, host) if nm.is_local(host): cmd = nm.settings().terminal_cmd([cmd], title_opt, noclose=True) rospy.loginfo("EXEC: %s" % cmd) ps = SupervisedPopen(shlex.split(cmd), object_id=cmd, description=mesg) else: ps = nm.ssh().ssh_x11_exec(host, [cmd, ';echo "";echo "this terminal will be closed in 10 sec...";sleep 10'], title_opt, user) return False
def ntpdate(cls, host, cmd, user=None, pw=None): ''' Opens the log file associated with the given node in a new terminal. @param host: the host name or ip where the log file are @type host: C{str} @param cmd: command to set the time @type cmd: C{str} @return: C{True}, if a log file was found @rtype: C{bool} @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' mesg = "synchronize time on '%s' using '%s'" % (str(host), cmd) rospy.loginfo(mesg) title_opt = "ntpdate on %s" % str(host) # '%s on %s' % (cmd, host) if nm.is_local(host): cmd = nm.settings().terminal_cmd([cmd], title_opt, noclose=True) rospy.loginfo("EXEC: %s" % cmd) ps = SupervisedPopen(shlex.split(cmd), object_id=cmd, description=mesg) else: ps = nm.ssh().ssh_x11_exec(host, [cmd, ';echo "";echo "this terminal will be closed in 10 sec...";sleep 10'], title_opt, user) return False
def updateMaster(self, master): ''' Updates the information of the ros master. If the ROS master not exists, it will be added. @param master: the ROS master to update @type master: L{master_discovery_fkie.msg.ROSMaster} ''' # remove master, if his name was changed but not the ROS master URI root = self.invisibleRootItem() for i in reversed(range(root.rowCount())): masterItem = root.child(i) if masterItem.master.uri == master.uri and masterItem.master.name != master.name: root.removeRow(i) try: del self.pyqt_workaround[masterItem.master.name] except: pass break # update or add a the item root = self.invisibleRootItem() doAddItem = True is_local = nm.is_local(nm.nameres().getHostname(master.uri)) for index in range(root.rowCount()): masterItem = root.child(index, self.COL_NAME) if (masterItem == master.name): # update item masterItem.master = master masterItem.updateMasterView(root) doAddItem = False break elif (masterItem > master.name): self.addRow(master, is_local, root, index) doAddItem = False break if doAddItem: self.addRow(master, is_local, root, -1)
def on_save_profile(self, masteruri='', path=None): ''' Saves the current environment to a node manager profile. :param path: the pach the file to save :type path: str :param masteruri: If not empty, save the profile only for given master :type masteruri: str ''' try: if path is None: path = self.get_profile_file() if path is None: return rospy.loginfo("Save profile %s" % path) import yaml content = {} for muri, master in self._main_window.masters.items(): if not masteruri or masteruri == muri: running_nodes = master.getRunningNodesIfLocal() configs = {} md_param = {} ms_param = {} zc_param = {} smuri = muri addr = nm.nameres().address(smuri) hostname = get_hostname(smuri) mastername = '' if nm.is_local(addr): smuri = smuri.replace(hostname, '$LOCAL$') addr = '$LOCAL$' else: mastername = nm.nameres().mastername( smuri, nm.nameres().address(smuri)) for node_name in running_nodes.keys(): node_items = master.getNode(node_name) for node in node_items: if node.is_running( ) and node.launched_cfg is not None: # node.has_launch_cfgs(node.cfgs): cfg = node.launched_cfg if isinstance(node.launched_cfg, (str, unicode)): # it is default config cfg = node.launched_cfg.replace( "/%s" % hostname, '/$LOCAL$').rstrip('/run') else: # it is a loaded launch file, get the filename cfg = to_url(node.launched_cfg.Filename) if cfg not in configs: configs[cfg] = {'nodes': []} configs[cfg]['nodes'].append(node_name) elif node_name.endswith('master_discovery'): md_param = get_rosparam( 'master_discovery', muri) elif node_name.endswith('master_sync'): ms_param = get_rosparam('master_sync', muri) elif node_name.endswith('zeroconf'): zc_param = get_rosparam('zeroconf', muri) elif node_name.endswith('default_cfg'): # store parameter for default configuration nn = node_name.replace("/%s" % hostname, '/$LOCAL$') if nn not in configs: configs[nn] = {'nodes': []} configs[nn]['params'] = get_rosparam( node_name, muri) configs[nn]['default'] = True # store arguments for launchfiles for a, b in master.launchfiles.items(): resolved_a = to_url(a) if resolved_a not in configs: if resolved_a.endswith('default_cfg/run'): pass else: configs[resolved_a] = {} configs[resolved_a]['default'] = False configs[resolved_a]['argv'] = b.argv # fill the configuration content for yaml as dictionary content[smuri] = { 'mastername': mastername, 'address': addr, 'configs': configs } if md_param: content[smuri]['master_discovery'] = md_param if ms_param: content[smuri]['master_sync'] = ms_param if zc_param: content[smuri]['zeroconf'] = zc_param text = yaml.dump(content, default_flow_style=False) with open(path, 'w+') as f: f.write(text) except Exception as e: import traceback print traceback.format_exc(3) WarningMessageBox(QMessageBox.Warning, "Save profile Error", 'Error while save profile', str(e)).exec_()