def on_heartbeat_received(self, msg, address, is_multicast):
     force_update = False
     with self.mutex:
         try:
             hostname = self._hosts[address[0]]
         except Exception:
             self.status_text_signal.emit("resolve %s" % address[0])
             hostname = nm.nameres().hostname(utf8(address[0]),
                                              resolve=True)
             self._hosts[address[0]] = hostname
         try:
             (_version,
              _msg_tuple) = Discoverer.msg2masterState(msg, address)
             index = address[1] - self.default_port
             if index not in self._discovered:
                 self._discovered[index] = dict()
             self._discovered[index][address] = (hostname, time.time())
             if hostname not in self._msg_counts:
                 self._msg_counts[hostname] = 0
             self._msg_counts[hostname] += 1
             self._received_msgs += 1
             force_update = True
         except Exception:
             print(traceback.format_exc(1))
     if force_update:
         self._updateDisplay()
示例#2
0
 def __gt__(self, item):
     if isstring(item):
         local = False
         try:
             local = nm.is_local(get_hostname(nm.nameres().masteruri(item)))
         except Exception:
             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
示例#3
0
    def on_load_profile_file(self, grpc_url):
        '''
        Load the profile file.

        :param str grpc_url: the path of the profile file.
        '''
        _url, path = nmdurl.split(grpc_url)
        rospy.loginfo("Load profile %s" % path)
        self.progressBar.setValue(0)
        self.setVisible(True)
        self.setWindowTitle("%s profile started" %
                            os.path.basename(path).rstrip('.nmprofile'))
        hasstart = False
        if path:
            try:
                with open(path, 'r') as f:
                    content = ruamel.yaml.load(f.read(),
                                               Loader=ruamel.yaml.Loader)
                    if not isinstance(content, dict):
                        raise Exception("Mailformed profile: %s" %
                                        os.path.basename(path))
                    for muri, master_dict in content.items():
                        local_hostname = get_hostname(
                            self._main_window.getMasteruri())
                        rmuri = muri.replace('$LOCAL$', local_hostname)
                        master = self._main_window.getMaster(rmuri)
                        running_nodes = master.get_nodes_runningIfLocal()
                        usr = None
                        self._current_profile[rmuri] = set()
                        if 'user' in master_dict:
                            usr = master_dict['user']
                        if master_dict['mastername'] and master_dict[
                                'mastername']:
                            nm.nameres().add_master_entry(
                                master.masteruri, master_dict['mastername'],
                                master_dict['address'])
                        hostname = master_dict['address'].replace(
                            '$LOCAL$', local_hostname)
                        if 'master_discovery' in master_dict:
                            self._start_node_from_profile(
                                master,
                                hostname,
                                'fkie_master_discovery',
                                'master_discovery',
                                usr,
                                cfg=master_dict['master_discovery'])
                            self._current_profile[rmuri].add(
                                '/master_discovery')
                        if 'master_sync' in master_dict:
                            self._start_node_from_profile(
                                master,
                                hostname,
                                'fkie_master_sync',
                                'master_sync',
                                usr,
                                cfg=master_dict['master_sync'])
                            self._current_profile[rmuri].add('/master_sync')
                        if 'zeroconf' in master_dict:
                            self._start_node_from_profile(
                                master,
                                hostname,
                                'fkie_master_discovery',
                                'zeroconf',
                                usr,
                                cfg=master_dict['zeroconf'])
                            self._current_profile[rmuri].add('/zeroconf')
                        if 'node_manager_daemon' in master_dict:
                            self._start_node_from_profile(
                                master,
                                hostname,
                                'fkie_node_manager_daemon',
                                'node_manager_daemon',
                                usr,
                                cfg=master_dict['node_manager_daemon'])
                            self._current_profile[rmuri].add(
                                '/node_manager_daemon')
                        try:
                            do_start = []
                            do_not_stop = {
                                '/rosout',
                                rospy.get_name(), '/node_manager',
                                '/master_discovery', '/master_sync',
                                '*default_cfg', '/zeroconf',
                                '/node_manager_daemon'
                            }
                            configs = master_dict['configs']
                            conf_set = set()
                            for cfg_name, cmdict in configs.items():
                                cfg_name = cfg_name.replace(
                                    '$LOCAL$', local_hostname)
                                if cfg_name.startswith("pkg://"):
                                    cfg_name = resolve_pkg(
                                        cfg_name, nmdurl.nmduri(rmuri))
                                conf_set.add(cfg_name)
                                reload_launch = True
                                args = {}
                                if 'args' in cmdict:
                                    if 'args' in cmdict:
                                        args = cmdict['args']
                                    # do we need to load to load/reload launch file
                                    if cfg_name in master.launchfiles:
                                        reload_launch = set(
                                            master.launchfiles[cfg_name].args.
                                            itervalues()) != set(
                                                args.itervalues())
                                if reload_launch:
                                    self._main_window.launch_dock.load_file(
                                        cfg_name, args, master.masteruri)
                                if 'nodes' in cmdict:
                                    self._current_profile[rmuri].update(
                                        cmdict['nodes'])
                                    force_start = True
                                    cfg = cfg_name
                                    if not reload_launch:
                                        force_start = False
                                        do_not_stop.update(set(
                                            cmdict['nodes']))
                                        do_start.append(
                                            (reload_launch, cfg,
                                             cmdict['nodes'], force_start))
                                    else:
                                        do_start.append(
                                            (reload_launch, cfg,
                                             cmdict['nodes'], force_start))
                            # close unused configurations
                            for lfile in set(
                                    master.launchfiles.keys()) - conf_set:
                                master._close_cfg(lfile)
                            master.stop_nodes_by_name(running_nodes.keys(),
                                                      True, do_not_stop)
                            for reload_launch, cfg, nodes, force_start in do_start:
                                if nodes:
                                    hasstart = True
                                if reload_launch:
                                    master.start_nodes_after_load_cfg(
                                        cfg, list(nodes), force_start)
                                else:
                                    master.start_nodes_by_name(
                                        list(nodes), cfg, force_start)
                        except Exception as ml:
                            import traceback
                            print(utf8(traceback.format_exc(1)))
                            rospy.logwarn(
                                "Can not load launch file for %s: %s" %
                                (muri, utf8(ml)))
            except Exception as e:
                import traceback
                print(traceback.format_exc(1))
                MessageBox.warning(self, "Load profile error",
                                   'Error while load profile', utf8(e))
            if not hasstart:
                self.update_progress()
            else:
                QTimer.singleShot(1000, self.update_progress)
示例#4
0
    def on_save_profile(self, masteruri='', path=None):
        '''
        Saves the current environment to a node manager profile.

        :param str masteruri: If not empty, save the profile only for given master
        :param str path: the path of file to save. If None :meth:`get_profile_file` is called to get a path.
        '''
        try:
            if path is None:
                path = self.get_profile_file()
                if path is None:
                    return
            rospy.loginfo("Save profile %s" % path)
            content = {}
            for muri, master in self._main_window.masters.items():
                if not masteruri or masteruri == muri:
                    running_nodes = master.get_nodes_runningIfLocal()
                    configs = {}
                    md_param = {}
                    ms_param = {}
                    zc_param = {}
                    nmd_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):
                                # it is a loaded launch file, get the filename
                                cfg = to_pkg(node.launched_cfg)
                                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('node_manager_daemon'):
                                nmd_param = get_rosparam(
                                    'node_manager_daemon', muri)
                    # store arguments for launchfiles
                    for a, b in master.launchfiles.items():
                        resolved_a = to_pkg(a)
                        if resolved_a not in configs:
                            configs[resolved_a] = {}
                            configs[resolved_a]['default'] = False
                        configs[resolved_a]['args'] = b.args
                    # 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
                    if nmd_param:
                        content[smuri]['node_manager_daemon'] = nmd_param
            buf = ruamel.yaml.compat.StringIO()
            ruamel.yaml.dump(content, buf, Dumper=ruamel.yaml.RoundTripDumper)
            with open(path, 'w+') as f:
                f.write(buf.getvalue())
        except Exception as e:
            import traceback
            print(utf8(traceback.format_exc(3)))
            MessageBox.warning(self, "Save profile Error",
                               'Error while save profile', utf8(e))