Example #1
0
Contact YarpNameSpace::detectNameServer(bool useDetectedServer,
                                        bool& scanNeeded,
                                        bool& serverUsed) {
    NameConfig nc;
    NameClient& nic = HELPER(this);
    nic.setFakeMode(false);
    nic.updateAddress();
    nic.setScan();
    if (useDetectedServer) {
        nic.setSave();
    }
    nic.send("ping", false);
    scanNeeded = nic.didScan();
    serverUsed = nic.didSave();

    Contact c = nic.getAddress();
    c.setName(nc.getNamespace().c_str());
    //Contact c = nic.getAddress().toContact();
    //    if (scanNeeded) {
    //        Address addr = nic.getAddress();
    //        c.setSocket("tcp", addr.getName().c_str(), addr.getPort());
    ////}
    //c.setName(nc.getNamespace().c_str());
    return c;
}
Example #2
0
void FallbackNameClient::run() {
    NameConfig nc;
    Contact call = FallbackNameServer::getAddress();
    DgramTwoWayStream send;
    send.join(call, true);
    listen.join(call, false);
    if (!listen.isOk()) {
        YARP_ERROR(Logger::get(), ConstString("Multicast not available"));
        return;
    }
    ConstString msg = ConstString("NAME_SERVER query ") + nc.getNamespace();
    send.beginPacket();
    send.writeLine(msg.c_str(), (int)msg.length());
    send.flush();
    send.endPacket();
    for (int i=0; i<5; i++) {
        listen.beginPacket();
        ConstString txt = listen.readLine();
        listen.endPacket();
        if (closed) return;
        YARP_DEBUG(Logger::get(), ConstString("Fallback name client got ") + txt);
        if (txt.find("registration ")==0) {
            address = NameClient::extractAddress(txt);
            YARP_INFO(Logger::get(), ConstString("Received address ") +
                      address.toURI());
            return;
        }
    }
}
Example #3
0
bool NetworkBase::setNameServerName(const ConstString& name) {
    NameConfig nc;
    ConstString fname = nc.getConfigFileName(YARP_CONFIG_NAMESPACE_FILENAME);
    nc.writeConfig(fname,name + "\n");
    nc.getNamespace(true);
    getNameSpace().activate(true);
    return true;
}
Example #4
0
 bool activate(bool force = false) {
     if (force) {
         // wipe if forced
         clear();
     }
     // return if namespaces already present
     if (spaces.size()!=0) return true;
     // read namespace list from config file
     NameConfig conf;
     if (!conf.fromFile()) {
         double now = Time::now();
         static double last_shown = now-10;
         if (now-last_shown>3) {
             last_shown = now;
             fprintf(stderr,"warning: YARP name server(s) not configured, ports will be anonymous\n");
             fprintf(stderr,"warning: check your namespace and settings with 'yarp detect'\n");
         }
         return false;
     }
     Bottle ns = conf.getNamespaces();
     // loop through namespaces
     for (int i=0; i<ns.size(); i++) {
         ConstString n = ns.get(i).asString();
         NameConfig conf2;
         // read configuration of individual namespace
         if (!conf2.fromFile(n.c_str())) {
             fprintf(stderr, "Could not find namespace %s\n",
                     n.c_str());
             continue;
         }
         String mode = conf2.getMode();
         Contact address = conf2.getAddress().addName(n);
         if (mode=="yarp"||mode=="//") {
             // add a yarp namespace
             NameSpace *ns = new YarpNameSpace(address);
             spaces.push_back(ns);
         } else if (mode=="ros") {
             // add a ros namespace
             NameSpace *ns = new RosNameSpace(address);
             spaces.push_back(ns);
         } else if (mode=="local") {
             NameSpace *ns = new YarpDummyNameSpace;
             spaces.push_back(ns);
         } else {
             // shrug
             YARP_SPRINTF1(Logger::get(),error,
                           "cannot deal with namespace of type %s",
                           mode.c_str());
             return false;
         }
     }
     // cache flags
     scan();
     return true;
 }
Example #5
0
bool NetworkBase::setNameServerContact(Contact &nameServerContact)
{
    NameConfig nameConfig;
    if (nameServerContact.getName() != "")
        setNameServerName(nameServerContact.getName());
    nameConfig.fromFile();
    nameConfig.setAddress(nameServerContact);
    bool result = nameConfig.toFile();
    getNameSpace().activate(true);
    return result;
}
Example #6
0
bool NameClient::updateAddress() {
    NameConfig conf;
    address = Contact();
    mode = "yarp";
    if (conf.fromFile()) {
        address = conf.getAddress();
        mode = conf.getMode();
        return true;
    }
    return false;
}
Example #7
0
Contact RosNameSpace::detectNameServer(bool useDetectedServer,
                                       bool& scanNeeded,
                                       bool& serverUsed) {
    YARP_UNUSED(useDetectedServer);
    NameConfig nc;
    nc.fromFile();
    Contact c = nc.getAddress();
    scanNeeded = false;
    serverUsed = false;

    if (!c.isValid()) {
        scanNeeded = true;
        fprintf(stderr, "Checking for ROS_MASTER_URI...\n");
        ConstString addr = NetworkBase::getEnvironment("ROS_MASTER_URI");
        c = Contact::fromString(addr.c_str());
        if (c.isValid()) {
            c.setCarrier("xmlrpc");
            c.setName(nc.getNamespace().c_str());
            NameConfig nc;
            nc.setAddress(c);
            nc.setMode("ros");
            nc.toFile();
            serverUsed = true;
         }
    }
    return c;
}
Example #8
0
int SocketTwoWayStream::open(const Contact& address) {
    if (address.getPort()==-1) {
        return -1;
    }
    std::string host = address.getHost();
    yarp::os::impl::TcpConnector connector;
#ifdef YARP_HAS_ACE
    if (address.getHost() == "localhost") {
        // ACE does not like localhost.  At all.
        NameConfig config;
        host = config.getHostName(true);
    }
    ACE_INET_Addr addr(address.getPort(), host.c_str());
    YARP_timeval openTimeout;
    YARP_timeval *timeout = nullptr;
    if (address.hasTimeout()) {
        openTimeout.set(address.getTimeout());
        timeout = &openTimeout;
    }
    int result = connector.connect(stream, addr, timeout, ACE_Addr::sap_any, 1);
#else
    int result;

    if (address.hasTimeout())
    {
        YARP_timeval timeout;
        /* set timeout seconds and microseconds */
        timeout.tv_sec = (int) address.getTimeout();
        timeout.tv_usec = (address.getTimeout() - (int) address.getTimeout()) * 1000000;
        result = connector.connect(stream, address, &timeout);
    }
    else
    {
        result = connector.connect(stream, address, nullptr);
    }


#endif
    if (result>=0) {
        happy = true;
    } else {
        YARP_SPRINTF2(Logger::get(),
                      debug,
                      "TCP connection to tcp://%s:%d failed to open",
                      host.c_str(),
                      address.getPort());
    }
    updateAddresses();
    return result;
}
Example #9
0
 bool activate(bool force = false) {
     if (force) {
         clear();
     }
     if (spaces.size()!=0) return true;
     NameConfig conf;
     if (!conf.fromFile()) {
         return false;
     }
     Bottle ns = conf.getNamespaces();
     for (int i=0; i<ns.size(); i++) {
         ConstString n = ns.get(i).asString();
         //printf("NAMESPACE %s\n", n.c_str());
         NameConfig conf2;
         if (!conf2.fromFile(n.c_str())) {
             fprintf(stderr, "Could not find namespace %s\n",
                     n.c_str());
             continue;
         }
         String mode = conf2.getMode();
         Contact address = conf2.getAddress().toContact().addName(n);
         //printf("ADDRESS %s\n", address.toString().c_str());
         if (mode=="yarp"||mode=="//") {
             NameSpace *ns = new YarpNameSpace(address);
             spaces.push_back(ns);
         } else if (mode=="ros") {
             NameSpace *ns = new RosNameSpace(address);
             spaces.push_back(ns);
         } else {
             YARP_SPRINTF1(Logger::get(),error,
                           "cannot deal with namespace of type %s",
                           mode.c_str());
             return false;
         }
     }
     scan();
     return true;
 }
Example #10
0
int SocketTwoWayStream::open(const Contact& address) {
    if (address.getPort()==-1) {
        return -1;
    }
    String host = address.getHost();
#ifdef YARP_HAS_ACE
    ACE_SOCK_Connector connector;
    if (address.getHost() == "localhost") {
        // ACE does not like localhost.  At all.
        NameConfig config;
        host = config.getHostName(true);
    }
    ACE_INET_Addr addr(address.getPort(),host.c_str());
    ACE_Time_Value openTimeout;
    ACE_Time_Value *timeout = NULL;
    if (address.hasTimeout()) {
        openTimeout.set(address.getTimeout());
        timeout = &openTimeout;
    }
    int result = connector.connect(stream,addr,timeout,ACE_Addr::sap_any,1);
#else
    TcpConnector connector;
    int result = connector.connect(stream, address);
#endif
    if (result>=0) {
        happy = true;
    } else {
        YARP_SPRINTF2(Logger::get(),
                      debug,
                      "TCP connection to tcp://%s:%d failed to open",
                      host.c_str(),
                      address.getPort());
    }
    updateAddresses();
    return result;
}
Example #11
0
ConstString NetworkBase::getNameServerName() {
    NameConfig nc;
    ConstString name = nc.getNamespace(false);
    return name.c_str();
}
Example #12
0
bool BootstrapServer::configFileBootstrap(yarp::os::Contact& contact,
                                          bool configFileRequired,
                                          bool mayEditConfigFile) {
    Contact suggest = contact;

    // see what address is lying around
    Contact prev;
    NameConfig conf;
    if (conf.fromFile()) {
        prev = conf.getAddress();
    } else if (configFileRequired) {
        fprintf(stderr,"Could not read configuration file %s\n",
                conf.getConfigFileName().c_str());
        return false;
    }

    // merge
    if (prev.isValid()) {
        if (suggest.getHost() == "...") {
            suggest.setHost(prev.getHost());
        }
        if (suggest.getCarrier() == "...") {
            suggest.setCarrier(prev.getCarrier());
        }
        if (suggest.getPort() == 0) {
            suggest.setPort(prev.getPort());
        }
    }

    if (suggest.getRegName() == "...") {
        suggest.setName(conf.getNamespace());
    }

    // still something not set?
    if (suggest.getPort() == 0) {
        suggest.setPort(10000);
    }
    if (suggest.getHost() == "...") {
        // should get my IP
        suggest.setHost(conf.getHostName());
    }

    if (!configFileRequired)  {
        // finally, should make sure IP is local, and if not, correct it
        if (!conf.isLocalName(suggest.getHost())) {
            fprintf(stderr,"Overriding non-local address for name server\n");
            suggest.setHost(conf.getHostName());
        } else {
            // Let's just check we're not a loopback
            ConstString betterHost = conf.getHostName(false,suggest.getHost());
            if (betterHost!=suggest.getHost()) {
                fprintf(stderr,"Overriding loopback address for name server\n");
                suggest.setHost(betterHost);
            }
        }
    }
    else
    {
        if (!conf.isLocalName(conf.getHostName())) {
            fprintf(stderr,"The address written in config file doesn't belong any interface \n");
            return false;
        }
        suggest.setHost(conf.getHostName());
    }

    bool changed = false;
    if (prev.isValid()) {
        changed = (prev.getHost() != suggest.getHost()) ||
            (prev.getPort() != suggest.getPort()) ||
            (conf.getMode() != "yarp" && conf.getMode() != "");
    }
    if (changed && !mayEditConfigFile) {
        fprintf(stderr,"PROBLEM: need to change settings in %s\n",
                conf.getConfigFileName().c_str());
        fprintf(stderr,"  Current settings: host %s port %d family %s\n",
                prev.getHost().c_str(), prev.getPort(),
                (conf.getMode()=="")?"yarp":conf.getMode().c_str());
        fprintf(stderr,"  Desired settings:  host %s port %d family %s\n",
                suggest.getHost().c_str(), suggest.getPort(), "yarp");
        fprintf(stderr,"Please specify '--write' if it is ok to overwrite current settings, or\n");
        if(!configFileRequired)
            fprintf(stderr,"Please specify '--read' to use the current settings, or\n");
        else
            fprintf(stderr,"Please set an existing address in config file, or\n");
        fprintf(stderr,"delete %s\n", conf.getConfigFileName().c_str());
        return false;
    }
    bool shouldSave = changed || !prev.isValid();

    if (shouldSave) {
        // and save
        conf.setAddress(suggest);
        if (!conf.toFile()) {
            fprintf(stderr,"Could not save configuration file %s\n",
                    conf.getConfigFileName().c_str());
        }
    }

    contact = suggest;
    return true;
}
Example #13
0
int yarp_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
                 off_t offset, struct fuse_file_info *fi)
{
    (void) offset;
    (void) fi;

    printf(">>>>>>>>>>>READING DIR\n");


    filler(buf, ".", NULL, 0);
    filler(buf, "..", NULL, 0);

    YPath ypath(path);

    if (ypath.isPort()) {
        filler(buf, "rw", NULL, 0);
        //filler(buf, "write", NULL, 0); //deprecated
        //filler(buf, "status", NULL, 0);
        return 0;
    }

    NameConfig nc;

    ConstString name = nc.getNamespace();
    Bottle msg, reply;
    msg.addString("bot");
    msg.addString("list");
    Network::write(name.c_str(),
                   msg,
                   reply);

    printf("Got %s\n", reply.toString().c_str());

    ACE_Ordered_MultiSet<ConstString> lines;


    for (int i=1; i<reply.size(); i++) {
        Bottle *entry = reply.get(i).asList();
        string rpath = path;
        if (rpath[rpath.length()-1]!='/') {
            rpath = rpath + "/";
        }
        if (entry!=NULL) {
            ConstString name = entry->check("name",Value("")).asString();
            if (name!="") {
                if (strstr(name.c_str(),rpath.c_str())==
                           name.c_str()) {
                    printf(">>> %s is in path %s\n", name.c_str(),
                           rpath.c_str());
                    ConstString part(name.c_str()+rpath.length());
                    if (part[0]=='/') {
                        part = part.substr(1,part.length()-1);
                    }
                    printf("    %s is the addition\n", part.c_str());

                    char *brk = (char*)strstr(part.c_str(),"/");
                    if (brk!=NULL) {
                        *brk = '\0';
                    }
                    ConstString item(part.c_str());
                    printf("    %s is the item\n", item.c_str());
                    if (item!="") {
                        lines.remove(item);
                        lines.insert(item);
                    }
                }
            }
        }
    }

    // return result in alphabetical order
    ACE_Ordered_MultiSet_Iterator<ConstString> iter(lines);
    iter.first();
    while (!iter.done()) {
        printf("adding item %s\n", (*iter).c_str());
        filler(buf, (*iter).c_str(), NULL, 0);
        iter.advance();
    }

    return 0;
}
Example #14
0
String NameClient::send(const String& cmd, bool multi) {
    //printf("*** OLD YARP command %s\n", cmd.c_str());
    setup();

    if (NetworkBase::getQueryBypass()) {
        ContactStyle style;
        Bottle bcmd(cmd.c_str()), reply;
        NetworkBase::writeToNameServer(bcmd,reply,style);
        ConstString si = reply.toString(), so;
        for (int i=0; i<(int)si.length(); i++) {
            if (si[i]!='\"') {
                so += si[i];
            }
        }
        return so.c_str();
    }
    bool retried = false;
    bool retry = false;
    String result;
    Contact server = getAddress();
    float timeout = 10;
    server.setTimeout(timeout);

    do {

        YARP_DEBUG(Logger::get(),String("sending to nameserver: ") + cmd);

        if (isFakeMode()) {
            //YARP_DEBUG(Logger::get(),"fake mode nameserver");
            return getServer().apply(cmd,Contact::bySocket("tcp","127.0.0.1",NetworkBase::getDefaultPortRange())) + "\n";
        }

        TcpFace face;
        YARP_DEBUG(Logger::get(),String("connecting to ") + getAddress().toURI());
        OutputProtocol *ip = NULL;
        if (!retry) {
            ip = face.write(server);
        } else {
            retried = true;
        }
        if (ip==NULL) {
            YARP_INFO(Logger::get(),"No connection to nameserver");
            if (!allowScan) {
                YARP_INFO(Logger::get(),"*** try running: yarp detect ***");
            }
            Contact alt;
            if (!isFakeMode()) {
                if (allowScan) {
                    YARP_INFO(Logger::get(),"no connection to nameserver, scanning mcast");
                    reportScan = true;
#ifdef YARP_HAS_ACE
                    alt = FallbackNameClient::seek();
#else
                    return ""; // nothing to do, nowhere to turn
#endif
                }
            }
            if (alt.isValid()) {
                address = alt;
                if (allowSaveScan) {
                    reportSaveScan = true;
                    NameConfig nc;
                    nc.setAddress(alt);
                    nc.toFile();
                }
                server = getAddress();
                server.setTimeout(timeout);
                ip = face.write(server);
                if (ip==NULL) {
                    YARP_ERROR(Logger::get(),
                               "no connection to nameserver, scanning mcast");
                    return "";
                }
            } else {
                return "";
            }
        }
        String cmdn = cmd + "\n";
        Bytes b((char*)cmdn.c_str(),cmdn.length());
        ip->getOutputStream().write(b);
        bool more = multi;
        while (more) {
            String line = "";
            line = ip->getInputStream().readLine();
            if (!(ip->isOk())) {
                more = false;
                //YARP_DEBUG(Logger::get(), e.toString() + " <<< exception from name server");
                retry = true;
                break;
            }
            if (line.length()>1) {
                if (line[0] == '*'||line[0] == '[') {
                    more = false;
                }
            }
            result += line + "\n";
        }
        ip->close();
        delete ip;
        YARP_SPRINTF1(Logger::get(),
                      debug,
                      "<<< received from nameserver: %s",result.c_str());
    } while (retry&&!retried);

    return result;
}
Example #15
0
bool Port::open(const Contact& contact, bool registerName,
                const char *fakeName)
{
    Contact contact2 = contact;

    if (!NetworkBase::initialized()) {
        YARP_ERROR(Logger::get(), "YARP not initialized; create a yarp::os::Network object before using ports");
        return false;
    }

    std::string n = contact2.getName();

    NameConfig conf;
    std::string nenv = std::string("YARP_RENAME") + conf.getSafeString(n);
    std::string rename = NetworkBase::getEnvironment(nenv.c_str());
    if (rename!="") {
        n = rename;
        contact2.setName(n);
    }

    bool local = false;
    if (n == "" && contact2.getPort()<=0) {
        local = true;
        registerName = false;
        n = "...";
    }

    NestedContact nc(n);
    if (nc.getNestedName()!="") {
        if (nc.getNodeName() == "") {
            Nodes& nodes = NameClient::getNameClient().getNodes();
            nodes.requireActiveName();
            std::string node_name = nodes.getActiveName();
            if (node_name!="") {
                n = n + node_name;
            }
        }
    }

    PortCoreAdapter *currentCore = &(IMPL());
    if (currentCore!=nullptr) {
        currentCore->active = false;
        if (n!="" && (n[0]!='/'||currentCore->includeNode) && n[0]!='=' && n!="..." && n.substr(0, 3)!="...") {
            if (fakeName==nullptr) {
                Nodes& nodes = NameClient::getNameClient().getNodes();
                std::string node_name = nodes.getActiveName();
                if (node_name!="") {
                    n = (n[0]=='/'?"":"/") + n + "@" + node_name;
                }
            }
        }
    }
    if (n!="" && n[0]!='/'  && n[0]!='=' && n!="..." && n.substr(0, 3)!="...") {
        if (fakeName==nullptr) {
            YARP_SPRINTF1(Logger::get(), error,
                          "Port name '%s' needs to start with a '/' character",
                          n.c_str());
            return false;
        }
    }
    if (n!="" && n!="..." && n[0]!='=' && n.substr(0, 3)!="...") {
        if (fakeName==nullptr) {
            std::string prefix = NetworkBase::getEnvironment("YARP_PORT_PREFIX");
            if (prefix!="") {
                n = prefix + n;
                contact2.setName(n);
            }
        }
    }
    if (currentCore!=nullptr) {
        NestedContact nc;
        nc.fromString(n);
        if (nc.getNestedName()!="") {
            if (nc.getCategory()=="") {
                // we need to add in a category
                std::string cat;
                if (currentCore->commitToRead) {
                    cat = "-";
                } else if (currentCore->commitToWrite) {
                    cat = "+";
                }
                if (cat!="") {
                    if (currentCore->commitToRpc) {
                        cat += "1";
                    }
                    contact2.setName(nc.getNestedName() +
                                     cat +
                                     "@" +
                                     nc.getNodeName());
                } else {
                    YARP_SPRINTF1(Logger::get(), error,
                                  "Error: Port '%s' is not committed to being either an input or output port.",
                                  n.c_str());
                    YARP_SPRINTF0(Logger::get(), error,
                                  "YARP does not mind, but we are trying to register with a name server that does.");
                    YARP_SPRINTF0(Logger::get(), error,
                                  "You can call Port::setWriteOnly() or Port::setReadOnly(), OR rename the port.");
                    NestedContact nc2 = nc;
                    nc2.setCategoryWrite();
                    YARP_SPRINTF1(Logger::get(), error,
                                  "For an output port, call it: %s (+ adds data)",
                                  nc2.toString().c_str());
                    nc2.setCategoryRead();
                    YARP_SPRINTF1(Logger::get(), error,
                                  "For an input port, call it: %s (- takes data)",
                                  nc2.toString().c_str());
                    return false;
                }
            }
        }
    }

    // Allow for open() to be called safely many times on the same Port
    if (currentCore && currentCore->isOpened()) {
        auto* newCore = new PortCoreAdapter(*this);
        yAssert(newCore != nullptr);
        // copy state that should survive in a new open()
        if (currentCore->checkPortReader() != nullptr) {
            newCore->configReader(*(currentCore->checkPortReader()));
        }
        if (currentCore->checkAdminPortReader() != nullptr) {
            newCore->configAdminReader(*(currentCore->checkAdminPortReader()));
        }
        if (currentCore->checkReadCreator() != nullptr) {
            newCore->configReadCreator(*(currentCore->checkReadCreator()));
        }
        if (currentCore->checkWaitAfterSend() >= 0) {
            newCore->configWaitAfterSend(currentCore->checkWaitAfterSend());
        }
        if (currentCore->haveCallbackLock) {
            newCore->configCallbackLock(currentCore->recCallbackLock);
        }
        close();
        if (owned) delete ((PortCoreAdapter*)implementation);
        implementation = newCore;
        owned = true;
        currentCore = newCore;
        currentCore->active = false;
    }

    PortCoreAdapter& core = IMPL();

    core.openable();

    if (NetworkBase::localNetworkAllocation()&&contact2.getPort()<=0) {
        YARP_DEBUG(Logger::get(), "local network allocation needed");
        local = true;
    }

    bool success = true;
    Contact address(contact2.getName(),
                    contact2.getCarrier(),
                    contact2.getHost(),
                    contact2.getPort());
    address.setNestedContact(contact2.getNested());

    core.setReadHandler(core);
    if (contact2.getPort()>0 && contact2.getHost()!="") {
        registerName = false;
    }

    std::string ntyp = getType().getNameOnWire();
    if (ntyp=="") {
        NestedContact nc;
        nc.fromString(n);
        if (nc.getTypeName()!="") ntyp = nc.getTypeName();
    }
    if (ntyp=="") {
        ntyp = getType().getName();
    }
    if (ntyp!="") {
        NestedContact nc;
        nc.fromString(contact2.getName());
        nc.setTypeName(ntyp);
        contact2.setNestedContact(nc);
        if (getType().getNameOnWire()!=ntyp) {
            core.promiseType(Type::byNameOnWire(ntyp.c_str()));
        }
    }

    if (registerName&&!local) {
        address = NetworkBase::registerContact(contact2);
    }

    core.setControlRegistration(registerName);
    success = (address.isValid()||local)&&(fakeName==nullptr);

    if (success) {
        // create a node if needed
        Nodes& nodes = NameClient::getNameClient().getNodes();
        nodes.prepare(address.getRegName());
    }

    // If we are a service client, go ahead and connect
    if (success) {
        NestedContact nc;
        nc.fromString(address.getName());
        if (nc.getNestedName()!="") {
            if (nc.getCategory() == "+1") {
                addOutput(nc.getNestedName());
            }
        }
    }

    std::string blame = "invalid address";
    if (success) {
        success = core.listen(address, registerName);
        blame = "address conflict";
        if (success) {
            success = core.start();
            blame = "manager did not start";
        }
    }
    if (success) {
        address = core.getAddress();
        if (registerName&&local) {
            contact2.setSocket(address.getCarrier(),
                               address.getHost(),
                               address.getPort());
            contact2.setName(address.getRegName());
            Contact newName = NetworkBase::registerContact(contact2);
            core.resetPortName(newName.getName());
            address = core.getAddress();
        } else if (core.getAddress().getRegName()=="" && !registerName) {
            core.resetPortName(core.getAddress().toURI(false));
            core.setName(core.getAddress().getRegName());
        }

        if (core.getVerbosity()>=1) {
            if (address.getRegName()=="") {
                YARP_INFO(Logger::get(),
                          std::string("Anonymous port active at ") +
                          address.toURI());
            } else {
                YARP_INFO(Logger::get(),
                          std::string("Port ") +
                          address.getRegName() +
                          " active at " +
                          address.toURI());
            }
        }
    }

    if (fakeName!=nullptr) {
        success = core.manualStart(fakeName);
        blame = "unmanaged port failed to start";
    }

    if (!success) {
        YARP_ERROR(Logger::get(),
                   std::string("Port ") +
                   (address.isValid()?(address.getRegName().c_str()):(contact2.getName().c_str())) +
                   " failed to activate" +
                   (address.isValid()?" at ":"") +
                   (address.isValid()?address.toURI():std::string("")) +
                   " (" +
                   blame +
                   ")");
    }

    if (success) {
        // create a node if needed
        Nodes& nodes = NameClient::getNameClient().getNodes();
        nodes.add(*this);
    }

    if (success && currentCore!=nullptr) currentCore->active = true;
    return success;
}
Example #16
0
int NameServer::main(int argc, char *argv[]) {
    //Network yarp;

    // pick an address
    Contact suggest("...",0); // suggestion is initially empty

    ConstString nameSpace = "";

    if (argc>=1) {
        if (argv[0][0]=='/') {
            nameSpace = argv[0];
            // BUT: not used yet
            argv++;
            argc--;
        }
        if (argc>=2) {
            suggest = Contact(argv[0],NetType::toInt(argv[1]));
        } else if (argc>=1) {
            suggest = Contact("...",NetType::toInt(argv[0]));
        }
    }

    Property config;
    config.fromCommand(argc,argv,false);

    bool bNoAuto=config.check("noauto");

    // see what address is lying around
    Contact prev;
    NameConfig conf;
    if (nameSpace!="") {
        conf.setNamespace(nameSpace.c_str());
    }
    if (conf.fromFile()) {
        prev = conf.getAddress();
    }
    else if (bNoAuto)
    {
        YARP_ERROR(Logger::get(), ConstString("Could not find configuration file ") +
        conf.getConfigFileName());

        return 1;
    }

    // merge
    if (prev.isValid()) {
        if (suggest.getHost()=="...") {
            suggest = Contact(prev.getHost(),suggest.getPort());
        }
        if (suggest.getPort()==0) {
            suggest = Contact(suggest.getHost(),prev.getPort());
        }
    }

    // still something not set?
    if (suggest.getPort()==0) {
        suggest = Contact(suggest.getHost(),NetworkBase::getDefaultPortRange());
    }
    if (suggest.getHost()=="...") {
        // should get my IP
        suggest = Contact(conf.getHostName(),suggest.getPort());
    }

    // finally, should make sure IP is local, and if not, correct it
    if (!conf.isLocalName(suggest.getHost())) {
        YARP_INFO(Logger::get(),"Overriding non-local address for name server");
        suggest = Contact(conf.getHostName(),suggest.getPort());
    }

    // and save
    conf.setAddress(suggest);
    if (!conf.toFile()) {
        YARP_ERROR(Logger::get(), ConstString("Could not save configuration file ") +
                   conf.getConfigFileName());
    }

    MainNameServer name(suggest.getPort() + 2);
    // register root for documentation purposes
    name.registerName(conf.getNamespace(),suggest);

    Port server;
    name.setPort(server);
    server.setReaderCreator(name);
    suggest.setName(conf.getNamespace());
    bool ok = server.open(suggest, false);
    if (ok) {
        YARP_DEBUG(Logger::get(), ConstString("Name server listening at ") +
                   suggest.toURI());

        YARP_SPRINTF2(Logger::get(),info,
                      "Name server can be browsed at http://%s:%d/",
                      suggest.getHost().c_str(), suggest.getPort());

#ifdef YARP_HAS_ACE
        FallbackNameServer fallback(name);
        fallback.start();

        // register fallback root for documentation purposes
        name.registerName("fallback",FallbackNameServer::getAddress());
        YARP_INFO(Logger::get(), ConstString("Bootstrap server listening at ") +
                  FallbackNameServer::getAddress().toURI());
#endif

        while (true) {
            YARP_DEBUG(Logger::get(),"name server running happily");
            Time::delay(60);
        }
        server.close();
#ifdef YARP_HAS_ACE
        fallback.close();
        fallback.join();
#endif
    }

    if (!ok) {
        YARP_ERROR(Logger::get(), "Name server failed to start");
        //YARP_ERROR(Logger::get(), ConstString("   reason for failure is \"") +
        //e.toString() + "\"");
        YARP_ERROR(Logger::get(), "Maybe it is already be running?");
        if (suggest.getPort()>0) {
            YARP_ERROR(Logger::get(), ConstString("Or perhaps another service may already be running on port ") + NetType::toString(suggest.getPort()) + "?");
        }
        return 1;
    }

    return 0;
}