コード例 #1
0
ファイル: watch_vision.py プロジェクト: anh0001/erojaya
def pingNode(node_name):
    max_count = None
    ID = '/rosnode'
    master = rosgraph.Master(ID)
    node_api = rosnode.get_api_uri(master, node_name)
    if not node_api:
        return False

    timeout = 3.

    socket.setdefaulttimeout(timeout)
    node = ServerProxy(node_api)
    lastcall = 0.
    count = 0
    acc = 0.
    try:
        while True:
            try:
                start = time.time()
                pid = _succeed(node.getPid(ID))
                end = time.time()

                dur = (end - start) * 1000.
                acc += dur
                count += 1

                # 1s between pings
            except socket.error as e:
                # 3786: catch ValueError on unpack as socket.error is not always a tuple
                try:
                    # #3659
                    errnum, msg = e
                    if errnum == -2:  #name/service unknown
                        p = urlparse.urlparse(node_api)
                    elif errnum == errno.ECONNREFUSED:
                        # check if node url has changed
                        new_node_api = rosnode.get_api_uri(master,
                                                           node_name,
                                                           skip_cache=True)
                        if not new_node_api:
                            return False
                        if new_node_api != node_api:
                            node_api = new_node_api
                            node = ServerProxy(node_api)
                            continue
                    else:
                        pass
                    return False
                except ValueError:
                    pass
            if max_count and count >= max_count:
                break
            time.sleep(1.0)
    except KeyboardInterrupt:
        pass

    return True
コード例 #2
0
def pingNode(node_name):
    max_count=None
    ID = '/rosnode'
    master = rosgraph.Master(ID)
    node_api = rosnode.get_api_uri(master,node_name)
    if not node_api:
        return False

    timeout = 3.

    socket.setdefaulttimeout(timeout)
    node = ServerProxy(node_api)
    lastcall = 0.
    count = 0
    acc = 0.
    try:
        while True:
            try:
                start = time.time()
                pid = _succeed(node.getPid(ID))
                end = time.time()

                dur = (end-start)*1000.
                acc += dur
                count += 1

                # 1s between pings
            except socket.error as e:
                # 3786: catch ValueError on unpack as socket.error is not always a tuple
                try:
                    # #3659
                    errnum, msg = e
                    if errnum == -2: #name/service unknown
                        p = urlparse.urlparse(node_api)
                    elif errnum == errno.ECONNREFUSED:
                        # check if node url has changed
                        new_node_api = rosnode.get_api_uri(master,node_name, skip_cache=True)
                        if not new_node_api:
                            return False
                        if new_node_api != node_api:
                            node_api = new_node_api
                            node = ServerProxy(node_api)
                            continue
                    else:
                        pass
                    return False
                except ValueError:
                    pass
            if max_count and count >= max_count:
                break
            time.sleep(1.0)
    except KeyboardInterrupt:
        pass
            
    return True
コード例 #3
0
    def get_node_info(self, event):
        """
        Get the list of all Nodes running on the host.
        Update the __node_list
        """
        if not self.__is_enabled:
            pass

        if self.__is_enabled:
            nodes = []
            for node_name in rosnode.get_node_names():
                try:
                    node_api = rosnode.get_api_uri(rospy.get_master(),
                                                   node_name,
                                                   skip_cache=True)
                    if self._id in node_api[2]:
                        nodes.append(node_name)
                except:
                    pass

            for node in nodes:
                if node not in self.__node_list:
                    """TODO currently not catching the exception here - master not running is a hard error so it does
                    not make sense to continue running.."""
                    node_api = rosnode.get_api_uri(rospy.get_master(),
                                                   node,
                                                   skip_cache=True)

                    try:
                        pid = self.get_node_pid(node_api, node)
                        if not pid:
                            continue
                        node_process = psutil.Process(pid)
                        new_node = NodeStatisticsHandler(
                            self._id, node, node_process)
                        self.__dict_lock.acquire(True)
                        self.__node_list[node] = new_node
                        self.__dict_lock.release()
                    except psutil.NoSuchProcess:
                        rospy.loginfo('pid of node %s could not be fetched' %
                                      node)
                        continue

            self.__dict_lock.acquire()
            to_remove = []
            for node_name in self.__node_list:
                if node_name not in nodes:
                    rospy.logdebug('removing %s from host' % node_name)
                    to_remove.append(node_name)
            for node_name in to_remove:
                self.remove_node(node_name)
            self.__dict_lock.release()
コード例 #4
0
def test_rosnode_started():
    master, roscore = pyros_utils.get_master()
    try:
        assert master.is_online()

        # hack needed to wait for master until fix for https://github.com/ros/ros_comm/pull/711 is released
        roslaunch.rlutil.get_or_generate_uuid(None, True)

        launch = roslaunch.scriptapi.ROSLaunch()
        launch.start()

        assert launch.started

        echo_node = roslaunch.core.Node('pyros_test', 'echo.py', name='echo')
        echo_process = launch.launch(echo_node)
        assert echo_process.is_alive()

        node_api = None
        with timeout(5) as t:
            while not t.timed_out and node_api is None:
                node_api = rosnode.get_api_uri(
                    master, 'echo'
                )  # would be good to find a way to do this without rosnode dependency
        assert node_api is not None

        launch.stop()

    finally:  # to make sure we always shutdown everything, even if test fails
        if roscore is not None:
            roscore.terminate()
        rospy.signal_shutdown('test_rosnode_started done')
        while roscore and roscore.is_alive():
            time.sleep(0.2)  # waiting for roscore to die
        assert not (roscore and master.is_online())
コード例 #5
0
    def run(self):
        ctx = self.ctx
        master = self.master
        actual_edges = self.actual_edges
        lock = self.lock
        n = self.n

        try:
            socket.setdefaulttimeout(3.0)
            node_api = rosnode.get_api_uri(master, n)
            if not node_api:
                ctx.errors.append(WtfError("Master does not have lookup information for node [%s]"%n))
                return
                
            node = xmlrpclib.ServerProxy(node_api)
            start = time.time()
            socket.setdefaulttimeout(3.0)            
            code, msg, bus_info = node.getBusInfo('/roswtf')
            end = time.time()
            with lock:
                if (end-start) > 1.:
                    ctx.warnings.append(WtfWarning("Communication with node [%s] is very slow"%n))
                if code != 1:
                    ctx.warnings.append(WtfWarning("Node [%s] would not return bus info"%n))
                elif not bus_info:
                    if not n in ctx.service_providers:
                        ctx.warnings.append(WtfWarning("Node [%s] is not connected to anything"%n))
                else:
                    edges = _businfo(ctx, n, bus_info)
                    actual_edges.extend(edges)
        except socket.error, e:
            pass #ignore as we have rules to catch this
コード例 #6
0
    def __init__(self):
        self.processes = dict()  # processes are NEVER removed from this dict
        self.master = rosnode.rosgraph.Master(rosnode.ID)
        node_api = rosnode.get_api_uri(self.master, rospy.get_name())
        self.own_hostname = rosnode.urlparse.urlparse(node_api).hostname

        self.node_infos_pub = rospy.Publisher('diag/node_infos', NodeInfoArray, queue_size=10)
コード例 #7
0
def get_process_ros(node_name, doprint=False):
    # get the node object from ros
    node_api = rosnode.get_api_uri(rospy.get_master(),
                                   node_name,
                                   skip_cache=True)[2]
    if not node_api:
        rospy.logerr("could not get api of node %s (%s)" %
                     (node_name, node_api))
        return False
    # now try to get the Pid of this process
    try:
        response = ServerProxy(node_api).getPid('/NODEINFO')
    except:
        rospy.logerr("failed to get of the pid of ros node %s (%s)" %
                     (node_name, node_api))
        return False
    # try to get the process using psutil
    try:
        process = psutil.Process(response[2])
        if doprint:
            rospy.loginfo("adding new node monitor %s (pid %d)" %
                          (node_name, process.pid))
        return process
    except:
        rospy.logerr("unable to open psutil object for %s" % (response[2]))
        return False
コード例 #8
0
    def get_node_names_and_pids(self):
        process_info = dict()

        node_names = rosnode.get_node_names()
        master = rosnode.rosgraph.Master(rosnode.ID)

        for node in node_names:
            try:
                node_api = rosnode.get_api_uri(master, node)

                # check if node can be found
                if not node_api:
                    rospy.logwarn("cannot find '" + node + "': unknown node")
                    continue

                hostname = rosnode.urlparse.urlparse(node_api).hostname

                # only take nodes, which are running on this machine
                if hostname != self.own_hostname:
                    continue

                # read out pid of node
                code, msg, pid = rosnode.ServerProxy(node_api).getPid(rosnode.ID)
                if code != 1:
                    rospy.logwarn("remote call failed: '" + node + "'")

                process_info[pid] = [node, hostname]

            except rosnode.ROSNodeIOException as error:
                rospy.logerr(error)
            except IOError as error:
                rospy.logerr(error)

        return process_info
コード例 #9
0
ファイル: nodes_graph.py プロジェクト: 130s/jsk_common
    def getnodepkg1(self, node_name):
        socket.setdefaulttimeout(1.0)
        master = roslib.scriptutil.get_master()
        node_api = rosnode.get_api_uri(master, node_name)
        host = node_api.split(':')[1].lstrip('/')
        node = xmlrpclib.ServerProxy(node_api)
        try:
            pid = rosnode._succeed(node.getPid(rosnode.ID))
        except socket.error:
            print("Communication with [%s=%s] failed!"%(node_name,node_api))
            return ['']

        cmd = ['ps','ww','--pid',str(pid)]
        if os.environ['ROS_IP'] != host and os.environ['ROS_HOSTNAME'] != host:
            ssh_target = self.user + '@' + host if self.user else hostname
            cmd = ['ssh', ssh_target] + cmd
            self.add_pkginfo_remote(host)

        ps = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
        res = ps[ps.find('/'):]
        node_args = res.split(' ')
        parsed = node_args[0].split('/')
        pkgnames = [pkg[0] for pkg in self.pkginfo[host]]
        result = [dirname for dirname in parsed if (dirname in pkgnames)]
        if len(result) == 0:
            result = ['']
        return result
コード例 #10
0
    def setUp(self):
        self.connection_cache_node = roslaunch.core.Node(
            'rocon_python_comms',
            'connection_cache.py',
            name='connection_cache',
            remap_args=[('~list', rospy.resolve_name('~connections_list')),
                        ('~diff', rospy.resolve_name('~connections_diff'))])
        # Easier to remap the node topic to the proxy ones, instead of the opposite, since there is no dynamic remapping.
        # However for normal usecase, remapping the proxy handles is preferable.
        try:
            self.connection_cache_proc = TestRosInterface.launch.launch(
                self.connection_cache_node)
        except roslaunch.RLException as rlexc:
            raise nose.SkipTest(
                "Connection Cache Node not found (part of rocon_python_comms pkg). Skipping test."
            )

        assert self.connection_cache_proc.is_alive()

        # wait for node to be started
        node_api = None
        with timeout(5) as t:
            while not t.timed_out and node_api is None:
                node_api = rosnode.get_api_uri(rospy.get_master(),
                                               'connection_cache')

        assert node_api is not None  # make sure the connection cache node is started before moving on.

        self.strpub = rospy.Publisher('/test/string', String, queue_size=1)
        self.emppub = rospy.Publisher('/test/empty', Empty, queue_size=1)

        self.interface = RosInterface(True)
コード例 #11
0
def get_exe_path(node_name):
    ID = '/NODEINFO'
    node_api = rosnode.get_api_uri(rospy.get_master(), node_name)
    code, msg, pid = client.ServerProxy(node_api[2]).getPid(ID)
    p = psutil.Process(pid)
    #print(p.name())
    return p.name()
コード例 #12
0
    def get_process_for_ros_node(self, node_name):
        target_node = None
        caller_id = '/experiment_manager'
        master = rosgraph.Master(caller_id)
        running_nodes = rosnode.get_node_names()
        for node in running_nodes:
            if node_name in node:
                if target_node is None:
                    target_node = node
                else:
                    rospy.logwarn("Multiple nodes found whose name "
                                  "contains " + node_name)
                    return None
        if target_node is None:
            rospy.logwarn("Could not find a node whose name contains " +
                          node_name)
            return None
        target_node_api = rosnode.get_api_uri(master, target_node)
        if not target_node_api:
            rospy.logwarn("Could not connect to " + target_node + "'s API")
            return None

        target_node = ServerProxy(target_node_api)
        target_node_pid = rosnode._succeed(
            target_node.getPid(caller_id))  # NOLINT
        rospy.loginfo('Registered %s node PID %i for resource '
                      'usage tracking' % (node_name, target_node_pid))
        return psutil.Process(target_node_pid)
コード例 #13
0
def main():
    rospy.init_node('start_user_mon', anonymous=True)
    try:
        from xmlrpc.client import ServerProxy
    except ImportError:
        from xmlrpclib import ServerProxy

    ID = '/rosnode'
    master = rosgraph.Master(ID, master_uri=None)
    global process, loc
    process = {}
    loc = rospy.get_param("/script_location")

    while not rospy.is_shutdown():
        nodes = rosnode.get_node_names()

        for node in nodes:
            name = " " + node
            name = name[2:]
            node_api = rosnode.get_api_uri(master, node)
            if not node_api:
                continue

            node = ServerProxy(node_api)
            pid = rosnode._succeed(node.getPid(ID))

            if process.has_key(pid):
                continue
            process[pid] = name
            print("nohup " + loc + "/usage-mon " + str(pid) + " " + name +
                  " &")
            os.system("nohup " + loc + "/usage-mon " + str(pid) + " " + name +
                      " &")
コード例 #14
0
    def setUp(self):
        # we need to speed fast enough for the tests to not fail on timeout...
        rospy.set_param('/connection_cache/spin_freq', 2)  # 2 Hz
        self.connection_cache_node = roslaunch.core.Node(
            'rocon_python_comms',
            'connection_cache.py',
            name='connection_cache',
            remap_args=[
                ('~list', '/pyros_ros/connections_list'),
                ('~diff', '/pyros_ros/connections_diff'),
            ])
        try:
            self.connection_cache_proc = self.launch.launch(
                self.connection_cache_node)
        except roslaunch.RLException as rlexc:
            raise nose.SkipTest(
                "Connection Cache Node not found (part of rocon_python_comms pkg). Skipping test."
            )

        node_api = None
        with Timeout(5) as t:
            while not t.timed_out and node_api is None:
                node_api = rosnode.get_api_uri(rospy.get_master(),
                                               'connection_cache')

        assert node_api is not None  # make sure the connection cache node is started before moving on.

        super(TestPyrosROSCache, self).setUp(enable_cache=True)
コード例 #15
0
    def run(self):
        ctx = self.ctx
        master = self.master
        actual_edges = self.actual_edges
        lock = self.lock
        n = self.n

        try:
            socket.setdefaulttimeout(3.0)
            node_api = rosnode.get_api_uri(master, n)
            if not node_api:
                ctx.errors.append(WtfError("Master does not have lookup information for node [%s]"%n))
                return
                
            node = xmlrpclib.ServerProxy(node_api)
            start = time.time()
            socket.setdefaulttimeout(3.0)            
            code, msg, bus_info = node.getBusInfo('/roswtf')
            end = time.time()
            with lock:
                if (end-start) > 1.:
                    ctx.warnings.append(WtfWarning("Communication with node [%s] is very slow"%n))
                if code != 1:
                    ctx.warnings.append(WtfWarning("Node [%s] would not return bus info"%n))
                elif not bus_info:
                    if not n in ctx.service_providers:
                        ctx.warnings.append(WtfWarning("Node [%s] is not connected to anything"%n))
                else:
                    edges = _businfo(ctx, n, bus_info)
                    actual_edges.extend(edges)
        except socket.error, e:
            pass #ignore as we have rules to catch this
コード例 #16
0
    def setUp(self):

        # first we setup our publishers and our node (used by rospy.resolve_name calls to remap topics)
        self.strpub = rospy.Publisher('/test/string', String, queue_size=1)
        self.emppub = rospy.Publisher('/test/empty', Empty, queue_size=1)

        self._master = rospy.get_master()
        self.service_if_pool = RosServiceIfPool()

        # we need to speed fast enough for the tests to not fail on timeout...
        rospy.set_param('/connection_cache/spin_freq', 2)  # 2 Hz
        self.connection_cache_node = roslaunch.core.Node('rocon_python_comms', 'connection_cache.py',
                                                         name='connection_cache',
                                                         remap_args=[('~list', rospy.resolve_name('~connections_list')),
                                                                     (
                                                                     '~diff', rospy.resolve_name('~connections_diff'))])

        # Easier to remap the node topic to the proxy ones, instead of the opposite, since there is no dynamic remapping.
        # However for normal usecase, remapping the proxy handles is preferable.
        try:
            self.connection_cache_proc = self.launch.launch(self.connection_cache_node)
        except roslaunch.RLException as rlexc:
            raise nose.SkipTest("Connection Cache Node not found (part of rocon_python_comms pkg). Skipping test.")

        assert self.connection_cache_proc.is_alive()

        # wait for node to be started
        node_api = None
        with Timeout(5) as t:
            while not t.timed_out and node_api is None:
                node_api = rosnode.get_api_uri(rospy.get_master(), 'connection_cache')

        assert node_api is not None  # make sure the connection cache node is started before moving on.

        self.connection_cache = connection_cache_proxy_create()
コード例 #17
0
    def getnodepkg1(self, node_name):
        socket.setdefaulttimeout(1.0)
        master = roslib.scriptutil.get_master()
        node_api = rosnode.get_api_uri(master, node_name)
        host = node_api.split(':')[1].lstrip('/')
        node = xmlrpclib.ServerProxy(node_api)
        try:
            pid = rosnode._succeed(node.getPid(rosnode.ID))
        except socket.error:
            print("Communication with [%s=%s] failed!" % (node_name, node_api))
            return ['']

        cmd = ['ps', 'ww', '--pid', str(pid)]
        if os.environ['ROS_IP'] != host and os.environ['ROS_HOSTNAME'] != host:
            ssh_target = self.user + '@' + host if self.user else hostname
            cmd = ['ssh', ssh_target] + cmd
            self.add_pkginfo_remote(host)

        ps = subprocess.Popen(cmd,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE).communicate()[0]
        res = ps[ps.find('/'):]
        node_args = res.split(' ')
        parsed = node_args[0].split('/')
        pkgnames = [pkg[0] for pkg in self.pkginfo[host]]
        result = [dirname for dirname in parsed if (dirname in pkgnames)]
        if len(result) == 0:
            result = ['']
        return result
コード例 #18
0
def get_node_list():
    """
    List all ROS Nodes
    Return: List containing ROS Nodes(name, pid)
    """
    rospy.logdebug("GET_NODE_LIST:")
    node_array_temp = rosnode.get_node_names()
    node_list = []
    j = 0
    for node_name in node_array_temp:
        try:
            node_api = rosnode.get_api_uri(rospy.get_master(), node_name)
            if socket.gethostname() not in node_api[2] and socket.gethostbyname(socket.gethostname()) not in node_api[2]:         # Only Get Info for Local Nodes
                continue

            code, msg, pid = xmlrpclib.ServerProxy(node_api[2]).getPid(ID)

            node_list.append(NODE(node_name, pid))
            rospy.logdebug("Node_name: " + node_list[j].name + " Node_PID: " + str(node_list[j].pid))
            j += 1
        except socket_error as serr:
             pass

    rospy.logdebug("=============================")
    return node_list
コード例 #19
0
    def get_node_info(self, event):
        """
        Get the list of all Nodes running on the host.
        Update the __node_list
        """
        if not self.__is_enabled:
            pass

        if self.__is_enabled:
            nodes = []
            for node_name in rosnode.get_node_names():
                try:
                    node_api = rosnode.get_api_uri(rospy.get_master(), node_name, skip_cache=True)
                    if self._id in node_api[2]:
                        nodes.append(node_name)
                except :
                    pass

            for node in nodes:
                if node not in self.__node_list:
                    """TODO currently not catching the exception here - master not running is a hard error so it does
                    not make sense to continue running.."""
                    node_api = rosnode.get_api_uri(rospy.get_master(), node, skip_cache=True)

                    try:
                        pid = self.get_node_pid(node_api, node)
                        if not pid:
                            continue
                        node_process = psutil.Process(pid)
                        new_node = NodeStatisticsHandler(
                            self._id, node, node_process)
                        self.__dict_lock.acquire(True)
                        self.__node_list[node] = new_node
                        self.__dict_lock.release()
                    except psutil.NoSuchProcess:
                        rospy.loginfo('pid of node %s could not be fetched' % node)
                        continue

            self.__dict_lock.acquire()
            to_remove = []
            for node_name in self.__node_list:
                if node_name not in nodes:
                    rospy.logdebug('removing %s from host' % node_name)
                    to_remove.append(node_name)
            for node_name in to_remove:
                self.remove_node(node_name)
            self.__dict_lock.release()
コード例 #20
0
ファイル: node_info.py プロジェクト: jonbinney/ros_monitor
    def get_node_info(self, node_name):
        node_api_uri = rosnode.get_api_uri(self.master, node_name)
        node = xmlrpclib.ServerProxy(node_api_uri)
        code, status_message, pid = node.getPid(rospy.get_name())

        netloc = urlparse.urlparse(node_api_uri).netloc
        host, api_port = netloc.split(':')

        return {'pid': pid, 'host': host}
コード例 #21
0
 def testNodePing(self, node_name):
     #Simplemente una funcion que devuelve bool de nodo si activo o no. SI NECESITA PALITO.
     master = rosgraph.Master('/rosnode')
     node_api = rosnode.get_api_uri(master, node_name)
     node_is_active = False
     if node_api:
         node_is_active = rosnode.rosnode_ping(
             node_name, 1, verbose=False)  #1: max ping request count
     return node_is_active
コード例 #22
0
def get_hostname_of_nodes(node_name,
                          master=rosnode.rosgraph.Master(rosnode.ID)):
    # check if master is available
    node_api = rosnode.get_api_uri(master, node_name, skip_cache=True)
    # check if node can be found
    if not node_api:
        raise rosnode.ROSNodeException("cannot find node '" + str(node_name) +
                                       "'; maybe its not running any more")

    return rosnode.urlparse.urlparse(node_api).hostname, node_api
コード例 #23
0
ファイル: impl.py プロジェクト: strawlab/rx
def get_info_text(selection_url):
    if selection_url is None:
        return ''
    if selection_url.startswith('node:'):
        try:
            node_name = selection_url[5:]
            master = roslib.scriptutil.get_master()
            node_api = rosnode.get_api_uri(master, node_name)
            return rosnode.get_node_info_description(node_name) + rosnode.get_node_connection_info_description(node_api)
        except rosnode.ROSNodeException, e:
            return "ERROR: %s"%str(e)
コード例 #24
0
def get_api_uri(master, caller_id):
    res = None
    while res is None:
        try:
            res = rosnode.get_api_uri(master, caller_id)
        except (socket.error, socket.herror, socket.gaierror) as e:
            rospy.logerr(
                "Pyros : got socket error calling get_api_uri({master}, {caller_id}). Retrying..."
                .format(**locals()))
            time.sleep(retry_timeout)
        else:
            return res
コード例 #25
0
ファイル: node_info.py プロジェクト: OSUrobotics/rostop_gui
 def get_node_info(self, node_name):
     node_api = rosnode.get_api_uri(rospy.get_master(), node_name)
     code, msg, pid = xmlrpclib.ServerProxy(node_api[2]).getPid(ID)
     if node_name in self.nodes:
         return self.nodes[node_name]
     else:
         try:
             p = psutil.Process(pid)
             self.nodes[node_name] = p
             return p
         except:
             return False
コード例 #26
0
 def get_node_info(self, node_name):
     node_api = rosnode.get_api_uri(rospy.get_master(), node_name)
     code, msg, pid = xmlrpclib.ServerProxy(node_api[2]).getPid(ID)
     if node_name in self.nodes:
         return self.nodes[node_name]
     else:
         try:
             p = psutil.Process(pid)
             self.nodes[node_name] = p
             return p
         except:
             return False
コード例 #27
0
ファイル: impl.py プロジェクト: imclab/rx
def get_info_text(selection_url):
    if selection_url is None:
        return ''
    if selection_url.startswith('node:'):
        try:
            node_name = selection_url[5:]
            master = rosgraph.Master('/rxgraph')
            node_api = rosnode.get_api_uri(master, node_name)
            return rosnode.get_node_info_description(
                node_name) + rosnode.get_node_connection_info_description(
                    node_api, master)
        except rosnode.ROSNodeException, e:
            return "ERROR: %s" % str(e)
コード例 #28
0
	def __init__(self, node_name):
		super(ProcessInfoDisplay, self).__init__()
		self.node_name = node_name
		self.node_api = rosnode.get_api_uri(rospy.get_master(), node_name)
		code, msg, self.pid = xmlrpclib.ServerProxy(self.node_api[2]).getPid(ID)
		try:
			self.process = psutil.Process(self.pid)
		except:
			print 'Bad PID: %s, name: %s, code: %s, msg: %s' % (self.pid, self.node_name, code, msg)
		self.initUI()
		self.timer = QtCore.QTimer(self.parent())
		self.timer.setInterval(1000)
		self.timer.timeout.connect(self.update_live_info)
		self.timer.start()
コード例 #29
0
 def nodes_ready():
     try:
         pids = {
             node: ServerProxy(
                 rosnode.get_api_uri(self.master, node,
                                     skip_cache=True)).getPid(self.name)
             for node in self.critical_nodes
         }
         if all([pid[0] for pid in pids.values()]):
             self.pids = {node: pid[2] for node, pid in pids.items()}
             return True
     except Exception:
         pass
     return False
コード例 #30
0
 def _init_node_table(self):
     
     nodes = rosnode._sub_rosnode_listnodes()
     nodelist = nodes.split('\n')
     
     for i in range(len(nodelist)):
         uri = rosnode.get_api_uri(self._master, nodelist[i])
         uri = uri.replace('/','')
         uri = '/'+uri.split(':')[1]
         self._add_node(uri, nodelist[i], i)
         
     self._qtable_index = len(nodelist)
     
     self._parent._table_monitor.resizeColumnsToContents()
     self._parent._table_monitor.resizeRowsToContents()
コード例 #31
0
    def start_eval(self):
        rate = rospy.Rate(2)
        while self.node_names is not None and not rospy.is_shutdown():
            rate.sleep()
            all_node_names = rosnode.get_node_names()
            for node_name in self.node_names:

                # check if node is running
                if node_name not in all_node_names:
                    rospy.logwarn('Node %s is not running' % node_name)
                    continue

                if node_name in self.node_pid:
                    continue

                rospy.loginfo('Looking for pid of node %s' % node_name)
                node_api = rosnode.get_api_uri(self.master, node_name)
                while True:
                    try:
                        node_con_info = rosnode.get_node_connection_info_description(
                            node_api, self.master)
                    except rosnode.ROSNodeIOException as e:
                        time.sleep(0.1)
                        rospy.loginfo_throttle(1, e)
                        continue
                    else:
                        break
                pid_match = re.search('Pid: (\d+)', node_con_info)
                if pid_match is None:
                    rospy.logwarn('Not found pid in description of node %s' %
                                  node_name)
                    continue
                self.node_pid[node_name] = int(pid_match.group(1))
                rospy.loginfo('Pid: %d' % self.node_pid[node_name])

            if len(self.node_pid) == len(self.node_names):
                break

        rospy.loginfo('Catched pid of every node, start evaluating')

        self._start_eval_threads()

        rospy.on_shutdown(self.stop_threads)

        self._plot_loop()
コード例 #32
0
 def discover_ros_nodes(self):
     self.nodes = {}
     node_names = rosnode.get_node_names()
     logging.info("Known nodes: " + ', '.join(node_names))
     for node_name in node_names:
         logging.info("   " + node_name)
         node_api = rosnode.get_api_uri(self.master, node_name)
         if not node_api:
             sys.stderr.write("    API URI: error (unknown node: %s)" %
                              str(node_name))
             continue
         logging.info("    API URI: " + node_api)
         node = ServerProxy(node_api)
         pid = rosnode._succeed(node.getPid(ID))
         logging.info("    PID    : " + str(pid))
         self.nodes[node_name] = {}
         self.nodes[node_name]['uri'] = node_api
         self.nodes[node_name]['pid'] = pid
コード例 #33
0
ファイル: node_info.py プロジェクト: codenotes/androidlibs2
 def get_node_info(self, node_name, skip_cache=False):
     node_api = rosnode.get_api_uri(rospy.get_master(), node_name, skip_cache=skip_cache)
     try:
         code, msg, pid = xmlrpclib.ServerProxy(node_api[2]).getPid(ID)
         if node_name in self.nodes:
             return self.nodes[node_name]
         else:
             try:
                 p = psutil.Process(pid)
                 self.nodes[node_name] = p
                 return p
             except:
                 return False
     except xmlrpclib.socket.error:
         if not skip_cache:
             return self.get_node_info(node_name, skip_cache=True)
         else:
             return False
コード例 #34
0
 def _update_node_table(self, alive_nodes):
     
     for node in alive_nodes.keys():
         if node not in self._table_dict.keys():
             uri = rosnode.get_api_uri(self._master, node)
             uri = uri.replace('/','')
             uri = '/'+uri.split(':')[1]
             self._add_node(uri, node, self._qtable_index)
             self._qtable_index += 1
     
     for node in self._table_dict.keys():
         if node not in alive_nodes.keys():
             
             self._table_dict[node].refresh(NodeItem.SHUTDOWN)
             
             if node not in self._deaded_nodes_alarm_register:
                 self._deaded_nodes_alarm_register.append(node)
                 self._parent.sendAlarm(Alarm.WARNING, "The node %s is dead !"%node)
     
     self._parent._table_monitor.resizeColumnsToContents()
     self._parent._table_monitor.resizeRowsToContents()
コード例 #35
0
 def get_node_info(self, node_name, skip_cache=False):
     node_api = rosnode.get_api_uri(
         rospy.get_master(), node_name, skip_cache=skip_cache
     )  #we need the PID but rosnode only provide XMLRPC URI
     try:
         code, msg, pid = ServerProxy(node_api[2]).getPid(
             ID)  #get PID via XMLRPC URI
         if node_name in self.nodes:
             return self.nodes[node_name]
         else:
             try:
                 p = psutil.Process(pid)
                 self.nodes[node_name] = p
                 return p
             except:
                 return False
     except (SocketError, IOError) as e:
         if not skip_cache:
             return self.get_node_info(node_name, skip_cache=True)
         else:
             return False
コード例 #36
0
    def setUp(self, cacheproxy=None):
        cacheproxy = cacheproxy or partial(rocon_python_comms.ConnectionCacheProxy, user_callback=self.user_cb, diff_opt=False, handle_actions=True)
        # We prepare our data structure for checking messages
        self.conn_list_msgq = deque()
        self.conn_diff_msgq = deque()
        self.spin_freq = 0.0
        self.cleanup_user_cb_ss()

        # Then we hookup to its topics and prepare a service proxy
        self.conn_list = rospy.Subscriber('/connection_cache/list', rocon_std_msgs.ConnectionsList, self._list_cb)
        self.conn_diff = rospy.Subscriber('/connection_cache/diff', rocon_std_msgs.ConnectionsDiff, self._diff_cb)
        self.set_spin = rospy.Publisher('/connection_cache/spin', rocon_std_msgs.ConnectionCacheSpin, queue_size=1)
        self.get_spin = rospy.Subscriber('/connection_cache/spin', rocon_std_msgs.ConnectionCacheSpin, self._spin_cb)

        # connecting to the master via proxy object
        self._master = rospy.get_master()

        self.node_default_spin_freq = 1  # change this to test different spin speed for the connection cache node
        rospy.set_param("/connection_cache/spin_freq", self.node_default_spin_freq)
        cache_node = roslaunch.core.Node('rocon_python_comms', 'connection_cache.py', name='connection_cache')
        self.cache_process = self.launch.launch(cache_node)

        node_api = None
        with timeout(5) as t:
            while not t.timed_out and node_api is None:
                node_api = rosnode.get_api_uri(self._master, 'connection_cache')

        assert node_api is not None  # make sure the connection cache node is started before moving on.

        # This will block until the cache node is available and has sent latched system state
        self.proxy = cacheproxy(
                list_sub='/connection_cache/list',
                diff_sub='/connection_cache/diff'
        )

        # Making sure System state is set after proxy initialized
        assert self.proxy._system_state is not None

        assert not t.timed_out
コード例 #37
0
ファイル: plugin_resources.py プロジェクト: chcorbato/atf
    def get_pid(name):
        try:
            pid = [p.pid for p in psutil.process_iter() if name in str(p.name)]
            return pid[0]
        except IndexError:
            pass

        try:
            node_id = '/NODEINFO'
            node_api = rosnode.get_api_uri(rospy.get_master(), name)
            code, msg, pid = xmlrpclib.ServerProxy(node_api[2]).getPid(node_id)
        except IOError:
            pass
        else:
            return pid

        try:
            return int(check_output(["pidof", "-s", name]))
        except CalledProcessError:
            pass

        rospy.logerr("Node '" + name + "' is not running!")
        return None
コード例 #38
0
ファイル: ftrace.py プロジェクト: hatem-darweesh/Autoware
  def getROSNodes(self):
    nodes = []
    try:
      nodenames = rosnode.get_node_names(None)
    except Exception as inst:
      print "ERROR:[getROSNodes-01] ", inst
      return nodes

    for nodename in nodenames:
      #rosnode.rosnode_info(nodename)
      api = rosnode.get_api_uri(rosgraph.Master("/rosnode"), nodename)
      if api:
        try:
          node = ServerProxy(api)
          code, msg, pid = node.getPid("/rosnode")
          if code == 1:
            res = re.search("^(.*)_[0-9]+$", nodename)
            while res is not None:
              nodename = res.group(1)
              res = re.search("^(.*)_[0-9]+$", nodename)
            nodes.append((nodename, pid))
        except:
          pass
    return nodes
コード例 #39
0
ファイル: node.py プロジェクト: OSUrobotics/rosh_core
 def _init_uri(self):
     if self._name and self._uri is None:
         try:
             self._uri = rosnode.get_api_uri(self._config.master.handle, self._name)
         except:
             pass