예제 #1
1
void
CallbackClient::run(int argc, char** argv)
{
    Ice::PropertiesPtr properties = createTestProperties(argc, argv);
    properties->setProperty("Ice.Warn.Connections", "0");
    properties->setProperty("Ice.ThreadPool.Client.Serialize", "1");

    Ice::CommunicatorHolder communicator = initialize(argc, argv, properties);
    ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50));
    Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase);
    communicator->setDefaultRouter(router);

    ObjectPrx base = communicator->stringToProxy("c/callback:" + getTestEndpoint());
    Glacier2::SessionPrx session = router->createSession("userid", "abc123");
    base->ice_ping();

    CallbackPrx twoway = CallbackPrx::checkedCast(base);
    CallbackPrx oneway = twoway->ice_oneway();
    CallbackPrx batchOneway = twoway->ice_batchOneway();

    communicator->getProperties()->setProperty("Ice.PrintAdapterReady", "0");
    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", router);
    adapter->activate();

    string category = router->getCategoryForClient();

    CallbackReceiverI* callbackReceiverImpl = new CallbackReceiverI;
    ObjectPtr callbackReceiver = callbackReceiverImpl;

    Identity callbackReceiverIdent;
    callbackReceiverIdent.name = "callbackReceiver";
    callbackReceiverIdent.category = category;
    CallbackReceiverPrx twowayR =
        CallbackReceiverPrx::uncheckedCast(adapter->add(callbackReceiver, callbackReceiverIdent));
    CallbackReceiverPrx onewayR = twowayR->ice_oneway();

    {
        cout << "testing client request override... " << flush;
        {
            for(int i = 0; i < 5; i++)
            {
                oneway->initiateCallback(twowayR, 0);
                oneway->initiateCallback(twowayR, 0);
                callbackReceiverImpl->callbackOK(2, 0);
            }
        }

        {
            Ice::Context ctx;
            ctx["_ovrd"] = "test";
            for(int i = 0; i < 5; i++)
            {
                oneway->initiateCallback(twowayR, i, ctx);
                oneway->initiateCallback(twowayR, i, ctx);
                oneway->initiateCallback(twowayR, i, ctx);
                IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100));
                test(callbackReceiverImpl->callbackOK(1, i) < 3);
            }
        }
        cout << "ok" << endl;
    }

    {
        cout << "testing server request override... " << flush;
        Ice::Context ctx;
        ctx["serverOvrd"] = "test";
        for(int i = 0; i < 5; i++)
        {
            oneway->initiateCallback(onewayR, i, ctx);
            oneway->initiateCallback(onewayR, i, ctx);
            oneway->initiateCallback(onewayR, i, ctx);
            IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100));
            test(callbackReceiverImpl->callbackOK(1, i) < 3);
        }
        oneway->initiateCallback(twowayR, 0);
        test(callbackReceiverImpl->callbackOK(1, 0) == 0);

        int count = 0;
        int nRetry = 0;
        do
        {
            callbackReceiverImpl->hold();
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallbackWithPayload(onewayR, ctx);
            oneway->initiateCallback(twowayR, 0);
            IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200 + nRetry * 200));
            callbackReceiverImpl->activate();
            test(callbackReceiverImpl->callbackOK(1, 0) == 0);
            count = callbackReceiverImpl->callbackWithPayloadOK(0);
            callbackReceiverImpl->callbackWithPayloadOK(count);
        }
        while(count == 10 && nRetry++ < 10);
        test(count < 10);

        oneway->initiateCallbackWithPayload(twowayR);
        oneway->initiateCallbackWithPayload(twowayR);
        callbackReceiverImpl->hold();
        oneway->initiateCallbackWithPayload(twowayR);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallbackWithPayload(twowayR);
        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1000));
        callbackReceiverImpl->activate();
        test(callbackReceiverImpl->callbackWithPayloadOK(4) == 0);

        int remainingCallbacks = callbackReceiverImpl->callbackOK(1, 0);
        //
        // Occasionally, Glacier2 flushes in the middle of our 5
        // callbacks, so we get more than 1 callback
        // (in theory we could get up to 5 total - more than 1 extra is extremely unlikely)
        //
        // The sleep above is also important as we want to have enough
        // time to receive this (these) extra callback(s).
        //
        test(remainingCallbacks <= 4);
        if(remainingCallbacks > 0)
        {
            test(callbackReceiverImpl->callbackOK(remainingCallbacks, 0) == 0);
        }

        ctx["_fwd"] = "O";

        oneway->initiateCallbackWithPayload(twowayR);
        callbackReceiverImpl->hold();
        oneway->initiateCallbackWithPayload(twowayR);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallback(onewayR, 0, ctx);
        oneway->initiateCallbackWithPayload(twowayR);
        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200));
        callbackReceiverImpl->activate();
        test(callbackReceiverImpl->callbackWithPayloadOK(3) == 0);
        remainingCallbacks = callbackReceiverImpl->callbackOK(1, 0);
        // Unlikely but sometime we get more than just one callback if the flush
        // occurs in the middle of our 5 callbacks.
        test(remainingCallbacks <= 3);
        if(remainingCallbacks > 0)
        {
            test(callbackReceiverImpl->callbackOK(remainingCallbacks, 0) == 0);
        }

        cout << "ok" << endl;
    }

    {
        cout << "shutdown... " << flush;
        twoway->shutdown();

        try
        {
            router->destroySession();
        }
        catch(const Ice::LocalException&)
        {
            test(false);
        }

        communicator->setDefaultRouter(0);
        ObjectPrx processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51));
        Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast(processBase);
        process->shutdown();
        try
        {
            process->ice_ping();
            test(false);
        }
        catch(const Ice::LocalException&)
        {
            cout << "ok" << endl;
        }
    }
}
예제 #2
0
파일: TestI.cpp 프로젝트: ming-hai/ice
void
TestI::transient(const Current& current)
{
    CommunicatorPtr communicator = current.adapter->getCommunicator();
    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("TransientTestAdapter",
                                                                              getTestEndpoint(communicator, 1));
    adapter->activate();
    adapter->destroy();
}
예제 #3
0
파일: Server.cpp 프로젝트: Jonavin/ice
int
CallbackServer::run(int, char**)
{
    communicator()->getProperties()->setProperty("CallbackAdapter.Endpoints", "tcp -p 12010");
    ObjectAdapterPtr adapter = communicator()->createObjectAdapter("CallbackAdapter");
    adapter->add(new CallbackI(), communicator()->stringToIdentity("c/callback"));
    adapter->activate();
    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
예제 #4
0
파일: Server.cpp 프로젝트: pedia/zeroc-ice
int
BackendServer::run(int, char**)
{
    communicator()->getProperties()->setProperty("BackendAdapter.Endpoints", "tcp -p 12010");
    ObjectAdapterPtr adapter = communicator()->createObjectAdapter("BackendAdapter");
    adapter->addServantLocator(new ServantLocatorI, "");
    adapter->activate();
    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
예제 #5
0
파일: Server.cpp 프로젝트: pedia/zeroc-ice
int
SessionControlServer::run(int, char**)
{
    communicator()->getProperties()->setProperty("SessionControlAdapter.Endpoints", "tcp -p 12010");
    ObjectAdapterPtr adapter = communicator()->createObjectAdapter("SessionControlAdapter");
    adapter->add(new SessionManagerI, communicator()->stringToIdentity("SessionManager"));
    adapter->activate();
    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
예제 #6
0
파일: Server.cpp 프로젝트: chenbk85/ice
int
CallbackServer::run(int, char**)
{
    communicator()->getProperties()->setProperty("CallbackAdapter.Endpoints", "tcp -p 12010");
    ObjectAdapterPtr adapter = communicator()->createObjectAdapter("CallbackAdapter");
    adapter->add(new CallbackI(), communicator()->stringToIdentity("c1/callback")); // The test allows "c1" as category.
    adapter->add(new CallbackI(), communicator()->stringToIdentity("c2/callback")); // The test allows "c2" as category.
    adapter->add(new CallbackI(), communicator()->stringToIdentity("c3/callback")); // The test rejects "c3" as category.
    adapter->add(new CallbackI(), communicator()->stringToIdentity("_userid/callback")); // The test allows the prefixed userid.
    adapter->activate();
    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
예제 #7
0
파일: Server.cpp 프로젝트: yuanbaopapa/ice
 ServerLocatorI(BackendPtr backend, ObjectAdapterPtr adapter) :
     _backend(backend),
     _adapter(adapter)
 {
     _registryPrx = LocatorRegistryPrx::uncheckedCast(adapter->add(new ServerLocatorRegistry,
                                                     Ice::stringToIdentity("registry")));
 }
예제 #8
0
Freeze::EvictorIBase::EvictorIBase(const ObjectAdapterPtr& adapter,
                                   const string& envName,
                                   DbEnv* dbEnv,
                                   const string& filename,
                                   const FacetTypeMap& facetTypes,
                                   const ServantInitializerPtr& initializer,
                                   bool createDb) :
    _evictorSize(10),
    _facetTypes(facetTypes),
    _deactivateController(this),
    _adapter(adapter),
    _communicator(adapter->getCommunicator()),
    _initializer(initializer),
    _dbEnv(SharedDbEnv::get(_communicator, envName, dbEnv)),
    _filename(filename),
    _createDb(createDb),
    _trace(0),
    _txTrace(0),
    _pingObject(new PingObject)
{
    _encoding = _dbEnv->getEncoding();

    _trace = _communicator->getProperties()->getPropertyAsInt("Freeze.Trace.Evictor");
    _txTrace = _communicator->getProperties()->getPropertyAsInt("Freeze.Trace.Transaction");
    _deadlockWarning = (_communicator->getProperties()->getPropertyAsInt("Freeze.Warn.Deadlocks") > 0);
}
예제 #9
0
파일: Service.cpp 프로젝트: ming-hai/ice
void
ServiceI::start(const CommunicatorPtr& communicator,
                const ObjectAdapterPtr& topicAdapter,
                const ObjectAdapterPtr& publishAdapter,
                const string& name,
                const Ice::Identity& id,
                const string& /*dbEnv*/)
{
    //
    // For IceGrid we don't validate the properties as all sorts of
    // non-IceStorm properties are included in the prefix.
    //
    //validateProperties(name, communicator->getProperties(), communicator->getLogger());

    // This is for IceGrid only and as such we use a transient
    // implementation of IceStorm.
    string instanceName = communicator->getProperties()->getPropertyWithDefault(name + ".InstanceName", "IceStorm");
    _instance = new Instance(instanceName, name, communicator, publishAdapter, topicAdapter, 0);

    try
    {
        TransientTopicManagerImplPtr manager = new TransientTopicManagerImpl(_instance);
        _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(manager, id));
    }
    catch(const Ice::Exception& ex)
    {
        _instance = 0;
        LoggerOutputBase s;
        s << "exception while starting IceStorm service " << name << ":\n";
        s << ex;

        throw IceBox::FailureException(__FILE__, __LINE__, s.str());
    }
}
예제 #10
0
    virtual
    void run()
    {
        CommunicatorPtr communicator = initialize(initData);
        ObjectPrx routerBase = communicator->stringToProxy(
            "Glacier2/router:" + TestHelper::getTestEndpoint(communicator->getProperties(), 50));
        _router = Glacier2::RouterPrx::checkedCast(routerBase);
        communicator->setDefaultRouter(_router);

        ostringstream os;
        os << "userid-" << _id;
        Glacier2::SessionPrx session = _router->createSession(os.str(), "abc123");
        communicator->getProperties()->setProperty("Ice.PrintAdapterReady", "");
        ObjectAdapterPtr adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", _router);
        adapter->activate();

        string category = _router->getCategoryForClient();
        _callbackReceiver = new CallbackReceiverI;
        Identity ident;
        ident.name = "callbackReceiver";
        ident.category = category;
        CallbackReceiverPrx receiver = CallbackReceiverPrx::uncheckedCast(adapter->add(_callbackReceiver, ident));

        ObjectPrx base = communicator->stringToProxy(
            "c1/callback:" + TestHelper::getTestEndpoint(communicator->getProperties()));
        base = base->ice_oneway();
        CallbackPrx callback = CallbackPrx::uncheckedCast(base);

        {
            Lock sync(*this);
            _initialized = true;
            notifyAll();
        }
        {
            Lock sync(*this);
            while(!_notified)
            {
                wait();
            }
        }

        //
        // Stress the router until the connection is closed.
        //
        stress(callback, receiver);
        communicator->destroy();
    }
예제 #11
0
void
Client::run(int argc, char** argv)
{
    Ice::CommunicatorHolder communicator = initialize(argc, argv);
    ObjectPrx base = communicator->stringToProxy("Test.IceStorm/TopicManager");
    IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base);
    if(!manager)
    {
        ostringstream os;
        os << argv[0] << ": `Test.IceStorm/TopicManager' is not running";
        throw invalid_argument(os.str());
    }

    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default:udp");

    TopicPrx topic = manager->create("single");

    //
    // Create subscribers with different QoS.
    //
    SingleIPtr sub = new SingleI;
    topic->subscribeAndGetPublisher(IceStorm::QoS(), adapter->addWithUUID(sub));

    adapter->activate();

    // Ensure that getPublisher & getNonReplicatedPublisher work
    // correctly.
    Ice::ObjectPrx p1 = topic->getPublisher();
    Ice::ObjectPrx p2 = topic->getNonReplicatedPublisher();
    test(p1->ice_getAdapterId() == "PublishReplicaGroup");
    test(p2->ice_getAdapterId() == "Test.IceStorm1.Publish" ||
         p2->ice_getAdapterId() == "Test.IceStorm2.Publish" ||
         p2->ice_getAdapterId() == "Test.IceStorm3.Publish");

    //
    // Get a publisher object, create a twoway proxy and then cast to
    // a Single object.
    //
    SinglePrx single = SinglePrx::uncheckedCast(topic->getPublisher()->ice_twoway());
    for(int i = 0; i < 1000; ++i)
    {
        single->event(i);
    }

    sub->waitForEvents();
}
예제 #12
0
int
BackendServer::run(int argc, char* argv[])
{
    string endpoints = 
        communicator()->getProperties()->getPropertyWithDefault("BackendAdapter.Endpoints", 
                                                                "tcp -p 12010 -t 20000:ssl -p 12011 -t 20000");

    communicator()->getProperties()->setProperty("BackendAdapter.Endpoints", endpoints);
    ObjectAdapterPtr adapter = communicator()->createObjectAdapter("BackendAdapter");
    BackendPtr backend = new BackendI;
    Ice::LocatorPtr locator = new ServerLocatorI(backend, adapter);
    adapter->add(locator, communicator()->stringToIdentity("locator"));
    adapter->addServantLocator(new ServantLocatorI(backend), "");
    adapter->activate();
    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
예제 #13
0
 ServerLocatorI(const BackendPtr& backend, const ObjectAdapterPtr& adapter) :
     _backend(backend),
     _adapter(adapter),
     _registryPrx(
         LocatorRegistryPrx::uncheckedCast(
             adapter->add(new ServerLocatorRegistry, _adapter->getCommunicator()->stringToIdentity("registry"))))
 {
 }
예제 #14
0
  int run(int argc, char* argv[]) {
    Example::CallbackIPtr servant = new Example::CallbackI(communicator());

    ObjectAdapterPtr adapter =
         communicator()->createObjectAdapter("CallbackAdapter");
    ObjectPrx proxy = adapter->add(
	 servant, communicator()->stringToIdentity("callback"));

    cout << communicator()->proxyToString(proxy) << endl;

    adapter->activate();

    servant->start();
    shutdownOnInterrupt();
    communicator()->waitForShutdown();
    servant->destroy();

    return 0;
  }
예제 #15
0
파일: Server.cpp 프로젝트: yuanbaopapa/ice
int
SessionControlServer::run(int, char*[])
{
    //
    // The server requires 3 separate server endpoints. One for the test
    // controller that will coordinate the tests and the required
    // configurations across the client and the router, an adapter for
    // the session manager for the router to communicate with and
    // finally, an adapter for the dummy backend server that the client
    // will ultimately attempt to make calls on. The backend uses a
    // servant locator that responds to each lookup with the same
    // servant, allowing us to use any reference as long as the client
    // expects to use a proxy for the correct type of object.
    //
    communicator()->getProperties()->setProperty("TestControllerAdapter.Endpoints",
                                                 getTestEndpoint(communicator(), 2, "tcp"));
    ObjectAdapterPtr controllerAdapter = communicator()->createObjectAdapter("TestControllerAdapter");
    TestControllerIPtr controller = new TestControllerI(getTestEndpoint(communicator(), 1));
    controllerAdapter->add(controller, Ice::stringToIdentity("testController"));
    controllerAdapter->activate();

    communicator()->getProperties()->setProperty("SessionControlAdapter.Endpoints", getTestEndpoint(communicator(), 0));
    ObjectAdapterPtr adapter = communicator()->createObjectAdapter("SessionControlAdapter");
    adapter->add(new SessionManagerI(controller), Ice::stringToIdentity("SessionManager"));
    adapter->activate();

    BackendPtr backend = new BackendI;
    communicator()->getProperties()->setProperty("BackendAdapter.Endpoints", getTestEndpoint(communicator(), 1));
    ObjectAdapterPtr backendAdapter = communicator()->createObjectAdapter("BackendAdapter");
    backendAdapter->addServantLocator(new ServantLocatorI(backend), "");
    backendAdapter->activate();

    Ice::LocatorPtr locator = new ServerLocatorI(backend, backendAdapter);
    backendAdapter->add(locator, Ice::stringToIdentity("locator"));

    communicator()->waitForShutdown();
    return EXIT_SUCCESS;
}
예제 #16
0
void
IceInternal::ObjectAdapterFactory::removeObjectAdapter(const ObjectAdapterPtr& adapter)
{
    IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(*this);

    if(!_instance)
    {
        return;
    }

    for(list<ObjectAdapterIPtr>::iterator p = _adapters.begin(); p != _adapters.end(); ++p)
    {
        if(*p == adapter)
        {
            _adapters.erase(p);
            break;
        }
    }
    _adapterNamesInUse.erase(adapter->getName());
}
예제 #17
0
bool
RegistryI::start(bool nowarn)
{
    assert(_communicator);
    PropertiesPtr properties = _communicator->getProperties();

    //
    // Initialize the database environment.
    //
    string dbPath = properties->getProperty("IceGrid.Registry.Data");
    if(dbPath.empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Data' is not set";
        return false;
    }
    else
    {
        struct stat filestat;
        if(stat(dbPath.c_str(), &filestat) != 0 || !S_ISDIR(filestat.st_mode))
        {
            Error out(_communicator->getLogger());
            SyscallException ex(__FILE__, __LINE__);
            ex.error = getSystemErrno();
            out << "property `IceGrid.Registry.Data' is set to an invalid path:\n" << ex;
            return false;
        }
    }

    //
    // Check that required properties are set and valid.
    //
    if(properties->getProperty("IceGrid.Registry.Client.Endpoints").empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Client.Endpoints' is not set";
        return false;
    }

    if(properties->getProperty("IceGrid.Registry.Server.Endpoints").empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Server.Endpoints' is not set";
        return false;
    }

    if(properties->getProperty("IceGrid.Registry.Internal.Endpoints").empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Internal.Endpoints' is not set";
        return false;
    }

    if(!properties->getProperty("IceGrid.Registry.SessionManager.Endpoints").empty())
    {
        if(!nowarn)
        {
            Warning out(_communicator->getLogger());
            out << "session manager endpoints `IceGrid.Registry.SessionManager.Endpoints' enabled";
        }
    }

    properties->setProperty("Ice.PrintProcessId", "0");
    properties->setProperty("Ice.ServerIdleTime", "0");
    properties->setProperty("IceGrid.Registry.Client.AdapterId", "");
    properties->setProperty("IceGrid.Registry.Server.AdapterId", "");
    properties->setProperty("IceGrid.Registry.SessionManager.AdapterId", "");
    properties->setProperty("IceGrid.Registry.Internal.AdapterId", "");

    setupThreadPool(properties, "Ice.ThreadPool.Client", 1, 100);
    setupThreadPool(properties, "IceGrid.Registry.Client.ThreadPool", 1, 10);
    setupThreadPool(properties, "IceGrid.Registry.Server.ThreadPool", 1, 10);
    setupThreadPool(properties, "IceGrid.Registry.SessionManager.ThreadPool", 1, 10);
    setupThreadPool(properties, "IceGrid.Registry.Internal.ThreadPool", 1, 100);

    _replicaName = properties->getPropertyWithDefault("IceGrid.Registry.ReplicaName", "Master");
    _master = _replicaName == "Master";
    _sessionTimeout = properties->getPropertyAsIntWithDefault("IceGrid.Registry.SessionTimeout", 30);

    //
    // Get the instance name
    //
    if(_master)
    {
        _instanceName = properties->getProperty("IceGrid.InstanceName");    
        if(_instanceName.empty())
        {
            if(_communicator->getDefaultLocator())
            {
                _instanceName = _communicator->getDefaultLocator()->ice_getIdentity().category;
            }
            else
            {
                _instanceName = "IceGrid";
            }
        }
    }
    else
    {
        if(properties->getProperty("Ice.Default.Locator").empty())
        {
            Error out(_communicator->getLogger());
            out << "property `Ice.Default.Locator' is not set";
            return false;
        }
        _instanceName = _communicator->getDefaultLocator()->ice_getIdentity().category;
    }

    //
    // Ensure that nothing is running on this port. This is also
    // useful to ensure that we don't run twice the same instance of
    // the service too (which would cause the database environment of
    // the already running instance to be "corrupted".)
    //
    try
    {
        string endpoints = properties->getProperty("IceGrid.Registry.Client.Endpoints");
        string strPrx = _instanceName + "/Locator:" + endpoints;
        _communicator->stringToProxy(strPrx)->ice_timeout(5000)->ice_ping();

        Error out(_communicator->getLogger());
        out << "an IceGrid registry is already running and listening on the client endpoints `" << endpoints << "'";
        return false;
    }
    catch(const Ice::LocalException&)
    {
    }
    
    properties->setProperty("Freeze.DbEnv.Registry.DbHome", dbPath);
    properties->setProperty("Freeze.DbEnv.Registry.DbPrivate", "0");

    //
    // Create the reaper thread.
    //
    _reaper = new ReapThread();
    _reaper->start();

    //
    // Create the internal registry object adapter.
    //
    ObjectAdapterPtr registryAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Internal");
    registryAdapter->activate();

    //
    // Create the internal IceStorm service.
    //
    Identity registryTopicManagerId;
    registryTopicManagerId.category = _instanceName;
    registryTopicManagerId.name = "RegistryTopicManager";
    _iceStorm = IceStorm::Service::create(_communicator, 
                                          registryAdapter, 
                                          registryAdapter, 
                                          "IceGrid.Registry", 
                                          registryTopicManagerId,
                                          "Registry");
    const IceStorm::TopicManagerPrx topicManager = _iceStorm->getTopicManager();

    //
    // Create the registry database.
    //
    _database = new Database(registryAdapter, topicManager, _instanceName, _traceLevels, getInfo());
    _wellKnownObjects = new WellKnownObjectsManager(_database);

    //
    // Get the saved replica/node proxies and remove them from the
    // database.
    //
    Ice::ObjectProxySeq proxies;
    Ice::ObjectProxySeq::const_iterator p;

    NodePrxSeq nodes;
    proxies = _database->getInternalObjectsByType(Node::ice_staticId());
    for(p = proxies.begin(); p != proxies.end(); ++p)
    {
        nodes.push_back(NodePrx::uncheckedCast(*p));
    }

    InternalRegistryPrxSeq replicas;
    proxies = _database->getObjectsByType(InternalRegistry::ice_staticId());
    for(p = proxies.begin(); p != proxies.end(); ++p)
    {
        replicas.push_back(InternalRegistryPrx::uncheckedCast(*p));
    }

    //
    // NOTE: The internal registry object must be added only once the
    // node/replica proxies are retrieved and removed from the
    // database. Otherwise, if some replica/node register as soon as
    // the internal registry is setup we might clear valid proxies.
    //
    InternalRegistryPrx internalRegistry = setupInternalRegistry(registryAdapter);
    if(_master)
    {
        nodes = registerReplicas(internalRegistry, replicas, nodes);
        registerNodes(internalRegistry, nodes);
    }
    else
    {
        InternalReplicaInfoPtr info = _platform.getInternalReplicaInfo();
        _session.create(_replicaName, info, _database, _wellKnownObjects, internalRegistry);
        registerNodes(internalRegistry, _session.getNodes(nodes));
    }

    ObjectAdapterPtr serverAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Server");
    _clientAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Client");
    ObjectAdapterPtr sessionManagerAdapter;
    if(!properties->getProperty("IceGrid.Registry.SessionManager.Endpoints").empty())
    {
        sessionManagerAdapter = _communicator->createObjectAdapter("IceGrid.Registry.SessionManager");
    }

    Ice::Identity dummy;
    dummy.name = "dummy";
    _wellKnownObjects->addEndpoint("Client", _clientAdapter->createDirectProxy(dummy));
    _wellKnownObjects->addEndpoint("Server", serverAdapter->createDirectProxy(dummy));
    if(sessionManagerAdapter)
    {
        _wellKnownObjects->addEndpoint("SessionManager", sessionManagerAdapter->createDirectProxy(dummy));
    }
    _wellKnownObjects->addEndpoint("Internal", registryAdapter->createDirectProxy(dummy));

    setupNullPermissionsVerifier(registryAdapter);
    if(!setupUserAccountMapper(registryAdapter))
    {
        return false;
    }

    QueryPrx query = setupQuery(_clientAdapter);
    RegistryPrx registry = setupRegistry(_clientAdapter);

    Ice::LocatorRegistryPrx locatorRegistry = setupLocatorRegistry(serverAdapter);
    LocatorPrx internalLocator = setupLocator(_clientAdapter, registryAdapter, locatorRegistry, registry, query);

    //
    // Add a default servant locator to the client object adapter. The
    // default servant ensure that request on session objects are from
    // the same connection as the connection that created the session.
    //
    _sessionServantLocator = new SessionServantLocatorI(_clientAdapter, _instanceName);
    _clientAdapter->addServantLocator(_sessionServantLocator, "");    
    
    setupClientSessionFactory(registryAdapter, sessionManagerAdapter, internalLocator, nowarn);
    setupAdminSessionFactory(registryAdapter, sessionManagerAdapter, internalLocator, nowarn);

    _wellKnownObjects->finish();
    if(_master)
    {
        _wellKnownObjects->registerAll();
    }
    else
    {
        _session.registerAllWellKnownObjects();
    }

    //
    // We are ready to go!
    //
    serverAdapter->activate();
    _clientAdapter->activate();
    if(sessionManagerAdapter)
    {
        sessionManagerAdapter->activate();
    }

    return true;
}
예제 #18
0
    virtual 
    void run()
    {
        CommunicatorPtr communicator = initialize(initData);
        ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:default -p 12347 -t 10000");
        Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase);
        communicator->setDefaultRouter(router);

        ostringstream os;
        os << "userid-" << _id;
        Glacier2::SessionPrx session = router->createSession(os.str(), "abc123");
        communicator->getProperties()->setProperty("Ice.PrintAdapterReady", "");
        ObjectAdapterPtr adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", router);
        adapter->activate();
        
        string category = router->getCategoryForClient();
        {
            Lock sync(*this);
            _callbackReceiver = new CallbackReceiverI;
            notify();
        }
        
        Identity ident;
        ident.name = "callbackReceiver";
        ident.category = category;
        CallbackReceiverPrx receiver = CallbackReceiverPrx::uncheckedCast(adapter->add(_callbackReceiver, ident));
        
        ObjectPrx base = communicator->stringToProxy("c1/callback:tcp -p 12010 -t 10000");
        base = base->ice_oneway();
        CallbackPrx callback = CallbackPrx::uncheckedCast(base);


        //
        // Block the CallbackReceiver in wait() to prevent the client from
        // processing other incoming calls and wait to receive the callback.
        //
        callback->initiateWaitCallback(receiver);
        test(_callbackReceiver->waitCallbackOK());

        //
        // Notify the main thread that the callback was received.
        //
        {
            Lock sync(*this);
            _callback = true;
            notify();
        }

        //
        // Callback the client with a large payload. This should cause
        // the Glacier2 request queue thread to block trying to send the
        // callback to the client because the client is currently blocked
        // in CallbackReceiverI::waitCallback() and can't process more 
        // requests.
        //
        callback->initiateCallbackWithPayload(receiver);
        test(_callbackReceiver->callbackWithPayloadOK());

        try
        {
            router->destroySession();
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }
        catch(const Ice::LocalException&)
        {
            test(false);
        }
        communicator->destroy();
    }
예제 #19
0
int
CallbackClient::run(int argc, char* argv[])
{
    ObjectPrx routerBase;

    {
        cout << "testing stringToProxy for router... " << flush;
        routerBase = communicator()->stringToProxy("Glacier2/router:default -p 12347 -t 10000");
        cout << "ok" << endl;
    }
    
    Glacier2::RouterPrx router;

    {
        cout << "testing checked cast for router... " << flush;
        router = Glacier2::RouterPrx::checkedCast(routerBase);
        test(router);
        cout << "ok" << endl;
    }

    {
        cout << "installing router with communicator... " << flush;
        communicator()->setDefaultRouter(router);
        cout << "ok" << endl;
    }

    {
        cout << "getting the session timeout... " << flush;
        Ice::Long timeout = router->getSessionTimeout();
        test(timeout == 30);
        cout << "ok" << endl;
    }

    ObjectPrx base;

    {
        cout << "testing stringToProxy for server object... " << flush;
        base = communicator()->stringToProxy("c1/callback:tcp -p 12010 -t 10000");
        cout << "ok" << endl;
    }
        
    {
        cout << "trying to ping server before session creation... " << flush;
        try
        {
            base->ice_ping();
            test(false);
        }
        catch(const ConnectionLostException&)
        {
            cout << "ok" << endl;
        }
    }

    Glacier2::SessionPrx session;

    {
        cout << "trying to create session with wrong password... " << flush;
        try
        {
            session = router->createSession("userid", "xxx");
            test(false);
        }
        catch(const Glacier2::PermissionDeniedException&)
        {
            cout << "ok" << endl;
        }
    }

    {
        cout << "trying to destroy non-existing session... " << flush;
        try
        {
            router->destroySession();
            test(false);
        }
        catch(const Glacier2::SessionNotExistException&)
        {
            cout << "ok" << endl;
        }
    }

    {
        cout << "creating session with correct password... " << flush;
        session = router->createSession("userid", "abc123");
        cout << "ok" << endl;
    }

    {
        cout << "trying to create a second session... " << flush;
        try
        {
            router->createSession("userid", "abc123");
            test(false);
        }
        catch(const Glacier2::CannotCreateSessionException&)
        {
            cout << "ok" << endl;
        }
    }

    {
        cout << "pinging server after session creation... " << flush;
        base->ice_ping();
        cout << "ok" << endl;
    }

    CallbackPrx twoway;

    {
        cout << "testing checked cast for server object... " << flush;
        twoway = CallbackPrx::checkedCast(base);
        test(twoway);
        cout << "ok" << endl;
    }

    ObjectAdapterPtr adapter;

    {
        cout << "creating and activating callback receiver adapter with router... " << flush;
        communicator()->getProperties()->setProperty("Ice.PrintAdapterReady", "0");
        adapter = communicator()->createObjectAdapterWithRouter("CallbackReceiverAdapter", router);
        adapter->activate();
        cout << "ok" << endl;
    }

    string category;

    {
        cout << "getting category from router... " << flush;
        category = router->getCategoryForClient();
        cout << "ok" << endl;
    }

    CallbackReceiverI* callbackReceiverImpl;
    ObjectPtr callbackReceiver;
    CallbackReceiverPrx twowayR;
    CallbackReceiverPrx fakeTwowayR;
    
    {
        cout << "creating and adding callback receiver object... " << flush;
        callbackReceiverImpl = new CallbackReceiverI;
        callbackReceiver = callbackReceiverImpl;
        Identity callbackReceiverIdent;
        callbackReceiverIdent.name = "callbackReceiver";
        callbackReceiverIdent.category = category;
        twowayR = CallbackReceiverPrx::uncheckedCast(adapter->add(callbackReceiver, callbackReceiverIdent));
        Identity fakeCallbackReceiverIdent;
        fakeCallbackReceiverIdent.name = "callbackReceiver";
        fakeCallbackReceiverIdent.category = "dummy";
        fakeTwowayR = CallbackReceiverPrx::uncheckedCast(adapter->add(callbackReceiver, fakeCallbackReceiverIdent));
        cout << "ok" << endl;
    }
    
    {
        cout << "testing oneway callback... " << flush;
        CallbackPrx oneway = CallbackPrx::uncheckedCast(twoway->ice_oneway());
        CallbackReceiverPrx onewayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_oneway());
        Context context;
        context["_fwd"] = "o";
        oneway->initiateCallback(onewayR, context);
        test(callbackReceiverImpl->callbackOK());
        cout << "ok" << endl;
    }

    {
        cout << "testing twoway callback... " << flush;
        Context context;
        context["_fwd"] = "t";
        twoway->initiateCallback(twowayR, context);
        test(callbackReceiverImpl->callbackOK());
        cout << "ok" << endl;
    }

    //
    // Send 3 twoway request to callback the receiver. The callback
    // receiver only reply to the callback once it received the 3
    // callbacks. This test ensures that Glacier2 doesn't serialize
    // twoway requests (see bug 337 for more information).
    //
    {
        cout << "testing concurrent twoway callback... " << flush;
        Context context;
        context["_fwd"] = "t";
        AMI_Callback_initiateConcurrentCallbackIPtr cb0 = new AMI_Callback_initiateConcurrentCallbackI();
        twoway->initiateConcurrentCallback_async(cb0, 0, twowayR, context);
        AMI_Callback_initiateConcurrentCallbackIPtr cb1 = new AMI_Callback_initiateConcurrentCallbackI();
        twoway->initiateConcurrentCallback_async(cb1, 1, twowayR, context);
        AMI_Callback_initiateConcurrentCallbackIPtr cb2 = new AMI_Callback_initiateConcurrentCallbackI();
        twoway->initiateConcurrentCallback_async(cb2, 2, twowayR, context);
        test(callbackReceiverImpl->answerConcurrentCallbacks(3));
        test(cb0->waitResponse() == 0);
        test(cb1->waitResponse() == 1);
        test(cb2->waitResponse() == 2);
        cout << "ok" << endl;
    }

    {
        cout << "ditto, but with user exception... " << flush;
        Context context;
        context["_fwd"] = "t";
        try
        {
            twoway->initiateCallbackEx(twowayR, context);
            test(false);
        }
        catch(const CallbackException& ex)
        {
            test(ex.someValue == 3.14);
            test(ex.someString == "3.14");
        }
        test(callbackReceiverImpl->callbackOK());
        cout << "ok" << endl;
    }

    {
        cout << "trying twoway callback with fake category... " << flush;
        Context context;
        context["_fwd"] = "t";
        try
        {
            twoway->initiateCallback(fakeTwowayR, context);
            test(false);
        }
        catch(const ObjectNotExistException&)
        {
            cout << "ok" << endl;
        }
    }

    {
        cout << "testing whether other allowed category is accepted... " << flush;
        Context context;
        context["_fwd"] = "t";
        CallbackPrx otherCategoryTwoway = CallbackPrx::uncheckedCast(
            twoway->ice_identity(communicator()->stringToIdentity("c2/callback")));
        otherCategoryTwoway->initiateCallback(twowayR, context);
        test(callbackReceiverImpl->callbackOK());
        cout << "ok" << endl;
    }

    {
        cout << "testing whether disallowed category gets rejected... " << flush;
        Context context;
        context["_fwd"] = "t";
        try
        {
            CallbackPrx otherCategoryTwoway = CallbackPrx::uncheckedCast(
                twoway->ice_identity(communicator()->stringToIdentity("c3/callback")));
            otherCategoryTwoway->initiateCallback(twowayR, context);
            test(false);
        }
        catch(const ObjectNotExistException&)
        {
            cout << "ok" << endl;
        }
    }

    {
        cout << "testing whether user-id as category is accepted... " << flush;
        Context context;
        context["_fwd"] = "t";
        CallbackPrx otherCategoryTwoway = CallbackPrx::uncheckedCast(
            twoway->ice_identity(communicator()->stringToIdentity("_userid/callback")));
        otherCategoryTwoway->initiateCallback(twowayR, context);
        test(callbackReceiverImpl->callbackOK());
        cout << "ok" << endl;
    }

    {
        cout << "testing buffered mode... " << flush;

        //
        // Start 3 misbehaving clients.
        //
        const int nClients = 3; // Passwords need to be added to the password file if more clients are needed.
        int i;
        vector<MisbehavedClientPtr> clients;
        for(i = 0; i < nClients; ++i)
        {
            clients.push_back(new MisbehavedClient(i));
            clients.back()->start();
            clients.back()->waitForCallback();
        }

        //
        // Sleep for one second to make sure the router starts sending
        // the callback with the payload to the clients.
        //
        IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1));

        //
        // Initiate few callbacks with a large payload. Because of 
        // the buffered mode, this shouldn't block even though the
        // misbehaved client are not answering their callback
        // requests.
        //
        Context context;
        context["_fwd"] = "t";
        twoway->initiateCallbackWithPayload(twowayR, context);
        test(callbackReceiverImpl->callbackWithPayloadOK());
        twoway->initiateCallbackWithPayload(twowayR, context);
        test(callbackReceiverImpl->callbackWithPayloadOK());
        twoway->initiateCallbackWithPayload(twowayR, context);
        test(callbackReceiverImpl->callbackWithPayloadOK());
        twoway->initiateCallbackWithPayload(twowayR, context);
        test(callbackReceiverImpl->callbackWithPayloadOK());

        for(vector<MisbehavedClientPtr>::const_iterator p = clients.begin(); p != clients.end(); ++p)
        {
            (*p)->notifyWaitCallback();
            (*p)->getThreadControl().join();
        }

        cout << "ok" << endl;
    }

    {
        cout << "stress test... " << flush;
        const int nClients = 3; // Passwords need to be added to the password file if more clients are needed.
        int i;
        vector<StressClientPtr> clients;
        for(i = 0; i < nClients; ++i)
        {
            switch(IceUtil::random(3))
            {
            case 0:
                clients.push_back(new PingStressClient(i));
                break;
            case 1:
                clients.push_back(new CallbackStressClient(i));
                break;
            case 2:
                clients.push_back(new CallbackWithPayloadStressClient(i));
                break;
            default:
                assert(false);
                break;
            }
            clients.back()->start();
        }
        for(vector<StressClientPtr>::const_iterator p = clients.begin(); p != clients.end(); ++p)
        {
            (*p)->notifyThread();
        }

        //
        // Let the stress client run for a bit.
        //
        IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(3));

        //
        // Send some callbacks.
        //
        Context context;
        context["_fwd"] = "t";
        twoway->initiateCallback(twowayR);
        test(callbackReceiverImpl->callbackOK());

        //
        // Kill the stress clients.
        //
        for(vector<StressClientPtr>::const_iterator q = clients.begin(); q != clients.end(); ++q)
        {
            (*q)->kill();
            (*q)->getThreadControl().join();
        }


        cout << "ok" << endl;
    }

    {
        cout << "testing server shutdown... " << flush;
        twoway->shutdown();
        // No ping, otherwise the router prints a warning message if it's
        // started with --Ice.Warn.Connections.
        cout << "ok" << endl;
        /*
          try
          {
          base->ice_ping();
          test(false);
          }
          // If we use the glacier router, the exact exception reason gets
          // lost.
          catch(const UnknownLocalException&)
          {
          cout << "ok" << endl;
          }
        */
    }
    
    {
        cout << "destroying session... " << flush;
        try
        {
            router->destroySession();
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }
        catch(const Ice::LocalException&)
        {
            test(false);
        }
        cout << "ok" << endl;
    }

    {
        cout << "trying to ping server after session destruction... " << flush;
        try
        {
            base->ice_ping();
            test(false);
        }
        catch(const ConnectionLostException&)
        {
            cout << "ok" << endl;
        }
    }

    if(argc >= 2 && strcmp(argv[1], "--shutdown") == 0)
    {
        {
            cout << "uninstalling router with communicator... " << flush;
            communicator()->setDefaultRouter(0);
            cout << "ok" << endl;
        }

        ObjectPrx adminBase;

        {
            cout << "testing stringToProxy for admin object... " << flush;
            adminBase = communicator()->stringToProxy("Glacier2/admin:tcp -h 127.0.0.1 -p 12348 -t 10000");
            cout << "ok" << endl;
        }
        
/*
        {
            cout << "uninstalling router with admin object... " << flush;
            adminBase->ice_router(0);
            cout << "ok" << endl;
        }
*/

        Glacier2::AdminPrx admin;
        
        {
            cout << "testing checked cast for admin object... " << flush;
            admin = Glacier2::AdminPrx::checkedCast(adminBase);
            test(admin);
            cout << "ok" << endl;
        }

        cout << "testing Glacier2 shutdown... " << flush;
        admin->shutdown();
        try
        {
            admin->ice_ping();
            test(false);
        }
        catch(const Ice::LocalException&)
        {
            cout << "ok" << endl;
        }
    }
    
    return EXIT_SUCCESS;
}
예제 #20
0
파일: Client.cpp 프로젝트: chenbk85/ice
int
Client::run(StringSeq& originalArgs)
{
    string commands;
    bool debug;

    IceUtilInternal::Options opts;
    opts.addOpt("h", "help");
    opts.addOpt("v", "version");
    opts.addOpt("e", "", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::Repeat);
    opts.addOpt("i", "instanceName", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("H", "host", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("P", "port", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("u", "username", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("p", "password", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);
    opts.addOpt("S", "ssl");
    opts.addOpt("d", "debug");
    opts.addOpt("s", "server");
    opts.addOpt("r", "replica", IceUtilInternal::Options::NeedArg, "", IceUtilInternal::Options::NoRepeat);

    vector<string> args;
    try
    {
        args = opts.parse(originalArgs);
    }
    catch(const IceUtilInternal::BadOptException& e)
    {
        cerr << e.reason << endl;
        usage();
        return EXIT_FAILURE;
    }
    if(!args.empty())
    {
        cerr << _appName << ": too many arguments" << endl;
        usage();
        return EXIT_FAILURE;
    }

    if(opts.isSet("help"))
    {
        usage();
        return EXIT_SUCCESS;
    }
    if(opts.isSet("version"))
    {
        cout << ICE_STRING_VERSION << endl;
        return EXIT_SUCCESS;
    }

    if(opts.isSet("server"))
    {
        ObjectAdapterPtr adapter =
            communicator()->createObjectAdapterWithEndpoints("FileParser", "tcp -h localhost");
        adapter->activate();
        ObjectPrx proxy = adapter->add(new FileParserI, communicator()->stringToIdentity("FileParser"));
        cout << proxy << endl;

        communicator()->waitForShutdown();
        return EXIT_SUCCESS;
    }

    if(opts.isSet("e"))
    {
        vector<string> optargs = opts.argVec("e");
        for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i)
        {
            commands += *i + ";";
        }
    }
    debug = opts.isSet("debug");

    bool ssl = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.AuthenticateUsingSSL");
    if(opts.isSet("ssl"))
    {
        ssl = true;
    }

    string id = communicator()->getProperties()->getProperty("IceGridAdmin.Username");
    if(!opts.optArg("username").empty())
    {
        id = opts.optArg("username");
    }
    string password = communicator()->getProperties()->getProperty("IceGridAdmin.Password");
    if(!opts.optArg("password").empty())
    {
        password = opts.optArg("password");
    }

    string host = communicator()->getProperties()->getProperty("IceGridAdmin.Host");
    if(!opts.optArg("host").empty())
    {
        host = opts.optArg("host");
    }

    string instanceName = communicator()->getProperties()->getProperty("IceGridAdmin.InstanceName");
    if(!opts.optArg("instanceName").empty())
    {
        instanceName = opts.optArg("instanceName");
    }

    int port = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.Port");
    if(!opts.optArg("port").empty())
    {
        istringstream is(opts.optArg("port"));
        if(!(is >> port))
        {
            cerr << _appName << ": given port number is not a numeric value" << endl;
            return EXIT_FAILURE;
        }
    }
예제 #21
0
파일: Subscriber.cpp 프로젝트: chenbk85/ice
int
run(int, char* argv[], const CommunicatorPtr& communicator)
{
    PropertiesPtr properties = communicator->getProperties();
    const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default";
    string managerProxy = properties->getProperty(managerProxyProperty);
    if(managerProxy.empty())
    {
        cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl;
        return EXIT_FAILURE;
    }

    ObjectPrx base = communicator->stringToProxy(managerProxy);
    IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base);
    if(!manager)
    {
        cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl;
        return EXIT_FAILURE;
    }

    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default:udp");

    //
    // Test topic name that is too long
    //
    if(string(argv[1]) != "transient")
    {
        try
        {
            manager->create(string(512, 'A'));
            test(false);
        }
        catch(const Ice::UnknownException&)
        {
        }
    }

    TopicPrx topic;
    try
    {
        topic = manager->retrieve("single");
    }
    catch(const IceStorm::NoSuchTopic& e)
    {
        cerr << argv[0] << ": NoSuchTopic: " << e.name << endl;
        return EXIT_FAILURE;
    }

    //
    // Test subscriber identity that is too long
    //
    if(string(argv[1]) != "transient")
    {
        try
        {
            Ice::ObjectPrx object = communicator->stringToProxy(string(512, 'A') + ":default -p 10000");
            topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
            test(false);
        }
        catch(const Ice::UnknownException&)
        {
        }
    }

    //
    // Create subscribers with different QoS.
    //
    vector<SingleIPtr> subscribers;
    vector<Ice::Identity> subscriberIdentities;

    {
        subscribers.push_back(new SingleI(communicator, "default"));
        Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back())->ice_oneway();
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
    }
    {
        subscribers.push_back(new SingleI(communicator, "oneway"));
        Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back())->ice_oneway();
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
    }
    {
        subscribers.push_back(new SingleI(communicator, "twoway"));
        Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back());
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
    }
    {
        subscribers.push_back(new SingleI(communicator, "batch"));
        Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back())->ice_batchOneway();
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
    }
    {
        subscribers.push_back(new SingleI(communicator, "twoway ordered")); // Ordered
        IceStorm::QoS qos;
        qos["reliability"] = "ordered";
        Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back());
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(qos, object);
    }
    {
        // Use a separate adapter to ensure a separate connection is used for the subscriber
        // (otherwise, if multiple UDP subscribers use the same connection we might get high
        // packet loss, see bug 1784).
        ObjectAdapterPtr adpt = communicator->createObjectAdapterWithEndpoints("UdpAdapter3", "udp");
        subscribers.push_back(new SingleI(communicator, "datagram"));
        Ice::ObjectPrx object = adpt->addWithUUID(subscribers.back())->ice_datagram();
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
        adpt->activate();
    }
    {
        // Use a separate adapter to ensure a separate connection is used for the subscriber
        // (otherwise, if multiple UDP subscribers use the same connection we might get high
        // packet loss, see bug 1784).
        ObjectAdapterPtr adpt = communicator->createObjectAdapterWithEndpoints("UdpAdapter4", "udp");
        subscribers.push_back(new SingleI(communicator, "batch datagram"));
        Ice::ObjectPrx object = adpt->addWithUUID(subscribers.back())->ice_batchDatagram();
        subscriberIdentities.push_back(object->ice_getIdentity());
        topic->subscribeAndGetPublisher(IceStorm::QoS(), object);
        adpt->activate();
    }

    adapter->activate();

    vector<Ice::Identity> ids = topic->getSubscribers();
    test(ids.size() == subscriberIdentities.size());
    for(vector<Ice::Identity>::const_iterator i = ids.begin(); i != ids.end(); ++i)
    {
        test(find(subscriberIdentities.begin(), subscriberIdentities.end(), *i) != subscriberIdentities.end());
    }

    for(vector<SingleIPtr>::const_iterator p = subscribers.begin(); p != subscribers.end(); ++p)
    {
        (*p)->waitForEvents();
    }

    return EXIT_SUCCESS;
}
예제 #22
0
int
run(int argc, char* argv[], const CommunicatorPtr& communicator)
{
    bool batch = false;

    int idx = 1;
    while(idx < argc)
    {
        if(strcmp(argv[idx], "-b") == 0)
        {
            batch = true;

            for(int i = idx ; i + 1 < argc ; ++i)
            {
                argv[i] = argv[i + 1];
            }
            --argc;
        }
        else if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0)
        {
            usage(argv[0]);
            return EXIT_SUCCESS;
        }
        else if(argv[idx][0] == '-')
        {
            cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl;
            usage(argv[0]);
            return EXIT_FAILURE;
        }
    }

    PropertiesPtr properties = communicator->getProperties();
    const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default";
    string managerProxy = properties->getProperty(managerProxyProperty);
    if(managerProxy.empty())
    {
        cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl;
        return EXIT_FAILURE;
    }

    ObjectPrx base = communicator->stringToProxy(managerProxy);
    IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base);
    if(!manager)
    {
        cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl;
        return EXIT_FAILURE;
    }

    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default");
    EventIPtr eventFed1 = new EventI(communicator);

    //
    // Activate the servants.
    //
    ObjectPrx obj = adapter->addWithUUID(eventFed1);

    IceStorm::QoS qos;
    if(batch)
    {
        obj = obj->ice_batchOneway();
    }
    else
    {
        obj = obj->ice_oneway();
    }

    TopicPrx fed1;

    try
    {
        fed1 = manager->retrieve("fed1");
    }
    catch(const IceStorm::NoSuchTopic& e)
    {
        cerr << argv[0] << ": NoSuchTopic: " << e.name << endl;
        return EXIT_FAILURE;
    }

    fed1->subscribeAndGetPublisher(qos, obj);

    adapter->activate();

    communicator->waitForShutdown();

    fed1->unsubscribe(obj);

    return EXIT_SUCCESS;
}
예제 #23
0
파일: Sub.cpp 프로젝트: bholl/zeroc-ice
int
run(int argc, char* argv[], const CommunicatorPtr& communicator)
{
    IceUtilInternal::Options opts;
    opts.addOpt("", "id", IceUtilInternal::Options::NeedArg);
    opts.addOpt("", "unsub");

    try
    {
        opts.parse(argc, (const char**)argv);
    }
    catch(const IceUtilInternal::BadOptException& e)
    {
        cerr << argv[0] << ": " << e.reason << endl;
        return EXIT_FAILURE;
    }

    PropertiesPtr properties = communicator->getProperties();
    const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default";
    string managerProxy = properties->getProperty(managerProxyProperty);
    if(managerProxy.empty())
    {
        cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl;
        return EXIT_FAILURE;
    }

    ObjectPrx base = communicator->stringToProxy(managerProxy);
    IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base);
    if(!manager)
    {
        cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl;
        return EXIT_FAILURE;
    }

    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default");

    TopicPrx topic;
    try
    {
        topic = manager->retrieve("single");
    }
    catch(const IceStorm::NoSuchTopic& e)
    {
        cerr << argv[0] << ": NoSuchTopic: " << e.name << endl;
        return EXIT_FAILURE;
    }

    Ice::ObjectPrx prx = adapter->add(new SingleI(), communicator->stringToIdentity(opts.optArg("id")));
    if(opts.isSet("unsub"))
    {
        topic->unsubscribe(prx);
    }
    else
    {
        IceStorm::QoS qos;
        qos["persistent"] = "true";
        topic->subscribeAndGetPublisher(qos, prx);
    }

    return EXIT_SUCCESS;
}
예제 #24
0
bool
RegistryI::startImpl()
{
    assert(_communicator);
    PropertiesPtr properties = _communicator->getProperties();

    //
    // Check that required properties are set and valid.
    //
    if(properties->getProperty("IceGrid.Registry.Client.Endpoints").empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Client.Endpoints' is not set";
        return false;
    }

    if(properties->getProperty("IceGrid.Registry.Server.Endpoints").empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Server.Endpoints' is not set";
        return false;
    }

    if(properties->getProperty("IceGrid.Registry.Internal.Endpoints").empty())
    {
        Error out(_communicator->getLogger());
        out << "property `IceGrid.Registry.Internal.Endpoints' is not set";
        return false;
    }

    if(!properties->getProperty("IceGrid.Registry.SessionManager.Endpoints").empty())
    {
        if(!_nowarn)
        {
            Warning out(_communicator->getLogger());
            out << "session manager endpoints `IceGrid.Registry.SessionManager.Endpoints' enabled";
            if(properties->getPropertyAsInt("IceGrid.Registry.SessionFilters") == 0)
            {
                out << " (with Glacier2 filters disabled)";
            }
        }
    }

    if(!properties->getProperty("IceGrid.Registry.AdminSessionManager.Endpoints").empty())
    {
        if(!_nowarn)
        {
            Warning out(_communicator->getLogger());
            out << "administrative session manager endpoints `IceGrid.Registry.AdminSessionManager.Endpoints' enabled";
            if(properties->getPropertyAsInt("IceGrid.Registry.AdminSessionFilters") == 0)
            {
                out << " (with Glacier2 filters disabled)";
            }
        }
    }

    properties->setProperty("Ice.PrintProcessId", "0");
    properties->setProperty("Ice.ServerIdleTime", "0");
    properties->setProperty("IceGrid.Registry.Client.AdapterId", "");
    properties->setProperty("IceGrid.Registry.Server.AdapterId", "");
    properties->setProperty("IceGrid.Registry.SessionManager.AdapterId", "");
    properties->setProperty("IceGrid.Registry.Internal.AdapterId", "");

    setupThreadPool(properties, "IceGrid.Registry.Client.ThreadPool", 1, 10);
    setupThreadPool(properties, "IceGrid.Registry.Server.ThreadPool", 1, 10, true); // Serialize for admin callbacks
    setupThreadPool(properties, "IceGrid.Registry.SessionManager.ThreadPool", 1, 10);
    setupThreadPool(properties, "IceGrid.Registry.Internal.ThreadPool", 1, 100);

    _replicaName = properties->getPropertyWithDefault("IceGrid.Registry.ReplicaName", "Master");
    _master = _replicaName == "Master";
    _sessionTimeout = properties->getPropertyAsIntWithDefault("IceGrid.Registry.SessionTimeout", 30);

    if(!_master && properties->getProperty("Ice.Default.Locator").empty())
    {
        if(properties->getProperty("Ice.Default.Locator").empty())
        {
            Error out(_communicator->getLogger());
            out << "property `Ice.Default.Locator' is not set";
            return false;
        }
    }

    //
    // Get the instance name
    //
    if(_master)
    {
        _instanceName = properties->getProperty("IceGrid.InstanceName");    
        if(_instanceName.empty())
        {
            if(_communicator->getDefaultLocator())
            {
                _instanceName = _communicator->getDefaultLocator()->ice_getIdentity().category;
            }
            else
            {
                _instanceName = "IceGrid";
            }
        }
    }
    else
    {
        _instanceName = _communicator->getDefaultLocator()->ice_getIdentity().category;
    }

    //
    // Ensure that nothing is running on this port. This is also
    // useful to ensure that we don't run twice the same instance of
    // the service too (which would cause the database environment of
    // the already running instance to be "corrupted".)
    //
    try
    {
        string endpoints = properties->getProperty("IceGrid.Registry.Client.Endpoints");
        string strPrx = _instanceName + "/Locator:" + endpoints;
        _communicator->stringToProxy(strPrx)->ice_timeout(5000)->ice_ping();

        Error out(_communicator->getLogger());
        out << "an IceGrid registry is already running and listening on the client endpoints `" << endpoints << "'";
        return false;
    }
    catch(const Ice::LocalException&)
    {
    }
    
    //
    // Create the reaper thread.
    //
    _reaper = new ReapThread();
    _reaper->start();

    //
    // Create the internal registry object adapter.
    //
    ObjectAdapterPtr registryAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Internal");
    registryAdapter->activate();

    //
    // Create the internal IceStorm service.
    //
    Identity registryTopicManagerId;
    registryTopicManagerId.category = _instanceName;
    registryTopicManagerId.name = "RegistryTopicManager";
    _iceStorm = IceStormInternal::Service::create(_communicator, 
					          registryAdapter, 
                                          	  registryAdapter, 
                                          	  "IceGrid.Registry", 
                                          	  registryTopicManagerId,
                                          	  "Registry");
    const IceStorm::TopicManagerPrx topicManager = _iceStorm->getTopicManager();

    //
    // Create the registry database.
    //
    DatabasePluginPtr plugin;
    try
    {
        plugin = DatabasePluginPtr::dynamicCast(_communicator->getPluginManager()->getPlugin("DB"));
    }
    catch(const NotRegisteredException&)
    {
    }
    if(!plugin)
    {
        Error out(_communicator->getLogger());
        out << "no database plugin configured with `Ice.Plugin.DB' or plugin is not a database plugin";
        return false;
    }
    
    _database = new Database(registryAdapter, topicManager, _instanceName, _traceLevels, getInfo(), plugin, _readonly);
    _wellKnownObjects = new WellKnownObjectsManager(_database);

    //
    // Get the saved replica/node proxies.
    //
    ObjectProxySeq proxies;
    ObjectProxySeq::const_iterator p;

    NodePrxSeq nodes;
    proxies = _database->getInternalObjectsByType(Node::ice_staticId());
    for(p = proxies.begin(); p != proxies.end(); ++p)
    {
        nodes.push_back(NodePrx::uncheckedCast(*p));
    }

    InternalRegistryPrxSeq replicas;
    proxies = _database->getObjectsByType(InternalRegistry::ice_staticId());
    for(p = proxies.begin(); p != proxies.end(); ++p)
    {
        replicas.push_back(InternalRegistryPrx::uncheckedCast(*p));
    }

    //
    // NOTE: The internal registry object must be added only once the
    // node/replica proxies are retrieved. Otherwise, if some
    // replica/node register as soon as the internal registry is setup
    // we might clear valid proxies.
    //
    InternalRegistryPrx internalRegistry = setupInternalRegistry(registryAdapter);
    if(_master)
    {
        nodes = registerReplicas(internalRegistry, replicas, nodes);
        registerNodes(internalRegistry, nodes);
    }
    else
    {
        InternalReplicaInfoPtr info = _platform.getInternalReplicaInfo();
        _session.create(_replicaName, info, _database, _wellKnownObjects, internalRegistry);
        registerNodes(internalRegistry, _session.getNodes(nodes));
    }

    _serverAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Server");
    _clientAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Client");

    Ice::Identity dummy;
    dummy.name = "dummy";
    _wellKnownObjects->addEndpoint("Client", _clientAdapter->createDirectProxy(dummy));
    _wellKnownObjects->addEndpoint("Server", _serverAdapter->createDirectProxy(dummy));
    _wellKnownObjects->addEndpoint("Internal", registryAdapter->createDirectProxy(dummy));

    setupNullPermissionsVerifier(registryAdapter);
    if(!setupUserAccountMapper(registryAdapter))
    {
        return false;
    }

    QueryPrx query = setupQuery(_clientAdapter);
    RegistryPrx registry = setupRegistry(_clientAdapter);

    Ice::LocatorRegistryPrx locatorRegistry = setupLocatorRegistry(_serverAdapter);
    LocatorPrx internalLocator = setupLocator(_clientAdapter, registryAdapter, locatorRegistry, registry, query);

    //
    // Create the session servant manager. The session servant manager is responsible
    // for managing sessions servants and to ensure that session servants are only 
    // accessed by the connection that created the session. The session servant manager
    // also takes care of providing the router servant for server admin objects.
    //
    ObjectPtr serverAdminRouter = new RegistryServerAdminRouter(_database);
    AdminCallbackRouterPtr adminCallbackRouter = new AdminCallbackRouter;

    _servantManager = new SessionServantManager(_clientAdapter, _instanceName, true, getServerAdminCategory(), 
                                                serverAdminRouter, adminCallbackRouter);

    _clientAdapter->addServantLocator(_servantManager, "");
    _serverAdapter->addServantLocator(new DefaultServantLocator(adminCallbackRouter), "");
    
    ObjectAdapterPtr sessionAdpt = setupClientSessionFactory(registryAdapter, internalLocator);
    ObjectAdapterPtr admSessionAdpt = setupAdminSessionFactory(registryAdapter, serverAdminRouter, internalLocator);

    _wellKnownObjects->finish();
    if(_master)
    {
        _wellKnownObjects->registerAll();
    }
    else
    {
        _session.registerAllWellKnownObjects();
    }

    //
    // We are ready to go!
    //
    _serverAdapter->activate();
    _clientAdapter->activate();
  
    if(sessionAdpt)
    {
        sessionAdpt->activate();
    }
    if(admSessionAdpt)
    {
        admSessionAdpt->activate();
    }

    return true;
}
예제 #25
0
Glacier2::PermissionsVerifierPrx
RegistryI::getPermissionsVerifier(const ObjectAdapterPtr& adapter, 
                                  const IceGrid::LocatorPrx& locator,
                                  const string& verifierProperty,
                                  const string& passwordsProperty)
{
    //
    // Get the permissions verifier, or create a default one if no
    // verifier is specified.
    //

    ObjectPrx verifier;
    string verifierPropertyValue = _communicator->getProperties()->getProperty(verifierProperty);
    if(!verifierPropertyValue.empty())
    {
        try
        {
            try
            {
                verifier = _communicator->propertyToProxy(verifierProperty);
            }
            catch(const ProxyParseException&)
            {
                //
                // Check if the property is just the identity of the null permissions verifier
                // (the identity might contain spaces which would prevent it to be parsed as a
                // proxy).
                //
                if(_communicator->stringToIdentity(verifierPropertyValue) ==
                   _nullPermissionsVerifier->ice_getIdentity())
                {
                    verifier = _communicator->stringToProxy("\"" + verifierPropertyValue + "\"");
                }
            }

            if(!verifier)
            {
                Error out(_communicator->getLogger());
                out << "permissions verifier `" + verifierPropertyValue + "' is invalid";
                return 0;
            }
            assert(_nullPermissionsVerifier);

            if(verifier->ice_getIdentity() == _nullPermissionsVerifier->ice_getIdentity())
            {
                verifier = _nullPermissionsVerifier;
            }
        }
        catch(const LocalException& ex)
        {
            Error out(_communicator->getLogger());
            out << "permissions verifier `" + verifierPropertyValue + "' is invalid:\n" << ex;
            return 0;
        }
    }
    else if(!passwordsProperty.empty())
    {
        //
        // No nativeToUTF8 conversion necessary here, since no string
        // converter is installed by IceGrid the string is UTF-8.
        //
        IceUtilInternal::ifstream passwordFile(passwordsProperty);
        if(!passwordFile)
        {
            Error out(_communicator->getLogger());
            string err = strerror(errno);
            out << "cannot open `" + passwordsProperty + "' for reading: " + err;
            return 0;
        }

        map<string, string> passwords;

        while(true)
        {
            string userId;
            passwordFile >> userId;
            if(!passwordFile)
            {
                break;
            }

            string password;
            passwordFile >> password;
            if(!passwordFile)
            {
                break;
            }

            assert(!userId.empty());
            assert(!password.empty());
            passwords.insert(make_pair(userId, password));
        }

        verifier = adapter->addWithUUID(new CryptPermissionsVerifierI(passwords));
    }
bool
RouterService::start(int argc, char* argv[], int& status)
{
    bool nowarn;

    IceUtilInternal::Options opts;
    opts.addOpt("h", "help");
    opts.addOpt("v", "version");
    opts.addOpt("", "nowarn");

    vector<string> args;
    try
    {
        args = opts.parse(argc, const_cast<const char**>(argv));
    }
    catch(const IceUtilInternal::BadOptException& e)
    {
        error(e.reason);
        usage(argv[0]);
        return false;
    }

    if(opts.isSet("help"))
    {
        usage(argv[0]);
        status = EXIT_SUCCESS;
        return false;
    }
    if(opts.isSet("version"))
    {
        print(ICE_STRING_VERSION);
        status = EXIT_SUCCESS;
        return false;
    }
    nowarn = opts.isSet("nowarn");

    if(!args.empty())
    {
        consoleErr << argv[0] << ": too many arguments" << endl;
        usage(argv[0]);
        return false;
    }

    PropertiesPtr properties = communicator()->getProperties();

    //
    // Initialize the client object adapter.
    //
    const string clientEndpointsProperty = "Glacier2.Client.Endpoints";
    if(properties->getProperty(clientEndpointsProperty).empty())
    {
        error("property `" + clientEndpointsProperty + "' is not set");
        return false;
    }

    if(properties->getPropertyAsInt("Glacier2.SessionTimeout") > 0 &&
       properties->getProperty("Glacier2.Client.ACM.Timeout").empty())
    {
        ostringstream os;
        os << properties->getPropertyAsInt("Glacier2.SessionTimeout");
        properties->setProperty("Glacier2.Client.ACM.Timeout", os.str());
    }

    if(properties->getProperty("Glacier2.Client.ACM.Close").empty())
    {
        properties->setProperty("Glacier2.Client.ACM.Close", "4"); // Forcefull close on invocation and idle.
    }

    ObjectAdapterPtr clientAdapter = communicator()->createObjectAdapter("Glacier2.Client");

    //
    // Initialize the server object adapter only if server endpoints
    // are defined.
    //
    const string serverEndpointsProperty = "Glacier2.Server.Endpoints";
    ObjectAdapterPtr serverAdapter;
    if(!properties->getProperty(serverEndpointsProperty).empty())
    {
        serverAdapter = communicator()->createObjectAdapter("Glacier2.Server");
    }

    string instanceName = communicator()->getProperties()->getPropertyWithDefault("Glacier2.InstanceName", "Glacier2");

    vector<string> verifierProperties;
    verifierProperties.push_back("Glacier2.PermissionsVerifier");
    verifierProperties.push_back("Glacier2.SSLPermissionsVerifier");

    Glacier2Internal::setupNullPermissionsVerifier(communicator(), instanceName, verifierProperties);

    string verifierProperty = verifierProperties[0];
    PermissionsVerifierPrx verifier;
    ObjectPrx obj;
    try
    {
        //
        // We use propertyToProxy instead of stringToProxy because the property
        // can provide proxy attributes
        //
        obj = communicator()->propertyToProxy(verifierProperty);
    }
    catch(const std::exception& ex)
    {
        ServiceError err(this);
        err << "permissions verifier `" << communicator()->getProperties()->getProperty(verifierProperty)
            << "' is invalid:\n" << ex;
        return false;
    }

    if(obj)
    {
        try
        {
            verifier = PermissionsVerifierPrx::checkedCast(obj);
            if(!verifier)
            {
                ServiceError err(this);
                err << "permissions verifier `" << communicator()->getProperties()->getProperty(verifierProperty)
                    << "' is invalid";
                return false;
            }
        }
        catch(const Ice::Exception& ex)
        {
            if(!nowarn)
            {
                ServiceWarning warn(this);
                warn << "unable to contact permissions verifier `"
                     << communicator()->getProperties()->getProperty(verifierProperty) << "'\n" << ex;
            }
            verifier = PermissionsVerifierPrx::uncheckedCast(obj);
        }
    }

    //
    // Get the session manager if specified.
    //
    string sessionManagerProperty = "Glacier2.SessionManager";
    string sessionManagerPropertyValue = properties->getProperty(sessionManagerProperty);
    SessionManagerPrx sessionManager;
    if(!sessionManagerPropertyValue.empty())
    {
        try
        {
            obj = communicator()->propertyToProxy(sessionManagerProperty);
        }
        catch(const std::exception& ex)
        {
            ServiceError err(this);
            err << "session manager `" << sessionManagerPropertyValue << "' is invalid\n:" << ex;
            return false;
        }
        try
        {
            sessionManager = SessionManagerPrx::checkedCast(obj);
            if(!sessionManager)
            {
                error("session manager `" + sessionManagerPropertyValue + "' is invalid");
                return false;
            }
        }
        catch(const std::exception& ex)
        {
            if(!nowarn)
            {
                ServiceWarning warn(this);
                warn << "unable to contact session manager `" << sessionManagerPropertyValue << "'\n" << ex;
            }
            sessionManager = SessionManagerPrx::uncheckedCast(obj);
        }
        sessionManager =
            SessionManagerPrx::uncheckedCast(sessionManager->ice_connectionCached(false)->ice_locatorCacheTimeout(
                properties->getPropertyAsIntWithDefault("Glacier2.SessionManager.LocatorCacheTimeout", 600)));
    }

    //
    // Check for an SSL permissions verifier.
    //
    string sslVerifierProperty = verifierProperties[1];
    SSLPermissionsVerifierPrx sslVerifier;

    try
    {
        obj = communicator()->propertyToProxy(sslVerifierProperty);
    }
    catch(const std::exception& ex)
    {
        ServiceError err(this);
        err << "ssl permissions verifier `" << communicator()->getProperties()->getProperty(sslVerifierProperty)
            << "' is invalid:\n" << ex;
        return false;
    }

    if(obj)
    {
        try
        {
            sslVerifier = SSLPermissionsVerifierPrx::checkedCast(obj);
            if(!sslVerifier)
            {
                ServiceError err(this);
                err << "ssl permissions verifier `"
                    << communicator()->getProperties()->getProperty(sslVerifierProperty)
                    << "' is invalid";
            }
        }
        catch(const Ice::Exception& ex)
        {
            if(!nowarn)
            {
                ServiceWarning warn(this);
                warn << "unable to contact ssl permissions verifier `"
                     <<  communicator()->getProperties()->getProperty(sslVerifierProperty) << "'\n"
                     << ex;
            }
            sslVerifier = SSLPermissionsVerifierPrx::uncheckedCast(obj);
        }
    }

    //
    // Get the SSL session manager if specified.
    //
    string sslSessionManagerProperty = "Glacier2.SSLSessionManager";
    string sslSessionManagerPropertyValue = properties->getProperty(sslSessionManagerProperty);
    SSLSessionManagerPrx sslSessionManager;
    if(!sslSessionManagerPropertyValue.empty())
    {
        try
        {
            obj = communicator()->propertyToProxy(sslSessionManagerProperty);
        }
        catch(const std::exception& ex)
        {
            ServiceError err(this);
            err << "ssl session manager `" << sslSessionManagerPropertyValue << "' is invalid:\n" << ex;
            return false;
        }
        try
        {
            sslSessionManager = SSLSessionManagerPrx::checkedCast(obj);
            if(!sslSessionManager)
            {
                error("ssl session manager `" + sslSessionManagerPropertyValue + "' is invalid");
                return false;
            }
        }
        catch(const Ice::Exception& ex)
        {
            if(!nowarn)
            {
                ServiceWarning warn(this);
                warn << "unable to contact ssl session manager `" << sslSessionManagerPropertyValue
                     << "'\n" << ex;
            }
            sslSessionManager = SSLSessionManagerPrx::uncheckedCast(obj);
        }
        sslSessionManager =
            SSLSessionManagerPrx::uncheckedCast(sslSessionManager->ice_connectionCached(false)->ice_locatorCacheTimeout(
                properties->getPropertyAsIntWithDefault("Glacier2.SSLSessionManager.LocatorCacheTimeout", 600)));
    }

    if(!verifier && !sslVerifier)
    {
        error("Glacier2 requires a permissions verifier or password file");
        return false;
    }

    //
    // Create the instance object.
    //
    try
    {
        _instance = new Glacier2::Instance(communicator(), clientAdapter, serverAdapter);
    }
    catch(const Ice::InitializationException& ex)
    {
        error("Glacier2 initialization failed:\n" + ex.reason);
        return false;
    }

    //
    // Create the session router. The session router registers itself
    // and all required servant locators, so no registration has to be
    // done here.
    //
    _sessionRouter = new SessionRouterI(_instance, verifier, sessionManager, sslVerifier, sslSessionManager);

    //
    // Th session router is used directly as servant for the main
    // Glacier2 router Ice object.
    //
    Identity routerId;
    routerId.category = instanceName;
    routerId.name = "router";
    Glacier2::RouterPrx routerPrx = Glacier2::RouterPrx::uncheckedCast(clientAdapter->add(_sessionRouter, routerId));

    //
    // Add the Ice router finder object to allow retrieving the router
    // proxy with just the endpoint information of the router.
    //
    Identity finderId;
    finderId.category = "Ice";
    finderId.name = "RouterFinder";
    clientAdapter->add(new FinderI(routerPrx), finderId);

    if(_instance->getObserver())
    {
        _instance->getObserver()->setObserverUpdater(_sessionRouter);
    }

    //
    // Everything ok, let's go.
    //
    try
    {
        clientAdapter->activate();
        if(serverAdapter)
        {
            serverAdapter->activate();
        }
    }
    catch(const std::exception& ex)
    {
        {
            ServiceError err(this);
            err << "caught exception activating object adapters\n" << ex;
        }

        stop();
        return false;
    }

    return true;
}
예제 #27
0
Glacier2::PermissionsVerifierPrx
RegistryI::getPermissionsVerifier(const ObjectAdapterPtr& adapter, 
                                  const IceGrid::LocatorPrx& locator,
                                  const string& verifierProperty,
                                  const string& passwordsProperty,
                                  bool nowarn)
{
    //
    // Get the permissions verifier, or create a default one if no
    // verifier is specified.
    //

    ObjectPrx verifier;
    string verifierPropertyValue = _communicator->getProperties()->getProperty(verifierProperty);
    if(!verifierPropertyValue.empty())
    {
        try
        {
            verifier = _communicator->propertyToProxy(verifierProperty);
            if(!verifier)
            {
                Error out(_communicator->getLogger());
                out << "permissions verifier `" + verifierPropertyValue + "' is invalid";
                return 0;
            }
            assert(_nullPermissionsVerifier);
            if(verifier->ice_getIdentity() == _nullPermissionsVerifier->ice_getIdentity())
            {
                verifier = _nullPermissionsVerifier;
            }
        }
        catch(const LocalException& ex)
        {
            Error out(_communicator->getLogger());
            out << "permissions verifier `" + verifierPropertyValue + "' is invalid:\n" << ex;
            return 0;
        }
    }
    else if(!passwordsProperty.empty())
    {
        ifstream passwordFile(passwordsProperty.c_str());
        if(!passwordFile)
        {
            Error out(_communicator->getLogger());
            string err = strerror(errno);
            out << "cannot open `" + passwordsProperty + "' for reading: " + err;
            return 0;
        }

        map<string, string> passwords;

        while(true)
        {
            string userId;
            passwordFile >> userId;
            if(!passwordFile)
            {
                break;
            }

            string password;
            passwordFile >> password;
            if(!passwordFile)
            {
                break;
            }

            assert(!userId.empty());
            assert(!password.empty());
            passwords.insert(make_pair(userId, password));
        }

        verifier = adapter->addWithUUID(new CryptPermissionsVerifierI(passwords));
    }
예제 #28
0
int
run(int argc, char* argv[], const CommunicatorPtr& communicator)
{
    IceUtilInternal::Options opts;
    opts.addOpt("", "ordered");
    opts.addOpt("", "twoway");
    opts.addOpt("", "events", IceUtilInternal::Options::NeedArg);

    try
    {
        opts.parse(argc, (const char**)argv);
    }
    catch(const IceUtilInternal::BadOptException& e)
    {
        cerr << argv[0] << ": " << e.reason << endl;
        return EXIT_FAILURE;
    }

    PropertiesPtr properties = communicator->getProperties();
    const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default";
    string managerProxy = properties->getProperty(managerProxyProperty);
    if(managerProxy.empty())
    {
        cerr << argv[0] << ": property `" << managerProxyProperty << "' is not set" << endl;
        return EXIT_FAILURE;
    }

    ObjectPrx base = communicator->stringToProxy(managerProxy);
    IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base);
    if(!manager)
    {
        cerr << argv[0] << ": `" << managerProxy << "' is not running" << endl;
        return EXIT_FAILURE;
    }

    ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default");

    TopicPrx topic;
    while(true)
    {
        try
        {
            topic = manager->retrieve("single");
            break;
        }
        // This can happen if the replica group loses the majority
        // during retrieve. In this case we retry.
        catch(const Ice::UnknownException&)
        {
            continue;
        }
        catch(const IceStorm::NoSuchTopic& e)
        {
            cerr << argv[0] << ": NoSuchTopic: " << e.name << endl;
            return EXIT_FAILURE;
        }
    }

    int events = 1000;
    if(opts.isSet("events"))
    {
        events = atoi(opts.optArg("events").c_str());
    }
    //
    // Create subscribers with different QoS.
    //
    SingleIPtr sub;
    IceStorm::QoS qos;
    if(opts.isSet("ordered"))
    {
        sub = new SingleI(communicator, "twoway ordered", events);
        qos["reliability"] = "ordered";
    }
    else
    {
        sub = new SingleI(communicator, "twoway", events);
    }

    Ice::ObjectPrx prx = adapter->addWithUUID(sub);

    while(true)
    {
        try
        {
            topic->subscribeAndGetPublisher(qos, prx);
            break;
        }
        // If we're already subscribed then we're done (previously we
        // got an UnknownException which succeeded).
        catch(const IceStorm::AlreadySubscribed&)
        {
            break;
        }
        // This can happen if the replica group loses the majority
        // during subscription. In this case we retry.
        catch(const Ice::UnknownException&)
        {
        }
    }

    adapter->activate();

    sub->waitForEvents();

    topic->unsubscribe(prx);

    return EXIT_SUCCESS;
}
예제 #29
0
bool
IceBox::ServiceManagerI::start()
{
    try
    {
        ServiceManagerPtr obj = this;
        PropertiesPtr properties = _communicator->getProperties();

        //
        // Create an object adapter. Services probably should NOT share
        // this object adapter, as the endpoint(s) for this object adapter
        // will most likely need to be firewalled for security reasons.
        //
        ObjectAdapterPtr adapter;
        if(properties->getProperty("IceBox.ServiceManager.Endpoints") != "")
        {
            adapter = _communicator->createObjectAdapter("IceBox.ServiceManager");

            Identity identity;
            identity.category = properties->getPropertyWithDefault("IceBox.InstanceName", "IceBox");
            identity.name = "ServiceManager";
            adapter->add(obj, identity);
        }

        //
        // Parse the property set with the prefix "IceBox.Service.". These
        // properties should have the following format:
        //
        // IceBox.Service.Foo=entry_point [args]
        //
        // We parse the service properties specified in IceBox.LoadOrder 
        // first, then the ones from remaining services.
        //
        const string prefix = "IceBox.Service.";
        PropertyDict services = properties->getPropertiesForPrefix(prefix);
        PropertyDict::iterator p;
        StringSeq loadOrder = properties->getPropertyAsList("IceBox.LoadOrder");
        vector<StartServiceInfo> servicesInfo;
        for(StringSeq::const_iterator q = loadOrder.begin(); q != loadOrder.end(); ++q)
        {
            p = services.find(prefix + *q);
            if(p == services.end())
            {
                FailureException ex(__FILE__, __LINE__);
                ex.reason = "ServiceManager: no service definition for `" + *q + "'";
                throw ex;
            }
            servicesInfo.push_back(StartServiceInfo(*q, p->second, _argv));
            services.erase(p);
        }
        for(p = services.begin(); p != services.end(); ++p)
        {
            servicesInfo.push_back(StartServiceInfo(p->first.substr(prefix.size()), p->second, _argv));
        }
        
        //
        // Check if some services are using the shared communicator in which
        // case we create the shared communicator now with a property set which
        // is the union of all the service properties (services which are using
        // the shared communicator).
        //
        PropertyDict sharedCommunicatorServices = properties->getPropertiesForPrefix("IceBox.UseSharedCommunicator.");
        if(!sharedCommunicatorServices.empty())
        {
            InitializationData initData;
            initData.properties = createServiceProperties("SharedCommunicator");
            for(vector<StartServiceInfo>::iterator q = servicesInfo.begin(); q != servicesInfo.end(); ++q)
            {
                if(properties->getPropertyAsInt("IceBox.UseSharedCommunicator." + q->name) <= 0)
                {
                    continue;
                }

                //
                // Load the service properties using the shared communicator properties as
                // the default properties.
                //
                PropertiesPtr svcProperties = createProperties(q->args, initData.properties);

                //
                // Erase properties from the shared communicator which don't exist in the
                // service properties (which include the shared communicator properties
                // overriden by the service properties).
                //
                PropertyDict allProps = initData.properties->getPropertiesForPrefix("");
                for(PropertyDict::iterator p = allProps.begin(); p != allProps.end(); ++p)
                {
                    if(svcProperties->getProperty(p->first) == "")
                    {
                        initData.properties->setProperty(p->first, "");
                    }
                }

                //
                // Add the service properties to the shared communicator properties.
                //
                PropertyDict props = svcProperties->getPropertiesForPrefix("");
                for(PropertyDict::const_iterator r = props.begin(); r != props.end(); ++r)
                {
                    initData.properties->setProperty(r->first, r->second);
                }
            
                //
                // Parse <service>.* command line options (the Ice command line options 
                // were parsed by the createProperties above)
                //
                q->args = initData.properties->parseCommandLineOptions(q->name, q->args);                
            }
            _sharedCommunicator = initialize(initData);
        }

        //
        // Start the services.
        //
        for(vector<StartServiceInfo>::const_iterator r = servicesInfo.begin(); r != servicesInfo.end(); ++r)
        {
            start(r->name, r->entryPoint, r->args);
        }

        //
        // We may want to notify external scripts that the services
        // have started. This is done by defining the property:
        //
        // IceBox.PrintServicesReady=bundleName
        //
        // Where bundleName is whatever you choose to call this set of
        // services. It will be echoed back as "bundleName ready".
        //
        // This must be done after start() has been invoked on the
        // services.
        //
        string bundleName = properties->getProperty("IceBox.PrintServicesReady");
        if(!bundleName.empty())
        {
            cout << bundleName << " ready" << endl;
        }

        //
        // Register "this" as a facet to the Admin object, and then create
        // Admin object
        //
        try
        {
            _communicator->addAdminFacet(this, "IceBox.ServiceManager");

            //
            // Add a Properties facet for each service
            // 
            for(vector<ServiceInfo>::iterator r = _services.begin(); r != _services.end(); ++r)
            {
                const ServiceInfo& info = *r;
                CommunicatorPtr communicator = info.communicator != 0 ? info.communicator : _sharedCommunicator;
                _communicator->addAdminFacet(new PropertiesAdminI(communicator->getProperties()),
                                             "IceBox.Service." + info.name + ".Properties");
            }
          
            _communicator->getAdmin();
        }
        catch(const ObjectAdapterDeactivatedException&)
        {
            //
            // Expected if the communicator has been shutdown.
            //
        }

        if(adapter)
        {
            try
            {
                adapter->activate();
            }
            catch(const ObjectAdapterDeactivatedException&)
            {
                //
                // Expected if the communicator has been shutdown.
                //
            }
        }
    }
    catch(const FailureException& ex)
    {
        Error out(_logger);
        out << ex.reason;
        stopAll();
        return false;
    }
    catch(const Exception& ex)
    {
        Error out(_logger);
        out << "ServiceManager: " << ex;
        stopAll();
        return false;
    }

    return true;
}
예제 #30
0
TestIntfPrx
allTests(const CommunicatorPtr& communicator)
{
    cout << "testing stringToProxy... " << flush;
    ObjectPrx base = communicator->stringToProxy("test:default -p 12010");
    test(base);
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    TestIntfPrx obj = TestIntfPrx::checkedCast(base);
    test(obj);
    test(obj == base);
    cout << "ok" << endl;

    {
        cout << "creating/destroying/recreating object adapter... " << flush;
        ObjectAdapterPtr adapter = 
            communicator->createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
        try
        {
            communicator->createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
            test(false);
        }
        catch(const AlreadyRegisteredException&)
        {
        }
        adapter->destroy();

        //
        // Use a different port than the first adapter to avoid an "address already in use" error.
        //
        adapter = communicator->createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
        adapter->destroy();
        cout << "ok" << endl;
    }

    cout << "creating/activating/deactivating object adapter in one operation... " << flush;
    obj->transient();
    cout << "ok" << endl;

    {
        cout << "testing connection closure... " << flush;
        for(int i = 0; i < 10; ++i)
        {
            Ice::InitializationData initData;
            initData.properties = communicator->getProperties()->clone();
            Ice::CommunicatorPtr comm = Ice::initialize(initData);
            comm->stringToProxy("test:default -p 12010")->begin_ice_ping();
            comm->destroy();
        }
        cout << "ok" << endl;
    }

    cout << "deactivating object adapter in the server... " << flush;
    obj->deactivate();
    cout << "ok" << endl;

    cout << "testing whether server is gone... " << flush;
    try
    {
        obj->ice_ping();
        test(false);
    }
    catch(const LocalException&)
    {
        cout << "ok" << endl;
    }

    return obj;
}