def main(argv=sys.argv): try: options, args = parse_options(argv) if args: if options['show_screen_log']: logfile = nm.ScreenHandler.getScreenLogFile( node=options['show_screen_log']) p = subprocess.Popen( shlex.split(' '.join( [nm.Settings.LOG_VIEWER, str(logfile)]))) p.wait() elif options['show_ros_log']: logfile = nm.ScreenHandler.getROSLogFile( node=options['show_ros_log']) p = subprocess.Popen( shlex.split(' '.join( [nm.Settings.LOG_VIEWER, str(logfile)]))) p.wait() elif options['ros_log_path']: if options['ros_log_path'] == '[]': print nm.get_ros_home() else: print nm.ScreenHandler.getScreenLogFile( node=options['ros_log_path']) elif options['delete_logs']: logfile = nm.ScreenHandler.getScreenLogFile( node=options['delete_logs']) pidfile = nm.ScreenHandler.getScreenPidFile( node=options['delete_logs']) roslog = nm.ScreenHandler.getROSLogFile( node=options['delete_logs']) if os.path.isfile(logfile): os.remove(logfile) if os.path.isfile(pidfile): os.remove(pidfile) if os.path.isfile(roslog): os.remove(roslog) elif options['node_type'] and options['package'] and options[ 'node_name']: runNode(options['package'], options['node_type'], options['node_name'], args, options['prefix'], options['node_respawn'], options['masteruri'], loglevel=options['loglevel']) elif options['pidkill']: import signal os.kill(int(options['pidkill']), signal.SIGKILL) elif options['package']: print roslib.packages.get_pkg_dir(options['package']) else: parser = _get_optparse() parser.print_help() time.sleep(3) except Exception, e: print >> sys.stderr, e
def runNode(package, type, name, args, prefix='', repawn=False, masteruri=None): ''' Runs a ROS node. Starts a roscore if needed. ''' if not masteruri: masteruri = _masteruri_from_ros() #start roscore, if needed try: master = xmlrpclib.ServerProxy(masteruri) master.getUri('remote_nm') except: # run a roscore # at this time roscore is available to handle the warning message :/ # rospy.logwarn("no master found, starting new one") from urlparse import urlparse master_port = str(urlparse(masteruri).port) new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri cmd_args = [nm.ScreenHandler.getSceenCmd(''.join(['/roscore', '--', master_port])), 'roscore', '--port', master_port] subprocess.Popen(shlex.split(' '.join([str(c) for c in cmd_args])), env=new_env) # wait for roscore to avoid connection problems while init_node result = -1 count = 0 while result == -1 and count < 30: try: master = xmlrpclib.ServerProxy(masteruri) result, uri, msg = master.getUri('remote_nm') except: time.sleep(1) count += 1 # start node try: cmd = roslib.packages.find_node(package, type) except roslib.packages.ROSPkgException as e: # multiple nodes, invalid package raise nm.StartException(str(e)) # handle different result types str or array of string (electric / fuerte) import types if isinstance(cmd, types.StringTypes): cmd = [cmd] if cmd is None or len(cmd) == 0: raise nm.StartException(' '.join([type, 'in package [', package, '] not found!\n\nThe package was created?\nIs the binary executable?\n'])) # create string for node parameter. Set arguments with spaces into "'". node_params = ' '.join(''.join(["'", a, "'"]) if a.find(' ') > -1 else a for a in args[1:]) cmd_args = [nm.ScreenHandler.getSceenCmd(name), nm.RESPAWN_SCRIPT if repawn else '', prefix, cmd[0], node_params] print 'run on remote host:', ' '.join(cmd_args) # determine the current working path arg_cwd = getCwdArg('__cwd', args) cwd = nm.get_ros_home() if not (arg_cwd is None): if arg_cwd == 'ROS_HOME': cwd = nm.get_ros_home() elif arg_cwd == 'node': cwd = os.path.dirname(cmd[0]) # set the masteruri to launch with other one master new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd, env=new_env)
def runNode(package, type, name, args, prefix='', repawn=False, masteruri=None): ''' Runs a ROS node. Starts a roscore if needed. ''' if not masteruri: masteruri = nm.masteruri_from_ros() #start roscore, if needed nm.StartHandler._prepareROSMaster(masteruri) # start node try: cmd = roslib.packages.find_node(package, type) except roslib.packages.ROSPkgException as e: # multiple nodes, invalid package raise nm.StartException(str(e)) # handle different result types str or array of string (electric / fuerte) import types if isinstance(cmd, types.StringTypes): cmd = [cmd] if cmd is None or len(cmd) == 0: raise nm.StartException(' '.join([ type, 'in package [', package, '] not found!\n\nThe package was created?\nIs the binary executable?\n' ])) # create string for node parameter. Set arguments with spaces into "'". node_params = ' '.join(''.join(["'", a, "'"]) if a.find(' ') > -1 else a for a in args[1:]) cmd_args = [ nm.ScreenHandler.getSceenCmd(name), nm.RESPAWN_SCRIPT if repawn else '', prefix, cmd[0], node_params ] print 'run on remote host:', ' '.join(cmd_args) # determine the current working path arg_cwd = getCwdArg('__cwd', args) cwd = nm.get_ros_home() if not (arg_cwd is None): if arg_cwd == 'ROS_HOME': cwd = nm.get_ros_home() elif arg_cwd == 'node': cwd = os.path.dirname(cmd[0]) # set the masteruri to launch with other one master new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd, env=new_env)
def main(argv=sys.argv): try: # (options, args) = parser.parse_args(argv) options, args = parse_options(argv) # print "ARGS", args # print 'OPTIONS:', options if args: if options['show_screen_log']: logfile = nm.ScreenHandler.getScreenLogFile(node=options['show_screen_log']) p = subprocess.Popen(shlex.split(' '.join([nm.Settings.LOG_VIEWER, str(logfile)]))) p.wait() elif options['show_ros_log']: logfile = nm.ScreenHandler.getROSLogFile(node=options['show_ros_log']) p = subprocess.Popen(shlex.split(' '.join([nm.Settings.LOG_VIEWER, str(logfile)]))) p.wait() elif options['ros_log_path']: if options['ros_log_path'] == '[]': print nm.get_ros_home() else: print nm.ScreenHandler.getScreenLogFile(node=options['ros_log_path']) elif options['delete_logs']: logfile = nm.ScreenHandler.getScreenLogFile(node=options['delete_logs']) pidfile = nm.ScreenHandler.getScreenPidFile(node=options['delete_logs']) roslog = nm.ScreenHandler.getROSLogFile(node=options['delete_logs']) if os.path.isfile(logfile): os.remove(logfile) if os.path.isfile(pidfile): os.remove(pidfile) if os.path.isfile(roslog): os.remove(roslog) elif options['node_type'] and options['package'] and options['node_name']: runNode(options['package'], options['node_type'], options['node_name'], args, options['prefix'], options['node_respawn'], options['masteruri']) elif options['pidkill']: import signal os.kill(int(options['pidkill']), signal.SIGKILL) elif options['package']: print roslib.packages.get_pkg_dir(options['package']) else: parser = _get_optparse() parser.print_help() time.sleep(3) except Exception, e: print >> sys.stderr, e
def runNode(package, executable, name, args, prefix='', repawn=False, masteruri=None, loglevel=''): ''' Runs a ROS node. Starts a roscore if needed. ''' if not masteruri: masteruri = nm.masteruri_from_ros() # start roscore, if needed nm.StartHandler._prepareROSMaster(masteruri) # start node try: cmd = roslib.packages.find_node(package, executable) except roslib.packages.ROSPkgException as e: # multiple nodes, invalid package raise nm.StartException(str(e)) # handle different result types str or array of string (electric / fuerte) import types if isinstance(cmd, types.StringTypes): cmd = [cmd] if cmd is None or len(cmd) == 0: raise nm.StartException(' '.join([executable, 'in package [', package, '] not found!\n\nThe package was created?\nIs the binary executable?\n'])) # create string for node parameter. Set arguments with spaces into "'". node_params = ' '.join(''.join(["'", a, "'"]) if a.find(' ') > -1 else a for a in args[1:]) cmd_args = [nm.ScreenHandler.getSceenCmd(name), nm.Settings.RESPAWN_SCRIPT if repawn else '', prefix, cmd[0], node_params] print 'run on remote host:', ' '.join(cmd_args) # determine the current working path arg_cwd = getCwdArg('__cwd', args) cwd = nm.get_ros_home() if not (arg_cwd is None): if arg_cwd == 'ROS_HOME': cwd = nm.get_ros_home() elif arg_cwd == 'node': cwd = os.path.dirname(cmd[0]) # set the masteruri to launch with other one master new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri ros_hostname = nm.get_ros_hostname(masteruri) if ros_hostname: new_env['ROS_HOSTNAME'] = ros_hostname if loglevel: new_env['ROSCONSOLE_CONFIG_FILE'] = rosconsole_cfg_file(package) subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd, env=new_env) if len(cmd) > 1: rospy.logwarn('Multiple executables are found! The first one was started! Exceutables:\n%s', str(cmd))
def runNode(cls, node, launch_config, force2host=None, masteruri=None): ''' Start the node with given name from the given configuration. @param node: the name of the node (with name space) @type node: C{str} @param launch_config: the configuration containing the node @type launch_config: L{LaunchConfig} @param force2host: start the node on given host. @type force2host: L{str} @param masteruri: force the masteruri. @type masteruri: L{str} @raise StartException: if the screen is not available on host. @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' n = launch_config.getNode(node) if n is None: raise StartException(''.join(["Node '", node, "' not found!"])) env = list(n.env_args) prefix = n.launch_prefix if not n.launch_prefix is None else '' if prefix.lower() == 'screen' or prefix.lower().find('screen ') != -1: rospy.loginfo("SCREEN prefix removed before start!") prefix = '' args = [''.join(['__ns:=', n.namespace]), ''.join(['__name:=', n.name])] if not (n.cwd is None): args.append(''.join(['__cwd:=', n.cwd])) # add remaps for remap in n.remap_args: args.append(''.join([remap[0], ':=', remap[1]])) # get host of the node host = launch_config.hostname env_loader = '' if n.machine_name: machine = launch_config.Roscfg.machines[n.machine_name] host = machine.address #TODO: env-loader support? # if hasattr(machine, "env_loader") and machine.env_loader: # env_loader = machine.env_loader # set the host to the given host if not force2host is None: host = force2host if masteruri is None: masteruri = nm.nameres().masteruri(n.machine_name) # set the ROS_MASTER_URI if masteruri is None: masteruri = nm.masteruri_from_ros() env.append(('ROS_MASTER_URI', masteruri)) abs_paths = list() # tuples of (parameter name, old value, new value) not_found_packages = list() # package names # set the global parameter if not masteruri is None and not masteruri in launch_config.global_param_done: global_node_names = cls.getGlobalParams(launch_config.Roscfg) rospy.loginfo("Register global parameter:\n%s", '\n'.join(global_node_names)) abs_paths[len(abs_paths):], not_found_packages[len(not_found_packages):] = cls._load_parameters(masteruri, global_node_names, []) launch_config.global_param_done.append(masteruri) # add params if not masteruri is None: nodens = ''.join([n.namespace, n.name, '/']) params = dict() for param, value in launch_config.Roscfg.params.items(): if param.startswith(nodens): params[param] = value clear_params = [] for cparam in launch_config.Roscfg.clear_params: if cparam.startswith(nodens): clear_params.append(param) rospy.loginfo("Register parameter:\n%s", '\n'.join(params)) abs_paths[len(abs_paths):], not_found_packages[len(not_found_packages):] = cls._load_parameters(masteruri, params, clear_params) if nm.is_local(host): nm.screen().testScreen() try: cmd = roslib.packages.find_node(n.package, n.type) except (Exception, roslib.packages.ROSPkgException) as e: # multiple nodes, invalid package raise StartException(''.join(["Can't find resource: ", str(e)])) # handle diferent result types str or array of string import types if isinstance(cmd, types.StringTypes): cmd = [cmd] cmd_type = '' if cmd is None or len(cmd) == 0: raise nm.StartException(' '.join([n.type, 'in package [', n.package, '] not found!\n\nThe package was created?\nIs the binary executable?\n'])) if len(cmd) > 1: # Open selection for executables try: from PySide import QtGui item, result = QtGui.QInputDialog.getItem(None, ' '.join(['Multiple executables', n.type, 'in', n.package]), 'Select an executable', cmd, 0, False) if result: #open the selected screen cmd_type = item else: return except: raise nm.StartException('Multiple executables with same name in package found!') else: cmd_type = cmd[0] # determine the current working path, Default: the package of the node cwd = nm.get_ros_home() if not (n.cwd is None): if n.cwd == 'ROS_HOME': cwd = nm.get_ros_home() elif n.cwd == 'node': cwd = os.path.dirname(cmd_type) # else: # cwd = LaunchConfig.packageName(os.path.dirname(cmd_type)) cls._prepareROSMaster(masteruri) node_cmd = [nm.RESPAWN_SCRIPT if n.respawn else '', prefix, cmd_type] cmd_args = [nm.screen().getSceenCmd(node)] cmd_args[len(cmd_args):] = node_cmd cmd_args.append(str(n.args)) cmd_args[len(cmd_args):] = args rospy.loginfo("RUN: %s", ' '.join(cmd_args)) if not masteruri is None: new_env=dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri ps = subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd, env=new_env) else: ps = subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: # start remote if launch_config.PackageName is None: raise StartException(''.join(["Can't run remote without a valid package name!"])) # thus the prefix parameters while the transfer are not separated if prefix: prefix = ''.join(['"', prefix, '"']) # setup environment env_command = '' if env_loader: rospy.logwarn("env_loader in machine tag currently not supported") raise nm.StartException("env_loader in machine tag currently not supported") if env: env_command = "env "+' '.join(["%s=%s"%(k,v) for (k, v) in env]) startcmd = [env_command, nm.STARTER_SCRIPT, '--package', str(n.package), '--node_type', str(n.type), '--node_name', str(node), '--node_respawn true' if n.respawn else ''] if not masteruri is None: startcmd.append('--masteruri') startcmd.append(masteruri) if prefix: startcmd[len(startcmd):] = ['--prefix', prefix] #rename the absolute paths in the args of the node node_args = [] for a in n.args.split(): a_value, is_abs_path, found, package = cls._resolve_abs_paths(a, host) node_args.append(a_value) if is_abs_path: abs_paths.append(('ARGS', a, a_value)) if not found and package: not_found_packages.append(package) startcmd[len(startcmd):] = node_args startcmd[len(startcmd):] = args rospy.loginfo("Run remote on %s: %s", host, str(' '.join(startcmd))) (stdin, stdout, stderr), ok = nm.ssh().ssh_exec(host, startcmd) if ok: stdin.close() # stderr.close() # stdout.close() error = stderr.read() if error: rospy.logwarn("ERROR while start '%s': %s", node, error) raise nm.StartException(str(''.join(['The host "', host, '" reports:\n', error]))) output = stdout.read() if output: rospy.loginfo("STDOUT while start '%s': %s", node, output) # inform about absolute paths in parameter value if len(abs_paths) > 0: rospy.loginfo("Absolute paths found while start:\n%s", str('\n'.join([''.join([p, '\n OLD: ', ov, '\n NEW: ', nv]) for p, ov, nv in abs_paths]))) if len(not_found_packages) > 0: packages = '\n'.join(not_found_packages) raise nm.StartException(str('\n'.join(['Some absolute paths are not renamed because following packages are not found on remote host:', packages])))
def runNode(cls, node, launch_config, force2host=None, masteruri=None, auto_pw_request=False, user=None, pw=None): ''' Start the node with given name from the given configuration. @param node: the name of the node (with name space) @type node: C{str} @param launch_config: the configuration containing the node @type launch_config: L{LaunchConfig} @param force2host: start the node on given host. @type force2host: L{str} @param masteruri: force the masteruri. @type masteruri: L{str} @raise StartException: if the screen is not available on host. @raise Exception: on errors while resolving host @see: L{node_manager_fkie.is_local()} ''' #'print "RUN node", node, time.time() n = launch_config.getNode(node) if n is None: raise StartException(''.join(["Node '", node, "' not found!"])) env = list(n.env_args) prefix = n.launch_prefix if not n.launch_prefix is None else '' if prefix.lower() == 'screen' or prefix.lower().find('screen ') != -1: rospy.loginfo("SCREEN prefix removed before start!") prefix = '' args = [ ''.join(['__ns:=', n.namespace]), ''.join(['__name:=', n.name]) ] if not (n.cwd is None): args.append(''.join(['__cwd:=', n.cwd])) # add remaps for remap in n.remap_args: args.append(''.join([remap[0], ':=', remap[1]])) # get host of the node host = launch_config.hostname env_loader = '' if n.machine_name: machine = launch_config.Roscfg.machines[n.machine_name] host = machine.address #TODO: env-loader support? # if hasattr(machine, "env_loader") and machine.env_loader: # env_loader = machine.env_loader # set the host to the given host if not force2host is None: host = force2host if masteruri is None: masteruri = nm.nameres().masteruri(n.machine_name) # set the ROS_MASTER_URI if masteruri is None: masteruri = nm.masteruri_from_ros() env.append(('ROS_MASTER_URI', masteruri)) abs_paths = list() # tuples of (parameter name, old value, new value) not_found_packages = list() # package names # set the global parameter if not masteruri is None and not masteruri in launch_config.global_param_done: global_node_names = cls.getGlobalParams(launch_config.Roscfg) rospy.loginfo("Register global parameter:\n%s", '\n'.join(global_node_names)) abs_paths[len(abs_paths):], not_found_packages[ len(not_found_packages):] = cls._load_parameters( masteruri, global_node_names, []) launch_config.global_param_done.append(masteruri) # add params if not masteruri is None: nodens = ''.join([n.namespace, n.name, '/']) params = dict() for param, value in launch_config.Roscfg.params.items(): if param.startswith(nodens): params[param] = value clear_params = [] for cparam in launch_config.Roscfg.clear_params: if cparam.startswith(nodens): clear_params.append(param) rospy.loginfo("Register parameter:\n%s", '\n'.join(params)) abs_paths[len(abs_paths):], not_found_packages[ len(not_found_packages):] = cls._load_parameters( masteruri, params, clear_params) #'print "RUN prepared", node, time.time() if nm.is_local(host): nm.screen().testScreen() try: cmd = roslib.packages.find_node(n.package, n.type) except (Exception, roslib.packages.ROSPkgException) as e: # multiple nodes, invalid package raise StartException(''.join(["Can't find resource: ", str(e)])) # handle diferent result types str or array of string import types if isinstance(cmd, types.StringTypes): cmd = [cmd] cmd_type = '' if cmd is None or len(cmd) == 0: raise StartException(' '.join([ n.type, 'in package [', n.package, '] not found!\n\nThe package was created?\nIs the binary executable?\n' ])) if len(cmd) > 1: # Open selection for executables try: from PySide import QtGui item, result = QtGui.QInputDialog.getItem( None, ' '.join( ['Multiple executables', n.type, 'in', n.package]), 'Select an executable', cmd, 0, False) if result: #open the selected screen cmd_type = item else: return except: raise StartException( 'Multiple executables with same name in package found!' ) else: cmd_type = cmd[0] # determine the current working path, Default: the package of the node cwd = nm.get_ros_home() if not (n.cwd is None): if n.cwd == 'ROS_HOME': cwd = nm.get_ros_home() elif n.cwd == 'node': cwd = os.path.dirname(cmd_type) # else: # cwd = LaunchConfig.packageName(os.path.dirname(cmd_type)) cls._prepareROSMaster(masteruri) node_cmd = [ nm.RESPAWN_SCRIPT if n.respawn else '', prefix, cmd_type ] cmd_args = [nm.screen().getSceenCmd(node)] cmd_args[len(cmd_args):] = node_cmd cmd_args.append(str(n.args)) cmd_args[len(cmd_args):] = args rospy.loginfo("RUN: %s", ' '.join(cmd_args)) if not masteruri is None: new_env = dict(os.environ) new_env['ROS_MASTER_URI'] = masteruri ps = subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd, env=new_env) else: ps = subprocess.Popen(shlex.split(str(' '.join(cmd_args))), cwd=cwd) # wait for process to avoid 'defunct' processes thread = threading.Thread(target=ps.wait) thread.setDaemon(True) thread.start() else: #'print "RUN REMOTE", node, time.time() # start remote if launch_config.PackageName is None: raise StartException(''.join( ["Can't run remote without a valid package name!"])) # thus the prefix parameters while the transfer are not separated if prefix: prefix = ''.join(['"', prefix, '"']) # setup environment env_command = '' if env_loader: rospy.logwarn( "env_loader in machine tag currently not supported") raise StartException( "env_loader in machine tag currently not supported") if env: env_command = "env " + ' '.join( ["%s=%s" % (k, v) for (k, v) in env]) startcmd = [ env_command, nm.STARTER_SCRIPT, '--package', str(n.package), '--node_type', str(n.type), '--node_name', str(node), '--node_respawn true' if n.respawn else '' ] if not masteruri is None: startcmd.append('--masteruri') startcmd.append(masteruri) if prefix: startcmd[len(startcmd):] = ['--prefix', prefix] #rename the absolute paths in the args of the node node_args = [] try: for a in n.args.split(): a_value, is_abs_path, found, package = cls._resolve_abs_paths( a, host) node_args.append(a_value) if is_abs_path: abs_paths.append(('ARGS', a, a_value)) if not found and package: not_found_packages.append(package) startcmd[len(startcmd):] = node_args startcmd[len(startcmd):] = args rospy.loginfo("Run remote on %s: %s", host, str(' '.join(startcmd))) #'print "RUN CALL", node, time.time() output, error, ok = nm.ssh().ssh_exec(host, startcmd, user, pw, auto_pw_request) #'print "RUN CALLOK", node, time.time() except nm.AuthenticationRequest as e: raise nm.InteractionNeededError( e, cls.runNode, (node, launch_config, force2host, masteruri, auto_pw_request)) if ok: if error: rospy.logwarn("ERROR while start '%s': %s", node, error) raise StartException( str(''.join( ['The host "', host, '" reports:\n', error]))) if output: rospy.loginfo("STDOUT while start '%s': %s", node, output) # inform about absolute paths in parameter value if len(abs_paths) > 0: rospy.loginfo( "Absolute paths found while start:\n%s", str('\n'.join([ ''.join([p, '\n OLD: ', ov, '\n NEW: ', nv]) for p, ov, nv in abs_paths ]))) if len(not_found_packages) > 0: packages = '\n'.join(not_found_packages) raise StartException( str('\n'.join([ 'Some absolute paths are not renamed because following packages are not found on remote host:', packages ])))