diff options
author | Joe George <joe@zeroc.com> | 2021-01-28 16:26:44 -0500 |
---|---|---|
committer | Joe George <joe@zeroc.com> | 2021-02-01 16:59:30 -0500 |
commit | 92a6531e409f2691d82591e185a92299d415fc0f (patch) | |
tree | 60c79e2a8f327b8f0b6ebc06b06f48a2e8086f6a /cpp/src | |
parent | Port Glacier2, IceBox, IceBridge, IceDB, IceXML, icegriddb (diff) | |
download | ice-92a6531e409f2691d82591e185a92299d415fc0f.tar.bz2 ice-92a6531e409f2691d82591e185a92299d415fc0f.tar.xz ice-92a6531e409f2691d82591e185a92299d415fc0f.zip |
IceGrid and IceStorm
Diffstat (limited to 'cpp/src')
133 files changed, 8318 insertions, 10443 deletions
diff --git a/cpp/src/IceGrid/Activator.cpp b/cpp/src/IceGrid/Activator.cpp index 23369aac08f..a403433d398 100644 --- a/cpp/src/IceGrid/Activator.cpp +++ b/cpp/src/IceGrid/Activator.cpp @@ -44,33 +44,12 @@ using namespace IceGrid; namespace IceGrid { -class TerminationListenerThread : public IceUtil::Thread -{ -public: - - TerminationListenerThread(Activator& activator) : - IceUtil::Thread("IceGrid termination listener thread"), - _activator(activator) - { - } - - virtual - void run() - { - _activator.runTerminationListener(); - } - -private: - - Activator& _activator; -}; - #ifndef _WIN32 // // Helper function for async-signal safe error reporting // void -reportChildError(int err, int fd, const char* cannot, const char* name, const TraceLevelsPtr& traceLevels) +reportChildError(int err, int fd, const char* cannot, const char* name, const shared_ptr<TraceLevels>& traceLevels) { // // Send any errors to the parent process, using the write @@ -301,19 +280,19 @@ extern "C" void CALLBACK activatorWaitCallback(PVOID data, BOOLEAN) } #endif -Activator::Activator(const TraceLevelsPtr& traceLevels) : +Activator::Activator(const shared_ptr<TraceLevels>& traceLevels) : _traceLevels(traceLevels), _deactivating(false) { #ifdef _WIN32 _hIntr = CreateEvent( - ICE_NULLPTR, // Security attributes + nullptr, // Security attributes TRUE, // Manual reset FALSE, // Initial state is nonsignaled - ICE_NULLPTR // Unnamed + nullptr // Unnamed ); - if(_hIntr == ICE_NULLPTR) + if(_hIntr == nullptr) { throw SyscallException(__FILE__, __LINE__, getSystemErrno()); @@ -335,10 +314,8 @@ Activator::Activator(const TraceLevelsPtr& traceLevels) : Activator::~Activator() { - assert(!_thread); - #ifdef _WIN32 - if(_hIntr != ICE_NULLPTR) + if(_hIntr != nullptr) { CloseHandle(_hIntr); } @@ -358,9 +335,9 @@ Activator::activate(const string& name, #endif const Ice::StringSeq& options, const Ice::StringSeq& envs, - const ServerIPtr& server) + const shared_ptr<ServerI>& server) { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); if(_deactivating) { @@ -390,7 +367,7 @@ Activator::activate(const string& name, // IceGrid doesn't support to use string converters, so don't need to use // any string converter in wstringToString conversions. // - if(SearchPathW(ICE_NULLPTR, stringToWstring(path).c_str(), ext.c_str(), _MAX_PATH, absbuf, &fPart) == 0) + if(SearchPathW(nullptr, stringToWstring(path).c_str(), ext.c_str(), _MAX_PATH, absbuf, &fPart) == 0) { if(_traceLevels->activator > 0) { @@ -417,7 +394,7 @@ Activator::activate(const string& name, if(!pwd.empty()) { wchar_t absbuf[_MAX_PATH]; - if(_wfullpath(absbuf, stringToWstring(pwd).c_str(), _MAX_PATH) == ICE_NULLPTR) + if(_wfullpath(absbuf, stringToWstring(pwd).c_str(), _MAX_PATH) == nullptr) { if(_traceLevels->activator > 0) { @@ -506,7 +483,7 @@ Activator::activate(const string& name, // any string converter in stringToWstring conversions. // wstring wpwd = stringToWstring(pwd); - const wchar_t* dir = !wpwd.empty() ? wpwd.c_str() : ICE_NULLPTR; + const wchar_t* dir = !wpwd.empty() ? wpwd.c_str() : nullptr; // // Make a copy of the command line. @@ -519,7 +496,7 @@ Activator::activate(const string& name, // Since Windows is case insensitive wrt environment variables we convert the keys to // uppercase to ensure matches are found. // - const wchar_t* env = ICE_NULLPTR; + const wchar_t* env = nullptr; wstring envbuf; if(!envs.empty()) { @@ -583,10 +560,10 @@ Activator::activate(const string& name, PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); BOOL b = CreateProcessW( - ICE_NULLPTR, // Executable + nullptr, // Executable cmdbuf, // Command line - ICE_NULLPTR, // Process attributes - ICE_NULLPTR, // Thread attributes + nullptr, // Process attributes + nullptr, // Thread attributes FALSE, // Do NOT inherit handles CREATE_NEW_PROCESS_GROUP | CREATE_UNICODE_ENVIRONMENT, // Process creation flags (LPVOID)env, // Process environment @@ -809,7 +786,7 @@ Activator::activate(const string& name, int maxFd = static_cast<int>(sysconf(_SC_OPEN_MAX)); if(maxFd <= 0) { - maxFd = INT_MAX; + maxFd = numeric_limits<int>::max(); } for(int fd = 3; fd < maxFd; ++fd) @@ -884,7 +861,7 @@ Activator::activate(const string& name, } // - // If an error occured before the exec() we do some cleanup and throw. + // If an error occurred before the exec() we do some cleanup and throw. // if(!message.empty()) { @@ -930,42 +907,8 @@ Activator::activate(const string& name, #endif } -namespace -{ - -class ShutdownCallback : public IceUtil::Shared -{ -public: - - ShutdownCallback(const ActivatorPtr& activator, const string& name, const TraceLevelsPtr& traceLevels) : - _activator(activator), _name(name), _traceLevels(traceLevels) - { - - } - - virtual void - exception(const Ice::Exception& ex) - { - Ice::Warning out(_traceLevels->logger); - out << "exception occurred while deactivating `" << _name << "' using process proxy:\n" << ex; - - // - // Send a SIGTERM to the process. - // - _activator->sendSignal(_name, SIGTERM); - } - -private: - - const ActivatorPtr _activator; - const string _name; - const TraceLevelsPtr _traceLevels; -}; - -} - void -Activator::deactivate(const string& name, const Ice::ProcessPrx& process) +Activator::deactivate(const string& name, const shared_ptr<Ice::ProcessPrx>& process) { #ifdef _WIN32 Ice::Int pid = getServerPid(name); @@ -988,8 +931,24 @@ Activator::deactivate(const string& name, const Ice::ProcessPrx& process) Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); out << "deactivating `" << name << "' using process proxy"; } - process->begin_shutdown(Ice::newCallback_Process_shutdown(new ShutdownCallback(this, name, _traceLevels), - &ShutdownCallback::exception)); + + process->shutdownAsync(nullptr, [self = shared_from_this(), name] (exception_ptr ex) + { + try + { + rethrow_exception(ex); + } + catch (const std::exception& e) + { + Ice::Warning out(self->_traceLevels->logger); + out << "exception occurred while deactivating `" << name << "' using process proxy:\n" << e; + } + + // + // Send a SIGTERM to the process. + // + self->sendSignal(name, SIGTERM); + }); return; } @@ -1051,7 +1010,7 @@ Activator::sendSignal(const string& name, int signal) else if(signal == SIGKILL) { HANDLE hnd = OpenProcess(PROCESS_TERMINATE, FALSE, pid); - if(hnd == ICE_NULLPTR) + if(hnd == nullptr) { throw SyscallException(__FILE__, __LINE__, getSystemErrno()); } @@ -1085,18 +1044,18 @@ Activator::sendSignal(const string& name, int signal) #endif } -Ice::Int +int Activator::getServerPid(const string& name) { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); - map<string, Process>::const_iterator p = _processes.find(name); + auto p = _processes.find(name); if(p == _processes.end()) { return 0; } - return static_cast<Ice::Int>(p->second.pid); + return static_cast<int>(p->second.pid); } void @@ -1105,24 +1064,20 @@ Activator::start() // // Create and start the termination listener thread. // - _thread = new TerminationListenerThread(*this); - _thread->start(); + _thread = thread([this] { runTerminationListener(); }); } void Activator::waitForShutdown() { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); - while(!_deactivating) - { - wait(); - } + unique_lock lock(_mutex); + _condVar.wait(lock, [this] { return _deactivating; }); } void Activator::shutdown() { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); if(_deactivating) { return; @@ -1136,7 +1091,7 @@ Activator::shutdown() // _deactivating = true; setInterrupt(); - notifyAll(); + _condVar.notify_all(); } void @@ -1144,7 +1099,7 @@ Activator::destroy() { map<string, Process> processes; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); assert(_deactivating); processes = _processes; } @@ -1152,7 +1107,7 @@ Activator::destroy() // // Stop all active processes. // - for(map<string, Process>::iterator p = processes.begin(); p != processes.end(); ++p) + for(const auto& [name, proc] : processes) { // // Stop the server. The listener thread should detect the @@ -1161,7 +1116,7 @@ Activator::destroy() // try { - p->second.server->stop_async(0, Ice::emptyCurrent); + proc.server->stopAsync(nullptr, nullptr, Ice::emptyCurrent); } catch(const ServerStopException&) { @@ -1176,7 +1131,7 @@ Activator::destroy() catch(const Ice::LocalException& ex) { Ice::Warning out(_traceLevels->logger); - out << "unexpected exception raised by server `" << p->first << "' stop:\n" << ex; + out << "unexpected exception raised by server `" << name << "' stop:\n" << ex; } } @@ -1185,18 +1140,14 @@ Activator::destroy() // when there's no more processes and when _deactivating is set to // true. // - if(_thread) - { - _thread->getThreadControl().join(); - _thread = 0; - } + _thread.join(); assert(_processes.empty()); } bool Activator::isActive() { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); return !_deactivating; } @@ -1245,7 +1196,7 @@ Activator::terminationListener() vector<Process> terminated; bool deactivated = false; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); for(vector<Process*>::const_iterator q = _terminated.begin(); q != _terminated.end(); ++q) { for(map<string, Process>::iterator p = _processes.begin(); p != _processes.end(); ++p) @@ -1307,7 +1258,7 @@ Activator::terminationListener() FD_SET(_fdIntrRead, &fdSet); { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); for(map<string, Process>::iterator p = _processes.begin(); p != _processes.end(); ++p) { @@ -1344,7 +1295,7 @@ Activator::terminationListener() vector<Process> terminated; bool deactivated = false; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); if(FD_ISSET(_fdIntrRead, &fdSet)) { @@ -1461,8 +1412,7 @@ Activator::clearInterrupt() ResetEvent(_hIntr); #else char c; - while(read(_fdIntrRead, &c, 1) == 1) - ; + while(read(_fdIntrRead, &c, 1) == 1); #endif } @@ -1534,7 +1484,7 @@ Activator::waitPid(pid_t processPid) void Activator::processTerminated(Activator::Process* process) { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); setInterrupt(); _terminated.push_back(process); } diff --git a/cpp/src/IceGrid/Activator.h b/cpp/src/IceGrid/Activator.h index f2eb0ff5a56..809dc1d7441 100644 --- a/cpp/src/IceGrid/Activator.h +++ b/cpp/src/IceGrid/Activator.h @@ -5,7 +5,6 @@ #ifndef ICE_GRID_ACTIVATOR_H #define ICE_GRID_ACTIVATOR_H -#include <IceUtil/Thread.h> #include <IceGrid/Internal.h> #ifndef _WIN32 @@ -16,14 +15,11 @@ namespace IceGrid { class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - class ServerI; -typedef IceUtil::Handle<ServerI> ServerIPtr; std::string signalToString(int); -class Activator : public IceUtil::Monitor< IceUtil::Mutex>, public IceUtil::Shared +class Activator final : public std::enable_shared_from_this<Activator> { public: @@ -39,27 +35,27 @@ public: int pipeFd; std::string msg; #endif - ServerIPtr server; + std::shared_ptr<ServerI> server; }; - Activator(const TraceLevelsPtr&); - virtual ~Activator(); + Activator(const std::shared_ptr<TraceLevels>&); + ~Activator(); - virtual int activate(const std::string&, const std::string&, const std::string&, + int activate(const std::string&, const std::string&, const std::string&, #ifndef _WIN32 - uid_t, gid_t, + uid_t, gid_t, #endif - const Ice::StringSeq&, const Ice::StringSeq&, const ServerIPtr&); - virtual void deactivate(const std::string&, const Ice::ProcessPrx&); - virtual void kill(const std::string&); - virtual void sendSignal(const std::string&, const std::string&); + const Ice::StringSeq&, const Ice::StringSeq&, const std::shared_ptr<ServerI>&); + void deactivate(const std::string&, const std::shared_ptr<Ice::ProcessPrx>&); + void kill(const std::string&); + void sendSignal(const std::string&, const std::string&); - virtual Ice::Int getServerPid(const std::string&); + int getServerPid(const std::string&); - virtual void start(); - virtual void waitForShutdown(); - virtual void shutdown(); - virtual void destroy(); + void start(); + void waitForShutdown(); + void shutdown(); + void destroy(); bool isActive(); @@ -80,7 +76,7 @@ private: int waitPid(pid_t); #endif - TraceLevelsPtr _traceLevels; + std::shared_ptr<TraceLevels> _traceLevels; std::map<std::string, Process> _processes; bool _deactivating; @@ -92,9 +88,10 @@ private: int _fdIntrWrite; #endif - IceUtil::ThreadPtr _thread; + std::mutex _mutex; + std::condition_variable _condVar; + std::thread _thread; }; -typedef IceUtil::Handle<Activator> ActivatorPtr; } diff --git a/cpp/src/IceGrid/AdapterCache.cpp b/cpp/src/IceGrid/AdapterCache.cpp index 941a653b5f3..e6fd6523609 100644 --- a/cpp/src/IceGrid/AdapterCache.cpp +++ b/cpp/src/IceGrid/AdapterCache.cpp @@ -11,6 +11,7 @@ #include <IceGrid/ServerCache.h> #include <IceGrid/NodeCache.h> #include <IceGrid/SessionI.h> +#include <IceGrid/Internal.h> #include <functional> @@ -20,52 +21,11 @@ using namespace IceGrid; namespace IceGrid { -struct ReplicaLoadComp : binary_function<ServerAdapterEntryPtr&, ServerAdapterEntryPtr&, bool> -{ - bool operator()(const pair<float, ServerAdapterEntryPtr>& lhs, const pair<float, ServerAdapterEntryPtr>& rhs) - { - return lhs.first < rhs.first; - } -}; - -struct ReplicaPriorityComp : binary_function<ServerAdapterEntryPtr&, ServerAdapterEntryPtr&, bool> -{ - bool operator()(const ServerAdapterEntryPtr& lhs, const ServerAdapterEntryPtr& rhs) - { - return lhs->getPriority() < rhs->getPriority(); - } -}; - -struct TransformToReplicaLoad : - public unary_function<const ServerAdapterEntryPtr&, pair<float, ServerAdapterEntryPtr> > +class ReplicaGroupSyncCallback final : public SynchronizationCallback { public: - TransformToReplicaLoad(LoadSample loadSample) : _loadSample(loadSample) { } - - pair<float, ServerAdapterEntryPtr> - operator()(const ServerAdapterEntryPtr& value) - { - return make_pair(value->getLeastLoadedNodeLoad(_loadSample), value); - } - - LoadSample _loadSample; -}; - -struct TransformToReplica : public unary_function<const pair<string, ServerAdapterEntryPtr>&, ServerAdapterEntryPtr> -{ - ServerAdapterEntryPtr - operator()(const pair<float, ServerAdapterEntryPtr>& value) - { - return value.second; - } -}; - -class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil::Mutex -{ -public: - - ReplicaGroupSyncCallback(const SynchronizationCallbackPtr& callback, int count, int nReplicas) : + ReplicaGroupSyncCallback(const shared_ptr<SynchronizationCallback>& callback, int count, int nReplicas) : _callback(callback), _responseCalled(false), _synchronizeCount(count), @@ -77,20 +37,20 @@ public: bool response() { - Lock sync(*this); + lock_guard lock(_mutex); _responseCalled = true; if(_synchronizedCount >= _nReplicas) { - _callback = 0; + _callback = nullptr; return false; } else if(_synchronizeCount == 0) { - if(_synchronizedCount == 0 && _exception.get()) + if(_synchronizedCount == 0 && _exception) { - _exception->ice_throw(); + rethrow_exception(_exception); } - _callback = 0; + _callback = nullptr; return false; } return true; @@ -99,9 +59,9 @@ public: void synchronized() { - SynchronizationCallbackPtr callback; + shared_ptr<SynchronizationCallback> callback; { - Lock sync(*this); + lock_guard lock(_mutex); ++_synchronizedCount; --_synchronizeCount; @@ -116,7 +76,7 @@ public: } callback = _callback; - _callback = 0; + _callback = nullptr; } if(callback) @@ -126,14 +86,14 @@ public: } void - synchronized(const Ice::Exception& ex) + synchronized(exception_ptr ex) { - SynchronizationCallbackPtr callback; + shared_ptr<SynchronizationCallback> callback; { - Lock sync(*this); - if(!_exception.get()) + lock_guard lock(_mutex); + if(!_exception) { - _exception.reset(ex.ice_clone()); + _exception = ex; } --_synchronizeCount; @@ -159,19 +119,20 @@ public: private: - SynchronizationCallbackPtr _callback; + shared_ptr<SynchronizationCallback> _callback; bool _responseCalled; int _synchronizeCount; int _synchronizedCount; int _nReplicas; - IceInternal::UniquePtr<Ice::Exception> _exception; + exception_ptr _exception; + + mutex _mutex; }; -typedef IceUtil::Handle<ReplicaGroupSyncCallback> ReplicaGroupSyncCallbackPtr; } void -GetAdapterInfoResult::add(const ServerAdapterEntryPtr& adapter) +GetAdapterInfoResult::add(const ServerAdapterEntry* adapter) { AdapterInfo info; info.id = adapter->getId(); @@ -179,15 +140,15 @@ GetAdapterInfoResult::add(const ServerAdapterEntryPtr& adapter) _adapters.push_back(info); try { - _results.push_back(adapter->getProxy("", true)->begin_getDirectProxy()); + _results.push_back(adapter->getProxy("", true)->getDirectProxyAsync()); } catch(const SynchronizationException&) { - _results.push_back(0); + _results.push_back(nullopt); } catch(const Ice::Exception&) { - _results.push_back(0); + _results.push_back(nullopt); } } @@ -195,13 +156,13 @@ AdapterInfoSeq GetAdapterInfoResult::get() { vector<AdapterInfo>::iterator q = _adapters.begin(); - for(vector<Ice::AsyncResultPtr>::const_iterator p = _results.begin(); p != _results.end(); ++p, ++q) + for(auto p = _results.begin(); p != _results.end(); ++p, ++q) { try { if(*p) { - q->proxy = AdapterPrx::uncheckedCast((*p)->getProxy())->end_getDirectProxy(*p); + q->proxy = Ice::uncheckedCast<AdapterPrx>((*p)->get()); } } catch(const Ice::Exception&) @@ -211,14 +172,14 @@ GetAdapterInfoResult::get() return _adapters; } -AdapterCache::AdapterCache(const Ice::CommunicatorPtr& communicator) : _communicator(communicator) +AdapterCache::AdapterCache(const shared_ptr<Ice::Communicator>& communicator) : _communicator(communicator) { } void -AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const ServerEntryPtr& server, const string& app) +AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const shared_ptr<ServerEntry>& server, const string& app) { - Lock sync(*this); + lock_guard lock(_mutex); if(getImpl(desc.id)) { Ice::Error out(_communicator->getLogger()); @@ -226,23 +187,29 @@ AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const ServerEntryP return; } - istringstream is(desc.priority); int priority = 0; - is >> priority; + try + { + priority = stoi(desc.priority); + } + catch(const std::exception&) + { + } - ServerAdapterEntryPtr entry = new ServerAdapterEntry(*this, desc.id, app, desc.replicaGroupId, priority, server); + auto entry = make_shared<ServerAdapterEntry>(*this, desc.id, app, desc.replicaGroupId, priority, server); addImpl(desc.id, entry); if(!desc.replicaGroupId.empty()) { - ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(desc.replicaGroupId)); + auto repEntry = dynamic_pointer_cast<ReplicaGroupEntry>(getImpl(desc.replicaGroupId)); if(!repEntry) { // // Add an un-assigned replica group, the replica group will in theory be added // shortly after when its application is loaded. // - repEntry = new ReplicaGroupEntry(*this, desc.replicaGroupId, "", new RandomLoadBalancingPolicy("0"), ""); + repEntry = make_shared<ReplicaGroupEntry>(*this, desc.replicaGroupId, "", + make_shared<RandomLoadBalancingPolicy>("0"), ""); addImpl(desc.replicaGroupId, repEntry); } repEntry->addReplica(desc.id, entry); @@ -252,8 +219,8 @@ AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const ServerEntryP void AdapterCache::addReplicaGroup(const ReplicaGroupDescriptor& desc, const string& app) { - Lock sync(*this); - ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(desc.id)); + lock_guard lock(_mutex); + auto repEntry = dynamic_pointer_cast<ReplicaGroupEntry>(getImpl(desc.id)); if(repEntry) { // @@ -271,14 +238,15 @@ AdapterCache::addReplicaGroup(const ReplicaGroupDescriptor& desc, const string& } return; } - addImpl(desc.id, new ReplicaGroupEntry(*this, desc.id, app, desc.loadBalancing, desc.filter)); + addImpl(desc.id, make_shared<ReplicaGroupEntry>(*this, desc.id, app, desc.loadBalancing, desc.filter)); } -AdapterEntryPtr +shared_ptr<AdapterEntry> AdapterCache::get(const string& id) const { - Lock sync(*this); - AdapterEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + + auto entry = getImpl(id); if(!entry) { throw AdapterNotExistException(id); @@ -289,9 +257,9 @@ AdapterCache::get(const string& id) const void AdapterCache::removeServerAdapter(const string& id) { - Lock sync(*this); + lock_guard lock(_mutex); - ServerAdapterEntryPtr entry = ServerAdapterEntryPtr::dynamicCast(getImpl(id)); + auto entry = dynamic_pointer_cast<ServerAdapterEntry>(getImpl(id)); if(!entry) { Ice::Error out(_communicator->getLogger()); @@ -303,7 +271,7 @@ AdapterCache::removeServerAdapter(const string& id) string replicaGroupId = entry->getReplicaGroupId(); if(!replicaGroupId.empty()) { - ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(replicaGroupId)); + auto repEntry = dynamic_pointer_cast<ReplicaGroupEntry>(getImpl(replicaGroupId)); if(!repEntry) { Ice::Error out(_communicator->getLogger()); @@ -325,8 +293,9 @@ AdapterCache::removeServerAdapter(const string& id) void AdapterCache::removeReplicaGroup(const string& id) { - Lock sync(*this); - ReplicaGroupEntryPtr entry = ReplicaGroupEntryPtr::dynamicCast(getImpl(id)); + lock_guard lock(_mutex); + + auto entry = dynamic_pointer_cast<ReplicaGroupEntry>(getImpl(id)); if(!entry) { Ice::Error out(_communicator->getLogger()); @@ -336,8 +305,8 @@ AdapterCache::removeReplicaGroup(const string& id) removeImpl(id); } -AdapterEntryPtr -AdapterCache::addImpl(const string& id, const AdapterEntryPtr& entry) +shared_ptr<AdapterEntry> +AdapterCache::addImpl(const string& id, const shared_ptr<AdapterEntry>& entry) { if(_traceLevels && _traceLevels->adapter > 0) { @@ -388,7 +357,7 @@ ServerAdapterEntry::ServerAdapterEntry(AdapterCache& cache, const string& application, const string& replicaGroupId, int priority, - const ServerEntryPtr& server) : + const shared_ptr<ServerEntry>& server) : AdapterEntry(cache, id, application), _replicaGroupId(replicaGroupId), _priority(priority), @@ -397,7 +366,7 @@ ServerAdapterEntry::ServerAdapterEntry(AdapterCache& cache, } bool -ServerAdapterEntry::addSyncCallback(const SynchronizationCallbackPtr& callback, const set<string>&) +ServerAdapterEntry::addSyncCallback(const shared_ptr<SynchronizationCallback>& callback, const set<string>&) { try { @@ -448,23 +417,18 @@ ServerAdapterEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const AdapterInfoSeq ServerAdapterEntry::getAdapterInfoNoEndpoints() const { - AdapterInfo info; - info.id = _id; - info.replicaGroupId = _replicaGroupId; - AdapterInfoSeq infos; - infos.push_back(info); - return infos; + return { { _id, nullptr, _replicaGroupId } }; } -GetAdapterInfoResultPtr +shared_ptr<GetAdapterInfoResult> ServerAdapterEntry::getAdapterInfoAsync() const { - GetAdapterInfoResultPtr result = new GetAdapterInfoResult(); - result->add(const_cast<ServerAdapterEntry*>(this)); + auto result = make_shared<GetAdapterInfoResult>(); + result->add(this); return result; } -AdapterPrx +shared_ptr<AdapterPrx> ServerAdapterEntry::getProxy(const string& replicaGroupId, bool upToDate) const { if(replicaGroupId.empty()) @@ -484,9 +448,10 @@ ServerAdapterEntry::getProxy(const string& replicaGroupId, bool upToDate) const void ServerAdapterEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters) const { - LocatorAdapterInfo info; - info.id = _id; - info.proxy = _server->getAdapter(info.activationTimeout, info.deactivationTimeout, _id, true); + chrono::seconds activationTimeout, deactivationTimeout; + auto proxy = _server->getAdapter(activationTimeout, deactivationTimeout, _id, true); + + LocatorAdapterInfo info = { _id, move(proxy), activationTimeout, deactivationTimeout }; adapters.push_back(info); } @@ -518,7 +483,7 @@ ServerAdapterEntry::getNodeName() const ReplicaGroupEntry::ReplicaGroupEntry(AdapterCache& cache, const string& id, const string& application, - const LoadBalancingPolicyPtr& policy, + const shared_ptr<LoadBalancingPolicy>& policy, const string& filter) : AdapterEntry(cache, id, application), _lastReplica(0), @@ -528,26 +493,27 @@ ReplicaGroupEntry::ReplicaGroupEntry(AdapterCache& cache, } bool -ReplicaGroupEntry::addSyncCallback(const SynchronizationCallbackPtr& callback, const set<string>& excludes) +ReplicaGroupEntry::addSyncCallback(const shared_ptr<SynchronizationCallback>& callback, const set<string>& excludes) { - vector<ServerAdapterEntryPtr> replicas; + vector<shared_ptr<ServerAdapterEntry>> replicas; int nReplicas; - int roundRobin = false; + bool roundRobin = false; { - Lock sync(*this); + lock_guard lock(_mutex); + nReplicas = _loadBalancingNReplicas > 0 ? _loadBalancingNReplicas : static_cast<int>(_replicas.size()); - roundRobin = RoundRobinLoadBalancingPolicyPtr::dynamicCast(_loadBalancing); + roundRobin = dynamic_pointer_cast<RoundRobinLoadBalancingPolicy>(_loadBalancing) != nullptr; if(!roundRobin) { replicas = _replicas; } else { - for(vector<ServerAdapterEntryPtr>::const_iterator p = _replicas.begin(); p != _replicas.end(); ++p) + for(const auto& replica : _replicas) { - if(excludes.find((*p)->getId()) == excludes.end()) + if(excludes.find(replica->getId()) == excludes.end()) { - replicas.push_back(*p); + replicas.push_back(replica); } } } @@ -558,39 +524,37 @@ ReplicaGroupEntry::addSyncCallback(const SynchronizationCallbackPtr& callback, c } } - ReplicaGroupSyncCallbackPtr cb = new ReplicaGroupSyncCallback(callback, - static_cast<int>(replicas.size()), - nReplicas); + auto cb = make_shared<ReplicaGroupSyncCallback>(callback, static_cast<int>(replicas.size()), nReplicas); set<string> emptyExcludes; - for(vector<ServerAdapterEntryPtr>::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { try { - if(!(*p)->addSyncCallback(cb, emptyExcludes)) + if(!replica->addSyncCallback(cb, emptyExcludes)) { cb->synchronized(); } } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - cb->synchronized(ex); + cb->synchronized(current_exception()); } } return cb->response(); } void -ReplicaGroupEntry::addReplica(const string& /*replicaId*/, const ServerAdapterEntryPtr& adapter) +ReplicaGroupEntry::addReplica(const string& /*replicaId*/, const shared_ptr<ServerAdapterEntry>& adapter) { - Lock sync(*this); + lock_guard lock(_mutex); _replicas.push_back(adapter); } bool ReplicaGroupEntry::removeReplica(const string& replicaId) { - Lock sync(*this); - for(vector<ServerAdapterEntryPtr>::iterator p = _replicas.begin(); p != _replicas.end(); ++p) + lock_guard lock(_mutex); + for(auto p = _replicas.cbegin(); p != _replicas.cend(); ++p) { if(replicaId == (*p)->getId()) { @@ -606,37 +570,44 @@ ReplicaGroupEntry::removeReplica(const string& replicaId) } void -ReplicaGroupEntry::update(const string& application, const LoadBalancingPolicyPtr& policy, const string& filter) +ReplicaGroupEntry::update(const string& application, const shared_ptr<LoadBalancingPolicy>& policy, const string& filter) { - Lock sync(*this); + lock_guard lock(_mutex); + assert(policy); _application = application; _loadBalancing = policy; _filter = filter; - istringstream is(_loadBalancing->nReplicas); int nReplicas = 0; - is >> nReplicas; + try + { + nReplicas = stoi(_loadBalancing->nReplicas); + } + catch(const std::exception&) + { + } + _loadBalancingNReplicas = nReplicas < 0 ? 1 : nReplicas; - AdaptiveLoadBalancingPolicyPtr alb = AdaptiveLoadBalancingPolicyPtr::dynamicCast(_loadBalancing); + auto alb = dynamic_pointer_cast<AdaptiveLoadBalancingPolicy>(_loadBalancing); if(alb) { if(alb->loadSample == "1") { - _loadSample = LoadSample1; + _loadSample = LoadSample::LoadSample1; } else if(alb->loadSample == "5") { - _loadSample = LoadSample5; + _loadSample = LoadSample::LoadSample5; } else if(alb->loadSample == "15") { - _loadSample = LoadSample15; + _loadSample = LoadSample::LoadSample15; } else { - _loadSample = LoadSample1; + _loadSample = LoadSample::LoadSample1; } } } @@ -645,11 +616,11 @@ void ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& nReplicas, bool& replicaGroup, bool& roundRobin, string& filter, const set<string>& excludes) { - vector<ServerAdapterEntryPtr> replicas; + vector<shared_ptr<ServerAdapterEntry>> replicas; bool adaptive = false; - LoadSample loadSample = LoadSample1; + LoadSample loadSample = LoadSample::LoadSample1; { - Lock sync(*this); + unique_lock lock(_mutex); replicaGroup = true; roundRobin = false; filter = _filter; @@ -661,13 +632,10 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n } replicas.reserve(_replicas.size()); - if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + if(dynamic_pointer_cast<RoundRobinLoadBalancingPolicy>(_loadBalancing)) { // Serialize round-robin requests - while(_requestInProgress) - { - wait(); - } + _condVar.wait(lock, [this] { return !_requestInProgress; } ); _requestInProgress = true; for(size_t i = 0; i < _replicas.size(); ++i) { @@ -676,19 +644,23 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n _lastReplica = (_lastReplica + 1) % static_cast<int>(_replicas.size()); roundRobin = true; } - else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + else if(dynamic_pointer_cast<AdaptiveLoadBalancingPolicy>(_loadBalancing)) { replicas = _replicas; IceUtilInternal::shuffle(replicas.begin(), replicas.end()); loadSample = _loadSample; adaptive = true; } - else if(OrderedLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + else if(dynamic_pointer_cast<OrderedLoadBalancingPolicy>(_loadBalancing)) { replicas = _replicas; - sort(replicas.begin(), replicas.end(), ReplicaPriorityComp()); + sort(replicas.begin(), replicas.end(), + [](const auto& lhs, const auto& rhs) + { + return lhs->getPriority() < rhs->getPriority(); + }); } - else if(RandomLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + else if(dynamic_pointer_cast<RandomLoadBalancingPolicy>(_loadBalancing)) { replicas = _replicas; IceUtilInternal::shuffle(replicas.begin(), replicas.end()); @@ -703,16 +675,20 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n { // // This must be done outside the synchronization block since - // the trasnform() might call and lock each server adapter + // the transform() might call and lock each server adapter // entry. We also can't sort directly as the load of each // server adapter is not stable so we first take a snapshot of // each adapter and sort the snapshot. // - vector<pair<float, ServerAdapterEntryPtr> > rl; - transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); - sort(rl.begin(), rl.end(), ReplicaLoadComp()); + vector<pair<float, shared_ptr<ServerAdapterEntry>>> rl; + transform(replicas.begin(), replicas.end(), back_inserter(rl), + [loadSample](const auto& value) -> pair<float, shared_ptr<ServerAdapterEntry>> + { + return { value -> getLeastLoadedNodeLoad(loadSample), value }; + }); + sort(rl.begin(), rl.end(), [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; }); replicas.clear(); - transform(rl.begin(), rl.end(), back_inserter(replicas), TransformToReplica()); + transform(rl.begin(), rl.end(), back_inserter(replicas), [](const auto& value) { return value.second; }); } // @@ -722,13 +698,13 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n // set<string> emptyExcludes; bool firstUnreachable = true; - for(vector<ServerAdapterEntryPtr>::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - if(!roundRobin || excludes.find((*p)->getId()) == excludes.end()) + if(!roundRobin || excludes.find(replica->getId()) == excludes.end()) { try { - (*p)->getLocatorAdapterInfo(adapters); + replica->getLocatorAdapterInfo(adapters); firstUnreachable = false; } catch(const SynchronizationException&) @@ -745,24 +721,24 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n } } } - catch(...) + catch(const std::exception&) { if(roundRobin) { - Lock sync(*this); + lock_guard lock(_mutex); assert(_requestInProgress); _requestInProgress = false; - notify(); + _condVar.notify_one(); } throw; } if(roundRobin) { - Lock sync(*this); + lock_guard lock(_mutex); assert(_requestInProgress); _requestInProgress = false; - notify(); + _condVar.notify_one(); if(unreachable > 0) { _lastReplica = (_lastReplica + unreachable) % static_cast<int>(_replicas.size()); @@ -778,9 +754,9 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n float ReplicaGroupEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const { - vector<ServerAdapterEntryPtr> replicas; + vector<shared_ptr<ServerAdapterEntry>> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } @@ -795,9 +771,17 @@ ReplicaGroupEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const else { IceUtilInternal::shuffle(replicas.begin(), replicas.end()); - vector<pair<float, ServerAdapterEntryPtr> > rl; - transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); - return min_element(rl.begin(), rl.end(), ReplicaLoadComp())->first; + vector<pair<float, shared_ptr<ServerAdapterEntry>>> rl; + transform(replicas.begin(), replicas.end(), back_inserter(rl), + [loadSample] (const auto& value) -> pair<float, shared_ptr<ServerAdapterEntry>> + { + return { value->getLeastLoadedNodeLoad(loadSample), value }; + }); + return min_element(rl.begin(), rl.end(), + [](const auto& lhs, const auto& rhs) + { + return lhs.first < rhs.first; + })->first; } } @@ -808,34 +792,34 @@ ReplicaGroupEntry::getAdapterInfoNoEndpoints() const // This method is called with the database locked so we're sure // that no new adapters will be added or removed concurrently. // - vector<ServerAdapterEntryPtr> replicas; + vector<shared_ptr<ServerAdapterEntry>> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } AdapterInfoSeq infos; - for(vector<ServerAdapterEntryPtr>::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - AdapterInfoSeq infs = (*p)->getAdapterInfoNoEndpoints(); + AdapterInfoSeq infs = replica->getAdapterInfoNoEndpoints(); assert(infs.size() == 1); infos.push_back(infs[0]); } return infos; } -GetAdapterInfoResultPtr +shared_ptr<GetAdapterInfoResult> ReplicaGroupEntry::getAdapterInfoAsync() const { - GetAdapterInfoResultPtr result = new GetAdapterInfoResult(); - vector<ServerAdapterEntryPtr> replicas; + auto result = make_shared<GetAdapterInfoResult>(); + vector<shared_ptr<ServerAdapterEntry>> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } - for(vector<ServerAdapterEntryPtr>::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - result->add(*p); + result->add(replica.get()); } return result; } @@ -843,16 +827,16 @@ ReplicaGroupEntry::getAdapterInfoAsync() const bool ReplicaGroupEntry::hasAdaptersFromOtherApplications() const { - vector<ServerAdapterEntryPtr> replicas; + vector<shared_ptr<ServerAdapterEntry>> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } AdapterInfoSeq infos; - for(vector<ServerAdapterEntryPtr>::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - if((*p)->getApplication() != _application) + if(replica->getApplication() != _application) { return true; } diff --git a/cpp/src/IceGrid/AdapterCache.h b/cpp/src/IceGrid/AdapterCache.h index bbe0bfeb794..3247315ef56 100644 --- a/cpp/src/IceGrid/AdapterCache.h +++ b/cpp/src/IceGrid/AdapterCache.h @@ -5,69 +5,60 @@ #ifndef ICE_GRID_ADAPTERCACHE_H #define ICE_GRID_ADAPTERCACHE_H -#include <IceUtil/Mutex.h> -#include <IceUtil/Shared.h> #include <IceGrid/Cache.h> #include <IceGrid/Registry.h> #include <IceGrid/Internal.h> +#include <optional> #include <set> namespace IceGrid { class AdapterCache; - -class SynchronizationCallback; -typedef IceUtil::Handle<SynchronizationCallback> SynchronizationCallbackPtr; - -class ServerEntry; -typedef IceUtil::Handle<ServerEntry> ServerEntryPtr; -typedef std::vector<ServerEntryPtr> ServerEntrySeq; - class AdapterEntry; -typedef IceUtil::Handle<AdapterEntry> AdapterEntryPtr; - class ServerAdapterEntry; -typedef IceUtil::Handle<ServerAdapterEntry> ServerAdapterEntryPtr; +class ServerEntry; +class SynchronizationCallback; + +using ServerEntrySeq = std::vector<std::shared_ptr<ServerEntry>>; struct LocatorAdapterInfo { std::string id; - AdapterPrx proxy; - int activationTimeout; - int deactivationTimeout; + std::shared_ptr<AdapterPrx> proxy; + std::chrono::seconds activationTimeout; + std::chrono::seconds deactivationTimeout; }; -typedef std::vector<LocatorAdapterInfo> LocatorAdapterInfoSeq; +using LocatorAdapterInfoSeq = std::vector<LocatorAdapterInfo>; -class GetAdapterInfoResult : public IceUtil::Shared +class GetAdapterInfoResult { public: - void add(const ServerAdapterEntryPtr&); + void add(const ServerAdapterEntry*); AdapterInfoSeq get(); private: AdapterInfoSeq _adapters; - std::vector<Ice::AsyncResultPtr> _results; + std::vector<std::optional<std::future<std::shared_ptr<Ice::ObjectPrx>>>> _results; }; -typedef IceUtil::Handle<GetAdapterInfoResult> GetAdapterInfoResultPtr; -class AdapterEntry : public virtual IceUtil::Shared +class AdapterEntry { public: AdapterEntry(AdapterCache&, const std::string&, const std::string&); - virtual bool addSyncCallback(const SynchronizationCallbackPtr&, const std::set<std::string>&) = 0; + virtual bool addSyncCallback(const std::shared_ptr<SynchronizationCallback>&, const std::set<std::string>&) = 0; virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, const std::set<std::string>&) = 0; virtual float getLeastLoadedNodeLoad(LoadSample) const = 0; virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const = 0; - virtual GetAdapterInfoResultPtr getAdapterInfoAsync() const = 0; - virtual AdapterPrx getProxy(const std::string&, bool) const = 0; + virtual std::shared_ptr<GetAdapterInfoResult> getAdapterInfoAsync() const = 0; + virtual std::shared_ptr<AdapterPrx> getProxy(const std::string&, bool) const = 0; virtual bool canRemove(); @@ -80,24 +71,23 @@ protected: const std::string _id; std::string _application; }; -typedef IceUtil::Handle<AdapterEntry> AdapterEntryPtr; -class ServerAdapterEntry : public AdapterEntry +class ServerAdapterEntry final : public AdapterEntry { public: ServerAdapterEntry(AdapterCache&, const std::string&, const std::string&, const std::string&, int, - const ServerEntryPtr&); + const std::shared_ptr<ServerEntry>&); - virtual bool addSyncCallback(const SynchronizationCallbackPtr&, const std::set<std::string>&); + bool addSyncCallback(const std::shared_ptr<SynchronizationCallback>&, const std::set<std::string>&) override; - virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, - const std::set<std::string>&); + void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, + const std::set<std::string>&) override; - virtual float getLeastLoadedNodeLoad(LoadSample) const; - virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const; - virtual GetAdapterInfoResultPtr getAdapterInfoAsync() const; - virtual AdapterPrx getProxy(const std::string&, bool) const; + float getLeastLoadedNodeLoad(LoadSample) const override; + AdapterInfoSeq getAdapterInfoNoEndpoints() const override; + std::shared_ptr<GetAdapterInfoResult> getAdapterInfoAsync() const override; + std::shared_ptr<AdapterPrx> getProxy(const std::string&, bool) const override; void getLocatorAdapterInfo(LocatorAdapterInfoSeq&) const; const std::string& getReplicaGroupId() const { return _replicaGroupId; } @@ -110,68 +100,69 @@ private: const std::string _replicaGroupId; const int _priority; - const ServerEntryPtr _server; + const std::shared_ptr<ServerEntry> _server; }; -typedef IceUtil::Handle<ServerAdapterEntry> ServerAdapterEntryPtr; -class ReplicaGroupEntry : public AdapterEntry, public IceUtil::Monitor<IceUtil::Mutex> +class ReplicaGroupEntry final : public AdapterEntry { public: - ReplicaGroupEntry(AdapterCache&, const std::string&, const std::string&, const LoadBalancingPolicyPtr&, + ReplicaGroupEntry(AdapterCache&, const std::string&, const std::string&, const std::shared_ptr<LoadBalancingPolicy>&, const std::string&); - virtual bool addSyncCallback(const SynchronizationCallbackPtr&, const std::set<std::string>&); + virtual bool addSyncCallback(const std::shared_ptr<SynchronizationCallback>&, const std::set<std::string>&); virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, const std::set<std::string>&); virtual float getLeastLoadedNodeLoad(LoadSample) const; virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const; - virtual GetAdapterInfoResultPtr getAdapterInfoAsync() const; - virtual AdapterPrx getProxy(const std::string&, bool) const { return 0; } + virtual std::shared_ptr<GetAdapterInfoResult> getAdapterInfoAsync() const; + virtual std::shared_ptr<AdapterPrx> getProxy(const std::string&, bool) const { return nullptr; } - void addReplica(const std::string&, const ServerAdapterEntryPtr&); + void addReplica(const std::string&, const std::shared_ptr<ServerAdapterEntry>&); bool removeReplica(const std::string&); - void update(const std::string&, const LoadBalancingPolicyPtr&, const std::string&); + void update(const std::string&, const std::shared_ptr<LoadBalancingPolicy>&, const std::string&); bool hasAdaptersFromOtherApplications() const; const std::string& getFilter() const { return _filter; } private: - LoadBalancingPolicyPtr _loadBalancing; + std::shared_ptr<LoadBalancingPolicy> _loadBalancing; int _loadBalancingNReplicas; LoadSample _loadSample; std::string _filter; - std::vector<ServerAdapterEntryPtr> _replicas; + std::vector<std::shared_ptr<ServerAdapterEntry>> _replicas; int _lastReplica; bool _requestInProgress; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle<ReplicaGroupEntry> ReplicaGroupEntryPtr; class AdapterCache : public CacheByString<AdapterEntry> { public: - AdapterCache(const Ice::CommunicatorPtr&); + AdapterCache(const std::shared_ptr<Ice::Communicator>&); - void addServerAdapter(const AdapterDescriptor&, const ServerEntryPtr&, const std::string&); + void addServerAdapter(const AdapterDescriptor&, const std::shared_ptr<ServerEntry>&, const std::string&); void addReplicaGroup(const ReplicaGroupDescriptor&, const std::string&); - AdapterEntryPtr get(const std::string&) const; + std::shared_ptr<AdapterEntry> get(const std::string&) const; void removeServerAdapter(const std::string&); void removeReplicaGroup(const std::string&); protected: - virtual AdapterEntryPtr addImpl(const std::string&, const AdapterEntryPtr&); + virtual std::shared_ptr<AdapterEntry> addImpl(const std::string&, const std::shared_ptr<AdapterEntry>&); virtual void removeImpl(const std::string&); private: - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr<Ice::Communicator> _communicator; }; }; diff --git a/cpp/src/IceGrid/AdminCallbackRouter.cpp b/cpp/src/IceGrid/AdminCallbackRouter.cpp index 3d58311845c..d1a394cf8a3 100644 --- a/cpp/src/IceGrid/AdminCallbackRouter.cpp +++ b/cpp/src/IceGrid/AdminCallbackRouter.cpp @@ -4,42 +4,26 @@ #include <IceGrid/AdminCallbackRouter.h> -using namespace Ice; using namespace std; +using namespace IceGrid; void -IceGrid::AdminCallbackRouter::invokeResponse(bool ok, - const std::pair<const Byte*, const Byte*>& outParams, - const AMD_Object_ice_invokePtr& amdCB) +AdminCallbackRouter::addMapping(const string& category, const shared_ptr<Ice::Connection>& con) { - amdCB->ice_response(ok, outParams); -} - -void -IceGrid::AdminCallbackRouter::invokeException(const Ice::Exception&, const AMD_Object_ice_invokePtr& amdCB) -{ - // Callback object is unreachable. - amdCB->ice_exception(ObjectNotExistException(__FILE__, __LINE__)); -} - -void -IceGrid::AdminCallbackRouter::addMapping(const string& category, const ConnectionPtr& con) -{ - IceUtil::Mutex::Lock sync(_mutex); + lock_guard lock(_mutex); #ifdef NDEBUG - _categoryToConnection.insert(map<string, ConnectionPtr>::value_type(category, con)); + _categoryToConnection.insert({ category, con }); #else - bool inserted = - _categoryToConnection.insert(map<string, ConnectionPtr>::value_type(category, con)).second; + bool inserted = _categoryToConnection.insert({ category, con }).second; assert(inserted == true); #endif } void -IceGrid::AdminCallbackRouter::removeMapping(const string& category) +AdminCallbackRouter::removeMapping(const string& category) { - IceUtil::Mutex::Lock sync(_mutex); + lock_guard lock(_mutex); #ifndef NDEBUG size_t one = @@ -50,30 +34,34 @@ IceGrid::AdminCallbackRouter::removeMapping(const string& category) } void -IceGrid::AdminCallbackRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const pair<const Byte*, const Byte*>& inParams, - const Current& current) +AdminCallbackRouter::ice_invokeAsync(pair<const Ice::Byte*, const Ice::Byte*> inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) { - ConnectionPtr con; + shared_ptr<Ice::Connection> con; { - IceUtil::Mutex::Lock sync(_mutex); - map<string, ConnectionPtr>::iterator p = _categoryToConnection.find(current.id.category); + lock_guard lock(_mutex); + auto p = _categoryToConnection.find(current.id.category); if(p == _categoryToConnection.end()) { - throw ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } con = p->second; } - ObjectPrx target = con->createProxy(current.id)->ice_facet(current.facet); + auto target = con->createProxy(current.id)->ice_facet(current.facet); // // Call with AMI // - target->begin_ice_invoke(current.operation, current.mode, inParams, current.ctx, - newCallback_Object_ice_invoke(this, - &AdminCallbackRouter::invokeResponse, - &AdminCallbackRouter::invokeException), - cb); + target->ice_invokeAsync(current.operation, current.mode, inParams, + move(response), + [exception = move(exception)] (exception_ptr) + { + exception(make_exception_ptr(Ice::ObjectNotExistException(__FILE__, __LINE__))); + }, + nullptr, + current.ctx); } diff --git a/cpp/src/IceGrid/AdminCallbackRouter.h b/cpp/src/IceGrid/AdminCallbackRouter.h index 67800fe1f97..7e8184408c7 100644 --- a/cpp/src/IceGrid/AdminCallbackRouter.h +++ b/cpp/src/IceGrid/AdminCallbackRouter.h @@ -21,25 +21,20 @@ class AdminCallbackRouter : public Ice::BlobjectArrayAsync { public: - void addMapping(const std::string&, const Ice::ConnectionPtr&); + void addMapping(const std::string&, const std::shared_ptr<Ice::Connection>&); void removeMapping(const std::string&); - virtual void invokeResponse(bool, - const std::pair<const ::Ice::Byte*, const ::Ice::Byte*>&, - const Ice::AMD_Object_ice_invokePtr&); - - virtual void invokeException(const Ice::Exception&, const Ice::AMD_Object_ice_invokePtr&); - - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair<const Ice::Byte*, const Ice::Byte*>&, - const Ice::Current&); + void ice_invokeAsync(std::pair<const Ice::Byte*, const Ice::Byte*>, + std::function<void(bool, const std::pair<const Ice::Byte*, const Ice::Byte*>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current& current) override; private: - IceUtil::Mutex _mutex; - std::map<std::string, Ice::ConnectionPtr> _categoryToConnection; + std::mutex _mutex; + std::map<std::string, std::shared_ptr<Ice::Connection>> _categoryToConnection; }; -typedef IceUtil::Handle<AdminCallbackRouter> AdminCallbackRouterPtr; } + #endif diff --git a/cpp/src/IceGrid/AdminI.cpp b/cpp/src/IceGrid/AdminI.cpp index 3c27f0a119f..b8637fce89b 100644 --- a/cpp/src/IceGrid/AdminI.cpp +++ b/cpp/src/IceGrid/AdminI.cpp @@ -16,23 +16,25 @@ #include <IceGrid/DescriptorHelper.h> #include <IceGrid/AdminSessionI.h> #include <IceGrid/NodeSessionI.h> +#include <IceGrid/Internal.h> using namespace std; +using namespace std::chrono; using namespace Ice; using namespace IceGrid; -namespace IceGrid +namespace { class ServerProxyWrapper { public: - ServerProxyWrapper(const DatabasePtr& database, const string& id) : _id(id) + ServerProxyWrapper(const shared_ptr<Database>& database, const string& id) : _id(id) { try { - _proxy = database->getServer(_id)->getProxy(_activationTimeout, _deactivationTimeout, _node, false, 5); + _proxy = database->getServer(_id)->getProxy(_activationTimeout, _deactivationTimeout, _node, false, 5s); } catch(const SynchronizationException&) { @@ -40,39 +42,65 @@ public: } } - ServerProxyWrapper(const ServerProxyWrapper& wrapper) : - _id(wrapper._id), - _proxy(wrapper._proxy), - _activationTimeout(wrapper._activationTimeout), - _deactivationTimeout(wrapper._deactivationTimeout), - _node(wrapper._node) + ServerProxyWrapper(const ServerProxyWrapper& wrapper) = default; + + template<typename Func, typename... Args> + auto invoke(Func&& f, Args&&... args) { + try + { + return std::invoke(forward<Func>(f), _proxy, forward<Args>(args)..., ::Ice::noExplicitContext); + } + catch (const Ice::Exception&) + { + handleException(current_exception()); + throw; // keep compiler happy + } + } + + template<typename Func> + auto invokeAsync(Func&& f, function<void()> response, function<void(exception_ptr)> exception) + { + auto exceptionWrapper = [this, exception = move(exception)](exception_ptr ex) + { + try + { + handleException(ex); + } + catch(const std::exception&) + { + exception(current_exception()); + } + }; + return std::invoke(forward<Func>(f), _proxy, move(response), move(exceptionWrapper), nullptr, Ice::noExplicitContext); } void useActivationTimeout() { - _proxy = ServerPrx::uncheckedCast(_proxy->ice_invocationTimeout(_activationTimeout * 1000)); + auto timeout = secondsToInt(_activationTimeout) * 1000; + _proxy = _proxy->ice_invocationTimeout(timeout); } void useDeactivationTimeout() { - _proxy = ServerPrx::uncheckedCast(_proxy->ice_invocationTimeout(_deactivationTimeout * 1000)); + auto timeout = secondsToInt(_deactivationTimeout) * 1000; + _proxy = _proxy->ice_invocationTimeout(timeout); } - IceProxy::IceGrid::Server* + ServerPrx* operator->() const { return _proxy.get(); } void - handleException(const Ice::Exception& ex) const + handleException(exception_ptr ex) const { try { - ex.ice_throw(); + rethrow_exception(ex); } catch(const Ice::UserException&) { @@ -84,24 +112,23 @@ public: } catch(const Ice::LocalException& e) { - ostringstream os; - os << e; - throw NodeUnreachableException(_node, os.str()); + throw NodeUnreachableException(_node, e.what()); } } private: string _id; - ServerPrx _proxy; - int _activationTimeout; - int _deactivationTimeout; + shared_ptr<ServerPrx> _proxy; + chrono::seconds _activationTimeout; + chrono::seconds _deactivationTimeout; string _node; }; } -AdminI::AdminI(const DatabasePtr& database, const RegistryIPtr& registry, const AdminSessionIPtr& session) : +AdminI::AdminI(const shared_ptr<Database>& database, const shared_ptr<RegistryI>& registry, + const shared_ptr<AdminSessionI>& session) : _database(database), _registry(registry), _traceLevels(_database->getTraceLevels()), @@ -109,17 +136,13 @@ AdminI::AdminI(const DatabasePtr& database, const RegistryIPtr& registry, const { } -AdminI::~AdminI() -{ -} - void -AdminI::addApplication(const ApplicationDescriptor& descriptor, const Current&) +AdminI::addApplication(ApplicationDescriptor descriptor, const Current&) { checkIsReadOnly(); ApplicationInfo info; - info.createTime = info.updateTime = IceUtil::Time::now().toMilliSeconds(); + info.createTime = info.updateTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); info.createUser = info.updateUser = _session->getId(); info.descriptor = descriptor; info.revision = 1; @@ -129,19 +152,19 @@ AdminI::addApplication(const ApplicationDescriptor& descriptor, const Current&) } void -AdminI::syncApplication(const ApplicationDescriptor& descriptor, const Current&) +AdminI::syncApplication(ApplicationDescriptor descriptor, const Current&) { checkIsReadOnly(); _database->syncApplicationDescriptor(descriptor, false, _session.get()); } void -AdminI::updateApplication(const ApplicationUpdateDescriptor& descriptor, const Current&) +AdminI::updateApplication(ApplicationUpdateDescriptor descriptor, const Current&) { checkIsReadOnly(); ApplicationUpdateInfo update; - update.updateTime = IceUtil::Time::now().toMilliSeconds(); + update.updateTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); update.updateUser = _session->getId(); update.descriptor = descriptor; update.revision = -1; // The database will set it. @@ -149,19 +172,19 @@ AdminI::updateApplication(const ApplicationUpdateDescriptor& descriptor, const C } void -AdminI::syncApplicationWithoutRestart(const ApplicationDescriptor& descriptor, const Current&) +AdminI::syncApplicationWithoutRestart(ApplicationDescriptor descriptor, const Current&) { checkIsReadOnly(); _database->syncApplicationDescriptor(descriptor, true, _session.get()); } void -AdminI::updateApplicationWithoutRestart(const ApplicationUpdateDescriptor& descriptor, const Current&) +AdminI::updateApplicationWithoutRestart(ApplicationUpdateDescriptor descriptor, const Current&) { checkIsReadOnly(); ApplicationUpdateInfo update; - update.updateTime = IceUtil::Time::now().toMilliSeconds(); + update.updateTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); update.updateUser = _session->getId(); update.descriptor = descriptor; update.revision = -1; // The database will set it. @@ -169,29 +192,29 @@ AdminI::updateApplicationWithoutRestart(const ApplicationUpdateDescriptor& descr } void -AdminI::removeApplication(const string& name, const Current&) +AdminI::removeApplication(string name, const Current&) { checkIsReadOnly(); - _database->removeApplication(name, _session.get()); + _database->removeApplication(move(name), _session.get()); } void -AdminI::instantiateServer(const string& app, const string& node, const ServerInstanceDescriptor& desc, const Current&) +AdminI::instantiateServer(string app, string node, ServerInstanceDescriptor desc, const Current&) { checkIsReadOnly(); - _database->instantiateServer(app, node, desc, _session.get()); + _database->instantiateServer(move(app), move(node), move(desc), _session.get()); } ApplicationInfo -AdminI::getApplicationInfo(const string& name, const Current&) const +AdminI::getApplicationInfo(string name, const Current&) const { - return _database->getApplicationInfo(name); + return _database->getApplicationInfo(move(name)); } ApplicationDescriptor AdminI::getDefaultApplicationDescriptor(const Current& current) const { - Ice::PropertiesPtr properties = current.adapter->getCommunicator()->getProperties(); + auto properties = current.adapter->getCommunicator()->getProperties(); string path = properties->getProperty("IceGrid.Registry.DefaultTemplates"); if(path.empty()) { @@ -243,39 +266,23 @@ AdminI::getAllApplicationNames(const Current&) const } ServerInfo -AdminI::getServerInfo(const string& id, const Current&) const +AdminI::getServerInfo(string id, const Current&) const { - return _database->getServer(id)->getInfo(true); + return _database->getServer(move(id))->getInfo(true); } ServerState -AdminI::getServerState(const string& id, const Current&) const +AdminI::getServerState(string id, const Current&) const { - ServerProxyWrapper proxy(_database, id); - try - { - return proxy->getState(); - } - catch(const Ice::Exception& ex) - { - proxy.handleException(ex); - return Inactive; - } + ServerProxyWrapper proxy(_database, move(id)); + return proxy.invoke(&ServerPrx::getState); } -Ice::Int -AdminI::getServerPid(const string& id, const Current&) const +int +AdminI::getServerPid(string id, const Current&) const { - ServerProxyWrapper proxy(_database, id); - try - { - return proxy->getPid(); - } - catch(const Ice::Exception& ex) - { - proxy.handleException(ex); - return 0; - } + ServerProxyWrapper proxy(_database, move(id)); + return proxy.invoke(&ServerPrx::getPid); } string @@ -284,115 +291,25 @@ AdminI::getServerAdminCategory(const Current&) const return _registry->getServerAdminCategory(); } -ObjectPrx -AdminI::getServerAdmin(const string& id, const Current& current) const +shared_ptr<ObjectPrx> +AdminI::getServerAdmin(string id, const Current& current) const { ServerProxyWrapper proxy(_database, id); // Ensure that the server exists and loaded on the node. - Ice::Identity adminId; - adminId.name = id; - adminId.category = _registry->getServerAdminCategory(); - return current.adapter->createProxy(adminId); -} - -namespace -{ - -class StartCB : public virtual IceUtil::Shared -{ -public: - - StartCB(const ServerProxyWrapper& proxy, const AMD_Admin_startServerPtr& amdCB) : _proxy(proxy), _amdCB(amdCB) - { - } - - virtual void - response() - { - _amdCB->ice_response(); - } - - virtual void - exception(const Ice::Exception& ex) - { - try - { - _proxy.handleException(ex); - assert(false); - } - catch(const Ice::Exception& e) - { - _amdCB->ice_exception(e); - } - } - -private: - - const ServerProxyWrapper _proxy; - const AMD_Admin_startServerPtr _amdCB; -}; - + return current.adapter->createProxy({ id, _registry->getServerAdminCategory() }); } void -AdminI::startServer_async(const AMD_Admin_startServerPtr& amdCB, const string& id, const Current&) +AdminI::startServerAsync(string id, function<void()> response, function<void(exception_ptr)> exception, const Current&) { - ServerProxyWrapper proxy(_database, id); + ServerProxyWrapper proxy(_database, move(id)); proxy.useActivationTimeout(); - // - // Since the server might take a while to be activated, we use AMI. - // - proxy->begin_start(newCallback_Server_start(new StartCB(proxy, amdCB), - &StartCB::response, - &StartCB::exception)); -} - -namespace -{ - -class StopCB : public virtual IceUtil::Shared -{ -public: - - StopCB(const ServerProxyWrapper& proxy, const AMD_Admin_stopServerPtr& amdCB) : _proxy(proxy), _amdCB(amdCB) - { - } - - virtual void - response() - { - _amdCB->ice_response(); - } - - virtual void - exception(const Ice::Exception& ex) - { - try - { - _proxy.handleException(ex); - assert(false); - } - catch(const Ice::TimeoutException&) - { - _amdCB->ice_response(); - } - catch(const Ice::Exception& e) - { - _amdCB->ice_exception(e); - } - } - -private: - - const ServerProxyWrapper _proxy; - const AMD_Admin_stopServerPtr _amdCB; -}; - + proxy.invokeAsync([](const auto& prx, auto... args) { prx->startAsync(args...); }, move(response), move(exception)); } void -AdminI::stopServer_async(const AMD_Admin_stopServerPtr& amdCB, const string& id, const Current&) +AdminI::stopServerAsync(string id, function<void()> response, function<void(exception_ptr)> exception, const Current&) { ServerProxyWrapper proxy(_database, id); proxy.useDeactivationTimeout(); @@ -400,23 +317,29 @@ AdminI::stopServer_async(const AMD_Admin_stopServerPtr& amdCB, const string& id, // // Since the server might take a while to be deactivated, we use AMI. // - proxy->begin_stop(newCallback_Server_stop(new StopCB(proxy, amdCB), - &StopCB::response, - &StopCB::exception)); + proxy.invokeAsync([](const auto& prx, auto... args) { prx->stopAsync(args...); }, + response, + [response, exception = move(exception)](exception_ptr ex) { + try + { + rethrow_exception(ex); + } + catch(const Ice::TimeoutException&) + { + response(); + } + catch(const Ice::Exception&) + { + exception(current_exception()); + } + }); } void -AdminI::sendSignal(const string& id, const string& signal, const Current&) +AdminI::sendSignal(string id, string signal, const Current&) { - ServerProxyWrapper proxy(_database, id); - try - { - proxy->sendSignal(signal); - } - catch(const Ice::Exception& ex) - { - proxy.handleException(ex); - } + ServerProxyWrapper proxy(_database, move(id)); + proxy.invoke(&ServerPrx::sendSignal, move(signal)); } StringSeq @@ -426,42 +349,27 @@ AdminI::getAllServerIds(const Current&) const } void -AdminI::enableServer(const string& id, bool enable, const Ice::Current&) +AdminI::enableServer(string id, bool enable, const Ice::Current&) { - ServerProxyWrapper proxy(_database, id); - try - { - proxy->setEnabled(enable); - } - catch(const Ice::Exception& ex) - { - proxy.handleException(ex); - } + ServerProxyWrapper proxy(_database, move(id)); + proxy.invoke(&ServerPrx::setEnabled, move(enable)); } bool -AdminI::isServerEnabled(const ::std::string& id, const Ice::Current&) const +AdminI::isServerEnabled(string id, const Ice::Current&) const { - ServerProxyWrapper proxy(_database, id); - try - { - return proxy->isEnabled(); - } - catch(const Ice::Exception& ex) - { - proxy.handleException(ex); - return true; // Keeps the compiler happy. - } + ServerProxyWrapper proxy(_database, move(id)); + return proxy.invoke(&ServerPrx::isEnabled); } AdapterInfoSeq -AdminI::getAdapterInfo(const string& id, const Current&) const +AdminI::getAdapterInfo(string id, const Current&) const { return _database->getAdapterInfo(id); } void -AdminI::removeAdapter(const string& adapterId, const Ice::Current&) +AdminI::removeAdapter(string adapterId, const Ice::Current&) { checkIsReadOnly(); _database->removeAdapter(adapterId); @@ -474,7 +382,7 @@ AdminI::getAllAdapterIds(const Current&) const } void -AdminI::addObject(const Ice::ObjectPrx& proxy, const ::Ice::Current& current) +AdminI::addObject(shared_ptr<Ice::ObjectPrx> proxy, const ::Ice::Current& current) { checkIsReadOnly(); @@ -497,7 +405,7 @@ AdminI::addObject(const Ice::ObjectPrx& proxy, const ::Ice::Current& current) } void -AdminI::updateObject(const Ice::ObjectPrx& proxy, const ::Ice::Current&) +AdminI::updateObject(shared_ptr<Ice::ObjectPrx> proxy, const ::Ice::Current&) { checkIsReadOnly(); @@ -517,7 +425,7 @@ AdminI::updateObject(const Ice::ObjectPrx& proxy, const ::Ice::Current&) } void -AdminI::addObjectWithType(const Ice::ObjectPrx& proxy, const string& type, const ::Ice::Current&) +AdminI::addObjectWithType(shared_ptr<Ice::ObjectPrx> proxy, string type, const ::Ice::Current&) { checkIsReadOnly(); @@ -541,7 +449,7 @@ AdminI::addObjectWithType(const Ice::ObjectPrx& proxy, const string& type, const } void -AdminI::removeObject(const Ice::Identity& id, const Ice::Current&) +AdminI::removeObject(Ice::Identity id, const Ice::Current&) { checkIsReadOnly(); if(id.category == _database->getInstanceName()) @@ -554,45 +462,42 @@ AdminI::removeObject(const Ice::Identity& id, const Ice::Current&) } ObjectInfo -AdminI::getObjectInfo(const Ice::Identity& id, const Ice::Current&) const +AdminI::getObjectInfo(Ice::Identity id, const Ice::Current&) const { - return _database->getObjectInfo(id); + return _database->getObjectInfo(move(id)); } ObjectInfoSeq -AdminI::getObjectInfosByType(const string& type, const Ice::Current&) const +AdminI::getObjectInfosByType(string type, const Ice::Current&) const { - return _database->getObjectInfosByType(type); + return _database->getObjectInfosByType(move(type)); } ObjectInfoSeq -AdminI::getAllObjectInfos(const string& expression, const Ice::Current&) const +AdminI::getAllObjectInfos(string expression, const Ice::Current&) const { - return _database->getAllObjectInfos(expression); + return _database->getAllObjectInfos(move(expression)); } NodeInfo -AdminI::getNodeInfo(const string& name, const Ice::Current&) const +AdminI::getNodeInfo(string name, const Ice::Current&) const { return toNodeInfo(_database->getNode(name)->getInfo()); } -ObjectPrx -AdminI::getNodeAdmin(const string& name, const Current& current) const +shared_ptr<ObjectPrx> +AdminI::getNodeAdmin(string name, const Current& current) const { // // Check if the node exists // _database->getNode(name); - Ice::Identity adminId; - adminId.name = name; - adminId.category = _registry->getNodeAdminCategory(); - return current.adapter->createProxy(adminId); + return current.adapter->createProxy({ name, _registry->getNodeAdminCategory() }); } bool -AdminI::pingNode(const string& name, const Current&) const +AdminI::pingNode(string name, const Current&) const { try { @@ -614,7 +519,7 @@ AdminI::pingNode(const string& name, const Current&) const } LoadInfo -AdminI::getNodeLoad(const string& name, const Current&) const +AdminI::getNodeLoad(string name, const Current&) const { try { @@ -633,7 +538,7 @@ AdminI::getNodeLoad(const string& name, const Current&) const } int -AdminI::getNodeProcessorSocketCount(const string& name, const Current&) const +AdminI::getNodeProcessorSocketCount(string name, const Current&) const { try { @@ -658,7 +563,7 @@ AdminI::getNodeProcessorSocketCount(const string& name, const Current&) const } void -AdminI::shutdownNode(const string& name, const Current&) +AdminI::shutdownNode(string name, const Current&) { try { @@ -677,7 +582,7 @@ AdminI::shutdownNode(const string& name, const Current&) } string -AdminI::getNodeHostname(const string& name, const Current&) const +AdminI::getNodeHostname(string name, const Current&) const { try { @@ -702,7 +607,7 @@ AdminI::getAllNodeNames(const Current&) const } RegistryInfo -AdminI::getRegistryInfo(const string& name, const Ice::Current&) const +AdminI::getRegistryInfo(string name, const Ice::Current&) const { if(name == _registry->getName()) { @@ -714,8 +619,8 @@ AdminI::getRegistryInfo(const string& name, const Ice::Current&) const } } -ObjectPrx -AdminI::getRegistryAdmin(const string& name, const Current& current) const +shared_ptr<ObjectPrx> +AdminI::getRegistryAdmin(string name, const Current& current) const { if(name != _registry->getName()) { @@ -725,14 +630,11 @@ AdminI::getRegistryAdmin(const string& name, const Current& current) const _database->getReplica(name); } - Identity adminId; - adminId.name = name; - adminId.category = _registry->getReplicaAdminCategory(); - return current.adapter->createProxy(adminId); + return current.adapter->createProxy({ name, _registry->getReplicaAdminCategory() }); } bool -AdminI::pingRegistry(const string& name, const Current&) const +AdminI::pingRegistry(string name, const Current&) const { if(name == _registry->getName()) { @@ -755,7 +657,7 @@ AdminI::pingRegistry(const string& name, const Current&) const } void -AdminI::shutdownRegistry(const string& name, const Current&) +AdminI::shutdownRegistry(string name, const Current&) { if(name == _registry->getName()) { diff --git a/cpp/src/IceGrid/AdminI.h b/cpp/src/IceGrid/AdminI.h index ac294ae0445..e6b065c149c 100644 --- a/cpp/src/IceGrid/AdminI.h +++ b/cpp/src/IceGrid/AdminI.h @@ -10,89 +10,83 @@ namespace IceGrid { +class AdminSessionI; class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - class RegistryI; -typedef IceUtil::Handle<RegistryI> RegistryIPtr; - -class AdminSessionI; -typedef IceUtil::Handle<AdminSessionI> AdminSessionIPtr; +class TraceLevels; -class AdminI : public Admin, public IceUtil::Mutex +class AdminI final : public Admin { public: - AdminI(const DatabasePtr&, const RegistryIPtr&, const AdminSessionIPtr&); - virtual ~AdminI(); - - virtual void addApplication(const ApplicationDescriptor&, const Ice::Current&); - virtual void syncApplication(const ApplicationDescriptor&, const Ice::Current&); - virtual void updateApplication(const ApplicationUpdateDescriptor&, const Ice::Current&); - virtual void syncApplicationWithoutRestart(const ApplicationDescriptor&, const Ice::Current&); - virtual void updateApplicationWithoutRestart(const ApplicationUpdateDescriptor&, const Ice::Current&); - virtual void removeApplication(const std::string&, const Ice::Current&); - virtual void instantiateServer(const std::string&, const std::string&, const ServerInstanceDescriptor&, - const Ice::Current&); - virtual ApplicationInfo getApplicationInfo(const ::std::string&, const Ice::Current&) const; - virtual ApplicationDescriptor getDefaultApplicationDescriptor(const Ice::Current&) const; - virtual Ice::StringSeq getAllApplicationNames(const Ice::Current&) const; - - virtual ServerInfo getServerInfo(const ::std::string&, const Ice::Current&) const; - virtual ServerState getServerState(const ::std::string&, const Ice::Current&) const; - virtual Ice::Int getServerPid(const ::std::string&, const Ice::Current&) const; - virtual std::string getServerAdminCategory(const Ice::Current&) const; - virtual Ice::ObjectPrx getServerAdmin(const std::string&, const Ice::Current&) const; - virtual void startServer_async(const AMD_Admin_startServerPtr&, const ::std::string&, const Ice::Current&); - virtual void stopServer_async(const AMD_Admin_stopServerPtr&, const ::std::string&, const Ice::Current&); - virtual void sendSignal(const ::std::string&, const ::std::string&, const Ice::Current&); - virtual Ice::StringSeq getAllServerIds(const Ice::Current&) const; - virtual void enableServer(const ::std::string&, bool, const Ice::Current&); - virtual bool isServerEnabled(const ::std::string&, const Ice::Current&) const; - - virtual AdapterInfoSeq getAdapterInfo(const ::std::string&, const ::Ice::Current&) const; - virtual void removeAdapter(const std::string&, const Ice::Current&); - virtual Ice::StringSeq getAllAdapterIds(const ::Ice::Current&) const; - - virtual void addObject(const ::Ice::ObjectPrx&, const ::Ice::Current&); - virtual void updateObject(const ::Ice::ObjectPrx&, const ::Ice::Current&); - virtual void addObjectWithType(const ::Ice::ObjectPrx&, const ::std::string&, const ::Ice::Current&); - virtual void removeObject(const ::Ice::Identity&, const ::Ice::Current&); - virtual ObjectInfo getObjectInfo(const Ice::Identity&, const ::Ice::Current&) const; - virtual ObjectInfoSeq getObjectInfosByType(const std::string&, const ::Ice::Current&) const; - virtual ObjectInfoSeq getAllObjectInfos(const std::string&, const ::Ice::Current&) const; - - virtual NodeInfo getNodeInfo(const std::string&, const Ice::Current&) const; - virtual Ice::ObjectPrx getNodeAdmin(const std::string&, const Ice::Current&) const; - virtual bool pingNode(const std::string&, const Ice::Current&) const; - virtual LoadInfo getNodeLoad(const std::string&, const Ice::Current&) const; - virtual int getNodeProcessorSocketCount(const std::string&, const Ice::Current&) const; - virtual void shutdownNode(const std::string&, const Ice::Current&); - virtual std::string getNodeHostname(const std::string&, const Ice::Current&) const; - virtual Ice::StringSeq getAllNodeNames(const ::Ice::Current&) const; - - virtual RegistryInfo getRegistryInfo(const std::string&, const Ice::Current&) const; - virtual Ice::ObjectPrx getRegistryAdmin(const std::string&, const Ice::Current&) const; - virtual bool pingRegistry(const std::string&, const Ice::Current&) const; - virtual void shutdownRegistry(const std::string&, const Ice::Current&); - virtual Ice::StringSeq getAllRegistryNames(const ::Ice::Current&) const; - - virtual void shutdown(const Ice::Current&); + AdminI(const std::shared_ptr<Database>&, const std::shared_ptr<RegistryI>&, const std::shared_ptr<AdminSessionI>&); + + void addApplication(ApplicationDescriptor, const Ice::Current&) override; + void syncApplication(ApplicationDescriptor, const Ice::Current&) override; + void updateApplication(ApplicationUpdateDescriptor, const Ice::Current&) override; + void syncApplicationWithoutRestart(ApplicationDescriptor, const Ice::Current&) override; + void updateApplicationWithoutRestart(ApplicationUpdateDescriptor, const Ice::Current&) override; + void removeApplication(std::string, const Ice::Current&) override; + void instantiateServer(std::string, std::string, ServerInstanceDescriptor, const Ice::Current&) override; + ApplicationInfo getApplicationInfo(std::string, const Ice::Current&) const override; + ApplicationDescriptor getDefaultApplicationDescriptor(const Ice::Current&) const override; + Ice::StringSeq getAllApplicationNames(const Ice::Current&) const override; + + ServerInfo getServerInfo(std::string, const Ice::Current&) const override; + ServerState getServerState(std::string, const Ice::Current&) const override; + Ice::Int getServerPid(std::string, const Ice::Current&) const override; + std::string getServerAdminCategory(const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> getServerAdmin(std::string, const Ice::Current&) const override; + void startServerAsync(std::string, std::function<void()>, std::function<void(std::exception_ptr)>, + const Ice::Current&) override; + void stopServerAsync(std::string, std::function<void()>, std::function<void(std::exception_ptr)>, + const Ice::Current&) override; + void sendSignal(std::string, std::string, const Ice::Current&) override; + Ice::StringSeq getAllServerIds(const Ice::Current&) const override; + void enableServer(std::string, bool, const Ice::Current&) override; + bool isServerEnabled(std::string, const Ice::Current&) const override; + + AdapterInfoSeq getAdapterInfo(std::string, const ::Ice::Current&) const override; + void removeAdapter(std::string, const Ice::Current&) override; + Ice::StringSeq getAllAdapterIds(const ::Ice::Current&) const override; + + void addObject(std::shared_ptr<Ice::ObjectPrx>, const ::Ice::Current&) override; + void updateObject(std::shared_ptr<Ice::ObjectPrx>, const ::Ice::Current&) override; + void addObjectWithType(std::shared_ptr<Ice::ObjectPrx>, std::string, const ::Ice::Current&) override; + void removeObject(Ice::Identity, const ::Ice::Current&) override; + ObjectInfo getObjectInfo(Ice::Identity, const ::Ice::Current&) const override; + ObjectInfoSeq getObjectInfosByType(std::string, const ::Ice::Current&) const override; + ObjectInfoSeq getAllObjectInfos(std::string, const ::Ice::Current&) const override; + + NodeInfo getNodeInfo(std::string, const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> getNodeAdmin(std::string, const Ice::Current&) const override; + bool pingNode(std::string, const Ice::Current&) const override; + LoadInfo getNodeLoad(std::string, const Ice::Current&) const override; + int getNodeProcessorSocketCount(std::string, const Ice::Current&) const override; + void shutdownNode(std::string, const Ice::Current&) override; + std::string getNodeHostname(std::string, const Ice::Current&) const override; + Ice::StringSeq getAllNodeNames(const ::Ice::Current&) const override; + + RegistryInfo getRegistryInfo(std::string, const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> getRegistryAdmin(std::string, const Ice::Current&) const override; + bool pingRegistry(std::string, const Ice::Current&) const override; + void shutdownRegistry(std::string, const Ice::Current&) override; + Ice::StringSeq getAllRegistryNames(const ::Ice::Current&) const override; + + void shutdown(const Ice::Current&) override; private: void checkIsReadOnly() const; - const DatabasePtr _database; - const RegistryIPtr _registry; - const TraceLevelsPtr _traceLevels; - const AdminSessionIPtr _session; + const std::shared_ptr<Database> _database; + const std::shared_ptr<RegistryI> _registry; + const std::shared_ptr<TraceLevels> _traceLevels; + const std::shared_ptr<AdminSessionI> _session; + + std::mutex _mutex; }; -typedef IceUtil::Handle<AdminI> AdminIPtr; } diff --git a/cpp/src/IceGrid/AdminRouter.cpp b/cpp/src/IceGrid/AdminRouter.cpp index 27c0fa9c0ae..b4ce2128540 100644 --- a/cpp/src/IceGrid/AdminRouter.cpp +++ b/cpp/src/IceGrid/AdminRouter.cpp @@ -4,89 +4,73 @@ #include <IceGrid/AdminRouter.h> -using namespace Ice; using namespace std; +using namespace IceGrid; -namespace -{ - -class CallbackI : public IceUtil::Shared -{ -public: - - CallbackI(const AMD_Object_ice_invokePtr& cb, const Ice::ObjectPrx& target, const string& operation, - const IceGrid::TraceLevelsPtr& traceLevels) : - _cb(cb), - _target(target), - _operation(operation), - _traceLevels(traceLevels) - { - } - - void response(bool ok, const pair<const Byte*, const Byte*>& outParams) - { - if(_traceLevels->admin > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->adminCat); - - out << "operation `" << _operation << "' routed to `" << Ice::identityToString(_target->ice_getIdentity()) - << " -f " << _target->ice_getFacet() << "' is returning "; - if(ok) - { - out << "successfully"; - } - else - { - out << "a user exception"; - } - } - _cb->ice_response(ok, outParams); - } - - void exception(const Ice::Exception& ex) - { - if(_traceLevels->admin > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->adminCat); - out << "operation `" << _operation << "' routed to `" << Ice::identityToString(_target->ice_getIdentity()) - << " -f " << _target->ice_getFacet() << "' failed with " << ex; - } - // Admin object is unreachable - _cb->ice_exception(ObjectNotExistException(__FILE__, __LINE__)); - } - -private: - AMD_Object_ice_invokePtr _cb; - Ice::ObjectPrx _target; - string _operation; - const IceGrid::TraceLevelsPtr _traceLevels; -}; - -} - -IceGrid::AdminRouter::AdminRouter(const TraceLevelsPtr& traceLevels) : +IceGrid::AdminRouter::AdminRouter(const shared_ptr<TraceLevels>& traceLevels) : _traceLevels(traceLevels) { } void -IceGrid::AdminRouter::invokeOnTarget(const Ice::ObjectPrx& target, - const AMD_Object_ice_invokePtr& cb, - const pair<const Byte*, const Byte*>& inParams, - const Current& current) +IceGrid::AdminRouter::invokeOnTarget(const shared_ptr<Ice::ObjectPrx>& target, + const pair<const Ice::Byte*, const Ice::Byte*>& inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)>&& response, + function<void(exception_ptr)>&& exception, + const Ice::Current& current) { - assert(target != 0); - - // - // Call with AMI - // - Callback_Object_ice_invokePtr amiCb = newCallback_Object_ice_invoke( - new CallbackI(cb, target, current.operation, _traceLevels), &CallbackI::response, &CallbackI::exception); + assert(target); if(_traceLevels->admin > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->adminCat); out << "routing operation `" << current.operation << "' to `" << target->ice_toString() << "'"; } - target->begin_ice_invoke(current.operation, current.mode, inParams, current.ctx, amiCb); + + target->ice_invokeAsync(current.operation, current.mode, inParams, + [response, operation = current.operation, traceLevels = _traceLevels, target] + (bool ok, auto bytes) + { + if(traceLevels->admin > 0) + { + Ice::Trace out(traceLevels->logger, traceLevels->adminCat); + + out << "operation `" << operation << "' routed to `" + << Ice::identityToString(target->ice_getIdentity()) + << " -f " << target->ice_getFacet() << "' is returning "; + + if(ok) + { + out << "successfully"; + } + else + { + out << "a user exception"; + } + } + + response(move(ok), move(bytes)); + }, + [exception, operation = current.operation, traceLevels = _traceLevels, target] + (exception_ptr exptr) + { + if(traceLevels->admin > 0) + { + Ice::Trace out(traceLevels->logger, traceLevels->adminCat); + try + { + rethrow_exception(exptr); + } + catch(const std::exception& ex) + { + out << "operation `" << operation << "' routed to `" + << Ice::identityToString(target->ice_getIdentity()) + << " -f " << target->ice_getFacet() << "' failed with " << ex; + } + } + + exception(exptr); + }, + nullptr, + current.ctx); } diff --git a/cpp/src/IceGrid/AdminRouter.h b/cpp/src/IceGrid/AdminRouter.h index fcb988e1f06..e261d2e088f 100644 --- a/cpp/src/IceGrid/AdminRouter.h +++ b/cpp/src/IceGrid/AdminRouter.h @@ -18,14 +18,15 @@ class AdminRouter : public Ice::BlobjectArrayAsync { protected: - AdminRouter(const TraceLevelsPtr&); + AdminRouter(const std::shared_ptr<TraceLevels>&); - void invokeOnTarget(const Ice::ObjectPrx&, - const Ice::AMD_Object_ice_invokePtr&, + void invokeOnTarget(const std::shared_ptr<Ice::ObjectPrx>&, const std::pair<const Ice::Byte*, const Ice::Byte*>&, + std::function<void(bool, const std::pair<const Ice::Byte*, const Ice::Byte*>&)>&&, + std::function<void(std::exception_ptr)>&&, const Ice::Current&); - const TraceLevelsPtr _traceLevels; + const std::shared_ptr<TraceLevels> _traceLevels; }; } diff --git a/cpp/src/IceGrid/AdminSessionI.cpp b/cpp/src/IceGrid/AdminSessionI.cpp index 947298e7842..4120f274f28 100644 --- a/cpp/src/IceGrid/AdminSessionI.cpp +++ b/cpp/src/IceGrid/AdminSessionI.cpp @@ -8,6 +8,7 @@ #include <IceGrid/AdminSessionI.h> #include <IceGrid/AdminI.h> #include <IceGrid/Database.h> +#include <IceGrid/Internal.h> #include <IceSSL/Plugin.h> @@ -19,67 +20,45 @@ namespace class SubscriberForwarderI : public Ice::BlobjectArrayAsync { - class CallbackI: public IceUtil::Shared - { - public: - - virtual void - exception(const Ice::Exception& ex, const Ice::AMD_Object_ice_invokePtr& amdCB) - { - try - { - ex.ice_throw(); - } - catch(const Ice::Exception&) - { - // Throw ObjectNotExistException, the subscriber is unreachable - amdCB->ice_exception(Ice::ObjectNotExistException(__FILE__, __LINE__)); - } - } - - virtual void - response(bool ok, - const pair<const Ice::Byte*, const Ice::Byte*>& outP, - const Ice::AMD_Object_ice_invokePtr& amdCB) - { - amdCB->ice_response(ok, outP); - } - }; - public: - SubscriberForwarderI(const Ice::ObjectPrx& proxy) : - _proxy(proxy), - _callback(newCallback_Object_ice_invoke(new CallbackI(), &CallbackI::response, &CallbackI::exception)) + SubscriberForwarderI(const std::shared_ptr<Ice::ObjectPrx>& proxy) : + _proxy(proxy) { } - virtual void - ice_invoke_async(const Ice::AMD_Object_ice_invokePtr& amdCB, - const pair<const Ice::Byte*, const Ice::Byte*>& inParams, - const Ice::Current& current) + void + ice_invokeAsync(pair<const Ice::Byte*, const Ice::Byte*> inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, const Ice::Current& current) override { - _proxy->begin_ice_invoke(current.operation, current.mode, inParams, current.ctx, _callback, amdCB); + _proxy->ice_invokeAsync(current.operation, current.mode, inParams, + move(response), + [exception = move(exception)] (exception_ptr) + { + // Throw ObjectNotExistException, the subscriber is unreachable + exception(make_exception_ptr(Ice::ObjectNotExistException(__FILE__, __LINE__))); + }, + nullptr, current.ctx); } private: - const Ice::ObjectPrx _proxy; - const Ice::Callback_Object_ice_invokePtr _callback; + const shared_ptr<Ice::ObjectPrx> _proxy; }; } -FileIteratorI::FileIteratorI(const AdminSessionIPtr& session, - const FileReaderPrx& reader, +FileIteratorI::FileIteratorI(const shared_ptr<AdminSessionI>& session, + const shared_ptr<FileReaderPrx>& reader, const string& filename, - Ice::Long offset, - int messageSizeMax) : + long long offset, + int messageMaxSize) : _session(session), _reader(reader), _filename(filename), _offset(offset), - _messageSizeMax(messageSizeMax - 256) // Room for the header + _messageMaxSize(messageMaxSize - 256) // Room for the header { } @@ -88,13 +67,11 @@ FileIteratorI::read(int size, Ice::StringSeq& lines, const Ice::Current&) { try { - return _reader->read(_filename, _offset, size > _messageSizeMax ? _messageSizeMax : size, _offset, lines); + return _reader->read(_filename, _offset, size > _messageMaxSize ? _messageMaxSize : size, _offset, lines); } - catch(const Ice::LocalException& ex) + catch(const std::exception& ex) { - ostringstream os; - os << ex; - throw FileNotAvailableException(os.str()); + throw FileNotAvailableException(ex.what()); } } @@ -104,7 +81,8 @@ FileIteratorI::destroy(const Ice::Current& current) _session->removeFileIterator(current.id, current); } -AdminSessionI::AdminSessionI(const string& id, const DatabasePtr& db, int timeout, const RegistryIPtr& registry) : +AdminSessionI::AdminSessionI(const string& id, const shared_ptr<Database>& db, chrono::seconds timeout, + const shared_ptr<RegistryI>& registry) : BaseSessionI(id, "admin", db), _timeout(timeout), _replicaName(registry->getName()), @@ -112,12 +90,9 @@ AdminSessionI::AdminSessionI(const string& id, const DatabasePtr& db, int timeou { } -AdminSessionI::~AdminSessionI() -{ -} - -Ice::ObjectPrx -AdminSessionI::_register(const SessionServantManagerPtr& servantManager, const Ice::ConnectionPtr& con) +shared_ptr<Ice::ObjectPrx> +AdminSessionI::_register(const shared_ptr<SessionServantManager>& servantManager, + const shared_ptr<Ice::Connection>& con) { // // This is supposed to be called after creation only, no need to synchronize. @@ -137,117 +112,123 @@ AdminSessionI::_register(const SessionServantManagerPtr& servantManager, const I _adminCallbackTemplate = _registry->createAdminCallbackProxy(templateId); } - Ice::ObjectPrx session = _servantManager->addSession(this, con, category); + auto self = static_pointer_cast<AdminSessionI>(shared_from_this()); + + auto session = _servantManager->addSession(self, con, category); - _admin = AdminPrx::uncheckedCast(_servantManager->add(new AdminI(_database, _registry, this), this)); + _admin = Ice::uncheckedCast<AdminPrx>(_servantManager->add(make_shared<AdminI>(_database, _registry, self), self)); return session; } -AdminPrx +shared_ptr<AdminPrx> AdminSessionI::getAdmin(const Ice::Current&) const { return _admin; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> AdminSessionI::getAdminCallbackTemplate(const Ice::Current&) const { return _adminCallbackTemplate; } void -AdminSessionI::setObservers(const RegistryObserverPrx& registryObserver, - const NodeObserverPrx& nodeObserver, - const ApplicationObserverPrx& appObserver, - const AdapterObserverPrx& adapterObserver, - const ObjectObserverPrx& objectObserver, +AdminSessionI::setObservers(shared_ptr<RegistryObserverPrx> registryObserver, + shared_ptr<NodeObserverPrx> nodeObserver, + shared_ptr<ApplicationObserverPrx> appObserver, + shared_ptr<AdapterObserverPrx> adapterObserver, + shared_ptr<ObjectObserverPrx> objectObserver, const Ice::Current& current) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, "", ""); } - const int t = _timeout * 1000; - const Ice::LocatorPrx l = _registry->getLocator(); + const auto t = secondsToInt(_timeout); + assert(t != 0); + const auto l = _registry->getLocator(); if(registryObserver) { - setupObserverSubscription(RegistryObserverTopicName, + setupObserverSubscription(TopicName::RegistryObserver, addForwarder(registryObserver->ice_timeout(t)->ice_locator(l))); } else { - setupObserverSubscription(RegistryObserverTopicName, Ice::ObjectPrx()); + setupObserverSubscription(TopicName::RegistryObserver, nullptr); } if(nodeObserver) { - setupObserverSubscription(NodeObserverTopicName, + setupObserverSubscription(TopicName::NodeObserver, addForwarder(nodeObserver->ice_timeout(t)->ice_locator(l))); } else { - setupObserverSubscription(NodeObserverTopicName, Ice::ObjectPrx()); + setupObserverSubscription(TopicName::NodeObserver, nullptr); } if(appObserver) { - setupObserverSubscription(ApplicationObserverTopicName, + setupObserverSubscription(TopicName::ApplicationObserver, addForwarder(appObserver->ice_timeout(t)->ice_locator(l))); } else { - setupObserverSubscription(ApplicationObserverTopicName, Ice::ObjectPrx()); + setupObserverSubscription(TopicName::ApplicationObserver, nullptr); } if(adapterObserver) { - setupObserverSubscription(AdapterObserverTopicName, + setupObserverSubscription(TopicName::AdapterObserver, addForwarder(adapterObserver->ice_timeout(t)->ice_locator(l))); } else { - setupObserverSubscription(AdapterObserverTopicName, Ice::ObjectPrx()); + setupObserverSubscription(TopicName::AdapterObserver, nullptr); } if(objectObserver) { - setupObserverSubscription(ObjectObserverTopicName, + setupObserverSubscription(TopicName::ObjectObserver, addForwarder(objectObserver->ice_timeout(t)->ice_locator(l))); } else { - setupObserverSubscription(ObjectObserverTopicName, Ice::ObjectPrx()); + setupObserverSubscription(TopicName::ObjectObserver, nullptr); } } void -AdminSessionI::setObserversByIdentity(const Ice::Identity& registryObserver, - const Ice::Identity& nodeObserver, - const Ice::Identity& appObserver, - const Ice::Identity& adapterObserver, - const Ice::Identity& objectObserver, +AdminSessionI::setObserversByIdentity(Ice::Identity registryObserver, + Ice::Identity nodeObserver, + Ice::Identity appObserver, + Ice::Identity adapterObserver, + Ice::Identity objectObserver, const Ice::Current& current) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, "", ""); } - setupObserverSubscription(RegistryObserverTopicName, addForwarder(registryObserver, current), true); - setupObserverSubscription(NodeObserverTopicName, addForwarder(nodeObserver, current), true); - setupObserverSubscription(ApplicationObserverTopicName, addForwarder(appObserver, current), true); - setupObserverSubscription(AdapterObserverTopicName, addForwarder(adapterObserver, current), true); - setupObserverSubscription(ObjectObserverTopicName, addForwarder(objectObserver, current), true); + setupObserverSubscription(TopicName::RegistryObserver, addForwarder(registryObserver, current), true); + setupObserverSubscription(TopicName::NodeObserver, addForwarder(nodeObserver, current), true); + setupObserverSubscription(TopicName::ApplicationObserver, addForwarder(appObserver, current), true); + setupObserverSubscription(TopicName::AdapterObserver, addForwarder(adapterObserver, current), true); + setupObserverSubscription(TopicName::ObjectObserver, addForwarder(objectObserver, current), true); } int AdminSessionI::startUpdate(const Ice::Current& current) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, "", ""); @@ -260,7 +241,8 @@ AdminSessionI::startUpdate(const Ice::Current& current) void AdminSessionI::finishUpdate(const Ice::Current& current) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, "", ""); @@ -275,12 +257,12 @@ AdminSessionI::getReplicaName(const Ice::Current&) const return _replicaName; } -FileIteratorPrx -AdminSessionI::openServerLog(const string& id, const string& path, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openServerLog(string id, string path, int nLines, const Ice::Current& current) { try { - return addFileIterator(_database->getServer(id)->getProxy(false, 5), "#" + path, nLines, current); + return addFileIterator(_database->getServer(move(id))->getProxy(false, 5s), "#" + move(path), nLines, current); } catch(const SynchronizationException&) { @@ -288,12 +270,12 @@ AdminSessionI::openServerLog(const string& id, const string& path, int nLines, c } } -FileIteratorPrx -AdminSessionI::openServerStdOut(const string& id, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openServerStdOut(string id, int nLines, const Ice::Current& current) { try { - return addFileIterator(_database->getServer(id)->getProxy(false, 5), "stdout", nLines, current); + return addFileIterator(_database->getServer(move(id))->getProxy(false, 5s), "stdout", nLines, current); } catch(const SynchronizationException&) { @@ -301,12 +283,12 @@ AdminSessionI::openServerStdOut(const string& id, int nLines, const Ice::Current } } -FileIteratorPrx -AdminSessionI::openServerStdErr(const string& id, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openServerStdErr(string id, int nLines, const Ice::Current& current) { try { - return addFileIterator(_database->getServer(id)->getProxy(false, 5), "stderr", nLines, current); + return addFileIterator(_database->getServer(move(id))->getProxy(false, 5s), "stderr", nLines, current); } catch(const SynchronizationException&) { @@ -314,44 +296,44 @@ AdminSessionI::openServerStdErr(const string& id, int nLines, const Ice::Current } } -FileIteratorPrx -AdminSessionI::openNodeStdOut(const string& name, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openNodeStdOut(string name, int nLines, const Ice::Current& current) { - return addFileIterator(_database->getNode(name)->getProxy(), "stdout", nLines, current); + return addFileIterator(_database->getNode(move(name))->getProxy(), "stdout", nLines, current); } -FileIteratorPrx -AdminSessionI::openNodeStdErr(const string& name, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openNodeStdErr(string name, int nLines, const Ice::Current& current) { - return addFileIterator(_database->getNode(name)->getProxy(), "stderr", nLines, current); + return addFileIterator(_database->getNode(move(name))->getProxy(), "stderr", nLines, current); } -FileIteratorPrx -AdminSessionI::openRegistryStdOut(const string& name, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openRegistryStdOut(string name, int nLines, const Ice::Current& current) { - FileReaderPrx reader; + shared_ptr<FileReaderPrx> reader; if(name == _replicaName) { reader = _database->getReplicaCache().getInternalRegistry(); } else { - reader = _database->getReplica(name)->getProxy(); + reader = _database->getReplica(move(name))->getProxy(); } return addFileIterator(reader, "stdout", nLines, current); } -FileIteratorPrx -AdminSessionI::openRegistryStdErr(const string& name, int nLines, const Ice::Current& current) +shared_ptr<FileIteratorPrx> +AdminSessionI::openRegistryStdErr(string name, int nLines, const Ice::Current& current) { - FileReaderPrx reader; + shared_ptr<FileReaderPrx> reader; if(name == _replicaName) { reader = _database->getReplicaCache().getInternalRegistry(); } else { - reader = _database->getReplica(name)->getProxy(); + reader = _database->getReplica(move(name))->getProxy(); } return addFileIterator(reader, "stderr", nLines, current); } @@ -363,7 +345,7 @@ AdminSessionI::destroy(const Ice::Current&) } void -AdminSessionI::setupObserverSubscription(TopicName name, const Ice::ObjectPrx& observer, bool forwarder) +AdminSessionI::setupObserverSubscription(TopicName name, const shared_ptr<Ice::ObjectPrx>& observer, bool forwarder) { if(_observers.find(name) != _observers.end() && _observers[name].first != observer) { @@ -390,27 +372,28 @@ AdminSessionI::setupObserverSubscription(TopicName name, const Ice::ObjectPrx& o } } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> AdminSessionI::addForwarder(const Ice::Identity& id, const Ice::Current& current) { if(id.name.empty()) { - return Ice::ObjectPrx(); + return nullptr; } return addForwarder(current.con->createProxy(id)->ice_encodingVersion(current.encoding)); } -Ice::ObjectPrx -AdminSessionI::addForwarder(const Ice::ObjectPrx& prx) +shared_ptr<Ice::ObjectPrx> +AdminSessionI::addForwarder(const shared_ptr<Ice::ObjectPrx>& prx) { - return _registry->getRegistryAdapter()->addWithUUID(new SubscriberForwarderI(prx)); + return _registry->getRegistryAdapter()->addWithUUID(make_shared<SubscriberForwarderI>(prx)); } -FileIteratorPrx -AdminSessionI::addFileIterator(const FileReaderPrx& reader, const string& filename, int nLines, +shared_ptr<FileIteratorPrx> +AdminSessionI::addFileIterator(const shared_ptr<FileReaderPrx>& reader, const string& filename, int nLines, const Ice::Current& current) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, "", ""); @@ -420,29 +403,29 @@ AdminSessionI::addFileIterator(const FileReaderPrx& reader, const string& filena // Always call getOffsetFromEnd even if nLines < 0. This allows to // throw right away if the file doesn't exit. // - Ice::Long offset; + long long offset; try { offset = reader->getOffsetFromEnd(filename, nLines); } - catch(const Ice::LocalException& ex) + catch(const std::exception& ex) { - ostringstream os; - os << ex; - throw FileNotAvailableException(os.str()); + throw FileNotAvailableException(ex.what()); } - Ice::PropertiesPtr properties = reader->ice_getCommunicator()->getProperties(); - int messageSizeMax = properties->getPropertyAsIntWithDefault("Ice.MessageSizeMax", 1024) * 1024; + auto properties = reader->ice_getCommunicator()->getProperties(); + int messageMaxSize = properties->getPropertyAsIntWithDefault("Ice.MessageMaxSize", 1024) * 1024; - Ice::ObjectPrx obj = _servantManager->add(new FileIteratorI(this, reader, filename, offset, messageSizeMax), this); - return FileIteratorPrx::uncheckedCast(obj); + auto self = static_pointer_cast<AdminSessionI>(shared_from_this()); + auto obj = _servantManager->add(make_shared<FileIteratorI>(self, reader, filename, offset, messageMaxSize), self); + return Ice::uncheckedCast<FileIteratorPrx>(obj); } void AdminSessionI::removeFileIterator(const Ice::Identity& id, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); + _servantManager->remove(id); } @@ -451,7 +434,7 @@ AdminSessionI::destroyImpl(bool shutdown) { BaseSessionI::destroyImpl(shutdown); - _servantManager->removeSession(this); + _servantManager->removeSession(shared_from_this()); try { @@ -466,18 +449,18 @@ AdminSessionI::destroyImpl(bool shutdown) // // Unsubscribe from the topics. // - setupObserverSubscription(RegistryObserverTopicName, 0); - setupObserverSubscription(NodeObserverTopicName, 0); - setupObserverSubscription(ApplicationObserverTopicName, 0); - setupObserverSubscription(AdapterObserverTopicName, 0); - setupObserverSubscription(ObjectObserverTopicName, 0); + setupObserverSubscription(TopicName::RegistryObserver, nullptr); + setupObserverSubscription(TopicName::NodeObserver, nullptr); + setupObserverSubscription(TopicName::ApplicationObserver, nullptr); + setupObserverSubscription(TopicName::AdapterObserver, nullptr); + setupObserverSubscription(TopicName::ObjectObserver, nullptr); } } -AdminSessionFactory::AdminSessionFactory(const SessionServantManagerPtr& servantManager, - const DatabasePtr& database, - const ReapThreadPtr& reaper, - const RegistryIPtr& registry) : +AdminSessionFactory::AdminSessionFactory(const shared_ptr<SessionServantManager>& servantManager, + const shared_ptr<Database>& database, + const shared_ptr<ReapThread>& reaper, + const shared_ptr<RegistryI>& registry) : _servantManager(servantManager), _database(database), _timeout(registry->getSessionTimeout(Ice::emptyCurrent)), @@ -487,35 +470,29 @@ AdminSessionFactory::AdminSessionFactory(const SessionServantManagerPtr& servant { if(_servantManager) // Not set if Glacier2 session manager adapter not enabled { - Ice::PropertiesPtr props = database->getCommunicator()->getProperties(); + auto props = database->getCommunicator()->getProperties(); const_cast<bool&>(_filters) = props->getPropertyAsIntWithDefault("IceGrid.Registry.AdminSessionFilters", 0) > 0; } } -Glacier2::SessionPrx -AdminSessionFactory::createGlacier2Session(const string& sessionId, const Glacier2::SessionControlPrx& ctl) +shared_ptr<Glacier2::SessionPrx> +AdminSessionFactory::createGlacier2Session(const string& sessionId, const shared_ptr<Glacier2::SessionControlPrx>& ctl) { assert(_servantManager); - AdminSessionIPtr session = createSessionServant(sessionId); - Ice::ObjectPrx proxy = session->_register(_servantManager, 0); + auto session = createSessionServant(sessionId); + auto proxy = session->_register(_servantManager, nullptr); - int timeout = 0; + chrono::seconds timeout = 0s; if(ctl) { try { if(_filters) { - Ice::IdentitySeq ids; - Ice::Identity queryId; - queryId.category = _database->getInstanceName(); - queryId.name = "Query"; - ids.push_back(queryId); - - _servantManager->setSessionControl(session, ctl, ids); + _servantManager->setSessionControl(session, ctl, { {"Query", _database->getInstanceName() } }); } - timeout = ctl->getSessionTimeout(); + timeout = chrono::seconds(ctl->getSessionTimeout()); } catch(const Ice::LocalException& e) { @@ -528,39 +505,40 @@ AdminSessionFactory::createGlacier2Session(const string& sessionId, const Glacie } } - _reaper->add(new SessionReapable<AdminSessionI>(_database->getTraceLevels()->logger, session), timeout); - return Glacier2::SessionPrx::uncheckedCast(proxy); + _reaper->add(make_shared<SessionReapable<AdminSessionI>>(_database->getTraceLevels()->logger, session), timeout); + return Ice::uncheckedCast<Glacier2::SessionPrx>(proxy); } -AdminSessionIPtr +shared_ptr<AdminSessionI> AdminSessionFactory::createSessionServant(const string& id) { - return new AdminSessionI(id, _database, _timeout, _registry); + return make_shared<AdminSessionI>(id, _database, _timeout, _registry); } -const TraceLevelsPtr& +const shared_ptr<TraceLevels>& AdminSessionFactory::getTraceLevels() const { return _database->getTraceLevels(); } -AdminSessionManagerI::AdminSessionManagerI(const AdminSessionFactoryPtr& factory) : _factory(factory) +AdminSessionManagerI::AdminSessionManagerI(const shared_ptr<AdminSessionFactory>& factory) : _factory(factory) { } -Glacier2::SessionPrx -AdminSessionManagerI::create(const string& userId, const Glacier2::SessionControlPrx& ctl, const Ice::Current&) +shared_ptr<Glacier2::SessionPrx> +AdminSessionManagerI::create(string userId, shared_ptr<Glacier2::SessionControlPrx> ctl, + const Ice::Current&) { - return _factory->createGlacier2Session(userId, ctl); + return _factory->createGlacier2Session(move(userId), move(ctl)); } -AdminSSLSessionManagerI::AdminSSLSessionManagerI(const AdminSessionFactoryPtr& factory) : _factory(factory) +AdminSSLSessionManagerI::AdminSSLSessionManagerI(const shared_ptr<AdminSessionFactory>& factory) : _factory(factory) { } -Glacier2::SessionPrx -AdminSSLSessionManagerI::create(const Glacier2::SSLInfo& info, - const Glacier2::SessionControlPrx& ctl, +shared_ptr<Glacier2::SessionPrx> +AdminSSLSessionManagerI::create(Glacier2::SSLInfo info, + shared_ptr<Glacier2::SessionControlPrx> ctl, const Ice::Current&) { string userDN; @@ -568,7 +546,7 @@ AdminSSLSessionManagerI::create(const Glacier2::SSLInfo& info, { try { - IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); + auto cert = IceSSL::Certificate::decode(info.certs[0]); userDN = cert->getSubjectDN(); } catch(const Ice::Exception& ex) @@ -580,5 +558,5 @@ AdminSSLSessionManagerI::create(const Glacier2::SSLInfo& info, } } - return _factory->createGlacier2Session(userDN, ctl); + return _factory->createGlacier2Session(move(userDN), move(ctl)); } diff --git a/cpp/src/IceGrid/AdminSessionI.h b/cpp/src/IceGrid/AdminSessionI.h index ee1d9c909d8..8ed7ab9e5b8 100644 --- a/cpp/src/IceGrid/AdminSessionI.h +++ b/cpp/src/IceGrid/AdminSessionI.h @@ -14,132 +14,135 @@ namespace IceGrid { class RegistryI; -typedef IceUtil::Handle<RegistryI> RegistryIPtr; - class FileIteratorI; -typedef IceUtil::Handle<FileIteratorI> FileIteratorIPtr; class AdminSessionI : public BaseSessionI, public AdminSession { public: - AdminSessionI(const std::string&, const DatabasePtr&, int, const RegistryIPtr&); - virtual ~AdminSessionI(); + AdminSessionI(const std::string&, const std::shared_ptr<Database>&, + std::chrono::seconds, const std::shared_ptr<RegistryI>&); - Ice::ObjectPrx _register(const SessionServantManagerPtr&, const Ice::ConnectionPtr&); + std::shared_ptr<Ice::ObjectPrx> _register(const std::shared_ptr<SessionServantManager>&, + const std::shared_ptr<Ice::Connection>&); - virtual void keepAlive(const Ice::Current& current) { BaseSessionI::keepAlive(current); } + void keepAlive(const Ice::Current& current) override { BaseSessionI::keepAlive(current); } - virtual AdminPrx getAdmin(const Ice::Current&) const; - virtual Ice::ObjectPrx getAdminCallbackTemplate(const Ice::Current&) const; + std::shared_ptr<AdminPrx> getAdmin(const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> getAdminCallbackTemplate(const Ice::Current&) const override; - virtual void setObservers(const RegistryObserverPrx&, const NodeObserverPrx&, const ApplicationObserverPrx&, - const AdapterObserverPrx&, const ObjectObserverPrx&, const Ice::Current&); + void setObservers(std::shared_ptr<RegistryObserverPrx>, std::shared_ptr<NodeObserverPrx>, + std::shared_ptr<ApplicationObserverPrx>, std::shared_ptr<AdapterObserverPrx>, + std::shared_ptr<ObjectObserverPrx>, const Ice::Current&) override; - virtual void setObserversByIdentity(const Ice::Identity&, const Ice::Identity&, const Ice::Identity&, - const Ice::Identity&, const Ice::Identity&, const Ice::Current&); + void setObserversByIdentity(Ice::Identity, Ice::Identity, Ice::Identity, Ice::Identity, Ice::Identity, + const Ice::Current&) override; - virtual int startUpdate(const Ice::Current&); - virtual void finishUpdate(const Ice::Current&); + int startUpdate(const Ice::Current&) override; + void finishUpdate(const Ice::Current&) override; - virtual std::string getReplicaName(const Ice::Current&) const; + std::string getReplicaName(const Ice::Current&) const override; - virtual FileIteratorPrx openServerLog(const std::string&, const std::string&, int, const Ice::Current&); - virtual FileIteratorPrx openServerStdOut(const std::string&, int, const Ice::Current&); - virtual FileIteratorPrx openServerStdErr(const std::string&, int, const Ice::Current&); + std::shared_ptr<FileIteratorPrx> openServerLog(std::string, std::string, int, const Ice::Current&) override; + std::shared_ptr<FileIteratorPrx> openServerStdOut(std::string, int, const Ice::Current&) override; + std::shared_ptr<FileIteratorPrx> openServerStdErr(std::string, int, const Ice::Current&) override; - virtual FileIteratorPrx openNodeStdOut(const std::string&, int, const Ice::Current&); - virtual FileIteratorPrx openNodeStdErr(const std::string&, int, const Ice::Current&); + std::shared_ptr<FileIteratorPrx> openNodeStdOut(std::string, int, const Ice::Current&) override; + std::shared_ptr<FileIteratorPrx> openNodeStdErr(std::string, int, const Ice::Current&) override; - virtual FileIteratorPrx openRegistryStdOut(const std::string&, int, const Ice::Current&); - virtual FileIteratorPrx openRegistryStdErr(const std::string&, int, const Ice::Current&); + std::shared_ptr<FileIteratorPrx> openRegistryStdOut(std::string, int, const Ice::Current&) override; + std::shared_ptr<FileIteratorPrx> openRegistryStdErr(std::string, int, const Ice::Current&) override; - virtual void destroy(const Ice::Current&); + void destroy(const Ice::Current&) override; void removeFileIterator(const Ice::Identity&, const Ice::Current&); private: - void setupObserverSubscription(TopicName, const Ice::ObjectPrx&, bool = false); - Ice::ObjectPrx addForwarder(const Ice::Identity&, const Ice::Current&); - Ice::ObjectPrx addForwarder(const Ice::ObjectPrx&); - FileIteratorPrx addFileIterator(const FileReaderPrx&, const std::string&, int, const Ice::Current&); + void setupObserverSubscription(TopicName, const std::shared_ptr<Ice::ObjectPrx>&, bool = false); + std::shared_ptr<Ice::ObjectPrx> addForwarder(const Ice::Identity&, const Ice::Current&); + std::shared_ptr<Ice::ObjectPrx> addForwarder(const std::shared_ptr<Ice::ObjectPrx>&); + std::shared_ptr<FileIteratorPrx> addFileIterator(const std::shared_ptr<FileReaderPrx>&, const std::string&, int, + const Ice::Current&); - virtual void destroyImpl(bool); + void destroyImpl(bool) override; - const int _timeout; + const std::chrono::seconds _timeout; const std::string _replicaName; - AdminPrx _admin; - std::map<TopicName, std::pair<Ice::ObjectPrx, bool> > _observers; - RegistryIPtr _registry; - Ice::ObjectPrx _adminCallbackTemplate; + std::shared_ptr<AdminPrx> _admin; + std::map<TopicName, std::pair<std::shared_ptr<Ice::ObjectPrx>, bool>> _observers; + std::shared_ptr<RegistryI> _registry; + std::shared_ptr<Ice::ObjectPrx> _adminCallbackTemplate; }; -typedef IceUtil::Handle<AdminSessionI> AdminSessionIPtr; -class AdminSessionFactory : public virtual IceUtil::Shared +class AdminSessionFactory { public: - AdminSessionFactory(const SessionServantManagerPtr&, const DatabasePtr&, const ReapThreadPtr&, const RegistryIPtr&); + AdminSessionFactory(const std::shared_ptr<SessionServantManager>&, const std::shared_ptr<Database>&, + const std::shared_ptr<ReapThread>&, const std::shared_ptr<RegistryI>&); - Glacier2::SessionPrx createGlacier2Session(const std::string&, const Glacier2::SessionControlPrx&); - AdminSessionIPtr createSessionServant(const std::string&); + std::shared_ptr<Glacier2::SessionPrx> createGlacier2Session(const std::string&, + const std::shared_ptr<Glacier2::SessionControlPrx>&); + std::shared_ptr<AdminSessionI> createSessionServant(const std::string&); - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr<TraceLevels>& getTraceLevels() const; private: - const SessionServantManagerPtr _servantManager; - const DatabasePtr _database; - const int _timeout; - const ReapThreadPtr _reaper; - const RegistryIPtr _registry; + const std::shared_ptr<SessionServantManager> _servantManager; + const std::shared_ptr<Database> _database; + const std::chrono::seconds _timeout; + const std::shared_ptr<ReapThread> _reaper; + const std::shared_ptr<RegistryI> _registry; const bool _filters; }; -typedef IceUtil::Handle<AdminSessionFactory> AdminSessionFactoryPtr; -class AdminSessionManagerI : public virtual Glacier2::SessionManager +class AdminSessionManagerI : public Glacier2::SessionManager { public: - AdminSessionManagerI(const AdminSessionFactoryPtr&); + AdminSessionManagerI(const std::shared_ptr<AdminSessionFactory>&); - virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); + std::shared_ptr<Glacier2::SessionPrx> create(std::string, std::shared_ptr<Glacier2::SessionControlPrx>, + const Ice::Current&) override; private: - const AdminSessionFactoryPtr _factory; + const std::shared_ptr<AdminSessionFactory> _factory; }; -class AdminSSLSessionManagerI : public virtual Glacier2::SSLSessionManager +class AdminSSLSessionManagerI : public Glacier2::SSLSessionManager { public: - AdminSSLSessionManagerI(const AdminSessionFactoryPtr&); - virtual Glacier2::SessionPrx create(const Glacier2::SSLInfo&, const Glacier2::SessionControlPrx&, - const Ice::Current&); + AdminSSLSessionManagerI(const std::shared_ptr<AdminSessionFactory>&); + + std::shared_ptr<Glacier2::SessionPrx> create(Glacier2::SSLInfo, std::shared_ptr<Glacier2::SessionControlPrx>, + const Ice::Current&) override; private: - const AdminSessionFactoryPtr _factory; + const std::shared_ptr<AdminSessionFactory> _factory; }; class FileIteratorI : public FileIterator { public: - FileIteratorI(const AdminSessionIPtr&, const FileReaderPrx&, const std::string&, Ice::Long, int); + FileIteratorI(const std::shared_ptr<AdminSessionI>&, const std::shared_ptr<FileReaderPrx>&, const std::string&, + long long, int); virtual bool read(int, Ice::StringSeq&, const Ice::Current&); virtual void destroy(const Ice::Current&); private: - const AdminSessionIPtr _session; - const FileReaderPrx _reader; + const std::shared_ptr<AdminSessionI> _session; + const std::shared_ptr<FileReaderPrx> _reader; const std::string _filename; - Ice::Long _offset; - const int _messageSizeMax; + long long _offset; + const int _messageMaxSize; }; }; diff --git a/cpp/src/IceGrid/Allocatable.cpp b/cpp/src/IceGrid/Allocatable.cpp index 35c1ad5b823..10889a1a871 100644 --- a/cpp/src/IceGrid/Allocatable.cpp +++ b/cpp/src/IceGrid/Allocatable.cpp @@ -8,26 +8,22 @@ using namespace std; using namespace IceGrid; -AllocationRequest::~AllocationRequest() -{ -} - bool AllocationRequest::pending() { - Lock sync(*this); + lock_guard lock(_mutex); assert(_state == Initial); if(_timeout == 0) { _state = Canceled; - canceled(AllocationTimeoutException()); + canceled(make_exception_ptr(AllocationTimeoutException())); return false; } - else if(!_session->addAllocationRequest(this)) + else if(!_session->addAllocationRequest(shared_from_this())) { _state = Canceled; - canceled(AllocationException("session destroyed")); + canceled(make_exception_ptr(AllocationException("session destroyed"))); return false; } @@ -35,7 +31,7 @@ AllocationRequest::pending() { try { - _session->getTimer()->schedule(this, IceUtil::Time::milliSeconds(_timeout)); + _session->getTimer()->schedule(shared_from_this(), IceUtil::Time::milliSeconds(_timeout)); } catch(const IceUtil::Exception&) { @@ -47,9 +43,9 @@ AllocationRequest::pending() } bool -AllocationRequest::allocate(const AllocatablePtr& /*allocatable*/, const SessionIPtr& session) +AllocationRequest::allocate(const shared_ptr<Allocatable>&, const shared_ptr<SessionI>& session) { - Lock sync(*this); + lock_guard lock(_mutex); switch(_state) { case Initial: @@ -59,9 +55,9 @@ AllocationRequest::allocate(const AllocatablePtr& /*allocatable*/, const Session case Pending: if(_timeout > 0) { - _session->getTimer()->cancel(this); + _session->getTimer()->cancel(shared_from_this()); } - _session->removeAllocationRequest(this); + _session->removeAllocationRequest(shared_from_this()); break; case Allocated: assert(false); @@ -74,7 +70,7 @@ AllocationRequest::allocate(const AllocatablePtr& /*allocatable*/, const Session if(_session == session) { _state = Canceled; - canceled(AllocationException("already allocated by the session")); + canceled(make_exception_ptr(AllocationException("already allocated by the session"))); return false; } else @@ -85,9 +81,9 @@ AllocationRequest::allocate(const AllocatablePtr& /*allocatable*/, const Session } void -AllocationRequest::cancel(const Ice::UserException& ex) +AllocationRequest::cancel(exception_ptr ex) { - Lock sync(*this); + lock_guard lock(_mutex); switch(_state) { case Initial: @@ -98,9 +94,9 @@ AllocationRequest::cancel(const Ice::UserException& ex) case Pending: if(_timeout > 0) { - _session->getTimer()->cancel(this); + _session->getTimer()->cancel(shared_from_this()); } - _session->removeAllocationRequest(this); + _session->removeAllocationRequest(shared_from_this()); break; } @@ -111,7 +107,7 @@ AllocationRequest::cancel(const Ice::UserException& ex) void AllocationRequest::runTimerTask() // TimerTask::runTimerTask() method implementation { - Lock sync(*this); + lock_guard lock(_mutex); switch(_state) { case Initial: @@ -120,18 +116,18 @@ AllocationRequest::runTimerTask() // TimerTask::runTimerTask() method implementa case Allocated: return; case Pending: - _session->removeAllocationRequest(this); + _session->removeAllocationRequest(shared_from_this()); break; } _state = Canceled; - canceled(AllocationTimeoutException()); + canceled(make_exception_ptr(AllocationTimeoutException())); } bool AllocationRequest::isCanceled() const { - Lock sync(*this); + lock_guard lock(_mutex); return _state == Canceled; } @@ -141,37 +137,22 @@ AllocationRequest::operator<(const AllocationRequest& r) const return this < &r; } -AllocationRequest::AllocationRequest(const SessionIPtr& session) : +AllocationRequest::AllocationRequest(const shared_ptr<SessionI>& session) : _session(session), _timeout(_session->getAllocationTimeout()), // The session timeout can be updated so we need to cache it here. _state(Initial) { } -Allocatable::Allocatable(bool allocatable, const AllocatablePtr& parent) : +Allocatable::Allocatable(bool allocatable, const shared_ptr<Allocatable>& parent) : _allocatable(allocatable || (parent && parent->isAllocatable())), + _parent((parent && parent->isAllocatable()) ? parent : nullptr), _count(0), _releasing(false) { - // - // COMPILERFIX: the constructor initializaton: - // - // _parent((parent && parent->isAllocatable()) ? parent : AllocatablePtr()) - // - // doesn't work on HP-UX (aCC: HP ANSI C++ B3910B A.03.56). It - // results in a SEGFAULT at runtime. - // - if(parent && parent->isAllocatable()) - { - const_cast<AllocatablePtr&>(_parent) = parent; - } assert(!_parent || _parent->isAllocatable()); // Parent is only set if it's allocatable. } -Allocatable::~Allocatable() -{ -} - void Allocatable::checkAllocatable() { @@ -182,7 +163,7 @@ Allocatable::checkAllocatable() } bool -Allocatable::allocate(const AllocationRequestPtr& request, bool fromRelease) +Allocatable::allocate(const shared_ptr<AllocationRequest>& request, bool fromRelease) { try { @@ -195,7 +176,7 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool fromRelease) } bool -Allocatable::tryAllocate(const AllocationRequestPtr& request, bool fromRelease) +Allocatable::tryAllocate(const shared_ptr<AllocationRequest>& request, bool fromRelease) { try { @@ -208,18 +189,15 @@ Allocatable::tryAllocate(const AllocationRequestPtr& request, bool fromRelease) } void -Allocatable::release(const SessionIPtr& session, bool fromRelease) +Allocatable::release(const shared_ptr<SessionI>& session, bool fromRelease) { bool isReleased = false; bool hasRequests = false; { - Lock sync(*this); + unique_lock lock(_mutex); if(!fromRelease) { - while(_releasing) - { - wait(); - } + _condVar.wait(lock, [this] { return !_releasing; }); assert(!_releasing); } @@ -260,17 +238,17 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) { while(true) { - AllocationRequestPtr request; - AllocatablePtr allocatable; + shared_ptr<AllocationRequest> request; + shared_ptr<Allocatable> allocatable; { - Lock sync(*this); + lock_guard lock(_mutex); allocatable = dequeueAllocationAttempt(request); if(!allocatable) { assert(_requests.empty()); assert(_count == 0); _releasing = false; - notifyAll(); + _condVar.notify_all(); return; } } @@ -287,7 +265,7 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) while(true) { { - Lock sync(*this); + lock_guard lock(_mutex); assert(_count); allocatable = 0; @@ -297,7 +275,7 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) // Check if there's other requests from the session // waiting to allocate this allocatable. // - list<pair<AllocatablePtr, AllocationRequestPtr> >::iterator p = _requests.begin(); + auto p = _requests.begin(); while(p != _requests.end()) { if(p->second && p->second->getSession() == _session) @@ -312,7 +290,7 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) if(!allocatable) { _releasing = false; - notifyAll(); + _condVar.notify_all(); return; // We're done, the allocatable was released (but is allocated again)! } } @@ -322,16 +300,16 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) assert(allocatable && request); allocatable->allocate(request, true); } - catch(const Ice::UserException& ex) + catch(const Ice::UserException&) { - request->cancel(ex); + request->cancel(current_exception()); } } } } - catch(const Ice::UserException& ex) + catch(const Ice::UserException&) { - request->cancel(ex); + request->cancel(current_exception()); } } } @@ -342,10 +320,10 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) } } -SessionIPtr +shared_ptr<SessionI> Allocatable::getSession() const { - Lock sync(*this); + lock_guard lock(_mutex); return _session; } @@ -356,8 +334,8 @@ Allocatable::operator<(const Allocatable& r) const } void -Allocatable::queueAllocationAttempt(const AllocatablePtr& allocatable, - const AllocationRequestPtr& request, +Allocatable::queueAllocationAttempt(const shared_ptr<Allocatable>& allocatable, + const shared_ptr<AllocationRequest>& request, bool tryAllocate) { assert(!_parent); @@ -365,17 +343,17 @@ Allocatable::queueAllocationAttempt(const AllocatablePtr& allocatable, { if(request->pending()) { - _requests.push_back(make_pair(allocatable, request)); + _requests.push_back({ allocatable, request }); } } else { - _requests.push_back(make_pair(allocatable, AllocationRequestPtr())); + _requests.push_back({ allocatable, nullptr }); } } void -Allocatable::queueAllocationAttemptFromChild(const AllocatablePtr& allocatable) +Allocatable::queueAllocationAttemptFromChild(const shared_ptr<Allocatable>& allocatable) { if(_parent) { @@ -383,19 +361,19 @@ Allocatable::queueAllocationAttemptFromChild(const AllocatablePtr& allocatable) return; } - Lock sync(*this); - _requests.push_back(make_pair(allocatable, AllocationRequestPtr())); + lock_guard lock(_mutex); + _requests.push_back({ allocatable, nullptr }); } -AllocatablePtr -Allocatable::dequeueAllocationAttempt(AllocationRequestPtr& request) +shared_ptr<Allocatable> +Allocatable::dequeueAllocationAttempt(shared_ptr<AllocationRequest>& request) { if(_requests.empty()) { - return 0; + return nullptr; } - pair<AllocatablePtr, AllocationRequestPtr> alloc = _requests.front(); + auto alloc = _requests.front(); _requests.pop_front(); if(alloc.second) { @@ -405,9 +383,9 @@ Allocatable::dequeueAllocationAttempt(AllocationRequestPtr& request) } bool -Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, bool fromRelease) +Allocatable::allocate(const shared_ptr<AllocationRequest>& request, bool tryAllocate, bool fromRelease) { - if(_parent && !_parent->allocateFromChild(request, this, tryAllocate, fromRelease)) + if(_parent && !_parent->allocateFromChild(request, shared_from_this(), tryAllocate, fromRelease)) { return false; } @@ -416,12 +394,12 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo int allocationCount = 0; try { - Lock sync(*this); + lock_guard lock(_mutex); checkAllocatable(); if(!_session && (fromRelease || !_releasing)) { - if(request->allocate(this, _session)) + if(request->allocate(shared_from_this(), _session)) { try { @@ -429,12 +407,12 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo } catch(const SessionDestroyedException&) { - request->canceled(AllocationException("session destroyed")); + request->canceled(make_exception_ptr(AllocationException("session destroyed"))); throw; } assert(_count == 0); _session = request->getSession(); - request->allocated(this, request->getSession()); + request->allocated(shared_from_this(), request->getSession()); ++_count; allocationCount = _count; } @@ -443,11 +421,11 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo { if(!tryAllocate) { - if(request->allocate(this, _session)) + if(request->allocate(shared_from_this(), _session)) { assert(_count > 0); ++_count; - request->allocated(this, _session); + request->allocated(shared_from_this(), _session); allocationCount = _count; } } @@ -458,7 +436,7 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo } else { - queueAllocationAttempt(this, request, tryAllocate); + queueAllocationAttempt(shared_from_this(), request, tryAllocate); } } catch(...) @@ -478,7 +456,7 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo { if(queueWithParent) { - _parent->queueAllocationAttemptFromChild(this); + _parent->queueAllocationAttemptFromChild(shared_from_this()); } _parent->release(request->getSession(), fromRelease); } @@ -486,8 +464,8 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo } bool -Allocatable::allocateFromChild(const AllocationRequestPtr& request, - const AllocatablePtr& child, +Allocatable::allocateFromChild(const shared_ptr<AllocationRequest>& request, + const shared_ptr<Allocatable>& child, bool tryAllocate, bool fromRelease) { @@ -498,7 +476,7 @@ Allocatable::allocateFromChild(const AllocationRequestPtr& request, int allocationCount = 0; { - Lock sync(*this); + lock_guard lock(_mutex); if((!_session || _session == request->getSession()) && (fromRelease || !_releasing)) { if(!_session) diff --git a/cpp/src/IceGrid/Allocatable.h b/cpp/src/IceGrid/Allocatable.h index 94f7fd2a183..bedf6dabce8 100644 --- a/cpp/src/IceGrid/Allocatable.h +++ b/cpp/src/IceGrid/Allocatable.h @@ -5,10 +5,6 @@ #ifndef ICE_GRID_ALLOCATABLE_H #define ICE_GRID_ALLOCATABLE_H -#include <IceUtil/Handle.h> -#include <IceUtil/Mutex.h> -#include <IceUtil/Shared.h> -#include <IceUtil/Time.h> #include <IceUtil/Timer.h> #include <IceGrid/Session.h> @@ -19,35 +15,33 @@ namespace IceGrid { -class SessionI; -typedef IceUtil::Handle<SessionI> SessionIPtr; - class Allocatable; -typedef IceUtil::Handle<Allocatable> AllocatablePtr; +class SessionI; -class AllocationRequest : public IceUtil::Mutex, public IceUtil::TimerTask +class AllocationRequest : public IceUtil::TimerTask, public std::enable_shared_from_this<AllocationRequest> { public: - virtual ~AllocationRequest(); + virtual ~AllocationRequest() = default; - virtual void allocated(const AllocatablePtr&, const SessionIPtr&) = 0; - virtual void canceled(const Ice::UserException&) = 0; + virtual void allocated(const std::shared_ptr<Allocatable>&, const std::shared_ptr<SessionI>&) = 0; + virtual void canceled(std::exception_ptr) = 0; bool pending(); - bool allocate(const AllocatablePtr&, const SessionIPtr&); - void cancel(const Ice::UserException&); - void runTimerTask(); // Implementation of IceUtil::TimerTask::runTimerTask() + bool allocate(const std::shared_ptr<Allocatable>&, const std::shared_ptr<SessionI>&); + void cancel(std::exception_ptr); + + void runTimerTask() override; int getTimeout() const { return _timeout; } - const SessionIPtr& getSession() const { return _session; } + const std::shared_ptr<SessionI>& getSession() const { return _session; } bool isCanceled() const; bool operator<(const AllocationRequest&) const; protected: - AllocationRequest(const SessionIPtr&); + AllocationRequest(const std::shared_ptr<SessionI>&); private: @@ -59,53 +53,57 @@ private: Allocated }; - const SessionIPtr _session; + const std::shared_ptr<SessionI> _session; const int _timeout; State _state; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<AllocationRequest> AllocationRequestPtr; -class Allocatable : public virtual IceUtil::Shared, public IceUtil::Monitor<IceUtil::Mutex> +class Allocatable: public virtual std::enable_shared_from_this<Allocatable> { public: - Allocatable(bool, const AllocatablePtr&); - virtual ~Allocatable(); + Allocatable(bool, const std::shared_ptr<Allocatable>&); + virtual ~Allocatable() = default; virtual void checkAllocatable(); - virtual bool allocate(const AllocationRequestPtr&, bool = false); - virtual bool tryAllocate(const AllocationRequestPtr&, bool = false); - virtual void release(const SessionIPtr&, bool = false); + virtual bool allocate(const std::shared_ptr<AllocationRequest>&, bool = false); + virtual bool tryAllocate(const std::shared_ptr<AllocationRequest>&, bool = false); + virtual void release(const std::shared_ptr<SessionI>&, bool = false); bool isAllocatable() const { return _allocatable; } - SessionIPtr getSession() const; + std::shared_ptr<SessionI> getSession() const; virtual bool isEnabled() const = 0; - virtual void allocated(const SessionIPtr&) = 0; - virtual void released(const SessionIPtr&) = 0; + virtual void allocated(const std::shared_ptr<SessionI>&) = 0; + virtual void released(const std::shared_ptr<SessionI>&) = 0; virtual bool canTryAllocate() { return false; } - virtual void allocatedNoSync(const SessionIPtr&) { ; } - virtual void releasedNoSync(const SessionIPtr&) { ; } + virtual void allocatedNoSync(const std::shared_ptr<SessionI>&) {} + virtual void releasedNoSync(const std::shared_ptr<SessionI>&) {} bool operator<(const Allocatable&) const; protected: - bool allocate(const AllocationRequestPtr&, bool, bool); - void queueAllocationAttemptFromChild(const AllocatablePtr&); - bool allocateFromChild(const AllocationRequestPtr&, const AllocatablePtr&, bool, bool); + bool allocate(const std::shared_ptr<AllocationRequest>&, bool, bool); + void queueAllocationAttemptFromChild(const std::shared_ptr<Allocatable>&); + bool allocateFromChild(const std::shared_ptr<AllocationRequest>&, const std::shared_ptr<Allocatable>&, bool, bool); - void queueAllocationAttempt(const AllocatablePtr&, const AllocationRequestPtr&, bool); - AllocatablePtr dequeueAllocationAttempt(AllocationRequestPtr&); + void queueAllocationAttempt(const std::shared_ptr<Allocatable>&, const std::shared_ptr<AllocationRequest>&, bool); + std::shared_ptr<Allocatable> dequeueAllocationAttempt(std::shared_ptr<AllocationRequest>&); bool _allocatable; - const AllocatablePtr _parent; + const std::shared_ptr<Allocatable> _parent; - std::list<std::pair<AllocatablePtr, AllocationRequestPtr> > _requests; - SessionIPtr _session; + std::list<std::pair<std::shared_ptr<Allocatable>, std::shared_ptr<AllocationRequest>>> _requests; + std::shared_ptr<SessionI> _session; int _count; bool _releasing; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; }; diff --git a/cpp/src/IceGrid/AllocatableObjectCache.cpp b/cpp/src/IceGrid/AllocatableObjectCache.cpp index 0f77b299ea1..54004e47f7d 100644 --- a/cpp/src/IceGrid/AllocatableObjectCache.cpp +++ b/cpp/src/IceGrid/AllocatableObjectCache.cpp @@ -13,32 +13,24 @@ using namespace std; using namespace IceGrid; -namespace IceGrid +namespace { -struct AllocatableObjectEntryCI : binary_function<AllocatableObjectEntryPtr&, AllocatableObjectEntryPtr&, bool> +bool compareAllocatableObjectEntry(const shared_ptr<AllocatableObjectEntry>& lhs, + const shared_ptr<AllocatableObjectEntry>& rhs) { - - bool - operator()(const AllocatableObjectEntryPtr& lhs, const AllocatableObjectEntryPtr& rhs) - { - return ::Ice::proxyIdentityLess(lhs->getProxy(), rhs->getProxy()); - } -}; + return Ice::proxyIdentityLess(lhs->getProxy(), rhs->getProxy()); +} }; -AllocatableObjectCache::TypeEntry::TypeEntry() -{ -} - void -AllocatableObjectCache::TypeEntry::add(const AllocatableObjectEntryPtr& obj) +AllocatableObjectCache::TypeEntry::add(const shared_ptr<AllocatableObjectEntry>& obj) { // // No mutex protection here, this is called with the cache locked. // - _objects.insert(lower_bound(_objects.begin(), _objects.end(), obj, AllocatableObjectEntryCI()), obj); + _objects.insert(lower_bound(_objects.begin(), _objects.end(), obj, compareAllocatableObjectEntry), obj); if(!_requests.empty()) { canTryAllocate(obj, false); @@ -46,28 +38,28 @@ AllocatableObjectCache::TypeEntry::add(const AllocatableObjectEntryPtr& obj) } bool -AllocatableObjectCache::TypeEntry::remove(const AllocatableObjectEntryPtr& obj) +AllocatableObjectCache::TypeEntry::remove(const shared_ptr<AllocatableObjectEntry>& obj) { // // No mutex protection here, this is called with the cache locked. // - vector<AllocatableObjectEntryPtr>::iterator q; - q = lower_bound(_objects.begin(), _objects.end(), obj, AllocatableObjectEntryCI()); + vector<shared_ptr<AllocatableObjectEntry>>::iterator q; + q = lower_bound(_objects.begin(), _objects.end(), obj, compareAllocatableObjectEntry); assert(q->get() == obj.get()); _objects.erase(q); if(!_requests.empty() && _objects.empty()) { - for(list<ObjectAllocationRequestPtr>::const_iterator p = _requests.begin(); p != _requests.end(); ++p) + for(const auto& req : _requests) { - (*p)->cancel(AllocationException("no allocatable objects with type `" + obj->getType() + "' registered")); + req->cancel(make_exception_ptr(AllocationException("no allocatable objects with type `" + obj->getType() + "' registered"))); } } return _objects.empty(); } void -AllocatableObjectCache::TypeEntry::addAllocationRequest(const ObjectAllocationRequestPtr& request) +AllocatableObjectCache::TypeEntry::addAllocationRequest(const shared_ptr<ObjectAllocationRequest>& request) { // // No mutex protection here, this is called with the cache locked. @@ -79,15 +71,15 @@ AllocatableObjectCache::TypeEntry::addAllocationRequest(const ObjectAllocationRe } bool -AllocatableObjectCache::TypeEntry::canTryAllocate(const AllocatableObjectEntryPtr& entry, bool fromRelease) +AllocatableObjectCache::TypeEntry::canTryAllocate(const shared_ptr<AllocatableObjectEntry>& entry, bool fromRelease) { // // No mutex protection here, this is called with the cache locked. // - list<ObjectAllocationRequestPtr>::iterator p = _requests.begin(); + auto p = _requests.begin(); while(p != _requests.end()) { - AllocationRequestPtr request = *p; + auto request = *p; try { if(request->isCanceled()) // If the request has been canceled, we just remove it. @@ -116,17 +108,18 @@ AllocatableObjectCache::TypeEntry::canTryAllocate(const AllocatableObjectEntryPt return false; } -AllocatableObjectCache::AllocatableObjectCache(const Ice::CommunicatorPtr& communicator) : +AllocatableObjectCache::AllocatableObjectCache(const shared_ptr<Ice::Communicator>& communicator) : _communicator(communicator) { } void -AllocatableObjectCache::add(const ObjectInfo& info, const ServerEntryPtr& parent) +AllocatableObjectCache::add(const ObjectInfo& info, const shared_ptr<ServerEntry>& parent) { - const Ice::Identity& id = info.proxy->ice_getIdentity(); + auto id = info.proxy->ice_getIdentity(); + + lock_guard lock(_mutex); - Lock sync(*this); if(getImpl(id)) { Ice::Error out(_communicator->getLogger()); @@ -134,7 +127,7 @@ AllocatableObjectCache::add(const ObjectInfo& info, const ServerEntryPtr& parent return; } - AllocatableObjectEntryPtr entry = new AllocatableObjectEntry(*this, info, parent); + auto entry = make_shared<AllocatableObjectEntry>(*this, info, parent); addImpl(id, entry); map<string, TypeEntry>::iterator p = _types.find(entry->getType()); @@ -151,11 +144,12 @@ AllocatableObjectCache::add(const ObjectInfo& info, const ServerEntryPtr& parent } } -AllocatableObjectEntryPtr +shared_ptr<AllocatableObjectEntry> AllocatableObjectCache::get(const Ice::Identity& id) const { - Lock sync(*this); - AllocatableObjectEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + + auto entry = getImpl(id); if(!entry) { throw ObjectNotRegisteredException(id); @@ -166,9 +160,10 @@ AllocatableObjectCache::get(const Ice::Identity& id) const void AllocatableObjectCache::remove(const Ice::Identity& id) { - AllocatableObjectEntryPtr entry; + shared_ptr<AllocatableObjectEntry> entry; { - Lock sync(*this); + lock_guard lock(_mutex); + entry = getImpl(id); if(!entry) { @@ -177,7 +172,7 @@ AllocatableObjectCache::remove(const Ice::Identity& id) } removeImpl(id); - map<string, TypeEntry>::iterator p = _types.find(entry->getType()); + auto p = _types.find(entry->getType()); assert(p != _types.end()); if(p->second.remove(entry)) { @@ -201,26 +196,27 @@ AllocatableObjectCache::remove(const Ice::Identity& id) } void -AllocatableObjectCache::allocateByType(const string& type, const ObjectAllocationRequestPtr& request) +AllocatableObjectCache::allocateByType(const string& type, const shared_ptr<ObjectAllocationRequest>& request) { - Lock sync(*this); - map<string, TypeEntry>::iterator p = _types.find(type); + lock_guard lock(_mutex); + + auto p = _types.find(type); if(p == _types.end()) { throw AllocationException("no allocatable objects with type `" + type + "' registered"); } - vector<AllocatableObjectEntryPtr> objects = p->second.getObjects(); + vector<shared_ptr<AllocatableObjectEntry>> objects = p->second.getObjects(); IceUtilInternal::shuffle(objects.begin(), objects.end()); // TODO: OPTIMIZE int allocatable = 0; try { - for(vector<AllocatableObjectEntryPtr>::const_iterator q = objects.begin(); q != objects.end(); ++q) + for(const auto& obj : objects) { - if((*q)->isEnabled()) + if(obj->isEnabled()) { ++allocatable; - if((*q)->tryAllocate(request)) + if(obj->tryAllocate(request)) { return; } @@ -239,13 +235,13 @@ AllocatableObjectCache::allocateByType(const string& type, const ObjectAllocatio } bool -AllocatableObjectCache::canTryAllocate(const AllocatableObjectEntryPtr& entry) +AllocatableObjectCache::canTryAllocate(const shared_ptr<AllocatableObjectEntry>& entry) { // // Notify the type entry that an object was released. // - Lock sync(*this); - map<string, TypeEntry>::iterator p = _types.find(entry->getType()); + lock_guard lock(_mutex); + auto p = _types.find(entry->getType()); if(p == _types.end()) { return false; @@ -255,7 +251,7 @@ AllocatableObjectCache::canTryAllocate(const AllocatableObjectEntryPtr& entry) AllocatableObjectEntry::AllocatableObjectEntry(AllocatableObjectCache& cache, const ObjectInfo& info, - const ServerEntryPtr& parent) : + const shared_ptr<ServerEntry>& parent) : Allocatable(true, parent), _cache(cache), _info(info), @@ -265,7 +261,7 @@ AllocatableObjectEntry::AllocatableObjectEntry(AllocatableObjectCache& cache, assert(_server); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> AllocatableObjectEntry::getProxy() const { return _info.proxy; @@ -290,15 +286,15 @@ AllocatableObjectEntry::isEnabled() const } void -AllocatableObjectEntry::allocated(const SessionIPtr& session) +AllocatableObjectEntry::allocated(const shared_ptr<SessionI>& session) { // // Add the object allocation to the session. The object will be // released once the session is destroyed. // - session->addAllocation(this); + session->addAllocation(shared_from_this()); - TraceLevelsPtr traceLevels = _cache.getTraceLevels(); + auto traceLevels = _cache.getTraceLevels(); if(traceLevels && traceLevels->object > 1) { Ice::Trace out(traceLevels->logger, traceLevels->objectCat); @@ -306,7 +302,7 @@ AllocatableObjectEntry::allocated(const SessionIPtr& session) << ")"; } - Glacier2::IdentitySetPrx identities = session->getGlacier2IdentitySet(); + auto identities = session->getGlacier2IdentitySet(); if(identities) { try @@ -328,16 +324,16 @@ AllocatableObjectEntry::allocated(const SessionIPtr& session) } void -AllocatableObjectEntry::released(const SessionIPtr& session) +AllocatableObjectEntry::released(const shared_ptr<SessionI>& session) { // // Remove the object allocation from the session. // - session->removeAllocation(this); + session->removeAllocation(shared_from_this()); - TraceLevelsPtr traceLevels = _cache.getTraceLevels(); + auto traceLevels = _cache.getTraceLevels(); - Glacier2::IdentitySetPrx identities = session->getGlacier2IdentitySet(); + auto identities = session->getGlacier2IdentitySet(); if(identities) { try @@ -368,9 +364,9 @@ AllocatableObjectEntry::released(const SessionIPtr& session) void AllocatableObjectEntry::destroy() { - SessionIPtr session; + shared_ptr<SessionI> session; { - Lock sync(*this); + lock_guard lock(_mutex); _destroyed = true; session = _session; } @@ -400,5 +396,5 @@ AllocatableObjectEntry::checkAllocatable() bool AllocatableObjectEntry::canTryAllocate() { - return _cache.canTryAllocate(this); + return _cache.canTryAllocate(static_pointer_cast<AllocatableObjectEntry>(shared_from_this())); } diff --git a/cpp/src/IceGrid/AllocatableObjectCache.h b/cpp/src/IceGrid/AllocatableObjectCache.h index 19f60f2ba11..bdae1d6037a 100644 --- a/cpp/src/IceGrid/AllocatableObjectCache.h +++ b/cpp/src/IceGrid/AllocatableObjectCache.h @@ -5,7 +5,6 @@ #ifndef ICE_GRID_ALLOCATABLEOBJECTCACHE_H #define ICE_GRID_ALLOCATABLEOBJECTCACHE_H -#include <IceUtil/Mutex.h> #include <Ice/CommunicatorF.h> #include <IceGrid/Cache.h> #include <IceGrid/Admin.h> @@ -14,77 +13,73 @@ namespace IceGrid { -class ServerEntry; -typedef IceUtil::Handle<ServerEntry> ServerEntryPtr; - class AllocatableObjectCache; +class ServerEntry; class AllocatableObjectEntry : public Allocatable { public: - AllocatableObjectEntry(AllocatableObjectCache&, const ObjectInfo&, const ServerEntryPtr&); - Ice::ObjectPrx getProxy() const; + AllocatableObjectEntry(AllocatableObjectCache&, const ObjectInfo&, const std::shared_ptr<ServerEntry>&); + std::shared_ptr<Ice::ObjectPrx> getProxy() const; std::string getType() const; bool canRemove(); - virtual bool isEnabled() const; - virtual void allocated(const SessionIPtr&); - virtual void released(const SessionIPtr&); - virtual bool canTryAllocate(); + bool isEnabled() const override; + void allocated(const std::shared_ptr<SessionI>&) override; + void released(const std::shared_ptr<SessionI>&) override; + bool canTryAllocate() override; void destroy(); - virtual void checkAllocatable(); + void checkAllocatable() override; private: AllocatableObjectCache& _cache; const ObjectInfo _info; - ServerEntryPtr _server; + std::shared_ptr<ServerEntry> _server; bool _destroyed; }; -typedef IceUtil::Handle<AllocatableObjectEntry> AllocatableObjectEntryPtr; class ObjectAllocationRequest : public AllocationRequest { public: - ObjectAllocationRequest(const SessionIPtr& session) : AllocationRequest(session) { } + ObjectAllocationRequest(const std::shared_ptr<SessionI>& session) : AllocationRequest(session) + { + } - virtual void response(const Ice::ObjectPrx&) = 0; - virtual void exception(const Ice::UserException&) = 0; + virtual void response(const std::shared_ptr<Ice::ObjectPrx>&) = 0; + virtual void exception(std::exception_ptr) = 0; private: - virtual void allocated(const AllocatablePtr& allocatable, const SessionIPtr& /*session*/) + void allocated(const std::shared_ptr<Allocatable>& allocatable, const std::shared_ptr<SessionI>&) override { - response(AllocatableObjectEntryPtr::dynamicCast(allocatable)->getProxy()); + response(std::dynamic_pointer_cast<AllocatableObjectEntry>(allocatable)->getProxy()); } - virtual void canceled(const Ice::UserException& ex) + void canceled(std::exception_ptr ex) override { exception(ex); } }; -typedef IceUtil::Handle<ObjectAllocationRequest> ObjectAllocationRequestPtr; - -class AdapterCache; class AllocatableObjectCache : public Cache<Ice::Identity, AllocatableObjectEntry> { public: - AllocatableObjectCache(const Ice::CommunicatorPtr&); + AllocatableObjectCache(const std::shared_ptr<Ice::Communicator>&); - void add(const ObjectInfo&, const ServerEntryPtr&); - AllocatableObjectEntryPtr get(const Ice::Identity&) const; + void add(const ObjectInfo&, const std::shared_ptr<ServerEntry>&); + std::shared_ptr<AllocatableObjectEntry> get(const Ice::Identity&) const; void remove(const Ice::Identity&); - void allocateByType(const std::string&, const ObjectAllocationRequestPtr&); - bool canTryAllocate(const AllocatableObjectEntryPtr&); + void allocateByType(const std::string&, const std::shared_ptr<ObjectAllocationRequest>&); + bool canTryAllocate(const std::shared_ptr<AllocatableObjectEntry>&); - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr<Ice::Communicator>& getCommunicator() const { return _communicator; } private: @@ -92,23 +87,21 @@ private: { public: - TypeEntry(); - - void add(const AllocatableObjectEntryPtr&); - bool remove(const AllocatableObjectEntryPtr&); + void add(const std::shared_ptr<AllocatableObjectEntry>&); + bool remove(const std::shared_ptr<AllocatableObjectEntry>&); - void addAllocationRequest(const ObjectAllocationRequestPtr&); - bool canTryAllocate(const AllocatableObjectEntryPtr&, bool); + void addAllocationRequest(const std::shared_ptr<ObjectAllocationRequest>&); + bool canTryAllocate(const std::shared_ptr<AllocatableObjectEntry>&, bool); - const std::vector<AllocatableObjectEntryPtr>& getObjects() const { return _objects; } + const std::vector<std::shared_ptr<AllocatableObjectEntry>>& getObjects() const { return _objects; } private: - std::vector<AllocatableObjectEntryPtr> _objects; - std::list<ObjectAllocationRequestPtr> _requests; + std::vector<std::shared_ptr<AllocatableObjectEntry>> _objects; + std::list<std::shared_ptr<ObjectAllocationRequest>> _requests; }; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr<Ice::Communicator> _communicator; std::map<std::string, TypeEntry> _types; std::map<std::string, std::vector<Ice::Identity> > _allocatablesByType; }; diff --git a/cpp/src/IceGrid/Cache.h b/cpp/src/IceGrid/Cache.h index 9e32c561d41..e1ec7f5682f 100644 --- a/cpp/src/IceGrid/Cache.h +++ b/cpp/src/IceGrid/Cache.h @@ -5,29 +5,26 @@ #ifndef ICE_GRID_CACHE_H #define ICE_GRID_CACHE_H -#include <IceUtil/Mutex.h> -#include <IceUtil/Shared.h> #include <IceGrid/Util.h> #include <IceGrid/TraceLevels.h> +#include <mutex> + namespace IceGrid { -class SynchronizationCallback : public virtual IceUtil::Shared +class SynchronizationCallback { public: - virtual void synchronized() = 0; - - virtual void synchronized(const Ice::Exception&) = 0; + virtual void synchronized(std::exception_ptr) = 0; }; -typedef IceUtil::Handle<SynchronizationCallback> SynchronizationCallbackPtr; template<typename Key, typename Value> -class Cache : public IceUtil::Monitor<IceUtil::Mutex> +class Cache { - typedef IceUtil::Handle<Value> ValuePtr; - typedef std::map<Key, ValuePtr> ValueMap; + using ValueType = std::shared_ptr<Value>; + using ValueMap = std::map<Key, ValueType>; public: @@ -35,39 +32,36 @@ public: { } - virtual - ~Cache() - { - } + virtual ~Cache() = default; bool has(const Key& key) const { - Lock sync(*this); - return getImpl(key); + std::lock_guard<std::mutex> lock(_mutex); + return getImpl(key) != nullptr; } void remove(const Key& key) { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); removeImpl(key); } void - setTraceLevels(const TraceLevelsPtr& traceLevels) + setTraceLevels(const std::shared_ptr<TraceLevels>& traceLevels) { _traceLevels = traceLevels; } - const TraceLevelsPtr& getTraceLevels() const { return _traceLevels; } + const std::shared_ptr<TraceLevels>& getTraceLevels() const { return _traceLevels; } protected: - virtual ValuePtr + virtual ValueType getImpl(const Key& key) const { - typename ValueMap::iterator p = const_cast<ValueMap&>(_entries).end(); + auto p = const_cast<ValueMap&>(_entries).end(); if(_entriesHint != p) { if(_entriesHint->first == key) @@ -88,22 +82,21 @@ protected: } else { - return 0; + return nullptr; } } - virtual ValuePtr - addImpl(const Key& key, const ValuePtr& entry) + virtual ValueType + addImpl(const Key& key, const ValueType& entry) { - typename ValueMap::value_type v(key, entry); - _entriesHint = _entries.insert(_entriesHint, v); + _entriesHint = _entries.insert(_entriesHint, { key, entry }); return entry; } virtual void removeImpl(const Key& key) { - typename ValueMap::iterator p = _entries.end(); + auto p = _entries.end(); if(_entriesHint != _entries.end()) { if(_entriesHint->first == key) @@ -129,23 +122,24 @@ protected: } } - TraceLevelsPtr _traceLevels; + std::shared_ptr<TraceLevels> _traceLevels; ValueMap _entries; typename ValueMap::iterator _entriesHint; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; template<typename T> class CacheByString : public Cache<std::string, T> { - typedef IceUtil::Handle<T> TPtr; - public: - virtual std::vector<std::string> + std::vector<std::string> getAll(const std::string& expr) { - IceUtil::Monitor<IceUtil::Mutex>::Lock sync(*this); - return getMatchingKeys<std::map<std::string,TPtr> >(Cache<std::string, T>::_entries, expr); + std::lock_guard<std::mutex> lock(Cache<std::string, T>::_mutex); + return getMatchingKeys<std::map<std::string, std::shared_ptr<T>>>(Cache<std::string, T>::_entries, expr); } }; diff --git a/cpp/src/IceGrid/Client.cpp b/cpp/src/IceGrid/Client.cpp index 627cb87e95d..555e0ee7e4a 100644 --- a/cpp/src/IceGrid/Client.cpp +++ b/cpp/src/IceGrid/Client.cpp @@ -4,12 +4,9 @@ #include <IceUtil/Options.h> #include <IceUtil/CtrlCHandler.h> -#include <IceUtil/Thread.h> #include <IceUtil/StringUtil.h> #include <Ice/ConsoleUtil.h> #include <Ice/UUID.h> -#include <IceUtil/Mutex.h> -#include <IceUtil/MutexPtrLock.h> #include <Ice/Ice.h> #include <IceGrid/Parser.h> #include <IceGrid/FileParserI.h> @@ -37,90 +34,46 @@ class Client; namespace { -IceUtil::Mutex* _staticMutex = 0; -Ice::CommunicatorPtr communicator; -IceGrid::ParserPtr parser; +mutex staticMutex; +shared_ptr<Ice::Communicator> communicator; +shared_ptr<IceGrid::Parser> parser; -class Init -{ -public: - - Init() - { - _staticMutex = new IceUtil::Mutex; - } - - ~Init() - { - delete _staticMutex; - _staticMutex = 0; - } }; -Init init; - -} - -class ReuseConnectionRouter : public Ice::Router +class ReuseConnectionRouter final : public Ice::Router { public: - ReuseConnectionRouter(const Ice::ObjectPrx& proxy) : _clientProxy(proxy) + ReuseConnectionRouter(shared_ptr<Ice::ObjectPrx> proxy) : _clientProxy(move(proxy)) { } - virtual Ice::ObjectPrx - getClientProxy(IceUtil::Optional<bool>& hasRoutingTable, const Ice::Current&) const + shared_ptr<Ice::ObjectPrx> + getClientProxy(IceUtil::Optional<bool>& hasRoutingTable, const Ice::Current&) const override { hasRoutingTable = false; return _clientProxy; } - virtual Ice::ObjectPrx - getServerProxy(const Ice::Current&) const - { - return 0; - } - - virtual void - addProxy(const Ice::ObjectPrx&, const Ice::Current&) + shared_ptr<Ice::ObjectPrx> + getServerProxy(const Ice::Current&) const override { + return nullptr; } - virtual Ice::ObjectProxySeq - addProxies(const Ice::ObjectProxySeq&, const Ice::Current&) + Ice::ObjectProxySeq + addProxies(Ice::ObjectProxySeq, const Ice::Current&) override { return Ice::ObjectProxySeq(); } private: - const Ice::ObjectPrx _clientProxy; + const shared_ptr<Ice::ObjectPrx> _clientProxy; }; int run(const Ice::StringSeq&); -// -// Callback for CtrlCHandler -// -static void -interruptCallback(int /*signal*/) -{ - IceUtilInternal::MutexPtrLock<IceUtil::Mutex> lock(_staticMutex); - if(parser) // If there's an interactive parser, notify the parser. - { - parser->interrupt(); - } - else - { - // - // Otherwise, destroy the communicator. - // - assert(communicator); - communicator->destroy(); - } -} - int #ifdef _WIN32 wmain(int argc, wchar_t* argv[]) @@ -138,16 +91,31 @@ main(int argc, char* argv[]) try { - Ice::CtrlCHandler ctrlCHandler; - Ice::PropertiesPtr defaultProps = Ice::createProperties(); - defaultProps->setProperty("IceGridAdmin.Server.Endpoints", "tcp -h localhost"); + IceUtil::CtrlCHandler ctrlCHandler; + auto defaultProps = Ice::createProperties(); + defaultProps->setProperty("IceGridAdmin.Server.Endpoints", "tcp -h 127.0.0.1"); + defaultProps->setProperty("IceGridAdmin.Server.ServerName", "127.0.0.1"); Ice::InitializationData id; id.properties = createProperties(args, defaultProps); id.properties->setProperty("Ice.Warn.Endpoints", "0"); Ice::CommunicatorHolder ich(id); communicator = ich.communicator(); - ctrlCHandler.setCallback(interruptCallback); + ctrlCHandler.setCallback([](int) { + lock_guard lg(staticMutex); + if(parser) // If there's an interactive parser, notify the parser. + { + parser->interrupt(); + } + else + { + // + // Otherwise, destroy the communicator. + // + assert(communicator); + communicator->destroy(); + } + }); try { @@ -224,7 +192,7 @@ getPassword(const string& prompt) } extern "C" ICE_LOCATOR_DISCOVERY_API Ice::Plugin* -createIceLocatorDiscovery(const Ice::CommunicatorPtr&, const string&, const Ice::StringSeq&); +createIceLocatorDiscovery(const shared_ptr<Ice::Communicator>&, const string&, const Ice::StringSeq&); int run(const Ice::StringSeq& args) @@ -275,9 +243,9 @@ run(const Ice::StringSeq& args) if(opts.isSet("server")) { - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("IceGridAdmin.Server"); + auto adapter = communicator->createObjectAdapter("IceGridAdmin.Server"); adapter->activate(); - Ice::ObjectPrx proxy = adapter->add(new FileParserI, Ice::stringToIdentity("FileParser")); + auto proxy = adapter->add(make_shared<IceGrid::FileParserI>(), Ice::stringToIdentity("FileParser")); consoleOut << proxy << endl; communicator->waitForShutdown(); @@ -286,10 +254,9 @@ run(const Ice::StringSeq& args) if(opts.isSet("e")) { - vector<string> optargs = opts.argVec("e"); - for(vector<string>::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + for(const auto& arg : opts.argVec("e")) { - commands += *i + ";"; + commands += arg + ";"; } } debug = opts.isSet("debug"); @@ -334,15 +301,15 @@ run(const Ice::StringSeq& args) } } - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string replica = properties->getProperty("IceGridAdmin.Replica"); if(!opts.optArg("replica").empty()) { replica = opts.optArg("replica"); } - Glacier2::RouterPrx router; - IceGrid::AdminSessionPrx session; + shared_ptr<Glacier2::RouterPrx> router; + shared_ptr<IceGrid::AdminSessionPrx> session; int status = 0; try { @@ -356,7 +323,7 @@ run(const Ice::StringSeq& args) os << "Ice/LocatorFinder" << (ssl ? " -s" : ""); os << ":tcp -h \"" << host << "\" -p " << (port == 0 ? 4061 : port) << " -t " << timeout; os << ":ssl -h \"" << host << "\" -p " << (port == 0 ? 4062 : port) << " -t " << timeout; - Ice::LocatorFinderPrx finder = Ice::LocatorFinderPrx::uncheckedCast(communicator->stringToProxy(os.str())); + auto finder = Ice::uncheckedCast<Ice::LocatorFinderPrx>(communicator->stringToProxy(os.str())); try { communicator->setDefaultLocator(finder->getLocator()); @@ -381,18 +348,19 @@ run(const Ice::StringSeq& args) // to lookup for locator proxies. We destroy the plugin, once we have selected a // locator. // - Ice::PluginPtr pluginObj = createIceLocatorDiscovery(communicator, "IceGridAdmin.Discovery", Ice::StringSeq()); - IceLocatorDiscovery::PluginPtr plugin = IceLocatorDiscovery::PluginPtr::dynamicCast(pluginObj); + shared_ptr<Ice::Plugin> pluginObj(createIceLocatorDiscovery(communicator, "IceGridAdmin.Discovery", + Ice::StringSeq())); + auto plugin = dynamic_pointer_cast<IceLocatorDiscovery::Plugin>(pluginObj); plugin->initialize(); - vector<Ice::LocatorPrx> locators = plugin->getLocators(instanceName, IceUtil::Time::milliSeconds(300)); + auto locators = plugin->getLocators(instanceName, IceUtil::Time::milliSeconds(300)); if(locators.size() > 1) { consoleOut << "found " << locators.size() << " Ice locators:" << endl; unsigned int num = 0; - for(vector<Ice::LocatorPrx>::const_iterator p = locators.begin(); p != locators.end(); ++p) + for(const auto& locator : locators) { - consoleOut << ++num << ": proxy = `" << *p << "'" << endl; + consoleOut << ++num << ": proxy = `" << locator << "'" << endl; } num = 0; @@ -440,7 +408,7 @@ run(const Ice::StringSeq& args) try { // Use SSL if available. - router = Glacier2::RouterPrx::checkedCast(communicator->getDefaultRouter()->ice_preferSecure(true)); + router = Ice::checkedCast<Glacier2::RouterPrx>(communicator->getDefaultRouter()->ice_preferSecure(true)); if(!router) { consoleErr << args[0] << ": configured router is not a Glacier2 router" << endl; @@ -455,7 +423,7 @@ run(const Ice::StringSeq& args) if(ssl) { - session = IceGrid::AdminSessionPrx::uncheckedCast(router->createSessionFromSecureConnection()); + session = Ice::uncheckedCast<IceGrid::AdminSessionPrx>(router->createSessionFromSecureConnection()); if(!session) { consoleErr << args[0] @@ -488,7 +456,7 @@ run(const Ice::StringSeq& args) #endif } - session = IceGrid::AdminSessionPrx::uncheckedCast(router->createSession(id, password)); + session = Ice::uncheckedCast<IceGrid::AdminSessionPrx>(router->createSession(id, password)); fill(password.begin(), password.end(), '\0'); // Zero the password string. if(!session) @@ -528,11 +496,11 @@ run(const Ice::StringSeq& args) // no need to go further. Otherwise, we get the proxy of local registry // proxy. // - IceGrid::LocatorPrx locator; - IceGrid::RegistryPrx localRegistry; + shared_ptr<IceGrid::LocatorPrx> locator; + shared_ptr<IceGrid::RegistryPrx> localRegistry; try { - locator = IceGrid::LocatorPrx::checkedCast(communicator->getDefaultLocator()); + locator = Ice::checkedCast<IceGrid::LocatorPrx>(communicator->getDefaultLocator()); if(!locator) { consoleErr << args[0] << ": configured locator is not an IceGrid locator" << endl; @@ -546,7 +514,7 @@ run(const Ice::StringSeq& args) return 1; } - IceGrid::RegistryPrx registry; + shared_ptr<IceGrid::RegistryPrx> registry; if(localRegistry->ice_getIdentity() == registryId) { registry = localRegistry; @@ -559,7 +527,7 @@ run(const Ice::StringSeq& args) try { - registry = IceGrid::RegistryPrx::checkedCast(locator->findObjectById(registryId)); + registry = Ice::checkedCast<IceGrid::RegistryPrx>(locator->findObjectById(registryId)); if(!registry) { consoleErr << args[0] << ": could not contact an IceGrid registry" << endl; @@ -603,9 +571,9 @@ run(const Ice::StringSeq& args) // if(registry->ice_getIdentity() == localRegistry->ice_getIdentity()) { - Ice::ObjectAdapterPtr colloc = communicator->createObjectAdapter(""); // colloc-only adapter - communicator->setDefaultRouter(Ice::RouterPrx::uncheckedCast( - colloc->addWithUUID(new ReuseConnectionRouter(locator)))); + auto colloc = communicator->createObjectAdapter(""); // colloc-only adapter + communicator->setDefaultRouter(Ice::uncheckedCast<Ice::RouterPrx>( + colloc->addWithUUID(make_shared<ReuseConnectionRouter>(locator)))); registry = registry->ice_router(communicator->getDefaultRouter()); } @@ -663,12 +631,12 @@ run(const Ice::StringSeq& args) if(acmTimeout > 0) { - session->ice_getConnection()->setACM(acmTimeout, IceUtil::None, Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); + session->ice_getConnection()->setACM(acmTimeout, IceUtil::None, Ice::ACMHeartbeat::HeartbeatAlways); } { - IceUtilInternal::MutexPtrLock<IceUtil::Mutex> lock(_staticMutex); - parser = IceGrid::Parser::createParser(communicator, session, session->getAdmin(), commands.empty()); + lock_guard lock(staticMutex); + parser = make_shared<IceGrid::Parser>(communicator, session, session->getAdmin(), commands.empty()); } if(!commands.empty()) // Commands were given diff --git a/cpp/src/IceGrid/Database.cpp b/cpp/src/IceGrid/Database.cpp index 4abfe9e436d..697e7fd8e70 100644 --- a/cpp/src/IceGrid/Database.cpp +++ b/cpp/src/IceGrid/Database.cpp @@ -4,7 +4,6 @@ #include <IceUtil/StringUtil.h> #include <IceUtil/Random.h> -#include <IceUtil/Functional.h> #include <Ice/LoggerUtil.h> #include <Ice/Communicator.h> #include <Ice/ObjectAdapter.h> @@ -25,11 +24,11 @@ using namespace std; using namespace IceGrid; -typedef IceDB::ReadWriteCursor<string, ApplicationInfo, IceDB::IceContext, Ice::OutputStream> ApplicationMapRWCursor; -typedef IceDB::ReadOnlyCursor<string, AdapterInfo, IceDB::IceContext, Ice::OutputStream> AdapterMapROCursor; -typedef IceDB::Cursor<string, string, IceDB::IceContext, Ice::OutputStream> AdaptersByGroupMapCursor; -typedef IceDB::ReadOnlyCursor<string, Ice::Identity, IceDB::IceContext, Ice::OutputStream> ObjectsByTypeMapROCursor; -typedef IceDB::ReadOnlyCursor<Ice::Identity, ObjectInfo, IceDB::IceContext, Ice::OutputStream> ObjectsMapROCursor; +using ApplicationMapRWCursor = IceDB::ReadWriteCursor<string, ApplicationInfo, IceDB::IceContext, Ice::OutputStream>; +using AdapterMapROCursor = IceDB::ReadOnlyCursor<string, AdapterInfo, IceDB::IceContext, Ice::OutputStream>; +using AdaptersByGroupMapCursor = IceDB::Cursor<string, string, IceDB::IceContext, Ice::OutputStream>; +using ObjectsByTypeMapROCursor = IceDB::ReadOnlyCursor<string, Ice::Identity, IceDB::IceContext, Ice::OutputStream>; +using ObjectsMapROCursor = IceDB::ReadOnlyCursor<Ice::Identity, ObjectInfo, IceDB::IceContext, Ice::OutputStream>; namespace { @@ -43,14 +42,6 @@ const string internalObjectsDbName = "internal-objects"; const string internalObjectsByTypeDbName = "internal-objectsByType"; const string serialsDbName = "serials"; -struct ObjectLoadCI : binary_function<pair<Ice::ObjectPrx, float>&, pair<Ice::ObjectPrx, float>&, bool> -{ - bool operator()(const pair<Ice::ObjectPrx, float>& lhs, const pair<Ice::ObjectPrx, float>& rhs) - { - return lhs.second < rhs.second; - } -}; - template<typename K, typename V, typename C, typename H> vector<V> toVector(const IceDB::ReadOnlyTxn& txn, const IceDB::Dbi<K, V, C, H>& m) { @@ -82,7 +73,7 @@ toMap(const IceDB::Txn& txn, const IceDB::Dbi<K, V, C, H>& d) } void -logError(const Ice::CommunicatorPtr& com, const IceDB::LMDBException& ex) +logError(const shared_ptr<Ice::Communicator>& com, const IceDB::LMDBException& ex) { Ice::Error error(com->getLogger()); error << "LMDB error: " << ex; @@ -91,8 +82,8 @@ logError(const Ice::CommunicatorPtr& com, const IceDB::LMDBException& ex) void filterAdapterInfos(const string& filter, const string& replicaGroupId, - const RegistryPluginFacadeIPtr& pluginFacade, - const Ice::ConnectionPtr& con, + const shared_ptr<RegistryPluginFacadeI>& pluginFacade, + const shared_ptr<Ice::Connection>& con, const Ice::Context& ctx, AdapterInfoSeq& infos) { @@ -101,7 +92,7 @@ filterAdapterInfos(const string& filter, return; } - vector<ReplicaGroupFilterPtr> filters = pluginFacade->getReplicaGroupFilters(filter); + auto filters = pluginFacade->getReplicaGroupFilters(filter); if(filters.empty()) { return; @@ -109,25 +100,25 @@ filterAdapterInfos(const string& filter, Ice::StringSeq adapterIds; adapterIds.reserve(infos.size()); - for(vector<AdapterInfo>::const_iterator p = infos.begin(); p != infos.end(); ++p) + for(const auto& info : infos) { - adapterIds.push_back(p->id); + adapterIds.push_back(info.id); } - for(vector<ReplicaGroupFilterPtr>::const_iterator q = filters.begin(); q != filters.end(); ++q) + for(const auto& f : filters) { - adapterIds = (*q)->filter(replicaGroupId, adapterIds, con, ctx); + adapterIds = f->filter(replicaGroupId, adapterIds, con, ctx); } vector<AdapterInfo> filteredAdpts; filteredAdpts.reserve(infos.size()); - for(Ice::StringSeq::const_iterator q = adapterIds.begin(); q != adapterIds.end(); ++q) + for(const auto& id : adapterIds) { - for(vector<AdapterInfo>::const_iterator r = infos.begin(); r != infos.end(); ++r) + for(const auto& info : infos) { - if(*q == r->id) + if(id == info.id) { - filteredAdpts.push_back(*r); + filteredAdpts.push_back(info); break; } } @@ -187,10 +178,25 @@ findByType(const IceDB::ReadOnlyTxn& txn, } -Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, - const IceStorm::TopicManagerPrx& topicManager, +shared_ptr<Database> +Database::create(const shared_ptr<Ice::ObjectAdapter>& registryAdapter, + const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, + const string& instanceName, + const shared_ptr<TraceLevels>& traceLevels, + const RegistryInfo& info, + bool readonly) +{ + shared_ptr<Database> db(new Database(registryAdapter, topicManager, instanceName, traceLevels, info, readonly)); + + db->_pluginFacade->setDatabase(db); + + return db; +} + +Database::Database(const shared_ptr<Ice::ObjectAdapter>& registryAdapter, + const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, const string& instanceName, - const TraceLevelsPtr& traceLevels, + const shared_ptr<TraceLevels>& traceLevels, const RegistryInfo& info, bool readonly) : _communicator(registryAdapter->getCommunicator()), @@ -209,8 +215,8 @@ Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, _dbLock(_communicator->getProperties()->getProperty("IceGrid.Registry.LMDB.Path") + "/icedb.lock"), _env(_communicator->getProperties()->getProperty("IceGrid.Registry.LMDB.Path"), 8, IceDB::getMapSize(_communicator->getProperties()->getPropertyAsInt("IceGrid.Registry.LMDB.MapSize"))), - _pluginFacade(RegistryPluginFacadeIPtr::dynamicCast(getRegistryPluginFacade())), - _lock(0) + _pluginFacade(dynamic_pointer_cast<RegistryPluginFacadeI>(getRegistryPluginFacade())), + _lock(nullptr) { IceDB::ReadWriteTxn txn(_env); @@ -257,13 +263,13 @@ Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, _objectCache.setTraceLevels(_traceLevels); _allocatableObjectCache.setTraceLevels(_traceLevels); - _nodeObserverTopic = new NodeObserverTopic(_topicManager, _internalAdapter); - _registryObserverTopic = new RegistryObserverTopic(_topicManager); + _nodeObserverTopic = NodeObserverTopic::create(_topicManager, _internalAdapter); + _registryObserverTopic = make_shared<RegistryObserverTopic>(_topicManager); _serverCache.setNodeObserverTopic(_nodeObserverTopic); // Set all serials to 1 if they have not yet been set. - Ice::Long serial; + long long serial; if(!_serials.get(txn, applicationsDbName, serial)) { _serials.put(txn, applicationsDbName, 1); @@ -277,18 +283,16 @@ Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, _serials.put(txn, objectsDbName, 1); } - _applicationObserverTopic = - new ApplicationObserverTopic(_topicManager, toMap(txn, _applications), getSerial(txn, applicationsDbName)); - _adapterObserverTopic = - new AdapterObserverTopic(_topicManager, toMap(txn, _adapters), getSerial(txn, adaptersDbName)); - _objectObserverTopic = - new ObjectObserverTopic(_topicManager, toMap(txn, _objects), getSerial(txn, objectsDbName)); + _applicationObserverTopic = make_shared<ApplicationObserverTopic>(_topicManager, toMap(txn, _applications), + getSerial(txn, applicationsDbName)); + _adapterObserverTopic = make_shared<AdapterObserverTopic>(_topicManager, toMap(txn, _adapters), + getSerial(txn, adaptersDbName)); + _objectObserverTopic = make_shared<ObjectObserverTopic>(_topicManager, toMap(txn, _objects), + getSerial(txn, objectsDbName)); txn.commit(); _registryObserverTopic->registryUp(info); - - _pluginFacade->setDatabase(this); } std::string @@ -300,7 +304,7 @@ Database::getInstanceName() const void Database::destroy() { - _pluginFacade->setDatabase(0); + _pluginFacade->setDatabase(nullptr); _registryObserverTopic->destroy(); _nodeObserverTopic->destroy(); @@ -309,31 +313,31 @@ Database::destroy() _objectObserverTopic->destroy(); } -ObserverTopicPtr +shared_ptr<ObserverTopic> Database::getObserverTopic(TopicName name) const { switch(name) { - case RegistryObserverTopicName: + case TopicName::RegistryObserver: return _registryObserverTopic; - case NodeObserverTopicName: + case TopicName::NodeObserver: return _nodeObserverTopic; - case ApplicationObserverTopicName: + case TopicName::ApplicationObserver: return _applicationObserverTopic; - case AdapterObserverTopicName: + case TopicName::AdapterObserver: return _adapterObserverTopic; - case ObjectObserverTopicName: + case TopicName::ObjectObserver: return _objectObserverTopic; default: break; } - return 0; + return nullptr; } void Database::checkSessionLock(AdminSessionI* session) { - if(_lock != 0 && session != _lock) + if(_lock != nullptr && session != _lock) { throw AccessDeniedException(_lockUserId); // Lock held by another session. } @@ -342,13 +346,13 @@ Database::checkSessionLock(AdminSessionI* session) int Database::lock(AdminSessionI* session, const string& userId) { - Lock sync(*this); + lock_guard lock(_mutex); - if(_lock != 0 && session != _lock) + if(_lock != nullptr && session != _lock) { throw AccessDeniedException(_lockUserId); // Lock held by another session. } - assert(_lock == 0 || _lock == session); + assert(_lock == nullptr || _lock == session); _lock = session; _lockUserId = userId; @@ -359,23 +363,24 @@ Database::lock(AdminSessionI* session, const string& userId) void Database::unlock(AdminSessionI* session) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_lock != session) { throw AccessDeniedException(); } - _lock = 0; + _lock = nullptr; _lockUserId.clear(); } void -Database::syncApplications(const ApplicationInfoSeq& newApplications, Ice::Long dbSerial) +Database::syncApplications(const ApplicationInfoSeq& newApplications, long long dbSerial) { assert(dbSerial != 0); int serial = 0; { - Lock sync(*this); + lock_guard lock(_mutex); map<string, ApplicationInfo> oldApplications; try @@ -433,7 +438,10 @@ Database::syncApplications(const ApplicationInfoSeq& newApplications, Ice::Long } } - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for(const auto& entry : entries) + { + entry->sync(); + } if(_traceLevels->application > 0) { @@ -447,21 +455,21 @@ Database::syncApplications(const ApplicationInfoSeq& newApplications, Ice::Long } void -Database::syncAdapters(const AdapterInfoSeq& adapters, Ice::Long dbSerial) +Database::syncAdapters(const AdapterInfoSeq& adapters, long long dbSerial) { assert(dbSerial != 0); int serial = 0; { - Lock sync(*this); + lock_guard lock(_mutex); try { IceDB::ReadWriteTxn txn(_env); _adapters.clear(txn); _adaptersByGroupId.clear(txn); - for(AdapterInfoSeq::const_iterator r = adapters.begin(); r != adapters.end(); ++r) + for(const auto& adapter : adapters) { - addAdapter(txn, *r); + addAdapter(txn, adapter); } dbSerial = updateSerial(txn, adaptersDbName, dbSerial); @@ -489,21 +497,21 @@ Database::syncAdapters(const AdapterInfoSeq& adapters, Ice::Long dbSerial) } void -Database::syncObjects(const ObjectInfoSeq& objects, Ice::Long dbSerial) +Database::syncObjects(const ObjectInfoSeq& objects, long long dbSerial) { assert(dbSerial != 0); int serial = 0; { - Lock sync(*this); + lock_guard lock(_mutex); try { IceDB::ReadWriteTxn txn(_env); _objects.clear(txn); _objectsByType.clear(txn); - for(ObjectInfoSeq::const_iterator q = objects.begin(); q != objects.end(); ++q) + for(const auto& obj : objects) { - addObject(txn, *q, false); + addObject(txn, obj, false); } dbSerial = updateSerial(txn, objectsDbName, dbSerial); @@ -527,7 +535,7 @@ Database::syncObjects(const ObjectInfoSeq& objects, Ice::Long dbSerial) } ApplicationInfoSeq -Database::getApplications(Ice::Long& serial) +Database::getApplications(long long& serial) { try { @@ -544,7 +552,7 @@ Database::getApplications(Ice::Long& serial) } AdapterInfoSeq -Database::getAdapters(Ice::Long& serial) +Database::getAdapters(long long& serial) { try { @@ -561,7 +569,7 @@ Database::getAdapters(Ice::Long& serial) } ObjectInfoSeq -Database::getObjects(Ice::Long& serial) +Database::getObjects(long long& serial) { try { @@ -585,7 +593,7 @@ Database::getSerials() const } void -Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ice::Long dbSerial) +Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, long long dbSerial) { assert(dbSerial != 0 || _master); @@ -593,10 +601,10 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic ServerEntrySeq entries; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(info.descriptor.name); + waitForUpdate(lock, info.descriptor.name); IceDB::ReadWriteTxn txn(_env); @@ -614,7 +622,11 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic load(helper, entries, info.uuid, info.revision); startUpdating(info.descriptor.name, info.uuid, info.revision); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for(const auto& entry : entries) + { + entry->sync(); + } + serial = _applicationObserverTopic->applicationAdded(dbSerial, info); } catch(const IceDB::KeyTooLongException& ex) @@ -634,7 +646,8 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic // for the nodes to start the servers. // { - Lock sync(*this); + lock_guard lock(_mutex); + vector<UpdateInfo>::iterator p = find(_updating.begin(), _updating.end(), info.descriptor.name); assert(p != _updating.end()); p->markUpdated(); @@ -660,7 +673,7 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic { try { - Lock sync(*this); + lock_guard lock(_mutex); entries.clear(); unload(ApplicationHelper(_communicator, info.descriptor), entries); @@ -668,7 +681,11 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic dbSerial = removeApplication(info.descriptor.name, txn); txn.commit(); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for(const auto& entry : entries) + { + entry->sync(); + } + serial = _applicationObserverTopic->applicationRemoved(dbSerial, info.descriptor.name); } catch(const DeploymentException& ex) @@ -682,7 +699,10 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic } _applicationObserverTopic->waitForSyncedSubscribers(serial); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitForSyncNoThrow)); + for(const auto& entry : entries) + { + entry->waitForSyncNoThrow(); + } finishUpdating(info.descriptor.name); throw; } @@ -704,14 +724,14 @@ Database::updateApplication(const ApplicationUpdateInfo& updt, bool noRestart, A ApplicationInfo oldApp; ApplicationUpdateInfo update = updt; - IceInternal::UniquePtr<ApplicationHelper> previous; - IceInternal::UniquePtr<ApplicationHelper> helper; + unique_ptr<ApplicationHelper> previous; + unique_ptr<ApplicationHelper> helper; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(update.descriptor.name); + waitForUpdate(lock, update.descriptor.name); IceDB::ReadOnlyTxn txn(_env); @@ -725,8 +745,8 @@ Database::updateApplication(const ApplicationUpdateInfo& updt, bool noRestart, A update.revision = oldApp.revision + 1; } - previous.reset(new ApplicationHelper(_communicator, oldApp.descriptor)); - helper.reset(new ApplicationHelper(_communicator, previous->update(update.descriptor), true)); + previous = make_unique<ApplicationHelper>(_communicator, oldApp.descriptor); + helper = make_unique<ApplicationHelper>(_communicator, previous->update(update.descriptor), true); startUpdating(update.descriptor.name, oldApp.uuid, oldApp.revision + 1); } @@ -736,7 +756,7 @@ Database::updateApplication(const ApplicationUpdateInfo& updt, bool noRestart, A throw; } - finishApplicationUpdate(update, oldApp, *previous, *helper, session, noRestart, dbSerial); + finishApplicationUpdate(update, oldApp, *previous.get(), *helper.get(), session, noRestart, dbSerial); } void @@ -746,14 +766,14 @@ Database::syncApplicationDescriptor(const ApplicationDescriptor& newDesc, bool n ApplicationUpdateInfo update; ApplicationInfo oldApp; - IceInternal::UniquePtr<ApplicationHelper> previous; - IceInternal::UniquePtr<ApplicationHelper> helper; + unique_ptr<ApplicationHelper> previous; + unique_ptr<ApplicationHelper> helper; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(newDesc.name); + waitForUpdate(lock, newDesc.name); IceDB::ReadOnlyTxn txn(_env); @@ -762,8 +782,8 @@ Database::syncApplicationDescriptor(const ApplicationDescriptor& newDesc, bool n throw ApplicationNotExistException(newDesc.name); } - previous.reset(new ApplicationHelper(_communicator, oldApp.descriptor)); - helper.reset(new ApplicationHelper(_communicator, newDesc, true)); + previous = make_unique<ApplicationHelper>(_communicator, oldApp.descriptor); + helper = make_unique<ApplicationHelper>(_communicator, newDesc, true); update.updateTime = IceUtil::Time::now().toMilliSeconds(); update.updateUser = _lockUserId; @@ -778,7 +798,7 @@ Database::syncApplicationDescriptor(const ApplicationDescriptor& newDesc, bool n throw; } - finishApplicationUpdate(update, oldApp, *previous, *helper, session, noRestart); + finishApplicationUpdate(update, oldApp, *previous.get(), *helper.get(), session, noRestart); } void @@ -791,15 +811,15 @@ Database::instantiateServer(const string& application, ApplicationUpdateInfo update; ApplicationInfo oldApp; - IceInternal::UniquePtr<ApplicationHelper> previous; - IceInternal::UniquePtr<ApplicationHelper> helper; + unique_ptr<ApplicationHelper> previous; + unique_ptr<ApplicationHelper> helper; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(application); + waitForUpdate(lock, application); IceDB::ReadOnlyTxn txn(_env); @@ -808,8 +828,8 @@ Database::instantiateServer(const string& application, throw ApplicationNotExistException(application); } - previous.reset(new ApplicationHelper(_communicator, oldApp.descriptor)); - helper.reset(new ApplicationHelper(_communicator, previous->instantiateServer(node, instance), true)); + previous = make_unique<ApplicationHelper>(_communicator, oldApp.descriptor); + helper = make_unique<ApplicationHelper>(_communicator, previous->instantiateServer(node, instance), true); update.updateTime = IceUtil::Time::now().toMilliSeconds(); update.updateUser = _lockUserId; @@ -824,7 +844,7 @@ Database::instantiateServer(const string& application, throw; } - finishApplicationUpdate(update, oldApp, *previous, *helper, session, true); + finishApplicationUpdate(update, oldApp, *previous.get(), *helper.get(), session, true); } void @@ -836,10 +856,10 @@ Database::removeApplication(const string& name, AdminSessionI* session, Ice::Lon int serial = 0; // Initialize to prevent warning. try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(name); + waitForUpdate(lock, name); ApplicationInfo appInfo; @@ -871,7 +891,11 @@ Database::removeApplication(const string& name, AdminSessionI* session, Ice::Lon startUpdating(name, appInfo.uuid, appInfo.revision); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for(const auto& entry : entries) + { + entry->sync(); + } + serial = _applicationObserverTopic->applicationRemoved(dbSerial, name); } catch(const IceDB::LMDBException& ex) @@ -884,7 +908,10 @@ Database::removeApplication(const string& name, AdminSessionI* session, Ice::Lon if(_master) { - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitForSyncNoThrow)); + for(const auto& entry : entries) + { + entry->waitForSyncNoThrow(); + } } if(_traceLevels->application > 0) @@ -917,20 +944,20 @@ Database::getAllApplications(const string& expression) } void -Database::waitForApplicationUpdate(const AMD_NodeSession_waitForApplicationUpdatePtr& cb, - const string& uuid, - int revision) +Database::waitForApplicationUpdate(const string& uuid, + int revision, + function<void()> response, function<void(exception_ptr)> exception) { - Lock sync(*this); + lock_guard lock(_mutex); vector<UpdateInfo>::iterator p = find(_updating.begin(), _updating.end(), make_pair(uuid, revision)); if(p != _updating.end() && !p->updated) { - p->cbs.push_back(cb); + p->cbs.push_back({ response, exception }); } else { - cb->ice_response(); + response(); } } @@ -940,7 +967,7 @@ Database::getNodeCache() return _nodeCache; } -NodeEntryPtr +shared_ptr<NodeEntry> Database::getNode(const string& name, bool create) const { return _nodeCache.get(name, create); @@ -952,7 +979,7 @@ Database::getReplicaCache() return _replicaCache; } -ReplicaEntryPtr +shared_ptr<ReplicaEntry> Database::getReplica(const string& name) const { return _replicaCache.get(name); @@ -964,7 +991,7 @@ Database::getServerCache() return _serverCache; } -ServerEntryPtr +shared_ptr<ServerEntry> Database::getServer(const string& id) const { return _serverCache.get(id); @@ -976,21 +1003,21 @@ Database::getAllocatableObjectCache() return _allocatableObjectCache; } -AllocatableObjectEntryPtr +shared_ptr<AllocatableObjectEntry> Database::getAllocatableObject(const Ice::Identity& id) const { return _allocatableObjectCache.get(id); } void -Database::setAdapterDirectProxy(const string& adapterId, const string& replicaGroupId, const Ice::ObjectPrx& proxy, - Ice::Long dbSerial) +Database::setAdapterDirectProxy(const string& adapterId, const string& replicaGroupId, + const shared_ptr<Ice::ObjectPrx>& proxy, long long dbSerial) { assert(dbSerial != 0 || _master); int serial = 0; // Initialize to prevent warning. { - Lock sync(*this); + lock_guard lock(_mutex); if(_adapterCache.has(adapterId)) { throw AdapterExistsException(adapterId); @@ -1003,10 +1030,7 @@ Database::setAdapterDirectProxy(const string& adapterId, const string& replicaGr "can be member of this replica group"); } - AdapterInfo info; - info.id = adapterId; - info.proxy = proxy; - info.replicaGroupId = replicaGroupId; + AdapterInfo info = { adapterId, proxy, replicaGroupId }; bool updated = false; try @@ -1077,8 +1101,9 @@ Database::setAdapterDirectProxy(const string& adapterId, const string& replicaGr _adapterObserverTopic->waitForSyncedSubscribers(serial); } -Ice::ObjectPrx -Database::getAdapterDirectProxy(const string& id, const Ice::EncodingVersion& encoding, const Ice::ConnectionPtr& con, +shared_ptr<Ice::ObjectPrx> +Database::getAdapterDirectProxy(const string& id, const Ice::EncodingVersion& encoding, + const shared_ptr<Ice::Connection>& con, const Ice::Context& ctx) { IceDB::ReadOnlyTxn txn(_env); @@ -1119,10 +1144,10 @@ Database::removeAdapter(const string& adapterId) int serial = 0; // Initialize to prevent warning. { - Lock sync(*this); + lock_guard lock(_mutex); if(_adapterCache.has(adapterId)) { - AdapterEntryPtr adpt = _adapterCache.get(adapterId); + auto adpt = _adapterCache.get(adapterId); throw DeploymentException("removing adapter `" + adapterId + "' is not allowed:\n" + "the adapter was added with the application descriptor `" + adpt->getApplication() + "'"); @@ -1188,16 +1213,16 @@ Database::removeAdapter(const string& adapterId) _adapterObserverTopic->waitForSyncedSubscribers(serial); } -AdapterPrx +shared_ptr<AdapterPrx> Database::getAdapterProxy(const string& adapterId, const string& replicaGroupId, bool upToDate) { - Lock sync(*this); // Make sure this isn't call during an update. + lock_guard lock(_mutex); // Make sure this isn't call during an update. return _adapterCache.get(adapterId)->getProxy(replicaGroupId, upToDate); } void Database::getLocatorAdapterInfo(const string& id, - const Ice::ConnectionPtr& connection, + const shared_ptr<Ice::Connection>& connection, const Ice::Context& context, LocatorAdapterInfoSeq& adpts, int& count, @@ -1207,13 +1232,13 @@ Database::getLocatorAdapterInfo(const string& id, { string filter; { - Lock sync(*this); // Make sure this isn't call during an update. + lock_guard lock(_mutex); // Make sure this isn't called during an update. _adapterCache.get(id)->getLocatorAdapterInfo(adpts, count, replicaGroup, roundRobin, filter, excludes); } if(_pluginFacade->hasReplicaGroupFilters() && !adpts.empty()) { - vector<ReplicaGroupFilterPtr> filters = _pluginFacade->getReplicaGroupFilters(filter); + auto filters = _pluginFacade->getReplicaGroupFilters(filter); if(!filters.empty()) { Ice::StringSeq adapterIds; @@ -1222,9 +1247,9 @@ Database::getLocatorAdapterInfo(const string& id, adapterIds.push_back(q->id); } - for(vector<ReplicaGroupFilterPtr>::const_iterator q = filters.begin(); q != filters.end(); ++q) + for(const auto& f : filters) { - adapterIds = (*q)->filter(id, adapterIds, connection, context); + adapterIds = f->filter(id, adapterIds, connection, context); } LocatorAdapterInfoSeq filteredAdpts; @@ -1247,10 +1272,10 @@ Database::getLocatorAdapterInfo(const string& id, bool Database::addAdapterSyncCallback(const string& id, - const SynchronizationCallbackPtr& callback, + const shared_ptr<SynchronizationCallback>& callback, const std::set<std::string>& excludes) { - Lock sync(*this); // Make sure this isn't call during an update. + lock_guard lock(_mutex); // Make sure this isn't call during an update. return _adapterCache.get(id)->addSyncCallback(callback, excludes); } @@ -1262,10 +1287,10 @@ Database::getAdapterInfo(const string& id) // server, if that's the case we get the adapter proxy from the // server. // - GetAdapterInfoResultPtr result; + shared_ptr<GetAdapterInfoResult> result; try { - Lock sync(*this); // Make sure this isn't call during an update. + lock_guard lock(_mutex); // Make sure this isn't call during an update. result = _adapterCache.get(id)->getAdapterInfoAsync(); } catch(const AdapterNotExistException&) @@ -1304,7 +1329,7 @@ Database::getAdapterInfo(const string& id) } AdapterInfoSeq -Database::getFilteredAdapterInfo(const string& id, const Ice::ConnectionPtr& con, const Ice::Context& ctx) +Database::getFilteredAdapterInfo(const string& id, const shared_ptr<Ice::Connection>& con, const Ice::Context& ctx) { // // First we check if the given adapter id is associated to a @@ -1314,13 +1339,13 @@ Database::getFilteredAdapterInfo(const string& id, const Ice::ConnectionPtr& con try { AdapterInfoSeq infos; - ReplicaGroupEntryPtr replicaGroup; + shared_ptr<ReplicaGroupEntry> replicaGroup; { - Lock sync(*this); // Make sure this isn't call during an update. + lock_guard lock(_mutex); // Make sure this isn't call during an update. - AdapterEntryPtr entry = _adapterCache.get(id); + auto entry = _adapterCache.get(id); infos = entry->getAdapterInfoNoEndpoints(); - replicaGroup = ReplicaGroupEntryPtr::dynamicCast(entry); + replicaGroup = dynamic_pointer_cast<ReplicaGroupEntry>(entry); } if(replicaGroup) { @@ -1365,8 +1390,8 @@ Database::getAdapterServer(const string& id) const { try { - Lock sync(*this); // Make sure this isn't call during an update. - ServerAdapterEntryPtr adapter = ServerAdapterEntryPtr::dynamicCast(_adapterCache.get(id)); + lock_guard lock(_mutex); // Make sure this isn't call during an update. + auto adapter = dynamic_pointer_cast<ServerAdapterEntry>(_adapterCache.get(id)); if(adapter) { return adapter->getServerId(); @@ -1383,7 +1408,7 @@ Database::getAdapterApplication(const string& id) const { try { - Lock sync(*this); // Make sure this isn't call during an update. + lock_guard lock(_mutex); // Make sure this isn't call during an update. return _adapterCache.get(id)->getApplication(); } catch(const AdapterNotExistException&) @@ -1397,8 +1422,8 @@ Database::getAdapterNode(const string& id) const { try { - Lock sync(*this); // Make sure this isn't call during an update. - ServerAdapterEntryPtr adapter = ServerAdapterEntryPtr::dynamicCast(_adapterCache.get(id)); + lock_guard lock(_mutex); // Make sure this isn't call during an update. + auto adapter = dynamic_pointer_cast<ServerAdapterEntry>(_adapterCache.get(id)); if(adapter) { return adapter->getNodeName(); @@ -1413,7 +1438,7 @@ Database::getAdapterNode(const string& id) const Ice::StringSeq Database::getAllAdapters(const string& expression) { - Lock sync(*this); + lock_guard lock(_mutex); vector<string> result; vector<string> ids = _adapterCache.getAll(expression); result.swap(ids); @@ -1456,7 +1481,7 @@ Database::addObject(const ObjectInfo& info) int serial = 0; { - Lock sync(*this); + lock_guard lock(_mutex); const Ice::Identity id = info.proxy->ice_getIdentity(); if(_objectCache.has(id)) @@ -1464,7 +1489,7 @@ Database::addObject(const ObjectInfo& info) throw ObjectExistsException(id); } - Ice::Long dbSerial = 0; + long long dbSerial = 0; try { IceDB::ReadWriteTxn txn(_env); @@ -1496,13 +1521,13 @@ Database::addObject(const ObjectInfo& info) } void -Database::addOrUpdateObject(const ObjectInfo& info, Ice::Long dbSerial) +Database::addOrUpdateObject(const ObjectInfo& info, long long dbSerial) { assert(dbSerial != 0 || _master); int serial = 0; // Initialize to prevent warning. { - Lock sync(*this); + lock_guard lock(_mutex); const Ice::Identity id = info.proxy->ice_getIdentity(); if(_objectCache.has(id)) @@ -1552,13 +1577,13 @@ Database::addOrUpdateObject(const ObjectInfo& info, Ice::Long dbSerial) } void -Database::removeObject(const Ice::Identity& id, Ice::Long dbSerial) +Database::removeObject(const Ice::Identity& id, long long dbSerial) { assert(dbSerial != 0 || _master); int serial = 0; // Initialize to prevent warning. { - Lock sync(*this); + lock_guard lock(_mutex); if(_objectCache.has(id)) { throw DeploymentException("removing object `" + _communicator->identityToString(id) + "' is not allowed:\n" @@ -1598,13 +1623,13 @@ Database::removeObject(const Ice::Identity& id, Ice::Long dbSerial) } void -Database::updateObject(const Ice::ObjectPrx& proxy) +Database::updateObject(const shared_ptr<Ice::ObjectPrx>& proxy) { assert(_master); int serial = 0; { - Lock sync(*this); + lock_guard lock(_mutex); const Ice::Identity id = proxy->ice_getIdentity(); if(_objectCache.has(id)) @@ -1649,19 +1674,19 @@ Database::updateObject(const Ice::ObjectPrx& proxy) int Database::addOrUpdateRegistryWellKnownObjects(const ObjectInfoSeq& objects) { - Lock sync(*this); + lock_guard lock(_mutex); try { IceDB::ReadWriteTxn txn(_env); - for(ObjectInfoSeq::const_iterator p = objects.begin(); p != objects.end(); ++p) + for(const auto& obj : objects) { - Ice::Identity id = p->proxy->ice_getIdentity(); + Ice::Identity id = obj.proxy->ice_getIdentity(); ObjectInfo info; if(_objects.get(txn, id, info)) { _objectsByType.del(txn, info.type, id); } - addObject(txn, *p, false); + addObject(txn, obj, false); } txn.commit(); } @@ -1677,13 +1702,13 @@ Database::addOrUpdateRegistryWellKnownObjects(const ObjectInfoSeq& objects) int Database::removeRegistryWellKnownObjects(const ObjectInfoSeq& objects) { - Lock sync(*this); + lock_guard lock(_mutex); try { IceDB::ReadWriteTxn txn(_env); - for(ObjectInfoSeq::const_iterator p = objects.begin(); p != objects.end(); ++p) + for(const auto& obj : objects) { - Ice::Identity id = p->proxy->ice_getIdentity(); + Ice::Identity id = obj.proxy->ice_getIdentity(); ObjectInfo info; if(_objects.get(txn, id, info)) { @@ -1701,7 +1726,7 @@ Database::removeRegistryWellKnownObjects(const ObjectInfoSeq& objects) return _objectObserverTopic->wellKnownObjectsRemoved(objects); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> Database::getObjectProxy(const Ice::Identity& id) { try @@ -1724,8 +1749,8 @@ Database::getObjectProxy(const Ice::Identity& id) return info.proxy; } -Ice::ObjectPrx -Database::getObjectByType(const string& type, const Ice::ConnectionPtr& con, const Ice::Context& ctx) +shared_ptr<Ice::ObjectPrx> +Database::getObjectByType(const string& type, const shared_ptr<Ice::Connection>& con, const Ice::Context& ctx) { Ice::ObjectProxySeq objs = getObjectsByType(type, con, ctx); if(objs.empty()) @@ -1735,9 +1760,9 @@ Database::getObjectByType(const string& type, const Ice::ConnectionPtr& con, con return objs[IceUtilInternal::random(static_cast<int>(objs.size()))]; } -Ice::ObjectPrx -Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample, const Ice::ConnectionPtr& con, - const Ice::Context& ctx) +shared_ptr<Ice::ObjectPrx> +Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample, + const shared_ptr<Ice::Connection>& con, const Ice::Context& ctx) { Ice::ObjectProxySeq objs = getObjectsByType(type, con, ctx); if(objs.empty()) @@ -1746,55 +1771,59 @@ Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample } IceUtilInternal::shuffle(objs.begin(), objs.end()); - vector<pair<Ice::ObjectPrx, float> > objectsWithLoad; + vector<pair<shared_ptr<Ice::ObjectPrx>, float>> objectsWithLoad; objectsWithLoad.reserve(objs.size()); - for(Ice::ObjectProxySeq::const_iterator p = objs.begin(); p != objs.end(); ++p) + for(const auto& obj : objs) { float load = 1.0f; - if(!(*p)->ice_getAdapterId().empty()) + if(!obj->ice_getAdapterId().empty()) { try { - load = _adapterCache.get((*p)->ice_getAdapterId())->getLeastLoadedNodeLoad(sample); + load = _adapterCache.get(obj->ice_getAdapterId())->getLeastLoadedNodeLoad(sample); } catch(const AdapterNotExistException&) { } } - objectsWithLoad.push_back(make_pair(*p, load)); + objectsWithLoad.push_back(make_pair(obj, load)); } - return min_element(objectsWithLoad.begin(), objectsWithLoad.end(), ObjectLoadCI())->first; + return min_element(objectsWithLoad.begin(), objectsWithLoad.end(), [](const auto& lhs, const auto& rhs) + { + return lhs.second < rhs.second; + })->first; } Ice::ObjectProxySeq -Database::getObjectsByType(const string& type, const Ice::ConnectionPtr& con, const Ice::Context& ctx) +Database::getObjectsByType(const string& type, const shared_ptr<Ice::Connection>& con, const Ice::Context& ctx) { Ice::ObjectProxySeq proxies; - vector<ObjectEntryPtr> objects = _objectCache.getObjectsByType(type); - for(vector<ObjectEntryPtr>::const_iterator q = objects.begin(); q != objects.end(); ++q) + auto objects = _objectCache.getObjectsByType(type); + + for(const auto& obj : objects) { - if(_nodeObserverTopic->isServerEnabled((*q)->getServer())) // Only return proxies from enabled servers. + if(_nodeObserverTopic->isServerEnabled(obj->getServer())) // Only return proxies from enabled servers. { - proxies.push_back((*q)->getProxy()); + proxies.push_back(obj->getProxy()); } } IceDB::ReadOnlyTxn txn(_env); vector<ObjectInfo> infos = findByType(txn, _objects, _objectsByType, type); - for(unsigned int i = 0; i < infos.size(); ++i) + for(const auto& info : infos) { - proxies.push_back(infos[i].proxy); + proxies.push_back(info.proxy); } if(con && !proxies.empty() && _pluginFacade->hasTypeFilters()) { - vector<TypeFilterPtr> filters = _pluginFacade->getTypeFilters(type); + auto filters = _pluginFacade->getTypeFilters(type); if(!filters.empty()) { - for(vector<TypeFilterPtr>::const_iterator p = filters.begin(); p != filters.end(); ++p) + for(const auto& filter: filters) { - proxies = (*p)->filter(type, proxies, con, ctx); + proxies = filter->filter(type, proxies, con, ctx); } } } @@ -1806,8 +1835,7 @@ Database::getObjectInfo(const Ice::Identity& id) { try { - ObjectEntryPtr object = _objectCache.get(id); - return object->getObjectInfo(); + return _objectCache.get(id)->getObjectInfo(); } catch(const ObjectNotRegisteredException&) { @@ -1859,7 +1887,7 @@ Database::getObjectInfosByType(const string& type) void Database::addInternalObject(const ObjectInfo& info, bool replace) { - Lock sync(*this); + lock_guard lock(_mutex); const Ice::Identity id = info.proxy->ice_getIdentity(); try @@ -1889,7 +1917,7 @@ Database::addInternalObject(const ObjectInfo& info, bool replace) void Database::removeInternalObject(const Ice::Identity& id) { - Lock sync(*this); + lock_guard lock(_mutex); try { @@ -1934,7 +1962,11 @@ Database::checkForAddition(const ApplicationHelper& app, const IceDB::ReadWriteT app.getIds(serverIds, adapterIds, objectIds); - for_each(serverIds.begin(), serverIds.end(), objFunc(*this, &Database::checkServerForAddition)); + for(const auto& serverId : serverIds) + { + checkServerForAddition(serverId); + } + if(!adapterIds.empty()) { for(set<string>::const_iterator p = adapterIds.begin(); p != adapterIds.end(); ++p) @@ -1953,7 +1985,10 @@ Database::checkForAddition(const ApplicationHelper& app, const IceDB::ReadWriteT set<string> repGrps; set<string> adptRepGrps; app.getReplicaGroups(repGrps, adptRepGrps); - for_each(adptRepGrps.begin(), adptRepGrps.end(), objFunc(*this, &Database::checkReplicaGroupExists)); + for(const auto& repGrp : adptRepGrps) + { + checkReplicaGroupExists(repGrp); + } } void @@ -1970,15 +2005,18 @@ Database::checkForUpdate(const ApplicationHelper& origApp, Ice::StringSeq addedSvrs; set_difference(newSvrs.begin(), newSvrs.end(), oldSvrs.begin(), oldSvrs.end(), back_inserter(addedSvrs)); - for_each(addedSvrs.begin(), addedSvrs.end(), objFunc(*this, &Database::checkServerForAddition)); + for(const auto& svr : addedSvrs) + { + checkServerForAddition(svr); + } Ice::StringSeq addedAdpts; set_difference(newAdpts.begin(), newAdpts.end(), oldAdpts.begin(), oldAdpts.end(), back_inserter(addedAdpts)); if(!addedAdpts.empty()) { - for(Ice::StringSeq::const_iterator p = addedAdpts.begin(); p != addedAdpts.end(); ++p) + for(const auto& adpt : addedAdpts) { - checkAdapterForAddition(*p, txn); + checkAdapterForAddition(adpt, txn); } } @@ -1986,9 +2024,9 @@ Database::checkForUpdate(const ApplicationHelper& origApp, set_difference(newObjs.begin(), newObjs.end(), oldObjs.begin(), oldObjs.end(), back_inserter(addedObjs)); if(!addedObjs.empty()) { - for(vector<Ice::Identity>::const_iterator p = addedObjs.begin(); p != addedObjs.end(); ++p) + for(const auto& obj : addedObjs) { - checkObjectForAddition(*p, txn); + checkObjectForAddition(obj, txn); } } @@ -1999,12 +2037,18 @@ Database::checkForUpdate(const ApplicationHelper& origApp, set<string> rmRepGrps; set_difference(oldRepGrps.begin(), oldRepGrps.end(), newRepGrps.begin(),newRepGrps.end(), set_inserter(rmRepGrps)); - for_each(rmRepGrps.begin(), rmRepGrps.end(), objFunc(*this, &Database::checkReplicaGroupForRemove)); + for(const auto& repGrp : rmRepGrps) + { + checkReplicaGroupForRemove(repGrp); + } set<string> addedAdptRepGrps; set_difference(newAdptRepGrps.begin(),newAdptRepGrps.end(), oldAdptRepGrps.begin(), oldAdptRepGrps.end(), set_inserter(addedAdptRepGrps)); - for_each(addedAdptRepGrps.begin(), addedAdptRepGrps.end(), objFunc(*this, &Database::checkReplicaGroupExists)); + for(const auto& repGrp : addedAdptRepGrps) + { + checkReplicaGroupExists(repGrp); + } vector<string> invalidAdptRepGrps; set_intersection(rmRepGrps.begin(), rmRepGrps.end(), newAdptRepGrps.begin(), newAdptRepGrps.end(), @@ -2021,7 +2065,11 @@ Database::checkForRemove(const ApplicationHelper& app) set<string> replicaGroups; set<string> adapterReplicaGroups; app.getReplicaGroups(replicaGroups, adapterReplicaGroups); - for_each(replicaGroups.begin(), replicaGroups.end(), objFunc(*this, &Database::checkReplicaGroupForRemove)); + + for(const auto& replicaGroup : replicaGroups) + { + checkReplicaGroupForRemove(replicaGroup); + } } void @@ -2088,10 +2136,10 @@ Database::checkObjectForAddition(const Ice::Identity& objectId, void Database::checkReplicaGroupExists(const string& replicaGroup) { - ReplicaGroupEntryPtr entry; + shared_ptr<ReplicaGroupEntry> entry; try { - entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(replicaGroup)); + entry = dynamic_pointer_cast<ReplicaGroupEntry>(_adapterCache.get(replicaGroup)); } catch(const AdapterNotExistException&) { @@ -2106,10 +2154,10 @@ Database::checkReplicaGroupExists(const string& replicaGroup) void Database::checkReplicaGroupForRemove(const string& replicaGroup) { - ReplicaGroupEntryPtr entry; + shared_ptr<ReplicaGroupEntry> entry; try { - entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(replicaGroup)); + entry = dynamic_pointer_cast<ReplicaGroupEntry>(_adapterCache.get(replicaGroup)); } catch(const AdapterNotExistException&) { @@ -2137,53 +2185,50 @@ Database::load(const ApplicationHelper& app, ServerEntrySeq& entries, const stri { const NodeDescriptorDict& nodes = app.getInstance().nodes; const string application = app.getInstance().name; - for(NodeDescriptorDict::const_iterator n = nodes.begin(); n != nodes.end(); ++n) + for(const auto& node : nodes) { - _nodeCache.get(n->first, true)->addDescriptor(application, n->second); + _nodeCache.get(node.first, true)->addDescriptor(application, node.second); } const ReplicaGroupDescriptorSeq& adpts = app.getInstance().replicaGroups; - for(ReplicaGroupDescriptorSeq::const_iterator r = adpts.begin(); r != adpts.end(); ++r) + for(const auto& adpt : adpts) { - assert(!r->id.empty()); - _adapterCache.addReplicaGroup(*r, application); - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + assert(!adpt.id.empty()); + _adapterCache.addReplicaGroup(adpt, application); + for(const auto& obj : adpt.objects) { - _objectCache.add(toObjectInfo(_communicator, *o, r->id), application, ""); + _objectCache.add(toObjectInfo(_communicator, obj, adpt.id), application, ""); } } - map<string, ServerInfo> servers = app.getServerInfos(uuid, revision); - for(map<string, ServerInfo>::const_iterator p = servers.begin(); p != servers.end(); ++p) + for(const auto& server : app.getServerInfos(uuid, revision)) { - entries.push_back(_serverCache.add(p->second)); + entries.push_back(_serverCache.add(server.second)); } } void Database::unload(const ApplicationHelper& app, ServerEntrySeq& entries) { - map<string, ServerInfo> servers = app.getServerInfos("", 0); - for(map<string, ServerInfo>::const_iterator p = servers.begin(); p != servers.end(); ++p) + for(const auto& server : app.getServerInfos("", 0)) { - entries.push_back(_serverCache.remove(p->first, false)); + entries.push_back(_serverCache.remove(server.first, false)); } - const ReplicaGroupDescriptorSeq& adpts = app.getInstance().replicaGroups; - for(ReplicaGroupDescriptorSeq::const_iterator r = adpts.begin(); r != adpts.end(); ++r) + for(const auto& adpt : app.getInstance().replicaGroups) { - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + for(ObjectDescriptorSeq::const_iterator o = adpt.objects.begin(); o != adpt.objects.end(); ++o) { _objectCache.remove(o->id); } - _adapterCache.removeReplicaGroup(r->id); + _adapterCache.removeReplicaGroup(adpt.id); } const NodeDescriptorDict& nodes = app.getInstance().nodes; const string application = app.getInstance().name; - for(NodeDescriptorDict::const_iterator n = nodes.begin(); n != nodes.end(); ++n) + for(const auto& node : nodes) { - _nodeCache.get(n->first)->removeDescriptor(application); + _nodeCache.get(node.first)->removeDescriptor(application); } } @@ -2200,8 +2245,8 @@ Database::reload(const ApplicationHelper& oldApp, // // Remove destroyed servers. // - map<string, ServerInfo> oldServers = oldApp.getServerInfos(uuid, revision); - map<string, ServerInfo> newServers = newApp.getServerInfos(uuid, revision); + auto oldServers = oldApp.getServerInfos(uuid, revision); + auto newServers = newApp.getServerInfos(uuid, revision); vector<pair<bool, ServerInfo> > load; for(map<string, ServerInfo>::const_iterator p = newServers.begin(); p != newServers.end(); ++p) { @@ -2217,7 +2262,7 @@ Database::reload(const ApplicationHelper& oldApp, } else { - ServerEntryPtr server = _serverCache.get(p->first); + auto server = _serverCache.get(p->first); server->update(q->second, noRestart); // Just update the server revision on the node. entries.push_back(server); } @@ -2281,7 +2326,7 @@ Database::reload(const ApplicationHelper& oldApp, { try { - ReplicaGroupEntryPtr entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(r->id)); + auto entry = dynamic_pointer_cast<ReplicaGroupEntry>(_adapterCache.get(r->id)); assert(entry); entry->update(application, r->loadBalancing, r->filter); } @@ -2312,16 +2357,16 @@ Database::reload(const ApplicationHelper& oldApp, } } -Ice::Long -Database::saveApplication(const ApplicationInfo& info, const IceDB::ReadWriteTxn& txn, Ice::Long dbSerial) +long long +Database::saveApplication(const ApplicationInfo& info, const IceDB::ReadWriteTxn& txn, long long dbSerial) { assert(dbSerial != 0 || _master); _applications.put(txn, info.descriptor.name, info); return updateSerial(txn, applicationsDbName, dbSerial); } -Ice::Long -Database::removeApplication(const string& name, const IceDB::ReadWriteTxn& txn, Ice::Long dbSerial) +long long +Database::removeApplication(const string& name, const IceDB::ReadWriteTxn& txn, long long dbSerial) { assert(dbSerial != 0 || _master); _applications.del(txn, name); @@ -2343,21 +2388,21 @@ Database::checkUpdate(const ApplicationHelper& oldApp, map<string, ServerInfo>::const_iterator p; vector<string> servers; vector<string> reasons; - vector<CheckUpdateResultPtr> results; + vector<shared_ptr<CheckUpdateResult>> results; set<string> unreachableNodes; if(noRestart) { for(p = oldServers.begin(); p != oldServers.end(); ++p) { - map<string, ServerInfo>::const_iterator q = newServers.find(p->first); + auto q = newServers.find(p->first); if(q == newServers.end()) { try { - ServerInfo info = p->second; + auto info = p->second; info.descriptor = 0; // Clear the descriptor to indicate removal. - CheckUpdateResultPtr result = _serverCache.get(p->first)->checkUpdate(info, true); + auto result = _serverCache.get(p->first)->checkUpdate(info, true); if(result) { results.push_back(result); @@ -2378,7 +2423,7 @@ Database::checkUpdate(const ApplicationHelper& oldApp, for(p = newServers.begin(); p != newServers.end(); ++p) { - map<string, ServerInfo>::const_iterator q = oldServers.find(p->first); + auto q = oldServers.find(p->first); if(q != oldServers.end() && isServerUpdated(p->second, q->second)) { if(noRestart && @@ -2400,7 +2445,7 @@ Database::checkUpdate(const ApplicationHelper& oldApp, // try { - CheckUpdateResultPtr result = _serverCache.get(p->first)->checkUpdate(p->second, noRestart); + auto result = _serverCache.get(p->first)->checkUpdate(p->second, noRestart); if(result) { results.push_back(result); @@ -2419,11 +2464,11 @@ Database::checkUpdate(const ApplicationHelper& oldApp, } } - for(vector<CheckUpdateResultPtr>::const_iterator q = results.begin(); q != results.end(); ++q) + for(const auto& result : results) { try { - (*q)->getResult(); + result->getResult(); } catch(const NodeUnreachableException& ex) { @@ -2431,7 +2476,7 @@ Database::checkUpdate(const ApplicationHelper& oldApp, } catch(const DeploymentException& ex) { - servers.push_back((*q)->getServer()); + servers.push_back(result->getServer()); reasons.push_back(ex.reason); } } @@ -2446,15 +2491,9 @@ Database::checkUpdate(const ApplicationHelper& oldApp, out << "check for application `" << application << "' update failed:"; if(!unreachableNodes.empty()) { -#if defined(__SUNPRO_CC) && defined(_RWSTD_NO_MEMBER_TEMPLATES) - Ice::StringSeq nodes; - for(set<string>::const_iterator r = unreachableNodes.begin(); r != unreachableNodes.end(); ++r) - { - nodes.push_back(*r); - } -#else + Ice::StringSeq nodes(unreachableNodes.begin(), unreachableNodes.end()); -#endif + if(nodes.size() == 1) { out << "\nthe node `" << nodes[0] << "' is down"; @@ -2488,15 +2527,7 @@ Database::checkUpdate(const ApplicationHelper& oldApp, } if(!unreachableNodes.empty()) { -#if defined(__SUNPRO_CC) && defined(_RWSTD_NO_MEMBER_TEMPLATES) - Ice::StringSeq nodes; - for(set<string>::const_iterator r = unreachableNodes.begin(); r != unreachableNodes.end(); ++r) - { - nodes.push_back(*r); - } -#else Ice::StringSeq nodes(unreachableNodes.begin(), unreachableNodes.end()); -#endif if(nodes.size() == 1) { os << "\nthe node `" << nodes[0] << "' is down"; @@ -2541,14 +2572,17 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, checkUpdate(previousAppHelper, appHelper, oldApp.uuid, oldApp.revision, noRestart); } - Lock sync(*this); + lock_guard lock(_mutex); IceDB::ReadWriteTxn txn(_env); checkForUpdate(previousAppHelper, appHelper, txn); reload(previousAppHelper, appHelper, entries, oldApp.uuid, oldApp.revision + 1, noRestart); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for(const auto& entry : entries) + { + entry->sync(); + } ApplicationInfo info = oldApp; info.updateTime = update.updateTime; @@ -2579,8 +2613,8 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, // for the nodes to start servers. // { - Lock sync(*this); - vector<UpdateInfo>::iterator p = find(_updating.begin(), _updating.end(), update.descriptor.name); + lock_guard lock(_mutex); + auto p = find(_updating.begin(), _updating.end(), update.descriptor.name); assert(p != _updating.end()); p->markUpdated(); } @@ -2605,7 +2639,7 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, { ApplicationUpdateInfo newUpdate; { - Lock sync(*this); + lock_guard lock(_mutex); entries.clear(); ApplicationHelper previous(_communicator, newDesc); ApplicationHelper helper(_communicator, oldApp.descriptor); @@ -2635,12 +2669,20 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, assert(p != _updating.end()); p->unmarkUpdated(); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for(const auto& entry : entries) + { + entry->sync(); + } serial = _applicationObserverTopic->applicationUpdated(dbSerial, newUpdate); } _applicationObserverTopic->waitForSyncedSubscribers(serial); // Wait for subscriber to be updated. - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitForSyncNoThrow)); + + for(const auto& entry : entries) + { + entry->waitForSyncNoThrow(); + } + finishUpdating(newDesc.name); throw; } @@ -2655,12 +2697,9 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, } void -Database::waitForUpdate(const string& name) +Database::waitForUpdate(unique_lock<mutex>& lock, const string& name) { - while(find(_updating.begin(), _updating.end(), name) != _updating.end()) - { - wait(); - } + _condVar.wait(lock, [this, &name] { return find(_updating.begin(), _updating.end(), name) == _updating.end(); }); } void @@ -2674,25 +2713,25 @@ Database::startUpdating(const string& name, const string& uuid, int revision) void Database::finishUpdating(const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); vector<UpdateInfo>::iterator p = find(_updating.begin(), _updating.end(), name); assert(p != _updating.end()); p->markUpdated(); _updating.erase(p); - notifyAll(); + _condVar.notify_all(); } -Ice::Long +long long Database::getSerial(const IceDB::Txn& txn, const string& dbName) { - Ice::Long serial = 1; + long long serial = 1; _serials.get(txn, dbName, serial); return serial; } -Ice::Long -Database::updateSerial(const IceDB::ReadWriteTxn& txn, const string& dbName, Ice::Long serial) +long long +Database::updateSerial(const IceDB::ReadWriteTxn& txn, const string& dbName, long long serial) { if(serial == -1) // The master we are talking to doesn't support serials (old IceGrid versions) { diff --git a/cpp/src/IceGrid/Database.h b/cpp/src/IceGrid/Database.h index 877f1d25a6f..f1e032be3c3 100644 --- a/cpp/src/IceGrid/Database.h +++ b/cpp/src/IceGrid/Database.h @@ -5,8 +5,6 @@ #ifndef ICE_GRID_DATABASE_H #define ICE_GRID_DATABASE_H -#include <IceUtil/Mutex.h> -#include <IceUtil/Shared.h> #include <IceUtil/FileUtil.h> #include <Ice/CommunicatorF.h> #include <IceGrid/Admin.h> @@ -25,126 +23,117 @@ namespace IceGrid { -class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - +class AdminSessionI; +class ApplicationHelper; class NodeSessionI; -typedef IceUtil::Handle<NodeSessionI> NodeSessionIPtr; - class ReplicaSessionI; -typedef IceUtil::Handle<ReplicaSessionI> ReplicaSessionIPtr; - -class AdminSessionI; - class ServerEntry; -typedef IceUtil::Handle<ServerEntry> ServerEntryPtr; - -class ApplicationHelper; - -typedef IceDB::Dbi<std::string, IceGrid::ApplicationInfo, IceDB::IceContext, Ice::OutputStream> - StringApplicationInfoMap; - -typedef IceDB::Dbi<Ice::Identity, IceGrid::ObjectInfo, IceDB::IceContext, Ice::OutputStream> IdentityObjectInfoMap; -typedef IceDB::Dbi<std::string, Ice::Identity, IceDB::IceContext, Ice::OutputStream> StringIdentityMap; - -typedef IceDB::Dbi<std::string, IceGrid::AdapterInfo, IceDB::IceContext, Ice::OutputStream> StringAdapterInfoMap; -typedef IceDB::Dbi<std::string, std::string, IceDB::IceContext, Ice::OutputStream> StringStringMap; - -typedef IceDB::Dbi<std::string, Ice::Long, IceDB::IceContext, Ice::OutputStream> StringLongMap; +class TraceLevels; -class Database : public IceUtil::Shared, public IceUtil::Monitor<IceUtil::Mutex> +using StringApplicationInfoMap = IceDB::Dbi<std::string, + IceGrid::ApplicationInfo, + IceDB::IceContext, Ice::OutputStream>; +using IdentityObjectInfoMap = IceDB::Dbi<Ice::Identity, + IceGrid::ObjectInfo, + IceDB::IceContext, + Ice::OutputStream>; +using StringIdentityMap = IceDB::Dbi<std::string, Ice::Identity, IceDB::IceContext, Ice::OutputStream>; +using StringAdapterInfoMap = IceDB::Dbi<std::string, IceGrid::AdapterInfo, IceDB::IceContext, Ice::OutputStream>; +using StringStringMap = IceDB::Dbi<std::string, std::string, IceDB::IceContext, Ice::OutputStream>; +using StringLongMap = IceDB::Dbi<std::string, Ice::Long, IceDB::IceContext, Ice::OutputStream>; + +class Database final { public: -#ifdef __SUNPRO_CC - using IceUtil::Monitor<IceUtil::Mutex>::lock; - using IceUtil::Monitor<IceUtil::Mutex>::unlock; -#endif - - Database(const Ice::ObjectAdapterPtr&, const IceStorm::TopicManagerPrx&, const std::string&, const TraceLevelsPtr&, - const RegistryInfo&, bool); + static std::shared_ptr<Database> + create(const std::shared_ptr<Ice::ObjectAdapter>&, const std::shared_ptr<IceStorm::TopicManagerPrx>&, + const std::string&, const std::shared_ptr<TraceLevels>&, const RegistryInfo&, bool); std::string getInstanceName() const; bool isReadOnly() const { return _readonly; } - const TraceLevelsPtr& getTraceLevels() const { return _traceLevels; } - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } - const Ice::ObjectAdapterPtr& getInternalAdapter() { return _internalAdapter; } + const std::shared_ptr<TraceLevels>& getTraceLevels() const { return _traceLevels; } + const std::shared_ptr<Ice::Communicator>& getCommunicator() const { return _communicator; } + const std::shared_ptr<Ice::ObjectAdapter>& getInternalAdapter() { return _internalAdapter; } void destroy(); - ObserverTopicPtr getObserverTopic(TopicName) const; + std::shared_ptr<ObserverTopic> getObserverTopic(TopicName) const; int lock(AdminSessionI*, const std::string&); void unlock(AdminSessionI*); - void syncApplications(const ApplicationInfoSeq&, Ice::Long); - void syncAdapters(const AdapterInfoSeq&, Ice::Long); - void syncObjects(const ObjectInfoSeq&, Ice::Long); + void syncApplications(const ApplicationInfoSeq&, long long); + void syncAdapters(const AdapterInfoSeq&, long long); + void syncObjects(const ObjectInfoSeq&, long long); - ApplicationInfoSeq getApplications(Ice::Long&); - AdapterInfoSeq getAdapters(Ice::Long&); - ObjectInfoSeq getObjects(Ice::Long&); + ApplicationInfoSeq getApplications(long long&); + AdapterInfoSeq getAdapters(long long&); + ObjectInfoSeq getObjects(long long&); StringLongDict getSerials() const; - void addApplication(const ApplicationInfo&, AdminSessionI*, Ice::Long = 0); - void updateApplication(const ApplicationUpdateInfo&, bool, AdminSessionI*, Ice::Long = 0); + void addApplication(const ApplicationInfo&, AdminSessionI*, long long = 0); + void updateApplication(const ApplicationUpdateInfo&, bool, AdminSessionI*, long long = 0); void syncApplicationDescriptor(const ApplicationDescriptor&, bool, AdminSessionI*); void instantiateServer(const std::string&, const std::string&, const ServerInstanceDescriptor&, AdminSessionI*); - void removeApplication(const std::string&, AdminSessionI*, Ice::Long = 0); + void removeApplication(const std::string&, AdminSessionI*, long long = 0); ApplicationInfo getApplicationInfo(const std::string&); Ice::StringSeq getAllApplications(const std::string& = std::string()); - void waitForApplicationUpdate(const AMD_NodeSession_waitForApplicationUpdatePtr&, const std::string&, int); + void waitForApplicationUpdate(const std::string&, int, std::function<void()>, + std::function<void(std::exception_ptr)>); NodeCache& getNodeCache(); - NodeEntryPtr getNode(const std::string&, bool = false) const; + std::shared_ptr<NodeEntry> getNode(const std::string&, bool = false) const; ReplicaCache& getReplicaCache(); - ReplicaEntryPtr getReplica(const std::string&) const; + std::shared_ptr<ReplicaEntry> getReplica(const std::string&) const; ServerCache& getServerCache(); - ServerEntryPtr getServer(const std::string&) const; + std::shared_ptr<ServerEntry> getServer(const std::string&) const; AllocatableObjectCache& getAllocatableObjectCache(); - AllocatableObjectEntryPtr getAllocatableObject(const Ice::Identity&) const; + std::shared_ptr<AllocatableObjectEntry> getAllocatableObject(const Ice::Identity&) const; - void setAdapterDirectProxy(const std::string&, const std::string&, const Ice::ObjectPrx&, Ice::Long = 0); - Ice::ObjectPrx getAdapterDirectProxy(const std::string&, const Ice::EncodingVersion&, const Ice::ConnectionPtr&, - const Ice::Context&); + void setAdapterDirectProxy(const std::string&, const std::string&, const std::shared_ptr<Ice::ObjectPrx>&, + long long = 0); + std::shared_ptr<Ice::ObjectPrx> getAdapterDirectProxy(const std::string&, const Ice::EncodingVersion&, + const std::shared_ptr<Ice::Connection>&, + const Ice::Context&); void removeAdapter(const std::string&); - AdapterPrx getAdapterProxy(const std::string&, const std::string&, bool); - void getLocatorAdapterInfo(const std::string&, const Ice::ConnectionPtr&, const Ice::Context&, + std::shared_ptr<AdapterPrx> getAdapterProxy(const std::string&, const std::string&, bool); + void getLocatorAdapterInfo(const std::string&, const std::shared_ptr<Ice::Connection>&, const Ice::Context&, LocatorAdapterInfoSeq&, int&, bool&, bool&, const std::set<std::string>& = std::set<std::string>()); - bool addAdapterSyncCallback(const std::string&, const SynchronizationCallbackPtr&, + bool addAdapterSyncCallback(const std::string&, const std::shared_ptr<SynchronizationCallback>&, const std::set<std::string>& = std::set<std::string>()); - std::vector<std::pair<std::string, AdapterPrx> > getAdapters(const std::string&, int&, bool&); + std::vector<std::pair<std::string, std::shared_ptr<AdapterPrx>>> getAdapters(const std::string&, int&, bool&); AdapterInfoSeq getAdapterInfo(const std::string&); - AdapterInfoSeq getFilteredAdapterInfo(const std::string&, const Ice::ConnectionPtr&, const Ice::Context&); + AdapterInfoSeq getFilteredAdapterInfo(const std::string&, const std::shared_ptr<Ice::Connection>&, const Ice::Context&); std::string getAdapterServer(const std::string&) const; std::string getAdapterApplication(const std::string&) const; std::string getAdapterNode(const std::string&) const; Ice::StringSeq getAllAdapters(const std::string& = std::string()); void addObject(const ObjectInfo&); - void addOrUpdateObject(const ObjectInfo&, Ice::Long = 0); - void removeObject(const Ice::Identity&, Ice::Long = 0); - void updateObject(const Ice::ObjectPrx&); + void addOrUpdateObject(const ObjectInfo&, long long = 0); + void removeObject(const Ice::Identity&, long long = 0); + void updateObject(const std::shared_ptr<Ice::ObjectPrx>&); int addOrUpdateRegistryWellKnownObjects(const ObjectInfoSeq&); int removeRegistryWellKnownObjects(const ObjectInfoSeq&); - Ice::ObjectPrx getObjectProxy(const Ice::Identity&); - Ice::ObjectPrx getObjectByType(const std::string&, - const Ice::ConnectionPtr& = Ice::ConnectionPtr(), - const Ice::Context& = Ice::Context()); - Ice::ObjectPrx getObjectByTypeOnLeastLoadedNode(const std::string&, LoadSample, - const Ice::ConnectionPtr& = Ice::ConnectionPtr(), + std::shared_ptr<Ice::ObjectPrx> getObjectProxy(const Ice::Identity&); + std::shared_ptr<Ice::ObjectPrx> getObjectByType(const std::string&, + const std::shared_ptr<Ice::Connection>& = nullptr, const Ice::Context& = Ice::Context()); + std::shared_ptr<Ice::ObjectPrx> getObjectByTypeOnLeastLoadedNode(const std::string&, LoadSample, + const std::shared_ptr<Ice::Connection>& = nullptr, + const Ice::Context& = Ice::Context()); Ice::ObjectProxySeq getObjectsByType(const std::string&, - const Ice::ConnectionPtr& = Ice::ConnectionPtr(), + const std::shared_ptr<Ice::Connection>& = nullptr, const Ice::Context& = Ice::Context()); ObjectInfo getObjectInfo(const Ice::Identity&); ObjectInfoSeq getObjectInfosByType(const std::string&); @@ -156,6 +145,9 @@ public: private: + Database(const std::shared_ptr<Ice::ObjectAdapter>&, const std::shared_ptr<IceStorm::TopicManagerPrx>&, + const std::string&, const std::shared_ptr<TraceLevels>&, const RegistryInfo&, bool); + void checkForAddition(const ApplicationHelper&, const IceDB::ReadWriteTxn&); void checkForUpdate(const ApplicationHelper&, const ApplicationHelper&, const IceDB::ReadWriteTxn&); void checkForRemove(const ApplicationHelper&); @@ -172,20 +164,20 @@ private: void checkUpdate(const ApplicationHelper&, const ApplicationHelper&, const std::string&, int, bool); - Ice::Long saveApplication(const ApplicationInfo&, const IceDB::ReadWriteTxn&, Ice::Long = 0); - Ice::Long removeApplication(const std::string&, const IceDB::ReadWriteTxn&, Ice::Long = 0); + long long saveApplication(const ApplicationInfo&, const IceDB::ReadWriteTxn&, long long = 0); + long long removeApplication(const std::string&, const IceDB::ReadWriteTxn&, long long = 0); void finishApplicationUpdate(const ApplicationUpdateInfo&, const ApplicationInfo&, const ApplicationHelper&, - const ApplicationHelper&, AdminSessionI*, bool, Ice::Long = 0); + const ApplicationHelper&, AdminSessionI*, bool, long long = 0); void checkSessionLock(AdminSessionI*); - void waitForUpdate(const std::string&); + void waitForUpdate(std::unique_lock<std::mutex>&, const std::string&); void startUpdating(const std::string&, const std::string&, int); void finishUpdating(const std::string&); - Ice::Long getSerial(const IceDB::Txn&, const std::string&); - Ice::Long updateSerial(const IceDB::ReadWriteTxn&, const std::string&, Ice::Long = 0); + long long getSerial(const IceDB::Txn&, const std::string&); + long long updateSerial(const IceDB::ReadWriteTxn&, const std::string&, long long = 0); void addAdapter(const IceDB::ReadWriteTxn&, const AdapterInfo&); void deleteAdapter(const IceDB::ReadWriteTxn&, const AdapterInfo&); @@ -201,11 +193,11 @@ private: static const std::string _adapterDbName; static const std::string _replicaGroupDbName; - const Ice::CommunicatorPtr _communicator; - const Ice::ObjectAdapterPtr _internalAdapter; - const IceStorm::TopicManagerPrx _topicManager; + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<Ice::ObjectAdapter> _internalAdapter; + const std::shared_ptr<IceStorm::TopicManagerPrx> _topicManager; const std::string _instanceName; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr<TraceLevels> _traceLevels; const bool _master; const bool _readonly; @@ -216,11 +208,11 @@ private: AllocatableObjectCache _allocatableObjectCache; ServerCache _serverCache; - RegistryObserverTopicPtr _registryObserverTopic; - NodeObserverTopicPtr _nodeObserverTopic; - ApplicationObserverTopicPtr _applicationObserverTopic; - AdapterObserverTopicPtr _adapterObserverTopic; - ObjectObserverTopicPtr _objectObserverTopic; + std::shared_ptr<RegistryObserverTopic> _registryObserverTopic; + std::shared_ptr<NodeObserverTopic> _nodeObserverTopic; + std::shared_ptr<ApplicationObserverTopic> _applicationObserverTopic; + std::shared_ptr<AdapterObserverTopic> _adapterObserverTopic; + std::shared_ptr<ObjectObserverTopic> _objectObserverTopic; IceUtilInternal::FileLock _dbLock; IceDB::Env _env; @@ -238,7 +230,7 @@ private: StringLongMap _serials; - RegistryPluginFacadeIPtr _pluginFacade; + std::shared_ptr<RegistryPluginFacadeI> _pluginFacade; AdminSessionI* _lock; std::string _lockUserId; @@ -248,7 +240,7 @@ private: std::string name; std::string uuid; int revision; - std::vector<AMD_NodeSession_waitForApplicationUpdatePtr> cbs; + std::vector<std::pair<std::function<void()>, std::function<void(std::exception_ptr)>>> cbs; bool updated; UpdateInfo(const std::string& n, const std::string& u, int r) : @@ -268,10 +260,9 @@ private: void markUpdated() { updated = true; - std::vector<AMD_NodeSession_waitForApplicationUpdatePtr>::const_iterator q; - for(q = cbs.begin(); q != cbs.end(); ++q) + for(const auto& cb: cbs) { - (*q)->ice_response(); + cb.first(); } cbs.clear(); } @@ -282,9 +273,11 @@ private: } }; std::vector<UpdateInfo> _updating; -}; -typedef IceUtil::Handle<Database> DatabasePtr; + mutable std::mutex _mutex; + std::condition_variable _condVar; }; +} + #endif diff --git a/cpp/src/IceGrid/DescriptorBuilder.cpp b/cpp/src/IceGrid/DescriptorBuilder.cpp index 472af859692..f96619368c0 100644 --- a/cpp/src/IceGrid/DescriptorBuilder.cpp +++ b/cpp/src/IceGrid/DescriptorBuilder.cpp @@ -13,7 +13,7 @@ using namespace std; using namespace IceGrid; XmlAttributesHelper::XmlAttributesHelper(const IceXML::Attributes& attrs, - const Ice::LoggerPtr& logger, + const shared_ptr<Ice::Logger>& logger, const string& filename, int line) : _attributes(attrs), @@ -215,7 +215,7 @@ PropertySetDescriptorBuilder::finish() return true; } -ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator, const XmlAttributesHelper& attrs, const map<string, string>& overrides) : _communicator(communicator), @@ -225,7 +225,7 @@ ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const Ice::Communicat _descriptor.variables = overrides; } -ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator, const ApplicationDescriptor& app, const XmlAttributesHelper& attrs, const map<string, string>& overrides) : @@ -264,7 +264,7 @@ ApplicationDescriptorBuilder::finishReplicaGroup() { if(!_descriptor.replicaGroups.back().loadBalancing) { - _descriptor.replicaGroups.back().loadBalancing = new RandomLoadBalancingPolicy(); + _descriptor.replicaGroups.back().loadBalancing = make_shared<RandomLoadBalancingPolicy>(); _descriptor.replicaGroups.back().loadBalancing->nReplicas = "0"; } } @@ -272,23 +272,23 @@ ApplicationDescriptorBuilder::finishReplicaGroup() void ApplicationDescriptorBuilder::setLoadBalancing(const XmlAttributesHelper& attrs) { - LoadBalancingPolicyPtr policy; + shared_ptr<LoadBalancingPolicy> policy; string type = attrs("type"); if(type == "random") { - policy = new RandomLoadBalancingPolicy(); + policy = make_shared<RandomLoadBalancingPolicy>(); } else if(type == "ordered") { - policy = new OrderedLoadBalancingPolicy(); + policy = make_shared<OrderedLoadBalancingPolicy>(); } else if(type == "round-robin") { - policy = new RoundRobinLoadBalancingPolicy(); + policy = make_shared<RoundRobinLoadBalancingPolicy>(); } else if(type == "adaptive") { - AdaptiveLoadBalancingPolicyPtr alb = new AdaptiveLoadBalancingPolicy(); + auto alb = make_shared<AdaptiveLoadBalancingPolicy>(); alb->loadSample = attrs("load-sample", "1"); policy = alb; } @@ -498,7 +498,7 @@ NodeDescriptorBuilder::addServerInstance(const ServerInstanceDescriptor& desc) } void -NodeDescriptorBuilder::addServer(const ServerDescriptorPtr& server) +NodeDescriptorBuilder::addServer(const shared_ptr<ServerDescriptor>& server) { _descriptor.servers.push_back(server); } @@ -544,7 +544,7 @@ TemplateDescriptorBuilder::addParameter(const XmlAttributesHelper& attrs) } void -TemplateDescriptorBuilder::setDescriptor(const CommunicatorDescriptorPtr& desc) +TemplateDescriptorBuilder::setDescriptor(const shared_ptr<CommunicatorDescriptor>& desc) { _descriptor.descriptor = desc; } @@ -579,13 +579,13 @@ TemplateDescriptorBuilder::createService(const XmlAttributesHelper& attrs) return new ServiceDescriptorBuilder(_application.getCommunicator(), attrs); } -CommunicatorDescriptorBuilder::CommunicatorDescriptorBuilder(const Ice::CommunicatorPtr& communicator) : +CommunicatorDescriptorBuilder::CommunicatorDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator) : _communicator(communicator) { } void -CommunicatorDescriptorBuilder::init(const CommunicatorDescriptorPtr& desc, const XmlAttributesHelper&) +CommunicatorDescriptorBuilder::init(const shared_ptr<CommunicatorDescriptor>& desc, const XmlAttributesHelper&) { _descriptor = desc; } @@ -644,7 +644,7 @@ CommunicatorDescriptorBuilder::addAdapter(const XmlAttributesHelper& attrs) else { string fqn = "${server}"; - if(ServiceDescriptorPtr::dynamicCast(_descriptor)) + if(dynamic_pointer_cast<ServiceDescriptor>(_descriptor)) { fqn += ".${service}"; } @@ -702,64 +702,6 @@ CommunicatorDescriptorBuilder::addAllocatable(const XmlAttributesHelper& attrs) } void -CommunicatorDescriptorBuilder::addDbEnv(const XmlAttributesHelper& attrs) -{ - DbEnvDescriptor desc; - desc.name = attrs("name"); - - DbEnvDescriptorSeq::iterator p; - for(p = _descriptor->dbEnvs.begin(); p != _descriptor->dbEnvs.end(); ++p) - { - // - // We are re-opening the dbenv element to define more properties. - // - if(p->name == desc.name) - { - break; - } - } - - if(p != _descriptor->dbEnvs.end()) - { - // - // Remove the previously defined dbenv, we'll add it back again when - // the dbenv element end tag is reached. - // - desc = *p; - _descriptor->dbEnvs.erase(p); - } - - if(desc.dbHome.empty()) - { - desc.dbHome = attrs("home", ""); - } - - _descriptor->dbEnvs.push_back(desc); -} - -void -CommunicatorDescriptorBuilder::addDbEnvProperty(const XmlAttributesHelper& attrs) -{ - if(!_descriptor->dbEnvs.back().dbHome.empty()) - { - throw invalid_argument("can't add property to the database environment:\n" - "properties are only allowed if the database\n" - "environment home directory is managed by the node"); - } - - PropertyDescriptor prop; - prop.name = attrs("name"); - prop.value = attrs("value", ""); - _descriptor->dbEnvs.back().properties.push_back(prop); -} - -void -CommunicatorDescriptorBuilder::setDbEnvDescription(const string& value) -{ - _descriptor->dbEnvs.back().description = value; -} - -void CommunicatorDescriptorBuilder::addLog(const XmlAttributesHelper& attrs) { if(attrs.contains("property")) @@ -802,20 +744,20 @@ ServiceInstanceDescriptorBuilder::addPropertySet(const PropertySetDescriptor& de p.properties.insert(p.properties.end(), desc.properties.begin(), desc.properties.end()); } -ServerDescriptorBuilder::ServerDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +ServerDescriptorBuilder::ServerDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator, const XmlAttributesHelper& attrs) : CommunicatorDescriptorBuilder(communicator) { - init(new ServerDescriptor(), attrs); + init(make_shared<ServerDescriptor>(), attrs); } -ServerDescriptorBuilder::ServerDescriptorBuilder(const Ice::CommunicatorPtr& communicator) : +ServerDescriptorBuilder::ServerDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator) : CommunicatorDescriptorBuilder(communicator) { } void -ServerDescriptorBuilder::init(const ServerDescriptorPtr& desc, const XmlAttributesHelper& attrs) +ServerDescriptorBuilder::init(const shared_ptr<ServerDescriptor>& desc, const XmlAttributesHelper& attrs) { CommunicatorDescriptorBuilder::init(desc, attrs); _descriptor = desc; @@ -855,7 +797,7 @@ ServerDescriptorBuilder::addEnv(const string& v) } void -ServerDescriptorBuilder::addService(const ServiceDescriptorPtr& /*desc*/) +ServerDescriptorBuilder::addService(const shared_ptr<ServiceDescriptor>& /*desc*/) { assert(false); } @@ -866,15 +808,15 @@ ServerDescriptorBuilder::addServiceInstance(const ServiceInstanceDescriptor& /*d assert(false); } -IceBoxDescriptorBuilder::IceBoxDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +IceBoxDescriptorBuilder::IceBoxDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator, const XmlAttributesHelper& attrs) : ServerDescriptorBuilder(communicator) { - init(new IceBoxDescriptor(), attrs); + init(make_shared<IceBoxDescriptor>(), attrs); } void -IceBoxDescriptorBuilder::init(const IceBoxDescriptorPtr& desc, const XmlAttributesHelper& attrs) +IceBoxDescriptorBuilder::init(const shared_ptr<IceBoxDescriptor>& desc, const XmlAttributesHelper& attrs) { ServerDescriptorBuilder::init(desc, attrs); _descriptor = desc; @@ -899,19 +841,13 @@ IceBoxDescriptorBuilder::addAdapter(const XmlAttributesHelper& /*attrs*/) } void -IceBoxDescriptorBuilder::addDbEnv(const XmlAttributesHelper& /*attrs*/) -{ - throw invalid_argument("<dbenv> element can't be a child of an <icebox> element"); -} - -void IceBoxDescriptorBuilder::addServiceInstance(const ServiceInstanceDescriptor& desc) { _descriptor->services.push_back(desc); } void -IceBoxDescriptorBuilder::addService(const ServiceDescriptorPtr& desc) +IceBoxDescriptorBuilder::addService(const shared_ptr<ServiceDescriptor>& desc) { ServiceInstanceDescriptor instance; assert(desc); @@ -919,15 +855,15 @@ IceBoxDescriptorBuilder::addService(const ServiceDescriptorPtr& desc) _descriptor->services.push_back(instance); } -ServiceDescriptorBuilder::ServiceDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +ServiceDescriptorBuilder::ServiceDescriptorBuilder(const shared_ptr<Ice::Communicator>& communicator, const XmlAttributesHelper& attrs) : CommunicatorDescriptorBuilder(communicator) { - init(new ServiceDescriptor(), attrs); + init(make_shared<ServiceDescriptor>(), attrs); } void -ServiceDescriptorBuilder::init(const ServiceDescriptorPtr& desc, const XmlAttributesHelper& attrs) +ServiceDescriptorBuilder::init(const shared_ptr<ServiceDescriptor>& desc, const XmlAttributesHelper& attrs) { CommunicatorDescriptorBuilder::init(desc, attrs); _descriptor = desc; diff --git a/cpp/src/IceGrid/DescriptorBuilder.h b/cpp/src/IceGrid/DescriptorBuilder.h index f58cf8e7a0e..02e9c397da3 100644 --- a/cpp/src/IceGrid/DescriptorBuilder.h +++ b/cpp/src/IceGrid/DescriptorBuilder.h @@ -10,13 +10,6 @@ #include <IceGrid/Descriptor.h> #include <set> -#ifdef __SUNPRO_CC -// -// We hide some init functions on purpose in classes below -// -# pragma error_messages(off,hidef) -#endif - namespace IceGrid { @@ -24,7 +17,7 @@ class XmlAttributesHelper { public: - XmlAttributesHelper(const IceXML::Attributes&, const Ice::LoggerPtr&, const std::string&, int); + XmlAttributesHelper(const IceXML::Attributes&, const std::shared_ptr<Ice::Logger>&, const std::string&, int); void checkUnknownAttributes(); bool contains(const std::string&) const; @@ -39,7 +32,7 @@ public: private: const IceXML::Attributes& _attributes; - const Ice::LoggerPtr _logger; + const std::shared_ptr<Ice::Logger> _logger; const std::string _filename; const int _line; @@ -52,7 +45,7 @@ class DescriptorBuilder { public: - virtual ~DescriptorBuilder() { } + virtual ~DescriptorBuilder() = default; virtual void addVariable(const XmlAttributesHelper&); }; @@ -89,10 +82,10 @@ class ApplicationDescriptorBuilder : public DescriptorBuilder { public: - ApplicationDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&, - const std::map<std::string, std::string>&); - ApplicationDescriptorBuilder(const Ice::CommunicatorPtr&, const ApplicationDescriptor&, const XmlAttributesHelper&, + ApplicationDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&, const XmlAttributesHelper&, const std::map<std::string, std::string>&); + ApplicationDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&, const ApplicationDescriptor&, + const XmlAttributesHelper&, const std::map<std::string, std::string>&); const ApplicationDescriptor& getDescriptor() const; @@ -117,11 +110,11 @@ public: bool isOverride(const std::string&); - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr<Ice::Communicator>& getCommunicator() const { return _communicator; } private: - Ice::CommunicatorPtr _communicator; + std::shared_ptr<Ice::Communicator> _communicator; ApplicationDescriptor _descriptor; std::map<std::string, std::string> _overrides; }; @@ -157,7 +150,7 @@ public: virtual PropertySetDescriptorBuilder* createPropertySet(const XmlAttributesHelper&) const; void addVariable(const XmlAttributesHelper&); - void addServer(const ServerDescriptorPtr&); + void addServer(const std::shared_ptr<ServerDescriptor>&); void addServerInstance(const ServerInstanceDescriptor&); void addPropertySet(const std::string&, const PropertySetDescriptor&); void setDescription(const std::string&); @@ -185,7 +178,7 @@ public: virtual ServiceDescriptorBuilder* createService(const XmlAttributesHelper&); void addParameter(const XmlAttributesHelper&); - void setDescriptor(const CommunicatorDescriptorPtr&); + void setDescriptor(const std::shared_ptr<CommunicatorDescriptor>&); const std::string& getId() const { return _id; } const TemplateDescriptor& getDescriptor() const { return _descriptor; } @@ -202,9 +195,9 @@ class CommunicatorDescriptorBuilder : public DescriptorBuilder { public: - CommunicatorDescriptorBuilder(const Ice::CommunicatorPtr&); + CommunicatorDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&); - void init(const CommunicatorDescriptorPtr&, const XmlAttributesHelper&); + void init(const std::shared_ptr<CommunicatorDescriptor>&, const XmlAttributesHelper&); virtual void finish(); virtual void setDescription(const std::string&); @@ -214,9 +207,6 @@ public: virtual void setAdapterDescription(const std::string&); virtual void addObject(const XmlAttributesHelper&); virtual void addAllocatable(const XmlAttributesHelper&); - virtual void addDbEnv(const XmlAttributesHelper&); - virtual void addDbEnvProperty(const XmlAttributesHelper&); - virtual void setDbEnvDescription(const std::string&); virtual void addLog(const XmlAttributesHelper&); virtual PropertySetDescriptorBuilder* createPropertySet() const; @@ -226,11 +216,11 @@ protected: void addProperty(PropertyDescriptorSeq&, const std::string&, const std::string&); PropertyDescriptorSeq _hiddenProperties; - Ice::CommunicatorPtr _communicator; + std::shared_ptr<Ice::Communicator> _communicator; private: - CommunicatorDescriptorPtr _descriptor; + std::shared_ptr<CommunicatorDescriptor> _descriptor; }; class ServiceInstanceDescriptorBuilder : public DescriptorBuilder @@ -252,65 +242,60 @@ class ServerDescriptorBuilder : public CommunicatorDescriptorBuilder { public: - ServerDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&); - ServerDescriptorBuilder(const Ice::CommunicatorPtr&); + ServerDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&, const XmlAttributesHelper&); + ServerDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&); - void init(const ServerDescriptorPtr&, const XmlAttributesHelper&); + void init(const std::shared_ptr<ServerDescriptor>&, const XmlAttributesHelper&); virtual ServiceDescriptorBuilder* createService(const XmlAttributesHelper&); virtual ServiceInstanceDescriptorBuilder* createServiceInstance(const XmlAttributesHelper&); virtual void addOption(const std::string&); virtual void addEnv(const std::string&); - virtual void addService(const ServiceDescriptorPtr&); + virtual void addService(const std::shared_ptr<ServiceDescriptor>&); virtual void addServiceInstance(const ServiceInstanceDescriptor&); - const ServerDescriptorPtr& getDescriptor() const { return _descriptor; } + const std::shared_ptr<ServerDescriptor>& getDescriptor() const { return _descriptor; } private: - ServerDescriptorPtr _descriptor; + std::shared_ptr<ServerDescriptor> _descriptor; }; class IceBoxDescriptorBuilder : public ServerDescriptorBuilder { public: - IceBoxDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&); + IceBoxDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&, const XmlAttributesHelper&); - void init(const IceBoxDescriptorPtr&, const XmlAttributesHelper&); + void init(const std::shared_ptr<IceBoxDescriptor>&, const XmlAttributesHelper&); virtual ServiceDescriptorBuilder* createService(const XmlAttributesHelper&); virtual ServiceInstanceDescriptorBuilder* createServiceInstance(const XmlAttributesHelper&); virtual void addAdapter(const XmlAttributesHelper&); - virtual void addDbEnv(const XmlAttributesHelper&); virtual void addServiceInstance(const ServiceInstanceDescriptor&); - virtual void addService(const ServiceDescriptorPtr&); + virtual void addService(const std::shared_ptr<ServiceDescriptor>&); private: - IceBoxDescriptorPtr _descriptor; + std::shared_ptr<IceBoxDescriptor> _descriptor; }; class ServiceDescriptorBuilder : public CommunicatorDescriptorBuilder { public: - ServiceDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&); - void init(const ServiceDescriptorPtr&, const XmlAttributesHelper&); + ServiceDescriptorBuilder(const std::shared_ptr<Ice::Communicator>&, const XmlAttributesHelper&); + void init(const std::shared_ptr<ServiceDescriptor>&, const XmlAttributesHelper&); - const ServiceDescriptorPtr& getDescriptor() const { return _descriptor; } + const std::shared_ptr<ServiceDescriptor>& getDescriptor() const { return _descriptor; } private: - ServiceDescriptorPtr _descriptor; + std::shared_ptr<ServiceDescriptor> _descriptor; }; } -#ifdef __SUNPRO_CC -# pragma error_messages(default,hidef) -#endif - #endif diff --git a/cpp/src/IceGrid/DescriptorHelper.cpp b/cpp/src/IceGrid/DescriptorHelper.cpp index 58ec1da1ec9..39cbcdebdef 100644 --- a/cpp/src/IceGrid/DescriptorHelper.cpp +++ b/cpp/src/IceGrid/DescriptorHelper.cpp @@ -13,42 +13,23 @@ using namespace IceUtil; using namespace IceUtilInternal; using namespace IceGrid; -#ifdef __SUNPRO_CC -// -// Disable warning about unassigned function objects -// -# pragma error_messages(off,unassigned) -#endif - -namespace IceGrid +namespace { -struct GetReplicaGroupId : unary_function<const ReplicaGroupDescriptor&, const string&> +const string& getReplicaGroupId(const ReplicaGroupDescriptor& desc) { - const string& - operator()(const ReplicaGroupDescriptor& desc) - { - return desc.id; - } -}; + return desc.id; +} -struct GetAdapterId : unary_function<const AdapterDescriptor&, const string&> +const string& getAdapterId(const AdapterDescriptor& desc) { - const string& - operator()(const AdapterDescriptor& desc) - { - return desc.id; - } -}; + return desc.id; +} -struct GetObjectId : unary_function<const ObjectDescriptor&, const Ice::Identity&> +const Ice::Identity& getObjectId(const ObjectDescriptor& desc) { - const Ice::Identity& - operator()(const ObjectDescriptor& desc) - { - return desc.id; - } -}; + return desc.id; +} template <typename GetKeyFunc, typename Seq, typename EqFunc> bool isSeqEqual(const Seq& lseq, const Seq& rseq, GetKeyFunc func, EqFunc eq = equal_to<typename Seq::value_type>()) @@ -76,162 +57,146 @@ isSeqEqual(const Seq& lseq, const Seq& rseq, GetKeyFunc func, EqFunc eq = equal_ return true; } -struct TemplateDescriptorEqual : std::binary_function<TemplateDescriptor&, TemplateDescriptor&, bool> +bool templateDescriptorEqual(const TemplateDescriptor& lhs, const TemplateDescriptor& rhs) { - bool - operator()(const TemplateDescriptor& lhs, const TemplateDescriptor& rhs) + if(lhs.parameters != rhs.parameters) { - if(lhs.parameters != rhs.parameters) - { - return false; - } + return false; + } - if(lhs.parameterDefaults != rhs.parameterDefaults) - { - return false; - } + if(lhs.parameterDefaults != rhs.parameterDefaults) + { + return false; + } + { + auto slhs = dynamic_pointer_cast<IceBoxDescriptor>(lhs.descriptor); + auto srhs = dynamic_pointer_cast<IceBoxDescriptor>(rhs.descriptor); + if(slhs && srhs) { - IceBoxDescriptorPtr slhs = IceBoxDescriptorPtr::dynamicCast(lhs.descriptor); - IceBoxDescriptorPtr srhs = IceBoxDescriptorPtr::dynamicCast(rhs.descriptor); - if(slhs && srhs) - { - return IceBoxHelper(slhs) == IceBoxHelper(srhs); - } + return IceBoxHelper(slhs) == IceBoxHelper(srhs); } + } + { + auto slhs = dynamic_pointer_cast<ServerDescriptor>(lhs.descriptor); + auto srhs = dynamic_pointer_cast<ServerDescriptor>(rhs.descriptor); + if(slhs && srhs) { - ServerDescriptorPtr slhs = ServerDescriptorPtr::dynamicCast(lhs.descriptor); - ServerDescriptorPtr srhs = ServerDescriptorPtr::dynamicCast(rhs.descriptor); - if(slhs && srhs) - { - return ServerHelper(slhs) == ServerHelper(srhs); - } + return ServerHelper(slhs) == ServerHelper(srhs); } + } + { + auto slhs = dynamic_pointer_cast<ServiceDescriptor>(lhs.descriptor); + auto srhs = dynamic_pointer_cast<ServiceDescriptor>(rhs.descriptor); + if(slhs && srhs) { - ServiceDescriptorPtr slhs = ServiceDescriptorPtr::dynamicCast(lhs.descriptor); - ServiceDescriptorPtr srhs = ServiceDescriptorPtr::dynamicCast(rhs.descriptor); - if(slhs && srhs) - { - return ServiceHelper(slhs) == ServiceHelper(srhs); - } + return ServiceHelper(slhs) == ServiceHelper(srhs); } - - return false; } -}; -struct ObjectDescriptorEq : std::binary_function<const ObjectDescriptor&, const ObjectDescriptor&, bool> + return false; +} + +bool objectDescriptorEqual(const ObjectDescriptor& lhs, const ObjectDescriptor& rhs) { - bool - operator()(const ObjectDescriptor& lhs, const ObjectDescriptor& rhs) + if(lhs.id != rhs.id) { - if(lhs.id != rhs.id) - { - return false; - } - if(lhs.type != rhs.type) - { - return false; - } - if(lhs.proxyOptions != rhs.proxyOptions) - { - return false; - } - return true; + return false; + } + if(lhs.type != rhs.type) + { + return false; + } + if(lhs.proxyOptions != rhs.proxyOptions) + { + return false; } -}; + return true; +} -struct AdapterEq : std::binary_function<const AdapterDescriptor&, const AdapterDescriptor&, bool> +bool adapterEqual(const AdapterDescriptor& lhs, const AdapterDescriptor& rhs) { - bool - operator()(const AdapterDescriptor& lhs, const AdapterDescriptor& rhs) + if(lhs.id != rhs.id) { - if(lhs.id != rhs.id) - { - return false; - } - if(lhs.name != rhs.name) - { - return false; - } - if(lhs.description != rhs.description) - { - return false; - } - if(lhs.replicaGroupId != rhs.replicaGroupId) - { - return false; - } - if(lhs.priority != rhs.priority) - { - return false; - } - if(lhs.registerProcess != rhs.registerProcess) - { - return false; - } - if(lhs.serverLifetime != rhs.serverLifetime) - { - return false; - } - if(!isSeqEqual(lhs.objects, rhs.objects, GetObjectId(), ObjectDescriptorEq())) - { - return false; - } - if(!isSeqEqual(lhs.allocatables, rhs.allocatables, GetObjectId(), ObjectDescriptorEq())) - { - return false; - } - return true; + return false; + } + if(lhs.name != rhs.name) + { + return false; + } + if(lhs.description != rhs.description) + { + return false; + } + if(lhs.replicaGroupId != rhs.replicaGroupId) + { + return false; } -}; + if(lhs.priority != rhs.priority) + { + return false; + } + if(lhs.registerProcess != rhs.registerProcess) + { + return false; + } + if(lhs.serverLifetime != rhs.serverLifetime) + { + return false; + } + if(!isSeqEqual(lhs.objects, rhs.objects, getObjectId, objectDescriptorEqual)) + { + return false; + } + if(!isSeqEqual(lhs.allocatables, rhs.allocatables, getObjectId, objectDescriptorEqual)) + { + return false; + } + return true; +} -struct ReplicaGroupEq : std::binary_function<const ReplicaGroupDescriptor&, const ReplicaGroupDescriptor&, bool> +bool replicaGroupEqual(const ReplicaGroupDescriptor& lhs, const ReplicaGroupDescriptor& rhs) { - bool - operator()(const ReplicaGroupDescriptor& lhs, const ReplicaGroupDescriptor& rhs) + if(lhs.id != rhs.id) { - if(lhs.id != rhs.id) - { - return false; - } - if(lhs.proxyOptions != rhs.proxyOptions) - { - return false; - } - if(lhs.filter != rhs.filter) + return false; + } + if(lhs.proxyOptions != rhs.proxyOptions) + { + return false; + } + if(lhs.filter != rhs.filter) + { + return false; + } + if(!isSeqEqual(lhs.objects, rhs.objects, getObjectId, objectDescriptorEqual)) + { + return false; + } + if(lhs.loadBalancing && rhs.loadBalancing) + { + if(lhs.loadBalancing->ice_id() != rhs.loadBalancing->ice_id()) { return false; } - if(!isSeqEqual(lhs.objects, rhs.objects, GetObjectId(), ObjectDescriptorEq())) + if(lhs.loadBalancing->nReplicas != rhs.loadBalancing->nReplicas) { return false; } - if(lhs.loadBalancing && rhs.loadBalancing) - { - if(lhs.loadBalancing->ice_id() != rhs.loadBalancing->ice_id()) - { - return false; - } - if(lhs.loadBalancing->nReplicas != rhs.loadBalancing->nReplicas) - { - return false; - } - AdaptiveLoadBalancingPolicyPtr alhs = AdaptiveLoadBalancingPolicyPtr::dynamicCast(lhs.loadBalancing); - AdaptiveLoadBalancingPolicyPtr arhs = AdaptiveLoadBalancingPolicyPtr::dynamicCast(rhs.loadBalancing); - if(alhs && arhs && alhs->loadSample != arhs->loadSample) - { - return false; - } - } - else if(lhs.loadBalancing || rhs.loadBalancing) + auto alhs = dynamic_pointer_cast<AdaptiveLoadBalancingPolicy>(lhs.loadBalancing); + auto arhs = dynamic_pointer_cast<AdaptiveLoadBalancingPolicy>(rhs.loadBalancing); + if(alhs && arhs && alhs->loadSample != arhs->loadSample) { return false; } - - return true; } -}; + else if(lhs.loadBalancing || rhs.loadBalancing) + { + return false; + } + + return true; +} template <typename GetKeyFunc, typename Seq> Seq getSeqUpdatedElts(const Seq& lseq, const Seq& rseq, GetKeyFunc func) @@ -383,7 +348,7 @@ validateProxyOptions(const Resolver& resolver, const string& proxyOptions) } -Resolver::Resolver(const ApplicationDescriptor& app, const Ice::CommunicatorPtr& communicator, bool enableWarning) : +Resolver::Resolver(const ApplicationDescriptor& app, const shared_ptr<Ice::Communicator>& communicator, bool enableWarning) : _application(&app), _communicator(communicator), _escape(false), @@ -508,7 +473,7 @@ Resolver::Resolver(const Resolver& resolve, } } -Resolver::Resolver(const InternalNodeInfoPtr& info, const Ice::CommunicatorPtr& com) : +Resolver::Resolver(const shared_ptr<InternalNodeInfo>& info, const shared_ptr<Ice::Communicator>& com) : _application(0), _communicator(com), _escape(true), @@ -1049,7 +1014,7 @@ Resolver::checkDeprecated(const string& name) const } } -CommunicatorHelper::CommunicatorHelper(const CommunicatorDescriptorPtr& desc, bool ignoreProps) : +CommunicatorHelper::CommunicatorHelper(const shared_ptr<CommunicatorDescriptor>& desc, bool ignoreProps) : _desc(desc), _ignoreProps(ignoreProps) { } @@ -1067,7 +1032,7 @@ CommunicatorHelper::operator==(const CommunicatorHelper& helper) const return false; } - if(!isSeqEqual(_desc->adapters, helper._desc->adapters, GetAdapterId(), AdapterEq())) + if(!isSeqEqual(_desc->adapters, helper._desc->adapters, getAdapterId, adapterEqual)) { return false; } @@ -1080,12 +1045,6 @@ CommunicatorHelper::operator==(const CommunicatorHelper& helper) const } } - if(set<DbEnvDescriptor>(_desc->dbEnvs.begin(), _desc->dbEnvs.end()) != - set<DbEnvDescriptor>(helper._desc->dbEnvs.begin(), helper._desc->dbEnvs.end())) - { - return false; - } - if(_desc->logs != helper._desc->logs) { return false; @@ -1143,7 +1102,7 @@ CommunicatorHelper::getReplicaGroups(set<string>& replicaGroups) const } void -CommunicatorHelper::instantiateImpl(const CommunicatorDescriptorPtr& instance, const Resolver& resolve) const +CommunicatorHelper::instantiateImpl(const shared_ptr<CommunicatorDescriptor>& instance, const Resolver& resolve) const { instance->description = resolve(_desc->description, "description"); instance->propertySet = resolve(_desc->propertySet); @@ -1200,16 +1159,6 @@ CommunicatorHelper::instantiateImpl(const CommunicatorDescriptorPtr& instance, c } } - for(DbEnvDescriptorSeq::const_iterator s = _desc->dbEnvs.begin(); s != _desc->dbEnvs.end(); ++s) - { - DbEnvDescriptor dbEnv; - dbEnv.name = resolve(s->name, "database environment name", false); - dbEnv.description = resolve(s->description, "database environment description"); - dbEnv.dbHome = resolve(s->dbHome, "database environment home directory"); - dbEnv.properties = resolve(s->properties, "database environment property"); - instance->dbEnvs.push_back(dbEnv); - } - for(Ice::StringSeq::const_iterator l = _desc->logs.begin(); l != _desc->logs.end(); ++l) { instance->logs.push_back(resolve(*l, "log path", false)); @@ -1217,7 +1166,7 @@ CommunicatorHelper::instantiateImpl(const CommunicatorDescriptorPtr& instance, c } void -CommunicatorHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +CommunicatorHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out) const { if(!_desc->description.empty()) { @@ -1228,12 +1177,6 @@ CommunicatorHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) } set<string> hiddenProperties; { - for(DbEnvDescriptorSeq::const_iterator p = _desc->dbEnvs.begin(); p != _desc->dbEnvs.end(); ++p) - { - printDbEnv(out, *p); - } - } - { for(AdapterDescriptorSeq::const_iterator p = _desc->adapters.begin(); p != _desc->adapters.end(); ++p) { hiddenProperties.insert(p->name + ".Endpoints"); @@ -1269,36 +1212,7 @@ CommunicatorHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) } void -CommunicatorHelper::printDbEnv(Output& out, const DbEnvDescriptor& dbEnv) const -{ - out << nl << "database environment `" << dbEnv.name << "'"; - if(!dbEnv.dbHome.empty() || !dbEnv.properties.empty() || !dbEnv.description.empty()) - { - out << sb; - if(!dbEnv.dbHome.empty()) - { - out << nl << "home = `" << dbEnv.dbHome << "'"; - } - if(!dbEnv.description.empty()) - { - out << nl << "description = `" << dbEnv.description << "'"; - } - if(!dbEnv.properties.empty()) - { - out << nl << "properties"; - out << sb; - for(PropertyDescriptorSeq::const_iterator p = dbEnv.properties.begin(); p != dbEnv.properties.end(); ++p) - { - out << nl << p->name << " = `" << p->value << "'"; - } - out << eb; - } - out << eb; - } -} - -void -CommunicatorHelper::printObjectAdapter(const Ice::CommunicatorPtr& communicator, +CommunicatorHelper::printObjectAdapter(const shared_ptr<Ice::Communicator>& communicator, Output& out, const AdapterDescriptor& adapter) const { @@ -1372,7 +1286,7 @@ CommunicatorHelper::getProperty(const string& name) const return IceGrid::getProperty(_desc->propertySet.properties, name); } -ServiceHelper::ServiceHelper(const ServiceDescriptorPtr& descriptor, bool ignoreProps) : +ServiceHelper::ServiceHelper(const shared_ptr<ServiceDescriptor>& descriptor, bool ignoreProps) : CommunicatorHelper(descriptor, ignoreProps), _desc(descriptor) { @@ -1400,29 +1314,23 @@ ServiceHelper::operator==(const CommunicatorHelper& h) const return true; } -bool -ServiceHelper::operator!=(const CommunicatorHelper& helper) const -{ - return !operator==(helper); -} - -ServiceDescriptorPtr +shared_ptr<ServiceDescriptor> ServiceHelper::getDescriptor() const { return _desc; } -ServiceDescriptorPtr +shared_ptr<ServiceDescriptor> ServiceHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const { - ServiceDescriptorPtr service = new ServiceDescriptor(); + auto service = make_shared<ServiceDescriptor>(); instantiateImpl(service, resolver, props, serviceProps); return service; } void -ServiceHelper::instantiateImpl(const ServiceDescriptorPtr& instance, +ServiceHelper::instantiateImpl(const shared_ptr<ServiceDescriptor>& instance, const Resolver& resolve, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const @@ -1441,7 +1349,7 @@ ServiceHelper::instantiateImpl(const ServiceDescriptorPtr& instance, } void -ServiceHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +ServiceHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out) const { out << "service `" + _desc->name + "'"; out << sb; @@ -1450,7 +1358,7 @@ ServiceHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) cons out << eb; } -ServerHelper::ServerHelper(const ServerDescriptorPtr& descriptor, bool ignoreProps) : +ServerHelper::ServerHelper(const shared_ptr<ServerDescriptor>& descriptor, bool ignoreProps) : CommunicatorHelper(descriptor, ignoreProps), _desc(descriptor) { @@ -1525,19 +1433,13 @@ ServerHelper::operator==(const CommunicatorHelper& h) const return true; } -bool -ServerHelper::operator!=(const CommunicatorHelper& helper) const -{ - return !operator==(helper); -} - -ServerDescriptorPtr +shared_ptr<ServerDescriptor> ServerHelper::getDescriptor() const { return _desc; } -ServerDescriptorPtr +shared_ptr<ServerDescriptor> ServerHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const @@ -1547,19 +1449,19 @@ ServerHelper::instantiate(const Resolver& resolver, resolver.exception("service property sets are only allowed in IceBox server instances"); } - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared<ServerDescriptor>(); instantiateImpl(server, resolver, props); return server; } void -ServerHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +ServerHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out) const { print(communicator, out, ServerInfo()); } void -ServerHelper::print(const Ice::CommunicatorPtr& communicator, Output& out, const ServerInfo& info) const +ServerHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out, const ServerInfo& info) const { out << "server `" + _desc->id + "'"; out << sb; @@ -1568,7 +1470,7 @@ ServerHelper::print(const Ice::CommunicatorPtr& communicator, Output& out, const } void -ServerHelper::printImpl(const Ice::CommunicatorPtr& communicator, Output& out, const ServerInfo& info) const +ServerHelper::printImpl(const shared_ptr<Ice::Communicator>& communicator, Output& out, const ServerInfo& info) const { if(!info.application.empty()) { @@ -1620,7 +1522,7 @@ ServerHelper::printImpl(const Ice::CommunicatorPtr& communicator, Output& out, c } void -ServerHelper::instantiateImpl(const ServerDescriptorPtr& instance, +ServerHelper::instantiateImpl(const shared_ptr<ServerDescriptor>& instance, const Resolver& resolve, const PropertyDescriptorSeq& props) const { @@ -1648,7 +1550,7 @@ ServerHelper::instantiateImpl(const ServerDescriptorPtr& instance, instance->propertySet.properties.insert(instance->propertySet.properties.end(), props.begin(), props.end()); } -IceBoxHelper::IceBoxHelper(const IceBoxDescriptorPtr& descriptor, bool ignoreProps) : +IceBoxHelper::IceBoxHelper(const shared_ptr<IceBoxDescriptor>& descriptor, bool ignoreProps) : ServerHelper(descriptor, ignoreProps), _desc(descriptor) { @@ -1675,18 +1577,12 @@ IceBoxHelper::operator==(const CommunicatorHelper& h) const return true; } -bool -IceBoxHelper::operator!=(const CommunicatorHelper& helper) const -{ - return !operator==(helper); -} - -ServerDescriptorPtr +shared_ptr<ServerDescriptor> IceBoxHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const { - IceBoxDescriptorPtr iceBox = new IceBoxDescriptor(); + auto iceBox = make_shared<IceBoxDescriptor>(); instantiateImpl(iceBox, resolver, props, serviceProps); return iceBox; } @@ -1712,13 +1608,13 @@ IceBoxHelper::getReplicaGroups(set<string>& replicaGroups) const } void -IceBoxHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +IceBoxHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out) const { print(communicator, out, ServerInfo()); } void -IceBoxHelper::print(const Ice::CommunicatorPtr& communicator, Output& out, const ServerInfo& info) const +IceBoxHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out, const ServerInfo& info) const { out << "icebox `" + _desc->id + "'"; out << sb; @@ -1738,7 +1634,7 @@ IceBoxHelper::print(const Ice::CommunicatorPtr& communicator, Output& out, const } void -IceBoxHelper::instantiateImpl(const IceBoxDescriptorPtr& instance, +IceBoxHelper::instantiateImpl(const shared_ptr<IceBoxDescriptor>& instance, const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const @@ -1864,7 +1760,7 @@ ServiceInstanceHelper::instantiate(const Resolver& resolve, const PropertySetDes { assert(!_def._cpp_template.empty()); TemplateDescriptor tmpl = resolve.getServiceTemplate(_def._cpp_template); - def = ServiceHelper(ServiceDescriptorPtr::dynamicCast(tmpl.descriptor)); + def = ServiceHelper(dynamic_pointer_cast<ServiceDescriptor>(tmpl.descriptor)); parameterValues = instantiateParams(resolve, _def._cpp_template, _def.parameterValues, @@ -1911,7 +1807,7 @@ ServiceInstanceHelper::getReplicaGroups(set<string>& replicaGroups) const } void -ServiceInstanceHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +ServiceInstanceHelper::print(const shared_ptr<Ice::Communicator>& communicator, Output& out) const { if(_service.getDescriptor()) { @@ -1942,7 +1838,7 @@ ServerInstanceHelper::ServerInstanceHelper(const ServerInstanceDescriptor& desc, init(0, resolve, instantiate); } -ServerInstanceHelper::ServerInstanceHelper(const ServerDescriptorPtr& definition, +ServerInstanceHelper::ServerInstanceHelper(const shared_ptr<ServerDescriptor>& definition, const Resolver& resolve, bool instantiate) : _def(ServerInstanceDescriptor()) @@ -1951,12 +1847,12 @@ ServerInstanceHelper::ServerInstanceHelper(const ServerDescriptorPtr& definition } void -ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver& resolve, bool instantiate) +ServerInstanceHelper::init(const shared_ptr<ServerDescriptor>& definition, const Resolver& resolve, bool instantiate) { // // Get the server definition if it's not provided. // - ServerDescriptorPtr def = definition; + auto def = definition; std::map<std::string, std::string> parameterValues; if(!def) { @@ -1969,7 +1865,7 @@ ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver // Get the server definition and the template property sets. // TemplateDescriptor tmpl = resolve.getServerTemplate(_def._cpp_template); - def = ServerDescriptorPtr::dynamicCast(tmpl.descriptor); + def = dynamic_pointer_cast<ServerDescriptor>(tmpl.descriptor); parameterValues = instantiateParams(resolve, _def._cpp_template, _def.parameterValues, @@ -2025,8 +1921,8 @@ ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver // // Instantiate the server definition. // - ServerDescriptorPtr inst = _serverDefinition->instantiate(svrResolve, _instance.propertySet.properties, - _instance.servicePropertySets); + shared_ptr<ServerDescriptor> inst = _serverDefinition->instantiate(svrResolve, _instance.propertySet.properties, + _instance.servicePropertySets); _serverInstance = createHelper(inst); } @@ -2072,14 +1968,14 @@ ServerInstanceHelper::getInstance() const return _instance; } -ServerDescriptorPtr +shared_ptr<ServerDescriptor> ServerInstanceHelper::getServerDefinition() const { assert(_def._cpp_template.empty()); return _serverDefinition->getDescriptor(); } -ServerDescriptorPtr +shared_ptr<ServerDescriptor> ServerInstanceHelper::getServerInstance() const { assert(_serverInstance); @@ -2214,12 +2110,12 @@ NodeHelper::diff(const NodeHelper& helper) const update.name = _name; if(_def.loadFactor != helper._def.loadFactor) { - update.loadFactor = new BoxedString(_def.loadFactor); + update.loadFactor = make_shared<BoxedString>(_def.loadFactor); } if(_def.description != helper._def.description) { - update.description = new BoxedString(_def.description); + update.description = make_shared<BoxedString>(_def.description); } update.variables = getDictUpdatedElts(helper._def.variables, _def.variables); @@ -2570,7 +2466,7 @@ NodeHelper::printDiff(Output& out, const NodeHelper& helper) const out << eb; } -ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, +ApplicationHelper::ApplicationHelper(const shared_ptr<Ice::Communicator>& communicator, const ApplicationDescriptor& appDesc, bool enableWarning, bool instantiate) : @@ -2609,7 +2505,7 @@ ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, { resolve.exception("replica group load balancing is not set"); } - desc.loadBalancing = LoadBalancingPolicyPtr::dynamicCast(r->loadBalancing->ice_clone()); + desc.loadBalancing = dynamic_pointer_cast<LoadBalancingPolicy>(r->loadBalancing->ice_clone()); desc.loadBalancing->nReplicas = resolve.asInt(r->loadBalancing->nReplicas, "replica group number of replicas"); if(desc.loadBalancing->nReplicas.empty()) @@ -2620,7 +2516,7 @@ ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, { resolve.exception("invalid replica group load balancing number of replicas value: inferior to 0"); } - AdaptiveLoadBalancingPolicyPtr al = AdaptiveLoadBalancingPolicyPtr::dynamicCast(desc.loadBalancing); + auto al = dynamic_pointer_cast<AdaptiveLoadBalancingPolicy>(desc.loadBalancing); if(al) { al->loadSample = resolve(al->loadSample, "replica group load sample"); @@ -2717,7 +2613,7 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const updt.name = _def.name; if(_def.description != helper._def.description) { - updt.description = new BoxedString(_def.description); + updt.description = make_shared<BoxedString>(_def.description); } updt.variables = getDictUpdatedElts(helper._def.variables, _def.variables); @@ -2726,15 +2622,12 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const updt.propertySets = getDictUpdatedElts(helper._def.propertySets, _def.propertySets); updt.removePropertySets = getDictRemovedElts(helper._def.propertySets, _def.propertySets); - GetReplicaGroupId rk; - ReplicaGroupEq req; - updt.replicaGroups = getSeqUpdatedEltsWithEq(helper._def.replicaGroups, _def.replicaGroups, rk, req); - updt.removeReplicaGroups = getSeqRemovedElts(helper._def.replicaGroups, _def.replicaGroups, rk); + updt.replicaGroups = getSeqUpdatedEltsWithEq(helper._def.replicaGroups, _def.replicaGroups, getReplicaGroupId, replicaGroupEqual); + updt.removeReplicaGroups = getSeqRemovedElts(helper._def.replicaGroups, _def.replicaGroups, getReplicaGroupId); - TemplateDescriptorEqual eq; - updt.serverTemplates = getDictUpdatedEltsWithEq(helper._def.serverTemplates, _def.serverTemplates, eq); + updt.serverTemplates = getDictUpdatedEltsWithEq(helper._def.serverTemplates, _def.serverTemplates, templateDescriptorEqual); updt.removeServerTemplates = getDictRemovedElts(helper._def.serverTemplates, _def.serverTemplates); - updt.serviceTemplates = getDictUpdatedEltsWithEq(helper._def.serviceTemplates, _def.serviceTemplates, eq); + updt.serviceTemplates = getDictUpdatedEltsWithEq(helper._def.serviceTemplates, _def.serviceTemplates, templateDescriptorEqual); updt.removeServiceTemplates = getDictRemovedElts(helper._def.serviceTemplates, _def.serviceTemplates); NodeHelperDict updated = getDictUpdatedElts(helper._nodes, _nodes); @@ -2749,8 +2642,8 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const nodeUpdate.variables = node.variables; nodeUpdate.servers = node.servers; nodeUpdate.serverInstances = node.serverInstances; - nodeUpdate.loadFactor = new BoxedString(node.loadFactor); - nodeUpdate.description = new BoxedString(node.description); + nodeUpdate.loadFactor = make_shared<BoxedString>(node.loadFactor); + nodeUpdate.description = make_shared<BoxedString>(node.description); updt.nodes.push_back(nodeUpdate); } else @@ -2767,11 +2660,10 @@ ApplicationDescriptor ApplicationHelper::update(const ApplicationUpdateDescriptor& updt) const { ApplicationDescriptor def; - GetReplicaGroupId rg; def.name = _def.name; def.description = updt.description ? updt.description->value : _def.description; - def.replicaGroups = updateSeqElts(_def.replicaGroups, updt.replicaGroups, updt.removeReplicaGroups, rg); + def.replicaGroups = updateSeqElts(_def.replicaGroups, updt.replicaGroups, updt.removeReplicaGroups, getReplicaGroupId); def.variables = updateDictElts(_def.variables, updt.variables, updt.removeVariables); def.propertySets = updateDictElts(_def.propertySets, updt.propertySets, updt.removePropertySets); def.serverTemplates = updateDictElts(_def.serverTemplates, updt.serverTemplates, updt.removeServerTemplates); @@ -2980,15 +2872,15 @@ ApplicationHelper::print(Output& out, const ApplicationInfo& info) const { out << "default (return all endpoints)"; } - else if(RandomLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + else if(dynamic_pointer_cast<RandomLoadBalancingPolicy>(p->loadBalancing)) { out << "random"; } - else if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + else if(dynamic_pointer_cast<RoundRobinLoadBalancingPolicy>(p->loadBalancing)) { out << "round-robin"; } - else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + else if(dynamic_pointer_cast<AdaptiveLoadBalancingPolicy>(p->loadBalancing)) { out << "adaptive" ; } @@ -3065,11 +2957,9 @@ ApplicationHelper::printDiff(Output& out, const ApplicationHelper& helper) const } } { - GetReplicaGroupId rk; - ReplicaGroupEq req; ReplicaGroupDescriptorSeq updated = - getSeqUpdatedEltsWithEq(helper._def.replicaGroups, _def.replicaGroups, rk, req); - Ice::StringSeq removed = getSeqRemovedElts(helper._def.replicaGroups, _def.replicaGroups, rk); + getSeqUpdatedEltsWithEq(helper._def.replicaGroups, _def.replicaGroups, getReplicaGroupId, replicaGroupEqual); + Ice::StringSeq removed = getSeqRemovedElts(helper._def.replicaGroups, _def.replicaGroups, getReplicaGroupId); if(!updated.empty() || !removed.empty()) { out << nl << "replica groups"; @@ -3105,9 +2995,8 @@ ApplicationHelper::printDiff(Output& out, const ApplicationHelper& helper) const } { - TemplateDescriptorEqual eq; TemplateDescriptorDict updated; - updated = getDictUpdatedEltsWithEq(helper._def.serverTemplates, _def.serverTemplates, eq); + updated = getDictUpdatedEltsWithEq(helper._def.serverTemplates, _def.serverTemplates, templateDescriptorEqual); Ice::StringSeq removed = getDictRemovedElts(helper._def.serverTemplates, _def.serverTemplates); if(!updated.empty() || !removed.empty()) { @@ -3135,9 +3024,8 @@ ApplicationHelper::printDiff(Output& out, const ApplicationHelper& helper) const } } { - TemplateDescriptorEqual eq; TemplateDescriptorDict updated; - updated = getDictUpdatedEltsWithEq(helper._def.serviceTemplates, _def.serviceTemplates, eq); + updated = getDictUpdatedEltsWithEq(helper._def.serviceTemplates, _def.serviceTemplates, templateDescriptorEqual); Ice::StringSeq removed = getDictRemovedElts(helper._def.serviceTemplates, _def.serviceTemplates); if(!updated.empty() || !removed.empty()) { @@ -3198,10 +3086,10 @@ ApplicationHelper::printDiff(Output& out, const ApplicationHelper& helper) const } bool -IceGrid::descriptorEqual(const ServerDescriptorPtr& lhs, const ServerDescriptorPtr& rhs, bool ignoreProps) +IceGrid::descriptorEqual(const shared_ptr<ServerDescriptor>& lhs, const shared_ptr<ServerDescriptor>& rhs, bool ignoreProps) { - IceBoxDescriptorPtr lhsIceBox = IceBoxDescriptorPtr::dynamicCast(lhs); - IceBoxDescriptorPtr rhsIceBox = IceBoxDescriptorPtr::dynamicCast(rhs); + auto lhsIceBox = dynamic_pointer_cast<IceBoxDescriptor>(lhs); + auto rhsIceBox = dynamic_pointer_cast<IceBoxDescriptor>(rhs); if(lhsIceBox && rhsIceBox) { return IceBoxHelper(lhsIceBox, ignoreProps) == IceBoxHelper(rhsIceBox, ignoreProps); @@ -3216,17 +3104,17 @@ IceGrid::descriptorEqual(const ServerDescriptorPtr& lhs, const ServerDescriptorP } } -ServerHelperPtr -IceGrid::createHelper(const ServerDescriptorPtr& desc) +shared_ptr<ServerHelper> +IceGrid::createHelper(const shared_ptr<ServerDescriptor>& desc) { - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(desc); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(desc); if(iceBox) { - return new IceBoxHelper(iceBox); + return make_shared<IceBoxHelper>(iceBox); } else { - return new ServerHelper(desc); + return make_shared<ServerHelper>(desc); } } diff --git a/cpp/src/IceGrid/DescriptorHelper.h b/cpp/src/IceGrid/DescriptorHelper.h index 4fa15ef3a5c..c0a40139719 100644 --- a/cpp/src/IceGrid/DescriptorHelper.h +++ b/cpp/src/IceGrid/DescriptorHelper.h @@ -19,9 +19,9 @@ class Resolver { public: - Resolver(const ApplicationDescriptor&, const Ice::CommunicatorPtr&, bool); + Resolver(const ApplicationDescriptor&, const std::shared_ptr<Ice::Communicator>&, bool); Resolver(const Resolver&, const std::map<std::string, std::string>&, bool); - Resolver(const InternalNodeInfoPtr&, const Ice::CommunicatorPtr&); + Resolver(const std::shared_ptr<InternalNodeInfo>&, const std::shared_ptr<Ice::Communicator>&); std::string operator()(const std::string&, const std::string& = std::string(), bool = true) const; Ice::StringSeq operator()(const Ice::StringSeq&, const std::string&) const; @@ -51,7 +51,7 @@ public: TemplateDescriptor getServiceTemplate(const std::string&) const; bool hasReplicaGroup(const std::string&) const; - Ice::CommunicatorPtr getCommunicator() const { return _communicator; } + std::shared_ptr<Ice::Communicator> getCommunicator() const { return _communicator; } bool warningEnabled() const { return _enableWarning; } private: @@ -65,7 +65,7 @@ private: void checkDeprecated(const std::string&) const; const ApplicationDescriptor* _application; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr<Ice::Communicator> _communicator; const bool _escape; const bool _enableWarning; std::string _context; @@ -82,90 +82,86 @@ class CommunicatorHelper { public: - CommunicatorHelper(const CommunicatorDescriptorPtr&, bool = false); CommunicatorHelper() : _ignoreProps(false) { } - virtual ~CommunicatorHelper() { } + CommunicatorHelper(const std::shared_ptr<CommunicatorDescriptor>&, bool = false); virtual bool operator==(const CommunicatorHelper&) const; - virtual bool operator!=(const CommunicatorHelper&) const; + bool operator!=(const CommunicatorHelper&) const; virtual void getIds(std::multiset<std::string>&, std::multiset<Ice::Identity>&) const; virtual void getReplicaGroups(std::set<std::string>&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&) const; protected: - void printDbEnv(IceUtilInternal::Output&, const DbEnvDescriptor&) const; - void printObjectAdapter(const Ice::CommunicatorPtr&, IceUtilInternal::Output&, const AdapterDescriptor&) const; + void printObjectAdapter(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&, const AdapterDescriptor&) const; void printPropertySet(IceUtilInternal::Output&, const PropertySetDescriptor&) const; virtual std::string getProperty(const std::string&) const; - void instantiateImpl(const CommunicatorDescriptorPtr&, const Resolver&) const; + void instantiateImpl(const std::shared_ptr<CommunicatorDescriptor>&, const Resolver&) const; private: - CommunicatorDescriptorPtr _desc; + std::shared_ptr<CommunicatorDescriptor> _desc; bool _ignoreProps; }; -class ServiceHelper : public CommunicatorHelper +class ServiceHelper final : public CommunicatorHelper { public: - ServiceHelper(const ServiceDescriptorPtr&, bool = false); - ServiceHelper() { } + ServiceHelper() = default; + ServiceHelper(const std::shared_ptr<ServiceDescriptor>&, bool = false); - virtual bool operator==(const CommunicatorHelper&) const; - virtual bool operator!=(const CommunicatorHelper&) const; + bool operator==(const CommunicatorHelper&) const override; - ServiceDescriptorPtr getDescriptor() const; - ServiceDescriptorPtr instantiate(const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + std::shared_ptr<ServiceDescriptor> getDescriptor() const; + std::shared_ptr<ServiceDescriptor> instantiate(const Resolver&, const PropertyDescriptorSeq&, + const PropertySetDescriptorDict&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&) const; protected: using CommunicatorHelper::instantiateImpl; - void instantiateImpl(const ServiceDescriptorPtr&, const Resolver&, const PropertyDescriptorSeq&, + void instantiateImpl(const std::shared_ptr<ServiceDescriptor>&, const Resolver&, const PropertyDescriptorSeq&, const PropertySetDescriptorDict&) const; private: - ServiceDescriptorPtr _desc; + std::shared_ptr<ServiceDescriptor> _desc; }; -class ServerHelper : public CommunicatorHelper, public IceUtil::SimpleShared +class ServerHelper : public CommunicatorHelper { public: - ServerHelper(const ServerDescriptorPtr&, bool = false); - ServerHelper() { } + ServerHelper() = default; + ServerHelper(const std::shared_ptr<ServerDescriptor>&, bool = false); + virtual ~ServerHelper() = default; - virtual bool operator==(const CommunicatorHelper&) const; - virtual bool operator!=(const CommunicatorHelper&) const; + bool operator==(const CommunicatorHelper&) const override; - ServerDescriptorPtr getDescriptor() const; - virtual ServerDescriptorPtr instantiate(const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + std::shared_ptr<ServerDescriptor> getDescriptor() const; + virtual std::shared_ptr<ServerDescriptor> instantiate(const Resolver&, const PropertyDescriptorSeq&, + const PropertySetDescriptorDict&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&, const ServerInfo&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&, const ServerInfo&) const; protected: using CommunicatorHelper::instantiateImpl; - void printImpl(const Ice::CommunicatorPtr&, IceUtilInternal::Output&, const ServerInfo&) const; - void instantiateImpl(const ServerDescriptorPtr&, const Resolver&, const PropertyDescriptorSeq&) const; + void printImpl(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&, const ServerInfo&) const; + void instantiateImpl(const std::shared_ptr<ServerDescriptor>&, const Resolver&, const PropertyDescriptorSeq&) const; private: - ServerDescriptorPtr _desc; + std::shared_ptr<ServerDescriptor> _desc; }; -typedef IceUtil::Handle<ServerHelper> ServerHelperPtr; class InstanceHelper { @@ -178,7 +174,7 @@ protected: const std::map<std::string, std::string>&) const; }; -class ServiceInstanceHelper : public InstanceHelper +class ServiceInstanceHelper final : public InstanceHelper { public: @@ -191,7 +187,7 @@ public: void getIds(std::multiset<std::string>&, std::multiset<Ice::Identity>&) const; void getReplicaGroups(std::set<std::string>&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&) const; private: @@ -199,47 +195,42 @@ private: mutable ServiceHelper _service; }; -class IceBoxHelper : public ServerHelper +class IceBoxHelper final : public ServerHelper { public: - IceBoxHelper(const IceBoxDescriptorPtr&, bool = false); - IceBoxHelper() { } + IceBoxHelper() = default; + IceBoxHelper(const std::shared_ptr<IceBoxDescriptor>&, bool = false); - virtual bool operator==(const CommunicatorHelper&) const; - virtual bool operator!=(const CommunicatorHelper&) const; + bool operator==(const CommunicatorHelper&) const override; - virtual ServerDescriptorPtr instantiate(const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + std::shared_ptr<ServerDescriptor> instantiate(const Resolver&, const PropertyDescriptorSeq&, + const PropertySetDescriptorDict&) const override; - virtual void getIds(std::multiset<std::string>&, std::multiset<Ice::Identity>&) const; - virtual void getReplicaGroups(std::set<std::string>&) const; + void getIds(std::multiset<std::string>&, std::multiset<Ice::Identity>&) const override; + void getReplicaGroups(std::set<std::string>&) const override; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&, const ServerInfo&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr<Ice::Communicator>&, IceUtilInternal::Output&, const ServerInfo&) const; protected: -#ifdef __SUNPRO_CC - using ServerHelper::instantiateImpl; -#endif - - void instantiateImpl(const IceBoxDescriptorPtr&, const Resolver&, const PropertyDescriptorSeq&, + void instantiateImpl(const std::shared_ptr<IceBoxDescriptor>&, const Resolver&, const PropertyDescriptorSeq&, const PropertySetDescriptorDict&) const; private: - IceBoxDescriptorPtr _desc; + std::shared_ptr<IceBoxDescriptor> _desc; std::vector<ServiceInstanceHelper> _services; }; -class ServerInstanceHelper : public InstanceHelper +class ServerInstanceHelper final : public InstanceHelper { public: ServerInstanceHelper(const ServerInstanceDescriptor&, const Resolver&, bool); - ServerInstanceHelper(const ServerDescriptorPtr&, const Resolver&, bool); + ServerInstanceHelper(const std::shared_ptr<ServerDescriptor>&, const Resolver&, bool); bool operator==(const ServerInstanceHelper&) const; bool operator!=(const ServerInstanceHelper&) const; @@ -248,33 +239,32 @@ public: ServerInstanceDescriptor getDefinition() const; ServerInstanceDescriptor getInstance() const; - ServerDescriptorPtr getServerDefinition() const; - ServerDescriptorPtr getServerInstance() const; + std::shared_ptr<ServerDescriptor> getServerDefinition() const; + std::shared_ptr<ServerDescriptor> getServerInstance() const; void getIds(std::multiset<std::string>&, std::multiset<Ice::Identity>&) const; void getReplicaGroups(std::set<std::string>&) const; private: - void init(const ServerDescriptorPtr&, const Resolver&, bool); + void init(const std::shared_ptr<ServerDescriptor>&, const Resolver&, bool); ServerInstanceDescriptor _def; std::string _id; ServerInstanceDescriptor _instance; - ServerHelperPtr _serverDefinition; - ServerHelperPtr _serverInstance; + std::shared_ptr<ServerHelper> _serverDefinition; + std::shared_ptr<ServerHelper> _serverInstance; }; -class NodeHelper +class NodeHelper final { public: NodeHelper(const std::string&, const NodeDescriptor&, const Resolver&, bool); - virtual ~NodeHelper() { } - virtual bool operator==(const NodeHelper&) const; - virtual bool operator!=(const NodeHelper&) const; + bool operator==(const NodeHelper&) const; + bool operator!=(const NodeHelper&) const; NodeUpdateDescriptor diff(const NodeHelper&) const; NodeDescriptor update(const NodeUpdateDescriptor&, const Resolver&) const; @@ -303,11 +293,11 @@ private: ServerInstanceHelperDict _servers; }; -class ApplicationHelper +class ApplicationHelper final { public: - ApplicationHelper(const Ice::CommunicatorPtr&, const ApplicationDescriptor&, bool = false, bool = true); + ApplicationHelper(const std::shared_ptr<Ice::Communicator>&, const ApplicationDescriptor&, bool = false, bool = true); ApplicationUpdateDescriptor diff(const ApplicationHelper&) const; ApplicationDescriptor update(const ApplicationUpdateDescriptor&) const; @@ -324,16 +314,16 @@ public: private: - Ice::CommunicatorPtr _communicator; + std::shared_ptr<Ice::Communicator> _communicator; ApplicationDescriptor _def; ApplicationDescriptor _instance; - typedef std::map<std::string, NodeHelper> NodeHelperDict; + using NodeHelperDict = std::map<std::string, NodeHelper>; NodeHelperDict _nodes; }; -bool descriptorEqual(const ServerDescriptorPtr&, const ServerDescriptorPtr&, bool = false); -ServerHelperPtr createHelper(const ServerDescriptorPtr&); +bool descriptorEqual(const std::shared_ptr<ServerDescriptor>&, const std::shared_ptr<ServerDescriptor>&, bool = false); +std::shared_ptr<ServerHelper> createHelper(const std::shared_ptr<ServerDescriptor>&); bool isServerUpdated(const ServerInfo&, const ServerInfo&, bool = false); } diff --git a/cpp/src/IceGrid/DescriptorParser.cpp b/cpp/src/IceGrid/DescriptorParser.cpp index b86f8cbb775..26cd9c24104 100644 --- a/cpp/src/IceGrid/DescriptorParser.cpp +++ b/cpp/src/IceGrid/DescriptorParser.cpp @@ -16,22 +16,22 @@ using namespace std; using namespace Ice; using namespace IceGrid; -namespace IceGrid +namespace { -class DescriptorHandler : public IceXML::Handler +class DescriptorHandler final : public IceXML::Handler { public: - DescriptorHandler(const string&, const Ice::CommunicatorPtr&); + DescriptorHandler(const string&, const shared_ptr<Ice::Communicator>&); - void setAdmin(const IceGrid::AdminPrx&); + void setAdmin(const shared_ptr<IceGrid::AdminPrx>&); void setVariables(const map<string, string>&, const vector<string>&); - virtual void startElement(const string&, const IceXML::Attributes&, int, int); - virtual void endElement(const string&, int, int); - virtual void characters(const string&, int, int); - virtual void error(const string&, int, int); + void startElement(const string&, const IceXML::Attributes&, int, int) override; + void endElement(const string&, int, int) override; + void characters(const string&, int, int) override; + void error(const string&, int, int) override; const ApplicationDescriptor& getApplicationDescriptor() const; @@ -43,8 +43,8 @@ private: void error(const string&) const; bool isTargetDeployable(const string&) const; - const Ice::CommunicatorPtr _communicator; - IceGrid::AdminPrx _admin; + const shared_ptr<Ice::Communicator> _communicator; + shared_ptr<IceGrid::AdminPrx> _admin; string _filename; map<string, string> _overrides; vector<string> _targets; @@ -55,38 +55,34 @@ private: int _line; int _column; - IceInternal::UniquePtr<ApplicationDescriptorBuilder> _currentApplication; - IceInternal::UniquePtr<NodeDescriptorBuilder> _currentNode; - IceInternal::UniquePtr<TemplateDescriptorBuilder> _currentTemplate; - IceInternal::UniquePtr<ServerInstanceDescriptorBuilder> _currentServerInstance; - IceInternal::UniquePtr<ServiceInstanceDescriptorBuilder> _currentServiceInstance; - IceInternal::UniquePtr<ServerDescriptorBuilder> _currentServer; - IceInternal::UniquePtr<ServiceDescriptorBuilder> _currentService; + unique_ptr<ApplicationDescriptorBuilder> _currentApplication; + unique_ptr<NodeDescriptorBuilder> _currentNode; + unique_ptr<TemplateDescriptorBuilder> _currentTemplate; + unique_ptr<ServerInstanceDescriptorBuilder> _currentServerInstance; + unique_ptr<ServiceInstanceDescriptorBuilder> _currentServiceInstance; + unique_ptr<ServerDescriptorBuilder> _currentServer; + unique_ptr<ServiceDescriptorBuilder> _currentService; CommunicatorDescriptorBuilder* _currentCommunicator; - IceInternal::UniquePtr<PropertySetDescriptorBuilder> _currentPropertySet; + unique_ptr<PropertySetDescriptorBuilder> _currentPropertySet; bool _isTopLevel; bool _inAdapter; bool _inReplicaGroup; - bool _inDbEnv; }; -} - -DescriptorHandler::DescriptorHandler(const string& filename, const Ice::CommunicatorPtr& communicator) : +DescriptorHandler::DescriptorHandler(const string& filename, const shared_ptr<Ice::Communicator>& communicator) : _communicator(communicator), _filename(filename), _isCurrentTargetDeployable(true), - _currentCommunicator(0), + _currentCommunicator(nullptr), _isTopLevel(true), _inAdapter(false), - _inReplicaGroup(false), - _inDbEnv(false) + _inReplicaGroup(false) { } void -DescriptorHandler::setAdmin(const AdminPrx& admin) +DescriptorHandler::setAdmin(const shared_ptr<AdminPrx>& admin) { _admin = admin; } @@ -405,15 +401,6 @@ DescriptorHandler::startElement(const string& name, const IceXML::Attributes& at } _currentCommunicator->addAllocatable(attributes); } - else if(name == "dbenv") - { - if(!_currentCommunicator) - { - error("the <dbenv> element can only be a child of a <server> or <service> element"); - } - _currentCommunicator->addDbEnv(attributes); - _inDbEnv = true; - } else if(name == "log") { if(!_currentCommunicator) @@ -422,14 +409,6 @@ DescriptorHandler::startElement(const string& name, const IceXML::Attributes& at } _currentCommunicator->addLog(attributes); } - else if(name == "dbproperty") - { - if(!_inDbEnv) - { - error("the <dbproperty> element can only be a child of a <dbenv> element"); - } - _currentCommunicator->addDbEnvProperty(attributes); - } else if(name == "description" || name == "option" || name == "env") { // @@ -488,7 +467,7 @@ DescriptorHandler::endElement(const string& name, int line, int column) else if(name == "node") { _currentApplication->addNode(_currentNode->getName(), _currentNode->getDescriptor()); - _currentNode.reset(0); + _currentNode.reset(nullptr); } else if(name == "server" || name == "icebox") { @@ -503,14 +482,14 @@ DescriptorHandler::endElement(const string& name, int line, int column) _currentNode->addServer(_currentServer->getDescriptor()); } _currentServer->finish(); - _currentServer.reset(0); - _currentCommunicator = 0; + _currentServer.reset(nullptr); + _currentCommunicator = nullptr; } else if(name == "server-template") { assert(_currentApplication.get()); _currentApplication->addServerTemplate(_currentTemplate->getId(), _currentTemplate->getDescriptor()); - _currentTemplate.reset(0); + _currentTemplate.reset(nullptr); } else if(name == "service") { @@ -524,26 +503,26 @@ DescriptorHandler::endElement(const string& name, int line, int column) _currentTemplate->setDescriptor(_currentService->getDescriptor()); } _currentService->finish(); - _currentService.reset(0); + _currentService.reset(nullptr); _currentCommunicator = _currentServer.get(); } else if(name == "service-template") { assert(_currentTemplate.get()); _currentApplication->addServiceTemplate(_currentTemplate->getId(), _currentTemplate->getDescriptor()); - _currentTemplate.reset(0); + _currentTemplate.reset(nullptr); } else if(name == "server-instance") { assert(_currentNode.get() && _currentServerInstance.get()); _currentNode->addServerInstance(_currentServerInstance->getDescriptor()); - _currentServerInstance.reset(0); + _currentServerInstance.reset(nullptr); } else if(name == "service-instance") { assert(_currentServer.get() && _currentServiceInstance.get()); _currentServer->addServiceInstance(_currentServiceInstance->getDescriptor()); - _currentServiceInstance.reset(0); + _currentServiceInstance.reset(nullptr); } else if(name == "properties") { @@ -577,7 +556,7 @@ DescriptorHandler::endElement(const string& name, int line, int column) { assert(false); } - _currentPropertySet.reset(0); + _currentPropertySet.reset(nullptr); } } else if(name == "description") @@ -590,11 +569,6 @@ DescriptorHandler::endElement(const string& name, int line, int column) { _currentApplication->setReplicaGroupDescription(elementValue()); } - else if(_inDbEnv) - { - assert(_currentCommunicator); - _currentCommunicator->setDbEnvDescription(elementValue()); - } else if(_currentCommunicator) { _currentCommunicator->setDescription(elementValue()); @@ -637,10 +611,6 @@ DescriptorHandler::endElement(const string& name, int line, int column) _currentApplication->finishReplicaGroup(); _inReplicaGroup = false; } - else if(name == "dbenv") - { - _inDbEnv = false; - } } catch(const exception& ex) { @@ -811,12 +781,14 @@ DescriptorHandler::isTargetDeployable(const string& target) const return false; } +} + ApplicationDescriptor DescriptorParser::parseDescriptor(const string& descriptor, const Ice::StringSeq& targets, const map<string, string>& variables, - const Ice::CommunicatorPtr& communicator, - const IceGrid::AdminPrx& admin) + const shared_ptr<Ice::Communicator>& communicator, + const shared_ptr<IceGrid::AdminPrx>& admin) { string filename = simplify(descriptor); DescriptorHandler handler(filename, communicator); @@ -827,7 +799,7 @@ DescriptorParser::parseDescriptor(const string& descriptor, } ApplicationDescriptor -DescriptorParser::parseDescriptor(const string& descriptor, const Ice::CommunicatorPtr& communicator) +DescriptorParser::parseDescriptor(const string& descriptor, const shared_ptr<Ice::Communicator>& communicator) { string filename = simplify(descriptor); DescriptorHandler handler(filename, communicator); diff --git a/cpp/src/IceGrid/DescriptorParser.h b/cpp/src/IceGrid/DescriptorParser.h index 2e8f3e2b5f6..eda03f32d53 100644 --- a/cpp/src/IceGrid/DescriptorParser.h +++ b/cpp/src/IceGrid/DescriptorParser.h @@ -8,19 +8,18 @@ namespace IceGrid { -class DescriptorParser +namespace DescriptorParser { -public: - static ApplicationDescriptor parseDescriptor(const std::string&, - const Ice::StringSeq&, - const std::map<std::string, std::string>&, - const Ice::CommunicatorPtr&, - const IceGrid::AdminPrx&); +ApplicationDescriptor parseDescriptor(const std::string&, + const Ice::StringSeq&, + const std::map<std::string, std::string>&, + const std::shared_ptr<Ice::Communicator>&, + const std::shared_ptr<IceGrid::AdminPrx>&); - static ApplicationDescriptor parseDescriptor(const std::string&, const Ice::CommunicatorPtr&); +ApplicationDescriptor parseDescriptor(const std::string&, const std::shared_ptr<Ice::Communicator>&); -}; +} } diff --git a/cpp/src/IceGrid/FileCache.cpp b/cpp/src/IceGrid/FileCache.cpp index 565e7896e62..ba06b25d61d 100644 --- a/cpp/src/IceGrid/FileCache.cpp +++ b/cpp/src/IceGrid/FileCache.cpp @@ -16,12 +16,12 @@ using namespace std; using namespace IceGrid; -FileCache::FileCache(const Ice::CommunicatorPtr& com) : - _messageSizeMax(com->getProperties()->getPropertyAsIntWithDefault("Ice.MessageSizeMax", 1024) * 1024 - 256) +FileCache::FileCache(const shared_ptr<Ice::Communicator>& com) : + _messageMaxSize(com->getProperties()->getPropertyAsIntWithDefault("Ice.MessageMaxSize", 1024) * 1024 - 256) { } -Ice::Long +long long FileCache::getOffsetFromEnd(const string& file, int originalCount) { ifstream is(IceUtilInternal::streamFilename(file).c_str()); // file is a UTF-8 string @@ -108,7 +108,7 @@ FileCache::getOffsetFromEnd(const string& file, int originalCount) if(is.bad()) { - throw FileNotAvailableException("unrecoverable error occured while reading file `" + file + "'"); + throw FileNotAvailableException("unrecoverable error occurred while reading file `" + file + "'"); } if(lines.empty()) @@ -122,13 +122,13 @@ FileCache::getOffsetFromEnd(const string& file, int originalCount) } bool -FileCache::read(const string& file, Ice::Long offset, int size, Ice::Long& newOffset, Ice::StringSeq& lines) +FileCache::read(const string& file, long long offset, int size, long long& newOffset, Ice::StringSeq& lines) { assert(size > 0); - if(size > _messageSizeMax) + if(size > _messageMaxSize) { - size = _messageSizeMax; + size = _messageMaxSize; } if(size <= 5) @@ -205,7 +205,7 @@ FileCache::read(const string& file, Ice::Long offset, int size, Ice::Long& newOf if(is.bad()) { - throw FileNotAvailableException("unrecoverable error occured while reading file `" + file + "'"); + throw FileNotAvailableException("unrecoverable error occurred while reading file `" + file + "'"); } return is.eof(); diff --git a/cpp/src/IceGrid/FileCache.h b/cpp/src/IceGrid/FileCache.h index 12751665402..3a40feac689 100644 --- a/cpp/src/IceGrid/FileCache.h +++ b/cpp/src/IceGrid/FileCache.h @@ -5,27 +5,25 @@ #ifndef ICE_GRID_FILE_CACHE_H #define ICE_GRID_FILE_CACHE_H -#include <IceUtil/Shared.h> #include <Ice/BuiltinSequences.h> #include <Ice/CommunicatorF.h> namespace IceGrid { -class FileCache : public IceUtil::Shared +class FileCache { public: - FileCache(const Ice::CommunicatorPtr&); + FileCache(const std::shared_ptr<Ice::Communicator>&); - Ice::Long getOffsetFromEnd(const std::string&, int); - bool read(const std::string&, Ice::Long, int, Ice::Long&, Ice::StringSeq&); + long long getOffsetFromEnd(const std::string&, int); + bool read(const std::string&, long long , int, long long &, Ice::StringSeq&); private: - const int _messageSizeMax; + const int _messageMaxSize; }; -typedef IceUtil::Handle<FileCache> FileCachePtr; }; diff --git a/cpp/src/IceGrid/FileParserI.cpp b/cpp/src/IceGrid/FileParserI.cpp index fefe366a693..b382c561d9f 100644 --- a/cpp/src/IceGrid/FileParserI.cpp +++ b/cpp/src/IceGrid/FileParserI.cpp @@ -11,12 +11,12 @@ using namespace std; using namespace IceGrid; ApplicationDescriptor -FileParserI::parse(const string& file, const AdminPrx& admin, const Ice::Current& current) +FileParserI::parse(string file, shared_ptr<AdminPrx> admin, const Ice::Current& current) { try { - return DescriptorParser::parseDescriptor(file, Ice::StringSeq(), map<string, string>(), - current.adapter->getCommunicator(), admin); + return DescriptorParser::parseDescriptor(move(file), Ice::StringSeq(), map<string, string>(), + current.adapter->getCommunicator(), move(admin)); } catch(const IceXML::ParserException& e) { diff --git a/cpp/src/IceGrid/FileParserI.h b/cpp/src/IceGrid/FileParserI.h index 1762db9eb09..36178f52e15 100644 --- a/cpp/src/IceGrid/FileParserI.h +++ b/cpp/src/IceGrid/FileParserI.h @@ -7,12 +7,17 @@ #include <IceGrid/FileParser.h> -class FileParserI : public IceGrid::FileParser +namespace IceGrid +{ + +class FileParserI : public FileParser { public: - IceGrid::ApplicationDescriptor - parse(const std::string& file, const IceGrid::AdminPrx& admin, const Ice::Current&); + ApplicationDescriptor + parse(std::string file, std::shared_ptr<AdminPrx> admin, const Ice::Current&) override; }; +} + #endif diff --git a/cpp/src/IceGrid/FileUserAccountMapperI.cpp b/cpp/src/IceGrid/FileUserAccountMapperI.cpp index a9a1ef6dd77..c2189f435e2 100644 --- a/cpp/src/IceGrid/FileUserAccountMapperI.cpp +++ b/cpp/src/IceGrid/FileUserAccountMapperI.cpp @@ -68,9 +68,9 @@ FileUserAccountMapperI::FileUserAccountMapperI(const string& filename) } string -FileUserAccountMapperI::getUserAccount(const string& user, const Ice::Current&) +FileUserAccountMapperI::getUserAccount(string user, const Ice::Current&) { - map<string, string>::const_iterator p = _accounts.find(user); + map<string, string>::const_iterator p = _accounts.find(move(user)); if(p == _accounts.end()) { throw UserAccountNotFoundException(); diff --git a/cpp/src/IceGrid/FileUserAccountMapperI.h b/cpp/src/IceGrid/FileUserAccountMapperI.h index 4630654082e..915455c6d8e 100644 --- a/cpp/src/IceGrid/FileUserAccountMapperI.h +++ b/cpp/src/IceGrid/FileUserAccountMapperI.h @@ -16,7 +16,7 @@ public: FileUserAccountMapperI(const std::string&); - virtual std::string getUserAccount(const std::string&, const Ice::Current&); + std::string getUserAccount(std::string, const Ice::Current&) override; private: diff --git a/cpp/src/IceGrid/Grammar.cpp b/cpp/src/IceGrid/Grammar.cpp index 2e3a629ac00..13023be904c 100644 --- a/cpp/src/IceGrid/Grammar.cpp +++ b/cpp/src/IceGrid/Grammar.cpp @@ -58,8 +58,6 @@ /* Using locations. */ #define YYLSP_NEEDED 0 - - /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE @@ -148,13 +146,9 @@ #define ICE_GRID_ENABLE 295 #define ICE_GRID_DISABLE 296 - - - /* Copy the first part of user declarations. */ #line 1 "src/IceGrid/Grammar.y" - // // Copyright (c) ZeroC, Inc. All rights reserved. // @@ -198,8 +192,6 @@ yyerror(const char* s) parser->invalidCommand(s); } - - /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 1 @@ -225,11 +217,8 @@ typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 #endif - - /* Copy the second part of user declarations. */ - /* Line 216 of yacc.c. */ #line 235 "src/IceGrid/Grammar.cpp" @@ -386,7 +375,6 @@ void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) @@ -1356,7 +1344,6 @@ static const yytype_uint8 yystos[] = #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab - /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ @@ -1382,11 +1369,9 @@ do \ } \ while (YYID (0)) - #define YYTERROR 1 #define YYERRCODE 256 - /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ @@ -1412,7 +1397,6 @@ while (YYID (0)) while (YYID (0)) #endif - /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ @@ -1428,7 +1412,6 @@ while (YYID (0)) # endif #endif - /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM @@ -1462,7 +1445,6 @@ do { \ } \ } while (YYID (0)) - /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ @@ -1495,7 +1477,6 @@ yy_symbol_value_print (yyoutput, yytype, yyvaluep) } } - /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ @@ -1549,7 +1530,6 @@ do { \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) - /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ @@ -1597,7 +1577,6 @@ int yydebug; # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ - /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 @@ -1614,8 +1593,6 @@ int yydebug; # define YYMAXDEPTH 10000 #endif - - #if YYERROR_VERBOSE # ifndef yystrlen @@ -1876,9 +1853,26 @@ int yyparse (); #endif /* ! YYPARSE_PARAM */ + default: + break; + } +} +/* Prevent warnings from -Wmissing-prototypes. */ - +#ifdef YYPARSE_PARAM +#if defined __STDC__ || defined __cplusplus +int yyparse (void *YYPARSE_PARAM); +#else +int yyparse (); +#endif +#else /* ! YYPARSE_PARAM */ +#if defined __STDC__ || defined __cplusplus +int yyparse (void); +#else +int yyparse (); +#endif +#endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | @@ -1947,8 +1941,6 @@ int yynerrs; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; - - #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; @@ -1957,7 +1949,6 @@ int yynerrs; action routines. */ YYSTYPE yyval; - /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; @@ -2126,7 +2117,6 @@ yybackup: goto yynewstate; - /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ @@ -2136,7 +2126,6 @@ yydefault: goto yyerrlab; goto yyreduce; - /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ @@ -2154,7 +2143,6 @@ yyreduce: GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; - YY_REDUCE_PRINT (yyn); switch (yyn) { @@ -3309,7 +3297,6 @@ yyreduce: ;} break; - /* Line 1267 of yacc.c. */ #line 3315 "src/IceGrid/Grammar.cpp" default: break; @@ -3337,7 +3324,6 @@ yyreduce: goto yynewstate; - /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ @@ -3383,8 +3369,6 @@ yyerrlab: #endif } - - if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an @@ -3408,7 +3392,6 @@ yyerrlab: token. */ goto yyerrlab1; - /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ @@ -3428,7 +3411,6 @@ yyerrorlab: yystate = *yyssp; goto yyerrlab1; - /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ @@ -3453,7 +3435,6 @@ yyerrlab1: if (yyssp == yyss) YYABORT; - yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); @@ -3466,14 +3447,12 @@ yyerrlab1: *++yyvsp = yylval; - /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; - /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ @@ -3523,6 +3502,3 @@ yyreturn: /* Make sure YYID is used. */ return YYID (yyresult); } - - - diff --git a/cpp/src/IceGrid/Grammar.h b/cpp/src/IceGrid/Grammar.h index fb0c3c72213..9b8655708e2 100644 --- a/cpp/src/IceGrid/Grammar.h +++ b/cpp/src/IceGrid/Grammar.h @@ -121,15 +121,9 @@ #define ICE_GRID_ENABLE 295 #define ICE_GRID_DISABLE 296 - - - #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif - - - diff --git a/cpp/src/IceGrid/IceGridNode.cpp b/cpp/src/IceGrid/IceGridNode.cpp index 7d404da3fe5..22efdc6c601 100644 --- a/cpp/src/IceGrid/IceGridNode.cpp +++ b/cpp/src/IceGrid/IceGridNode.cpp @@ -31,68 +31,61 @@ using namespace Ice; using namespace IceInternal; using namespace IceGrid; -// Work-around for anonymous namspace bug in xlclang++ -#ifdef __ibmxl__ -namespace IceGridNodeNamespace -#else namespace -#endif { -class ProcessI : public Process +class ProcessI final : public Process { public: - ProcessI(const ActivatorPtr&, const ProcessPtr&); + ProcessI(const shared_ptr<Activator>&, const shared_ptr<Process>&); - virtual void shutdown(const Current&); - virtual void writeMessage(const std::string&, Int, const Current&); + void shutdown(const Current&) override; + void writeMessage(std::string, int, const Current&) override; private: - ActivatorPtr _activator; - ProcessPtr _origProcess; + shared_ptr<Activator> _activator; + shared_ptr<Process> _origProcess; }; -class NodeService : public Service +class NodeService final : public Service { public: - NodeService(); - ~NodeService(); - - virtual bool shutdown(); + bool shutdown() override; protected: - virtual bool start(int, char*[], int&); + bool start(int, char*[], int&) override; bool startImpl(int, char*[], int&); - virtual void waitForShutdown(); - virtual bool stop(); - virtual CommunicatorPtr initializeCommunicator(int&, char*[], const InitializationData&, int); + void waitForShutdown() override; + bool stop() override; + shared_ptr<Communicator> initializeCommunicator(int&, char*[], const InitializationData&, int) override; private: void usage(const std::string&); - ActivatorPtr _activator; + shared_ptr<Activator> _activator; IceUtil::TimerPtr _timer; - RegistryIPtr _registry; - NodeIPtr _node; - IceInternal::UniquePtr<NodeSessionManager> _sessions; - Ice::ObjectAdapterPtr _adapter; + shared_ptr<RegistryI> _registry; + shared_ptr<NodeI> _node; + unique_ptr<NodeSessionManager> _sessions; + shared_ptr<ObjectAdapter> _adapter; }; -class CollocatedRegistry : public RegistryI +class CollocatedRegistry final : public RegistryI { public: - CollocatedRegistry(const CommunicatorPtr&, const ActivatorPtr&, bool, bool, const std::string&, const std::string&); - virtual void shutdown(); + CollocatedRegistry(const shared_ptr<Communicator>&, const shared_ptr<Activator>&, bool, bool, const std::string&, + const std::string&); + void shutdown() override; private: - ActivatorPtr _activator; + shared_ptr<Activator> _activator; }; #ifdef _WIN32 @@ -114,17 +107,13 @@ setNoIndexingAttribute(const string& path) } -#ifdef __ibmxl__ -using namespace IceGridNodeNamespace; -#endif - -CollocatedRegistry::CollocatedRegistry(const CommunicatorPtr& com, - const ActivatorPtr& activator, +CollocatedRegistry::CollocatedRegistry(const shared_ptr<Communicator>& com, + const shared_ptr<Activator>& activator, bool nowarn, bool readonly, const string& initFromReplica, const string& nodeName) : - RegistryI(com, new TraceLevels(com, "IceGrid.Registry"), nowarn, readonly, initFromReplica, nodeName), + RegistryI(com, make_shared<TraceLevels>(com, "IceGrid.Registry"), nowarn, readonly, initFromReplica, nodeName), _activator(activator) { } @@ -135,7 +124,7 @@ CollocatedRegistry::shutdown() _activator->shutdown(); } -ProcessI::ProcessI(const ActivatorPtr& activator, const ProcessPtr& origProcess) : +ProcessI::ProcessI(const shared_ptr<Activator>& activator, const shared_ptr<Process>& origProcess) : _activator(activator), _origProcess(origProcess) { @@ -148,17 +137,9 @@ ProcessI::shutdown(const Current&) } void -ProcessI::writeMessage(const string& message, Int fd, const Current& current) -{ - _origProcess->writeMessage(message, fd, current); -} - -NodeService::NodeService() -{ -} - -NodeService::~NodeService() +ProcessI::writeMessage(string message, int fd, const Current& current) { + _origProcess->writeMessage(move(message), move(fd), current); } bool @@ -265,7 +246,7 @@ NodeService::startImpl(int argc, char* argv[], int& status) } } - PropertiesPtr properties = communicator()->getProperties(); + auto properties = communicator()->getProperties(); string name = properties->getProperty("IceGrid.Node.Name"); if(name.empty()) @@ -300,15 +281,15 @@ NodeService::startImpl(int argc, char* argv[], int& status) // // Create the activator. // - TraceLevelsPtr traceLevels = new TraceLevels(communicator(), "IceGrid.Node"); - _activator = new Activator(traceLevels); + auto traceLevels = make_shared<TraceLevels>(communicator(), "IceGrid.Node"); + _activator = make_shared<Activator>(traceLevels); // // Collocate the IceGrid registry if we need to. // if(properties->getPropertyAsInt("IceGrid.Node.CollocateRegistry") > 0) { - _registry = new CollocatedRegistry(communicator(), _activator, nowarn, readonly, initFromReplica, name); + _registry = make_shared<CollocatedRegistry>(communicator(), _activator, nowarn, readonly, initFromReplica, name); if(!_registry->start()) { return false; @@ -405,12 +386,12 @@ NodeService::startImpl(int argc, char* argv[], int& status) // string mapperProperty = "IceGrid.Node.UserAccountMapper"; string mapperPropertyValue = properties->getProperty(mapperProperty); - UserAccountMapperPrx mapper; + shared_ptr<UserAccountMapperPrx> mapper; if(!mapperPropertyValue.empty()) { try { - mapper = UserAccountMapperPrx::uncheckedCast(communicator()->propertyToProxy(mapperProperty)); + mapper = uncheckedCast<UserAccountMapperPrx>(communicator()->propertyToProxy(mapperProperty)); } catch(const std::exception& ex) { @@ -426,8 +407,8 @@ NodeService::startImpl(int argc, char* argv[], int& status) { try { - Ice::ObjectPrx object = _adapter->addWithUUID(new FileUserAccountMapperI(userAccountFileProperty)); - mapper = UserAccountMapperPrx::uncheckedCast(object); + auto object = _adapter->addWithUUID(make_shared<FileUserAccountMapperI>(userAccountFileProperty)); + mapper = uncheckedCast<UserAccountMapperPrx>(object); } catch(const exception& ex) { @@ -440,7 +421,7 @@ NodeService::startImpl(int argc, char* argv[], int& status) // // Create a new timer to handle server activation/deactivation timeouts. // - _timer = new IceUtil::Timer(); + _timer = new IceUtil::Timer; // // The IceGrid instance name. @@ -459,7 +440,7 @@ NodeService::startImpl(int argc, char* argv[], int& status) instanceName = "IceGrid"; } - _sessions.reset(new NodeSessionManager(communicator(), instanceName)); + _sessions = make_unique<NodeSessionManager>(communicator(), instanceName); // // Create the server factory. The server factory creates persistent objects @@ -467,18 +448,19 @@ NodeService::startImpl(int argc, char* argv[], int& status) // evictors and object factories necessary to store these objects. // Identity id = stringToIdentity(instanceName + "/Node-" + name); - NodePrx nodeProxy = NodePrx::uncheckedCast(_adapter->createProxy(id)); - _node = new NodeI(_adapter, *_sessions, _activator, _timer, traceLevels, nodeProxy, name, mapper, instanceName); + auto nodeProxy = uncheckedCast<NodePrx>(_adapter->createProxy(id)); + _node = make_shared<NodeI>(_adapter, *_sessions, _activator, _timer, traceLevels, nodeProxy, name, mapper, + instanceName); _adapter->add(_node, nodeProxy->ice_getIdentity()); - _adapter->addDefaultServant(new NodeServerAdminRouter(_node), _node->getServerAdminCategory()); + _adapter->addDefaultServant(make_shared<NodeServerAdminRouter>(_node), _node->getServerAdminCategory()); // // Keep the old default servant for backward compatibility with IceGrid registries 3.5 that // still forward requests to this category. This can be removed when we decide to break // backward compatibility with 3.5 registries. // - _adapter->addDefaultServant(new NodeServerAdminRouter(_node), instanceName + "-NodeRouter"); + _adapter->addDefaultServant(make_shared<NodeServerAdminRouter>(_node), instanceName + "-NodeRouter"); // // Start the platform info thread if needed. @@ -514,13 +496,9 @@ NodeService::startImpl(int argc, char* argv[], int& status) if(!_registry && properties->getPropertyAsInt("Ice.Admin.Enabled") > 0) { // Replace Admin facet - ProcessPtr origProcess = ProcessPtr::dynamicCast(communicator()->removeAdminFacet("Process")); - communicator()->addAdminFacet(new ProcessI(_activator, origProcess), "Process"); - - Identity adminId; - adminId.name = "NodeAdmin-" + name; - adminId.category = instanceName; - communicator()->createAdmin(_adapter, adminId); + auto origProcess = dynamic_pointer_cast<Process>(communicator()->removeAdminFacet("Process")); + communicator()->addAdminFacet(make_shared<ProcessI>(_activator, origProcess), "Process"); + communicator()->createAdmin(_adapter, { "NodeAdmin-" + name, instanceName }); } // @@ -561,11 +539,9 @@ NodeService::startImpl(int argc, char* argv[], int& status) { try { - Ice::Identity regId; - regId.category = instanceName; - regId.name = "Registry"; + Ice::Identity regId = { "Registry", instanceName }; - RegistryPrx registry = RegistryPrx::checkedCast(communicator()->getDefaultLocator()->findObjectById(regId)); + auto registry = checkedCast<RegistryPrx>(communicator()->getDefaultLocator()->findObjectById(regId)); if(!registry) { throw runtime_error("invalid registry"); @@ -573,7 +549,7 @@ NodeService::startImpl(int argc, char* argv[], int& status) registry = registry->ice_preferSecure(true); // Use SSL if available. - IceGrid::AdminSessionPrx session; + shared_ptr<AdminSessionPrx> session; if(communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.AuthenticateUsingSSL")) { session = registry->createAdminSessionFromSecureConnection(); @@ -600,9 +576,9 @@ NodeService::startImpl(int argc, char* argv[], int& status) } assert(session); - AdminPrx admin = session->getAdmin(); + auto admin = session->getAdmin(); map<string, string> vars; - ApplicationDescriptor app = DescriptorParser::parseDescriptor(desc, targets, vars, communicator(), admin); + auto app = DescriptorParser::parseDescriptor(desc, targets, vars, communicator(), admin); try { @@ -681,7 +657,7 @@ NodeService::stop() { assert(false); } - _timer = 0; + _timer = nullptr; } // @@ -692,7 +668,7 @@ NodeService::stop() try { _adapter->deactivate(); - _adapter = 0; + _adapter = nullptr; } catch(const std::exception& ex) { @@ -737,7 +713,7 @@ NodeService::stop() if(_node) { _node->shutdown(); - _node = 0; + _node = nullptr; } // @@ -746,13 +722,13 @@ NodeService::stop() if(_registry) { _registry->stop(); - _registry = 0; + _registry = nullptr; } return true; } -CommunicatorPtr +shared_ptr<Communicator> NodeService::initializeCommunicator(int& argc, char* argv[], const InitializationData& initializationData, int version) @@ -768,20 +744,20 @@ NodeService::initializeCommunicator(int& argc, char* argv[], vTypes.push_back(""); vTypes.push_back("Admin"); - for(vector<string>::const_iterator p = vTypes.begin(); p != vTypes.end(); ++p) + for(const auto& type : vTypes) { - string verifier = "IceGrid.Registry." + *p + "PermissionsVerifier"; + string verifier = "IceGrid.Registry." + type + "PermissionsVerifier"; if(initData.properties->getProperty(verifier).empty()) { - string cryptPasswords = initData.properties->getProperty("IceGrid.Registry." + *p + "CryptPasswords"); + string cryptPasswords = initData.properties->getProperty("IceGrid.Registry." + type + "CryptPasswords"); if(!cryptPasswords.empty()) { initData.properties->setProperty("Ice.Plugin.Glacier2CryptPermissionsVerifier", "Glacier2CryptPermissionsVerifier:createCryptPermissionsVerifier"); - initData.properties->setProperty("Glacier2CryptPermissionsVerifier.IceGrid.Registry." + *p + + initData.properties->setProperty("Glacier2CryptPermissionsVerifier.IceGrid.Registry." + type + "PermissionsVerifier", cryptPasswords); } } diff --git a/cpp/src/IceGrid/IceGridRegistry.cpp b/cpp/src/IceGrid/IceGridRegistry.cpp index 34cea54dc50..04f6c7f2f33 100644 --- a/cpp/src/IceGrid/IceGridRegistry.cpp +++ b/cpp/src/IceGrid/IceGridRegistry.cpp @@ -22,35 +22,24 @@ class RegistryService : public Service { public: - RegistryService(); - ~RegistryService(); - - virtual bool shutdown(); + bool shutdown() override; protected: - virtual bool start(int, char*[], int&); - virtual void waitForShutdown(); - virtual bool stop(); - virtual CommunicatorPtr initializeCommunicator(int&, char*[], const InitializationData&, int); + bool start(int, char*[], int&) override; + void waitForShutdown() override; + bool stop() override; + shared_ptr<Communicator> initializeCommunicator(int&, char*[], const InitializationData&, int) override; private: void usage(const std::string&); - RegistryIPtr _registry; + shared_ptr<RegistryI> _registry; }; } // End of namespace IceGrid -RegistryService::RegistryService() -{ -} - -RegistryService::~RegistryService() -{ -} - bool RegistryService::shutdown() { @@ -111,7 +100,7 @@ RegistryService::start(int argc, char* argv[], int& status) return false; } - Ice::PropertiesPtr properties = communicator()->getProperties(); + auto properties = communicator()->getProperties(); // // Warn the user that setting Ice.ThreadPool.Server isn't useful. @@ -123,9 +112,9 @@ RegistryService::start(int argc, char* argv[], int& status) out << "you should set individual adapter thread pools instead."; } - TraceLevelsPtr traceLevels = new TraceLevels(communicator(), "IceGrid.Registry"); + auto traceLevels = make_shared<TraceLevels>(communicator(), "IceGrid.Registry"); - _registry = new RegistryI(communicator(), traceLevels, nowarn, readonly, initFromReplica, ""); + _registry = make_shared<RegistryI>(communicator(), traceLevels, nowarn, readonly, initFromReplica, ""); if(!_registry->start()) { return false; @@ -153,7 +142,7 @@ RegistryService::stop() return true; } -CommunicatorPtr +shared_ptr<Communicator> RegistryService::initializeCommunicator(int& argc, char* argv[], const InitializationData& initializationData, int version) diff --git a/cpp/src/IceGrid/Internal.ice b/cpp/src/IceGrid/Internal.ice index dabf62015e4..d273e2879ef 100644 --- a/cpp/src/IceGrid/Internal.ice +++ b/cpp/src/IceGrid/Internal.ice @@ -9,7 +9,6 @@ #include <Ice/Identity.ice> #include <Ice/BuiltinSequences.ice> #include <Ice/ProcessF.ice> -#include <Ice/Properties.ice> #include <Glacier2/Session.ice> #include <IceGrid/Admin.ice> @@ -22,6 +21,8 @@ local exception SynchronizationException { } +// This class is no longer used. We keep it only for interop with IceGrid 3.7. +// class InternalDbEnvDescriptor { /** The name of the database environment. */ @@ -111,7 +112,7 @@ class InternalServerDescriptor /** The indirect object adapters. */ InternalAdapterDescriptorSeq adapters; - /** The database environments. */ + // Not used, always empty. Kept only for interop with IceGrid 3.7. InternalDbEnvDescriptorSeq dbEnvs; /** The configuration files of the server. */ @@ -514,11 +515,11 @@ exception ReplicaActiveException enum TopicName { - RegistryObserverTopicName, - NodeObserverTopicName, - ApplicationObserverTopicName, - AdapterObserverTopicName, - ObjectObserverTopicName + RegistryObserver, + NodeObserver, + ApplicationObserver, + AdapterObserver, + ObjectObserver } interface DatabaseObserver extends ApplicationObserver, ObjectObserver, AdapterObserver diff --git a/cpp/src/IceGrid/InternalRegistryI.cpp b/cpp/src/IceGrid/InternalRegistryI.cpp index 379743d6cf6..a1db6e6e49e 100644 --- a/cpp/src/IceGrid/InternalRegistryI.cpp +++ b/cpp/src/IceGrid/InternalRegistryI.cpp @@ -21,47 +21,43 @@ using namespace std; using namespace IceGrid; -InternalRegistryI::InternalRegistryI(const RegistryIPtr& registry, - const DatabasePtr& database, - const ReapThreadPtr& reaper, - const WellKnownObjectsManagerPtr& wellKnownObjects, +InternalRegistryI::InternalRegistryI(const shared_ptr<RegistryI>& registry, + const shared_ptr<Database>& database, + const shared_ptr<ReapThread>& reaper, + const shared_ptr<WellKnownObjectsManager>& wellKnownObjects, ReplicaSessionManager& session) : _registry(registry), _database(database), _reaper(reaper), _wellKnownObjects(wellKnownObjects), - _fileCache(new FileCache(database->getCommunicator())), + _fileCache(make_shared<FileCache>(database->getCommunicator())), _session(session) { - Ice::PropertiesPtr properties = database->getCommunicator()->getProperties(); - _nodeSessionTimeout = properties->getPropertyAsIntWithDefault("IceGrid.Registry.NodeSessionTimeout", 30); - _replicaSessionTimeout = properties->getPropertyAsIntWithDefault("IceGrid.Registry.ReplicaSessionTimeout", 30); + auto properties = database->getCommunicator()->getProperties(); + _nodeSessionTimeout = + chrono::seconds(properties->getPropertyAsIntWithDefault("IceGrid.Registry.NodeSessionTimeout", 30)); + _replicaSessionTimeout = + chrono::seconds(properties->getPropertyAsIntWithDefault("IceGrid.Registry.ReplicaSessionTimeout", 30)); _requireNodeCertCN = properties->getPropertyAsIntWithDefault("IceGrid.Registry.RequireNodeCertCN", 0); _requireReplicaCertCN = properties->getPropertyAsIntWithDefault("IceGrid.Registry.RequireReplicaCertCN", 0); } -InternalRegistryI::~InternalRegistryI() -{ -} - -NodeSessionPrx -InternalRegistryI::registerNode(const InternalNodeInfoPtr& info, - const NodePrx& node, - const LoadInfo& load, +shared_ptr<NodeSessionPrx> +InternalRegistryI::registerNode(shared_ptr<InternalNodeInfo> info, shared_ptr<NodePrx> node, LoadInfo load, const Ice::Current& current) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); - const Ice::LoggerPtr logger = traceLevels->logger; + const auto traceLevels = _database->getTraceLevels(); + const auto logger = traceLevels->logger; if(!info || !node) { - return 0; + return nullptr; } if(_requireNodeCertCN) { try { - IceSSL::ConnectionInfoPtr sslConnInfo = IceSSL::ConnectionInfoPtr::dynamicCast(current.con->getInfo()); + auto sslConnInfo = dynamic_pointer_cast<IceSSL::ConnectionInfo>(current.con->getInfo()); if(sslConnInfo) { if (sslConnInfo->certs.empty() || @@ -102,8 +98,8 @@ InternalRegistryI::registerNode(const InternalNodeInfoPtr& info, try { - NodeSessionIPtr session = new NodeSessionI(_database, node, info, _nodeSessionTimeout, load); - _reaper->add(new SessionReapable<NodeSessionI>(logger, session), _nodeSessionTimeout); + auto session = NodeSessionI::create(_database, node, info, _nodeSessionTimeout, load); + _reaper->add(make_shared<SessionReapable<NodeSessionI>>(logger, session), _nodeSessionTimeout); return session->getProxy(); } catch(const Ice::ObjectAdapterDeactivatedException&) @@ -112,23 +108,23 @@ InternalRegistryI::registerNode(const InternalNodeInfoPtr& info, } } -ReplicaSessionPrx -InternalRegistryI::registerReplica(const InternalReplicaInfoPtr& info, - const InternalRegistryPrx& prx, +shared_ptr<ReplicaSessionPrx> +InternalRegistryI::registerReplica(shared_ptr<InternalReplicaInfo> info, + shared_ptr<InternalRegistryPrx> prx, const Ice::Current& current) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); - const Ice::LoggerPtr logger = traceLevels->logger; + const auto traceLevels = _database->getTraceLevels(); + const auto logger = traceLevels->logger; if(!info || !prx) { - return 0; + return nullptr; } if(_requireReplicaCertCN) { try { - IceSSL::ConnectionInfoPtr sslConnInfo = IceSSL::ConnectionInfoPtr::dynamicCast(current.con->getInfo()); + auto sslConnInfo = dynamic_pointer_cast<IceSSL::ConnectionInfo>(current.con->getInfo()); if(sslConnInfo) { if (sslConnInfo->certs.empty() || @@ -169,8 +165,8 @@ InternalRegistryI::registerReplica(const InternalReplicaInfoPtr& info, try { - ReplicaSessionIPtr s = new ReplicaSessionI(_database, _wellKnownObjects, info, prx, _replicaSessionTimeout); - _reaper->add(new SessionReapable<ReplicaSessionI>(logger, s), _replicaSessionTimeout); + auto s = ReplicaSessionI::create(_database, _wellKnownObjects, info, prx, _replicaSessionTimeout); + _reaper->add(make_shared<SessionReapable<ReplicaSessionI>>(logger, s), _replicaSessionTimeout); return s->getProxy(); } catch(const Ice::ObjectAdapterDeactivatedException&) @@ -180,9 +176,9 @@ InternalRegistryI::registerReplica(const InternalReplicaInfoPtr& info, } void -InternalRegistryI::registerWithReplica(const InternalRegistryPrx& replica, const Ice::Current&) +InternalRegistryI::registerWithReplica(shared_ptr<InternalRegistryPrx> replica, const Ice::Current&) { - _session.create(replica); + _session.create(move(replica)); } NodePrxSeq @@ -192,7 +188,7 @@ InternalRegistryI::getNodes(const Ice::Current&) const Ice::ObjectProxySeq proxies = _database->getInternalObjectsByType(Node::ice_staticId()); for(Ice::ObjectProxySeq::const_iterator p = proxies.begin(); p != proxies.end(); ++p) { - nodes.push_back(NodePrx::uncheckedCast(*p)); + nodes.push_back(Ice::uncheckedCast<NodePrx>(*p)); } return nodes; } @@ -204,25 +200,25 @@ InternalRegistryI::getReplicas(const Ice::Current&) const Ice::ObjectProxySeq proxies = _database->getObjectsByType(InternalRegistry::ice_staticId()); for(Ice::ObjectProxySeq::const_iterator p = proxies.begin(); p != proxies.end(); ++p) { - replicas.push_back(InternalRegistryPrx::uncheckedCast(*p)); + replicas.push_back(Ice::uncheckedCast<InternalRegistryPrx>(*p)); } return replicas; } ApplicationInfoSeq -InternalRegistryI::getApplications(Ice::Long& serial, const Ice::Current&) const +InternalRegistryI::getApplications(long long& serial, const Ice::Current&) const { return _database->getApplications(serial); } AdapterInfoSeq -InternalRegistryI::getAdapters(Ice::Long& serial, const Ice::Current&) const +InternalRegistryI::getAdapters(long long& serial, const Ice::Current&) const { return _database->getAdapters(serial); } ObjectInfoSeq -InternalRegistryI::getObjects(Ice::Long& serial, const Ice::Current&) const +InternalRegistryI::getObjects(long long& serial, const Ice::Current&) const { return _database->getObjects(serial); } @@ -233,14 +229,14 @@ InternalRegistryI::shutdown(const Ice::Current& /*current*/) const _registry->shutdown(); } -Ice::Long -InternalRegistryI::getOffsetFromEnd(const string& filename, int count, const Ice::Current&) const +long long +InternalRegistryI::getOffsetFromEnd(string filename, int count, const Ice::Current&) const { return _fileCache->getOffsetFromEnd(getFilePath(filename), count); } bool -InternalRegistryI::read(const string& filename, Ice::Long pos, int size, Ice::Long& newPos, Ice::StringSeq& lines, +InternalRegistryI::read(string filename, long long pos, int size, long long& newPos, Ice::StringSeq& lines, const Ice::Current&) const { return _fileCache->read(getFilePath(filename), pos, size, newPos, lines); diff --git a/cpp/src/IceGrid/InternalRegistryI.h b/cpp/src/IceGrid/InternalRegistryI.h index 9333650f7ae..f90637f66c6 100644 --- a/cpp/src/IceGrid/InternalRegistryI.h +++ b/cpp/src/IceGrid/InternalRegistryI.h @@ -12,61 +12,52 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - class FileCache; -typedef IceUtil::Handle<FileCache> FileCachePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle<WellKnownObjectsManager> WellKnownObjectsManagerPtr; - class ReapThread; -typedef IceUtil::Handle<ReapThread> ReapThreadPtr; - class RegistryI; -typedef IceUtil::Handle<RegistryI> RegistryIPtr; - class ReplicaSessionManager; +class WellKnownObjectsManager; class InternalRegistryI : public InternalRegistry { public: - InternalRegistryI(const RegistryIPtr&, const DatabasePtr&, const ReapThreadPtr&, - const WellKnownObjectsManagerPtr&, ReplicaSessionManager&); - virtual ~InternalRegistryI(); + InternalRegistryI(const std::shared_ptr<RegistryI>&, const std::shared_ptr<Database>&, + const std::shared_ptr<ReapThread>&, const std::shared_ptr<WellKnownObjectsManager>&, + ReplicaSessionManager&); - virtual NodeSessionPrx registerNode(const InternalNodeInfoPtr&, const NodePrx&, const LoadInfo&, - const Ice::Current&); - virtual ReplicaSessionPrx registerReplica(const InternalReplicaInfoPtr&, const InternalRegistryPrx&, - const Ice::Current&); + std::shared_ptr<NodeSessionPrx> registerNode(std::shared_ptr<InternalNodeInfo>, std::shared_ptr<NodePrx>, LoadInfo, + const Ice::Current&) override; + std::shared_ptr<ReplicaSessionPrx> registerReplica(std::shared_ptr<InternalReplicaInfo>, + std::shared_ptr<InternalRegistryPrx>, + const Ice::Current&) override; - virtual void registerWithReplica(const InternalRegistryPrx&, const Ice::Current&); + void registerWithReplica(std::shared_ptr<InternalRegistryPrx>, const Ice::Current&) override; - virtual NodePrxSeq getNodes(const Ice::Current&) const; - virtual InternalRegistryPrxSeq getReplicas(const Ice::Current&) const; + NodePrxSeq getNodes(const Ice::Current&) const override; + InternalRegistryPrxSeq getReplicas(const Ice::Current&) const override; - virtual ApplicationInfoSeq getApplications(Ice::Long&, const Ice::Current&) const; - virtual AdapterInfoSeq getAdapters(Ice::Long&, const Ice::Current&) const; - virtual ObjectInfoSeq getObjects(Ice::Long&, const Ice::Current&) const; + ApplicationInfoSeq getApplications(long long&, const Ice::Current&) const override; + AdapterInfoSeq getAdapters(long long&, const Ice::Current&) const override; + ObjectInfoSeq getObjects(long long&, const Ice::Current&) const override; - virtual void shutdown(const Ice::Current&) const; + void shutdown(const Ice::Current&) const override; - virtual Ice::Long getOffsetFromEnd(const std::string&, int, const Ice::Current&) const; - virtual bool read(const std::string&, Ice::Long, int, Ice::Long&, Ice::StringSeq&, const Ice::Current&) const; + long long getOffsetFromEnd(std::string, int, const Ice::Current&) const override; + bool read(std::string, long long, int, long long&, Ice::StringSeq&, const Ice::Current&) const override; private: std::string getFilePath(const std::string&) const; - const RegistryIPtr _registry; - const DatabasePtr _database; - const ReapThreadPtr _reaper; - const WellKnownObjectsManagerPtr _wellKnownObjects; - const FileCachePtr _fileCache; + const std::shared_ptr<RegistryI> _registry; + const std::shared_ptr<Database> _database; + const std::shared_ptr<ReapThread> _reaper; + const std::shared_ptr<WellKnownObjectsManager> _wellKnownObjects; + const std::shared_ptr<FileCache> _fileCache; ReplicaSessionManager& _session; - int _nodeSessionTimeout; - int _replicaSessionTimeout; + std::chrono::seconds _nodeSessionTimeout; + std::chrono::seconds _replicaSessionTimeout; bool _requireNodeCertCN; bool _requireReplicaCertCN; }; diff --git a/cpp/src/IceGrid/LocatorI.cpp b/cpp/src/IceGrid/LocatorI.cpp index ae21fa49175..e6da5a12384 100644 --- a/cpp/src/IceGrid/LocatorI.cpp +++ b/cpp/src/IceGrid/LocatorI.cpp @@ -8,153 +8,26 @@ #include <IceGrid/WellKnownObjectsManager.h> #include <IceGrid/SessionI.h> #include <IceGrid/Util.h> +#include <IceGrid/Internal.h> using namespace std; +using namespace std::chrono; using namespace IceGrid; -namespace IceGrid +namespace { -// -// Callback from asynchronous call to adapter->getDirectProxy() invoked in LocatorI::findAdapterById_async(). -// -class AdapterGetDirectProxyCallback : public virtual IceUtil::Shared -{ -public: - - AdapterGetDirectProxyCallback(const LocatorIPtr& locator, const LocatorAdapterInfo& adapter) : - _locator(locator), _adapter(adapter) - { - } - - virtual void response(const ::Ice::ObjectPrx& obj) - { - assert(obj); - _locator->getDirectProxyResponse(_adapter, obj); - } - - virtual void exception(const ::Ice::Exception& e) - { - _locator->getDirectProxyException(_adapter, e); - } - -private: - - const LocatorIPtr _locator; - const LocatorAdapterInfo _adapter; -}; - -class AdapterActivateCallback : public virtual IceUtil::Shared -{ -public: - - AdapterActivateCallback(const LocatorIPtr& locator, const LocatorAdapterInfo& adapter) : - _locator(locator), _adapter(adapter) - { - } - - virtual void response(const ::Ice::ObjectPrx& obj) - { - _locator->getDirectProxyResponse(_adapter, obj); - } - - virtual void exception(const ::Ice::Exception& ex) - { - _locator->getDirectProxyException(_adapter, ex); - } - -private: - - const LocatorIPtr _locator; - const LocatorAdapterInfo _adapter; -}; - -// -// Callback from asynchrnous call to LocatorI::findAdapterById_async() -// invoked in LocatorI::findObjectById_async(). -// -class AMD_Locator_findAdapterByIdI : public Ice::AMD_Locator_findAdapterById +class AdapterRequest final : public LocatorI::Request { public: - AMD_Locator_findAdapterByIdI(const Ice::AMD_Locator_findObjectByIdPtr& cb, const Ice::ObjectPrx& obj) : - _cb(cb), - _obj(obj) - { - } - - virtual void ice_response(const ::Ice::ObjectPrx& obj) - { - // - // If the adapter dummy direct proxy is not null, return a - // proxy containing the identity we were looking for and the - // endpoints of the adapter. - // - // If null, return the proxy registered with the object - // registry. - // - if(obj) - { - _cb->ice_response(obj->ice_identity(_obj->ice_getIdentity())); - } - else - { - _cb->ice_response(_obj); - } - } - - virtual void ice_exception(const ::Ice::Exception& ex) - { - try - { - ex.ice_throw(); - } - catch(const Ice::AdapterNotFoundException&) - { - // - // We couldn't find the adapter, we ignore and return the - // original proxy containing the adapter id. - // - _cb->ice_response(_obj); - return; - } - catch(const Ice::Exception& e) - { - // - // Rethrow unexpected exception. - // - _cb->ice_exception(e); - return; - } - - assert(false); - } - - virtual void ice_exception(const std::exception& ex) - { - _cb->ice_exception(ex); - } - - virtual void ice_exception() - { - _cb->ice_exception(); - } - -private: - - const Ice::AMD_Locator_findObjectByIdPtr _cb; - const Ice::ObjectPrx _obj; -}; - -class AdapterRequest : public LocatorI::Request -{ -public: - - AdapterRequest(const Ice::AMD_Locator_findAdapterByIdPtr& amdCB, - const LocatorIPtr& locator, + AdapterRequest(function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)> exception, + const shared_ptr<LocatorI>& locator, const Ice::EncodingVersion& encoding, const LocatorAdapterInfo& adapter) : - _amdCB(amdCB), + _response(move(response)), + _exception(move(exception)), _locator(locator), _encoding(encoding), _adapter(adapter), @@ -163,20 +36,20 @@ public: assert(_adapter.proxy); } - virtual void - execute() + void + execute() override { - _locator->getDirectProxy(_adapter, this); + _locator->getDirectProxy(_adapter, shared_from_this()); } - virtual void - activating(const string&) + void + activating(const string&) override { // Nothing to do. } - virtual void - response(const std::string& id, const Ice::ObjectPrx& proxy) + void + response(const std::string& id, const shared_ptr<Ice::ObjectPrx>& proxy) override { assert(proxy); @@ -185,49 +58,52 @@ public: // if(!IceInternal::isSupported(_encoding, proxy->ice_getEncodingVersion())) { - exception(id, Ice::UnsupportedEncodingException(__FILE__, - __LINE__, - "server doesn't support requested encoding", - _encoding, - proxy->ice_getEncodingVersion())); + exception(id, + make_exception_ptr(Ice::UnsupportedEncodingException(__FILE__, __LINE__, + "server doesn't support requested encoding", + _encoding, + proxy->ice_getEncodingVersion()))); return; } - _amdCB->ice_response(proxy->ice_identity(Ice::stringToIdentity("dummy"))); + _response(proxy->ice_identity(Ice::stringToIdentity("dummy"))); } - virtual void - exception(const std::string&, const Ice::Exception& ex) + void + exception(const std::string&, exception_ptr ex) override { if(_traceLevels->locator > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); out << "couldn't resolve adapter`" << _adapter.id << "' endpoints:\n" << toString(ex); } - _amdCB->ice_response(0); + _response(nullptr); } private: - const Ice::AMD_Locator_findAdapterByIdPtr _amdCB; - const LocatorIPtr _locator; + const function<void(const shared_ptr<Ice::ObjectPrx>&)> _response; + const function<void(exception_ptr)> _exception; + const shared_ptr<LocatorI> _locator; const Ice::EncodingVersion _encoding; const LocatorAdapterInfo _adapter; - const TraceLevelsPtr _traceLevels; + const shared_ptr<TraceLevels> _traceLevels; }; -class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex +class ReplicaGroupRequest final : public LocatorI::Request { public: - ReplicaGroupRequest(const Ice::AMD_Locator_findAdapterByIdPtr& amdCB, - const LocatorIPtr& locator, + ReplicaGroupRequest(function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)> exception, + const shared_ptr<LocatorI>& locator, const string& id, const Ice::EncodingVersion& encoding, const LocatorAdapterInfoSeq& adapters, int count, - Ice::ObjectPrx firstProxy) : - _amdCB(amdCB), + shared_ptr<Ice::ObjectPrx> firstProxy) : + _response(move(response)), + _exception(move(exception)), _locator(locator), _id(id), _encoding(encoding), @@ -254,15 +130,15 @@ public: } } - virtual void - execute() + void + execute() override { // // Otherwise, request as many adapters as required. // LocatorAdapterInfoSeq adapters; { - Lock sync(*this); + lock_guard lock(_mutex); for(unsigned int i = static_cast<unsigned int>(_proxies.size()); i < _count; ++i) { if(_lastAdapter == _adapters.end()) @@ -286,17 +162,17 @@ public: } } - for(LocatorAdapterInfoSeq::const_iterator p = adapters.begin(); p != adapters.end(); ++p) + for(const auto& adapter : adapters) { - if(_locator->getDirectProxy(*p, this)) + if(_locator->getDirectProxy(adapter, shared_from_this())) { - activating(p->id); + activating(adapter.id); } } } - virtual void - activating(const string&) + void + activating(const string&) override { // // An adapter is being activated. Don't wait for the activation to complete. Instead, @@ -305,7 +181,7 @@ public: LocatorAdapterInfo adapter; do { - Lock sync(*this); + lock_guard lock(_mutex); if(_lastAdapter == _adapters.end()) { break; @@ -313,23 +189,23 @@ public: adapter = *_lastAdapter; ++_lastAdapter; } - while(_locator->getDirectProxy(adapter, this)); + while(_locator->getDirectProxy(adapter, shared_from_this())); } - virtual void - exception(const string& /*id*/, const Ice::Exception& ex) + void + exception(const string&, exception_ptr exptr) override { LocatorAdapterInfo adapter; { - Lock sync(*this); + lock_guard lock(_mutex); if(_proxies.size() == _count) // Nothing to do if we already sent the response. { return; } - if(!_exception.get()) + if(!_exptr) { - _exception.reset(ex.ice_clone()); + _exptr = exptr; } if(_lastAdapter == _adapters.end()) @@ -354,30 +230,31 @@ public: if(adapter.proxy) { - if(_locator->getDirectProxy(adapter, this)) + if(_locator->getDirectProxy(adapter, shared_from_this())) { activating(adapter.id); } } } - virtual void - response(const string& id, const Ice::ObjectPrx& proxy) + void + response(const string& id, const shared_ptr<Ice::ObjectPrx>& proxy) override { // // Ensure the server supports the request encoding. // if(!IceInternal::isSupported(_encoding, proxy->ice_getEncodingVersion())) { - exception(id, Ice::UnsupportedEncodingException(__FILE__, - __LINE__, - "server doesn't support requested encoding", - _encoding, - proxy->ice_getEncodingVersion())); + exception(id, + make_exception_ptr(Ice::UnsupportedEncodingException(__FILE__, + __LINE__, + "server doesn't support requested encoding", + _encoding, + proxy->ice_getEncodingVersion()))); return; } - Lock sync(*this); + lock_guard lock(_mutex); assert(proxy); if(_proxies.size() == _count) // Nothing to do if we already sent the response. { @@ -403,7 +280,7 @@ private: { if(_proxies.size() == 1) { - _amdCB->ice_response(_proxies.begin()->second); + _response(_proxies.begin()->second); } else if(_proxies.empty()) { @@ -411,58 +288,63 @@ private: // If there's no proxies, it's either because we couldn't contact the adapters or // because the replica group has no members. // - assert(_exception.get() || _adapters.empty()); + assert(_exptr || _adapters.empty()); if(_traceLevels->locator > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); out << "couldn't resolve replica group `" << _id << "' endpoints:\n"; - out << (_exception.get() ? toString(*_exception) : string("replica group is empty")); + out << (_exptr ? toString(_exptr) : string("replica group is empty")); } - _amdCB->ice_response(0); + _response(nullptr); } else if(_proxies.size() > 1) { Ice::EndpointSeq endpoints; endpoints.reserve(_proxies.size()); - for(LocatorAdapterInfoSeq::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + for(const auto& adapter : _adapters) { - map<string, Ice::ObjectPrx>::const_iterator q = _proxies.find(p->id); + auto q = _proxies.find(adapter.id); if(q != _proxies.end()) { - Ice::EndpointSeq edpts = q->second->ice_getEndpoints(); + auto edpts = q->second->ice_getEndpoints(); endpoints.insert(endpoints.end(), edpts.begin(), edpts.end()); + } } - Ice::ObjectPrx proxy = _locator->getCommunicator()->stringToProxy("dummy:default"); - _amdCB->ice_response(proxy->ice_endpoints(endpoints)); + auto proxy = _locator->getCommunicator()->stringToProxy("dummy:default"); + _response(proxy->ice_endpoints(endpoints)); } } - const Ice::AMD_Locator_findAdapterByIdPtr _amdCB; - const LocatorIPtr _locator; + const function<void(const shared_ptr<Ice::ObjectPrx>&)> _response; + const function<void(exception_ptr)> _exception; + const shared_ptr<LocatorI> _locator; const std::string _id; const Ice::EncodingVersion _encoding; LocatorAdapterInfoSeq _adapters; - const TraceLevelsPtr _traceLevels; + const shared_ptr<TraceLevels> _traceLevels; unsigned int _count; LocatorAdapterInfoSeq::const_iterator _lastAdapter; - std::map<std::string, Ice::ObjectPrx> _proxies; - IceInternal::UniquePtr<Ice::Exception> _exception; + std::map<std::string, shared_ptr<Ice::ObjectPrx>> _proxies; + exception_ptr _exptr; + std::mutex _mutex; }; -class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, public IceUtil::Mutex +class RoundRobinRequest final : public LocatorI::Request, SynchronizationCallback { public: - RoundRobinRequest(const Ice::AMD_Locator_findAdapterByIdPtr& amdCB, - const LocatorIPtr& locator, - const DatabasePtr database, + RoundRobinRequest(function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)> exception, + const shared_ptr<LocatorI>& locator, + const shared_ptr<Database> database, const string& id, const Ice::Current& current, const LocatorAdapterInfoSeq& adapters, int count) : - _amdCB(amdCB), + _response(move(response)), + _exception(move(exception)), _locator(locator), _database(database), _id(id), @@ -477,8 +359,8 @@ public: assert(_adapters.empty() || _count > 0); } - virtual void - execute() + void + execute() override { if(_adapters.empty()) { @@ -487,26 +369,26 @@ public: Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); out << "couldn't resolve replica group `" << _id << "' endpoints:\nreplica group is empty"; } - _amdCB->ice_response(0); + _response(nullptr); return; } LocatorAdapterInfo adapter = _adapters[0]; assert(adapter.proxy); - if(_locator->getDirectProxy(adapter, this)) + if(_locator->getDirectProxy(adapter, shared_from_this())) { activating(adapter.id); } } - virtual void - activating(const string& id) + void + activating(const string& id) override { LocatorAdapterInfo adapter; adapter.id = id; do { - Lock sync(*this); + lock_guard lock(_mutex); if(_adapters.empty() || _waitForActivation) { return; @@ -514,26 +396,27 @@ public: _activatingOrFailed.insert(adapter.id); adapter = nextAdapter(); } - while(adapter.proxy && _locator->getDirectProxy(adapter, this)); + while(adapter.proxy && _locator->getDirectProxy(adapter, shared_from_this())); } - virtual void - response(const std::string& id, const Ice::ObjectPrx& proxy) + void + response(const std::string& id, const shared_ptr<Ice::ObjectPrx>& proxy) override { // // Ensure the server supports the request encoding. // if(!IceInternal::isSupported(_encoding, proxy->ice_getEncodingVersion())) { - exception(id, Ice::UnsupportedEncodingException(__FILE__, - __LINE__, - "server doesn't support requested encoding", - _encoding, - proxy->ice_getEncodingVersion())); + exception(id, + make_exception_ptr(Ice::UnsupportedEncodingException(__FILE__, + __LINE__, + "server doesn't support requested encoding", + _encoding, + proxy->ice_getEncodingVersion()))); return; } - Lock sync(*this); + lock_guard lock(_mutex); assert(proxy); if(_adapters.empty() || id != _adapters[0].id) { @@ -542,30 +425,30 @@ public: if(_count > 1) { - Ice::ObjectPrx p = proxy->ice_identity(Ice::stringToIdentity("dummy")); - LocatorI::RequestPtr request = - new ReplicaGroupRequest(_amdCB, _locator, _id, _encoding, _adapters, _count, p); + auto p = proxy->ice_identity(Ice::stringToIdentity("dummy")); + shared_ptr<LocatorI::Request> request = + make_shared<ReplicaGroupRequest>(_response, _exception, _locator, _id, _encoding, _adapters, _count, p); request->execute(); } else { - _amdCB->ice_response(proxy->ice_identity(Ice::stringToIdentity("dummy"))); + _response(proxy->ice_identity(Ice::stringToIdentity("dummy"))); } _adapters.clear(); } - virtual void - exception(const std::string& id, const Ice::Exception& ex) + void + exception(const std::string& id, exception_ptr ex) override { LocatorAdapterInfo adapter; { - Lock sync(*this); + lock_guard<std::mutex> lock(_mutex); _failed.insert(id); _activatingOrFailed.insert(id); - if(!_exception.get()) + if(!_exptr) { - _exception.reset(ex.ice_clone()); + _exptr = ex; } if(_adapters.empty() || id != _adapters[0].id) @@ -576,34 +459,34 @@ public: adapter = nextAdapter(); } - if(adapter.proxy && _locator->getDirectProxy(adapter, this)) + if(adapter.proxy && _locator->getDirectProxy(adapter, shared_from_this())) { activating(adapter.id); } } void - synchronized() + synchronized() override { LocatorAdapterInfo adapter; { - Lock sync(*this); + lock_guard lock(_mutex); assert(_adapters.empty()); adapter = nextAdapter(); } - if(adapter.proxy && _locator->getDirectProxy(adapter, this)) + if(adapter.proxy && _locator->getDirectProxy(adapter, shared_from_this())) { activating(adapter.id); } } void - synchronized(const Ice::Exception& ex) + synchronized(exception_ptr ex) override { LocatorAdapterInfo adapter; { - Lock sync(*this); + lock_guard lock(_mutex); assert(_adapters.empty()); if(_activatingOrFailed.size() > _failed.size()) @@ -618,12 +501,12 @@ public: Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); out << "couldn't resolve replica group `" << _id << "' endpoints:\n" << toString(ex); } - _amdCB->ice_response(0); + _response(nullptr); return; } } - if(adapter.proxy && _locator->getDirectProxy(adapter, this)) + if(adapter.proxy && _locator->getDirectProxy(adapter, shared_from_this())) { activating(adapter.id); } @@ -667,13 +550,15 @@ private: { assert(_adapters.empty()); bool callback; + auto self = dynamic_pointer_cast<SynchronizationCallback>(shared_from_this()); + assert(self); if(!_waitForActivation) { - callback = _database->addAdapterSyncCallback(_id, this, _activatingOrFailed); + callback = _database->addAdapterSyncCallback(_id, move(self), _activatingOrFailed); } else { - callback = _database->addAdapterSyncCallback(_id, this, _failed); + callback = _database->addAdapterSyncCallback(_id, move(self), _failed); } if(callback) { @@ -688,11 +573,11 @@ private: { Ice::Current current; current.encoding = _encoding; - _locator->findAdapterById_async(_amdCB, _id, current); + _locator->findAdapterByIdAsync( _id, _response, _exception, current); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - _amdCB->ice_exception(ex); + _exception(current_exception()); } _adapters.clear(); return LocatorAdapterInfo(); @@ -708,108 +593,117 @@ private: { Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); out << "couldn't resolve replica group `" << _id << "' endpoints:\n"; - out << (_exception.get() ? toString(*_exception) : string("replica group is empty")); + out << (_exptr ? toString(_exptr) : string("replica group is empty")); } - _amdCB->ice_response(0); + _response(nullptr); return LocatorAdapterInfo(); } } catch(const AdapterNotExistException&) { assert(_adapters.empty()); - _amdCB->ice_exception(Ice::AdapterNotFoundException()); + _exception(make_exception_ptr(Ice::AdapterNotFoundException())); return LocatorAdapterInfo(); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { assert(_adapters.empty()); if(_traceLevels->locator > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); - out << "couldn't resolve replica group `" << _id << "' endpoints:\n" << toString(ex); + out << "couldn't resolve replica group `" << _id << "' endpoints:\n" << toString(current_exception()); } - _amdCB->ice_response(0); + _response(nullptr); return LocatorAdapterInfo(); } } - const Ice::AMD_Locator_findAdapterByIdPtr _amdCB; - const LocatorIPtr _locator; - const DatabasePtr _database; - const std::string _id; + const function<void(const shared_ptr<Ice::ObjectPrx>&)> _response; + const function<void(exception_ptr)> _exception; + const shared_ptr<LocatorI> _locator; + const shared_ptr<Database> _database; + const string _id; const Ice::EncodingVersion _encoding; - const Ice::ConnectionPtr _connection; + const shared_ptr<Ice::Connection> _connection; const Ice::Context _context; LocatorAdapterInfoSeq _adapters; - const TraceLevelsPtr _traceLevels; + const shared_ptr<TraceLevels> _traceLevels; int _count; bool _waitForActivation; set<string> _failed; set<string> _activatingOrFailed; - IceInternal::UniquePtr<Ice::Exception> _exception; + exception_ptr _exptr; + mutex _mutex; }; -class FindAdapterByIdCallback : public SynchronizationCallback +class FindAdapterByIdCallback final : public SynchronizationCallback { public: - FindAdapterByIdCallback(const LocatorIPtr& locator, - const Ice::AMD_Locator_findAdapterByIdPtr& cb, + FindAdapterByIdCallback(const shared_ptr<LocatorI>& locator, + function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)> exception, const string& id, - const Ice::Current& current) : _locator(locator), _cb(cb), _id(id), _current(current) + const Ice::Current& current) : + _locator(locator), + _response(move(response)), + _exception(move(exception)), + _id(id), + _current(current) { } - virtual void - synchronized() + void + synchronized() override { try { - _locator->findAdapterById_async(_cb, _id, _current); + _locator->findAdapterByIdAsync(_id, _response, _exception, _current); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - _cb->ice_exception(ex); + _exception(current_exception()); } } - virtual void - synchronized(const Ice::Exception& sex) + void + synchronized(exception_ptr exptr) override { try { - sex.ice_throw(); + rethrow_exception(exptr); } catch(const AdapterNotExistException&) { } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - const TraceLevelsPtr traceLevels = _locator->getTraceLevels(); + const shared_ptr<TraceLevels> traceLevels = _locator->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); - out << "couldn't resolve adapter `" << _id << "' endpoints:\n" << toString(ex); + out << "couldn't resolve adapter `" << _id << "' endpoints:\n" << toString(exptr); } } - _cb->ice_response(0); + _response(nullptr); } private: - const LocatorIPtr _locator; - const Ice::AMD_Locator_findAdapterByIdPtr _cb; + const shared_ptr<LocatorI> _locator; + const function<void(const shared_ptr<Ice::ObjectPrx>&)> _response; + const function<void(exception_ptr)> _exception; const string _id; const Ice::Current _current; }; }; -LocatorI::LocatorI(const Ice::CommunicatorPtr& communicator, - const DatabasePtr& database, - const WellKnownObjectsManagerPtr& wellKnownObjects, - const RegistryPrx& registry, - const QueryPrx& query) : +LocatorI::LocatorI(const shared_ptr<Ice::Communicator>& communicator, + const shared_ptr<Database>& database, + const shared_ptr<WellKnownObjectsManager>& wellKnownObjects, + const shared_ptr<RegistryPrx>& registry, + const shared_ptr<QueryPrx>& query) : _communicator(communicator), _database(database), _wellKnownObjects(wellKnownObjects), @@ -823,13 +717,14 @@ LocatorI::LocatorI(const Ice::CommunicatorPtr& communicator, // registry. // void -LocatorI::findObjectById_async(const Ice::AMD_Locator_findObjectByIdPtr& cb, - const Ice::Identity& id, - const Ice::Current&) const +LocatorI::findObjectByIdAsync(Ice::Identity id, + function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)>, + const Ice::Current&) const { try { - cb->ice_response(_database->getObjectProxy(id)); + response(_database->getObjectProxy(id)); } catch(const ObjectNotRegisteredException&) { @@ -842,11 +737,13 @@ LocatorI::findObjectById_async(const Ice::AMD_Locator_findObjectByIdPtr& cb, // registry. If found, we try to get its direct proxy. // void -LocatorI::findAdapterById_async(const Ice::AMD_Locator_findAdapterByIdPtr& cb, - const string& id, - const Ice::Current& current) const +LocatorI::findAdapterByIdAsync(string id, + function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) const { - LocatorIPtr self = const_cast<LocatorI*>(this); + auto self = const_pointer_cast<LocatorI>(shared_from_this()); + bool replicaGroup = false; try { @@ -868,26 +765,28 @@ LocatorI::findAdapterById_async(const Ice::AMD_Locator_findAdapterByIdPtr& cb, } catch(const SynchronizationException&) { - if(_database->addAdapterSyncCallback(id, new FindAdapterByIdCallback(self, cb, id, current))) + if(_database->addAdapterSyncCallback(id, make_shared<FindAdapterByIdCallback>(self, response, exception, id, current))) { return; } } } - RequestPtr request; + shared_ptr<Request> request; if(roundRobin) { - request = new RoundRobinRequest(cb, self, _database, id, current, adapters, count); + request = make_shared<RoundRobinRequest>(response, exception, self, _database, id, current, adapters, + count); } else if(replicaGroup) { - request = new ReplicaGroupRequest(cb, self, id, current.encoding, adapters, count, 0); + request = make_shared<ReplicaGroupRequest>(response, exception, self, id, current.encoding, adapters, count, + nullptr); } else { assert(adapters.size() == 1); - request = new AdapterRequest(cb, self, current.encoding, adapters[0]); + request = make_shared<AdapterRequest>(response, exception, self, current.encoding, adapters[0]); } request->execute(); return; @@ -895,95 +794,100 @@ LocatorI::findAdapterById_async(const Ice::AMD_Locator_findAdapterByIdPtr& cb, catch(const AdapterNotExistException&) { } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); + auto traceLevels = _database->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); if(replicaGroup) { - out << "couldn't resolve replica group `" << id << "' endpoints:\n" << toString(ex); + out << "couldn't resolve replica group `" << id << "' endpoints:\n" << toString(current_exception()); } else { - out << "couldn't resolve adapter `" << id << "' endpoints:\n" << toString(ex); + out << "couldn't resolve adapter `" << id << "' endpoints:\n" << toString(current_exception()); } } - cb->ice_response(0); + response(nullptr); return; } try { - cb->ice_response(_database->getAdapterDirectProxy(id, current.encoding, current.con, current.ctx)); + response(_database->getAdapterDirectProxy(id, current.encoding, current.con, current.ctx)); } catch(const AdapterNotExistException&) { - cb->ice_exception(Ice::AdapterNotFoundException()); + exception(make_exception_ptr(Ice::AdapterNotFoundException())); } } -Ice::LocatorRegistryPrx +shared_ptr<Ice::LocatorRegistryPrx> LocatorI::getRegistry(const Ice::Current&) const { return _wellKnownObjects->getLocatorRegistry(); } -RegistryPrx +shared_ptr<RegistryPrx> LocatorI::getLocalRegistry(const Ice::Current&) const { return _localRegistry; } -QueryPrx +shared_ptr<QueryPrx> LocatorI::getLocalQuery(const Ice::Current&) const { return _localQuery; } -const Ice::CommunicatorPtr& +const shared_ptr<Ice::Communicator>& LocatorI::getCommunicator() const { return _communicator; } -const TraceLevelsPtr& +const shared_ptr<TraceLevels>& LocatorI::getTraceLevels() const { return _database->getTraceLevels(); } bool -LocatorI::getDirectProxy(const LocatorAdapterInfo& adapter, const RequestPtr& request) +LocatorI::getDirectProxy(const LocatorAdapterInfo& adapter, const shared_ptr<Request>& request) { { - Lock sync(*this); - PendingRequestsMap::iterator p = _pendingRequests.find(adapter.id); + lock_guard lock(_mutex); + auto p = _pendingRequests.find(adapter.id); if(p != _pendingRequests.end()) { p->second.push_back(request); return _activating.find(adapter.id) != _activating.end(); } - PendingRequests requests; - requests.push_back(request); - _pendingRequests.insert(make_pair(adapter.id, requests)); + _pendingRequests.insert({ adapter.id, { request } }); } - adapter.proxy->begin_getDirectProxy(newCallback_Adapter_getDirectProxy( - new AdapterGetDirectProxyCallback(this, adapter), - &AdapterGetDirectProxyCallback::response, - &AdapterGetDirectProxyCallback::exception)); + + auto self = shared_from_this(); + adapter.proxy->getDirectProxyAsync([self, adapter] (auto obj) + { + assert(obj); + self->getDirectProxyResponse(adapter, move(obj)); + }, + [self, adapter] (exception_ptr ex) + { + self->getDirectProxyException(adapter, ex); + }); return false; } void -LocatorI::getDirectProxyResponse(const LocatorAdapterInfo& adapter, const Ice::ObjectPrx& proxy) +LocatorI::getDirectProxyResponse(const LocatorAdapterInfo& adapter, const shared_ptr<Ice::ObjectPrx>& proxy) { PendingRequests requests; { - Lock sync(*this); - PendingRequestsMap::iterator p = _pendingRequests.find(adapter.id); + lock_guard lock(_mutex); + auto p = _pendingRequests.find(adapter.id); assert(p != _pendingRequests.end()); requests.swap(p->second); _pendingRequests.erase(p); @@ -992,27 +896,27 @@ LocatorI::getDirectProxyResponse(const LocatorAdapterInfo& adapter, const Ice::O if(proxy) { - for(PendingRequests::iterator q = requests.begin(); q != requests.end(); ++q) + for(const auto& request : requests) { - (*q)->response(adapter.id, proxy); + request->response(adapter.id, proxy); } } else { - for(PendingRequests::iterator q = requests.begin(); q != requests.end(); ++q) + for(const auto& request : requests) { - (*q)->exception(adapter.id, AdapterNotActiveException()); + request->exception(adapter.id, make_exception_ptr(AdapterNotActiveException())); } } } void -LocatorI::getDirectProxyException(const LocatorAdapterInfo& adapter, const Ice::Exception& ex) +LocatorI::getDirectProxyException(const LocatorAdapterInfo& adapter, exception_ptr ex) { bool activate = false; try { - ex.ice_throw(); + rethrow_exception(ex); } catch(const AdapterNotActiveException& e) { @@ -1024,8 +928,8 @@ LocatorI::getDirectProxyException(const LocatorAdapterInfo& adapter, const Ice:: PendingRequests requests; { - Lock sync(*this); - PendingRequestsMap::iterator p = _pendingRequests.find(adapter.id); + lock_guard lock(_mutex); + auto p = _pendingRequests.find(adapter.id); assert(p != _pendingRequests.end()); if(activate) { @@ -1042,22 +946,28 @@ LocatorI::getDirectProxyException(const LocatorAdapterInfo& adapter, const Ice:: if(activate) { - for(PendingRequests::iterator q = requests.begin(); q != requests.end(); ++q) + for(const auto& request : requests) { - (*q)->activating(adapter.id); + request->activating(adapter.id); } - int timeout = adapter.activationTimeout + adapter.deactivationTimeout; - AdapterPrx::uncheckedCast(adapter.proxy->ice_invocationTimeout(timeout * 1000))->begin_activate( - newCallback_Adapter_activate(new AdapterActivateCallback(this, adapter), - &AdapterActivateCallback::response, - &AdapterActivateCallback::exception)); + int timeout = secondsToInt(adapter.activationTimeout + adapter.deactivationTimeout) * 1000; + auto self = shared_from_this(); + Ice::uncheckedCast<AdapterPrx>(adapter.proxy->ice_invocationTimeout(timeout))->activateAsync( + [self, adapter] (auto obj) + { + self->getDirectProxyResponse(adapter, move(obj)); + }, + [self, adapter] (auto e) + { + self->getDirectProxyException(adapter, e); + }); } else { - for(PendingRequests::iterator q = requests.begin(); q != requests.end(); ++q) + for(const auto& request : requests) { - (*q)->exception(adapter.id, ex); + request->exception(adapter.id, ex); } } } diff --git a/cpp/src/IceGrid/LocatorI.h b/cpp/src/IceGrid/LocatorI.h index 8eb5524fc04..6ef0b5f1c58 100644 --- a/cpp/src/IceGrid/LocatorI.h +++ b/cpp/src/IceGrid/LocatorI.h @@ -14,67 +14,65 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle<WellKnownObjectsManager> WellKnownObjectsManagerPtr; - class LocatorI; -typedef IceUtil::Handle<LocatorI> LocatorIPtr; - class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; +class WellKnownObjectsManager; struct LocatorAdapterInfo; typedef std::vector<LocatorAdapterInfo> LocatorAdapterInfoSeq; -class LocatorI : public Locator, public IceUtil::Mutex +class LocatorI : public Locator, public std::enable_shared_from_this<LocatorI> { public: - class Request : public virtual IceUtil::Shared + class Request : public std::enable_shared_from_this<Request> { public: - virtual void execute() = 0; virtual void activating(const std::string&) = 0; - virtual void response(const std::string&, const Ice::ObjectPrx&) = 0; - virtual void exception(const std::string&, const Ice::Exception&) = 0; + virtual void response(const std::string&, const std::shared_ptr<Ice::ObjectPrx>&) = 0; + virtual void exception(const std::string&, std::exception_ptr) = 0; }; - typedef IceUtil::Handle<Request> RequestPtr; - LocatorI(const Ice::CommunicatorPtr&, const DatabasePtr&, const WellKnownObjectsManagerPtr&, const RegistryPrx&, - const QueryPrx&); + LocatorI(const std::shared_ptr<Ice::Communicator>&, const std::shared_ptr<Database>&, + const std::shared_ptr<WellKnownObjectsManager>&, const std::shared_ptr<RegistryPrx>&, + const std::shared_ptr<QueryPrx>&); - virtual void findObjectById_async(const Ice::AMD_Locator_findObjectByIdPtr&, const Ice::Identity&, - const Ice::Current&) const; + void findObjectByIdAsync(Ice::Identity, + std::function<void(const std::shared_ptr<Ice::ObjectPrx>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) const override; - virtual void findAdapterById_async(const Ice::AMD_Locator_findAdapterByIdPtr&, const ::std::string&, - const Ice::Current&) const; + void findAdapterByIdAsync(std::string, + std::function<void(const std::shared_ptr<Ice::ObjectPrx>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) const override; - virtual Ice::LocatorRegistryPrx getRegistry(const Ice::Current&) const; - virtual RegistryPrx getLocalRegistry(const Ice::Current&) const; - virtual QueryPrx getLocalQuery(const Ice::Current&) const; + std::shared_ptr<Ice::LocatorRegistryPrx> getRegistry(const Ice::Current&) const override; + std::shared_ptr<RegistryPrx> getLocalRegistry(const Ice::Current&) const override; + std::shared_ptr<QueryPrx> getLocalQuery(const Ice::Current&) const override; - const Ice::CommunicatorPtr& getCommunicator() const; - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr<Ice::Communicator>& getCommunicator() const; + const std::shared_ptr<TraceLevels>& getTraceLevels() const; - bool getDirectProxy(const LocatorAdapterInfo&, const RequestPtr&); - void getDirectProxyResponse(const LocatorAdapterInfo&, const Ice::ObjectPrx&); - void getDirectProxyException(const LocatorAdapterInfo&, const Ice::Exception&); + bool getDirectProxy(const LocatorAdapterInfo&, const std::shared_ptr<Request>&); + void getDirectProxyResponse(const LocatorAdapterInfo&, const std::shared_ptr<Ice::ObjectPrx>&); + void getDirectProxyException(const LocatorAdapterInfo&, std::exception_ptr); protected: - const Ice::CommunicatorPtr _communicator; - const DatabasePtr _database; - const WellKnownObjectsManagerPtr _wellKnownObjects; - const RegistryPrx _localRegistry; - const QueryPrx _localQuery; + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<Database> _database; + const std::shared_ptr<WellKnownObjectsManager> _wellKnownObjects; + const std::shared_ptr<RegistryPrx> _localRegistry; + const std::shared_ptr<QueryPrx> _localQuery; - typedef std::vector<RequestPtr> PendingRequests; - typedef std::map<std::string, PendingRequests> PendingRequestsMap; + using PendingRequests = std::vector<std::shared_ptr<Request>>; + using PendingRequestsMap = std::map<std::string, PendingRequests>; PendingRequestsMap _pendingRequests; std::set<std::string> _activating; + + std::mutex _mutex; }; } diff --git a/cpp/src/IceGrid/LocatorRegistryI.cpp b/cpp/src/IceGrid/LocatorRegistryI.cpp index 52e254e2ee0..e6a172f3f41 100644 --- a/cpp/src/IceGrid/LocatorRegistryI.cpp +++ b/cpp/src/IceGrid/LocatorRegistryI.cpp @@ -7,6 +7,7 @@ #include <IceGrid/ReplicaSessionManager.h> #include <IceGrid/Database.h> #include <IceGrid/Util.h> +#include <IceGrid/Internal.h> using namespace std; using namespace IceGrid; @@ -14,241 +15,175 @@ using namespace IceGrid; namespace IceGrid { -template<class AmdCB> -class SetDirectProxyCB : public LocatorRegistryI::AdapterSetDirectProxyCB +tuple<function<void()>, function<void(exception_ptr)>> +newSetDirectProxyCB(function<void()> responseCb, + function<void(exception_ptr)> exceptionCb, + const shared_ptr<TraceLevels>& traceLevels, const string& id, + const shared_ptr<Ice::ObjectPrx>& proxy) { -public: - - SetDirectProxyCB(const AmdCB& cb, - const TraceLevelsPtr& traceLevels, - const string& id, - const Ice::ObjectPrx& proxy) : - _cb(cb), _traceLevels(traceLevels), _id(id), _proxy(proxy) - { - } - - virtual void response() + auto response = [traceLevels, id, proxy, responseCb = move(responseCb)] () { - if(_traceLevels->locator > 1) + if(traceLevels->locator > 1) { - Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); - out << "registered adapter `" << _id << "' endpoints: `"; - out << (_proxy ? _proxy->ice_toString() : string("")) << "'"; + Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); + out << "registered adapter `" << id << "' endpoints: `"; + out << (proxy ? proxy->ice_toString() : string("")) << "'"; } - _cb->ice_response(); - } + responseCb(); + }; - virtual void exception(const ::Ice::Exception& ex) + auto exception = [traceLevels, id, exceptionCb = move(exceptionCb)](auto exptr) { - if(_traceLevels->locator > 1) + if(traceLevels->locator > 1) { - Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); - out << "failed to register adapter `" << _id << "' endpoints:\n" << ex; + try + { + rethrow_exception(exptr); + } + catch(const std::exception& ex) + { + Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); + out << "failed to register adapter `" << id << "' endpoints:\n" << ex; + } } try { - ex.ice_throw(); + rethrow_exception(exptr); } catch(const AdapterActiveException&) { - _cb->ice_exception(Ice::AdapterAlreadyActiveException()); + exceptionCb(make_exception_ptr(Ice::AdapterAlreadyActiveException())); return; } catch(const Ice::ObjectNotExistException&) { - _cb->ice_exception(Ice::AdapterNotFoundException()); // Expected if the adapter was destroyed. + exceptionCb(make_exception_ptr(Ice::AdapterNotFoundException())); // Expected if the adapter was destroyed). return; } catch(const Ice::Exception&) { - _cb->ice_exception(Ice::AdapterNotFoundException()); + exceptionCb(make_exception_ptr(Ice::AdapterNotFoundException())); return; } + }; - assert(false); - } - -private: - - const AmdCB _cb; - const TraceLevelsPtr _traceLevels; - const string _id; - const Ice::ObjectPrx _proxy; -}; - -template<class AmdCB> SetDirectProxyCB<AmdCB>* -newSetDirectProxyCB(const AmdCB& cb, const TraceLevelsPtr& traceLevels, const string& id, const Ice::ObjectPrx& p) -{ - return new SetDirectProxyCB<AmdCB>(cb, traceLevels, id, p); + return { move(response), move(exception) }; } -class ServerSetProcessCB : public virtual IceUtil::Shared +class SetAdapterDirectProxyCallback final : public SynchronizationCallback { public: - ServerSetProcessCB(const Ice::AMD_LocatorRegistry_setServerProcessProxyPtr& cb, - const TraceLevelsPtr& traceLevels, - const string& id, - const Ice::ObjectPrx& proxy) : - _cb(cb), _traceLevels(traceLevels), _id(id), _proxy(proxy) - { - } - - virtual void ice_response() - { - if(_traceLevels->locator > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); - out << "registered server `" << _id << "' process proxy: `"; - out << (_proxy ? _proxy->ice_toString() : string("")) << "'"; - } - _cb->ice_response(); - } - - virtual void ice_exception(const ::Ice::Exception& ex) - { - if(_traceLevels->locator > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->locatorCat); - out << "failed to register server process proxy `" << _id << "':\n" << ex; - } - - try - { - ex.ice_throw(); - } - catch(const Ice::ObjectNotExistException&) - { - // Expected if the server was destroyed. - _cb->ice_exception(Ice::ServerNotFoundException()); - return; - } - catch(const Ice::LocalException&) - { - _cb->ice_exception(Ice::ServerNotFoundException()); - return; - } - - assert(false); - } - -private: - - const Ice::AMD_LocatorRegistry_setServerProcessProxyPtr _cb; - const TraceLevelsPtr _traceLevels; - const string _id; - const Ice::ObjectPrx _proxy; -}; -typedef IceUtil::Handle<ServerSetProcessCB> ServerSetProcessCBPtr; - -class SetAdapterDirectProxyCallback : public SynchronizationCallback -{ -public: - - SetAdapterDirectProxyCallback(const LocatorRegistryIPtr& registry, - const LocatorRegistryI::AdapterSetDirectProxyCBPtr& amiCB, + SetAdapterDirectProxyCallback(const shared_ptr<LocatorRegistryI>& registry, + function<void()> response, + function<void(exception_ptr)> exception, const string& adapterId, const string& replicaGroupId, - const Ice::ObjectPrx& proxy) : - _registry(registry), _amiCB(amiCB), _adapterId(adapterId), _replicaGroupId(replicaGroupId), _proxy(proxy) + const shared_ptr<Ice::ObjectPrx>& proxy) : + _registry(registry), + _response(move(response)), + _exception(move(exception)), + _adapterId(adapterId), + _replicaGroupId(replicaGroupId), + _proxy(proxy) { } - virtual void - synchronized() + void + synchronized() override { try { - _registry->setAdapterDirectProxy(_amiCB, _adapterId, _replicaGroupId, _proxy); + _registry->setAdapterDirectProxy(_adapterId, _replicaGroupId, _proxy, _response, _exception); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - _amiCB->exception(ex); + _exception(current_exception()); } } - virtual void - synchronized(const Ice::Exception& ex) + void + synchronized(exception_ptr ex) override { - try - { - ex.ice_throw(); - } - catch(const Ice::Exception& e) - { - _amiCB->exception(e); - } + _exception(ex); } private: - const LocatorRegistryIPtr _registry; - const LocatorRegistryI::AdapterSetDirectProxyCBPtr _amiCB; + const shared_ptr<LocatorRegistryI> _registry; + const function<void()> _response; + const function<void(exception_ptr)> _exception; const string _adapterId; const string _replicaGroupId; - const Ice::ObjectPrx _proxy; + const shared_ptr<Ice::ObjectPrx> _proxy; }; -class SetServerProcessProxyCallback : public SynchronizationCallback +class SetServerProcessProxyCallback final : public SynchronizationCallback { public: - SetServerProcessProxyCallback(const LocatorRegistryIPtr& registry, - const Ice::AMD_LocatorRegistry_setServerProcessProxyPtr& cb, + SetServerProcessProxyCallback(const shared_ptr<LocatorRegistryI>& registry, + const function<void()> response, + const function<void(exception_ptr)> exception, const string& id, - const Ice::ProcessPrx& proxy) : - _registry(registry), _cb(cb), _id(id), _proxy(proxy) + const shared_ptr<Ice::ProcessPrx>& proxy) : + _registry(registry), + _response(move(response)), + _exception(move(exception)), + _id(id), + _proxy(proxy) { } - virtual void - synchronized() + void + synchronized() override { try { - _registry->setServerProcessProxy_async(_cb, _id, _proxy, Ice::Current()); + _registry->setServerProcessProxyAsync(_id, _proxy, _response, _exception, Ice::Current()); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - _cb->ice_exception(ex); + _exception(current_exception()); } } - virtual void - synchronized(const Ice::Exception& sex) + void + synchronized(exception_ptr exptr) override { try { - sex.ice_throw(); + rethrow_exception(exptr); } catch(const ServerNotExistException&) { - _cb->ice_exception(Ice::ServerNotFoundException()); + _exception(make_exception_ptr(Ice::ServerNotFoundException())); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - const TraceLevelsPtr traceLevels = _registry->getTraceLevels(); + auto traceLevels = _registry->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); - out << "couldn't register server `" << _id << "' process proxy:\n" << toString(ex); + out << "couldn't register server `" << _id << "' process proxy:\n" << toString(current_exception()); } - _cb->ice_exception(Ice::ServerNotFoundException()); + _exception(make_exception_ptr(Ice::ServerNotFoundException())); } } private: - const LocatorRegistryIPtr _registry; - const Ice::AMD_LocatorRegistry_setServerProcessProxyPtr _cb; + const shared_ptr<LocatorRegistryI> _registry; + const function<void()> _response; + const function<void(exception_ptr)> _exception; const string _id; - const Ice::ProcessPrx _proxy; + const shared_ptr<Ice::ProcessPrx> _proxy; }; }; -LocatorRegistryI::LocatorRegistryI(const DatabasePtr& database, +LocatorRegistryI::LocatorRegistryI(const shared_ptr<Database>& database, bool dynamicRegistration, bool master, ReplicaSessionManager& session) : @@ -260,36 +195,42 @@ LocatorRegistryI::LocatorRegistryI(const DatabasePtr& database, } void -LocatorRegistryI::setAdapterDirectProxy_async(const Ice::AMD_LocatorRegistry_setAdapterDirectProxyPtr& cb, - const string& adapterId, - const Ice::ObjectPrx& proxy, +LocatorRegistryI::setAdapterDirectProxyAsync(string adapterId, shared_ptr<Ice::ObjectPrx> proxy, + function<void()> response, + function<void(exception_ptr)> exception, const Ice::Current&) { - setAdapterDirectProxy(newSetDirectProxyCB(cb, _database->getTraceLevels(), adapterId, proxy), - adapterId, + auto [responseCb, exceptionCb] = newSetDirectProxyCB(move(response), move(exception), _database->getTraceLevels(), + adapterId, proxy); + + setAdapterDirectProxy(adapterId, "", - proxy); + proxy, + move(responseCb), + move(exceptionCb)); } void -LocatorRegistryI::setReplicatedAdapterDirectProxy_async( - const Ice::AMD_LocatorRegistry_setReplicatedAdapterDirectProxyPtr& cb, - const string& adapterId, - const string& replicaGroupId, - const Ice::ObjectPrx& proxy, - const Ice::Current&) +LocatorRegistryI::setReplicatedAdapterDirectProxyAsync(string adapterId, string replicaGroupId, + shared_ptr<Ice::ObjectPrx> proxy, + function<void()> response, + function<void(exception_ptr)> exception, + const Ice::Current&) { - setAdapterDirectProxy(newSetDirectProxyCB(cb, _database->getTraceLevels(), adapterId, proxy), - adapterId, + auto [responseCb, exceptionCb] = newSetDirectProxyCB(move(response), move(exception), _database->getTraceLevels(), + adapterId, proxy); + setAdapterDirectProxy(adapterId, replicaGroupId, - proxy); + proxy, + move(responseCb), + move(exceptionCb)); } void -LocatorRegistryI::setServerProcessProxy_async(const Ice::AMD_LocatorRegistry_setServerProcessProxyPtr& cb, - const string& id, - const Ice::ProcessPrx& proxy, - const Ice::Current&) +LocatorRegistryI::setServerProcessProxyAsync(string id, shared_ptr<Ice::ProcessPrx> proxy, + function<void()> response, + function<void(exception_ptr)> exception, + const Ice::Current&) { try { @@ -301,7 +242,7 @@ LocatorRegistryI::setServerProcessProxy_async(const Ice::AMD_LocatorRegistry_set // is needed for the session activation mode for cases where // the server is released during the server startup. // - ServerPrx server; + shared_ptr<ServerPrx> server; while(true) { try @@ -311,46 +252,86 @@ LocatorRegistryI::setServerProcessProxy_async(const Ice::AMD_LocatorRegistry_set } catch(const SynchronizationException&) { - if(_database->getServer(id)->addSyncCallback(new SetServerProcessProxyCallback(this, cb, id, proxy))) + auto cb = make_shared<SetServerProcessProxyCallback>(shared_from_this(), response, + exception, id, proxy); + if(_database->getServer(id)->addSyncCallback(move(cb))) { return; } } } - server->begin_setProcess(proxy, IceGrid::newCallback_Server_setProcess( - new ServerSetProcessCB(cb, _database->getTraceLevels(), id, proxy), - &ServerSetProcessCB::ice_response, - &ServerSetProcessCB::ice_exception)); + server->setProcessAsync(proxy, + [id, proxy, response, traceLevels = _database->getTraceLevels()] + { + if(traceLevels->locator > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); + out << "registered server `" << id << "' process proxy: `"; + out << (proxy ? proxy->ice_toString() : string("")) << "'"; + } + response(); + }, + [id, exception, traceLevels = _database->getTraceLevels()] (exception_ptr exptr) + { + if(traceLevels->locator > 1) + { + try + { + rethrow_exception(exptr); + } + catch(const std::exception& ex) + { + Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); + out << "failed to register server process proxy `" << id << "':\n" << ex; + } + } + + try + { + rethrow_exception(exptr); + } + catch(const Ice::ObjectNotExistException&) + { + // Expected if the server was destroyed. + exception(make_exception_ptr(Ice::ServerNotFoundException())); + return; + } + catch(const Ice::LocalException&) + { + exception(make_exception_ptr(Ice::ServerNotFoundException())); + return; + } + }); } catch(const ServerNotExistException&) { - cb->ice_exception(Ice::ServerNotFoundException()); + exception(make_exception_ptr(Ice::ServerNotFoundException())); } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); + auto traceLevels = _database->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); - out << "couldn't register server `" << id << "' process proxy:\n" << toString(ex); + out << "couldn't register server `" << id << "' process proxy:\n" << toString(current_exception()); } - cb->ice_exception(Ice::ServerNotFoundException()); + exception(make_exception_ptr(Ice::ServerNotFoundException())); } } void -LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirectProxyCBPtr& amiCB, - const string& adapterId, - const string& replicaGroupId, - const Ice::ObjectPrx& proxy) +LocatorRegistryI::setAdapterDirectProxy(string adapterId, string replicaGroupId, + shared_ptr<Ice::ObjectPrx> proxy, + function<void()> response, + function<void(exception_ptr)> exception) { // // Ignore request with empty adapter id. // if(adapterId.empty()) { - amiCB->response(); + response(); return; } @@ -362,7 +343,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect // // Get the adapter from the registry and set its direct proxy. // - AdapterPrx adapter; + shared_ptr<AdapterPrx> adapter; while(true) { try @@ -376,17 +357,19 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect } catch(const SynchronizationException&) { - if(_database->addAdapterSyncCallback(adapterId, new SetAdapterDirectProxyCallback( - this, amiCB, adapterId, replicaGroupId, proxy))) + if(_database->addAdapterSyncCallback(adapterId, + make_shared<SetAdapterDirectProxyCallback>(shared_from_this(), + response, exception, + adapterId, + replicaGroupId, + proxy))) { return; } } } - adapter->begin_setDirectProxy(proxy, IceGrid::newCallback_Adapter_setDirectProxy(amiCB, - &LocatorRegistryI::AdapterSetDirectProxyCB::response, - &LocatorRegistryI::AdapterSetDirectProxyCB::exception)); + adapter->setDirectProxyAsync(proxy, response, exception); return; } catch(const AdapterNotExistException&) @@ -396,13 +379,13 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect throw Ice::AdapterNotFoundException(); } } - catch(const Ice::Exception& ex) + catch(const Ice::Exception&) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); + auto traceLevels = _database->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); - out << "couldn't register adapter `" << adapterId << "' endpoints:\n" << toString(ex); + out << "couldn't register adapter `" << adapterId << "' endpoints:\n" << toString(current_exception()); } throw Ice::AdapterNotFoundException(); } @@ -413,7 +396,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect try { _database->setAdapterDirectProxy(adapterId, replicaGroupId, proxy); - amiCB->response(); + response(); return; } catch(const AdapterExistsException&) @@ -422,7 +405,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect } catch(const DeploymentException& ex) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); + auto traceLevels = _database->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); @@ -433,10 +416,10 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect } else { - ReplicaSessionPrx session = _session.getSession(); + auto session = _session.getSession(); if(!session) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); + auto traceLevels = _database->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); @@ -449,7 +432,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect try { session->setAdapterDirectProxy(adapterId, replicaGroupId, proxy); - amiCB->response(); + response(); return; } catch(const AdapterExistsException&) @@ -460,13 +443,14 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect { throw Ice::AdapterNotFoundException(); // Dynamic registration not allowed on the master. } - catch(const Ice::LocalException& ex) + catch(const Ice::LocalException&) { - const TraceLevelsPtr traceLevels = _database->getTraceLevels(); + auto traceLevels = _database->getTraceLevels(); if(traceLevels->locator > 0) { Ice::Trace out(traceLevels->logger, traceLevels->locatorCat); - out << "couldn't register adapter `" << adapterId << "' endpoints with master:\n" << toString(ex); + out << "couldn't register adapter `" << adapterId << "' endpoints with master:\n" + << toString(current_exception()); } throw Ice::AdapterNotFoundException(); } @@ -476,7 +460,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect throw Ice::AdapterNotFoundException(); } -const TraceLevelsPtr& +const shared_ptr<TraceLevels>& LocatorRegistryI::getTraceLevels() const { return _database->getTraceLevels(); diff --git a/cpp/src/IceGrid/LocatorRegistryI.h b/cpp/src/IceGrid/LocatorRegistryI.h index eb7253fe9f9..c9137ccf1e2 100644 --- a/cpp/src/IceGrid/LocatorRegistryI.h +++ b/cpp/src/IceGrid/LocatorRegistryI.h @@ -5,59 +5,50 @@ #ifndef ICE_GRID_LOCATOR_REGISTRY_I_H #define ICE_GRID_LOCATOR_REGISTRY_I_H -#include <IceGrid/Internal.h> #include <Ice/Locator.h> -#include <IceUtil/Shared.h> +#include <IceGrid/Internal.h> namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - class ReplicaSessionManager; +class TraceLevels; -class LocatorRegistryI : public Ice::LocatorRegistry +class LocatorRegistryI final : public Ice::LocatorRegistry, public std::enable_shared_from_this<LocatorRegistryI> { public: - class AdapterSetDirectProxyCB : public virtual IceUtil::Shared - { - public: - - virtual void response() = 0; - virtual void exception(const ::Ice::Exception&) = 0; - }; - typedef IceUtil::Handle<AdapterSetDirectProxyCB> AdapterSetDirectProxyCBPtr; - - LocatorRegistryI(const DatabasePtr&, bool, bool, ReplicaSessionManager&); + LocatorRegistryI(const std::shared_ptr<Database>&, bool, bool, ReplicaSessionManager&); - virtual void setAdapterDirectProxy_async(const Ice::AMD_LocatorRegistry_setAdapterDirectProxyPtr&, - const std::string&, const Ice::ObjectPrx&, const Ice::Current&); + void setAdapterDirectProxyAsync(std::string, std::shared_ptr<Ice::ObjectPrx>, + std::function<void()>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) override; - virtual void setReplicatedAdapterDirectProxy_async( - const Ice::AMD_LocatorRegistry_setReplicatedAdapterDirectProxyPtr&, const std::string&, const std::string&, - const Ice::ObjectPrx&, const Ice::Current&); + void setReplicatedAdapterDirectProxyAsync(std::string, std::string, std::shared_ptr<Ice::ObjectPrx>, + std::function<void()>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) override; - virtual void setServerProcessProxy_async(const Ice::AMD_LocatorRegistry_setServerProcessProxyPtr&, - const ::std::string&, const ::Ice::ProcessPrx&, const ::Ice::Current&); + void setServerProcessProxyAsync(std::string, std::shared_ptr<Ice::ProcessPrx>, + std::function<void()>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) override; - void setAdapterDirectProxy(const AdapterSetDirectProxyCBPtr&, const std::string&, const std::string&, - const Ice::ObjectPrx&); + void setAdapterDirectProxy(std::string, std::string, std::shared_ptr<Ice::ObjectPrx>, + std::function<void()>, + std::function<void(std::exception_ptr)>); - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr<TraceLevels>& getTraceLevels() const; private: - const DatabasePtr _database; + const std::shared_ptr<Database> _database; const bool _dynamicRegistration; const bool _master; ReplicaSessionManager& _session; }; -typedef IceUtil::Handle<LocatorRegistryI> LocatorRegistryIPtr; } diff --git a/cpp/src/IceGrid/NodeAdminRouter.cpp b/cpp/src/IceGrid/NodeAdminRouter.cpp index f739f6e06b2..f6e1f9b5fbc 100644 --- a/cpp/src/IceGrid/NodeAdminRouter.cpp +++ b/cpp/src/IceGrid/NodeAdminRouter.cpp @@ -11,23 +11,24 @@ using namespace IceGrid; using namespace Ice; using namespace std; -IceGrid::NodeServerAdminRouter::NodeServerAdminRouter(const NodeIPtr& node) : +NodeServerAdminRouter::NodeServerAdminRouter(const shared_ptr<NodeI>& node) : AdminRouter(node->getTraceLevels()), _node(node) { } void -IceGrid::NodeServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair<const Ice::Byte*, const Ice::Byte*>& inParams, - const Current& current) +NodeServerAdminRouter::ice_invokeAsync(pair<const Ice::Byte*, const Ice::Byte*> inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) { // // First, get the ServerI servant // Identity serverId = _node->createServerIdentity(current.id.name); - ServerIPtr server = ServerIPtr::dynamicCast(_node->getAdapter()->find(serverId)); - if(server == 0) + auto server = dynamic_pointer_cast<ServerI>(_node->getAdapter()->find(serverId)); + if(server == nullptr) { if(_traceLevels->admin > 0) { @@ -41,9 +42,9 @@ IceGrid::NodeServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& // // Then get a proxy to the Process facet of the real admin object // - ObjectPrx target = server->getProcess(); + auto target = server->getProcess(); - if(target == 0) + if(target == nullptr) { if(_traceLevels->admin > 0) { @@ -65,5 +66,5 @@ IceGrid::NodeServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& target = target->ice_facet(current.facet); } - invokeOnTarget(target, cb, inParams, current); + invokeOnTarget(target, inParams, move(response), move(exception), current); } diff --git a/cpp/src/IceGrid/NodeAdminRouter.h b/cpp/src/IceGrid/NodeAdminRouter.h index 795dfdbe12a..b32f0f6011c 100644 --- a/cpp/src/IceGrid/NodeAdminRouter.h +++ b/cpp/src/IceGrid/NodeAdminRouter.h @@ -14,19 +14,20 @@ namespace IceGrid // // Routes requests to a server's admin object through the Node // -class NodeServerAdminRouter : public AdminRouter +class NodeServerAdminRouter final : public AdminRouter { public: - NodeServerAdminRouter(const NodeIPtr&); + NodeServerAdminRouter(const std::shared_ptr<NodeI>&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair<const Ice::Byte*, const Ice::Byte*>&, - const Ice::Current&); + void ice_invokeAsync(std::pair<const Ice::Byte*, const Ice::Byte*>, + std::function<void(bool, const std::pair<const Ice::Byte*, const Ice::Byte*>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current& current) override; private: - NodeIPtr _node; + std::shared_ptr<NodeI> _node; }; } diff --git a/cpp/src/IceGrid/NodeCache.cpp b/cpp/src/IceGrid/NodeCache.cpp index b727edb4966..8d397255f72 100644 --- a/cpp/src/IceGrid/NodeCache.cpp +++ b/cpp/src/IceGrid/NodeCache.cpp @@ -2,7 +2,6 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include <IceUtil/Functional.h> #include <Ice/Communicator.h> #include <Ice/Properties.h> #include <Ice/LoggerUtil.h> @@ -16,361 +15,122 @@ using namespace std; using namespace IceGrid; -namespace IceGrid +namespace { -struct ToInternalServerDescriptor : std::unary_function<CommunicatorDescriptorPtr&, void> +PropertyDescriptor +removeProperty(PropertyDescriptorSeq& properties, const string& name) { - ToInternalServerDescriptor(const InternalServerDescriptorPtr& descriptor, const InternalNodeInfoPtr& node, - int iceVersion) : - _desc(descriptor), - _node(node), - _iceVersion(iceVersion) + string value; + PropertyDescriptorSeq::iterator p = properties.begin(); + while(p != properties.end()) { - } - - void - operator()(const CommunicatorDescriptorPtr& desc) - { - // - // Figure out the configuration file name for the communicator - // (if it's a service, it's "config_<service name>", if it's - // the server, it's just "config"). - // - string filename = "config"; - ServiceDescriptorPtr svc = ServiceDescriptorPtr::dynamicCast(desc); - if(svc) - { - filename += "_" + svc->name; - _desc->services->push_back(svc->name); - } - - PropertyDescriptorSeq& props = _desc->properties[filename]; - PropertyDescriptorSeq communicatorProps = desc->propertySet.properties; - - // - // If this is a service communicator and the IceBox server has Admin - // enabled or Admin endpoints configured, we ignore the server-lifetime attributes - // of the service object adapters and assume it's set to false. - // - bool ignoreServerLifetime = false; - if(svc) - { - if(_iceVersion == 0 || _iceVersion >= 30300) - { - if(getPropertyAsInt(_desc->properties["config"], "Ice.Admin.Enabled") > 0 || - getProperty(_desc->properties["config"], "Ice.Admin.Endpoints") != "") - { - ignoreServerLifetime = true; - } - } - } - // - // Add the adapters and their configuration. - // - for(AdapterDescriptorSeq::const_iterator q = desc->adapters.begin(); q != desc->adapters.end(); ++q) - { - _desc->adapters.push_back(new InternalAdapterDescriptor(q->id, - ignoreServerLifetime ? false : q->serverLifetime)); - - props.push_back(createProperty("# Object adapter " + q->name)); - PropertyDescriptor prop = removeProperty(communicatorProps, q->name + ".Endpoints"); - prop.name = q->name + ".Endpoints"; - props.push_back(prop); - props.push_back(createProperty(q->name + ".AdapterId", q->id)); - if(!q->replicaGroupId.empty()) - { - props.push_back(createProperty(q->name + ".ReplicaGroupId", q->replicaGroupId)); - } - - // - // Ignore the register process attribute if the server is using Ice >= 3.3.0 - // - if(_iceVersion != 0 && _iceVersion < 30300) - { - if(q->registerProcess) - { - props.push_back(createProperty(q->name + ".RegisterProcess", "1")); - _desc->processRegistered = true; - } - } - } - - _desc->logs.insert(_desc->logs.end(), desc->logs.begin(), desc->logs.end()); - - const string dbsPath = _node->dataDir + "/servers/" + _desc->id + "/dbs/"; - for(DbEnvDescriptorSeq::const_iterator p = desc->dbEnvs.begin(); p != desc->dbEnvs.end(); ++p) - { - props.push_back(createProperty("# Database environment " + p->name)); - if(p->dbHome.empty()) - { - _desc->dbEnvs.push_back(new InternalDbEnvDescriptor(p->name, p->properties)); - props.push_back(createProperty("Freeze.DbEnv." + p->name + ".DbHome", dbsPath + p->name)); - } - else - { - props.push_back(createProperty("Freeze.DbEnv." + p->name + ".DbHome", p->dbHome)); - } - } - - // - // Copy the communicator descriptor properties. - // - if(!communicatorProps.empty()) - { - if(svc) - { - props.push_back(createProperty("# Service descriptor properties")); - } - else - { - props.push_back(createProperty("# Server descriptor properties")); - } - copy(communicatorProps.begin(), communicatorProps.end(), back_inserter(props)); - } - - // - // For Ice servers > 3.3.0 escape the properties. - // - if(_iceVersion == 0 || _iceVersion >= 30300) - { - for(PropertyDescriptorSeq::iterator p = props.begin(); p != props.end(); ++p) - { - if(p->name.find('#') != 0 || !p->value.empty()) - { - p->name = escapeProperty(p->name, true); - p->value = escapeProperty(p->value); - } - } - } - } - - PropertyDescriptor - removeProperty(PropertyDescriptorSeq& properties, const string& name) - { - string value; - PropertyDescriptorSeq::iterator p = properties.begin(); - while(p != properties.end()) - { - if(p->name == name) - { - value = p->value; - p = properties.erase(p); - } - else - { - ++p; - } - } - PropertyDescriptor desc; - desc.name = name; - desc.value = value; - return desc; - } - - InternalServerDescriptorPtr _desc; - InternalNodeInfoPtr _node; - int _iceVersion; -}; - -class LoadCB : public virtual IceUtil::Shared -{ -public: - - LoadCB(const TraceLevelsPtr& traceLevels, const ServerEntryPtr& server, const string& node, int timeout) : - _traceLevels(traceLevels), _server(server), _id(server->getId()), _node(node), _timeout(timeout) - { - } - - void - response(const ServerPrx& server, const AdapterPrxDict& adapters, int at, int dt) - { - if(_traceLevels && _traceLevels->server > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat); - out << "loaded `" << _id << "' on node `" << _node << "'"; - } - - // - // Add the node session timeout on the proxies to ensure the - // timeout is large enough. - // - _server->loadCallback(server, adapters, at + _timeout, dt + _timeout); - } - - void - exception(const Ice::Exception& lex) - { - try - { - lex.ice_throw(); - } - catch(const DeploymentException& ex) - { - if(_traceLevels && _traceLevels->server > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat); - out << "couldn't load `" << _id << "' on node `" << _node << "':\n" << ex.reason; - } - - ostringstream os; - os << "couldn't load `" << _id << "' on node `" << _node << "':\n" << ex.reason; - _server->exception(DeploymentException(os.str())); - } - catch(const Ice::Exception& ex) - { - if(_traceLevels && _traceLevels->server > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat); - out << "couldn't load `" << _id << "' on node `" << _node << "':\n" << ex; - } - - ostringstream os; - os << ex; - _server->exception(NodeUnreachableException(_node, os.str())); - } - } - -private: - - const TraceLevelsPtr _traceLevels; - const ServerEntryPtr _server; - const string _id; - const string _node; - const int _timeout; -}; - -class DestroyCB : public virtual IceUtil::Shared -{ -public: - - DestroyCB(const TraceLevelsPtr& traceLevels, const ServerEntryPtr& server, const string& node) : - _traceLevels(traceLevels), _server(server), _id(server->getId()), _node(node) - { - } - - void - response() - { - if(_traceLevels && _traceLevels->server > 1) + if(p->name == name) { - Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat); - out << "unloaded `" << _id << "' on node `" << _node << "'"; - } - _server->destroyCallback(); - } - - void - exception(const Ice::Exception& dex) - { - try - { - dex.ice_throw(); - } - catch(const DeploymentException& ex) - { - if(_traceLevels && _traceLevels->server > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat); - out << "couldn't unload `" << _id << "' on node `" << _node << "':\n" << ex.reason; - } - - ostringstream os; - os << "couldn't unload `" << _id << "' on node `" << _node << "':\n" << ex.reason; - _server->exception(DeploymentException(os.str())); + value = p->value; + p = properties.erase(p); } - catch(const Ice::Exception& ex) + else { - if(_traceLevels && _traceLevels->server > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->serverCat); - out << "couldn't unload `" << _id << "' on node `" << _node << "':\n" << ex; - } - ostringstream os; - os << ex; - _server->exception(NodeUnreachableException(_node, os.str())); + ++p; } } - -private: - - const TraceLevelsPtr _traceLevels; - const ServerEntryPtr _server; - const string _id; - const string _node; -}; + return { name, value }; +} } -NodeCache::NodeCache(const Ice::CommunicatorPtr& communicator, ReplicaCache& replicaCache, const string& replicaName) : +NodeCache::NodeCache(const shared_ptr<Ice::Communicator>& communicator, + ReplicaCache& replicaCache, const string& replicaName) : _communicator(communicator), _replicaName(replicaName), _replicaCache(replicaCache) { } -NodeEntryPtr +shared_ptr<NodeEntry> NodeCache::get(const string& name, bool create) const { - Lock sync(*this); - NodeEntryPtr entry = getImpl(name); - if(!entry && create) + lock_guard lock(_mutex); + + auto cacheEntry = getImpl(name); + if(!cacheEntry && create) { NodeCache& self = const_cast<NodeCache&>(*this); - entry = new NodeEntry(self, name); - self.addImpl(name, entry); + cacheEntry = make_shared<NodeEntry>(self, name); + self.addImpl(name, cacheEntry); } - if(!entry) + if(!cacheEntry) { throw NodeNotExistException(name); } + + // Get a self removing shared_ptr to the cached NodeEntry which will remove + // itself from the this cache upon destruction + auto entry = cacheEntry->_selfRemovingPtr.lock(); + + if (!entry) + { + // Create self removing shared_ptr of cacheEntry. The cacheEntry maintains a ref count for the case where + // the self removing shared_ptr has no more references but its deleter has yet to run (weak_ptr has expired) + // and at the same time another thread calls NodeCache::get which refreshes the self removing ptr before + // the cached entry can be removed. + entry = shared_ptr<NodeEntry>(const_cast<NodeEntry*>(cacheEntry.get()), + [cache = const_cast<NodeCache*>(this), name](NodeEntry* e) + { + lock_guard cacheLock(cache->_mutex); + if(--e->_selfRemovingRefCount == 0) + { + cache->removeImpl(name); + } + }); + cacheEntry->_selfRemovingRefCount++; + cacheEntry->_selfRemovingPtr = entry; + } + return entry; } NodeEntry::NodeEntry(NodeCache& cache, const std::string& name) : _cache(cache), - _ref(0), _name(name), - _registering(false) -{ -} - -NodeEntry::~NodeEntry() + _registering(false), + _selfRemovingRefCount(0) { } void NodeEntry::addDescriptor(const string& application, const NodeDescriptor& descriptor) { - Lock sync(*this); + lock_guard lock(_mutex); _descriptors.insert(make_pair(application, descriptor)); } void NodeEntry::removeDescriptor(const string& application) { - Lock sync(*this); + lock_guard lock(_mutex); _descriptors.erase(application); } void -NodeEntry::addServer(const ServerEntryPtr& entry) +NodeEntry::addServer(const shared_ptr<ServerEntry>& entry) { - Lock sync(*this); + lock_guard lock(_mutex); _servers.insert(make_pair(entry->getId(), entry)); } void -NodeEntry::removeServer(const ServerEntryPtr& entry) +NodeEntry::removeServer(const shared_ptr<ServerEntry>& entry) { - Lock sync(*this); + lock_guard lock(_mutex); _servers.erase(entry->getId()); } void -NodeEntry::setSession(const NodeSessionIPtr& session) +NodeEntry::setSession(const shared_ptr<NodeSessionI>& session) { - Lock sync(*this); + unique_lock lock(_mutex); if(session) { @@ -380,12 +140,12 @@ NodeEntry::setSession(const NodeSessionIPtr& session) { // If the current session has just been destroyed, wait for the setSession(0) call. assert(session != _session); - wait(); + _condVar.wait(lock); } else { - NodeSessionIPtr s = _session; - sync.release(); + auto s = _session; + lock.unlock(); try { s->getNode()->ice_ping(); @@ -401,7 +161,7 @@ NodeEntry::setSession(const NodeSessionIPtr& session) { } } - sync.acquire(); + lock.lock(); } } @@ -410,7 +170,7 @@ NodeEntry::setSession(const NodeSessionIPtr& session) // so we won't need anymore to try to register it with this // registry. // - _proxy = 0; + _proxy = nullptr; } else { @@ -421,12 +181,12 @@ NodeEntry::setSession(const NodeSessionIPtr& session) } _session = session; - notifyAll(); + _condVar.notify_all(); if(_registering) { _registering = false; - notifyAll(); + _condVar.notify_all(); } if(session) @@ -447,28 +207,28 @@ NodeEntry::setSession(const NodeSessionIPtr& session) } } -NodePrx +shared_ptr<NodePrx> NodeEntry::getProxy() const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); return _session->getNode(); } -InternalNodeInfoPtr +shared_ptr<InternalNodeInfo> NodeEntry::getInfo() const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); return _session->getInfo(); } ServerEntrySeq NodeEntry::getServers() const { - Lock sync(*this); + lock_guard lock(_mutex); ServerEntrySeq entries; - for(map<string, ServerEntryPtr>::const_iterator p = _servers.begin(); p != _servers.end(); ++p) + for(map<string, shared_ptr<ServerEntry>>::const_iterator p = _servers.begin(); p != _servers.end(); ++p) { entries.push_back(p->second); } @@ -478,8 +238,8 @@ NodeEntry::getServers() const LoadInfo NodeEntry::getLoadInfoAndLoadFactor(const string& application, float& loadFactor) const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); map<string, NodeDescriptor>::const_iterator p = _descriptors.find(application); if(p == _descriptors.end()) @@ -523,46 +283,45 @@ NodeEntry::getLoadInfoAndLoadFactor(const string& application, float& loadFactor return _session->getLoadInfo(); } -NodeSessionIPtr +shared_ptr<NodeSessionI> NodeEntry::getSession() const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); return _session; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> NodeEntry::getAdminProxy() const { - Ice::ObjectPrx prx = getProxy(); + auto prx = getProxy(); assert(prx); - Ice::Identity adminId; - adminId.name = "NodeAdmin-" + _name ; - adminId.category = prx->ice_getIdentity().category; - return prx->ice_identity(adminId); + return prx->ice_identity({ "NodeAdmin-" + _name, prx->ice_getIdentity().category }); } bool NodeEntry::canRemove() { - Lock sync(*this); - return _servers.empty() && !_session && _descriptors.empty(); + lock_guard lock(_mutex); + + // The cache mutex must be locked to acesss _selfRemovingRefCount + return _servers.empty() && !_session && _descriptors.empty() && _selfRemovingRefCount == 0; } void -NodeEntry::loadServer(const ServerEntryPtr& entry, const ServerInfo& server, const SessionIPtr& session, int timeout, - bool noRestart) +NodeEntry::loadServer(const shared_ptr<ServerEntry>& entry, const ServerInfo& server, + const shared_ptr<SessionI>& session, chrono::seconds timeout, bool noRestart) { try { - NodePrx node; - int sessionTimeout; - InternalServerDescriptorPtr desc; + shared_ptr<NodePrx> node; + chrono::seconds sessionTimeout; + shared_ptr<InternalServerDescriptor> desc; { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); node = _session->getNode(); - sessionTimeout = _session->getTimeout(Ice::emptyCurrent); + sessionTimeout = chrono::seconds(_session->getTimeout(Ice::emptyCurrent)); // // Check if we should use a specific timeout (the load @@ -570,9 +329,10 @@ NodeEntry::loadServer(const ServerEntryPtr& entry, const ServerInfo& server, con // time to deactivate, up to "deactivation-timeout" // seconds). // - if(timeout > 0) + if(timeout > 0s) { - node = NodePrx::uncheckedCast(node->ice_invocationTimeout(timeout * 1000)); + auto timeoutInMilliseconds = secondsToInt(timeout) * 1000; + node = Ice::uncheckedCast<NodePrx>(node->ice_invocationTimeout(move(timeoutInMilliseconds))); } ServerInfo info = server; @@ -603,38 +363,79 @@ NodeEntry::loadServer(const ServerEntryPtr& entry, const ServerInfo& server, con } } + auto response = [traceLevels = _cache.getTraceLevels(), entry, name = _name, sessionTimeout] + (shared_ptr<ServerPrx> serverPrx, AdapterPrxDict adapters, int at, int dt) + { + if(traceLevels && traceLevels->server > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->serverCat); + out << "loaded `" << entry->getId() << "' on node `" << name << "'"; + } + + // + // Add the node session timeout on the proxies to ensure the + // timeout is large enough. + // + entry->loadCallback(move(serverPrx), move(adapters), + chrono::seconds(at) + sessionTimeout, + chrono::seconds(dt) + sessionTimeout); + + }; + + auto exception = [traceLevels = _cache.getTraceLevels(), entry, name = _name](auto exptr) + { + try + { + rethrow_exception(exptr); + } + catch(const DeploymentException& ex) + { + if(traceLevels && traceLevels->server > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->serverCat); + out << "couldn't load `" << entry->getId() << "' on node `" << name << "':\n" << ex.reason; + } + + ostringstream os; + os << "couldn't load `" << entry->getId() << "' on node `" << name << "':\n" << ex.reason; + entry->exception(make_exception_ptr(DeploymentException(os.str()))); + } + catch(const Ice::Exception& ex) + { + if(traceLevels && traceLevels->server > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->serverCat); + out << "couldn't load `" << entry->getId() << "' on node `" << name << "':\n" << ex; + } + + entry->exception(make_exception_ptr(NodeUnreachableException(name, ex.what()))); + } + }; + if(noRestart) { - node->begin_loadServerWithoutRestart(desc, _cache.getReplicaName(), - newCallback_Node_loadServerWithoutRestart( - new LoadCB(_cache.getTraceLevels(), entry, _name, sessionTimeout), - &LoadCB::response, - &LoadCB::exception)); + node->loadServerWithoutRestartAsync(desc, _cache.getReplicaName(), move(response), move(exception)); } else { - node->begin_loadServer(desc, _cache.getReplicaName(), - newCallback_Node_loadServer( - new LoadCB(_cache.getTraceLevels(), entry, _name, sessionTimeout), - &LoadCB::response, - &LoadCB::exception)); + node->loadServerAsync(desc, _cache.getReplicaName(), move(response), move(exception)); } } - catch(const NodeUnreachableException& ex) + catch(const NodeUnreachableException&) { - entry->exception(ex); + entry->exception(current_exception()); } } void -NodeEntry::destroyServer(const ServerEntryPtr& entry, const ServerInfo& info, int timeout, bool noRestart) +NodeEntry::destroyServer(const shared_ptr<ServerEntry>& entry, const ServerInfo& info, chrono::seconds timeout, bool noRestart) { try { - NodePrx node; + shared_ptr<NodePrx> node; { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); node = _session->getNode(); // @@ -643,9 +444,10 @@ NodeEntry::destroyServer(const ServerEntryPtr& entry, const ServerInfo& info, in // time to deactivate, up to "deactivation-timeout" // seconds). // - if(timeout > 0) + if(timeout > 0s) { - node = NodePrx::uncheckedCast(node->ice_invocationTimeout(timeout * 1000)); + int timeoutInMilliseconds = secondsToInt(timeout) * 1000; + node = Ice::uncheckedCast<NodePrx>(node->ice_invocationTimeout(move(timeoutInMilliseconds))); } } @@ -655,35 +457,67 @@ NodeEntry::destroyServer(const ServerEntryPtr& entry, const ServerInfo& info, in out << "unloading `" << info.descriptor->id << "' on node `" << _name << "'"; } + auto response = [traceLevels = _cache.getTraceLevels(), entry, name = _name] + { + if(traceLevels && traceLevels->server > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->serverCat); + out << "unloaded `" << entry->getId() << "' on node `" << name << "'"; + } + entry->destroyCallback(); + }; + + auto exception = [traceLevels = _cache.getTraceLevels(), entry, name = _name](auto exptr) + { + try + { + rethrow_exception(exptr); + } + catch(const DeploymentException& ex) + { + if(traceLevels && traceLevels->server > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->serverCat); + out << "couldn't unload `" << entry->getId() << "' on node `" << name << "':\n" << ex.reason; + } + + ostringstream os; + os << "couldn't unload `" << entry->getId() << "' on node `" << name << "':\n" << ex.reason; + entry->exception(make_exception_ptr(DeploymentException(os.str()))); + } + catch(const Ice::Exception& ex) + { + if(traceLevels && traceLevels->server > 1) + { + Ice::Trace out(traceLevels->logger, traceLevels->serverCat); + out << "couldn't unload `" << entry->getId() << "' on node `" << name << "':\n" << ex; + } + entry->exception(make_exception_ptr(NodeUnreachableException(name, ex.what()))); + } + }; + if(noRestart) { - node->begin_destroyServerWithoutRestart(info.descriptor->id, info.uuid, info.revision, - _cache.getReplicaName(), - newCallback_Node_destroyServerWithoutRestart( - new DestroyCB(_cache.getTraceLevels(), entry, _name), - &DestroyCB::response, - &DestroyCB::exception)); + node->destroyServerWithoutRestartAsync(info.descriptor->id, info.uuid, info.revision, + _cache.getReplicaName(), move(response), move(exception)); } else { - node->begin_destroyServer(info.descriptor->id, info.uuid, info.revision, _cache.getReplicaName(), - newCallback_Node_destroyServer( - new DestroyCB(_cache.getTraceLevels(), entry, _name), - &DestroyCB::response, - &DestroyCB::exception)); + node->destroyServerAsync(info.descriptor->id, info.uuid, info.revision, _cache.getReplicaName(), + move(response), move(exception)); } } - catch(const NodeUnreachableException& ex) + catch(const NodeUnreachableException&) { - entry->exception(ex); + entry->exception(current_exception()); } } ServerInfo -NodeEntry::getServerInfo(const ServerInfo& server, const SessionIPtr& session) +NodeEntry::getServerInfo(const ServerInfo& server, const shared_ptr<SessionI>& session) { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); ServerInfo info = server; info.descriptor = getServerDescriptor(server, session); @@ -691,11 +525,11 @@ NodeEntry::getServerInfo(const ServerInfo& server, const SessionIPtr& session) return info; } -InternalServerDescriptorPtr -NodeEntry::getInternalServerDescriptor(const ServerInfo& server, const SessionIPtr& session) +shared_ptr<InternalServerDescriptor> +NodeEntry::getInternalServerDescriptor(const ServerInfo& server, const shared_ptr<SessionI>& session) { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); ServerInfo info = server; try @@ -715,54 +549,7 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& server, const SessionIP } void -NodeEntry::__incRef() -{ - Lock sync(*this); - assert(_ref >= 0); - ++_ref; -} - -void -NodeEntry::__decRef() -{ - // - // The node entry implements its own reference counting. If the - // reference count drops to 1, this means that only the cache - // holds a reference on the node entry. If that's the case, we - // check if the node entry can be removed or not and if it can be - // removed we remove it from the cache map. - // - - bool doRemove = false; - bool doDelete = false; - { - Lock sync(*this); // We use a recursive mutex so it's fine to - // create Ptr with the mutex locked. - assert(_ref > 0); - --_ref; - - if(_ref == 1) - { - doRemove = canRemove(); - } - else if(_ref == 0) - { - doDelete = true; - } - } - - if(doRemove) - { - _cache.remove(_name); - } - else if(doDelete) - { - delete this; - } -} - -void -NodeEntry::checkSession() const +NodeEntry::checkSession(unique_lock<mutex>& lock) const { if(_session) { @@ -796,22 +583,27 @@ NodeEntry::checkSession() const // hang in the while loop. // _registering = true; - NodeEntry* self = const_cast<NodeEntry*>(this); - _proxy->begin_registerWithReplica(_cache.getReplicaCache().getInternalRegistry(), - newCallback_Node_registerWithReplica(self, - &NodeEntry::finishedRegistration, - &NodeEntry::finishedRegistration)); - _proxy = 0; // Registration with the proxy is only attempted once. - } - while(_registering) - { - if(!timedWait(IceUtil::Time::seconds(10))) - { - break; // Consider the node down if it doesn't respond promptly. - } + // 'this' is only ever accessed though the self removing pointer, ensuring _selfRemovingPtr is always + // valid and its access is thread safe + auto self = _selfRemovingPtr.lock(); + assert(self); + _proxy->registerWithReplicaAsync(_cache.getReplicaCache().getInternalRegistry(), + [self] + { + self->finishedRegistration(); + }, + [self] (exception_ptr ex) + { + self->finishedRegistration(ex); + }); + _proxy = nullptr; // Registration with the proxy is only attempted once. + } + // Consider the node down if it doesn't respond promptly. + _condVar.wait_for(lock, 10s, [this] { return !_registering; }); + if(!_session || _session->isDestroyed()) { throw NodeUnreachableException(_name, "the node is not active"); @@ -819,9 +611,9 @@ NodeEntry::checkSession() const } void -NodeEntry::setProxy(const NodePrx& node) +NodeEntry::setProxy(const shared_ptr<NodePrx>& node) { - Lock sync(*this); + lock_guard lock(_mutex); // // If the node has already established a session with the @@ -838,7 +630,7 @@ NodeEntry::setProxy(const NodePrx& node) void NodeEntry::finishedRegistration() { - Lock sync(*this); + lock_guard lock(_mutex); if(_cache.getTraceLevels() && _cache.getTraceLevels()->node > 0) { Ice::Trace out(_cache.getTraceLevels()->logger, _cache.getTraceLevels()->nodeCat); @@ -855,29 +647,36 @@ NodeEntry::finishedRegistration() if(_registering) { _registering = false; - notifyAll(); + _condVar.notify_all(); } } void -NodeEntry::finishedRegistration(const Ice::Exception& ex) +NodeEntry::finishedRegistration(exception_ptr exptr) { - Lock sync(*this); + lock_guard lock(_mutex); if(_cache.getTraceLevels() && _cache.getTraceLevels()->node > 0) { - Ice::Trace out(_cache.getTraceLevels()->logger, _cache.getTraceLevels()->nodeCat); - out << "node `" << _name << "' session creation failed:\n" << ex; + try + { + rethrow_exception(exptr); + } + catch(const std::exception& ex) + { + Ice::Trace out(_cache.getTraceLevels()->logger, _cache.getTraceLevels()->nodeCat); + out << "node `" << _name << "' session creation failed:\n" << ex.what(); + } } if(_registering) { _registering = false; - notifyAll(); + _condVar.notify_all(); } } -ServerDescriptorPtr -NodeEntry::getServerDescriptor(const ServerInfo& server, const SessionIPtr& session) +shared_ptr<ServerDescriptor> +NodeEntry::getServerDescriptor(const ServerInfo& server, const shared_ptr<SessionI>& session) { assert(_session); @@ -891,7 +690,7 @@ NodeEntry::getServerDescriptor(const ServerInfo& server, const SessionIPtr& sess resolve.setReserved("session.id", session->getId()); } - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(server.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(server.descriptor); if(iceBox) { return IceBoxHelper(iceBox).instantiate(resolve, PropertyDescriptorSeq(), PropertySetDescriptorDict()); @@ -903,7 +702,7 @@ NodeEntry::getServerDescriptor(const ServerInfo& server, const SessionIPtr& sess } } -InternalServerDescriptorPtr +shared_ptr<InternalServerDescriptor> NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const { // @@ -911,7 +710,7 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const // assert(_session); - InternalServerDescriptorPtr server = new InternalServerDescriptor(); + shared_ptr<InternalServerDescriptor> server = make_shared<InternalServerDescriptor>(); server->id = info.descriptor->id; server->application = info.application; server->uuid = info.uuid; @@ -929,7 +728,6 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const // server->logs: assigned for each communicator (see below) // server->adapters: assigned for each communicator (see below) - // server->dbEnvs: assigned for each communicator (see below) // server->properties: assigned for each communicator (see below) // @@ -966,7 +764,8 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const } else { - props.push_back(createProperty("Ice.Admin.Endpoints", "tcp -h localhost")); + props.push_back(createProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1")); + props.push_back(createProperty("Ice.Admin.ServerName", "127.0.0.1")); server->processRegistered = true; } } @@ -985,12 +784,12 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const // Add IceBox properties. // string servicesStr; - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(info.descriptor); if(iceBox) { - for(ServiceInstanceDescriptorSeq::const_iterator p = iceBox->services.begin(); p != iceBox->services.end();++p) + for(const auto& serviceInstance : iceBox->services) { - ServiceDescriptorPtr s = p->descriptor; + const auto& s = serviceInstance.descriptor; const string path = _session->getInfo()->dataDir + "/servers/" + server->id + "/config/config_" + s->name; // @@ -1012,38 +811,115 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const } props.push_back(createProperty("IceBox.LoadOrder", servicesStr)); + } - if(iceVersion != 0 && iceVersion < 30300) + // + // Now, for each communicator of the descriptor, add the necessary + // logs, adapters and properties to the internal server + // descriptor. + // + forEachCommunicator(info.descriptor, + [server, node = _session->getInfo(), iceVersion](const auto& desc) { - if(hasProperty(iceBox->propertySet.properties, "IceBox.ServiceManager.RegisterProcess")) + // + // Figure out the configuration file name for the communicator + // (if it's a service, it's "config_<service name>", if it's + // the server, it's just "config"). + // + string filename = "config"; + auto svc = dynamic_pointer_cast<ServiceDescriptor>(desc); + if(svc) { - if(getProperty(iceBox->propertySet.properties, "IceBox.ServiceManager.RegisterProcess") != "0") + filename += "_" + svc->name; + server->services->push_back(svc->name); + } + + PropertyDescriptorSeq& serverProps = server->properties[filename]; + PropertyDescriptorSeq communicatorProps = desc->propertySet.properties; + + // + // If this is a service communicator and the IceBox server has Admin + // enabled or Admin endpoints configured, we ignore the server-lifetime attributes + // of the service object adapters and assume it's set to false. + // + bool ignoreServerLifetime = false; + if(svc) + { + if(iceVersion == 0 || iceVersion >= 30300) { - server->processRegistered = true; + if(getPropertyAsInt(server->properties["config"], "Ice.Admin.Enabled") > 0 || + getProperty(server->properties["config"], "Ice.Admin.Endpoints") != "") + { + ignoreServerLifetime = true; + } } } - else + // + // Add the adapters and their configuration. + // + for(const auto& adapter : desc->adapters) { - props.push_back(createProperty("IceBox.ServiceManager.RegisterProcess", "1")); - server->processRegistered = true; + server->adapters.push_back(make_shared<InternalAdapterDescriptor>(adapter.id, + ignoreServerLifetime ? false : + adapter.serverLifetime)); + + serverProps.push_back(createProperty("# Object adapter " + adapter.name)); + + PropertyDescriptor prop = removeProperty(communicatorProps, adapter.name + ".Endpoints"); + prop.name = adapter.name + ".Endpoints"; + serverProps.push_back(prop); + serverProps.push_back(createProperty(adapter.name + ".AdapterId", adapter.id)); + + if(!adapter.replicaGroupId.empty()) + { + serverProps.push_back(createProperty(adapter.name + ".ReplicaGroupId", adapter.replicaGroupId)); + } + + // + // Ignore the register process attribute if the server is using Ice >= 3.3.0 + // + if(iceVersion != 0 && iceVersion < 30300) + { + if(adapter.registerProcess) + { + serverProps.push_back(createProperty(adapter.name + ".RegisterProcess", "1")); + server->processRegistered = true; + } + } } - if(!hasProperty(iceBox->propertySet.properties, "IceBox.ServiceManager.Endpoints")) + + server->logs.insert(server->logs.end(), desc->logs.begin(), desc->logs.end()); + + // + // Copy the communicator descriptor properties. + // + if(!communicatorProps.empty()) { - props.push_back(createProperty("IceBox.ServiceManager.Endpoints", "tcp -h 127.0.0.1")); + if(svc) + { + serverProps.push_back(createProperty("# Service descriptor properties")); + } + else + { + serverProps.push_back(createProperty("# Server descriptor properties")); + } + copy(communicatorProps.begin(), communicatorProps.end(), back_inserter(serverProps)); } - } - if(!hasProperty(info.descriptor->propertySet.properties, "IceBox.InstanceName") && - hasProperty(iceBox->propertySet.properties, "IceBox.ServiceManager.Endpoints")) - { - props.push_back(createProperty("IceBox.InstanceName", server->id)); - } - } - // - // Now, for each communicator of the descriptor, add the necessary - // logs, adapters, db envs and properties to the internal server - // descriptor. - // - forEachCommunicator(ToInternalServerDescriptor(server, _session->getInfo(), iceVersion))(info.descriptor); + // + // For Ice servers > 3.3.0 escape the properties. + // + if(iceVersion == 0 || iceVersion >= 30300) + { + for(PropertyDescriptorSeq::iterator p = serverProps.begin(); p != serverProps.end(); ++p) + { + if(p->name.find('#') != 0 || !p->value.empty()) + { + p->name = escapeProperty(p->name, true); + p->value = escapeProperty(p->value); + } + } + } + }); return server; } diff --git a/cpp/src/IceGrid/NodeCache.h b/cpp/src/IceGrid/NodeCache.h index 0230b7d05b2..639ff988ce1 100644 --- a/cpp/src/IceGrid/NodeCache.h +++ b/cpp/src/IceGrid/NodeCache.h @@ -5,8 +5,6 @@ #ifndef ICE_GRID_NODECACHE_H #define ICE_GRID_NODECACHE_H -#include <IceUtil/RecMutex.h> -#include <IceUtil/Shared.h> #include <IceGrid/Cache.h> #include <IceGrid/Internal.h> @@ -14,90 +12,94 @@ namespace IceGrid { class NodeCache; - -class SessionI; -typedef IceUtil::Handle<SessionI> SessionIPtr; - class NodeSessionI; -typedef IceUtil::Handle<NodeSessionI> NodeSessionIPtr; - +class ReplicaCache; class ServerEntry; -typedef IceUtil::Handle<ServerEntry> ServerEntryPtr; -typedef std::vector<ServerEntryPtr> ServerEntrySeq; +class SessionI; -class ReplicaCache; +using ServerEntrySeq = std::vector<std::shared_ptr<ServerEntry>>; -class NodeEntry : private IceUtil::Monitor<IceUtil::RecMutex> +class NodeEntry final { public: NodeEntry(NodeCache&, const std::string&); - virtual ~NodeEntry(); void addDescriptor(const std::string&, const NodeDescriptor&); void removeDescriptor(const std::string&); - void addServer(const ServerEntryPtr&); - void removeServer(const ServerEntryPtr&); - void setSession(const NodeSessionIPtr&); + void addServer(const std::shared_ptr<ServerEntry>&); + void removeServer(const std::shared_ptr<ServerEntry>&); + void setSession(const std::shared_ptr<NodeSessionI>&); - NodePrx getProxy() const; - InternalNodeInfoPtr getInfo() const; + std::shared_ptr<NodePrx> getProxy() const; + std::shared_ptr<InternalNodeInfo> getInfo() const; ServerEntrySeq getServers() const; LoadInfo getLoadInfoAndLoadFactor(const std::string&, float&) const; - NodeSessionIPtr getSession() const; + std::shared_ptr<NodeSessionI> getSession() const; - Ice::ObjectPrx getAdminProxy() const; + std::shared_ptr<Ice::ObjectPrx> getAdminProxy() const; bool canRemove(); - void loadServer(const ServerEntryPtr&, const ServerInfo&, const SessionIPtr&, int, bool); - void destroyServer(const ServerEntryPtr&, const ServerInfo&, int, bool); + void loadServer(const std::shared_ptr<ServerEntry>&, const ServerInfo&, const std::shared_ptr<SessionI>&, + std::chrono::seconds, bool); + void destroyServer(const std::shared_ptr<ServerEntry>&, const ServerInfo&, std::chrono::seconds, bool); - ServerInfo getServerInfo(const ServerInfo&, const SessionIPtr&); - InternalServerDescriptorPtr getInternalServerDescriptor(const ServerInfo&, const SessionIPtr&); + ServerInfo getServerInfo(const ServerInfo&, const std::shared_ptr<SessionI>&); + std::shared_ptr<InternalServerDescriptor> getInternalServerDescriptor(const ServerInfo&, const std::shared_ptr<SessionI>&); - void __incRef(); - void __decRef(); - - void checkSession() const; - void setProxy(const NodePrx&); + void checkSession(std::unique_lock<std::mutex>&) const; + void setProxy(const std::shared_ptr<NodePrx>&); void finishedRegistration(); - void finishedRegistration(const Ice::Exception&); + void finishedRegistration(std::exception_ptr); private: - ServerDescriptorPtr getServerDescriptor(const ServerInfo&, const SessionIPtr&); - InternalServerDescriptorPtr getInternalServerDescriptor(const ServerInfo&) const; + std::shared_ptr<NodeEntry> selfRemovingPtr() const; + + std::shared_ptr<ServerDescriptor> getServerDescriptor(const ServerInfo&, const std::shared_ptr<SessionI>&); + std::shared_ptr<InternalServerDescriptor> getInternalServerDescriptor(const ServerInfo&) const; NodeCache& _cache; - IceUtil::Mutex _refMutex; - int _ref; const std::string _name; - NodeSessionIPtr _session; - std::map<std::string, ServerEntryPtr> _servers; + std::shared_ptr<NodeSessionI> _session; + std::map<std::string, std::shared_ptr<ServerEntry>> _servers; std::map<std::string, NodeDescriptor> _descriptors; mutable bool _registering; - mutable NodePrx _proxy; + mutable std::shared_ptr<NodePrx> _proxy; + + mutable std::mutex _mutex; + mutable std::condition_variable _condVar; + + // A self removing shared_ptr of 'this' which removes itself from the NodeCache upon destruction + std::weak_ptr<NodeEntry> _selfRemovingPtr; + + // The number of self removing shared_ptr deleters left to run. + // Always accessed with the cache mutex locked + int _selfRemovingRefCount; + + friend NodeCache; }; -typedef IceUtil::Handle<NodeEntry> NodeEntryPtr; class NodeCache : public CacheByString<NodeEntry> { public: - NodeCache(const Ice::CommunicatorPtr&, ReplicaCache&, const std::string&); + using ValueType = NodeEntry*; + + NodeCache(const std::shared_ptr<Ice::Communicator>&, ReplicaCache&, const std::string&); - NodeEntryPtr get(const std::string&, bool = false) const; + std::shared_ptr<NodeEntry> get(const std::string&, bool = false) const; - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr<Ice::Communicator>& getCommunicator() const { return _communicator; } const std::string& getReplicaName() const { return _replicaName; } ReplicaCache& getReplicaCache() const { return _replicaCache; } private: - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr<Ice::Communicator> _communicator; const std::string _replicaName; ReplicaCache& _replicaCache; }; diff --git a/cpp/src/IceGrid/NodeI.cpp b/cpp/src/IceGrid/NodeI.cpp index d098d71e83f..09c45027550 100644 --- a/cpp/src/IceGrid/NodeI.cpp +++ b/cpp/src/IceGrid/NodeI.cpp @@ -16,121 +16,37 @@ using namespace std; using namespace IceGrid; -namespace +NodeI::Update::Update(UpdateFunction updateFunction, const shared_ptr<NodeI>& node, + const shared_ptr<NodeObserverPrx>& observer) : _func(move(updateFunction)), + _node(node), _observer(observer) { +} -class NodeUp : public NodeI::Update +bool +NodeI::Update::send() { -public: - - NodeUp(const NodeIPtr& node, const NodeObserverPrx& observer, NodeDynamicInfo info) : - NodeI::Update(node, observer), _info(info) + auto self = shared_from_this(); + try { - } + _func([self] { self->_node->dequeueUpdate(self->_observer, self, false); }, + [self](exception_ptr) { self->_node->dequeueUpdate(self->_observer, self, true); }); - virtual bool - send() - { - try - { - _observer->begin_nodeUp(_info, newCallback(static_cast<NodeI::Update*>(this), &NodeI::Update::completed)); - } - catch(const Ice::LocalException&) - { - return false; - } return true; } - -private: - - NodeDynamicInfo _info; -}; - -class UpdateServer : public NodeI::Update -{ -public: - - UpdateServer(const NodeIPtr& node, const NodeObserverPrx& observer, ServerDynamicInfo info) : - NodeI::Update(node, observer), _info(info) - { - } - - virtual bool - send() + catch(const std::exception&) { - try - { - _observer->begin_updateServer(_node->getName(Ice::emptyCurrent), - _info, - newCallback(static_cast<NodeI::Update*>(this), &NodeI::Update::completed)); - } - catch(const Ice::LocalException&) - { - return false; - } - return true; - } - -private: - - ServerDynamicInfo _info; -}; - -class UpdateAdapter : public NodeI::Update -{ -public: - - UpdateAdapter(const NodeIPtr& node, const NodeObserverPrx& observer, AdapterDynamicInfo info) : - NodeI::Update(node, observer), _info(info) - { - } - - virtual bool - send() - { - try - { - _observer->begin_updateAdapter(_node->getName(Ice::emptyCurrent), - _info, - newCallback(static_cast<NodeI::Update*>(this), &NodeI::Update::completed)); - } - catch(const Ice::LocalException&) - { - return false; - } - return true; + return false; } - -private: - - AdapterDynamicInfo _info; -}; - -} - -NodeI::Update::Update(const NodeIPtr& node, const NodeObserverPrx& observer) : _node(node), _observer(observer) -{ } -NodeI::Update::~Update() -{ -} - -void -NodeI::Update::finished(bool success) -{ - _node->dequeueUpdate(_observer, this, !success); -} - -NodeI::NodeI(const Ice::ObjectAdapterPtr& adapter, +NodeI::NodeI(const shared_ptr<Ice::ObjectAdapter>& adapter, NodeSessionManager& sessions, - const ActivatorPtr& activator, + const shared_ptr<Activator>& activator, const IceUtil::TimerPtr& timer, - const TraceLevelsPtr& traceLevels, - const NodePrx& proxy, + const shared_ptr<TraceLevels>& traceLevels, + const shared_ptr<NodePrx>& proxy, const string& name, - const UserAccountMapperPrx& mapper, + const shared_ptr<UserAccountMapperPrx>& mapper, const string& instanceName) : _communicator(adapter->getCommunicator()), _adapter(adapter), @@ -146,16 +62,16 @@ NodeI::NodeI(const Ice::ObjectAdapterPtr& adapter, _instanceName(instanceName), _userAccountMapper(mapper), _platform("IceGrid.Node", _communicator, _traceLevels), - _fileCache(new FileCache(_communicator)), + _fileCache(make_shared<FileCache>(_communicator)), _serial(1), _consistencyCheckDone(false) { - Ice::PropertiesPtr props = _communicator->getProperties(); + auto props = _communicator->getProperties(); const_cast<string&>(_dataDir) = _platform.getDataDir(); const_cast<string&>(_serversDir) = _dataDir + "/servers"; const_cast<string&>(_tmpDir) = _dataDir + "/tmp"; - const_cast<Ice::Int&>(_waitTime) = props->getPropertyAsIntWithDefault("IceGrid.Node.WaitTime", 60); + const_cast<int&>(_waitTime) = props->getPropertyAsIntWithDefault("IceGrid.Node.WaitTime", 60); const_cast<string&>(_outputDir) = props->getProperty("IceGrid.Node.Output"); const_cast<bool&>(_redirectErrToOut) = props->getPropertyAsInt("IceGrid.Node.RedirectErrToOut") > 0; const_cast<bool&>(_allowEndpointsOverride) = props->getPropertyAsInt("IceGrid.Node.AllowEndpointsOverride") > 0; @@ -174,156 +90,75 @@ NodeI::NodeI(const Ice::ObjectAdapterPtr& adapter, } } - Ice::PropertiesPtr p = Ice::createProperties(); + auto p = Ice::createProperties(); p->parseCommandLineOptions("", overrides); - Ice::PropertyDict propDict = p->getPropertiesForPrefix(""); - for(Ice::PropertyDict::const_iterator q = propDict.begin(); q != propDict.end(); ++q) + auto propDict = p->getPropertiesForPrefix(""); + for(const auto& prop : propDict) { - _propertiesOverride.push_back(createProperty(q->first, q->second)); + _propertiesOverride.push_back({ prop.first, prop.second }); } } } void -NodeI::Update::completed(const Ice::AsyncResultPtr& result) -{ - try - { - result->throwLocalException(); - finished(true); - } - catch(const Ice::LocalException&) - { - finished(false); - } -} - -NodeI::~NodeI() +NodeI::loadServerAsync(shared_ptr<InternalServerDescriptor> descriptor, string replicaName, + function<void(const shared_ptr<ServerPrx>&, const AdapterPrxDict&, int, int)> response, + function<void(exception_ptr)> exception, const Ice::Current& current) { + loadServer(move(descriptor), move(replicaName), false, move(response), move(exception), current); } void -NodeI::loadServer_async(const AMD_Node_loadServerPtr& amdCB, - const InternalServerDescriptorPtr& descriptor, - const string& replicaName, - const Ice::Current& current) +NodeI::loadServerWithoutRestartAsync(shared_ptr<InternalServerDescriptor> descriptor, + string replicaName, + function<void(const shared_ptr<ServerPrx>&, + const AdapterPrxDict&, int, int)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) { - loadServer(amdCB, descriptor, replicaName, false, current); -} - -void -NodeI::loadServerWithoutRestart_async(const AMD_Node_loadServerWithoutRestartPtr& amdCB, - const InternalServerDescriptorPtr& descriptor, - const string& replicaName, - const Ice::Current& current) -{ - class LoadServerCB : public AMD_Node_loadServer - { - public: - - LoadServerCB(const AMD_Node_loadServerWithoutRestartPtr& cb) : _cb(cb) - { - } - - virtual void - ice_response(const ServerPrx& server, const AdapterPrxDict& adapters, Ice::Int actTimeout, Ice::Int deacTimeout) - { - _cb->ice_response(server, adapters, actTimeout, deacTimeout); - }; - - virtual void - ice_exception(const ::std::exception& ex) - { - _cb->ice_exception(ex); - } - - virtual void - ice_exception() - { - _cb->ice_exception(); - } - - private: - - const AMD_Node_loadServerWithoutRestartPtr _cb; - }; - loadServer(new LoadServerCB(amdCB), descriptor, replicaName, true, current); + loadServer(move(descriptor), move(replicaName), true, move(response), move(exception), current); } void -NodeI::destroyServer_async(const AMD_Node_destroyServerPtr& amdCB, - const string& serverId, - const string& uuid, - int revision, - const string& replicaName, - const Ice::Current& current) +NodeI::destroyServerAsync(string serverId, string uuid, int revision, string replicaName, + function<void()> response, function<void(exception_ptr)> exception, + const Ice::Current& current) { - destroyServer(amdCB, serverId, uuid, revision, replicaName, false, current); + destroyServer(move(serverId), move(uuid), move(revision), move(replicaName), false, + move(response), move(exception), current); } void -NodeI::destroyServerWithoutRestart_async(const AMD_Node_destroyServerWithoutRestartPtr& amdCB, - const string& serverId, - const string& uuid, - int revision, - const string& replicaName, - const Ice::Current& current) +NodeI::destroyServerWithoutRestartAsync(string serverId, string uuid, int revision, string replicaName, + function<void()> response, function<void(exception_ptr)> exception, + const Ice::Current& current) { - class DestroyServerCB : public AMD_Node_destroyServer - { - public: - - DestroyServerCB(const AMD_Node_destroyServerWithoutRestartPtr& cb) : _cb(cb) - { - } - - virtual void - ice_response() - { - _cb->ice_response(); - }; - - virtual void - ice_exception(const ::std::exception& ex) - { - _cb->ice_exception(ex); - } - - virtual void - ice_exception() - { - _cb->ice_exception(); - } - - private: - - const AMD_Node_destroyServerWithoutRestartPtr _cb; - }; - destroyServer(new DestroyServerCB(amdCB), serverId, uuid, revision, replicaName, true, current); + destroyServer(move(serverId), move(uuid), move(revision), move(replicaName), true, + move(response), move(exception), current); } void -NodeI::registerWithReplica(const InternalRegistryPrx& replica, const Ice::Current&) +NodeI::registerWithReplica(shared_ptr<InternalRegistryPrx> replica, const Ice::Current&) { - _sessions.create(replica); + _sessions.create(move(replica)); } void -NodeI::replicaInit(const InternalRegistryPrxSeq& replicas, const Ice::Current&) +NodeI::replicaInit(InternalRegistryPrxSeq replicas, const Ice::Current&) { - _sessions.replicaInit(replicas); + _sessions.replicaInit(move(replicas)); } void -NodeI::replicaAdded(const InternalRegistryPrx& replica, const Ice::Current&) +NodeI::replicaAdded(shared_ptr<InternalRegistryPrx> replica, const Ice::Current&) { - _sessions.replicaAdded(replica); + _sessions.replicaAdded(move(replica)); } void -NodeI::replicaRemoved(const InternalRegistryPrx& replica, const Ice::Current&) +NodeI::replicaRemoved(shared_ptr<InternalRegistryPrx> replica, const Ice::Current&) { - _sessions.replicaRemoved(replica); + _sessions.replicaRemoved(move(replica)); } std::string @@ -356,14 +191,14 @@ NodeI::shutdown(const Ice::Current&) const _activator->shutdown(); } -Ice::Long -NodeI::getOffsetFromEnd(const string& filename, int count, const Ice::Current&) const +long long +NodeI::getOffsetFromEnd(string filename, int count, const Ice::Current&) const { return _fileCache->getOffsetFromEnd(getFilePath(filename), count); } bool -NodeI::read(const string& filename, Ice::Long pos, int size, Ice::Long& newPos, Ice::StringSeq& lines, +NodeI::read(string filename, long long pos, int size, long long& newPos, Ice::StringSeq& lines, const Ice::Current&) const { return _fileCache->read(getFilePath(filename), pos, size, newPos, lines); @@ -372,31 +207,30 @@ NodeI::read(const string& filename, Ice::Long pos, int size, Ice::Long& newPos, void NodeI::shutdown() { - IceUtil::Mutex::Lock sync(_serversLock); - for(map<string, set<ServerIPtr> >::const_iterator p = _serversByApplication.begin(); - p != _serversByApplication.end(); ++p) + lock_guard lock(_serversMutex); + for(const auto& servers : _serversByApplication) { - for(set<ServerIPtr>::const_iterator q = p->second.begin(); q != p->second.end(); ++q) + for(const auto& server : servers.second) { - (*q)->shutdown(); + server->shutdown(); } } _serversByApplication.clear(); } -Ice::CommunicatorPtr +shared_ptr<Ice::Communicator> NodeI::getCommunicator() const { return _communicator; } -Ice::ObjectAdapterPtr +shared_ptr<Ice::ObjectAdapter> NodeI::getAdapter() const { return _adapter; } -ActivatorPtr +shared_ptr<Activator> NodeI::getActivator() const { return _activator; @@ -408,31 +242,31 @@ NodeI::getTimer() const return _timer; } -TraceLevelsPtr +shared_ptr<TraceLevels> NodeI::getTraceLevels() const { return _traceLevels; } -UserAccountMapperPrx +shared_ptr<UserAccountMapperPrx> NodeI::getUserAccountMapper() const { return _userAccountMapper; } PlatformInfo& -NodeI::getPlatformInfo() const +NodeI::getPlatformInfo() { return _platform; } -FileCachePtr +shared_ptr<FileCache> NodeI::getFileCache() const { return _fileCache; } -NodePrx +shared_ptr<NodePrx> NodeI::getProxy() const { return _proxy; @@ -468,14 +302,14 @@ NodeI::allowEndpointsOverride() const return _allowEndpointsOverride; } -NodeSessionPrx -NodeI::registerWithRegistry(const InternalRegistryPrx& registry) +shared_ptr<NodeSessionPrx> +NodeI::registerWithRegistry(const shared_ptr<InternalRegistryPrx>& registry) { return registry->registerNode(_platform.getInternalNodeInfo(), _proxy, _platform.getLoadInfo()); } void -NodeI::checkConsistency(const NodeSessionPrx& session) +NodeI::checkConsistency(const shared_ptr<NodeSessionPrx>& session) { // // Only do the consistency check on the startup. This ensures that servers can't @@ -499,11 +333,11 @@ NodeI::checkConsistency(const NodeSessionPrx& session) // unsigned long serial = 0; Ice::StringSeq servers; - vector<ServerCommandPtr> commands; + vector<shared_ptr<ServerCommand>> commands; while(true) { { - Lock sync(*this); + lock_guard lock(_mutex); if(serial == _serial) { _serial = 1; // We can reset the serial number. @@ -524,54 +358,56 @@ NodeI::checkConsistency(const NodeSessionPrx& session) sort(servers.begin(), servers.end()); } - for_each(commands.begin(), commands.end(), IceUtil::voidMemFun(&ServerCommand::execute)); + for(const auto& command : commands) + { + command->execute(); + } } void -NodeI::addObserver(const NodeSessionPrx& session, const NodeObserverPrx& observer) +NodeI::addObserver(const shared_ptr<NodeSessionPrx>& session, const shared_ptr<NodeObserverPrx>& observer) { - IceUtil::Mutex::Lock sync(_observerMutex); + lock_guard observerLock(_observerMutex); assert(_observers.find(session) == _observers.end()); - _observers.insert(make_pair(session, observer)); + _observers.insert({ session, observer }); _observerUpdates.erase(observer); // Remove any updates from the previous session. ServerDynamicInfoSeq serverInfos; AdapterDynamicInfoSeq adapterInfos; - for(map<string, ServerDynamicInfo>::const_iterator p = _serversDynamicInfo.begin(); - p != _serversDynamicInfo.end(); ++p) + for(const auto& info : _serversDynamicInfo) { - assert(p->second.state != Destroyed && (p->second.state != Inactive || !p->second.enabled)); - serverInfos.push_back(p->second); + assert(info.second.state != ServerState::Destroyed && + (info.second.state != ServerState::Inactive || !info.second.enabled)); + serverInfos.push_back(info.second); } - for(map<string, AdapterDynamicInfo>::const_iterator q = _adaptersDynamicInfo.begin(); - q != _adaptersDynamicInfo.end(); ++q) + for(const auto& info : _adaptersDynamicInfo) { - assert(q->second.proxy); - adapterInfos.push_back(q->second); + assert(info.second.proxy); + adapterInfos.push_back(info.second); } - NodeDynamicInfo info; - info.info = _platform.getNodeInfo(); - info.servers = serverInfos; - info.adapters = adapterInfos; - queueUpdate(observer, new NodeUp(this, observer, info)); + NodeDynamicInfo info = { _platform.getNodeInfo(), move(serverInfos), move(adapterInfos) }; + queueUpdate(observer, [observer, info = move(info)] (auto&& response, auto&& exception) + { + observer->nodeUpAsync(info, move(response), move(exception)); + }); } void -NodeI::removeObserver(const NodeSessionPrx& session) +NodeI::removeObserver(const shared_ptr<NodeSessionPrx>& session) { - IceUtil::Mutex::Lock sync(_observerMutex); + lock_guard observerLock(_observerMutex); _observers.erase(session); } void NodeI::observerUpdateServer(const ServerDynamicInfo& info) { - IceUtil::Mutex::Lock sync(_observerMutex); + lock_guard observerLock(_observerMutex); - if(info.state == Destroyed || (info.state == Inactive && info.enabled)) + if(info.state == ServerState::Destroyed || (info.state == ServerState::Inactive && info.enabled)) { _serversDynamicInfo.erase(info.id); } @@ -586,13 +422,20 @@ NodeI::observerUpdateServer(const ServerDynamicInfo& info) // registered twice if a replica is removed and added right away // after). // - set<NodeObserverPrx> sent; - for(map<NodeSessionPrx, NodeObserverPrx>::const_iterator p = _observers.begin(); p != _observers.end(); ++p) + set<shared_ptr<NodeObserverPrx>> sent; + for(const auto& observer : _observers) { - if(sent.find(p->second) == sent.end()) + if(sent.find(observer.second) == sent.end()) { - queueUpdate(p->second, new UpdateServer(this, p->second, info)); - sent.insert(p->second); + + queueUpdate(observer.second, + [observer = observer.second, info, name = getName(Ice::emptyCurrent)](auto&& response, + auto&& exception) + { + observer->updateServerAsync(name, info, move(response), move(exception)); + }); + + sent.insert(observer.second); } } } @@ -600,7 +443,7 @@ NodeI::observerUpdateServer(const ServerDynamicInfo& info) void NodeI::observerUpdateAdapter(const AdapterDynamicInfo& info) { - IceUtil::Mutex::Lock sync(_observerMutex); + lock_guard observerLock(_observerMutex); if(info.proxy) { @@ -617,22 +460,28 @@ NodeI::observerUpdateAdapter(const AdapterDynamicInfo& info) // registered twice if a replica is removed and added right away // after). // - set<NodeObserverPrx> sent; - for(map<NodeSessionPrx, NodeObserverPrx>::const_iterator p = _observers.begin(); p != _observers.end(); ++p) + set<shared_ptr<NodeObserverPrx>> sent; + for(const auto& observer : _observers) { - if(sent.find(p->second) == sent.end()) + if(sent.find(observer.second) == sent.end()) { - queueUpdate(p->second, new UpdateAdapter(this, p->second, info)); - sent.insert(p->second); + queueUpdate(observer.second, + [observer = observer.second, info, name = getName(Ice::emptyCurrent)] (auto&& response, + auto&& exception) + { + observer->updateAdapterAsync(name, info, move(response), move(exception)); + }); + sent.insert(observer.second); } } } void -NodeI::queueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update) +NodeI::queueUpdate(const shared_ptr<NodeObserverPrx>& proxy, Update::UpdateFunction updateFunction) { - //Lock sync(*this); Called within the synchronization - map<NodeObserverPrx, deque<UpdatePtr> >::iterator p = _observerUpdates.find(proxy); + // Must be called with mutex locked + auto update = make_shared<Update>(move(updateFunction), shared_from_this(), proxy); + auto p = _observerUpdates.find(proxy); if(p == _observerUpdates.end()) { if(update->send()) @@ -647,10 +496,10 @@ NodeI::queueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update) } void -NodeI::dequeueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update, bool all) +NodeI::dequeueUpdate(const shared_ptr<NodeObserverPrx>& proxy, const shared_ptr<Update>& update, bool all) { - IceUtil::Mutex::Lock sync(_observerMutex); - map<NodeObserverPrx, deque<UpdatePtr> >::iterator p = _observerUpdates.find(proxy); + lock_guard observerLock(_observerMutex); + auto p = _observerUpdates.find(proxy); if(p == _observerUpdates.end() || p->second.front().get() != update.get()) { return; @@ -670,23 +519,22 @@ NodeI::dequeueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update, bool } void -NodeI::addServer(const ServerIPtr& server, const string& application) +NodeI::addServer(const shared_ptr<ServerI>& server, const string& application) { - IceUtil::Mutex::Lock sync(_serversLock); - map<string, set<ServerIPtr> >::iterator p = _serversByApplication.find(application); + lock_guard serversLock(_serversMutex); + auto p = _serversByApplication.find(application); if(p == _serversByApplication.end()) { - map<string, set<ServerIPtr> >::value_type v(application, set<ServerIPtr>()); - p = _serversByApplication.insert(p, v); + p = _serversByApplication.insert(p, { application, {} }); } p->second.insert(server); } void -NodeI::removeServer(const ServerIPtr& server, const std::string& application) +NodeI::removeServer(const shared_ptr<ServerI>& server, const std::string& application) { - IceUtil::Mutex::Lock sync(_serversLock); - map<string, set<ServerIPtr> >::iterator p = _serversByApplication.find(application); + lock_guard serversLock(_serversMutex); + auto p = _serversByApplication.find(application); if(p != _serversByApplication.end()) { p->second.erase(server); @@ -700,10 +548,7 @@ NodeI::removeServer(const ServerIPtr& server, const std::string& application) Ice::Identity NodeI::createServerIdentity(const string& name) const { - Ice::Identity id; - id.category = _instanceName + "-Server"; - id.name = name; - return id; + return { name, _instanceName + "-Server" }; } string @@ -712,10 +557,10 @@ NodeI::getServerAdminCategory() const return _instanceName + "-NodeServerAdminRouter"; } -vector<ServerCommandPtr> +vector<shared_ptr<ServerCommand>> NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) { - vector<ServerCommandPtr> commands; + vector<shared_ptr<ServerCommand>> commands; // // Check if the servers directory doesn't contain more servers @@ -741,10 +586,10 @@ NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) // try { - vector<string>::iterator p = remove.begin(); + auto p = remove.begin(); while(p != remove.end()) { - ServerIPtr server = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(*p))); + auto server = dynamic_pointer_cast<ServerI>(_adapter->find(createServerIdentity(*p))); if(server) { // @@ -752,7 +597,7 @@ NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) // try { - ServerCommandPtr command = server->destroy(0, "", 0, "Master", false); + auto command = server->destroy("", 0, "Master", false, nullptr); if(command) { commands.push_back(command); @@ -812,7 +657,7 @@ NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) return commands; } -NodeSessionPrx +shared_ptr<NodeSessionPrx> NodeI::getMasterNodeSession() const { return _sessions.getMasterNodeSession(); @@ -900,12 +745,12 @@ NodeI::canRemoveServerDirectory(const string& name) return true; } -set<ServerIPtr> +set<shared_ptr<ServerI>> NodeI::getApplicationServers(const string& application) const { - IceUtil::Mutex::Lock sync(_serversLock); - set<ServerIPtr> servers; - map<string, set<ServerIPtr> >::const_iterator p = _serversByApplication.find(application); + lock_guard lock(_serversMutex); + set<shared_ptr<ServerI>> servers; + auto p = _serversByApplication.find(application); if(p != _serversByApplication.end()) { servers = p->second; @@ -941,18 +786,17 @@ NodeI::getFilePath(const string& filename) const } void -NodeI::loadServer(const AMD_Node_loadServerPtr& amdCB, - const InternalServerDescriptorPtr& descriptor, - const string& replicaName, - bool noRestart, +NodeI::loadServer(shared_ptr<InternalServerDescriptor> descriptor, string replicaName, bool noRestart, + function<void(const shared_ptr<ServerPrx> &, const AdapterPrxDict &, int, int)>&& response, + function<void(exception_ptr)>&& exception, const Ice::Current& current) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); + lock_guard lock(_mutex); ++_serial; - Ice::Identity id = createServerIdentity(descriptor->id); + auto id = createServerIdentity(descriptor->id); // // Check if we already have a servant for this server. If that's @@ -962,14 +806,14 @@ NodeI::loadServer(const AMD_Node_loadServerPtr& amdCB, while(true) { bool added = false; - ServerIPtr server; + shared_ptr<ServerI> server; try { - server = ServerIPtr::dynamicCast(_adapter->find(id)); + server = dynamic_pointer_cast<ServerI>(_adapter->find(id)); if(!server) { - ServerPrx proxy = ServerPrx::uncheckedCast(_adapter->createProxy(id)); - server = new ServerI(this, proxy, _serversDir, descriptor->id, _waitTime); + auto proxy = Ice::uncheckedCast<ServerPrx>(_adapter->createProxy(id)); + server = make_shared<ServerI>(shared_from_this(), proxy, _serversDir, descriptor->id, _waitTime); _adapter->add(server, id); added = true; } @@ -989,7 +833,8 @@ NodeI::loadServer(const AMD_Node_loadServerPtr& amdCB, try { - command = server->load(amdCB, descriptor, replicaName, noRestart); + // Don't std::move response/exception as we may need to loop and call again load. + command = server->load(descriptor, replicaName, noRestart, response, exception); } catch(const Ice::ObjectNotExistException&) { @@ -1021,30 +866,27 @@ NodeI::loadServer(const AMD_Node_loadServerPtr& amdCB, } void -NodeI::destroyServer(const AMD_Node_destroyServerPtr& amdCB, - const string& serverId, - const string& uuid, - int revision, - const string& replicaName, - bool noRestart, +NodeI::destroyServer(string serverId, string uuid, int revision, string replicaName, bool noRestart, + function<void()> response, + function<void(exception_ptr)>, const Ice::Current& current) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); + lock_guard lock(_mutex); ++_serial; - ServerIPtr server; + shared_ptr<ServerI> server; try { - server = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(serverId))); + server = dynamic_pointer_cast<ServerI>(_adapter->find(createServerIdentity(serverId))); } catch(const Ice::ObjectAdapterDeactivatedException&) { // // We throw an object not exist exception to avoid // dispatch warnings. The registry will consider the node - // has being unreachable upon receival of this exception + // has being unreachable upon receipt of this exception // (like any other Ice::LocalException). We could also // have disabled dispatch warnings but they can still // useful to catch other issues. @@ -1054,7 +896,7 @@ NodeI::destroyServer(const AMD_Node_destroyServerPtr& amdCB, if(!server) { - server = new ServerI(this, 0, _serversDir, serverId, _waitTime); + server = make_shared<ServerI>(shared_from_this(), nullptr, _serversDir, serverId, _waitTime); } // @@ -1062,11 +904,12 @@ NodeI::destroyServer(const AMD_Node_destroyServerPtr& amdCB, // try { - command = server->destroy(amdCB, uuid, revision, replicaName, noRestart); + // Don't std::move response as we may need to call it if there is an exception + command = server->destroy(uuid, revision, replicaName, noRestart, response); } catch(const Ice::ObjectNotExistException&) { - amdCB->ice_response(); + response(); return; } } diff --git a/cpp/src/IceGrid/NodeI.h b/cpp/src/IceGrid/NodeI.h index f01eda09c38..0f62c78f48d 100644 --- a/cpp/src/IceGrid/NodeI.h +++ b/cpp/src/IceGrid/NodeI.h @@ -15,101 +15,83 @@ namespace IceGrid { -class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - class Activator; -typedef IceUtil::Handle<Activator> ActivatorPtr; - -class ServerI; -typedef IceUtil::Handle<ServerI> ServerIPtr; - -class ServerCommand; -typedef IceUtil::Handle<ServerCommand> ServerCommandPtr; - class NodeSessionManager; +class ServerCommand; +class ServerI; +class TraceLevels; -class NodeI; -typedef IceUtil::Handle<NodeI> NodeIPtr; - -class NodeI : public Node, public IceUtil::Monitor<IceUtil::Mutex> +class NodeI : public Node, public std::enable_shared_from_this<NodeI> { public: - class Update : public virtual IceUtil::Shared + class Update final : public std::enable_shared_from_this<Update> { public: - Update(const NodeIPtr&, const NodeObserverPrx&); - virtual ~Update(); + using UpdateFunction = std::function<void(std::function<void()>, std::function<void(std::exception_ptr)>)>; - virtual bool send() = 0; + Update(UpdateFunction, const std::shared_ptr<NodeI>&, const std::shared_ptr<NodeObserverPrx>&); + bool send(); - void finished(bool); + private: - void completed(const Ice::AsyncResultPtr&); + UpdateFunction _func; + std::shared_ptr<NodeI> _node; + std::shared_ptr<NodeObserverPrx> _observer; + }; - protected: + NodeI(const std::shared_ptr<Ice::ObjectAdapter>&, NodeSessionManager&, const std::shared_ptr<Activator>&, + const IceUtil::TimerPtr&, const std::shared_ptr<TraceLevels>&, const std::shared_ptr<NodePrx>&, + const std::string&, const std::shared_ptr<UserAccountMapperPrx>&, const std::string&); - const NodeIPtr _node; - const NodeObserverPrx _observer; - }; - typedef IceUtil::Handle<Update> UpdatePtr; - - NodeI(const Ice::ObjectAdapterPtr&, NodeSessionManager&, const ActivatorPtr&, const IceUtil::TimerPtr&, - const TraceLevelsPtr&, const NodePrx&, const std::string&, const UserAccountMapperPrx&, const std::string&); - virtual ~NodeI(); - - virtual void loadServer_async(const AMD_Node_loadServerPtr&, - const InternalServerDescriptorPtr&, - const std::string&, - const Ice::Current&); - - virtual void loadServerWithoutRestart_async(const AMD_Node_loadServerWithoutRestartPtr&, - const InternalServerDescriptorPtr&, - const std::string&, - const Ice::Current&); - - virtual void destroyServer_async(const AMD_Node_destroyServerPtr&, - const std::string&, - const std::string&, - int, - const std::string&, - const Ice::Current&); - - virtual void destroyServerWithoutRestart_async(const AMD_Node_destroyServerWithoutRestartPtr&, - const std::string&, - const std::string&, - int, - const std::string&, - const Ice::Current&); - - virtual void registerWithReplica(const InternalRegistryPrx&, const Ice::Current&); - - virtual void replicaInit(const InternalRegistryPrxSeq&, const Ice::Current&); - virtual void replicaAdded(const InternalRegistryPrx&, const Ice::Current&); - virtual void replicaRemoved(const InternalRegistryPrx&, const Ice::Current&); - - virtual std::string getName(const Ice::Current&) const; - virtual std::string getHostname(const Ice::Current&) const; - virtual LoadInfo getLoad(const Ice::Current&) const; - virtual int getProcessorSocketCount(const Ice::Current&) const; - virtual void shutdown(const Ice::Current&) const; - - virtual Ice::Long getOffsetFromEnd(const std::string&, int, const Ice::Current&) const; - virtual bool read(const std::string&, Ice::Long, int, Ice::Long&, Ice::StringSeq&, const Ice::Current&) const; + void loadServerAsync(std::shared_ptr<InternalServerDescriptor>, std::string, + std::function<void(const std::shared_ptr<ServerPrx> &, const AdapterPrxDict &, int, int)>, + std::function<void(std::exception_ptr)>, + const Ice::Current &) override; + + void loadServerWithoutRestartAsync(std::shared_ptr<InternalServerDescriptor>, std::string, + std::function<void(const std::shared_ptr<ServerPrx>&, + const AdapterPrxDict&, int, int)>, + std::function<void(std::exception_ptr)>, + const Ice::Current &) override; + + void destroyServerAsync(std::string, std::string, int, std::string, + std::function<void()>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) override; + + void destroyServerWithoutRestartAsync(std::string, std::string, int, std::string, + std::function<void()>, + std::function<void(std::exception_ptr)>, + const ::Ice::Current& current) override; + + void registerWithReplica(std::shared_ptr<InternalRegistryPrx>, const Ice::Current&) override; + + void replicaInit(InternalRegistryPrxSeq, const Ice::Current&) override; + void replicaAdded(std::shared_ptr<InternalRegistryPrx>, const Ice::Current&) override; + void replicaRemoved(std::shared_ptr<InternalRegistryPrx>, const Ice::Current&) override; + + std::string getName(const Ice::Current&) const override; + std::string getHostname(const Ice::Current&) const override; + LoadInfo getLoad(const Ice::Current&) const override; + int getProcessorSocketCount(const Ice::Current&) const override; + void shutdown(const Ice::Current&) const override; + + long long getOffsetFromEnd(std::string, int, const Ice::Current&) const override; + bool read(std::string, long long, int, long long&, Ice::StringSeq&, const Ice::Current&) const override; void shutdown(); IceUtil::TimerPtr getTimer() const; - Ice::CommunicatorPtr getCommunicator() const; - Ice::ObjectAdapterPtr getAdapter() const; - ActivatorPtr getActivator() const; - TraceLevelsPtr getTraceLevels() const; - UserAccountMapperPrx getUserAccountMapper() const; - PlatformInfo& getPlatformInfo() const; - FileCachePtr getFileCache() const; - NodePrx getProxy() const; + std::shared_ptr<Ice::Communicator> getCommunicator() const; + std::shared_ptr<Ice::ObjectAdapter> getAdapter() const; + std::shared_ptr<Activator> getActivator() const; + std::shared_ptr<TraceLevels> getTraceLevels() const; + std::shared_ptr<UserAccountMapperPrx> getUserAccountMapper() const; + PlatformInfo& getPlatformInfo(); + std::shared_ptr<FileCache> getFileCache() const; + std::shared_ptr<NodePrx> getProxy() const; const PropertyDescriptorSeq& getPropertiesOverride() const; const std::string& getInstanceName() const; @@ -117,19 +99,20 @@ public: bool getRedirectErrToOut() const; bool allowEndpointsOverride() const; - NodeSessionPrx registerWithRegistry(const InternalRegistryPrx&); - void checkConsistency(const NodeSessionPrx&); - NodeSessionPrx getMasterNodeSession() const; + std::shared_ptr<NodeSessionPrx> registerWithRegistry(const std::shared_ptr<InternalRegistryPrx>&); + void checkConsistency(const std::shared_ptr<NodeSessionPrx>&); + std::shared_ptr<NodeSessionPrx> getMasterNodeSession() const; - void addObserver(const NodeSessionPrx&, const NodeObserverPrx&); - void removeObserver(const NodeSessionPrx&); + void addObserver(const std::shared_ptr<NodeSessionPrx>&, const std::shared_ptr<NodeObserverPrx>&); + void removeObserver(const std::shared_ptr<NodeSessionPrx>&); void observerUpdateServer(const ServerDynamicInfo&); void observerUpdateAdapter(const AdapterDynamicInfo&); - void queueUpdate(const NodeObserverPrx&, const UpdatePtr&); - void dequeueUpdate(const NodeObserverPrx&, const UpdatePtr&, bool); - void addServer(const ServerIPtr&, const std::string&); - void removeServer(const ServerIPtr&, const std::string&); + void queueUpdate(const std::shared_ptr<NodeObserverPrx>&, Update::UpdateFunction); + void dequeueUpdate(const std::shared_ptr<NodeObserverPrx>&, const std::shared_ptr<Update>&, bool); + + void addServer(const std::shared_ptr<ServerI>&, const std::string&); + void removeServer(const std::shared_ptr<ServerI>&, const std::string&); Ice::Identity createServerIdentity(const std::string&) const; std::string getServerAdminCategory() const; @@ -138,52 +121,57 @@ public: private: - std::vector<ServerCommandPtr> checkConsistencyNoSync(const Ice::StringSeq&); + std::vector<std::shared_ptr<ServerCommand>> checkConsistencyNoSync(const Ice::StringSeq&); - std::set<ServerIPtr> getApplicationServers(const std::string&) const; + std::set<std::shared_ptr<ServerI>> getApplicationServers(const std::string&) const; std::string getFilePath(const std::string&) const; - void loadServer(const AMD_Node_loadServerPtr&, const InternalServerDescriptorPtr&, const std::string&, bool, + void loadServer(std::shared_ptr<InternalServerDescriptor>, std::string, bool, + std::function<void(const std::shared_ptr<ServerPrx> &, const AdapterPrxDict &, int, int)>&&, + std::function<void(std::exception_ptr)>&&, const Ice::Current&); - void destroyServer(const AMD_Node_destroyServerPtr&, const std::string&, const std::string&, int, - const std::string&, bool, const Ice::Current&); + void destroyServer(std::string, std::string, int, std::string, bool, + std::function<void()>, + std::function<void(std::exception_ptr)>, + const Ice::Current&); - const Ice::CommunicatorPtr _communicator; - const Ice::ObjectAdapterPtr _adapter; + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<Ice::ObjectAdapter> _adapter; NodeSessionManager& _sessions; - const ActivatorPtr _activator; + const std::shared_ptr<Activator> _activator; const IceUtil::TimerPtr _timer; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr<TraceLevels> _traceLevels; const std::string _name; - const NodePrx _proxy; + const std::shared_ptr<NodePrx> _proxy; const std::string _outputDir; const bool _redirectErrToOut; const bool _allowEndpointsOverride; - const Ice::Int _waitTime; + const int _waitTime; const std::string _instanceName; - const UserAccountMapperPrx _userAccountMapper; - mutable PlatformInfo _platform; + const std::shared_ptr<UserAccountMapperPrx> _userAccountMapper; + PlatformInfo _platform; const std::string _dataDir; const std::string _serversDir; const std::string _tmpDir; - const FileCachePtr _fileCache; + const std::shared_ptr<FileCache> _fileCache; PropertyDescriptorSeq _propertiesOverride; unsigned long _serial; bool _consistencyCheckDone; - IceUtil::Mutex _observerMutex; - std::map<NodeSessionPrx, NodeObserverPrx> _observers; + std::mutex _observerMutex; + std::map<std::shared_ptr<NodeSessionPrx>, std::shared_ptr<NodeObserverPrx>> _observers; std::map<std::string, ServerDynamicInfo> _serversDynamicInfo; std::map<std::string, AdapterDynamicInfo> _adaptersDynamicInfo; - std::map<NodeObserverPrx, std::deque<UpdatePtr> > _observerUpdates; + std::map<std::shared_ptr<NodeObserverPrx>, std::deque<std::shared_ptr<Update>>> _observerUpdates; + + mutable std::mutex _serversMutex; + std::map<std::string, std::set<std::shared_ptr<ServerI>> > _serversByApplication; - IceUtil::Mutex _serversLock; - std::map<std::string, std::set<ServerIPtr> > _serversByApplication; + std::mutex _mutex; }; -typedef IceUtil::Handle<NodeI> NodeIPtr; } diff --git a/cpp/src/IceGrid/NodeSessionI.cpp b/cpp/src/IceGrid/NodeSessionI.cpp index 72e57e02a8c..d57b3af112a 100644 --- a/cpp/src/IceGrid/NodeSessionI.cpp +++ b/cpp/src/IceGrid/NodeSessionI.cpp @@ -11,66 +11,74 @@ using namespace std; using namespace IceGrid; -NodeSessionI::NodeSessionI(const DatabasePtr& database, - const NodePrx& node, - const InternalNodeInfoPtr& info, - int timeout, - const LoadInfo& load) : - _database(database), - _traceLevels(database->getTraceLevels()), - _node(node), - _info(info), - _timeout(timeout), - _timestamp(IceUtil::Time::now(IceUtil::Time::Monotonic)), - _load(load), - _destroy(false) +shared_ptr<NodeSessionI> +NodeSessionI::create(const shared_ptr<Database>& database, + const shared_ptr<NodePrx>& node, + const shared_ptr<InternalNodeInfo>& info, + std::chrono::seconds timeout, + const LoadInfo& load) { - __setNoDelete(true); + shared_ptr<NodeSessionI> nodeSession(new NodeSessionI(database, node, info, timeout, load)); try { - _database->getNode(info->name, true)->setSession(this); + database->getNode(info->name, true)->setSession(nodeSession); - ObjectInfo objInfo; - objInfo.type = Node::ice_staticId(); - objInfo.proxy = _node; - _database->addInternalObject(objInfo, true); // Add or update previous node proxy. + ObjectInfo objInfo = { node, Node::ice_staticId() }; + database->addInternalObject(objInfo, true); // Add or update previous node proxy. - _proxy = NodeSessionPrx::uncheckedCast(_database->getInternalAdapter()->addWithUUID(this)); + nodeSession->_proxy = Ice::uncheckedCast<NodeSessionPrx>( + database->getInternalAdapter()->addWithUUID(nodeSession)); } catch(const NodeActiveException&) { - __setNoDelete(false); throw; } - catch(...) + catch(const std::exception&) { try { - _database->removeInternalObject(_node->ice_getIdentity()); + database->removeInternalObject(node->ice_getIdentity()); } catch(const ObjectNotRegisteredException&) { } - _database->getNode(info->name)->setSession(0); + database->getNode(info->name)->setSession(nullptr); - __setNoDelete(false); throw; } - __setNoDelete(false); + + return nodeSession; +} + +NodeSessionI::NodeSessionI(const shared_ptr<Database>& database, + const shared_ptr<NodePrx>& node, + const shared_ptr<InternalNodeInfo>& info, + std::chrono::seconds timeout, + const LoadInfo& load) : + _database(database), + _traceLevels(database->getTraceLevels()), + _node(node), + _info(info), + _timeout(timeout), + _timestamp(chrono::steady_clock::now()), + _load(load), + _destroy(false) +{ } void -NodeSessionI::keepAlive(const LoadInfo& load, const Ice::Current&) +NodeSessionI::keepAlive(LoadInfo load, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); } - _timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic); - _load = load; + _timestamp = chrono::steady_clock::now(); + _load = move(load); if(_traceLevels->node > 2) { @@ -81,9 +89,10 @@ NodeSessionI::keepAlive(const LoadInfo& load, const Ice::Current&) } void -NodeSessionI::setReplicaObserver(const ReplicaObserverPrx& observer, const Ice::Current&) +NodeSessionI::setReplicaObserver(shared_ptr<ReplicaObserverPrx> observer, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroy) { return; @@ -101,17 +110,18 @@ NodeSessionI::setReplicaObserver(const ReplicaObserverPrx& observer, const Ice:: int NodeSessionI::getTimeout(const Ice::Current&) const { - return _timeout; + return secondsToInt(_timeout); } -NodeObserverPrx +shared_ptr<NodeObserverPrx> NodeSessionI::getObserver(const Ice::Current&) const { - return NodeObserverTopicPtr::dynamicCast(_database->getObserverTopic(NodeObserverTopicName))->getPublisher(); + return dynamic_pointer_cast<NodeObserverTopic>( + _database->getObserverTopic(TopicName::NodeObserver))->getPublisher(); } void -NodeSessionI::loadServers_async(const AMD_NodeSession_loadServersPtr& amdCB, const Ice::Current&) const +NodeSessionI::loadServersAsync(function<void()> response, function<void(exception_ptr)>, const Ice::Current&) const { // // No need to wait for the servers to be loaded. If we were @@ -119,38 +129,37 @@ NodeSessionI::loadServers_async(const AMD_NodeSession_loadServersPtr& amdCB, con // calling this method since each load() call might take time to // complete. // - amdCB->ice_response(); + response(); // // Get the server proxies to load them on the node. // - ServerEntrySeq servers = _database->getNode(_info->name)->getServers(); - for(ServerEntrySeq::const_iterator p = servers.begin(); p != servers.end(); ++p) + auto servers = _database->getNode(_info->name)->getServers(); + for(const auto& server : servers) { - (*p)->sync(); - (*p)->waitForSyncNoThrow(1); // Don't wait too long. + server->sync(); + server->waitForSyncNoThrow(1s); // Don't wait too long. } } Ice::StringSeq NodeSessionI::getServers(const Ice::Current&) const { - ServerEntrySeq servers = _database->getNode(_info->name)->getServers(); + auto servers = _database->getNode(_info->name)->getServers(); Ice::StringSeq names; - for(ServerEntrySeq::const_iterator p = servers.begin(); p != servers.end(); ++p) + for(const auto& server : servers) { - names.push_back((*p)->getId()); + names.push_back(server->getId()); } return names; } void -NodeSessionI::waitForApplicationUpdate_async(const AMD_NodeSession_waitForApplicationUpdatePtr& cb, - const std::string& application, - int revision, +NodeSessionI::waitForApplicationUpdateAsync(std::string application, int revision, + function<void()> response, function<void(exception_ptr)> exception, const Ice::Current&) const { - _database->waitForApplicationUpdate(cb, application, revision); + _database->waitForApplicationUpdate(move(application), move(revision), move(response), move(exception)); } void @@ -159,10 +168,10 @@ NodeSessionI::destroy(const Ice::Current&) destroyImpl(false); } -IceUtil::Time +chrono::steady_clock::time_point NodeSessionI::timestamp() const { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -176,13 +185,13 @@ NodeSessionI::shutdown() destroyImpl(true); } -const NodePrx& +const shared_ptr<NodePrx>& NodeSessionI::getNode() const { return _node; } -const InternalNodeInfoPtr& +const shared_ptr<InternalNodeInfo>& NodeSessionI::getInfo() const { return _info; @@ -191,11 +200,11 @@ NodeSessionI::getInfo() const const LoadInfo& NodeSessionI::getLoadInfo() const { - Lock sync(*this); + lock_guard lock(_mutex); return _load; } -NodeSessionPrx +shared_ptr<NodeSessionPrx> NodeSessionI::getProxy() const { return _proxy; @@ -204,7 +213,7 @@ NodeSessionI::getProxy() const bool NodeSessionI::isDestroyed() const { - Lock sync(*this); + lock_guard lock(_mutex); return _destroy; } @@ -212,7 +221,7 @@ void NodeSessionI::destroyImpl(bool shutdown) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -221,7 +230,10 @@ NodeSessionI::destroyImpl(bool shutdown) } ServerEntrySeq servers = _database->getNode(_info->name)->getServers(); - for_each(servers.begin(), servers.end(), IceUtil::voidMemFun(&ServerEntry::unsync)); + for(const auto& server : servers) + { + server->unsync(); + } // // If the registry isn't being shutdown we remove the node @@ -235,7 +247,8 @@ NodeSessionI::destroyImpl(bool shutdown) // // Next we notify the observer. // - NodeObserverTopicPtr::dynamicCast(_database->getObserverTopic(NodeObserverTopicName))->nodeDown(_info->name); + static_pointer_cast<NodeObserverTopic>( + _database->getObserverTopic(TopicName::NodeObserver))->nodeDown(_info->name); // // Unsubscribe the node replica observer. @@ -243,7 +256,7 @@ NodeSessionI::destroyImpl(bool shutdown) if(_replicaObserver) { _database->getReplicaCache().unsubscribe(_replicaObserver); - _replicaObserver = 0; + _replicaObserver = nullptr; } // @@ -251,7 +264,7 @@ NodeSessionI::destroyImpl(bool shutdown) // as the node entry session is set to 0 another session might be // created. // - _database->getNode(_info->name)->setSession(0); + _database->getNode(_info->name)->setSession(nullptr); if(!shutdown) { diff --git a/cpp/src/IceGrid/NodeSessionI.h b/cpp/src/IceGrid/NodeSessionI.h index b3ee36155b5..5958bd0a84e 100644 --- a/cpp/src/IceGrid/NodeSessionI.h +++ b/cpp/src/IceGrid/NodeSessionI.h @@ -12,54 +12,58 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; -class NodeSessionI : public NodeSession, public IceUtil::Mutex +class NodeSessionI : public NodeSession { public: - NodeSessionI(const DatabasePtr&, const NodePrx&, const InternalNodeInfoPtr&, int, const LoadInfo&); - - virtual void keepAlive(const LoadInfo&, const Ice::Current&); - virtual void setReplicaObserver(const ReplicaObserverPrx&, const Ice::Current&); - virtual int getTimeout(const Ice::Current&) const; - virtual NodeObserverPrx getObserver(const Ice::Current&) const; - virtual void loadServers_async(const AMD_NodeSession_loadServersPtr&, const Ice::Current&) const; - virtual Ice::StringSeq getServers(const Ice::Current&) const; - virtual void waitForApplicationUpdate_async(const AMD_NodeSession_waitForApplicationUpdatePtr&, - const std::string&, int, const Ice::Current&) const; - virtual void destroy(const Ice::Current&); - - virtual IceUtil::Time timestamp() const; - virtual void shutdown(); - - const NodePrx& getNode() const; - const InternalNodeInfoPtr& getInfo() const; + static std::shared_ptr<NodeSessionI> create(const std::shared_ptr<Database>&, const std::shared_ptr<NodePrx>&, + const std::shared_ptr<InternalNodeInfo>&, + std::chrono::seconds, const LoadInfo&); + + void keepAlive(LoadInfo, const Ice::Current&) override; + void setReplicaObserver(std::shared_ptr<ReplicaObserverPrx>, const Ice::Current&) override; + int getTimeout(const Ice::Current&) const override; + std::shared_ptr<NodeObserverPrx> getObserver(const Ice::Current&) const override; + void loadServersAsync(std::function<void()>, std::function<void(std::exception_ptr)>, + const Ice::Current&) const override; + Ice::StringSeq getServers(const Ice::Current&) const override; + void waitForApplicationUpdateAsync(std::string, int, std::function<void()>, std::function<void(std::exception_ptr)>, + const Ice::Current&) const override; + void destroy(const Ice::Current&) override; + + std::chrono::steady_clock::time_point timestamp() const; + void shutdown(); + + const std::shared_ptr<NodePrx>& getNode() const; + const std::shared_ptr<InternalNodeInfo>& getInfo() const; const LoadInfo& getLoadInfo() const; - NodeSessionPrx getProxy() const; + std::shared_ptr<NodeSessionPrx> getProxy() const; bool isDestroyed() const; private: + NodeSessionI(const std::shared_ptr<Database>&, const std::shared_ptr<NodePrx>&, + const std::shared_ptr<InternalNodeInfo>&, std::chrono::seconds, const LoadInfo&); + void destroyImpl(bool); - const DatabasePtr _database; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr<Database> _database; + const std::shared_ptr<TraceLevels> _traceLevels; const std::string _name; - const NodePrx _node; - const InternalNodeInfoPtr _info; - const int _timeout; - NodeSessionPrx _proxy; - ReplicaObserverPrx _replicaObserver; - IceUtil::Time _timestamp; + const std::shared_ptr<NodePrx> _node; + const std::shared_ptr<InternalNodeInfo> _info; + const std::chrono::seconds _timeout; + std::shared_ptr<NodeSessionPrx> _proxy; + std::shared_ptr<ReplicaObserverPrx> _replicaObserver; + std::chrono::steady_clock::time_point _timestamp; LoadInfo _load; bool _destroy; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<NodeSessionI> NodeSessionIPtr; }; diff --git a/cpp/src/IceGrid/NodeSessionManager.cpp b/cpp/src/IceGrid/NodeSessionManager.cpp index ab9ef518313..f90a242a430 100644 --- a/cpp/src/IceGrid/NodeSessionManager.cpp +++ b/cpp/src/IceGrid/NodeSessionManager.cpp @@ -10,8 +10,8 @@ using namespace std; using namespace IceGrid; -NodeSessionKeepAliveThread::NodeSessionKeepAliveThread(const InternalRegistryPrx& registry, - const NodeIPtr& node, +NodeSessionKeepAliveThread::NodeSessionKeepAliveThread(const shared_ptr<InternalRegistryPrx>& registry, + const shared_ptr<NodeI>& node, NodeSessionManager& manager) : SessionKeepAliveThread<NodeSessionPrx>(registry, node->getTraceLevels()->logger), _node(node), _manager(manager) { @@ -26,12 +26,12 @@ NodeSessionKeepAliveThread::NodeSessionKeepAliveThread(const InternalRegistryPrx const_cast<string&>(_replicaName) = name; } -NodeSessionPrx -NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil::Time& timeout) +shared_ptr<NodeSessionPrx> +NodeSessionKeepAliveThread::createSession(shared_ptr<InternalRegistryPrx>& registry, chrono::seconds& timeout) { - NodeSessionPrx session; - IceInternal::UniquePtr<Ice::Exception> exception; - TraceLevelsPtr traceLevels = _node->getTraceLevels(); + shared_ptr<NodeSessionPrx> session; + string exceptionMessage; + auto traceLevels = _node->getTraceLevels(); try { if(traceLevels && traceLevels->replica > 1) @@ -40,7 +40,7 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil out << "trying to establish session with replica `" << _replicaName << "'"; } - set<InternalRegistryPrx> used; + set<shared_ptr<InternalRegistryPrx>> used; if(!registry->ice_getEndpoints().empty()) { try @@ -49,34 +49,33 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil } catch(const Ice::LocalException& ex) { - exception.reset(ex.ice_clone()); + exceptionMessage = ex.what(); used.insert(registry); - registry = InternalRegistryPrx::uncheckedCast(registry->ice_endpoints(Ice::EndpointSeq())); + registry = Ice::uncheckedCast<InternalRegistryPrx>(registry->ice_endpoints(Ice::EndpointSeq())); } } if(!session) { - vector<Ice::AsyncResultPtr> results; - vector<QueryPrx> queryObjects = _manager.getQueryObjects(); - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector<future<shared_ptr<Ice::ObjectPrx>>> results; + auto queryObjects = _manager.getQueryObjects(); + for(const auto& object : queryObjects) { - results.push_back((*q)->begin_findObjectById(registry->ice_getIdentity())); + results.push_back(object->findObjectByIdAsync(registry->ice_getIdentity())); } - for(vector<Ice::AsyncResultPtr>::const_iterator p = results.begin(); p != results.end(); ++p) + for(auto& result : results) { - QueryPrx query = QueryPrx::uncheckedCast((*p)->getProxy()); if(isDestroyed()) { break; } - InternalRegistryPrx newRegistry; + shared_ptr<InternalRegistryPrx> newRegistry; try { - Ice::ObjectPrx obj = query->end_findObjectById(*p); - newRegistry = InternalRegistryPrx::uncheckedCast(obj); + auto obj = result.get(); + newRegistry = Ice::uncheckedCast<InternalRegistryPrx>(obj); if(newRegistry && used.find(newRegistry) == used.end()) { session = createSessionImpl(newRegistry, timeout); @@ -86,7 +85,7 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil } catch(const Ice::LocalException& ex) { - exception.reset(ex.ice_clone()); + exceptionMessage = ex.what(); if(newRegistry) { used.insert(newRegistry); @@ -102,7 +101,7 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil traceLevels->logger->error("a node with the same name is already active with the replica `" + _replicaName + "'"); } - exception.reset(ex.ice_clone()); + exceptionMessage = ex.what(); } catch(const PermissionDeniedException& ex) { @@ -110,11 +109,11 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil { traceLevels->logger->error("connection to the registry `" + _replicaName + "' was denied:\n" + ex.reason); } - exception.reset(ex.ice_clone()); + exceptionMessage = ex.what(); } catch(const Ice::Exception& ex) { - exception.reset(ex.ice_clone()); + exceptionMessage = ex.what(); } if(session) @@ -131,9 +130,9 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil { Ice::Trace out(traceLevels->logger, traceLevels->replicaCat); out << "failed to establish session with replica `" << _replicaName << "':\n"; - if(exception.get()) + if(!exceptionMessage.empty()) { - out << *exception.get(); + out << exceptionMessage; } else { @@ -145,17 +144,19 @@ NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil return session; } -NodeSessionPrx -NodeSessionKeepAliveThread::createSessionImpl(const InternalRegistryPrx& registry, IceUtil::Time& timeout) +shared_ptr<NodeSessionPrx> +NodeSessionKeepAliveThread::createSessionImpl(const shared_ptr<InternalRegistryPrx>& registry, chrono::seconds& timeout) { - NodeSessionPrx session; + shared_ptr<NodeSessionPrx> session; try { session = _node->registerWithRegistry(registry); - int t = session->getTimeout(); + auto t = session->getTimeout(); if(t > 0) { - timeout = IceUtil::Time::seconds(t / 2); + // Timeout is used to configure the delay to wait between two keep alives + // If we used t directly, a delayed keep alive could kill the session + timeout = chrono::seconds(t / 2); } _node->addObserver(session, session->getObserver()); return session; @@ -168,7 +169,7 @@ NodeSessionKeepAliveThread::createSessionImpl(const InternalRegistryPrx& registr } void -NodeSessionKeepAliveThread::destroySession(const NodeSessionPrx& session) +NodeSessionKeepAliveThread::destroySession(const shared_ptr<NodeSessionPrx>& session) { _node->removeObserver(session); @@ -196,7 +197,7 @@ NodeSessionKeepAliveThread::destroySession(const NodeSessionPrx& session) } bool -NodeSessionKeepAliveThread::keepAlive(const NodeSessionPrx& session) +NodeSessionKeepAliveThread::keepAlive(const shared_ptr<NodeSessionPrx>& session) { if(_node->getTraceLevels() && _node->getTraceLevels()->replica > 2) { @@ -221,7 +222,7 @@ NodeSessionKeepAliveThread::keepAlive(const NodeSessionPrx& session) } } -NodeSessionManager::NodeSessionManager(const Ice::CommunicatorPtr& communicator, const string& instanceName) : +NodeSessionManager::NodeSessionManager(const shared_ptr<Ice::Communicator>& communicator, const string& instanceName) : SessionManager(communicator, instanceName), _destroyed(false), _activated(false) @@ -229,14 +230,13 @@ NodeSessionManager::NodeSessionManager(const Ice::CommunicatorPtr& communicator, } void -NodeSessionManager::create(const NodeIPtr& node) +NodeSessionManager::create(const shared_ptr<NodeI>& node) { { - Lock sync(*this); + lock_guard lock(_mutex); assert(!_node); - const_cast<NodeIPtr&>(_node) = node; - _thread = new Thread(*this); - _thread->start(); + const_cast<shared_ptr<NodeI>&>(_node) = node; + _thread = make_shared<Thread>(*this); } // @@ -246,14 +246,14 @@ NodeSessionManager::create(const NodeIPtr& node) // before the node is activated. // _thread->tryCreateSession(); - _thread->waitTryCreateSession(IceUtil::Time::seconds(3)); + _thread->waitTryCreateSession(3s); } void -NodeSessionManager::create(const InternalRegistryPrx& replica) +NodeSessionManager::create(const shared_ptr<InternalRegistryPrx>& replica) { assert(_thread); - NodeSessionKeepAliveThreadPtr thread; + shared_ptr<NodeSessionKeepAliveThread> thread; if(replica->ice_getIdentity() == _master->ice_getIdentity()) { thread = _thread; @@ -261,7 +261,7 @@ NodeSessionManager::create(const InternalRegistryPrx& replica) } else { - Lock sync(*this); + lock_guard lock(_mutex); thread = addReplicaSession(replica); } @@ -276,7 +276,7 @@ void NodeSessionManager::activate() { { - Lock sync(*this); + lock_guard lock(_mutex); _activated = true; } @@ -285,7 +285,7 @@ NodeSessionManager::activate() // again and make sure that the servers are synchronized and the // replica observer is set on the session. // - NodeSessionPrx session = _thread->getSession(); + auto session = _thread->getSession(); if(session) { try @@ -319,6 +319,7 @@ NodeSessionManager::terminate() { assert(_thread); _thread->terminate(); + _thread->join(); } void @@ -326,14 +327,14 @@ NodeSessionManager::destroy() { NodeSessionMap sessions; { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; } _destroyed = true; _sessions.swap(sessions); - notifyAll(); + _condVar.notify_all(); } if(_thread) @@ -341,25 +342,27 @@ NodeSessionManager::destroy() _thread->terminate(); } - for(NodeSessionMap::const_iterator p = sessions.begin(); p != sessions.end(); ++p) + for(const auto& session : sessions) { - p->second->terminate(); + session.second->terminate(); } if(_thread) { - _thread->getThreadControl().join(); + _thread->join(); } - for(NodeSessionMap::const_iterator p = sessions.begin(); p != sessions.end(); ++p) + + for(const auto& session : sessions) { - p->second->getThreadControl().join(); + session.second->join(); } + } void NodeSessionManager::replicaInit(const InternalRegistryPrxSeq& replicas) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; @@ -369,17 +372,17 @@ NodeSessionManager::replicaInit(const InternalRegistryPrxSeq& replicas) // Initialize the set of replicas known by the master. // _replicas.clear(); - for(InternalRegistryPrxSeq::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - _replicas.insert((*p)->ice_getIdentity()); - addReplicaSession(*p)->tryCreateSession(); + _replicas.insert(replica->ice_getIdentity()); + addReplicaSession(replica)->tryCreateSession(); } } void -NodeSessionManager::replicaAdded(const InternalRegistryPrx& replica) +NodeSessionManager::replicaAdded(const shared_ptr<InternalRegistryPrx>& replica) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; @@ -389,10 +392,10 @@ NodeSessionManager::replicaAdded(const InternalRegistryPrx& replica) } void -NodeSessionManager::replicaRemoved(const InternalRegistryPrx& replica) +NodeSessionManager::replicaRemoved(const shared_ptr<InternalRegistryPrx>& replica) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; @@ -406,12 +409,12 @@ NodeSessionManager::replicaRemoved(const InternalRegistryPrx& replica) // } -NodeSessionKeepAliveThreadPtr -NodeSessionManager::addReplicaSession(const InternalRegistryPrx& replica) +shared_ptr<NodeSessionKeepAliveThread> +NodeSessionManager::addReplicaSession(const shared_ptr<InternalRegistryPrx>& replica) { assert(!_destroyed); - NodeSessionMap::const_iterator p = _sessions.find(replica->ice_getIdentity()); - NodeSessionKeepAliveThreadPtr thread; + auto p = _sessions.find(replica->ice_getIdentity()); + shared_ptr<NodeSessionKeepAliveThread> thread; if(p != _sessions.end()) { thread = p->second; @@ -419,9 +422,8 @@ NodeSessionManager::addReplicaSession(const InternalRegistryPrx& replica) } else { - thread = new NodeSessionKeepAliveThread(replica, _node, *this); + thread = make_shared<NodeSessionKeepAliveThread>(replica, _node, *this); _sessions.insert(make_pair(replica->ice_getIdentity(), thread)); - thread->start(); } return thread; } @@ -429,15 +431,17 @@ NodeSessionManager::addReplicaSession(const InternalRegistryPrx& replica) void NodeSessionManager::reapReplicas() { - vector<NodeSessionKeepAliveThreadPtr> reap; + // NodeSessionKeepAliveThread's destructor will join its thread on destruction + // Keep this vector do the destruction outside the lock + vector<shared_ptr<NodeSessionKeepAliveThread>> reap; { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; } - NodeSessionMap::iterator q = _sessions.begin(); + auto q = _sessions.begin(); while(q != _sessions.end()) { if(_replicas.find(q->first) == _replicas.end() && q->second->terminateIfDisconnected()) @@ -453,14 +457,14 @@ NodeSessionManager::reapReplicas() } } - for(vector<NodeSessionKeepAliveThreadPtr>::const_iterator p = reap.begin(); p != reap.end(); ++p) + for(const auto& r : reap) { - (*p)->getThreadControl().join(); + r->join(); } } void -NodeSessionManager::syncServers(const NodeSessionPrx& session) +NodeSessionManager::syncServers(const shared_ptr<NodeSessionPrx>& session) { // // Ask the session to load the servers on the node. Once this is @@ -479,11 +483,11 @@ NodeSessionManager::syncServers(const NodeSessionPrx& session) } void -NodeSessionManager::createdSession(const NodeSessionPrx& session) +NodeSessionManager::createdSession(const shared_ptr<NodeSessionPrx>& session) { bool activated; { - Lock sync(*this); + lock_guard lock(_mutex); activated = _activated; } @@ -534,9 +538,10 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) } else { - vector<Ice::AsyncResultPtr> results1; - vector<Ice::AsyncResultPtr> results2; - vector<QueryPrx> queryObjects = findAllQueryObjects(false); + + vector<future<Ice::ObjectProxySeq>> results1; + vector<future<Ice::ObjectProxySeq>> results2; + auto queryObjects = findAllQueryObjects(false); // // Below we try to retrieve internal registry proxies either @@ -549,19 +554,19 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) // more reliable. // - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + for(const auto& object : queryObjects) { - results1.push_back((*q)->begin_findAllObjectsByType(InternalRegistry::ice_staticId())); + results1.push_back(object->findAllObjectsByTypeAsync(InternalRegistry::ice_staticId())); } - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + for(const auto& object : queryObjects) { - results2.push_back((*q)->begin_findAllObjectsByType(Registry::ice_staticId())); + results2.push_back(object->findAllObjectsByTypeAsync(Registry::ice_staticId())); } - map<Ice::Identity, Ice::ObjectPrx> proxies; - for(vector<Ice::AsyncResultPtr>::const_iterator p = results1.begin(); p != results1.end(); ++p) + map<Ice::Identity, shared_ptr<Ice::ObjectPrx>> proxies; + + for(auto& result : results1) { - QueryPrx query = QueryPrx::uncheckedCast((*p)->getProxy()); if(isDestroyed()) { return; @@ -569,10 +574,10 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) try { - Ice::ObjectProxySeq prxs = query->end_findAllObjectsByType(*p); - for(Ice::ObjectProxySeq::const_iterator q = prxs.begin(); q != prxs.end(); ++q) + auto prxs = result.get(); + for(const auto& prx : prxs) { - proxies[(*q)->ice_getIdentity()] = *q; + proxies[prx->ice_getIdentity()] = prx; } } catch(const Ice::LocalException&) @@ -580,9 +585,8 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) // Ignore. } } - for(vector<Ice::AsyncResultPtr>::const_iterator p = results2.begin(); p != results2.end(); ++p) + for(auto& result : results2) { - QueryPrx query = QueryPrx::uncheckedCast((*p)->getProxy()); if(isDestroyed()) { return; @@ -590,22 +594,24 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) try { - Ice::ObjectProxySeq prxs = query->end_findAllObjectsByType(*p); - for(Ice::ObjectProxySeq::const_iterator q = prxs.begin(); q != prxs.end(); ++q) + auto prxs = result.get(); + for(auto prx : prxs) { - Ice::Identity id = (*q)->ice_getIdentity(); + Ice::Identity id = prx->ice_getIdentity(); const string prefix("Registry-"); string::size_type pos = id.name.find(prefix); if(pos == string::npos) { continue; // Ignore the master registry proxy. } + id.name = "InternalRegistry-" + id.name.substr(prefix.size()); + prx = prx->ice_identity(id)->ice_endpoints(Ice::EndpointSeq()); - Ice::ObjectPrx prx = (*q)->ice_identity(id)->ice_endpoints(Ice::EndpointSeq()); id.name = "Locator"; - prx = prx->ice_locator(Ice::LocatorPrx::uncheckedCast((*q)->ice_identity(id))); - proxies[id] = prx; + prx = prx->ice_locator(Ice::uncheckedCast<Ice::LocatorPrx>(prx->ice_identity(id))); + + proxies[id] = move(prx); } } catch(const Ice::LocalException&) @@ -614,15 +620,15 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) } } - for(map<Ice::Identity, Ice::ObjectPrx>::const_iterator q = proxies.begin(); q != proxies.end(); ++q) + for(const auto& prx : proxies) { - replicas.push_back(InternalRegistryPrx::uncheckedCast(q->second)); + replicas.push_back(Ice::uncheckedCast<InternalRegistryPrx>(prx.second)); } } - vector<NodeSessionKeepAliveThreadPtr> sessions; + vector<shared_ptr<NodeSessionKeepAliveThread>> sessions; { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; @@ -635,21 +641,21 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) if(!session || !_activated) { _replicas.clear(); - for(InternalRegistryPrxSeq::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - if((*p)->ice_getIdentity() != _master->ice_getIdentity()) + if(replica->ice_getIdentity() != _master->ice_getIdentity()) { - _replicas.insert((*p)->ice_getIdentity()); + _replicas.insert(replica->ice_getIdentity()); - if(_sessions.find((*p)->ice_getIdentity()) == _sessions.end()) + if(_sessions.find(replica->ice_getIdentity()) == _sessions.end()) { - NodeSessionKeepAliveThreadPtr thread = addReplicaSession(*p); + auto thread = addReplicaSession(replica); thread->tryCreateSession(); sessions.push_back(thread); } else { - addReplicaSession(*p); // Update the session + addReplicaSession(replica); // Update the session } } } @@ -661,18 +667,18 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) // the replica sessions are created before the node adapter is // activated. // - IceUtil::Time before = IceUtil::Time::now(); - for(vector<NodeSessionKeepAliveThreadPtr>::const_iterator p = sessions.begin(); p != sessions.end(); ++p) + auto before = chrono::system_clock::now(); + for(const auto& s : sessions) { if(isDestroyed()) { return; } - IceUtil::Time timeout = IceUtil::Time::seconds(5) - (IceUtil::Time::now() - before); - if(timeout <= IceUtil::Time()) + auto timeout = 5s - (chrono::system_clock::now() - before); + if(timeout <= 0s) { break; } - (*p)->waitTryCreateSession(timeout); + s->waitTryCreateSession(chrono::duration_cast<chrono::seconds>(timeout)); } } diff --git a/cpp/src/IceGrid/NodeSessionManager.h b/cpp/src/IceGrid/NodeSessionManager.h index 27abb769ecf..791c4c286be 100644 --- a/cpp/src/IceGrid/NodeSessionManager.h +++ b/cpp/src/IceGrid/NodeSessionManager.h @@ -5,10 +5,6 @@ #ifndef ICE_GRID_NODE_SESSION_MANAGER_H #define ICE_GRID_NODE_SESSION_MANAGER_H -#include <IceUtil/Handle.h> -#include <IceUtil/Mutex.h> -#include <IceUtil/Monitor.h> - #include <IceGrid/SessionManager.h> #include <IceGrid/Registry.h> #include <IceGrid/Internal.h> @@ -18,40 +14,40 @@ namespace IceGrid { class NodeI; -typedef IceUtil::Handle<NodeI> NodeIPtr; - class NodeSessionManager; class NodeSessionKeepAliveThread : public SessionKeepAliveThread<NodeSessionPrx> { public: - NodeSessionKeepAliveThread(const InternalRegistryPrx&, const NodeIPtr&, NodeSessionManager&); + NodeSessionKeepAliveThread(const std::shared_ptr<InternalRegistryPrx>&, const std::shared_ptr<NodeI>&, + NodeSessionManager&); - virtual NodeSessionPrx createSession(InternalRegistryPrx&, IceUtil::Time&); - virtual void destroySession(const NodeSessionPrx&); - virtual bool keepAlive(const NodeSessionPrx&); + virtual std::shared_ptr<NodeSessionPrx> createSession(std::shared_ptr<InternalRegistryPrx>&, + std::chrono::seconds&) override; + virtual void destroySession(const std::shared_ptr<NodeSessionPrx>&) override; + virtual bool keepAlive(const std::shared_ptr<NodeSessionPrx>&) override; - std::string getName() const { return _name; } + std::string getName() const { return "IceGrid session keepalive thread"; } protected: - virtual NodeSessionPrx createSessionImpl(const InternalRegistryPrx&, IceUtil::Time&); + std::shared_ptr<NodeSessionPrx> createSessionImpl(const std::shared_ptr<InternalRegistryPrx>&, + std::chrono::seconds&); - const NodeIPtr _node; + const std::shared_ptr<NodeI> _node; const std::string _replicaName; NodeSessionManager& _manager; }; -typedef IceUtil::Handle<NodeSessionKeepAliveThread> NodeSessionKeepAliveThreadPtr; class NodeSessionManager : public SessionManager { public: - NodeSessionManager(const Ice::CommunicatorPtr&, const std::string&); + NodeSessionManager(const std::shared_ptr<Ice::Communicator>&, const std::string&); - void create(const NodeIPtr&); - void create(const InternalRegistryPrx&); + void create(const std::shared_ptr<NodeI>&); + void create(const std::shared_ptr<InternalRegistryPrx>&); void activate(); bool isWaitingForCreate(); bool waitForCreate(); @@ -59,27 +55,27 @@ public: void destroy(); void replicaInit(const InternalRegistryPrxSeq&); - void replicaAdded(const InternalRegistryPrx&); - void replicaRemoved(const InternalRegistryPrx&); + void replicaAdded(const std::shared_ptr<InternalRegistryPrx>&); + void replicaRemoved(const std::shared_ptr<InternalRegistryPrx>&); - NodeSessionPrx getMasterNodeSession() const { return _thread->getSession(); } - std::vector<IceGrid::QueryPrx> getQueryObjects() { return findAllQueryObjects(true); } + std::shared_ptr<NodeSessionPrx> getMasterNodeSession() const { return _thread->getSession(); } + std::vector<std::shared_ptr<IceGrid::QueryPrx>> getQueryObjects() { return findAllQueryObjects(true); } private: - NodeSessionKeepAliveThreadPtr addReplicaSession(const InternalRegistryPrx&); + std::shared_ptr<NodeSessionKeepAliveThread> addReplicaSession(const std::shared_ptr<InternalRegistryPrx>&); void reapReplicas(); - void syncServers(const NodeSessionPrx&); + void syncServers(const std::shared_ptr<NodeSessionPrx>&); bool isDestroyed() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); return _destroyed; } - class Thread : public NodeSessionKeepAliveThread + class Thread final : public NodeSessionKeepAliveThread { public: @@ -87,41 +83,40 @@ private: { } - virtual NodeSessionPrx - createSession(InternalRegistryPrx& master, IceUtil::Time& timeout) + std::shared_ptr<NodeSessionPrx> + createSession(std::shared_ptr<InternalRegistryPrx>& master, std::chrono::seconds& timeout) override { - NodeSessionPrx session = NodeSessionKeepAliveThread::createSession(master, timeout); + auto session = NodeSessionKeepAliveThread::createSession(master, timeout); _manager.createdSession(session); _manager.reapReplicas(); return session; } - virtual void - destroySession(const NodeSessionPrx& session) + void + destroySession(const std::shared_ptr<NodeSessionPrx>& session) override { NodeSessionKeepAliveThread::destroySession(session); _manager.reapReplicas(); } - virtual bool - keepAlive(const NodeSessionPrx& session) + bool + keepAlive(const std::shared_ptr<NodeSessionPrx>& session) override { bool alive = NodeSessionKeepAliveThread::keepAlive(session); _manager.reapReplicas(); return alive; } }; - typedef IceUtil::Handle<Thread> ThreadPtr; friend class Thread; - void createdSession(const NodeSessionPrx&); + void createdSession(const std::shared_ptr<NodeSessionPrx>&); - const NodeIPtr _node; - ThreadPtr _thread; + const std::shared_ptr<NodeI> _node; + std::shared_ptr<Thread> _thread; bool _destroyed; bool _activated; - typedef std::map<Ice::Identity, NodeSessionKeepAliveThreadPtr> NodeSessionMap; + using NodeSessionMap = std::map<Ice::Identity, std::shared_ptr<NodeSessionKeepAliveThread>>; NodeSessionMap _sessions; std::set<Ice::Identity> _replicas; }; diff --git a/cpp/src/IceGrid/ObjectCache.cpp b/cpp/src/IceGrid/ObjectCache.cpp index caa5a75d3db..3ea4e33495d 100644 --- a/cpp/src/IceGrid/ObjectCache.cpp +++ b/cpp/src/IceGrid/ObjectCache.cpp @@ -14,57 +14,43 @@ using namespace std; using namespace IceGrid; -pointer_to_unary_function<int, unsigned int> ObjectCache::_rand(IceUtilInternal::random); - namespace IceGrid { -struct ObjectEntryCI : binary_function<ObjectEntryPtr&, ObjectEntryPtr&, bool> +bool compareObjectEntryCI(const shared_ptr<ObjectEntry>& lhs, const shared_ptr<ObjectEntry>& rhs) { + return Ice::proxyIdentityLess(lhs->getProxy(), rhs->getProxy()); +} - bool - operator()(const ObjectEntryPtr& lhs, const ObjectEntryPtr& rhs) - { - return ::Ice::proxyIdentityLess(lhs->getProxy(), rhs->getProxy()); - } -}; - -struct ObjectLoadCI : binary_function<pair<Ice::ObjectPrx, float>&, pair<Ice::ObjectPrx, float>&, bool> +bool compareObjectLoadCI(const pair<Ice::ObjectPrx, float>& lhs, const pair<Ice::ObjectPrx, float>& rhs) { - bool operator()(const pair<Ice::ObjectPrx, float>& lhs, const pair<Ice::ObjectPrx, float>& rhs) - { - return lhs.second < rhs.second; - } -}; + return lhs.second < rhs.second; +} }; -ObjectCache::TypeEntry::TypeEntry() -{ -} - void -ObjectCache::TypeEntry::add(const ObjectEntryPtr& obj) +ObjectCache::TypeEntry::add(const shared_ptr<ObjectEntry>& obj) { // // No mutex protection here, this is called with the cache locked. // - _objects.insert(lower_bound(_objects.begin(), _objects.end(), obj, ObjectEntryCI()), obj); + _objects.insert(lower_bound(_objects.begin(), _objects.end(), obj, compareObjectEntryCI), obj); } bool -ObjectCache::TypeEntry::remove(const ObjectEntryPtr& obj) +ObjectCache::TypeEntry::remove(const shared_ptr<ObjectEntry>& obj) { // // No mutex protection here, this is called with the cache locked. // - vector<ObjectEntryPtr>::iterator q = lower_bound(_objects.begin(), _objects.end(), obj, ObjectEntryCI()); + auto q = lower_bound(_objects.begin(), _objects.end(), obj, compareObjectEntryCI); assert(q->get() == obj.get()); _objects.erase(q); return _objects.empty(); } -ObjectCache::ObjectCache(const Ice::CommunicatorPtr& communicator) : _communicator(communicator) +ObjectCache::ObjectCache(const shared_ptr<Ice::Communicator>& communicator) : _communicator(communicator) { } @@ -73,7 +59,7 @@ ObjectCache::add(const ObjectInfo& info, const string& application, const string { const Ice::Identity& id = info.proxy->ice_getIdentity(); - Lock sync(*this); + lock_guard lock(_mutex); if(getImpl(id)) { Ice::Error out(_communicator->getLogger()); @@ -81,13 +67,13 @@ ObjectCache::add(const ObjectInfo& info, const string& application, const string return; } - ObjectEntryPtr entry = new ObjectEntry(info, application, server); + auto entry = make_shared<ObjectEntry>(info, application, server); addImpl(id, entry); map<string, TypeEntry>::iterator p = _types.find(entry->getType()); if(p == _types.end()) { - p = _types.insert(p, map<string, TypeEntry>::value_type(entry->getType(), TypeEntry())); + p = _types.insert(p, { entry->getType(), TypeEntry() }); } p->second.add(entry); @@ -98,11 +84,11 @@ ObjectCache::add(const ObjectInfo& info, const string& application, const string } } -ObjectEntryPtr +shared_ptr<ObjectEntry> ObjectCache::get(const Ice::Identity& id) const { - Lock sync(*this); - ObjectEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + shared_ptr<ObjectEntry> entry = getImpl(id); if(!entry) { throw ObjectNotRegisteredException(id); @@ -113,8 +99,8 @@ ObjectCache::get(const Ice::Identity& id) const void ObjectCache::remove(const Ice::Identity& id) { - Lock sync(*this); - ObjectEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + shared_ptr<ObjectEntry> entry = getImpl(id); if(!entry) { Ice::Error out(_communicator->getLogger()); @@ -137,14 +123,14 @@ ObjectCache::remove(const Ice::Identity& id) } } -vector<ObjectEntryPtr> +vector<shared_ptr<ObjectEntry>> ObjectCache::getObjectsByType(const string& type) { - Lock sync(*this); + lock_guard lock(_mutex); map<string, TypeEntry>::const_iterator p = _types.find(type); if(p == _types.end()) { - return vector<ObjectEntryPtr>(); + return vector<shared_ptr<ObjectEntry>>(); } return p->second.getObjects(); } @@ -152,9 +138,9 @@ ObjectCache::getObjectsByType(const string& type) ObjectInfoSeq ObjectCache::getAll(const string& expression) { - Lock sync(*this); + lock_guard lock(_mutex); ObjectInfoSeq infos; - for(map<Ice::Identity, ObjectEntryPtr>::const_iterator p = _entries.begin(); p != _entries.end(); ++p) + for(auto p = _entries.cbegin(); p != _entries.cend(); ++p) { if(expression.empty() || IceUtilInternal::match(_communicator->identityToString(p->first), expression, true)) { @@ -167,7 +153,7 @@ ObjectCache::getAll(const string& expression) ObjectInfoSeq ObjectCache::getAllByType(const string& type) { - Lock sync(*this); + lock_guard lock(_mutex); ObjectInfoSeq infos; map<string, TypeEntry>::const_iterator p = _types.find(type); if(p == _types.end()) @@ -175,8 +161,8 @@ ObjectCache::getAllByType(const string& type) return infos; } - const vector<ObjectEntryPtr>& objects = p->second.getObjects(); - for(vector<ObjectEntryPtr>::const_iterator q = objects.begin(); q != objects.end(); ++q) + const vector<shared_ptr<ObjectEntry>>& objects = p->second.getObjects(); + for(vector<shared_ptr<ObjectEntry>>::const_iterator q = objects.begin(); q != objects.end(); ++q) { infos.push_back((*q)->getObjectInfo()); } @@ -190,7 +176,7 @@ ObjectEntry::ObjectEntry(const ObjectInfo& info, const string& application, cons { } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> ObjectEntry::getProxy() const { return _info.proxy; diff --git a/cpp/src/IceGrid/ObjectCache.h b/cpp/src/IceGrid/ObjectCache.h index 3ad01e04679..a0b3f01bf25 100644 --- a/cpp/src/IceGrid/ObjectCache.h +++ b/cpp/src/IceGrid/ObjectCache.h @@ -5,7 +5,6 @@ #ifndef ICE_GRID_OBJECTCACHE_H #define ICE_GRID_OBJECTCACHE_H -#include <IceUtil/Mutex.h> #include <Ice/CommunicatorF.h> #include <IceGrid/Cache.h> #include <IceGrid/Internal.h> @@ -15,12 +14,12 @@ namespace IceGrid class ObjectCache; -class ObjectEntry : public IceUtil::Shared +class ObjectEntry { public: ObjectEntry(const ObjectInfo&, const std::string&, const std::string&); - Ice::ObjectPrx getProxy() const; + std::shared_ptr<Ice::ObjectPrx> getProxy() const; std::string getType() const; std::string getApplication() const; std::string getServer() const; @@ -34,24 +33,23 @@ private: const std::string _application; const std::string _server; }; -typedef IceUtil::Handle<ObjectEntry> ObjectEntryPtr; class ObjectCache : public Cache<Ice::Identity, ObjectEntry> { public: - ObjectCache(const Ice::CommunicatorPtr&); + ObjectCache(const std::shared_ptr<Ice::Communicator>&); void add(const ObjectInfo&, const std::string&, const std::string&); - ObjectEntryPtr get(const Ice::Identity&) const; + std::shared_ptr<ObjectEntry> get(const Ice::Identity&) const; void remove(const Ice::Identity&); - std::vector<ObjectEntryPtr> getObjectsByType(const std::string&); + std::vector<std::shared_ptr<ObjectEntry>> getObjectsByType(const std::string&); ObjectInfoSeq getAll(const std::string&); ObjectInfoSeq getAllByType(const std::string&); - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr<Ice::Communicator>& getCommunicator() const { return _communicator; } private: @@ -59,22 +57,19 @@ private: { public: - TypeEntry(); + void add(const std::shared_ptr<ObjectEntry>&); + bool remove(const std::shared_ptr<ObjectEntry>&); - void add(const ObjectEntryPtr&); - bool remove(const ObjectEntryPtr&); - - const std::vector<ObjectEntryPtr>& getObjects() const { return _objects; } + const std::vector<std::shared_ptr<ObjectEntry>>& getObjects() const { return _objects; } private: - std::vector<ObjectEntryPtr> _objects; + std::vector<std::shared_ptr<ObjectEntry>> _objects; }; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr<Ice::Communicator> _communicator; std::map<std::string, TypeEntry> _types; - static std::pointer_to_unary_function<int, unsigned int> _rand; }; }; diff --git a/cpp/src/IceGrid/Parser.cpp b/cpp/src/IceGrid/Parser.cpp index 736bd3ed421..8d85f207cd0 100644 --- a/cpp/src/IceGrid/Parser.cpp +++ b/cpp/src/IceGrid/Parser.cpp @@ -13,8 +13,9 @@ #include <IceGrid/DescriptorHelper.h> #include <IceBox/IceBox.h> -#if defined(__APPLE__) || defined(__linux__) -# include <editline/readline.h> +#ifdef HAVE_READLINE +# include <readline/readline.h> +# include <readline/history.h> #endif #include <iterator> @@ -233,7 +234,7 @@ const char* _commandsHelp[][3] = { int loggerCallbackCount = 0; #ifdef _WIN32 -Ice::StringConverterPtr windowsConsoleConverter = 0; +shared_ptr<Ice::StringConverter> windowsConsoleConverter = nullptr; #endif void outputNewline() @@ -283,12 +284,12 @@ void printLogMessage(const string& p, const Ice::LogMessage& logMessage) switch(logMessage.type) { - case Ice::PrintMessage: + case Ice::LogMessageType::PrintMessage: { writeMessage(timestamp + " " + logMessage.message, false); break; } - case Ice::TraceMessage: + case Ice::LogMessageType::TraceMessage: { string s = "-- " + timestamp + " " + prefix; if(!logMessage.traceCategory.empty()) @@ -299,12 +300,12 @@ void printLogMessage(const string& p, const Ice::LogMessage& logMessage) writeMessage(s, true); break; } - case Ice::WarningMessage: + case Ice::LogMessageType::WarningMessage: { writeMessage("!- " + timestamp + " " + prefix + "warning: " + logMessage.message, true); break; } - case Ice::ErrorMessage: + case Ice::LogMessageType::ErrorMessage: { writeMessage("!! " + timestamp + " " + prefix + "error: " + logMessage.message, true); break; @@ -316,27 +317,26 @@ void printLogMessage(const string& p, const Ice::LogMessage& logMessage) } } -class RemoteLoggerI : public Ice::RemoteLogger +class RemoteLoggerI final : public Ice::RemoteLogger { public: RemoteLoggerI(); - virtual void init(const string&, const Ice::LogMessageSeq&, const Ice::Current&); - virtual void log(const Ice::LogMessage&, const Ice::Current&); + void init(string, Ice::LogMessageSeq, const Ice::Current&) override; + void log(Ice::LogMessage, const Ice::Current&) override; void destroy(); private: - IceUtil::Monitor<IceUtil::Mutex> _monitor; + mutex _mutex; + condition_variable _condVar; bool _initDone; bool _destroyed; string _prefix; }; -typedef IceUtil::Handle<RemoteLoggerI> RemoteLoggerIPtr; - RemoteLoggerI::RemoteLoggerI() : _initDone(false), _destroyed(false) @@ -344,31 +344,30 @@ RemoteLoggerI::RemoteLoggerI() : } void -RemoteLoggerI::init(const string& prefix, const Ice::LogMessageSeq& logMessages, const Ice::Current&) +RemoteLoggerI::init(string prefix, Ice::LogMessageSeq logMessages, const Ice::Current&) { - IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor); + lock_guard lock(_mutex); if(!_destroyed) { _prefix = prefix; - for(Ice::LogMessageSeq::const_iterator p = logMessages.begin(); p != logMessages.end(); ++p) + for(const auto& message : logMessages) { - printLogMessage(_prefix, *p); + printLogMessage(_prefix, message); } _initDone = true; - _monitor.notifyAll(); + _condVar.notify_all(); } } void -RemoteLoggerI::log(const Ice::LogMessage& logMessage, const Ice::Current&) +RemoteLoggerI::log(Ice::LogMessage logMessage, const Ice::Current&) { - IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor); - while(!_initDone && !_destroyed) - { - _monitor.wait(); - } + unique_lock lock(_mutex); + + _condVar.wait(lock, [this] { return _initDone || _destroyed; } ); + if(!_destroyed) { printLogMessage(_prefix, logMessage); @@ -378,9 +377,9 @@ RemoteLoggerI::log(const Ice::LogMessage& logMessage, const Ice::Current&) void RemoteLoggerI::destroy() { - IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor); + lock_guard lock(_mutex); _destroyed = true; - _monitor.notifyAll(); + _condVar.notify_all(); } } @@ -392,11 +391,31 @@ Parser* parser; } -ParserPtr -Parser::createParser(const CommunicatorPtr& communicator, const AdminSessionPrx& session, const AdminPrx& admin, - bool interactive) +Parser::Parser(shared_ptr<Communicator> communicator, + shared_ptr<AdminSessionPrx> session, + shared_ptr<AdminPrx> admin, + bool interactive) : + _communicator(move(communicator)), + _session(move(session)), + _admin(move(admin)), + _interrupted(false), + _interactive(interactive) { - return new Parser(communicator, session, admin, interactive); + for(int i = 0; _commandsHelp[i][0]; i++) + { + const string category = _commandsHelp[i][0]; + const string cmd = _commandsHelp[i][1]; + const string help = _commandsHelp[i][2]; + _helpCommands[category][""] += help; + _helpCommands[category][cmd] += help; + } + +#ifdef _WIN32 + if(!windowsConsoleConverter) + { + windowsConsoleConverter = Ice::createWindowsStringConverter(GetConsoleOutputCP()); + } +#endif } void @@ -459,22 +478,22 @@ Parser::usage() void Parser::interrupt() { - Lock sync(*this); + lock_guard lock(_mutex); _interrupted = true; - notifyAll(); + _condVar.notify_all(); } bool Parser::interrupted() const { - Lock sync(*this); + lock_guard lock(_mutex); return _interrupted; } void Parser::resetInterrupt() { - Lock sync(*this); + lock_guard lock(_mutex); _interrupted = false; } @@ -483,7 +502,7 @@ Parser::checkInterrupted() { if(!_interactive) { - Lock sync(*this); + lock_guard lock(_mutex); if(_interrupted) { throw runtime_error("interrupted with Ctrl-C"); @@ -501,9 +520,9 @@ Parser::addApplication(const list<string>& origArgs) vector<string> args; try { - for(list<string>::const_iterator p = copyArgs.begin(); p != copyArgs.end(); ++p) + for(const auto& arg : copyArgs) { - args.push_back(*p); + args.push_back(arg); } args = opts.parse(args); } @@ -614,9 +633,9 @@ Parser::diffApplication(const list<string>& origArgs) vector<string> args; try { - for(list<string>::const_iterator p = copyArgs.begin(); p != copyArgs.end(); ++p) + for(const auto& arg : copyArgs) { - args.push_back(*p); + args.push_back(arg); } args = opts.parse(args); } @@ -840,8 +859,8 @@ Parser::describeServerTemplate(const list<string>& args) out << nl << "parameters = `" << toString(q->second.parameters) << "'"; out << nl; - ServerDescriptorPtr server = ServerDescriptorPtr::dynamicCast(q->second.descriptor); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(server); + auto server = dynamic_pointer_cast<ServerDescriptor>(q->second.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(server); if(iceBox) { IceBoxHelper(iceBox).print(_communicator, out); @@ -931,7 +950,7 @@ Parser::describeServiceTemplate(const list<string>& args) out << nl << "parameters = `" << toString(q->second.parameters) << "'"; out << nl; - ServiceDescriptorPtr desc = ServiceDescriptorPtr::dynamicCast(q->second.descriptor); + auto desc = dynamic_pointer_cast<ServiceDescriptor>(q->second.descriptor); ServiceHelper(desc).print(_communicator, out); out << eb; out << nl; @@ -1346,8 +1365,8 @@ Parser::writeMessage(const list<string>& args, int fd) list<string>::const_iterator p = args.begin(); string server = *p++; - Ice::ObjectPrx serverAdmin = _admin->getServerAdmin(server); - Ice::ProcessPrx process = Ice::ProcessPrx::uncheckedCast(serverAdmin, "Process"); + auto serverAdmin = _admin->getServerAdmin(server); + auto process = Ice::uncheckedCast<Ice::ProcessPrx>(serverAdmin, "Process"); process->writeMessage(*p, fd); } @@ -1379,7 +1398,7 @@ Parser::describeServer(const list<string>& args) ServerInfo info = _admin->getServerInfo(args.front()); ostringstream os; Output out(os); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(info.descriptor); if(iceBox) { IceBoxHelper(iceBox).print(_communicator, out, info); @@ -1412,39 +1431,39 @@ Parser::stateServer(const list<string>& args) string enabled = _admin->isServerEnabled(args.front()) ? "enabled" : "disabled"; switch(state) { - case Inactive: + case ServerState::Inactive: { consoleOut << "inactive (" << enabled << ")" << endl; break; } - case Activating: + case ServerState::Activating: { consoleOut << "activating (" << enabled << ")" << endl; break; } - case Active: + case ServerState::Active: { int pid = _admin->getServerPid(args.front()); consoleOut << "active (pid = " << pid << ", " << enabled << ")" << endl; break; } - case ActivationTimedOut: + case ServerState::ActivationTimedOut: { int pid = _admin->getServerPid(args.front()); consoleOut << "activation timed out (pid = " << pid << ", " << enabled << ")" << endl; break; } - case Deactivating: + case ServerState::Deactivating: { consoleOut << "deactivating (" << enabled << ")" << endl; break; } - case Destroying: + case ServerState::Destroying: { consoleOut << "destroying (" << enabled << ")" << endl; break; } - case Destroyed: + case ServerState::Destroyed: { consoleOut << "destroyed (" << enabled << ")" << endl; break; @@ -1502,8 +1521,8 @@ Parser::propertiesServer(const list<string>& args, bool single) try { - Ice::ObjectPrx serverAdmin = _admin->getServerAdmin(args.front()); - Ice::PropertiesAdminPrx propAdmin = Ice::PropertiesAdminPrx::uncheckedCast(serverAdmin, "Properties"); + auto serverAdmin = _admin->getServerAdmin(args.front()); + auto propAdmin = Ice::uncheckedCast<Ice::PropertiesAdminPrx>(serverAdmin, "Properties"); if(single) { @@ -1512,10 +1531,9 @@ Parser::propertiesServer(const list<string>& args, bool single) } else { - Ice::PropertyDict properties = propAdmin->getPropertiesForPrefix(""); - for(Ice::PropertyDict::const_iterator p = properties.begin(); p != properties.end(); ++p) + for(const auto& prop : propAdmin->getPropertiesForPrefix("")) { - consoleOut << p->first << "=" << p->second << endl; + consoleOut << prop.first << "=" << prop.second << endl; } } } @@ -1594,8 +1612,8 @@ Parser::startService(const list<string>& args) string service = *(++args.begin()); try { - Ice::ObjectPrx admin = _admin->getServerAdmin(server); - IceBox::ServiceManagerPrx manager = IceBox::ServiceManagerPrx::uncheckedCast(admin, "IceBox.ServiceManager"); + auto admin = _admin->getServerAdmin(server); + auto manager = Ice::uncheckedCast<IceBox::ServiceManagerPrx>(admin, "IceBox.ServiceManager"); manager->startService(service); } catch(const IceBox::AlreadyStartedException&) @@ -1633,8 +1651,8 @@ Parser::stopService(const list<string>& args) string service = *(++args.begin()); try { - Ice::ObjectPrx admin = _admin->getServerAdmin(server); - IceBox::ServiceManagerPrx manager = IceBox::ServiceManagerPrx::uncheckedCast(admin, "IceBox.ServiceManager"); + auto admin = _admin->getServerAdmin(server); + auto manager = Ice::uncheckedCast<IceBox::ServiceManagerPrx>(admin, "IceBox.ServiceManager"); manager->stopService(service); } catch(const IceBox::AlreadyStoppedException&) @@ -1673,7 +1691,7 @@ Parser::describeService(const list<string>& args) try { ServerInfo info = _admin->getServerInfo(server); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(info.descriptor); if(!iceBox) { error("server `" + server + "' is not an IceBox server"); @@ -1683,11 +1701,11 @@ Parser::describeService(const list<string>& args) ostringstream os; Output out(os); bool found = false; - for(ServiceInstanceDescriptorSeq::const_iterator p = iceBox->services.begin(); p != iceBox->services.end(); ++p) + for(const auto& s : iceBox->services) { - if(p->descriptor && p->descriptor->name == service) + if(s.descriptor && s.descriptor->name == service) { - ServiceHelper(p->descriptor).print(_communicator, out); + ServiceHelper(s.descriptor).print(_communicator, out); out << nl; found = true; break; @@ -1732,7 +1750,7 @@ Parser::propertiesService(const list<string>& args, bool single) // First, we ensure that the service exists. // ServerInfo info = _admin->getServerInfo(server); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(info.descriptor); if(!iceBox) { error("server `" + server + "' is not an IceBox server"); @@ -1740,9 +1758,10 @@ Parser::propertiesService(const list<string>& args, bool single) } bool found = false; - for(ServiceInstanceDescriptorSeq::const_iterator p = iceBox->services.begin(); p != iceBox->services.end(); ++p) + + for(const auto& s : iceBox->services) { - if(p->descriptor && p->descriptor->name == service) + if(s.descriptor && s.descriptor->name == service) { found = true; break; @@ -1754,15 +1773,15 @@ Parser::propertiesService(const list<string>& args, bool single) return; } - Ice::ObjectPrx admin = _admin->getServerAdmin(server); - Ice::PropertiesAdminPrx propAdmin; + auto admin = _admin->getServerAdmin(server); + shared_ptr<Ice::PropertiesAdminPrx> propAdmin; if(getPropertyAsInt(info.descriptor->propertySet.properties, "IceBox.UseSharedCommunicator." + service) > 0) { - propAdmin = Ice::PropertiesAdminPrx::uncheckedCast(admin, "IceBox.SharedCommunicator.Properties"); + propAdmin = Ice::uncheckedCast<Ice::PropertiesAdminPrx>(admin, "IceBox.SharedCommunicator.Properties"); } else { - propAdmin = Ice::PropertiesAdminPrx::uncheckedCast(admin, "IceBox.Service." + service + ".Properties"); + propAdmin = Ice::uncheckedCast<Ice::PropertiesAdminPrx>(admin, "IceBox.Service." + service + ".Properties"); } if(single) @@ -1806,17 +1825,17 @@ Parser::listServices(const list<string>& args) try { ServerInfo info = _admin->getServerInfo(server); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(info.descriptor); if(!iceBox) { error("server `" + server + "' is not an IceBox server"); return; } - for(ServiceInstanceDescriptorSeq::const_iterator p = iceBox->services.begin(); p != iceBox->services.end(); ++p) + for(const auto& s : iceBox->services) { - if(p->descriptor) + if(s.descriptor) { - consoleOut << p->descriptor->name << endl; + consoleOut << s.descriptor->name << endl; } } } @@ -2152,9 +2171,9 @@ Parser::showFile(const string& id, const string& reader, const string& filename, bool head, bool tail, bool follow, int lineCount) { - int maxBytes = _communicator->getProperties()->getPropertyAsIntWithDefault("Ice.MessageSizeMax", 1024) * 1024; + int maxBytes = _communicator->getProperties()->getPropertyAsIntWithDefault("Ice.MessageMaxSize", 1024) * 1024; - FileIteratorPrx it; + shared_ptr<FileIteratorPrx> it; try { @@ -2217,10 +2236,10 @@ Parser::showFile(const string& id, const string& reader, const string& filename, while(!interrupted() && !eof && i < lineCount) { eof = it->read(maxBytes, lines); - for(Ice::StringSeq::const_iterator p = lines.begin(); i < lineCount && p != lines.end(); ++p, ++i) + for(const auto& line : lines) { outputNewline(); - outputString(*p); + outputString(line); flushOutput(); } } @@ -2231,10 +2250,10 @@ Parser::showFile(const string& id, const string& reader, const string& filename, while(!interrupted() && !eof) { eof = it->read(maxBytes, lines); - for(Ice::StringSeq::const_iterator p = lines.begin(); p != lines.end(); ++p) + for(const auto& line : lines) { outputNewline(); - outputString(*p); + outputString(line); flushOutput(); } } @@ -2260,12 +2279,12 @@ Parser::showFile(const string& id, const string& reader, const string& filename, if(eof) { - Lock sync(*this); + unique_lock lock(_mutex); if(_interrupted) { break; } - timedWait(IceUtil::Time::seconds(5)); + _condVar.wait_for(lock, 5s); } } } @@ -2299,7 +2318,7 @@ Parser::showLog(const string& id, const string& reader, bool tail, bool follow, { outputNewline(); - Ice::ObjectPrx admin; + shared_ptr<Ice::ObjectPrx> admin; if(reader == "server") { @@ -2320,11 +2339,11 @@ Parser::showLog(const string& id, const string& reader, bool tail, bool follow, return; } - Ice::LoggerAdminPrx loggerAdmin; + shared_ptr<Ice::LoggerAdminPrx> loggerAdmin; try { - loggerAdmin = Ice::LoggerAdminPrx::checkedCast(admin, "Logger"); + loggerAdmin = Ice::checkedCast<Ice::LoggerAdminPrx>(admin, "Logger"); } catch(const Ice::Exception&) { @@ -2338,7 +2357,7 @@ Parser::showLog(const string& id, const string& reader, bool tail, bool follow, if(follow) { - Ice::ObjectPrx adminCallbackTemplate = _session->getAdminCallbackTemplate(); + auto adminCallbackTemplate = _session->getAdminCallbackTemplate(); if(adminCallbackTemplate == 0) { @@ -2349,44 +2368,39 @@ Parser::showLog(const string& id, const string& reader, bool tail, bool follow, const Ice::EndpointSeq endpoints = adminCallbackTemplate->ice_getEndpoints(); string publishedEndpoints; - for(Ice::EndpointSeq::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) + for(const auto& endpoint : endpoints) { if(publishedEndpoints.empty()) { - publishedEndpoints = (*p)->toString(); + publishedEndpoints = endpoint->toString(); } else { - publishedEndpoints += ":" + (*p)->toString(); + publishedEndpoints += ":" + endpoint->toString(); } } _communicator->getProperties()->setProperty("RemoteLoggerAdapter.PublishedEndpoints", publishedEndpoints); - Ice::ObjectAdapterPtr adapter = _communicator->createObjectAdapter("RemoteLoggerAdapter"); + auto adapter = _communicator->createObjectAdapter("RemoteLoggerAdapter"); _session->ice_getConnection()->setAdapter(adapter); - Ice::Identity ident; - ostringstream name; - name << "RemoteLogger-" << loggerCallbackCount++; - ident.name = name.str(); - ident.category = adminCallbackTemplate->ice_getIdentity().category; + ostringstream os; + os << "RemoteLogger-" << loggerCallbackCount++; + Ice::Identity ident = { os.str(), + adminCallbackTemplate->ice_getIdentity().category }; - RemoteLoggerIPtr servant = new RemoteLoggerI; - Ice::RemoteLoggerPrx prx = - Ice::RemoteLoggerPrx::uncheckedCast(adapter->add(servant, ident)); + auto servant = make_shared<RemoteLoggerI>(); + auto prx = Ice::uncheckedCast<Ice::RemoteLoggerPrx>(adapter->add(servant, ident)); adapter->activate(); loggerAdmin->attachRemoteLogger(prx, Ice::LogMessageTypeSeq(), Ice::StringSeq(), tail ? lineCount : -1); resetInterrupt(); { - Lock lock(*this); - while(!_interrupted) - { - wait(); - } + unique_lock lock(_mutex); + _condVar.wait(lock, [this] { return _interrupted; }); } servant->destroy(); @@ -2467,78 +2481,72 @@ Parser::getInput(char* buf, size_t& result, size_t maxSize) } else { -#if defined(__APPLE__) || defined(__linux__) - if (isatty(fileno(stdin)) == 1) +#ifdef HAVE_READLINE + + const char* prompt = parser->getPrompt(); + char* line = readline(const_cast<char*>(prompt)); + if(!line) { - const char* prompt = parser->getPrompt(); - char* line = readline(const_cast<char*>(prompt)); - if(!line) + result = 0; + } + else + { + if(*line) + { + add_history(line); + } + + result = strlen(line) + 1; + if(result > maxSize) { + free(line); + error("input line too long"); result = 0; } else { - if(*line) - { - add_history(line); - } - - result = strlen(line) + 1; - if(result > maxSize) - { - free(line); - error("input line too long"); - result = 0; - } - else - { - strcpy(buf, line); - strcat(buf, "\n"); - free(line); - } + strcpy(buf, line); + strcat(buf, "\n"); + free(line); } } - else +#else + consoleOut << parser->getPrompt() << flush; + string line; + while(true) { -#endif - consoleOut << parser->getPrompt() << flush; - string line; - while(true) + int c = getc(yyin); + if(c == EOF) { - int c = getc(yyin); - if(c == EOF) + if(line.size()) { - if(line.size()) - { - line += '\n'; - } - break; - } - - line += static_cast<char>(c); - if(c == '\n') - { - break; + line += '\n'; } + break; } -#ifdef _WIN32 - if(windowsConsoleConverter) + + line += static_cast<char>(c); + if(c == '\n') { - line = nativeToUTF8(line, windowsConsoleConverter); + break; } + } +#ifdef _WIN32 + if(windowsConsoleConverter) + { + line = nativeToUTF8(line, windowsConsoleConverter); + } #endif - result = line.length(); - if(result > maxSize) - { - error("input line too long"); - buf[0] = EOF; - result = 1; - } - else - { - strcpy(buf, line.c_str()); - } -#if defined(__APPLE__) || defined(__linux__) + result = line.length(); + if(result > maxSize) + { + error("input line too long"); + buf[0] = EOF; + result = 1; + } + else + { + strcpy(buf, line.c_str()); } #endif } @@ -2692,33 +2700,6 @@ Parser::parse(const std::string& commands, bool debug) return status; } -Parser::Parser(const CommunicatorPtr& communicator, - const AdminSessionPrx& session, - const AdminPrx& admin, - bool interactive) : - _communicator(communicator), - _session(session), - _admin(admin), - _interrupted(false), - _interactive(interactive) -{ - for(int i = 0; _commandsHelp[i][0]; i++) - { - const string category = _commandsHelp[i][0]; - const string cmd = _commandsHelp[i][1]; - const string help = _commandsHelp[i][2]; - _helpCommands[category][""] += help; - _helpCommands[category][cmd] += help; - } - -#ifdef _WIN32 - if(!windowsConsoleConverter) - { - windowsConsoleConverter = Ice::createWindowsStringConverter(GetConsoleOutputCP()); - } -#endif -} - void Parser::exception(const Ice::Exception& pex) { diff --git a/cpp/src/IceGrid/Parser.h b/cpp/src/IceGrid/Parser.h index b28492f08e2..3c3f8d19a25 100644 --- a/cpp/src/IceGrid/Parser.h +++ b/cpp/src/IceGrid/Parser.h @@ -5,9 +5,9 @@ #ifndef ICE_GRID_PARSER_H #define ICE_GRID_PARSER_H -#include <IceUtil/Handle.h> #include <IceGrid/Admin.h> #include <IceGrid/Registry.h> + #include <list> #include <stdio.h> @@ -38,19 +38,11 @@ YY_DECL; namespace IceGrid { -class Parser; -typedef ::IceUtil::Handle<Parser> ParserPtr; - -} - -namespace IceGrid -{ - -class Parser : public ::IceUtil::SimpleShared, IceUtil::Monitor<IceUtil::Mutex> +class Parser { public: - static ParserPtr createParser(const Ice::CommunicatorPtr&, const AdminSessionPrx&, const AdminPrx&, bool); + Parser(std::shared_ptr<Ice::Communicator>, std::shared_ptr<AdminSessionPrx>, std::shared_ptr<AdminPrx>, bool); void usage(); void usage(const std::string&, const std::string& = std::string()); @@ -145,16 +137,18 @@ public: private: - Parser(const Ice::CommunicatorPtr&, const AdminSessionPrx&, const AdminPrx&, bool); void exception(const Ice::Exception&); void showFile(const std::string&, const std::string&, const std::string&, bool, bool, bool, int); void showLog(const std::string&, const std::string&, bool, bool, int); + mutable std::mutex _mutex; + std::condition_variable _condVar; + std::string _commands; - Ice::CommunicatorPtr _communicator; - AdminSessionPrx _session; - AdminPrx _admin; + std::shared_ptr<Ice::Communicator> _communicator; + std::shared_ptr<AdminSessionPrx> _session; + std::shared_ptr<AdminPrx> _admin; bool _continue; bool _interrupted; int _errors; diff --git a/cpp/src/IceGrid/PlatformInfo.cpp b/cpp/src/IceGrid/PlatformInfo.cpp index 5b953d0ebb1..a15e2fd89dc 100644 --- a/cpp/src/IceGrid/PlatformInfo.cpp +++ b/cpp/src/IceGrid/PlatformInfo.cpp @@ -22,13 +22,6 @@ # include <sys/utsname.h> # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) # include <sys/sysctl.h> -# elif defined(__sun) -# include <sys/loadavg.h> -# elif defined(__hpux) -# include <sys/pstat.h> -# elif defined(_AIX) -# include <nlist.h> -# include <fcntl.h> # endif #endif @@ -47,7 +40,7 @@ pdhErrorToString(PDH_STATUS err) } static string -getLocalizedPerfName(int idx, const Ice::LoggerPtr& logger) +getLocalizedPerfName(int idx, const shared_ptr<Ice::Logger>& logger) { vector<char> localized; unsigned long size = 256; @@ -95,7 +88,7 @@ private: typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); int -getSocketCount(const Ice::LoggerPtr& logger) +getSocketCount(const shared_ptr<Ice::Logger>& logger) { LPFN_GLPI glpi; glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); @@ -149,7 +142,7 @@ namespace IceGrid { RegistryInfo -toRegistryInfo(const InternalReplicaInfoPtr& replica) +toRegistryInfo(const shared_ptr<InternalReplicaInfo>& replica) { RegistryInfo info; info.name = replica->name; @@ -158,7 +151,7 @@ toRegistryInfo(const InternalReplicaInfoPtr& replica) } NodeInfo -toNodeInfo(const InternalNodeInfoPtr& node) +toNodeInfo(const shared_ptr<InternalNodeInfo>& node) { NodeInfo info; info.name = node->name; @@ -175,8 +168,8 @@ toNodeInfo(const InternalNodeInfoPtr& node) } PlatformInfo::PlatformInfo(const string& prefix, - const Ice::CommunicatorPtr& communicator, - const TraceLevelsPtr& traceLevels) : + const shared_ptr<Ice::Communicator>& communicator, + const shared_ptr<TraceLevels>& traceLevels) : _traceLevels(traceLevels) { // @@ -190,25 +183,6 @@ PlatformInfo::PlatformInfo(const string& prefix, _last1Total = 0; _last5Total = 0; _last15Total = 0; -#elif defined(_AIX) - struct nlist nl; - nl.n_name = const_cast<char*>("avenrun"); - nl.n_value = 0; - if(knlist(&nl, 1, sizeof(nl)) == 0) - { - _kmem = open("/dev/kmem", O_RDONLY); - - // - // Give up root permissions to minimize security risks, it's - // only needed to access /dev/kmem. - // - setuid(getuid()); - setgid(getgid()); - } - else - { - _kmem = -1; - } #endif // @@ -253,11 +227,11 @@ PlatformInfo::PlatformInfo(const string& prefix, // // GetVersionEx deprecated in Windows 8.1 // -# if defined(_MSC_VER) && _MSC_VER >= 1800 +# if defined(_MSC_VER) # pragma warning (disable : 4996) # endif GetVersionEx(&osInfo); -# if defined(_MSC_VER) && _MSC_VER >= 1800 +# if defined(_MSC_VER) # pragma warning (default : 4996) # endif @@ -323,7 +297,7 @@ PlatformInfo::PlatformInfo(const string& prefix, _machine = utsinfo.machine; #endif - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); // // Try to obtain the number of processor sockets. @@ -400,22 +374,11 @@ PlatformInfo::PlatformInfo(const string& prefix, } } -PlatformInfo::~PlatformInfo() -{ -#if defined(_AIX) - if(_kmem > 0) - { - close(_kmem); - } -#endif -} - void PlatformInfo::start() { #if defined(_WIN32) - _updateUtilizationThread = new UpdateUtilizationAverageThread(*this); - _updateUtilizationThread->start(); + _updateUtilizationThread = std::thread([this] { runUpdateLoadInfo(); }); #endif } @@ -424,14 +387,11 @@ PlatformInfo::stop() { #if defined(_WIN32) { - IceUtil::Monitor<IceUtil::Mutex>::Lock sync(_utilizationMonitor); + lock_guard lock(_utilizationMutex); _terminated = true; - _utilizationMonitor.notify(); + _utilizationCondVar.notify_one(); } - - assert(_updateUtilizationThread); - _updateUtilizationThread->getThreadControl().join(); - _updateUtilizationThread = 0; + _updateUtilizationThread.join(); #endif } @@ -447,40 +407,26 @@ PlatformInfo::getRegistryInfo() const return toRegistryInfo(getInternalReplicaInfo()); } -InternalNodeInfoPtr +shared_ptr<InternalNodeInfo> PlatformInfo::getInternalNodeInfo() const { - InternalNodeInfoPtr info = new InternalNodeInfo(); - info->name = _name; - info->os = _os; - info->hostname = _hostname; - info->release = _release; - info->version = _version; - info->machine = _machine; - info->nProcessors = _nProcessorThreads; - info->dataDir = _dataDir; - return info; + return make_shared<InternalNodeInfo>(_name, _os, _hostname, _release, _version, + _machine, _nProcessorThreads, _dataDir); } -InternalReplicaInfoPtr +shared_ptr<InternalReplicaInfo> PlatformInfo::getInternalReplicaInfo() const { - InternalReplicaInfoPtr info = new InternalReplicaInfo(); - info->name = _name; - info->hostname = _hostname; - return info; + return make_shared<InternalReplicaInfo>(_name, _hostname); } LoadInfo -PlatformInfo::getLoadInfo() +PlatformInfo::getLoadInfo() const { - LoadInfo info; - info.avg1 = -1.0f; - info.avg5 = -1.0f; - info.avg15 = -1.0f; + LoadInfo info = { -1.0f, -1.0f, -1.0f }; #if defined(_WIN32) - IceUtil::Monitor<IceUtil::Mutex>::Lock sync(_utilizationMonitor); + lock_guard lock(_utilizationMutex); info.avg1 = static_cast<float>(_last1Total) / _usages1.size() / 100.0f; info.avg5 = static_cast<float>(_last5Total) / _usages5.size() / 100.0f; info.avg15 = static_cast<float>(_last15Total) / _usages15.size() / 100.0f; @@ -491,37 +437,12 @@ PlatformInfo::getLoadInfo() // not. The result is capped at 1.0f. // double loadAvg[3]; - if(getloadavg(loadAvg, 3) != -1) + if (getloadavg(loadAvg, 3) != -1) { info.avg1 = static_cast<float>(loadAvg[0]); info.avg5 = static_cast<float>(loadAvg[1]); info.avg15 = static_cast<float>(loadAvg[2]); } -#elif defined(__hpux) - struct pst_dynamic dynInfo; - if(pstat_getdynamic(&dynInfo, sizeof(dynInfo), 1, 0) >= 0) - { - info.avg1 = dynInfo.psd_avg_1_min; - info.avg5 = dynInfo.psd_avg_5_min; - info.avg15 = dynInfo.psd_avg_15_min; - } -#elif defined(_AIX) - if(_kmem > 1) - { - long long avenrun[3]; - struct nlist nl; - nl.n_name = const_cast<char*>("avenrun"); - nl.n_value = 0; - if(knlist(&nl, 1, sizeof(nl)) == 0) - { - if(pread(_kmem, avenrun, sizeof(avenrun), nl.n_value) >= sizeof(avenrun)) - { - info.avg1 = avenrun[0] / 65536.0f; - info.avg5 = avenrun[1] / 65536.0f; - info.avg15 = avenrun[2] / 65536.0f; - } - } - } #endif return info; } @@ -614,8 +535,8 @@ PlatformInfo::runUpdateLoadInfo() while(true) { - IceUtil::Monitor<IceUtil::Mutex>::Lock sync(_utilizationMonitor); - _utilizationMonitor.timedWait(IceUtil::Time::seconds(5)); // 5 seconds. + unique_lock lock(_utilizationMutex); + _utilizationCondVar.wait_for(lock, 5s); if(_terminated) { break; diff --git a/cpp/src/IceGrid/PlatformInfo.h b/cpp/src/IceGrid/PlatformInfo.h index e9ca4942eff..6615908ada3 100644 --- a/cpp/src/IceGrid/PlatformInfo.h +++ b/cpp/src/IceGrid/PlatformInfo.h @@ -5,7 +5,6 @@ #ifndef ICE_GRID_PLATFORM_INFO_H #define ICE_GRID_PLATFORM_INFO_H -#include <IceUtil/Thread.h> #include <IceGrid/Internal.h> #ifdef _WIN32 @@ -17,28 +16,26 @@ namespace IceGrid { class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; -NodeInfo toNodeInfo(const InternalNodeInfoPtr&); -RegistryInfo toRegistryInfo(const InternalReplicaInfoPtr&); +NodeInfo toNodeInfo(const std::shared_ptr<InternalNodeInfo>&); +RegistryInfo toRegistryInfo(const std::shared_ptr<InternalReplicaInfo>&); -class PlatformInfo +class PlatformInfo final { public: - PlatformInfo(const std::string&, const Ice::CommunicatorPtr&, const TraceLevelsPtr&); - ~PlatformInfo(); + PlatformInfo(const std::string&, const std::shared_ptr<Ice::Communicator>&, const std::shared_ptr<TraceLevels>&); void start(); void stop(); - InternalNodeInfoPtr getInternalNodeInfo() const; - InternalReplicaInfoPtr getInternalReplicaInfo() const; + std::shared_ptr<InternalNodeInfo> getInternalNodeInfo() const; + std::shared_ptr<InternalReplicaInfo> getInternalReplicaInfo() const; NodeInfo getNodeInfo() const; RegistryInfo getRegistryInfo() const; - LoadInfo getLoadInfo(); + LoadInfo getLoadInfo() const; int getProcessorSocketCount() const; std::string getHostname() const; std::string getDataDir() const; @@ -50,7 +47,7 @@ public: private: - const TraceLevelsPtr _traceLevels; + const std::shared_ptr<TraceLevels> _traceLevels; std::string _name; std::string _os; std::string _hostname; @@ -64,17 +61,16 @@ private: int _nProcessorSockets; #if defined(_WIN32) - IceUtil::ThreadPtr _updateUtilizationThread; - IceUtil::Monitor<IceUtil::Mutex> _utilizationMonitor; - bool _terminated; std::deque<int> _usages1; std::deque<int> _usages5; std::deque<int> _usages15; int _last1Total; int _last5Total; int _last15Total; -#elif defined(_AIX) - int _kmem; + bool _terminated; + mutable std::mutex _utilizationMutex; + std::condition_variable _utilizationCondVar; + std::thread _updateUtilizationThread; #endif }; diff --git a/cpp/src/IceGrid/PluginFacadeI.cpp b/cpp/src/IceGrid/PluginFacadeI.cpp index 2aab4145681..79fd99739d4 100644 --- a/cpp/src/IceGrid/PluginFacadeI.cpp +++ b/cpp/src/IceGrid/PluginFacadeI.cpp @@ -13,7 +13,7 @@ using namespace IceGrid; namespace IceGrid { -ICEGRID_API void setRegistryPluginFacade(const RegistryPluginFacadePtr&); +ICEGRID_API void setRegistryPluginFacade(const shared_ptr<RegistryPluginFacade>&); } @@ -26,23 +26,23 @@ public: Init() { - IceGrid::setRegistryPluginFacade(new RegistryPluginFacadeI); + IceGrid::setRegistryPluginFacade(make_shared<RegistryPluginFacadeI>()); } ~Init() { - IceGrid::setRegistryPluginFacade(0); + IceGrid::setRegistryPluginFacade(nullptr); } }; Init init; bool -hasAdapter(const CommunicatorDescriptorPtr& descriptor, const string& adapterId) +hasAdapter(const shared_ptr<CommunicatorDescriptor>& descriptor, const string& adapterId) { - for(AdapterDescriptorSeq::const_iterator p = descriptor->adapters.begin(); p != descriptor->adapters.end(); ++p) + for(const auto& adapter : descriptor->adapters) { - if(p->id == adapterId) + if(adapter.id == adapterId) { return true; } @@ -52,14 +52,10 @@ hasAdapter(const CommunicatorDescriptorPtr& descriptor, const string& adapterId) } -RegistryPluginFacadeI::RegistryPluginFacadeI() -{ -} - ApplicationInfo RegistryPluginFacadeI::getApplicationInfo(const string& name) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -70,7 +66,7 @@ RegistryPluginFacadeI::getApplicationInfo(const string& name) const ServerInfo RegistryPluginFacadeI::getServerInfo(const string& serverId) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -81,7 +77,7 @@ RegistryPluginFacadeI::getServerInfo(const string& serverId) const AdapterInfoSeq RegistryPluginFacadeI::getAdapterInfo(const string& adapterId) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -92,7 +88,7 @@ RegistryPluginFacadeI::getAdapterInfo(const string& adapterId) const string RegistryPluginFacadeI::getAdapterServer(const string& adapterId) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -103,7 +99,7 @@ RegistryPluginFacadeI::getAdapterServer(const string& adapterId) const string RegistryPluginFacadeI::getAdapterNode(const string& adapterId) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -114,7 +110,7 @@ RegistryPluginFacadeI::getAdapterNode(const string& adapterId) const string RegistryPluginFacadeI::getAdapterApplication(const string& adapterId) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -125,7 +121,7 @@ RegistryPluginFacadeI::getAdapterApplication(const string& adapterId) const ObjectInfo RegistryPluginFacadeI::getObjectInfo(const Ice::Identity& id) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -136,7 +132,7 @@ RegistryPluginFacadeI::getObjectInfo(const Ice::Identity& id) const NodeInfo RegistryPluginFacadeI::getNodeInfo(const string& name) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -147,7 +143,7 @@ RegistryPluginFacadeI::getNodeInfo(const string& name) const LoadInfo RegistryPluginFacadeI::getNodeLoad(const string& name) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_database) { throw RegistryUnreachableException("", "registry not initialized yet"); @@ -166,7 +162,7 @@ RegistryPluginFacadeI::getPropertyForAdapter(const std::string& adapterId, const return IceGrid::getProperty(info.descriptor->propertySet.properties, name); } - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast<IceBoxDescriptor>(info.descriptor); if(!iceBox) { return ""; @@ -190,29 +186,29 @@ RegistryPluginFacadeI::getPropertyForAdapter(const std::string& adapterId, const } void -RegistryPluginFacadeI::addReplicaGroupFilter(const string& id, const ReplicaGroupFilterPtr& filter) ICE_NOEXCEPT +RegistryPluginFacadeI::addReplicaGroupFilter(const string& id, const shared_ptr<ReplicaGroupFilter>& filter) noexcept { - Lock sync(*this); - map<string, vector<ReplicaGroupFilterPtr> >::iterator p = _replicaGroupFilters.find(id); + lock_guard lock(_mutex); + map<string, vector<shared_ptr<ReplicaGroupFilter>> >::iterator p = _replicaGroupFilters.find(id); if(p == _replicaGroupFilters.end()) { - p = _replicaGroupFilters.insert(make_pair(id, vector<ReplicaGroupFilterPtr>())).first; + p = _replicaGroupFilters.insert(make_pair(id, vector<shared_ptr<ReplicaGroupFilter>>())).first; } p->second.push_back(filter); } bool -RegistryPluginFacadeI::removeReplicaGroupFilter(const string& id, const ReplicaGroupFilterPtr& filter) ICE_NOEXCEPT +RegistryPluginFacadeI::removeReplicaGroupFilter(const string& id, const shared_ptr<ReplicaGroupFilter>& filter) noexcept { - Lock sync(*this); + lock_guard lock(_mutex); - map<string, vector<ReplicaGroupFilterPtr> >::iterator p = _replicaGroupFilters.find(id); + map<string, vector<shared_ptr<ReplicaGroupFilter>> >::iterator p = _replicaGroupFilters.find(id); if(p == _replicaGroupFilters.end()) { return false; } - vector<ReplicaGroupFilterPtr>::iterator q = find(p->second.begin(), p->second.end(), filter); + vector<shared_ptr<ReplicaGroupFilter>>::iterator q = find(p->second.begin(), p->second.end(), filter); if(q == p->second.end()) { return false; @@ -227,29 +223,29 @@ RegistryPluginFacadeI::removeReplicaGroupFilter(const string& id, const ReplicaG } void -RegistryPluginFacadeI::addTypeFilter(const string& id, const TypeFilterPtr& filter) ICE_NOEXCEPT +RegistryPluginFacadeI::addTypeFilter(const string& id, const shared_ptr<TypeFilter>& filter) noexcept { - Lock sync(*this); - map<string, vector<TypeFilterPtr> >::iterator p = _typeFilters.find(id); + lock_guard lock(_mutex); + map<string, vector<shared_ptr<TypeFilter>> >::iterator p = _typeFilters.find(id); if(p == _typeFilters.end()) { - p = _typeFilters.insert(make_pair(id, vector<TypeFilterPtr>())).first; + p = _typeFilters.insert(make_pair(id, vector<shared_ptr<TypeFilter>>())).first; } p->second.push_back(filter); } bool -RegistryPluginFacadeI::removeTypeFilter(const string& id, const TypeFilterPtr& filter) ICE_NOEXCEPT +RegistryPluginFacadeI::removeTypeFilter(const string& id, const shared_ptr<TypeFilter>& filter) noexcept { - Lock sync(*this); + lock_guard lock(_mutex); - map<string, vector<TypeFilterPtr> >::iterator p = _typeFilters.find(id); + map<string, vector<shared_ptr<TypeFilter>> >::iterator p = _typeFilters.find(id); if(p == _typeFilters.end()) { return false; } - vector<TypeFilterPtr>::iterator q = find(p->second.begin(), p->second.end(), filter); + vector<shared_ptr<TypeFilter>>::iterator q = find(p->second.begin(), p->second.end(), filter); if(q == p->second.end()) { return false; @@ -263,16 +259,16 @@ RegistryPluginFacadeI::removeTypeFilter(const string& id, const TypeFilterPtr& f return true; } -vector<ReplicaGroupFilterPtr> +vector<shared_ptr<ReplicaGroupFilter>> RegistryPluginFacadeI::getReplicaGroupFilters(const string& id) const { - Lock sync(*this); - map<string, vector<ReplicaGroupFilterPtr> >::const_iterator p = _replicaGroupFilters.find(id); + lock_guard lock(_mutex); + map<string, vector<shared_ptr<ReplicaGroupFilter>> >::const_iterator p = _replicaGroupFilters.find(id); if(p != _replicaGroupFilters.end()) { return p->second; } - return vector<ReplicaGroupFilterPtr>(); + return vector<shared_ptr<ReplicaGroupFilter>>(); } bool @@ -281,16 +277,16 @@ RegistryPluginFacadeI::hasReplicaGroupFilters() const return !_replicaGroupFilters.empty(); } -vector<TypeFilterPtr> +vector<shared_ptr<TypeFilter>> RegistryPluginFacadeI::getTypeFilters(const string& id) const { - Lock sync(*this); - map<string, vector<TypeFilterPtr> >::const_iterator p = _typeFilters.find(id); + lock_guard lock(_mutex); + map<string, vector<shared_ptr<TypeFilter>> >::const_iterator p = _typeFilters.find(id); if(p != _typeFilters.end()) { return p->second; } - return vector<TypeFilterPtr>(); + return vector<shared_ptr<TypeFilter>>(); } bool @@ -300,8 +296,8 @@ RegistryPluginFacadeI::hasTypeFilters() const } void -RegistryPluginFacadeI::setDatabase(const DatabasePtr& database) +RegistryPluginFacadeI::setDatabase(const shared_ptr<Database>& database) { - Lock sync(*this); + lock_guard lock(_mutex); _database = database; } diff --git a/cpp/src/IceGrid/PluginFacadeI.h b/cpp/src/IceGrid/PluginFacadeI.h index 3972eee6b11..2f9ee7624a6 100644 --- a/cpp/src/IceGrid/PluginFacadeI.h +++ b/cpp/src/IceGrid/PluginFacadeI.h @@ -5,60 +5,55 @@ #ifndef ICEGRID_PLUGIN_FACADE_I_H #define ICEGRID_PLUGIN_FACADE_I_H -#include <IceUtil/Mutex.h> -#include <IceUtil/Handle.h> - #include <IceGrid/PluginFacade.h> namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; -class RegistryPluginFacadeI : public RegistryPluginFacade, private IceUtil::Mutex +class RegistryPluginFacadeI : public RegistryPluginFacade { public: - RegistryPluginFacadeI(); - - virtual ApplicationInfo getApplicationInfo(const ::std::string&) const; + ApplicationInfo getApplicationInfo(const ::std::string&) const override; - virtual ServerInfo getServerInfo(const std::string&) const; + ServerInfo getServerInfo(const std::string&) const override; - virtual std::string getAdapterServer(const std::string&) const; - virtual std::string getAdapterApplication(const std::string&) const; - virtual std::string getAdapterNode(const std::string&) const; - virtual AdapterInfoSeq getAdapterInfo(const ::std::string&) const; + std::string getAdapterServer(const std::string&) const override; + std::string getAdapterApplication(const std::string&) const override; + std::string getAdapterNode(const std::string&) const override; + AdapterInfoSeq getAdapterInfo(const ::std::string&) const override; - virtual ObjectInfo getObjectInfo(const Ice::Identity&) const; + ObjectInfo getObjectInfo(const Ice::Identity&) const override; - virtual NodeInfo getNodeInfo(const std::string&) const; - virtual LoadInfo getNodeLoad(const std::string&) const; + NodeInfo getNodeInfo(const std::string&) const override; + LoadInfo getNodeLoad(const std::string&) const override; - virtual std::string getPropertyForAdapter(const std::string&, const std::string&) const; + std::string getPropertyForAdapter(const std::string&, const std::string&) const override; - virtual void addReplicaGroupFilter(const std::string&, const ReplicaGroupFilterPtr&) ICE_NOEXCEPT; - virtual bool removeReplicaGroupFilter(const std::string&, const ReplicaGroupFilterPtr&) ICE_NOEXCEPT; + void addReplicaGroupFilter(const std::string&, const std::shared_ptr<ReplicaGroupFilter>&) noexcept override; + bool removeReplicaGroupFilter(const std::string&, const std::shared_ptr<ReplicaGroupFilter>&) noexcept override; - virtual void addTypeFilter(const std::string&, const TypeFilterPtr&) ICE_NOEXCEPT; - virtual bool removeTypeFilter(const std::string&, const TypeFilterPtr&) ICE_NOEXCEPT; + void addTypeFilter(const std::string&, const std::shared_ptr<TypeFilter>&) noexcept override; + bool removeTypeFilter(const std::string&, const std::shared_ptr<TypeFilter>&) noexcept override; - std::vector<ReplicaGroupFilterPtr> getReplicaGroupFilters(const std::string&) const; + std::vector<std::shared_ptr<ReplicaGroupFilter>> getReplicaGroupFilters(const std::string&) const; bool hasReplicaGroupFilters() const; - std::vector<TypeFilterPtr> getTypeFilters(const std::string&) const; + std::vector<std::shared_ptr<TypeFilter>> getTypeFilters(const std::string&) const; bool hasTypeFilters() const; - void setDatabase(const DatabasePtr&); + void setDatabase(const std::shared_ptr<Database>&); private: - DatabasePtr _database; - std::map<std::string, std::vector<ReplicaGroupFilterPtr> > _replicaGroupFilters; - std::map<std::string, std::vector<TypeFilterPtr> > _typeFilters; + std::shared_ptr<Database> _database; + std::map<std::string, std::vector<std::shared_ptr<ReplicaGroupFilter>> > _replicaGroupFilters; + std::map<std::string, std::vector<std::shared_ptr<TypeFilter>> > _typeFilters; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<RegistryPluginFacadeI> RegistryPluginFacadeIPtr; } diff --git a/cpp/src/IceGrid/QueryI.cpp b/cpp/src/IceGrid/QueryI.cpp index e6f5b1ee090..3e47319dff3 100644 --- a/cpp/src/IceGrid/QueryI.cpp +++ b/cpp/src/IceGrid/QueryI.cpp @@ -10,18 +10,14 @@ using namespace std; using namespace Ice; using namespace IceGrid; -QueryI::QueryI(const CommunicatorPtr& communicator, const DatabasePtr& database) : +QueryI::QueryI(const shared_ptr<Communicator>& communicator, const shared_ptr<Database>& database) : _communicator(communicator), _database(database) { } -QueryI::~QueryI() -{ -} - -Ice::ObjectPrx -QueryI::findObjectById(const Ice::Identity& id, const Ice::Current&) const +shared_ptr<Ice::ObjectPrx> +QueryI::findObjectById(Ice::Identity id, const Ice::Current&) const { try { @@ -29,30 +25,30 @@ QueryI::findObjectById(const Ice::Identity& id, const Ice::Current&) const } catch(const ObjectNotRegisteredException&) { - return 0; + return nullptr; } } -Ice::ObjectPrx -QueryI::findObjectByType(const string& type, const Ice::Current& current) const +shared_ptr<Ice::ObjectPrx> +QueryI::findObjectByType(string type, const Ice::Current& current) const { - return _database->getObjectByType(type, current.con, current.ctx); + return _database->getObjectByType(move(type), current.con, current.ctx); } -Ice::ObjectPrx -QueryI::findObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample, const Ice::Current& current) const +shared_ptr<Ice::ObjectPrx> +QueryI::findObjectByTypeOnLeastLoadedNode(string type, LoadSample sample, const Ice::Current& current) const { - return _database->getObjectByTypeOnLeastLoadedNode(type, sample, current.con, current.ctx); + return _database->getObjectByTypeOnLeastLoadedNode(move(type), move(sample), current.con, current.ctx); } Ice::ObjectProxySeq -QueryI::findAllObjectsByType(const string& type, const Ice::Current& current) const +QueryI::findAllObjectsByType(string type, const Ice::Current& current) const { - return _database->getObjectsByType(type, current.con, current.ctx); + return _database->getObjectsByType(move(type), current.con, current.ctx); } Ice::ObjectProxySeq -QueryI::findAllReplicas(const Ice::ObjectPrx& proxy, const Ice::Current& current) const +QueryI::findAllReplicas(shared_ptr<Ice::ObjectPrx> proxy, const Ice::Current& current) const { if(!proxy) { @@ -64,13 +60,12 @@ QueryI::findAllReplicas(const Ice::ObjectPrx& proxy, const Ice::Current& current // well-known object. If it's a well-known object we use the // registered proxy instead. // - Ice::ObjectPrx prx = proxy; - if(prx->ice_getAdapterId().empty()) + if(proxy->ice_getAdapterId().empty()) { try { - ObjectInfo info = _database->getObjectInfo(prx->ice_getIdentity()); - prx = info.proxy; + ObjectInfo info = _database->getObjectInfo(proxy->ice_getIdentity()); + proxy = info.proxy; } catch(const ObjectNotRegisteredException&) { @@ -80,18 +75,18 @@ QueryI::findAllReplicas(const Ice::ObjectPrx& proxy, const Ice::Current& current try { - AdapterInfoSeq infos = _database->getFilteredAdapterInfo(prx->ice_getAdapterId(), current.con, current.ctx); - if(infos.empty() || infos[0].replicaGroupId != prx->ice_getAdapterId()) + AdapterInfoSeq infos = _database->getFilteredAdapterInfo(proxy->ice_getAdapterId(), current.con, current.ctx); + if(infos.empty() || infos[0].replicaGroupId != proxy->ice_getAdapterId()) { // The adapter id doesn't refer to a replica group or the replica group is empty. return Ice::ObjectProxySeq(); } Ice::ObjectProxySeq proxies; - for(AdapterInfoSeq::const_iterator p = infos.begin(); p != infos.end(); ++p) + for(const auto& info : infos) { - assert(!p->id.empty()); - proxies.push_back(prx->ice_adapterId(p->id)); + assert(!info.id.empty()); + proxies.push_back(proxy->ice_adapterId(info.id)); } return proxies; } diff --git a/cpp/src/IceGrid/QueryI.h b/cpp/src/IceGrid/QueryI.h index d9f9dec92c2..9fed187cc11 100644 --- a/cpp/src/IceGrid/QueryI.h +++ b/cpp/src/IceGrid/QueryI.h @@ -12,30 +12,28 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; -class QueryI : public Query, public IceUtil::Mutex +class QueryI final : public Query { public: - QueryI(const Ice::CommunicatorPtr&, const DatabasePtr&); - virtual ~QueryI(); + QueryI(const std::shared_ptr<Ice::Communicator>&, const std::shared_ptr<Database>&); - virtual Ice::ObjectPrx findObjectById(const ::Ice::Identity&, const ::Ice::Current&) const; + std::shared_ptr<Ice::ObjectPrx> findObjectById(Ice::Identity, const Ice::Current&) const override; - virtual Ice::ObjectPrx findObjectByType(const ::std::string&, const ::Ice::Current&) const; + std::shared_ptr<Ice::ObjectPrx> findObjectByType(std::string, const Ice::Current&) const override; - virtual Ice::ObjectPrx findObjectByTypeOnLeastLoadedNode(const ::std::string&, LoadSample, - const ::Ice::Current&) const; + std::shared_ptr<Ice::ObjectPrx> findObjectByTypeOnLeastLoadedNode(std::string, LoadSample, + const Ice::Current&) const override; - virtual Ice::ObjectProxySeq findAllObjectsByType(const ::std::string&, const ::Ice::Current&) const; + Ice::ObjectProxySeq findAllObjectsByType(std::string, const Ice::Current&) const override; - virtual Ice::ObjectProxySeq findAllReplicas(const Ice::ObjectPrx&, const Ice::Current&) const; + Ice::ObjectProxySeq findAllReplicas(std::shared_ptr<Ice::ObjectPrx>, const Ice::Current&) const override; private: - const Ice::CommunicatorPtr _communicator; - const DatabasePtr _database; + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<Database> _database; }; } diff --git a/cpp/src/IceGrid/ReapThread.cpp b/cpp/src/IceGrid/ReapThread.cpp index 54626b1cdbf..649c5092795 100644 --- a/cpp/src/IceGrid/ReapThread.cpp +++ b/cpp/src/IceGrid/ReapThread.cpp @@ -8,54 +8,11 @@ using namespace std; using namespace IceGrid; -namespace -{ - -class CloseCallbackI : public Ice::CloseCallback -{ -public: - - CloseCallbackI(const ReapThreadPtr& reaper) : _reaper(reaper) - { - } - - virtual void - closed(const Ice::ConnectionPtr& con) - { - _reaper->connectionClosed(con); - } - -private: - - const ReapThreadPtr _reaper; -}; - -class HeartbeatCallbackI : public Ice::HeartbeatCallback -{ -public: - - HeartbeatCallbackI(const ReapThreadPtr& reaper) : _reaper(reaper) - { - } - - virtual void - heartbeat(const Ice::ConnectionPtr& con) - { - _reaper->connectionHeartbeat(con); - } - -private: - - const ReapThreadPtr _reaper; -}; - -} - ReapThread::ReapThread() : - IceUtil::Thread("Icegrid reaper thread"), - _closeCallback(new CloseCallbackI(this)), - _heartbeatCallback(new HeartbeatCallbackI(this)), - _terminated(false) + _closeCallback([this](const auto& con) { connectionClosed(con); }), + _heartbeatCallback([this](const auto& con) { connectionHeartbeat(con); }), + _terminated(false), + _thread([this] { run(); }) { } @@ -66,7 +23,7 @@ ReapThread::run() while(true) { { - Lock sync(*this); + unique_lock lock(_mutex); if(_terminated) { break; @@ -77,13 +34,13 @@ ReapThread::run() // // If the wake interval is zero then we wait forever. // - if(_wakeInterval == IceUtil::Time()) + if(_wakeInterval == 0s) { - wait(); + _condVar.wait(lock); } else { - timedWait(_wakeInterval); + _condVar.wait_for(lock, _wakeInterval); } if(_terminated) @@ -91,18 +48,18 @@ ReapThread::run() break; } - list<ReapableItem>::iterator p = _sessions.begin(); + auto p = _sessions.begin(); while(p != _sessions.end()) { try { - if(p->timeout == IceUtil::Time()) + if(p->timeout == 0s) { p->item->timestamp(); // This should throw if the reapable is destroyed. ++p; continue; } - else if((IceUtil::Time::now(IceUtil::Time::Monotonic) - p->item->timestamp()) > p->timeout) + else if((chrono::steady_clock::now() - p->item->timestamp()) > p->timeout) { reap.push_back(*p); } @@ -121,14 +78,14 @@ ReapThread::run() // if(p->connection) { - map<Ice::ConnectionPtr, set<ReapablePtr> >::iterator q = _connections.find(p->connection); + auto q = _connections.find(p->connection); if(q != _connections.end()) { q->second.erase(p->item); if(q->second.empty()) { - p->connection->setCloseCallback(0); - p->connection->setHeartbeatCallback(0); + p->connection->setCloseCallback(nullptr); + p->connection->setHeartbeatCallback(nullptr); _connections.erase(q); } } @@ -137,9 +94,9 @@ ReapThread::run() } } - for(vector<ReapableItem>::const_iterator p = reap.begin(); p != reap.end(); ++p) + for(const auto& r : reap) { - p->item->destroy(false); + r.item->destroy(false); } reap.clear(); } @@ -150,36 +107,43 @@ ReapThread::terminate() { list<ReapableItem> reap; { - Lock sync(*this); + lock_guard lock(_mutex); if(_terminated) { assert(_sessions.empty()); return; } _terminated = true; - notify(); + _condVar.notify_one(); reap.swap(_sessions); - for(map<Ice::ConnectionPtr, set<ReapablePtr> >::iterator p = _connections.begin(); p != _connections.end(); ++p) + for(const auto& conn : _connections) { - p->first->setCloseCallback(0); - p->first->setHeartbeatCallback(0); + conn.first->setCloseCallback(nullptr); + conn.first->setHeartbeatCallback(nullptr); } _connections.clear(); - _closeCallback = 0; - _heartbeatCallback = 0; + _closeCallback = nullptr; + _heartbeatCallback = nullptr; } - for(list<ReapableItem>::iterator p = reap.begin(); p != reap.end(); ++p) + for(const auto& r : reap) { - p->item->destroy(true); + r.item->destroy(true); } } void -ReapThread::add(const ReapablePtr& reapable, int timeout, const Ice::ConnectionPtr& connection) +ReapThread::join() { - Lock sync(*this); + _thread.join(); +} + +void +ReapThread::add(const shared_ptr<Reapable>& reapable, chrono::seconds timeout, + const shared_ptr<Ice::Connection>& connection) +{ + lock_guard lock(_mutex); if(_terminated) { return; @@ -193,31 +157,26 @@ ReapThread::add(const ReapablePtr& reapable, int timeout, const Ice::ConnectionP // // 10 seconds is the minimum permissable timeout. // - if(timeout > 0 && timeout < 10) + if(timeout > 0s && timeout < 10s) { - timeout = 10; + timeout = 10s; } - ReapableItem item; - item.item = reapable; - item.connection = connection; - item.timeout = timeout == 0 ? IceUtil::Time() : IceUtil::Time::seconds(timeout); - _sessions.push_back(item); + _sessions.push_back({ reapable, connection, timeout }); if(connection) { - map<Ice::ConnectionPtr, set<ReapablePtr> >::iterator p = _connections.find(connection); + auto p = _connections.find(connection); if(p == _connections.end()) { - p = _connections.insert(make_pair(connection, set<ReapablePtr>())).first; + p = _connections.insert({connection, {} }).first; connection->setCloseCallback(_closeCallback); connection->setHeartbeatCallback(_heartbeatCallback); - } p->second.insert(reapable); } - if(timeout > 0) + if(timeout > 0s) { // // If there is a new minimum wake interval then wake the reaping @@ -225,50 +184,52 @@ ReapThread::add(const ReapablePtr& reapable, int timeout, const Ice::ConnectionP // if(calcWakeInterval()) { - notify(); + _condVar.notify_one(); } // // Since we just added a new session with a non null timeout there // must be a non-zero wakeInterval. // - assert(_wakeInterval != IceUtil::Time()); + assert(_wakeInterval != 0s); } } void -ReapThread::connectionHeartbeat(const Ice::ConnectionPtr& con) +ReapThread::connectionHeartbeat(const shared_ptr<Ice::Connection>& con) { - Lock sync(*this); - map<Ice::ConnectionPtr, set<ReapablePtr> >::const_iterator p = _connections.find(con); + lock_guard lock(_mutex); + + auto p = _connections.find(con); if(p == _connections.end()) { - con->setCloseCallback(0); - con->setHeartbeatCallback(0); + con->setCloseCallback(nullptr); + con->setHeartbeatCallback(nullptr); return; } - for(set<ReapablePtr>::const_iterator q = p->second.begin(); q != p->second.end(); ++q) + for(const auto& reapable : p->second) { - (*q)->heartbeat(); + reapable->heartbeat(); } } void -ReapThread::connectionClosed(const Ice::ConnectionPtr& con) +ReapThread::connectionClosed(const shared_ptr<Ice::Connection>& con) { - Lock sync(*this); - map<Ice::ConnectionPtr, set<ReapablePtr> >::iterator p = _connections.find(con); + lock_guard lock(_mutex); + + auto p = _connections.find(con); if(p == _connections.end()) { - con->setCloseCallback(0); - con->setHeartbeatCallback(0); + con->setCloseCallback(nullptr); + con->setHeartbeatCallback(nullptr); return; } - for(set<ReapablePtr>::const_iterator q = p->second.begin(); q != p->second.end(); ++q) + for(const auto& reapable : p->second) { - (*q)->destroy(false); + reapable->destroy(false); } _connections.erase(p); } @@ -281,18 +242,18 @@ bool ReapThread::calcWakeInterval() { // Re-calculate minimum timeout - IceUtil::Time oldWakeInterval = _wakeInterval; - IceUtil::Time minimum; + auto oldWakeInterval = _wakeInterval; + chrono::milliseconds minimum = 0s; bool first = true; - for(list<ReapableItem>::const_iterator p = _sessions.begin(); p != _sessions.end(); ++p) + for(const auto& session : _sessions) { - if(p->timeout != IceUtil::Time() && (first || p->timeout < minimum)) + if(session.timeout != 0s && (first || session.timeout < minimum)) { - minimum = p->timeout; + minimum = session.timeout; first = false; } } _wakeInterval = minimum; - return oldWakeInterval == IceUtil::Time() || minimum < oldWakeInterval; + return oldWakeInterval == 0s || minimum < oldWakeInterval; } diff --git a/cpp/src/IceGrid/ReapThread.h b/cpp/src/IceGrid/ReapThread.h index a847b9e720f..99afaa8f56f 100644 --- a/cpp/src/IceGrid/ReapThread.h +++ b/cpp/src/IceGrid/ReapThread.h @@ -5,10 +5,6 @@ #ifndef ICEGRID_REAPER_THREAD_H #define ICEGRID_REAPER_THREAD_H -#include <IceUtil/Thread.h> -#include <IceUtil/Mutex.h> -#include <IceUtil/Monitor.h> - #include <Ice/Logger.h> #include <Ice/LocalException.h> #include <Ice/LoggerUtil.h> @@ -19,44 +15,37 @@ namespace IceGrid { -class Reapable : public Ice::LocalObject +class Reapable { public: - virtual ~Reapable() { } + virtual ~Reapable() = default; virtual void heartbeat() const { }; - virtual IceUtil::Time timestamp() const = 0; + virtual std::chrono::steady_clock::time_point timestamp() const = 0; virtual void destroy(bool) = 0; }; -typedef IceUtil::Handle<Reapable> ReapablePtr; template<class T> class SessionReapable : public Reapable { - typedef IceUtil::Handle<T> TPtr; - public: - SessionReapable(const Ice::LoggerPtr& logger, const TPtr& session) : + SessionReapable(const std::shared_ptr<Ice::Logger>& logger, const std::shared_ptr<T>& session) : _logger(logger), _session(session) { } - virtual ~SessionReapable() - { - } - - virtual IceUtil::Time - timestamp() const + std::chrono::steady_clock::time_point + timestamp() const override { return _session->timestamp(); } - virtual void - destroy(bool shutdown) + void + destroy(bool shutdown) override { try { @@ -81,24 +70,22 @@ public: protected: - const Ice::LoggerPtr _logger; - const TPtr _session; + const std::shared_ptr<Ice::Logger> _logger; + const std::shared_ptr<T> _session; }; template<class T> -class SessionReapableWithHeartbeat : public SessionReapable<T> +class SessionReapableWithHeartbeat final : public SessionReapable<T> { - typedef IceUtil::Handle<T> TPtr; - public: - SessionReapableWithHeartbeat(const Ice::LoggerPtr& logger, const TPtr& session) : + SessionReapableWithHeartbeat(const std::shared_ptr<Ice::Logger>& logger, const std::shared_ptr<T>& session) : SessionReapable<T>(logger, session) { } - virtual void - heartbeat() const + void + heartbeat() const override { try { @@ -110,39 +97,44 @@ public: } }; -class ReapThread : public IceUtil::Thread, public IceUtil::Monitor<IceUtil::Mutex> +class ReapThread final { public: ReapThread(); - virtual void run(); void terminate(); - void add(const ReapablePtr&, int, const Ice::ConnectionPtr& = Ice::ConnectionPtr()); + void join(); + void add(const std::shared_ptr<Reapable>&, std::chrono::seconds, const std::shared_ptr<Ice::Connection>& = nullptr); - void connectionHeartbeat(const Ice::ConnectionPtr&); - void connectionClosed(const Ice::ConnectionPtr&); + void connectionHeartbeat(const std::shared_ptr<Ice::Connection>&); + void connectionClosed(const std::shared_ptr<Ice::Connection>&); private: + void run(); + bool calcWakeInterval(); - Ice::CloseCallbackPtr _closeCallback; - Ice::HeartbeatCallbackPtr _heartbeatCallback; - IceUtil::Time _wakeInterval; + Ice::CloseCallback _closeCallback; + Ice::HeartbeatCallback _heartbeatCallback; + std::chrono::milliseconds _wakeInterval; bool _terminated; struct ReapableItem { - ReapablePtr item; - Ice::ConnectionPtr connection; - IceUtil::Time timeout; + std::shared_ptr<Reapable> item; + std::shared_ptr<Ice::Connection> connection; + std::chrono::milliseconds timeout; }; std::list<ReapableItem> _sessions; - std::map<Ice::ConnectionPtr, std::set<ReapablePtr> > _connections; -}; -typedef IceUtil::Handle<ReapThread> ReapThreadPtr; + std::map<std::shared_ptr<Ice::Connection>, std::set<std::shared_ptr<Reapable>> > _connections; + std::mutex _mutex; + std::condition_variable _condVar; + std::thread _thread; }; +} + #endif diff --git a/cpp/src/IceGrid/RegistryAdminRouter.cpp b/cpp/src/IceGrid/RegistryAdminRouter.cpp index cb88ed843e8..71184b0cbb9 100644 --- a/cpp/src/IceGrid/RegistryAdminRouter.cpp +++ b/cpp/src/IceGrid/RegistryAdminRouter.cpp @@ -3,6 +3,7 @@ // #include <IceGrid/RegistryAdminRouter.h> +#include <IceGrid/Internal.h> #include <Ice/Ice.h> using namespace IceGrid; @@ -12,15 +13,20 @@ using namespace std; namespace { -class SynchronizationCallbackI : public SynchronizationCallback +class SynchronizationCallbackI final : public SynchronizationCallback { public: - SynchronizationCallbackI(const IceUtil::Handle<RegistryServerAdminRouter>& adminRouter, - const AMD_Object_ice_invokePtr& cb, + SynchronizationCallbackI(const shared_ptr<RegistryServerAdminRouter>& adminRouter, const pair<const Byte*, const Byte*>& inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, const Current& current) : - _adminRouter(adminRouter), _callback(cb), _inParams(inParams.first, inParams.second), _current(current) + _adminRouter(adminRouter), + _response(move(response)), + _exception(move(exception)), + _inParams(inParams.first, inParams.second), + _current(current) { } @@ -29,47 +35,51 @@ public: // // Retry to forward the call. // - _adminRouter->ice_invoke_async(_callback, make_pair(&_inParams[0], &_inParams[0] + _inParams.size()), _current); + _adminRouter->ice_invokeAsync({ &_inParams[0], &_inParams[0] + _inParams.size() }, + move(_response), move(_exception), _current); } - void synchronized(const Ice::Exception&) + void synchronized(exception_ptr) { - _callback->ice_exception(Ice::ObjectNotExistException(__FILE__, __LINE__)); + _exception(make_exception_ptr(Ice::ObjectNotExistException(__FILE__, __LINE__))); } private: - const IceUtil::Handle<RegistryServerAdminRouter> _adminRouter; - const AMD_Object_ice_invokePtr _callback; + const shared_ptr<RegistryServerAdminRouter> _adminRouter; + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> _response; + function<void(exception_ptr)> _exception; const vector<Byte> _inParams; const Current _current; }; } -IceGrid::RegistryServerAdminRouter::RegistryServerAdminRouter(const DatabasePtr& database) : +RegistryServerAdminRouter::RegistryServerAdminRouter(const shared_ptr<Database>& database) : AdminRouter(database->getTraceLevels()), _database(database) { } void -IceGrid::RegistryServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair<const Ice::Byte*, const Ice::Byte*>& inParams, - const Current& current) +RegistryServerAdminRouter::ice_invokeAsync(pair<const Ice::Byte*, const Ice::Byte*> inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) { - ObjectPrx target = 0; + shared_ptr<ObjectPrx> target; try { - ServerEntryPtr server = _database->getServer(current.id.name); + auto server = _database->getServer(current.id.name); try { target = server->getAdminProxy(); } catch(const SynchronizationException&) { - server->addSyncCallback(new SynchronizationCallbackI(this, cb, inParams, current)); + server->addSyncCallback(make_shared<SynchronizationCallbackI>(shared_from_this(), inParams, + move(response), move(exception), current)); return; // Wait for the server synchronization to complete and retry. } } @@ -83,17 +93,17 @@ IceGrid::RegistryServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invoke { } - if(target == 0) + if(target == nullptr) { throw ObjectNotExistException(__FILE__, __LINE__); } target = target->ice_facet(current.facet); - invokeOnTarget(target, cb, inParams, current); + invokeOnTarget(target, inParams, move(response), move(exception), current); } -IceGrid::RegistryNodeAdminRouter::RegistryNodeAdminRouter(const string& collocNodeName, const DatabasePtr& database) : +RegistryNodeAdminRouter::RegistryNodeAdminRouter(const string& collocNodeName, const shared_ptr<Database>& database) : AdminRouter(database->getTraceLevels()), _collocNodeName(collocNodeName), _database(database) @@ -101,11 +111,12 @@ IceGrid::RegistryNodeAdminRouter::RegistryNodeAdminRouter(const string& collocNo } void -IceGrid::RegistryNodeAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair<const Ice::Byte*, const Ice::Byte*>& inParams, - const Current& current) +RegistryNodeAdminRouter::ice_invokeAsync(pair<const Ice::Byte*, const Ice::Byte*> inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) { - ObjectPrx target; + shared_ptr<ObjectPrx> target; if(!_collocNodeName.empty() && current.id.name == _collocNodeName) { @@ -139,11 +150,11 @@ IceGrid::RegistryNodeAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePt target = target->ice_facet(current.facet); - invokeOnTarget(target, cb, inParams, current); + invokeOnTarget(target, inParams, move(response), move(exception), current); } -IceGrid::RegistryReplicaAdminRouter::RegistryReplicaAdminRouter(const string& name, - const DatabasePtr& database) : +RegistryReplicaAdminRouter::RegistryReplicaAdminRouter(const string& name, + const shared_ptr<Database>& database) : AdminRouter(database->getTraceLevels()), _name(name), _database(database) @@ -151,11 +162,12 @@ IceGrid::RegistryReplicaAdminRouter::RegistryReplicaAdminRouter(const string& na } void -IceGrid::RegistryReplicaAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair<const Ice::Byte*, const Ice::Byte*>& inParams, - const Current& current) +RegistryReplicaAdminRouter::ice_invokeAsync(pair<const Ice::Byte*, const Ice::Byte*> inParams, + function<void(bool, const pair<const Ice::Byte*, const Ice::Byte*>&)> response, + function<void(exception_ptr)> exception, + const Ice::Current& current) { - ObjectPrx target; + shared_ptr<ObjectPrx> target; if(current.id.name == _name) { @@ -174,7 +186,7 @@ IceGrid::RegistryReplicaAdminRouter::ice_invoke_async(const AMD_Object_ice_invok } } - if(target == 0) + if(target == nullptr) { if(_traceLevels->admin > 0) { @@ -187,5 +199,5 @@ IceGrid::RegistryReplicaAdminRouter::ice_invoke_async(const AMD_Object_ice_invok target = target->ice_facet(current.facet); - invokeOnTarget(target, cb, inParams, current); + invokeOnTarget(target, inParams, move(response), move(exception), current); } diff --git a/cpp/src/IceGrid/RegistryAdminRouter.h b/cpp/src/IceGrid/RegistryAdminRouter.h index 8deb750fd86..3e214c21cee 100644 --- a/cpp/src/IceGrid/RegistryAdminRouter.h +++ b/cpp/src/IceGrid/RegistryAdminRouter.h @@ -11,51 +11,55 @@ namespace IceGrid { -class RegistryServerAdminRouter : public AdminRouter +class RegistryServerAdminRouter final : public AdminRouter, + public std::enable_shared_from_this<RegistryServerAdminRouter> { public: - RegistryServerAdminRouter(const DatabasePtr&); + RegistryServerAdminRouter(const std::shared_ptr<Database>&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair<const Ice::Byte*, const Ice::Byte*>&, - const Ice::Current&); + void ice_invokeAsync(std::pair<const Ice::Byte*, const Ice::Byte*>, + std::function<void(bool, const std::pair<const Ice::Byte*, const Ice::Byte*>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current& current) override; private: - const DatabasePtr _database; + const std::shared_ptr<Database> _database; }; -class RegistryNodeAdminRouter : public AdminRouter +class RegistryNodeAdminRouter final : public AdminRouter { public: - RegistryNodeAdminRouter(const std::string&, const DatabasePtr&); + RegistryNodeAdminRouter(const std::string&, const std::shared_ptr<Database>&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair<const Ice::Byte*, const Ice::Byte*>&, - const Ice::Current&); + void ice_invokeAsync(std::pair<const Ice::Byte*, const Ice::Byte*>, + std::function<void(bool, const std::pair<const Ice::Byte*, const Ice::Byte*>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current& current) override; private: const std::string _collocNodeName; - const DatabasePtr _database; + const std::shared_ptr<Database> _database; }; -class RegistryReplicaAdminRouter : public AdminRouter +class RegistryReplicaAdminRouter final : public AdminRouter { public: - RegistryReplicaAdminRouter(const std::string&, const DatabasePtr&); + RegistryReplicaAdminRouter(const std::string&, const std::shared_ptr<Database>&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair<const Ice::Byte*, const Ice::Byte*>&, - const Ice::Current&); + void ice_invokeAsync(std::pair<const Ice::Byte*, const Ice::Byte*>, + std::function<void(bool, const std::pair<const Ice::Byte*, const Ice::Byte*>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current& current) override; private: const std::string _name; - const DatabasePtr _database; + const std::shared_ptr<Database> _database; }; } diff --git a/cpp/src/IceGrid/RegistryI.cpp b/cpp/src/IceGrid/RegistryI.cpp index 092ac2bf322..df387dbd09a 100644 --- a/cpp/src/IceGrid/RegistryI.cpp +++ b/cpp/src/IceGrid/RegistryI.cpp @@ -44,19 +44,20 @@ using namespace IceGrid; namespace { -class LookupI : public IceLocatorDiscovery::Lookup +class LookupI final : public IceLocatorDiscovery::Lookup { public: - LookupI(const std::string& instanceName, - const WellKnownObjectsManagerPtr& wellKnownObjects, - const TraceLevelsPtr& traceLevels) : + LookupI(const string& instanceName, + const shared_ptr<WellKnownObjectsManager>& wellKnownObjects, + const shared_ptr<TraceLevels>& traceLevels) : _instanceName(instanceName), _wellKnownObjects(wellKnownObjects), _traceLevels(traceLevels) { } - virtual void - findLocator(const string& instanceName, const IceLocatorDiscovery::LookupReplyPrx& reply, const Ice::Current&) + void + findLocator(string instanceName, shared_ptr<IceLocatorDiscovery::LookupReplyPrx> reply, + const Ice::Current&) override { if(!instanceName.empty() && instanceName != _instanceName) { @@ -75,11 +76,11 @@ public: Trace out(_traceLevels->logger, _traceLevels->discoveryCat); out << "replying to discovery lookup:\nreply = " << reply; } - reply->begin_foundLocator(_wellKnownObjects->getLocator()); + reply->foundLocatorAsync(_wellKnownObjects->getLocator()); } } - virtual Ice::LocatorPrx + shared_ptr<Ice::LocatorPrx> getLocator(const Ice::Current&) { return _wellKnownObjects->getLocator(); @@ -88,59 +89,59 @@ public: private: const string _instanceName; - const WellKnownObjectsManagerPtr _wellKnownObjects; - const TraceLevelsPtr _traceLevels; + const shared_ptr<WellKnownObjectsManager> _wellKnownObjects; + const shared_ptr<TraceLevels> _traceLevels; }; -class FinderI : public Ice::LocatorFinder +class FinderI final : public Ice::LocatorFinder { public: - FinderI(const WellKnownObjectsManagerPtr& wellKnownObjects) : _wellKnownObjects(wellKnownObjects) + FinderI(const shared_ptr<WellKnownObjectsManager>& wellKnownObjects) : _wellKnownObjects(wellKnownObjects) { } - virtual Ice::LocatorPrx - getLocator(const Ice::Current&) + shared_ptr<Ice::LocatorPrx> + getLocator(const Ice::Current&) override { return _wellKnownObjects->getLocator(); } private: - const WellKnownObjectsManagerPtr _wellKnownObjects; + const shared_ptr<WellKnownObjectsManager> _wellKnownObjects; }; -class ProcessI : public Process +class ProcessI final : public Process { public: - ProcessI(const RegistryIPtr&, const ProcessPtr&); + ProcessI(const shared_ptr<RegistryI>&, const shared_ptr<Process>&); - virtual void shutdown(const Current&); - virtual void writeMessage(const std::string&, Int, const Current&); + void shutdown(const Current&) override; + void writeMessage(string, int, const Current&) override; private: - RegistryIPtr _registry; - ProcessPtr _origProcess; + shared_ptr<RegistryI> _registry; + shared_ptr<Process> _origProcess; }; -Ice::IPConnectionInfoPtr -getIPConnectionInfo(const Ice::ConnectionInfoPtr& info) +shared_ptr<IPConnectionInfo> +getIPConnectionInfo(const shared_ptr<ConnectionInfo>& info) { - for(Ice::ConnectionInfoPtr p = info; p; p = p->underlying) + for(auto p = info; p; p = p->underlying) { - Ice::IPConnectionInfoPtr ipInfo = Ice::IPConnectionInfoPtr::dynamicCast(p); + auto ipInfo = dynamic_pointer_cast<IPConnectionInfo>(p); if(ipInfo) { return ipInfo; } } - return ICE_NULLPTR; + return nullptr; } -ProcessI::ProcessI(const RegistryIPtr& registry, const ProcessPtr& origProcess) : +ProcessI::ProcessI(const shared_ptr<RegistryI>& registry, const shared_ptr<Process>& origProcess) : _registry(registry), _origProcess(origProcess) { @@ -153,15 +154,15 @@ ProcessI::shutdown(const Current&) } void -ProcessI::writeMessage(const string& message, Int fd, const Current& current) +ProcessI::writeMessage(string message, int fd, const Current& current) { - _origProcess->writeMessage(message, fd, current); + _origProcess->writeMessage(move(message), move(fd), current); } } -RegistryI::RegistryI(const CommunicatorPtr& communicator, - const TraceLevelsPtr& traceLevels, +RegistryI::RegistryI(const shared_ptr<Communicator>& communicator, + const shared_ptr<TraceLevels>& traceLevels, bool nowarn, bool readonly, const string& initFromReplica, @@ -176,10 +177,6 @@ RegistryI::RegistryI(const CommunicatorPtr& communicator, { } -RegistryI::~RegistryI() -{ -} - bool RegistryI::start() { @@ -203,7 +200,7 @@ bool RegistryI::startImpl() { assert(_communicator); - PropertiesPtr properties = _communicator->getProperties(); + auto properties = _communicator->getProperties(); // // Check that required properties are set and valid. @@ -275,7 +272,7 @@ RegistryI::startImpl() _replicaName = properties->getPropertyWithDefault("IceGrid.Registry.ReplicaName", "Master"); _master = _replicaName == "Master"; - _sessionTimeout = properties->getPropertyAsIntWithDefault("IceGrid.Registry.SessionTimeout", 30); + _sessionTimeout = chrono::seconds(properties->getPropertyAsIntWithDefault("IceGrid.Registry.SessionTimeout", 30)); if(!_initFromReplica.empty() && (_initFromReplica == _replicaName || (_master && _initFromReplica == "Master"))) { @@ -284,11 +281,9 @@ RegistryI::startImpl() return false; } - if(_sessionTimeout > 0 && properties->getProperty("IceGrid.Registry.Client.ACM.Timeout").empty()) + if(_sessionTimeout > 0s && properties->getProperty("IceGrid.Registry.Client.ACM.Timeout").empty()) { - ostringstream os; - os << _sessionTimeout; - properties->setProperty("IceGrid.Registry.Client.ACM.Timeout", os.str()); + properties->setProperty("IceGrid.Registry.Client.ACM.Timeout", to_string(secondsToInt(_sessionTimeout))); } if(properties->getProperty("IceGrid.Registry.Server.ACM.Timeout").empty()) @@ -300,9 +295,7 @@ RegistryI::startImpl() { int nt = properties->getPropertyAsIntWithDefault("IceGrid.Registry.NodeSessionTimeout", 30); int rt = properties->getPropertyAsIntWithDefault("IceGrid.Registry.ReplicaSessionTimeout", 30); - ostringstream os; - os << std::max(nt, rt); - properties->setProperty("IceGrid.Registry.Internal.ACM.Timeout", os.str()); + properties->setProperty("IceGrid.Registry.Internal.ACM.Timeout", to_string(max(nt, rt))); } properties->setProperty("Ice.ACM.Server.Close", "3"); // Close on invocation and idle. @@ -315,7 +308,7 @@ RegistryI::startImpl() } else if(_master) { - _communicator->setDefaultLocator(0); // Clear the default locator in case it's set. + _communicator->setDefaultLocator(nullptr); // Clear the default locator in case it's set. } // @@ -338,7 +331,7 @@ RegistryI::startImpl() // // Create the replica session manager // - _session.reset(new ReplicaSessionManager(_communicator, _instanceName)); + _session = make_unique<ReplicaSessionManager>(_communicator, _instanceName); // // Create the registry database. @@ -384,8 +377,7 @@ RegistryI::startImpl() // // Create the reaper thread. // - _reaper = new ReapThread(); - _reaper->start(); + _reaper = make_shared<ReapThread>(); // // Create the internal registry object adapter. @@ -405,11 +397,11 @@ RegistryI::startImpl() "IceGrid.Registry", registryTopicManagerId, ""); - const IceStorm::TopicManagerPrx topicManager = _iceStorm->getTopicManager(); + const auto topicManager = _iceStorm->getTopicManager(); try { - _database = new Database(_registryAdapter, topicManager, _instanceName, _traceLevels, getInfo(), _readonly); + _database = Database::create(_registryAdapter, topicManager, _instanceName, _traceLevels, getInfo(), _readonly); } catch(const IceDB::LMDBException& ex) { @@ -418,19 +410,20 @@ RegistryI::startImpl() out << ex; return false; } - _wellKnownObjects = new WellKnownObjectsManager(_database); + _wellKnownObjects = make_shared<WellKnownObjectsManager>(_database); if(!_initFromReplica.empty()) { - Ice::Identity id; + Identity id; id.category = _instanceName; id.name = (_initFromReplica == "Master") ? "Registry" : "Registry-" + _initFromReplica; - Ice::ObjectPrx proxy; + + shared_ptr<ObjectPrx> proxy; try { proxy = _database->getObjectProxy(id); id.name = "Query"; - IceGrid::QueryPrx query = IceGrid::QueryPrx::uncheckedCast(proxy->ice_identity(id)); + auto query = uncheckedCast<IceGrid::QueryPrx>(proxy->ice_identity(id)); if(query) { id.name = "InternalRegistry-" + _initFromReplica; @@ -475,8 +468,8 @@ RegistryI::startImpl() try { - Ice::Long serial; - IceGrid::InternalRegistryPrx registry = IceGrid::InternalRegistryPrx::checkedCast(proxy); + long long serial; + auto registry = checkedCast<IceGrid::InternalRegistryPrx>(proxy); ApplicationInfoSeq applications = registry->getApplications(serial); _database->syncApplications(applications, serial); AdapterInfoSeq adapters = registry->getAdapters(serial); @@ -506,9 +499,9 @@ RegistryI::startImpl() // NodePrxSeq nodes; ObjectProxySeq proxies = _database->getInternalObjectsByType(Node::ice_staticId()); - for(ObjectProxySeq::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + for(const auto& proxy : proxies) { - nodes.push_back(NodePrx::uncheckedCast(*p)); + nodes.push_back(uncheckedCast<NodePrx>(proxy)); } // @@ -517,7 +510,7 @@ RegistryI::startImpl() // replica/node register as soon as the internal registry is setup // we might clear valid proxies. // - InternalRegistryPrx internalRegistry = setupInternalRegistry(); + auto internalRegistry = setupInternalRegistry(); if(_master) { nodes = registerReplicas(internalRegistry, nodes); @@ -525,7 +518,7 @@ RegistryI::startImpl() } else { - InternalReplicaInfoPtr info = _platform.getInternalReplicaInfo(); + auto info = _platform.getInternalReplicaInfo(); _session->create(_replicaName, info, _database, _wellKnownObjects, internalRegistry); registerNodes(internalRegistry, _session->getNodes(nodes)); } @@ -533,8 +526,7 @@ RegistryI::startImpl() _serverAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Server"); _clientAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Client"); - Ice::Identity dummy; - dummy.name = "dummy"; + Ice::Identity dummy = { "dummy", "" }; _wellKnownObjects->addEndpoint("Client", _clientAdapter->createDirectProxy(dummy)); _wellKnownObjects->addEndpoint("Server", _serverAdapter->createDirectProxy(dummy)); _wellKnownObjects->addEndpoint("Internal", _registryAdapter->createDirectProxy(dummy)); @@ -544,11 +536,11 @@ RegistryI::startImpl() return false; } - QueryPrx query = setupQuery(); - RegistryPrx registry = setupRegistry(); + auto query = setupQuery(); + auto registry = setupRegistry(); setupLocatorRegistry(); - LocatorPrx internalLocator = setupLocator(registry, query); + auto internalLocator = setupLocator(registry, query); // // Create the session servant manager. The session servant manager is responsible @@ -556,16 +548,16 @@ RegistryI::startImpl() // accessed by the connection that created the session. The session servant manager // also takes care of providing router servants for admin objects. // - ObjectPtr serverAdminRouter = new RegistryServerAdminRouter(_database); - ObjectPtr nodeAdminRouter = new RegistryNodeAdminRouter(_collocatedNodeName, _database); - ObjectPtr replicaAdminRouter = new RegistryReplicaAdminRouter(_replicaName, _database); - AdminCallbackRouterPtr adminCallbackRouter = new AdminCallbackRouter; + auto serverAdminRouter = make_shared<RegistryServerAdminRouter>(_database); + auto nodeAdminRouter = make_shared<RegistryNodeAdminRouter>(_collocatedNodeName, _database); + auto replicaAdminRouter = make_shared<RegistryReplicaAdminRouter>(_replicaName, _database); + auto adminCallbackRouter = make_shared<AdminCallbackRouter>(); - _servantManager = new SessionServantManager(_clientAdapter, _instanceName, true, - getServerAdminCategory(), serverAdminRouter, - getNodeAdminCategory(), nodeAdminRouter, - getReplicaAdminCategory(), replicaAdminRouter, - adminCallbackRouter); + _servantManager = make_shared<SessionServantManager>(_clientAdapter, _instanceName, true, + getServerAdminCategory(), serverAdminRouter, + getNodeAdminCategory(), nodeAdminRouter, + getReplicaAdminCategory(), replicaAdminRouter, + adminCallbackRouter); _clientAdapter->addServantLocator(_servantManager, ""); _serverAdapter->addDefaultServant(adminCallbackRouter, ""); @@ -578,9 +570,9 @@ RegistryI::startImpl() Glacier2Internal::setupNullPermissionsVerifier(_communicator, _instanceName, verifierProperties); - ObjectAdapterPtr sessionAdpt = setupClientSessionFactory(internalLocator); - ObjectAdapterPtr admSessionAdpt = setupAdminSessionFactory(serverAdminRouter, nodeAdminRouter, replicaAdminRouter, - internalLocator); + auto sessionAdpt = setupClientSessionFactory(internalLocator); + auto admSessionAdpt = setupAdminSessionFactory(serverAdminRouter, nodeAdminRouter, replicaAdminRouter, + internalLocator); _wellKnownObjects->finish(); if(_master) @@ -595,13 +587,13 @@ RegistryI::startImpl() // // Add the locator finder object to the client adapter. // - _clientAdapter->add(new FinderI(_wellKnownObjects), stringToIdentity("Ice/LocatorFinder")); + _clientAdapter->add(make_shared<FinderI>(_wellKnownObjects), stringToIdentity("Ice/LocatorFinder")); // // Setup the discovery object adapter and also add it the lookup // servant to receive multicast lookup queries. // - Ice::ObjectAdapterPtr discoveryAdapter; + shared_ptr<ObjectAdapter> discoveryAdapter; if(properties->getPropertyAsIntWithDefault("IceGrid.Registry.Discovery.Enabled", 1) > 0) { bool ipv4 = properties->getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0; @@ -630,9 +622,9 @@ RegistryI::startImpl() try { - Ice::Identity lookupId = stringToIdentity("IceLocatorDiscovery/Lookup"); + auto lookupId = stringToIdentity("IceLocatorDiscovery/Lookup"); discoveryAdapter = _communicator->createObjectAdapter("IceGrid.Registry.Discovery"); - discoveryAdapter->add(new LookupI(_instanceName, _wellKnownObjects, _traceLevels), lookupId); + discoveryAdapter->add(make_shared<LookupI>(_instanceName, _wellKnownObjects, _traceLevels), lookupId); } catch(const Ice::LocalException& ex) { @@ -672,16 +664,14 @@ void RegistryI::setupLocatorRegistry() { const bool dynReg = _communicator->getProperties()->getPropertyAsInt("IceGrid.Registry.DynamicRegistration") > 0; - Identity locatorRegId; - locatorRegId.category = _instanceName; - locatorRegId.name = "LocatorRegistry"; - _serverAdapter->add(new LocatorRegistryI(_database, dynReg, _master, *_session), locatorRegId); + Identity locatorRegId = { "LocatorRegistry", _instanceName }; + _serverAdapter->add(make_shared<LocatorRegistryI>(_database, dynReg, _master, *_session), locatorRegId); } -IceGrid::LocatorPrx -RegistryI::setupLocator(const RegistryPrx& registry, const QueryPrx& query) +shared_ptr<IceGrid::LocatorPrx> +RegistryI::setupLocator(const shared_ptr<RegistryPrx>& registry, const shared_ptr<QueryPrx>& query) { - LocatorPtr locator = new LocatorI(_communicator, _database, _wellKnownObjects, registry, query); + auto locator = make_shared<LocatorI>(_communicator, _database, _wellKnownObjects, registry, query); Identity locatorId; locatorId.category = _instanceName; @@ -691,42 +681,41 @@ RegistryI::setupLocator(const RegistryPrx& registry, const QueryPrx& query) locatorId.name = "Locator-" + _replicaName; _clientAdapter->add(locator, locatorId); - return LocatorPrx::uncheckedCast(_registryAdapter->addWithUUID(locator)); + return uncheckedCast<LocatorPrx>(_registryAdapter->addWithUUID(locator)); } -QueryPrx +shared_ptr<QueryPrx> RegistryI::setupQuery() { - Identity queryId; - queryId.category = _instanceName; - queryId.name = "Query"; - return QueryPrx::uncheckedCast(_clientAdapter->add(new QueryI(_communicator, _database), queryId)); + Identity queryId = { "Query", _instanceName }; + return uncheckedCast<QueryPrx>(_clientAdapter->add(make_shared<QueryI>(_communicator, _database), move(queryId))); } -RegistryPrx +shared_ptr<RegistryPrx> RegistryI::setupRegistry() { - Identity registryId; - registryId.category = _instanceName; - registryId.name = "Registry"; + Identity registryId = { "Registry", _instanceName }; if(!_master) { registryId.name += "-" + _replicaName; } - RegistryPrx proxy = RegistryPrx::uncheckedCast(_clientAdapter->add(this, registryId)); + + auto proxy = uncheckedCast<RegistryPrx>(_clientAdapter->add(shared_from_this(), move(registryId))); _wellKnownObjects->add(proxy, Registry::ice_staticId()); return proxy; } -InternalRegistryPrx +shared_ptr<InternalRegistryPrx> RegistryI::setupInternalRegistry() { - Identity internalRegistryId; - internalRegistryId.category = _instanceName; - internalRegistryId.name = "InternalRegistry-" + _replicaName; assert(_reaper); - ObjectPtr internalRegistry = new InternalRegistryI(this, _database, _reaper, _wellKnownObjects, *_session); - Ice::ObjectPrx proxy = _registryAdapter->add(internalRegistry, internalRegistryId); + + Identity internalRegistryId = { "InternalRegistry-" + _replicaName, _instanceName }; + + auto internalRegistry = make_shared<InternalRegistryI>(shared_from_this(), _database, _reaper, _wellKnownObjects, + *_session); + auto proxy = _registryAdapter->add(internalRegistry, internalRegistryId); + _wellKnownObjects->add(proxy, InternalRegistry::ice_staticId()); // @@ -735,16 +724,14 @@ RegistryI::setupInternalRegistry() if(_communicator->getProperties()->getPropertyAsInt("Ice.Admin.Enabled") > 0) { // Replace Admin facet - ProcessPtr origProcess = ProcessPtr::dynamicCast(_communicator->removeAdminFacet("Process")); - _communicator->addAdminFacet(new ProcessI(this, origProcess), "Process"); + auto origProcess = dynamic_pointer_cast<Process>(_communicator->removeAdminFacet("Process")); + _communicator->addAdminFacet(make_shared<ProcessI>(shared_from_this(), origProcess), "Process"); - Identity adminId; - adminId.name = "RegistryAdmin-" + _replicaName; - adminId.category = _instanceName; - _communicator->createAdmin(_registryAdapter, adminId); + Identity adminId = { "RegistryAdmin-" + _replicaName, _instanceName }; + _communicator->createAdmin(_registryAdapter, move(adminId)); } - InternalRegistryPrx registry = InternalRegistryPrx::uncheckedCast(proxy); + auto registry = uncheckedCast<InternalRegistryPrx>(proxy); _database->getReplicaCache().setInternalRegistry(registry); return registry; } @@ -752,7 +739,7 @@ RegistryI::setupInternalRegistry() bool RegistryI::setupUserAccountMapper() { - Ice::PropertiesPtr properties = _communicator->getProperties(); + auto properties = _communicator->getProperties(); // // Setup file user account mapper object if the property is set. @@ -762,17 +749,16 @@ RegistryI::setupUserAccountMapper() { try { - Identity mapperId; - mapperId.category = _instanceName; - mapperId.name = "RegistryUserAccountMapper"; + Identity mapperId = { "RegistryUserAccountMapper", _instanceName }; if(!_master) { mapperId.name += "-" + _replicaName; } - _registryAdapter->add(new FileUserAccountMapperI(userAccountFileProperty), mapperId); + + _registryAdapter->add(make_shared<FileUserAccountMapperI>(userAccountFileProperty), mapperId); _wellKnownObjects->add(_registryAdapter->createProxy(mapperId), UserAccountMapper::ice_staticId()); } - catch(const std::string& msg) + catch(const string& msg) { Error out(_communicator->getLogger()); out << msg; @@ -782,35 +768,32 @@ RegistryI::setupUserAccountMapper() return true; } -Ice::ObjectAdapterPtr -RegistryI::setupClientSessionFactory(const IceGrid::LocatorPrx& locator) +shared_ptr<ObjectAdapter> +RegistryI::setupClientSessionFactory(const shared_ptr<IceGrid::LocatorPrx>& locator) { - Ice::PropertiesPtr properties = _communicator->getProperties(); + auto properties = _communicator->getProperties(); - Ice::ObjectAdapterPtr adapter; - SessionServantManagerPtr servantManager; + shared_ptr<ObjectAdapter> adapter; + shared_ptr<SessionServantManager> servantManager; if(!properties->getProperty("IceGrid.Registry.SessionManager.Endpoints").empty()) { adapter = _communicator->createObjectAdapter("IceGrid.Registry.SessionManager"); - servantManager = new SessionServantManager(adapter, _instanceName, false, "", 0, "", 0, "", 0, 0); + servantManager = make_shared<SessionServantManager>(adapter, _instanceName, false, + "", nullptr, "", nullptr, "", nullptr, nullptr); adapter->addServantLocator(servantManager, ""); } assert(_reaper); - _timer = new IceUtil::Timer(); // Used for session allocation timeout. - _clientSessionFactory = new ClientSessionFactory(servantManager, _database, _timer, _reaper); + _timer = new IceUtil::Timer; // Used for session allocation timeout. + _clientSessionFactory = make_shared<ClientSessionFactory>(servantManager, _database, _timer, _reaper); if(servantManager && _master) // Slaves don't support client session manager objects. { - Identity sessionMgrId; - sessionMgrId.category = _instanceName; - sessionMgrId.name = "SessionManager"; - Identity sslSessionMgrId; - sslSessionMgrId.category = _instanceName; - sslSessionMgrId.name = "SSLSessionManager"; + Identity sessionMgrId = { "SessionManager", _instanceName }; + Identity sslSessionMgrId = { "SSLSessionManager", _instanceName }; - adapter->add(new ClientSessionManagerI(_clientSessionFactory), sessionMgrId); - adapter->add(new ClientSSLSessionManagerI(_clientSessionFactory), sslSessionMgrId); + adapter->add(make_shared<ClientSessionManagerI>(_clientSessionFactory), sessionMgrId); + adapter->add(make_shared<ClientSSLSessionManagerI>(_clientSessionFactory), sslSessionMgrId); _wellKnownObjects->add(adapter->createProxy(sessionMgrId), Glacier2::SessionManager::ice_staticId()); _wellKnownObjects->add(adapter->createProxy(sslSessionMgrId), Glacier2::SSLSessionManager::ice_staticId()); @@ -818,9 +801,8 @@ RegistryI::setupClientSessionFactory(const IceGrid::LocatorPrx& locator) if(adapter) { - Ice::Identity dummy; - dummy.name = "dummy"; - _wellKnownObjects->addEndpoint("SessionManager", adapter->createDirectProxy(dummy)); + Ice::Identity dummy = { "dummy", "" }; + _wellKnownObjects->addEndpoint("SessionManager", adapter->createDirectProxy(move(dummy))); } _clientVerifier = getPermissionsVerifier(locator, "IceGrid.Registry.PermissionsVerifier"); @@ -829,43 +811,41 @@ RegistryI::setupClientSessionFactory(const IceGrid::LocatorPrx& locator) return adapter; } -Ice::ObjectAdapterPtr -RegistryI::setupAdminSessionFactory(const Ice::ObjectPtr& serverAdminRouter, const Ice::ObjectPtr& nodeAdminRouter, - const Ice::ObjectPtr& replicaAdminRouter, const IceGrid::LocatorPrx& locator) +shared_ptr<ObjectAdapter> +RegistryI::setupAdminSessionFactory(const shared_ptr<Object>& serverAdminRouter, + const shared_ptr<Object>& nodeAdminRouter, + const shared_ptr<Object>& replicaAdminRouter, + const shared_ptr<IceGrid::LocatorPrx>& locator) { - Ice::PropertiesPtr properties = _communicator->getProperties(); + auto properties = _communicator->getProperties(); - Ice::ObjectAdapterPtr adapter; - SessionServantManagerPtr servantManager; + shared_ptr<ObjectAdapter> adapter; + shared_ptr<SessionServantManager> servantManager; if(!properties->getProperty("IceGrid.Registry.AdminSessionManager.Endpoints").empty()) { adapter = _communicator->createObjectAdapter("IceGrid.Registry.AdminSessionManager"); - servantManager = new SessionServantManager(adapter, _instanceName, false, + servantManager = make_shared<SessionServantManager>(adapter, _instanceName, false, getServerAdminCategory(), serverAdminRouter, getNodeAdminCategory(), nodeAdminRouter, - getReplicaAdminCategory(), replicaAdminRouter, 0); + getReplicaAdminCategory(), replicaAdminRouter, nullptr); adapter->addServantLocator(servantManager, ""); } assert(_reaper); - _adminSessionFactory = new AdminSessionFactory(servantManager, _database, _reaper, this); + _adminSessionFactory = make_shared<AdminSessionFactory>(servantManager, _database, _reaper, shared_from_this()); if(servantManager) { - Identity sessionMgrId; - sessionMgrId.category = _instanceName; - sessionMgrId.name = "AdminSessionManager"; - Identity sslSessionMgrId; - sslSessionMgrId.category = _instanceName; - sslSessionMgrId.name = "AdminSSLSessionManager"; + Identity sessionMgrId = { "AdminSessionManager", _instanceName }; + Identity sslSessionMgrId = { "AdminSSLSessionManager", _instanceName }; if(!_master) { sessionMgrId.name += "-" + _replicaName; sslSessionMgrId.name += "-" + _replicaName; } - adapter->add(new AdminSessionManagerI(_adminSessionFactory), sessionMgrId); - adapter->add(new AdminSSLSessionManagerI(_adminSessionFactory), sslSessionMgrId); + adapter->add(make_shared<AdminSessionManagerI>(_adminSessionFactory), sessionMgrId); + adapter->add(make_shared<AdminSSLSessionManagerI>(_adminSessionFactory), sslSessionMgrId); _wellKnownObjects->add(adapter->createProxy(sessionMgrId), Glacier2::SessionManager::ice_staticId()); _wellKnownObjects->add(adapter->createProxy(sslSessionMgrId), Glacier2::SSLSessionManager::ice_staticId()); @@ -873,9 +853,8 @@ RegistryI::setupAdminSessionFactory(const Ice::ObjectPtr& serverAdminRouter, con if(adapter) { - Ice::Identity dummy; - dummy.name = "dummy"; - _wellKnownObjects->addEndpoint("AdminSessionManager", adapter->createDirectProxy(dummy)); + Ice::Identity dummy = { "dummy", "" }; + _wellKnownObjects->addEndpoint("AdminSessionManager", adapter->createDirectProxy(move(dummy))); } _adminVerifier = getPermissionsVerifier(locator, "IceGrid.Registry.AdminPermissionsVerifier"); @@ -887,7 +866,7 @@ RegistryI::setupAdminSessionFactory(const Ice::ObjectPtr& serverAdminRouter, con void RegistryI::stop() { - if(_session.get()) + if(_session) { _session->destroy(); } @@ -916,30 +895,30 @@ RegistryI::stop() if(_reaper) { _reaper->terminate(); - _reaper->getThreadControl().join(); - _reaper = 0; + _reaper->join(); + _reaper = nullptr; } if(_timer) { _timer->destroy(); - _timer = 0; + _timer = nullptr; } if(_iceStorm) { _iceStorm->stop(); - _iceStorm = 0; + _iceStorm = nullptr; } - _wellKnownObjects = 0; - _clientSessionFactory = 0; - _adminSessionFactory = 0; - _database = 0; + _wellKnownObjects = nullptr; + _clientSessionFactory = nullptr; + _adminSessionFactory = nullptr; + _database = nullptr; } -SessionPrx -RegistryI::createSession(const string& user, const string& password, const Current& current) +shared_ptr<SessionPrx> +RegistryI::createSession(string user, string password, const Current& current) { if(!_master) { @@ -983,15 +962,15 @@ RegistryI::createSession(const string& user, const string& password, const Curre throw PermissionDeniedException("internal server error"); } - SessionIPtr session = _clientSessionFactory->createSessionServant(user, 0); - Ice::ObjectPrx proxy = session->_register(_servantManager, current.con); - _reaper->add(new SessionReapableWithHeartbeat<SessionI>(_traceLevels->logger, session), _sessionTimeout, + auto session = _clientSessionFactory->createSessionServant(user, nullptr); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared<SessionReapableWithHeartbeat<SessionI>>(_traceLevels->logger, session), _sessionTimeout, current.con); - return SessionPrx::uncheckedCast(proxy); + return uncheckedCast<SessionPrx>(proxy); } -AdminSessionPrx -RegistryI::createAdminSession(const string& user, const string& password, const Current& current) +shared_ptr<AdminSessionPrx> +RegistryI::createAdminSession(string user, string password, const Current& current) { assert(_reaper && _adminSessionFactory); @@ -1030,14 +1009,14 @@ RegistryI::createAdminSession(const string& user, const string& password, const throw PermissionDeniedException("internal server error"); } - AdminSessionIPtr session = _adminSessionFactory->createSessionServant(user); - Ice::ObjectPrx proxy = session->_register(_servantManager, current.con); - _reaper->add(new SessionReapableWithHeartbeat<AdminSessionI>(_traceLevels->logger, session), _sessionTimeout, + auto session = _adminSessionFactory->createSessionServant(user); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared<SessionReapableWithHeartbeat<AdminSessionI>>(_traceLevels->logger, session), _sessionTimeout, current.con); - return AdminSessionPrx::uncheckedCast(proxy); + return uncheckedCast<AdminSessionPrx>(proxy); } -SessionPrx +shared_ptr<SessionPrx> RegistryI::createSessionFromSecureConnection(const Current& current) { if(!_master) @@ -1084,14 +1063,14 @@ RegistryI::createSessionFromSecureConnection(const Current& current) throw PermissionDeniedException("internal server error"); } - SessionIPtr session = _clientSessionFactory->createSessionServant(userDN, 0); - Ice::ObjectPrx proxy = session->_register(_servantManager, current.con); - _reaper->add(new SessionReapableWithHeartbeat<SessionI>(_traceLevels->logger, session), _sessionTimeout, + auto session = _clientSessionFactory->createSessionServant(userDN, 0); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared<SessionReapableWithHeartbeat<SessionI>>(_traceLevels->logger, session), _sessionTimeout, current.con); - return SessionPrx::uncheckedCast(proxy); + return uncheckedCast<SessionPrx>(proxy); } -AdminSessionPrx +shared_ptr<AdminSessionPrx> RegistryI::createAdminSessionFromSecureConnection(const Current& current) { assert(_reaper && _adminSessionFactory); @@ -1131,17 +1110,17 @@ RegistryI::createAdminSessionFromSecureConnection(const Current& current) // // We let the connection access the administrative interface. // - AdminSessionIPtr session = _adminSessionFactory->createSessionServant(userDN); - Ice::ObjectPrx proxy = session->_register(_servantManager, current.con); - _reaper->add(new SessionReapableWithHeartbeat<AdminSessionI>(_traceLevels->logger, session), _sessionTimeout, + auto session = _adminSessionFactory->createSessionServant(userDN); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared<SessionReapableWithHeartbeat<AdminSessionI>>(_traceLevels->logger, session), _sessionTimeout, current.con); - return AdminSessionPrx::uncheckedCast(proxy); + return uncheckedCast<AdminSessionPrx>(proxy); } int -RegistryI::getSessionTimeout(const Ice::Current& /*current*/) const +RegistryI::getSessionTimeout(const Ice::Current&) const { - return _sessionTimeout; + return secondsToInt(_sessionTimeout); } int @@ -1176,26 +1155,26 @@ RegistryI::shutdown() _clientAdapter->deactivate(); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> RegistryI::createAdminCallbackProxy(const Identity& id) const { return _serverAdapter->createProxy(id); } -Ice::LocatorPrx +shared_ptr<Ice::LocatorPrx> RegistryI::getLocator() { return _wellKnownObjects->getLocator(); } -Glacier2::PermissionsVerifierPrx -RegistryI::getPermissionsVerifier(const IceGrid::LocatorPrx& locator, +shared_ptr<Glacier2::PermissionsVerifierPrx> +RegistryI::getPermissionsVerifier(const shared_ptr<IceGrid::LocatorPrx>& locator, const string& verifierProperty) { // // Get the permissions verifier // - ObjectPrx verifier; + shared_ptr<ObjectPrx> verifier; try { @@ -1206,15 +1185,15 @@ RegistryI::getPermissionsVerifier(const IceGrid::LocatorPrx& locator, Error out(_communicator->getLogger()); out << "permissions verifier `" << _communicator->getProperties()->getProperty(verifierProperty) << "' is invalid:\n" << ex; - return 0; + return nullptr; } if(!verifier) { - return 0; + return nullptr; } - Glacier2::PermissionsVerifierPrx verifierPrx; + shared_ptr<Glacier2::PermissionsVerifierPrx> verifierPrx; try { // @@ -1223,13 +1202,13 @@ RegistryI::getPermissionsVerifier(const IceGrid::LocatorPrx& locator, // to deadlocks if there's not enough threads in the client // thread pool anymore. // - verifierPrx = Glacier2::PermissionsVerifierPrx::checkedCast(verifier->ice_locator(locator)); + verifierPrx = checkedCast<Glacier2::PermissionsVerifierPrx>(verifier->ice_locator(locator)); if(!verifierPrx) { Error out(_communicator->getLogger()); out << "permissions verifier `" << _communicator->getProperties()->getProperty(verifierProperty) << "' is invalid"; - return 0; + return nullptr; } } catch(const LocalException& ex) @@ -1240,19 +1219,19 @@ RegistryI::getPermissionsVerifier(const IceGrid::LocatorPrx& locator, out << "couldn't contact permissions verifier `" << _communicator->getProperties()->getProperty(verifierProperty) << "':\n" << ex; } - verifierPrx = Glacier2::PermissionsVerifierPrx::uncheckedCast(verifier->ice_locator(locator)); + verifierPrx = uncheckedCast<Glacier2::PermissionsVerifierPrx>(verifier->ice_locator(locator)); } return verifierPrx; } -Glacier2::SSLPermissionsVerifierPrx -RegistryI::getSSLPermissionsVerifier(const IceGrid::LocatorPrx& locator, const string& verifierProperty) +shared_ptr<Glacier2::SSLPermissionsVerifierPrx> +RegistryI::getSSLPermissionsVerifier(const shared_ptr<IceGrid::LocatorPrx>& locator, const string& verifierProperty) { // // Get the permissions verifier, or create a default one if no // verifier is specified. // - ObjectPrx verifier; + shared_ptr<ObjectPrx> verifier; try { verifier = _communicator->propertyToProxy(verifierProperty); @@ -1262,15 +1241,15 @@ RegistryI::getSSLPermissionsVerifier(const IceGrid::LocatorPrx& locator, const s Error out(_communicator->getLogger()); out << "ssl permissions verifier `" << _communicator->getProperties()->getProperty(verifierProperty) << "' is invalid:\n" << ex; - return 0; + return nullptr; } if(!verifier) { - return 0; + return nullptr; } - Glacier2::SSLPermissionsVerifierPrx verifierPrx; + shared_ptr<Glacier2::SSLPermissionsVerifierPrx> verifierPrx; try { // @@ -1279,13 +1258,13 @@ RegistryI::getSSLPermissionsVerifier(const IceGrid::LocatorPrx& locator, const s // to deadlocks if there's not enough threads in the client // thread pool anymore. // - verifierPrx = Glacier2::SSLPermissionsVerifierPrx::checkedCast(verifier->ice_locator(locator)); + verifierPrx = checkedCast<Glacier2::SSLPermissionsVerifierPrx>(verifier->ice_locator(locator)); if(!verifierPrx) { Error out(_communicator->getLogger()); out << "ssl permissions verifier `" << _communicator->getProperties()->getProperty(verifierProperty) << "' is invalid"; - return 0; + return nullptr; } } catch(const LocalException& ex) @@ -1296,32 +1275,32 @@ RegistryI::getSSLPermissionsVerifier(const IceGrid::LocatorPrx& locator, const s out << "couldn't contact ssl permissions verifier `" << _communicator->getProperties()->getProperty(verifierProperty) << "':\n" << ex; } - verifierPrx = Glacier2::SSLPermissionsVerifierPrx::uncheckedCast(verifier->ice_locator(locator)); + verifierPrx = uncheckedCast<Glacier2::SSLPermissionsVerifierPrx>(verifier->ice_locator(locator)); } return verifierPrx; } Glacier2::SSLInfo -RegistryI::getSSLInfo(const ConnectionPtr& connection, string& userDN) +RegistryI::getSSLInfo(const shared_ptr<Connection>& connection, string& userDN) { Glacier2::SSLInfo sslinfo; try { - IceSSL::ConnectionInfoPtr info = IceSSL::ConnectionInfoPtr::dynamicCast(connection->getInfo()); + auto info = dynamic_pointer_cast<IceSSL::ConnectionInfo>(connection->getInfo()); if(!info) { throw PermissionDeniedException("not ssl connection"); } - Ice::IPConnectionInfoPtr ipInfo = getIPConnectionInfo(info); + auto ipInfo = getIPConnectionInfo(info); sslinfo.remotePort = ipInfo->remotePort; sslinfo.remoteHost = ipInfo->remoteAddress; sslinfo.localPort = ipInfo->localPort; sslinfo.localHost = ipInfo->localAddress; sslinfo.cipher = info->cipher; - for(std::vector<IceSSL::CertificatePtr>::const_iterator i = info->certs.begin(); i != info->certs.end(); ++i) + for(const auto& cert : info->certs) { - sslinfo.certs.push_back((*i)->encode()); + sslinfo.certs.push_back(cert->encode()); } if(info->certs.size() > 0) { @@ -1341,7 +1320,7 @@ RegistryI::getSSLInfo(const ConnectionPtr& connection, string& userDN) } NodePrxSeq -RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const NodePrxSeq& dbNodes) +RegistryI::registerReplicas(const shared_ptr<InternalRegistryPrx>& internalRegistry, const NodePrxSeq& dbNodes) { // // Get proxies for slaves that we we connected with on last @@ -1355,17 +1334,16 @@ RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const N // version <= 3.5.0 also kept the internal proxy in the database // instead of the public proxy. // - map<InternalRegistryPrx, RegistryPrx> replicas; - Ice::ObjectProxySeq proxies = _database->getObjectsByType(InternalRegistry::ice_staticId()); - for(ObjectProxySeq::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + map<shared_ptr<InternalRegistryPrx>, shared_ptr<RegistryPrx>> replicas; + + for(const auto& p : _database->getObjectsByType(InternalRegistry::ice_staticId())) { - replicas.insert(pair<InternalRegistryPrx, RegistryPrx>(InternalRegistryPrx::uncheckedCast(*p), RegistryPrx())); + replicas.insert({ uncheckedCast<InternalRegistryPrx>(p), nullptr }); } - proxies = _database->getObjectsByType(Registry::ice_staticId()); - for(ObjectProxySeq::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + for(const auto& p : _database->getObjectsByType(Registry::ice_staticId())) { - Ice::Identity id = (*p)->ice_getIdentity(); + Ice::Identity id = p->ice_getIdentity(); const string prefix("Registry-"); string::size_type pos = id.name.find(prefix); if(pos == string::npos) @@ -1374,11 +1352,11 @@ RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const N } id.name = "InternalRegistry-" + id.name.substr(prefix.size()); - Ice::ObjectPrx prx = (*p)->ice_identity(id)->ice_endpoints(Ice::EndpointSeq()); + auto prx = p->ice_identity(id)->ice_endpoints(Ice::EndpointSeq()); id.name = "Locator"; - prx = prx->ice_locator(Ice::LocatorPrx::uncheckedCast((*p)->ice_identity(id))); + prx = prx->ice_locator(uncheckedCast<Ice::LocatorPrx>(p->ice_identity(id))); - for(map<InternalRegistryPrx, RegistryPrx>::iterator q = replicas.begin(); q != replicas.end(); ++q) + for(auto q = replicas.begin(); q != replicas.end(); ++q) { if(q->first->ice_getIdentity() == prx->ice_getIdentity()) { @@ -1386,24 +1364,24 @@ RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const N break; } } - replicas.insert(pair<InternalRegistryPrx, RegistryPrx>(InternalRegistryPrx::uncheckedCast(prx), - RegistryPrx::uncheckedCast(*p))); + replicas.insert({uncheckedCast<InternalRegistryPrx>(prx), uncheckedCast<RegistryPrx>(p)}); } - set<NodePrx> nodes; + set<shared_ptr<NodePrx>> nodes; nodes.insert(dbNodes.begin(), dbNodes.end()); - vector<Ice::AsyncResultPtr> results; - for(map<InternalRegistryPrx, RegistryPrx>::const_iterator r = replicas.begin(); r != replicas.end(); ++r) + map<shared_ptr<InternalRegistryPrx>, future<void>> results; + for(const auto& registryPrx : replicas) { - if(r->first->ice_getIdentity() != internalRegistry->ice_getIdentity()) + if(registryPrx.first->ice_getIdentity() != internalRegistry->ice_getIdentity()) { - results.push_back(r->first->begin_registerWithReplica(internalRegistry)); + auto fut = registryPrx.first->registerWithReplicaAsync(internalRegistry); + results.insert({registryPrx.first, move(fut)}); } } - for(vector<Ice::AsyncResultPtr>::const_iterator p = results.begin(); p != results.end(); ++p) + for(const auto& result : results) { - InternalRegistryPrx replica = InternalRegistryPrx::uncheckedCast((*p)->getProxy()); + const auto& replica = result.first; string replicaName; if(_traceLevels && _traceLevels->replica > 1) @@ -1422,7 +1400,7 @@ RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const N try { - replica->end_registerWithReplica(*p); + result.second.wait(); NodePrxSeq nds = replica->getNodes(); nodes.insert(nds.begin(), nds.end()); @@ -1439,12 +1417,12 @@ RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const N // Clear the proxy from the database if we can't // contact the replica. // - RegistryPrx registry; - for(map<InternalRegistryPrx, RegistryPrx>::const_iterator q = replicas.begin(); q != replicas.end(); ++q) + shared_ptr<RegistryPrx> registry; + for(const auto& r : replicas) { - if(q->first->ice_getIdentity() == replica->ice_getIdentity()) + if(r.first->ice_getIdentity() == replica->ice_getIdentity()) { - registry = q->second; + registry = r.second; break; } } @@ -1477,24 +1455,24 @@ RegistryI::registerReplicas(const InternalRegistryPrx& internalRegistry, const N } NodePrxSeq result; - for(set<NodePrx>::iterator p = nodes.begin(); p != nodes.end(); ++p) + for(const auto& node : nodes) { - result.push_back(*p); + result.push_back(node); } return result; } void -RegistryI::registerNodes(const InternalRegistryPrx& /*internalRegistry*/, const NodePrxSeq& nodes) +RegistryI::registerNodes(const shared_ptr<InternalRegistryPrx>&, const NodePrxSeq& nodes) { const string prefix("Node-"); - for(NodePrxSeq::const_iterator p = nodes.begin(); p != nodes.end(); ++p) + for(const auto& node : nodes) { - assert((*p)->ice_getIdentity().name.find(prefix) != string::npos); + assert(node->ice_getIdentity().name.find(prefix) != string::npos); try { - _database->getNode((*p)->ice_getIdentity().name.substr(prefix.size()))->setProxy(*p); + _database->getNode(node->ice_getIdentity().name.substr(prefix.size()))->setProxy(node); } catch(const NodeNotExistException&) { @@ -1505,7 +1483,7 @@ RegistryI::registerNodes(const InternalRegistryPrx& /*internalRegistry*/, const // try { - _database->removeInternalObject((*p)->ice_getIdentity()); + _database->removeInternalObject(node->ice_getIdentity()); } catch(const ObjectNotRegisteredException&) { diff --git a/cpp/src/IceGrid/RegistryI.h b/cpp/src/IceGrid/RegistryI.h index 7589bdada8b..ca6f9d997d9 100644 --- a/cpp/src/IceGrid/RegistryI.h +++ b/cpp/src/IceGrid/RegistryI.h @@ -6,60 +6,47 @@ #define ICE_GRID_REGISTRYI_H #include <IceUtil/Timer.h> -#include <Ice/UniquePtr.h> #include <IceGrid/Registry.h> #include <IceGrid/Internal.h> #include <IceGrid/PlatformInfo.h> #include <IceGrid/ReplicaSessionManager.h> #include <IceGrid/PluginFacade.h> -#include <Glacier2/PermissionsVerifierF.h> +#include <Glacier2/PermissionsVerifier.h> #include <IceStorm/Service.h> namespace IceGrid { +class AdminSessionFactory; +class ClientSessionFactory; class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle<WellKnownObjectsManager> WellKnownObjectsManagerPtr; - -class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - class ReapThread; -typedef IceUtil::Handle<ReapThread> ReapThreadPtr; - class SessionServantManager; -typedef IceUtil::Handle<SessionServantManager> SessionServantManagerPtr; - -class ClientSessionFactory; -typedef IceUtil::Handle<ClientSessionFactory> ClientSessionFactoryPtr; - -class AdminSessionFactory; -typedef IceUtil::Handle<AdminSessionFactory> AdminSessionFactoryPtr; +class TraceLevels; +class WellKnownObjectsManager; -std::string getInstanceName(const Ice::CommunicatorPtr&); +std::string getInstanceName(const std::shared_ptr<Ice::Communicator>&); -class RegistryI : public Registry +class RegistryI : public Registry, public std::enable_shared_from_this<RegistryI> { public: - RegistryI(const Ice::CommunicatorPtr&, const TraceLevelsPtr&, bool, bool, const std::string&, const std::string&); - ~RegistryI(); + RegistryI(const std::shared_ptr<Ice::Communicator>&, const std::shared_ptr<TraceLevels>&, bool, bool, + const std::string&, const std::string&); + virtual ~RegistryI() = default; bool start(); bool startImpl(); void stop(); - virtual SessionPrx createSession(const std::string&, const std::string&, const Ice::Current&); - virtual AdminSessionPrx createAdminSession(const std::string&, const std::string&, const Ice::Current&); + std::shared_ptr<SessionPrx> createSession(std::string, std::string, const Ice::Current&) override; + std::shared_ptr<AdminSessionPrx> createAdminSession(std::string, std::string, const Ice::Current&) override; - virtual SessionPrx createSessionFromSecureConnection(const Ice::Current&); - virtual AdminSessionPrx createAdminSessionFromSecureConnection(const Ice::Current&); + std::shared_ptr<SessionPrx> createSessionFromSecureConnection(const Ice::Current&) override; + std::shared_ptr<AdminSessionPrx> createAdminSessionFromSecureConnection(const Ice::Current&) override; - virtual int getSessionTimeout(const Ice::Current&) const; - virtual int getACMTimeout(const Ice::Current&) const; + int getSessionTimeout(const Ice::Current&) const override; + int getACMTimeout(const Ice::Current&) const override; std::string getName() const; RegistryInfo getInfo() const; @@ -71,64 +58,67 @@ public: std::string getNodeAdminCategory() const { return _instanceName + "-RegistryNodeAdminRouter"; } std::string getReplicaAdminCategory() const { return _instanceName + "-RegistryReplicaAdminRouter"; } - Ice::ObjectPrx createAdminCallbackProxy(const Ice::Identity&) const; + std::shared_ptr<Ice::ObjectPrx> createAdminCallbackProxy(const Ice::Identity&) const; - const Ice::ObjectAdapterPtr& getRegistryAdapter() { return _registryAdapter; } + const std::shared_ptr<Ice::ObjectAdapter>& getRegistryAdapter() { return _registryAdapter; } - Ice::LocatorPrx getLocator(); + std::shared_ptr<Ice::LocatorPrx> getLocator(); private: void setupLocatorRegistry(); - LocatorPrx setupLocator(const RegistryPrx&, const QueryPrx&); - QueryPrx setupQuery(); - RegistryPrx setupRegistry(); - InternalRegistryPrx setupInternalRegistry(); + std::shared_ptr<LocatorPrx> setupLocator(const std::shared_ptr<RegistryPrx>&, const std::shared_ptr<QueryPrx>&); + std::shared_ptr<QueryPrx> setupQuery(); + std::shared_ptr<RegistryPrx> setupRegistry(); + std::shared_ptr<InternalRegistryPrx> setupInternalRegistry(); bool setupUserAccountMapper(); - Ice::ObjectAdapterPtr setupClientSessionFactory(const LocatorPrx&); - Ice::ObjectAdapterPtr setupAdminSessionFactory(const Ice::ObjectPtr&, const Ice::ObjectPtr&, - const Ice::ObjectPtr&, const LocatorPrx&); - - Glacier2::PermissionsVerifierPrx getPermissionsVerifier(const LocatorPrx&, const std::string&); - Glacier2::SSLPermissionsVerifierPrx getSSLPermissionsVerifier(const LocatorPrx&, const std::string&); - Glacier2::SSLInfo getSSLInfo(const Ice::ConnectionPtr&, std::string&); - - NodePrxSeq registerReplicas(const InternalRegistryPrx&, const NodePrxSeq&); - void registerNodes(const InternalRegistryPrx&, const NodePrxSeq&); - - const Ice::CommunicatorPtr _communicator; - const TraceLevelsPtr _traceLevels; + std::shared_ptr<Ice::ObjectAdapter> setupClientSessionFactory(const std::shared_ptr<LocatorPrx>&); + std::shared_ptr<Ice::ObjectAdapter> setupAdminSessionFactory(const std::shared_ptr<Ice::Object>&, + const std::shared_ptr<Ice::Object>&, + const std::shared_ptr<Ice::Object>&, + const std::shared_ptr<LocatorPrx>&); + + std::shared_ptr<Glacier2::PermissionsVerifierPrx> getPermissionsVerifier(const std::shared_ptr<LocatorPrx>&, + const std::string&); + std::shared_ptr<Glacier2::SSLPermissionsVerifierPrx> getSSLPermissionsVerifier(const std::shared_ptr<LocatorPrx>&, + const std::string&); + Glacier2::SSLInfo getSSLInfo(const std::shared_ptr<Ice::Connection>&, std::string&); + + NodePrxSeq registerReplicas(const std::shared_ptr<InternalRegistryPrx>&, const NodePrxSeq&); + void registerNodes(const std::shared_ptr<InternalRegistryPrx>&, const NodePrxSeq&); + + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<TraceLevels> _traceLevels; const bool _nowarn; const bool _readonly; const std::string _initFromReplica; const std::string _collocatedNodeName; - DatabasePtr _database; - Ice::ObjectAdapterPtr _clientAdapter; - Ice::ObjectAdapterPtr _serverAdapter; - Ice::ObjectAdapterPtr _registryAdapter; - WellKnownObjectsManagerPtr _wellKnownObjects; + std::shared_ptr<Database> _database; + std::shared_ptr<Ice::ObjectAdapter> _clientAdapter; + std::shared_ptr<Ice::ObjectAdapter> _serverAdapter; + std::shared_ptr<Ice::ObjectAdapter> _registryAdapter; + std::shared_ptr<WellKnownObjectsManager> _wellKnownObjects; std::string _instanceName; bool _master; std::string _replicaName; - ReapThreadPtr _reaper; + std::shared_ptr<ReapThread> _reaper; IceUtil::TimerPtr _timer; - SessionServantManagerPtr _servantManager; - int _sessionTimeout; - IceInternal::UniquePtr<ReplicaSessionManager> _session; + std::shared_ptr<SessionServantManager> _servantManager; + std::chrono::seconds _sessionTimeout; + std::unique_ptr<ReplicaSessionManager> _session; mutable PlatformInfo _platform; - ClientSessionFactoryPtr _clientSessionFactory; - Glacier2::PermissionsVerifierPrx _clientVerifier; - Glacier2::SSLPermissionsVerifierPrx _sslClientVerifier; + std::shared_ptr<ClientSessionFactory> _clientSessionFactory; + std::shared_ptr<Glacier2::PermissionsVerifierPrx> _clientVerifier; + std::shared_ptr<Glacier2::SSLPermissionsVerifierPrx> _sslClientVerifier; - AdminSessionFactoryPtr _adminSessionFactory; - Glacier2::PermissionsVerifierPrx _adminVerifier; - Glacier2::SSLPermissionsVerifierPrx _sslAdminVerifier; + std::shared_ptr<AdminSessionFactory> _adminSessionFactory; + std::shared_ptr<Glacier2::PermissionsVerifierPrx> _adminVerifier; + std::shared_ptr<Glacier2::SSLPermissionsVerifierPrx> _sslAdminVerifier; - IceStormInternal::ServicePtr _iceStorm; + std::shared_ptr<IceStormInternal::Service> _iceStorm; }; -typedef IceUtil::Handle<RegistryI> RegistryIPtr; } diff --git a/cpp/src/IceGrid/ReplicaCache.cpp b/cpp/src/IceGrid/ReplicaCache.cpp index 56cfac1d3e7..93ac8cb652d 100644 --- a/cpp/src/IceGrid/ReplicaCache.cpp +++ b/cpp/src/IceGrid/ReplicaCache.cpp @@ -12,10 +12,11 @@ using namespace std; using namespace IceGrid; -ReplicaCache::ReplicaCache(const Ice::CommunicatorPtr& communicator, const IceStorm::TopicManagerPrx& topicManager) : +ReplicaCache::ReplicaCache(const shared_ptr<Ice::Communicator>& communicator, + const shared_ptr<IceStorm::TopicManagerPrx>& topicManager) : _communicator(communicator) { - IceStorm::TopicPrx t; + shared_ptr<IceStorm::TopicPrx> t; try { t = topicManager->create("ReplicaObserverTopic"); @@ -25,22 +26,25 @@ ReplicaCache::ReplicaCache(const Ice::CommunicatorPtr& communicator, const IceSt t = topicManager->retrieve("ReplicaObserverTopic"); } - const_cast<IceStorm::TopicPrx&>(_topic) = IceStorm::TopicPrx::uncheckedCast(t->ice_endpoints(Ice::EndpointSeq())); - const_cast<ReplicaObserverPrx&>(_observers) = ReplicaObserverPrx::uncheckedCast(_topic->getPublisher()->ice_endpoints(Ice::EndpointSeq())); + const_cast<shared_ptr<IceStorm::TopicPrx>&>(_topic) = + Ice::uncheckedCast<IceStorm::TopicPrx>(t->ice_endpoints(Ice::EndpointSeq())); + const_cast<shared_ptr<ReplicaObserverPrx>&>(_observers) = + Ice::uncheckedCast<ReplicaObserverPrx>(_topic->getPublisher()->ice_endpoints(Ice::EndpointSeq())); } -ReplicaEntryPtr -ReplicaCache::add(const string& name, const ReplicaSessionIPtr& session) +shared_ptr<ReplicaEntry> +ReplicaCache::add(const string& name, const shared_ptr<ReplicaSessionI>& session) { - Lock sync(*this); + unique_lock lock(_mutex); - ReplicaEntryPtr entry; + shared_ptr<ReplicaEntry> entry; while((entry = getImpl(name))) { - ReplicaSessionIPtr s = entry->getSession(); + auto s = entry->getSession(); if(s->isDestroyed()) { - wait(); // Wait for the session to be removed. + // Wait for the session to be removed. + _condVar.wait(lock); } else { @@ -48,7 +52,7 @@ ReplicaCache::add(const string& name, const ReplicaSessionIPtr& session) // Check if the replica is still reachable, if not, we // destroy its session. // - sync.release(); + lock.unlock(); try { s->getInternalRegistry()->ice_ping(); @@ -64,7 +68,7 @@ ReplicaCache::add(const string& name, const ReplicaSessionIPtr& session) { } } - sync.acquire(); + lock.lock(); } } @@ -88,7 +92,7 @@ ReplicaCache::add(const string& name, const ReplicaSessionIPtr& session) } catch(const Ice::LocalException& ex) { - TraceLevelsPtr traceLevels = getTraceLevels(); + auto traceLevels = getTraceLevels(); if(traceLevels) { Ice::Warning out(traceLevels->logger); @@ -96,18 +100,18 @@ ReplicaCache::add(const string& name, const ReplicaSessionIPtr& session) } } - return addImpl(name, new ReplicaEntry(name, session)); + return addImpl(name, make_shared<ReplicaEntry>(name, session)); } -ReplicaEntryPtr +shared_ptr<ReplicaEntry> ReplicaCache::remove(const string& name, bool shutdown) { - Lock sync(*this); + lock_guard lock(_mutex); - ReplicaEntryPtr entry = getImpl(name); + auto entry = getImpl(name); assert(entry); removeImpl(name); - notifyAll(); + _condVar.notify_all(); if(_traceLevels && _traceLevels->replica > 0) { @@ -131,7 +135,7 @@ ReplicaCache::remove(const string& name, bool shutdown) } catch(const Ice::LocalException& ex) { - TraceLevelsPtr traceLevels = getTraceLevels(); + auto traceLevels = getTraceLevels(); if(traceLevels) { Ice::Warning out(traceLevels->logger); @@ -143,11 +147,11 @@ ReplicaCache::remove(const string& name, bool shutdown) return entry; } -ReplicaEntryPtr +shared_ptr<ReplicaEntry> ReplicaCache::get(const string& name) const { - Lock sync(*this); - ReplicaEntryPtr entry = getImpl(name); + lock_guard lock(_mutex); + auto entry = getImpl(name); if(!entry) { throw RegistryNotExistException(name); @@ -156,21 +160,21 @@ ReplicaCache::get(const string& name) const } void -ReplicaCache::subscribe(const ReplicaObserverPrx& observer) +ReplicaCache::subscribe(const shared_ptr<ReplicaObserverPrx>& observer) { try { - Lock sync(*this); + lock_guard lock(_mutex); InternalRegistryPrxSeq replicas; - for(map<string, ReplicaEntryPtr>::const_iterator p = _entries.begin(); p != _entries.end(); ++p) + for(const auto& entry : _entries) { - replicas.push_back(p->second->getProxy()); + replicas.push_back(entry.second->getProxy()); } IceStorm::QoS qos; qos["reliability"] = "ordered"; - Ice::ObjectPrx publisher = _topic->subscribeAndGetPublisher(qos, observer->ice_twoway()); - ReplicaObserverPrx::uncheckedCast(publisher)->replicaInit(replicas); + auto publisher = _topic->subscribeAndGetPublisher(qos, observer->ice_twoway()); + Ice::uncheckedCast<ReplicaObserverPrx>(publisher)->replicaInit(replicas); } catch(const Ice::NoEndpointException&) { @@ -182,7 +186,7 @@ ReplicaCache::subscribe(const ReplicaObserverPrx& observer) } catch(const Ice::LocalException& ex) { - TraceLevelsPtr traceLevels = getTraceLevels(); + auto traceLevels = getTraceLevels(); if(traceLevels) { Ice::Warning out(traceLevels->logger); @@ -192,7 +196,7 @@ ReplicaCache::subscribe(const ReplicaObserverPrx& observer) } void -ReplicaCache::unsubscribe(const ReplicaObserverPrx& observer) +ReplicaCache::unsubscribe(const shared_ptr<ReplicaObserverPrx>& observer) { try { @@ -208,7 +212,7 @@ ReplicaCache::unsubscribe(const ReplicaObserverPrx& observer) } catch(const Ice::LocalException& ex) { - TraceLevelsPtr traceLevels = getTraceLevels(); + auto traceLevels = getTraceLevels(); if(traceLevels) { Ice::Warning out(traceLevels->logger); @@ -217,8 +221,8 @@ ReplicaCache::unsubscribe(const ReplicaObserverPrx& observer) } } -Ice::ObjectPrx -ReplicaCache::getEndpoints(const string& name, const Ice::ObjectPrx& proxy) const +shared_ptr<Ice::ObjectPrx> +ReplicaCache::getEndpoints(const string& name, const shared_ptr<Ice::ObjectPrx>& proxy) const { Ice::EndpointSeq endpoints; @@ -228,10 +232,10 @@ ReplicaCache::getEndpoints(const string& name, const Ice::ObjectPrx& proxy) cons endpoints.insert(endpoints.end(), endpts.begin(), endpts.end()); } - Lock sync(*this); - for(map<string, ReplicaEntryPtr>::const_iterator p = _entries.begin(); p != _entries.end(); ++p) + lock_guard lock(_mutex); + for(const auto& entry : _entries) { - Ice::ObjectPrx prx = p->second->getSession()->getEndpoint(name); + auto prx = entry.second->getSession()->getEndpoint(name); if(prx) { Ice::EndpointSeq endpts = prx->ice_getEndpoints(); @@ -243,7 +247,7 @@ ReplicaCache::getEndpoints(const string& name, const Ice::ObjectPrx& proxy) cons } void -ReplicaCache::setInternalRegistry(const InternalRegistryPrx& proxy) +ReplicaCache::setInternalRegistry(const shared_ptr<InternalRegistryPrx>& proxy) { // // Setup this replica internal registry proxy. @@ -251,7 +255,7 @@ ReplicaCache::setInternalRegistry(const InternalRegistryPrx& proxy) _self = proxy; } -InternalRegistryPrx +shared_ptr<InternalRegistryPrx> ReplicaCache::getInternalRegistry() const { // @@ -260,41 +264,35 @@ ReplicaCache::getInternalRegistry() const return _self; } -ReplicaEntry::ReplicaEntry(const std::string& name, const ReplicaSessionIPtr& session) : +ReplicaEntry::ReplicaEntry(const std::string& name, const shared_ptr<ReplicaSessionI>& session) : _name(name), _session(session) { } -ReplicaEntry::~ReplicaEntry() -{ -} - -const ReplicaSessionIPtr& +const shared_ptr<ReplicaSessionI>& ReplicaEntry::getSession() const { return _session; } -InternalReplicaInfoPtr +shared_ptr<InternalReplicaInfo> ReplicaEntry::getInfo() const { return _session->getInfo(); } -InternalRegistryPrx +shared_ptr<InternalRegistryPrx> ReplicaEntry::getProxy() const { return _session->getInternalRegistry(); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> ReplicaEntry::getAdminProxy() const { - Ice::ObjectPrx prx = getProxy(); + auto prx = getProxy(); assert(prx); - Ice::Identity adminId; - adminId.name = "RegistryAdmin-" + _name; - adminId.category = prx->ice_getIdentity().category; - return prx->ice_identity(adminId); + Ice::Identity adminId = { "RegistryAdmin-" + _name, prx->ice_getIdentity().category }; + return prx->ice_identity(move(adminId)); } diff --git a/cpp/src/IceGrid/ReplicaCache.h b/cpp/src/IceGrid/ReplicaCache.h index 9e38f0cadfd..c0c90e9b5eb 100644 --- a/cpp/src/IceGrid/ReplicaCache.h +++ b/cpp/src/IceGrid/ReplicaCache.h @@ -5,8 +5,6 @@ #ifndef ICE_GRID_REPLICACACHE_H #define ICE_GRID_REPLICACACHE_H -#include <IceUtil/Mutex.h> -#include <IceUtil/Shared.h> #include <IceGrid/Cache.h> #include <IceGrid/Internal.h> #include <IceStorm/IceStorm.h> @@ -15,59 +13,51 @@ namespace IceGrid { class ReplicaCache; - class ReplicaSessionI; -typedef IceUtil::Handle<ReplicaSessionI> ReplicaSessionIPtr; -class ReplicaEntry : public IceUtil::Shared +class ReplicaEntry final { public: - ReplicaEntry(const std::string&, const ReplicaSessionIPtr&); - virtual ~ReplicaEntry(); + ReplicaEntry(const std::string&, const std::shared_ptr<ReplicaSessionI>&); bool canRemove() const { return true; } - const ReplicaSessionIPtr& getSession() const; - InternalReplicaInfoPtr getInfo() const; - InternalRegistryPrx getProxy() const; + const std::shared_ptr<ReplicaSessionI>& getSession() const; + std::shared_ptr<InternalReplicaInfo> getInfo() const; + std::shared_ptr<InternalRegistryPrx> getProxy() const; - Ice::ObjectPrx getAdminProxy() const; + std::shared_ptr<Ice::ObjectPrx> getAdminProxy() const; private: const std::string _name; - const ReplicaSessionIPtr _session; + const std::shared_ptr<ReplicaSessionI> _session; }; -typedef IceUtil::Handle<ReplicaEntry> ReplicaEntryPtr; -class ReplicaCache : public CacheByString<ReplicaEntry> +class ReplicaCache final : public CacheByString<ReplicaEntry> { public: -#ifdef __SUNPRO_CC - using CacheByString<ReplicaEntry>::remove; -#endif - - ReplicaCache(const Ice::CommunicatorPtr&, const IceStorm::TopicManagerPrx&); + ReplicaCache(const std::shared_ptr<Ice::Communicator>&, const std::shared_ptr<IceStorm::TopicManagerPrx>&); - ReplicaEntryPtr add(const std::string&, const ReplicaSessionIPtr&); - ReplicaEntryPtr remove(const std::string&, bool); - ReplicaEntryPtr get(const std::string&) const; + std::shared_ptr<ReplicaEntry> add(const std::string&, const std::shared_ptr<ReplicaSessionI>&); + std::shared_ptr<ReplicaEntry> remove(const std::string&, bool); + std::shared_ptr<ReplicaEntry> get(const std::string&) const; - void subscribe(const ReplicaObserverPrx&); - void unsubscribe(const ReplicaObserverPrx&); + void subscribe(const std::shared_ptr<ReplicaObserverPrx>&); + void unsubscribe(const std::shared_ptr<ReplicaObserverPrx>&); - Ice::ObjectPrx getEndpoints(const std::string&, const Ice::ObjectPrx&) const; + std::shared_ptr<Ice::ObjectPrx> getEndpoints(const std::string&, const std::shared_ptr<Ice::ObjectPrx>&) const; - void setInternalRegistry(const InternalRegistryPrx&); - InternalRegistryPrx getInternalRegistry() const; + void setInternalRegistry(const std::shared_ptr<InternalRegistryPrx>&); + std::shared_ptr<InternalRegistryPrx> getInternalRegistry() const; private: - const Ice::CommunicatorPtr _communicator; - const IceStorm::TopicPrx _topic; - const ReplicaObserverPrx _observers; - InternalRegistryPrx _self; // This replica internal registry proxy. + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<IceStorm::TopicPrx> _topic; + const std::shared_ptr<ReplicaObserverPrx> _observers; + std::shared_ptr<InternalRegistryPrx> _self; // This replica internal registry proxy. }; }; diff --git a/cpp/src/IceGrid/ReplicaSessionI.cpp b/cpp/src/IceGrid/ReplicaSessionI.cpp index 6d9030fb886..381e9afe036 100644 --- a/cpp/src/IceGrid/ReplicaSessionI.cpp +++ b/cpp/src/IceGrid/ReplicaSessionI.cpp @@ -23,58 +23,69 @@ operator==(const ObjectInfo& info, const Ice::Identity& id) } -ReplicaSessionI::ReplicaSessionI(const DatabasePtr& database, - const WellKnownObjectsManagerPtr& wellKnownObjects, - const InternalReplicaInfoPtr& info, - const InternalRegistryPrx& proxy, - int timeout) : - _database(database), - _wellKnownObjects(wellKnownObjects), - _traceLevels(database->getTraceLevels()), - _internalRegistry(proxy), - _info(info), - _timeout(timeout), - _timestamp(IceUtil::Time::now(IceUtil::Time::Monotonic)), - _destroy(false) +shared_ptr<ReplicaSessionI> +ReplicaSessionI::create(const shared_ptr<Database>& database, + const shared_ptr<WellKnownObjectsManager>& wellKnownObjects, + const shared_ptr<InternalReplicaInfo>& info, + const shared_ptr<InternalRegistryPrx>& proxy, + chrono::seconds timeout) { - __setNoDelete(true); + + shared_ptr<ReplicaSessionI> replicaSession(new ReplicaSessionI(database, wellKnownObjects, info, proxy, timeout)); + try { - _database->getReplicaCache().add(info->name, this); + database->getReplicaCache().add(info->name, replicaSession); - ObserverTopicPtr obsv = _database->getObserverTopic(RegistryObserverTopicName); - RegistryObserverTopicPtr::dynamicCast(obsv)->registryUp(toRegistryInfo(_info)); + auto obsv = database->getObserverTopic(TopicName::RegistryObserver); + static_pointer_cast<RegistryObserverTopic>(obsv)->registryUp(toRegistryInfo(info)); - _proxy = ReplicaSessionPrx::uncheckedCast(_database->getInternalAdapter()->addWithUUID(this)); + replicaSession->_proxy = + Ice::uncheckedCast<ReplicaSessionPrx>(database->getInternalAdapter()->addWithUUID(replicaSession)); } catch(const ReplicaActiveException&) { - __setNoDelete(false); throw; } - catch(...) + catch(const std::exception&) { - ObserverTopicPtr obsv = _database->getObserverTopic(RegistryObserverTopicName); - RegistryObserverTopicPtr::dynamicCast(obsv)->registryDown(_info->name); + auto obsv = database->getObserverTopic(TopicName::RegistryObserver); + static_pointer_cast<RegistryObserverTopic>(obsv)->registryDown(info->name); - _database->getReplicaCache().remove(_info->name, false); + database->getReplicaCache().remove(info->name, false); - __setNoDelete(false); throw; } - __setNoDelete(false); + + return replicaSession; +} + +ReplicaSessionI::ReplicaSessionI(const shared_ptr<Database>& database, + const shared_ptr<WellKnownObjectsManager>& wellKnownObjects, + const shared_ptr<InternalReplicaInfo>& info, + const shared_ptr<InternalRegistryPrx>& proxy, + chrono::seconds timeout) : + _database(database), + _wellKnownObjects(wellKnownObjects), + _traceLevels(database->getTraceLevels()), + _internalRegistry(proxy), + _info(info), + _timeout(timeout), + _timestamp(chrono::steady_clock::now()), + _destroy(false) +{ } void ReplicaSessionI::keepAlive(const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); } - _timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic); + _timestamp = chrono::steady_clock::now(); if(_traceLevels->replica > 2) { @@ -86,12 +97,12 @@ ReplicaSessionI::keepAlive(const Ice::Current&) int ReplicaSessionI::getTimeout(const Ice::Current&) const { - return _timeout; + return secondsToInt(_timeout); } void -ReplicaSessionI::setDatabaseObserver(const DatabaseObserverPrx& observer, - const IceUtil::Optional<StringLongDict>& slaveSerials, +ReplicaSessionI::setDatabaseObserver(shared_ptr<DatabaseObserverPrx> observer, + IceUtil::Optional<StringLongDict> slaveSerials, const Ice::Current&) { // @@ -146,12 +157,12 @@ ReplicaSessionI::setDatabaseObserver(const DatabaseObserverPrx& observer, int serialAdapterObserver; int serialObjectObserver; - const ObserverTopicPtr applicationObserver = _database->getObserverTopic(ApplicationObserverTopicName); - const ObserverTopicPtr adapterObserver = _database->getObserverTopic(AdapterObserverTopicName); - const ObserverTopicPtr objectObserver = _database->getObserverTopic(ObjectObserverTopicName); + const auto applicationObserver = _database->getObserverTopic(TopicName::ApplicationObserver); + const auto adapterObserver = _database->getObserverTopic(TopicName::AdapterObserver); + const auto objectObserver = _database->getObserverTopic(TopicName::ObjectObserver); { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -169,25 +180,25 @@ ReplicaSessionI::setDatabaseObserver(const DatabaseObserverPrx& observer, } void -ReplicaSessionI::setEndpoints(const StringObjectProxyDict& endpoints, const Ice::Current&) +ReplicaSessionI::setEndpoints(StringObjectProxyDict endpoints, const Ice::Current&) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); } - _replicaEndpoints = endpoints; + _replicaEndpoints = move(endpoints); } _wellKnownObjects->updateReplicatedWellKnownObjects(); } void -ReplicaSessionI::registerWellKnownObjects(const ObjectInfoSeq& objects, const Ice::Current&) +ReplicaSessionI::registerWellKnownObjects(ObjectInfoSeq objects, const Ice::Current&) { int serial; { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -202,13 +213,13 @@ ReplicaSessionI::registerWellKnownObjects(const ObjectInfoSeq& objects, const Ic // are correctly setup when the replica starts accepting requests // from clients (if the replica is being started). // - _database->getObserverTopic(ObjectObserverTopicName)->waitForSyncedSubscribers(serial, _info->name); + _database->getObserverTopic(TopicName::ObjectObserver)->waitForSyncedSubscribers(serial, _info->name); } void -ReplicaSessionI::setAdapterDirectProxy(const string& adapterId, - const string& replicaGroupId, - const Ice::ObjectPrx& proxy, +ReplicaSessionI::setAdapterDirectProxy(string adapterId, + string replicaGroupId, + shared_ptr<Ice::ObjectPrx> proxy, const Ice::Current&) { if(_database->getCommunicator()->getProperties()->getPropertyAsInt("IceGrid.Registry.DynamicRegistration") <= 0) @@ -219,9 +230,9 @@ ReplicaSessionI::setAdapterDirectProxy(const string& adapterId, } void -ReplicaSessionI::receivedUpdate(TopicName topicName, int serial, const string& failure, const Ice::Current&) +ReplicaSessionI::receivedUpdate(TopicName topicName, int serial, string failure, const Ice::Current&) { - ObserverTopicPtr topic = _database->getObserverTopic(topicName); + auto topic = _database->getObserverTopic(topicName); if(topic) { topic->receivedUpdate(_info->name, serial, failure); @@ -234,10 +245,10 @@ ReplicaSessionI::destroy(const Ice::Current&) destroyImpl(false); } -IceUtil::Time +chrono::steady_clock::time_point ReplicaSessionI::timestamp() const { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -251,31 +262,31 @@ ReplicaSessionI::shutdown() destroyImpl(true); } -const InternalRegistryPrx& +const shared_ptr<InternalRegistryPrx>& ReplicaSessionI::getInternalRegistry() const { return _internalRegistry; } -const InternalReplicaInfoPtr& +const shared_ptr<InternalReplicaInfo>& ReplicaSessionI::getInfo() const { return _info; } -ReplicaSessionPrx +shared_ptr<ReplicaSessionPrx> ReplicaSessionI::getProxy() const { return _proxy; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> ReplicaSessionI::getEndpoint(const std::string& name) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { - return 0; + return nullptr; } return _replicaEndpoints[name]; } @@ -283,7 +294,7 @@ ReplicaSessionI::getEndpoint(const std::string& name) bool ReplicaSessionI::isDestroyed() const { - Lock sync(*this); + lock_guard lock(_mutex); return _destroy; } @@ -291,7 +302,7 @@ void ReplicaSessionI::destroyImpl(bool shutdown) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -301,9 +312,9 @@ ReplicaSessionI::destroyImpl(bool shutdown) if(_observer) { - _database->getObserverTopic(ApplicationObserverTopicName)->unsubscribe(_observer, _info->name); - _database->getObserverTopic(AdapterObserverTopicName)->unsubscribe(_observer, _info->name); - _database->getObserverTopic(ObjectObserverTopicName)->unsubscribe(_observer, _info->name); + _database->getObserverTopic(TopicName::ApplicationObserver)->unsubscribe(_observer, _info->name); + _database->getObserverTopic(TopicName::AdapterObserver)->unsubscribe(_observer, _info->name); + _database->getObserverTopic(TopicName::ObjectObserver)->unsubscribe(_observer, _info->name); } // Don't remove the replica proxy from the database if the registry is being shutdown. @@ -311,10 +322,8 @@ ReplicaSessionI::destroyImpl(bool shutdown) { if(shutdown) // Don't remove the replica proxy from the database if the registry is being shutdown. { - Ice::Identity id; - id.category = _internalRegistry->ice_getIdentity().category; - id.name = "Registry-" + _info->name; - ObjectInfoSeq::iterator p = find(_replicaWellKnownObjects.begin(), _replicaWellKnownObjects.end(), id); + Ice::Identity id = { "Registry-" + _info->name, _internalRegistry->ice_getIdentity().category }; + auto p = find(_replicaWellKnownObjects.begin(), _replicaWellKnownObjects.end(), id); if(p != _replicaWellKnownObjects.end()) { _replicaWellKnownObjects.erase(p); @@ -331,8 +340,8 @@ ReplicaSessionI::destroyImpl(bool shutdown) // // Notify the observer that the registry is down. // - ObserverTopicPtr obsv = _database->getObserverTopic(RegistryObserverTopicName); - RegistryObserverTopicPtr::dynamicCast(obsv)->registryDown(_info->name); + auto obsv = _database->getObserverTopic(TopicName::RegistryObserver); + static_pointer_cast<RegistryObserverTopic>(obsv)->registryDown(_info->name); // // Remove the replica from the cache. This must be done last. As diff --git a/cpp/src/IceGrid/ReplicaSessionI.h b/cpp/src/IceGrid/ReplicaSessionI.h index 1977d7e9734..86f3277d703 100644 --- a/cpp/src/IceGrid/ReplicaSessionI.h +++ b/cpp/src/IceGrid/ReplicaSessionI.h @@ -12,60 +12,62 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle<WellKnownObjectsManager> WellKnownObjectsManagerPtr; - class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; +class WellKnownObjectsManager; -class ReplicaSessionI : public ReplicaSession, public IceUtil::Mutex +class ReplicaSessionI final : public ReplicaSession { public: - ReplicaSessionI(const DatabasePtr&, const WellKnownObjectsManagerPtr&, const InternalReplicaInfoPtr&, - const InternalRegistryPrx&, int); - - virtual void keepAlive(const Ice::Current&); - virtual int getTimeout(const Ice::Current&) const; - virtual void setDatabaseObserver(const DatabaseObserverPrx&, const IceUtil::Optional<StringLongDict>&, - const Ice::Current&); - virtual void setEndpoints(const StringObjectProxyDict&, const Ice::Current&); - virtual void registerWellKnownObjects(const ObjectInfoSeq&, const Ice::Current&); - virtual void setAdapterDirectProxy(const std::string&, const std::string&, const Ice::ObjectPrx&, - const Ice::Current&); - virtual void receivedUpdate(TopicName, int, const std::string&, const Ice::Current&); - virtual void destroy(const Ice::Current&); - - virtual IceUtil::Time timestamp() const; - virtual void shutdown(); - - const InternalRegistryPrx& getInternalRegistry() const; - const InternalReplicaInfoPtr& getInfo() const; - ReplicaSessionPrx getProxy() const; - - Ice::ObjectPrx getEndpoint(const std::string&); + static std::shared_ptr<ReplicaSessionI> create(const std::shared_ptr<Database>&, + const std::shared_ptr<WellKnownObjectsManager>&, + const std::shared_ptr<InternalReplicaInfo>&, + const std::shared_ptr<InternalRegistryPrx>&, + std::chrono::seconds); + + void keepAlive(const Ice::Current&) override; + int getTimeout(const Ice::Current&) const override; + void setDatabaseObserver(std::shared_ptr<DatabaseObserverPrx>, IceUtil::Optional<StringLongDict>, + const Ice::Current&) override; + void setEndpoints(StringObjectProxyDict, const Ice::Current&) override; + void registerWellKnownObjects(ObjectInfoSeq, const Ice::Current&) override; + void setAdapterDirectProxy(std::string, std::string, std::shared_ptr<Ice::ObjectPrx>, const Ice::Current&) override; + void receivedUpdate(TopicName, int, std::string, const Ice::Current&) override; + void destroy(const Ice::Current&) override; + + std::chrono::steady_clock::time_point timestamp() const; + void shutdown(); + + const std::shared_ptr<InternalRegistryPrx>& getInternalRegistry() const; + const std::shared_ptr<InternalReplicaInfo>& getInfo() const; + std::shared_ptr<ReplicaSessionPrx> getProxy() const; + + std::shared_ptr<Ice::ObjectPrx> getEndpoint(const std::string&); bool isDestroyed() const; private: + ReplicaSessionI(const std::shared_ptr<Database>&, const std::shared_ptr<WellKnownObjectsManager>&, + const std::shared_ptr<InternalReplicaInfo>&, const std::shared_ptr<InternalRegistryPrx>&, + std::chrono::seconds); + void destroyImpl(bool); - const DatabasePtr _database; - const WellKnownObjectsManagerPtr _wellKnownObjects; - const TraceLevelsPtr _traceLevels; - const InternalRegistryPrx _internalRegistry; - const InternalReplicaInfoPtr _info; - const int _timeout; - ReplicaSessionPrx _proxy; - DatabaseObserverPrx _observer; + const std::shared_ptr<Database> _database; + const std::shared_ptr<WellKnownObjectsManager> _wellKnownObjects; + const std::shared_ptr<TraceLevels> _traceLevels; + const std::shared_ptr<InternalRegistryPrx> _internalRegistry; + const std::shared_ptr<InternalReplicaInfo> _info; + const std::chrono::seconds _timeout; + std::shared_ptr<ReplicaSessionPrx> _proxy; + std::shared_ptr<DatabaseObserverPrx> _observer; ObjectInfoSeq _replicaWellKnownObjects; StringObjectProxyDict _replicaEndpoints; - IceUtil::Time _timestamp; + std::chrono::steady_clock::time_point _timestamp; bool _destroy; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<ReplicaSessionI> ReplicaSessionIPtr; }; diff --git a/cpp/src/IceGrid/ReplicaSessionManager.cpp b/cpp/src/IceGrid/ReplicaSessionManager.cpp index da6f5cb4983..73547a5a304 100644 --- a/cpp/src/IceGrid/ReplicaSessionManager.cpp +++ b/cpp/src/IceGrid/ReplicaSessionManager.cpp @@ -14,35 +14,35 @@ using namespace IceGrid; namespace IceGrid { -class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex +class MasterDatabaseObserverI : public DatabaseObserver { public: - MasterDatabaseObserverI(const ReplicaSessionManager::ThreadPtr& thread, - const DatabasePtr& database, - const ReplicaSessionPrx& session) : + MasterDatabaseObserverI(const shared_ptr<ReplicaSessionManager::Thread>& thread, + const shared_ptr<Database>& database, + const shared_ptr<ReplicaSessionPrx>& session) : _thread(thread), _database(database), _session(session) { } - virtual void - applicationInit(int, const ApplicationInfoSeq& applications, const Ice::Current& current) + void + applicationInit(int, ApplicationInfoSeq applications, const Ice::Current& current) override { int serial = 0; - _database->syncApplications(applications, getSerials(current.ctx, serial)); - receivedUpdate(ApplicationObserverTopicName, serial); + _database->syncApplications(move(applications), getSerials(current.ctx, serial)); + receivedUpdate(TopicName::ApplicationObserver, serial); } - virtual void - applicationAdded(int, const ApplicationInfo& application, const Ice::Current& current) + void + applicationAdded(int, ApplicationInfo application, const Ice::Current& current) override { int serial = 0; string failure; try { - _database->addApplication(application, 0, getSerials(current.ctx, serial)); + _database->addApplication(move(application), nullptr, getSerials(current.ctx, serial)); } catch(const DeploymentException& ex) { @@ -50,17 +50,17 @@ public: os << ex << ":\n" << ex.reason; failure = os.str(); } - receivedUpdate(ApplicationObserverTopicName, serial, failure); + receivedUpdate(TopicName::ApplicationObserver, serial, failure); } - virtual void - applicationRemoved(int, const std::string& name, const Ice::Current& current) + void + applicationRemoved(int, std::string name, const Ice::Current& current) override { int serial = 0; string failure; try { - _database->removeApplication(name, 0, getSerials(current.ctx, serial)); + _database->removeApplication(name, nullptr, getSerials(current.ctx, serial)); } catch(const ApplicationNotExistException& ex) { @@ -68,17 +68,17 @@ public: os << ex << ":\napplication: " << ex.name; failure = os.str(); } - receivedUpdate(ApplicationObserverTopicName, serial, failure); + receivedUpdate(TopicName::ApplicationObserver, serial, failure); } - virtual void - applicationUpdated(int, const ApplicationUpdateInfo& update, const Ice::Current& current) + void + applicationUpdated(int, ApplicationUpdateInfo update, const Ice::Current& current) override { int serial = 0; string failure; try { - _database->updateApplication(update, false, 0, getSerials(current.ctx, serial)); + _database->updateApplication(move(update), false, nullptr, getSerials(current.ctx, serial)); } catch(const DeploymentException& ex) { @@ -92,19 +92,19 @@ public: os << ex << ":\napplication: " << ex.name; failure = os.str(); } - receivedUpdate(ApplicationObserverTopicName, serial, failure); + receivedUpdate(TopicName::ApplicationObserver, serial, failure); } - virtual void - adapterInit(const AdapterInfoSeq& adapters, const Ice::Current& current) + void + adapterInit(AdapterInfoSeq adapters, const Ice::Current& current) override { int serial = 0; _database->syncAdapters(adapters, getSerials(current.ctx, serial)); - receivedUpdate(AdapterObserverTopicName, serial); + receivedUpdate(TopicName::AdapterObserver, serial); } - virtual void - adapterAdded(const AdapterInfo& info, const Ice::Current& current) + void + adapterAdded(AdapterInfo info, const Ice::Current& current) override { int serial = 0; string failure; @@ -116,11 +116,11 @@ public: { failure = "adapter `" + info.id + "' already exists and belongs to an application"; } - receivedUpdate(AdapterObserverTopicName, serial, failure); + receivedUpdate(TopicName::AdapterObserver, serial, failure); } - virtual void - adapterUpdated(const AdapterInfo& info, const Ice::Current& current) + void + adapterUpdated(AdapterInfo info, const Ice::Current& current) override { int serial = 0; string failure; @@ -132,35 +132,35 @@ public: { failure = "adapter `" + info.id + "' already exists and belongs to an application"; } - receivedUpdate(AdapterObserverTopicName, serial, failure); + receivedUpdate(TopicName::AdapterObserver, serial, failure); } - virtual void - adapterRemoved(const std::string& id, const Ice::Current& current) + void + adapterRemoved(std::string id, const Ice::Current& current) override { int serial = 0; string failure; try { - _database->setAdapterDirectProxy(id, "", 0, getSerials(current.ctx, serial)); + _database->setAdapterDirectProxy(id, "", nullptr, getSerials(current.ctx, serial)); } catch(const AdapterExistsException&) { failure = "adapter `" + id + "' already exists and belongs to an application"; } - receivedUpdate(AdapterObserverTopicName, serial, failure); + receivedUpdate(TopicName::AdapterObserver, serial, failure); } - virtual void - objectInit(const ObjectInfoSeq& objects, const Ice::Current& current) + void + objectInit(ObjectInfoSeq objects, const Ice::Current& current) override { int serial = 0; - _database->syncObjects(objects, getSerials(current.ctx, serial)); - receivedUpdate(ObjectObserverTopicName, serial); + _database->syncObjects(move(objects), getSerials(current.ctx, serial)); + receivedUpdate(TopicName::ObjectObserver, serial); } - virtual void - objectAdded(const ObjectInfo& info, const Ice::Current& current) + void + objectAdded(ObjectInfo info, const Ice::Current& current) override { int serial = 0; string failure; @@ -175,11 +175,11 @@ public: os << "id: " << _database->getCommunicator()->identityToString(info.proxy->ice_getIdentity()); failure = os.str(); } - receivedUpdate(ObjectObserverTopicName, serial, failure); + receivedUpdate(TopicName::ObjectObserver, serial, failure); } - virtual void - objectUpdated(const ObjectInfo& info, const Ice::Current& current) + void + objectUpdated(ObjectInfo info, const Ice::Current& current) override { int serial = 0; string failure; @@ -200,11 +200,11 @@ public: os << ex << ":\n" << ex.reason; failure = os.str(); } - receivedUpdate(ObjectObserverTopicName, serial, failure); + receivedUpdate(TopicName::ObjectObserver, serial, failure); } - virtual void - objectRemoved(const Ice::Identity& id, const Ice::Current& current) + void + objectRemoved(Ice::Identity id, const Ice::Current& current) override { int serial = 0; string failure; @@ -221,15 +221,15 @@ public: catch(const ObjectNotRegisteredException&) { } - receivedUpdate(ObjectObserverTopicName, serial, failure); + receivedUpdate(TopicName::ObjectObserver, serial, failure); } private: - Ice::Long + long long getSerials(const Ice::Context& context, int& serial) { - Ice::Context::const_iterator p = context.find("serial"); + auto p = context.find("serial"); if(p != context.end()) { istringstream is(p->second); @@ -243,7 +243,7 @@ private: p = context.find("dbSerial"); if(p != context.end()) { - Ice::Long dbSerial; + long long dbSerial; istringstream is(p->second); is >> dbSerial; return dbSerial; @@ -270,27 +270,22 @@ private: } } - const ReplicaSessionManager::ThreadPtr _thread; - const DatabasePtr _database; - const ReplicaSessionPrx _session; + const shared_ptr<ReplicaSessionManager::Thread> _thread; + const shared_ptr<Database> _database; + const shared_ptr<ReplicaSessionPrx> _session; }; }; -ReplicaSessionManager::ReplicaSessionManager(const Ice::CommunicatorPtr& communicator, const string& instanceName) : - SessionManager(communicator, instanceName) -{ -} - void ReplicaSessionManager::create(const string& name, - const InternalReplicaInfoPtr& info, - const DatabasePtr& database, - const WellKnownObjectsManagerPtr& wellKnownObjects, - const InternalRegistryPrx& internalRegistry) + const shared_ptr<InternalReplicaInfo>& info, + const shared_ptr<Database>& database, + const shared_ptr<WellKnownObjectsManager>& wellKnownObjects, + const shared_ptr<InternalRegistryPrx>& internalRegistry) { { - Lock sync(*this); + lock_guard lock(_mutex); _name = name; _info = info; @@ -299,9 +294,8 @@ ReplicaSessionManager::create(const string& name, _wellKnownObjects = wellKnownObjects; _traceLevels = _database->getTraceLevels(); - _thread = new Thread(*this, _master, _traceLevels->logger); - _thread->start(); - notifyAll(); + _thread = make_shared<Thread>(*this, _master, _traceLevels->logger); + _condVar.notify_all(); } _thread->tryCreateSession(); @@ -309,14 +303,13 @@ ReplicaSessionManager::create(const string& name, } void -ReplicaSessionManager::create(const InternalRegistryPrx& replica) +ReplicaSessionManager::create(const std::shared_ptr<InternalRegistryPrx>& replica) { { - Lock sync(*this); - while(!_master) // Wait to be initialized. - { - wait(); - } + unique_lock lock(_mutex); + + // Wait to be initialized. + _condVar.wait(lock, [this] { return _master; }); } if(replica->ice_getIdentity() != _master->ice_getIdentity()) @@ -354,27 +347,27 @@ ReplicaSessionManager::getNodes(const NodePrxSeq& nodes) const void ReplicaSessionManager::destroy() { - ThreadPtr thread; + shared_ptr<Thread> thread; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_communicator) { return; } thread = _thread; - _thread = 0; + _thread = nullptr; - _communicator = 0; + _communicator = nullptr; } if(thread) { thread->terminate(); - thread->getThreadControl().join(); + thread->join(); } - _database = 0; - _wellKnownObjects = 0; + _database = nullptr; + _wellKnownObjects = nullptr; } void @@ -392,7 +385,7 @@ ReplicaSessionManager::registerAllWellKnownObjects() // If there's an active session, register the well-known objects // with the session. // - ReplicaSessionPrx session = _thread->getSession(); + auto session = _thread->getSession(); if(session) { try @@ -406,33 +399,31 @@ ReplicaSessionManager::registerAllWellKnownObjects() } } -IceGrid::InternalRegistryPrx +shared_ptr<InternalRegistryPrx> ReplicaSessionManager::findInternalRegistryForReplica(const Ice::Identity& id) { - vector<Ice::AsyncResultPtr> results; - vector<QueryPrx> queryObjects = findAllQueryObjects(true); - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector<future<shared_ptr<Ice::ObjectPrx>>> results; + for(const auto& obj : findAllQueryObjects(true)) { - results.push_back((*q)->begin_findObjectById(id)); + results.push_back(obj->findObjectByIdAsync(id)); } - for(vector<Ice::AsyncResultPtr>::const_iterator p = results.begin(); p != results.end(); ++p) + for(auto& result : results) { - QueryPrx query = QueryPrx::uncheckedCast((*p)->getProxy()); try { - return InternalRegistryPrx::checkedCast(query->end_findObjectById(*p)); + return Ice::checkedCast<InternalRegistryPrx>(result.get()); } catch(const Ice::Exception&) { } } - return 0; + return nullptr; } bool -ReplicaSessionManager::keepAlive(const ReplicaSessionPrx& session) +ReplicaSessionManager::keepAlive(const shared_ptr<ReplicaSessionPrx>& session) { try { @@ -456,11 +447,11 @@ ReplicaSessionManager::keepAlive(const ReplicaSessionPrx& session) } } -ReplicaSessionPrx -ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Time& timeout) +shared_ptr<ReplicaSessionPrx> +ReplicaSessionManager::createSession(shared_ptr<InternalRegistryPrx>& registry, chrono::seconds& timeout) { - ReplicaSessionPrx session; - IceInternal::UniquePtr<Ice::Exception> exception; + shared_ptr<ReplicaSessionPrx> session; + string exceptionMsg = ""; try { if(_traceLevels && _traceLevels->replica > 1) @@ -469,7 +460,7 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim out << "trying to establish session with master replica"; } - set<InternalRegistryPrx> used; + set<shared_ptr<InternalRegistryPrx>> used; if(!registry->ice_getEndpoints().empty()) { try @@ -478,34 +469,32 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim } catch(const Ice::LocalException& ex) { - exception.reset(ex.ice_clone()); + exceptionMsg = ex.what(); used.insert(registry); - registry = InternalRegistryPrx::uncheckedCast(registry->ice_endpoints(Ice::EndpointSeq())); + registry = Ice::uncheckedCast<InternalRegistryPrx>(registry->ice_endpoints({})); } } if(!session) { - vector<Ice::AsyncResultPtr> results; - vector<QueryPrx> queryObjects = findAllQueryObjects(false); - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector<future<shared_ptr<Ice::ObjectPrx>>> results; + for(const auto& obj : findAllQueryObjects(false)) { - results.push_back((*q)->begin_findObjectById(registry->ice_getIdentity())); + results.push_back(obj->findObjectByIdAsync(registry->ice_getIdentity())); } - for(vector<Ice::AsyncResultPtr>::const_iterator p = results.begin(); p != results.end(); ++p) + for(auto& result : results) { - QueryPrx query = QueryPrx::uncheckedCast((*p)->getProxy()); if(isDestroyed()) { break; } - InternalRegistryPrx newRegistry; + shared_ptr<InternalRegistryPrx> newRegistry; try { - Ice::ObjectPrx obj = query->end_findObjectById(*p); - newRegistry = InternalRegistryPrx::uncheckedCast(obj); + auto obj = result.get(); + newRegistry = Ice::uncheckedCast<InternalRegistryPrx>(obj); if(newRegistry && used.find(newRegistry) == used.end()) { session = createSessionImpl(newRegistry, timeout); @@ -515,7 +504,7 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim } catch(const Ice::LocalException& ex) { - exception.reset(ex.ice_clone()); + exceptionMsg = ex.what(); if(newRegistry) { used.insert(newRegistry); @@ -530,7 +519,7 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim { _traceLevels->logger->error("a replica with the same name is already registered and active"); } - exception.reset(ex.ice_clone()); + exceptionMsg = ex.what(); } catch(const DeploymentException& ex) { @@ -538,7 +527,7 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim { _traceLevels->logger->error("database synchronization with master failed:\n" + ex.reason); } - exception.reset(ex.ice_clone()); + exceptionMsg = ex.what(); } catch(const PermissionDeniedException& ex) { @@ -546,11 +535,11 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim { _traceLevels->logger->error("connection to master was denied:\n" + ex.reason); } - exception.reset(ex.ice_clone()); + exceptionMsg = ex.what(); } catch(const Ice::Exception& ex) { - exception.reset(ex.ice_clone()); + exceptionMsg = ex.what(); } if(session) @@ -578,30 +567,30 @@ ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Tim else { out << "failed to establish session with master replica:\n"; - if(exception.get()) + if(exceptionMsg.empty()) { - out << *exception.get(); + out << "failed to get replica proxy"; } else { - out << "failed to get replica proxy"; + out << exceptionMsg; } } } return session; } -ReplicaSessionPrx -ReplicaSessionManager::createSessionImpl(const InternalRegistryPrx& registry, IceUtil::Time& timeout) +shared_ptr<ReplicaSessionPrx> +ReplicaSessionManager::createSessionImpl(const shared_ptr<InternalRegistryPrx>& registry, chrono::seconds& timeout) { - ReplicaSessionPrx session; + shared_ptr<ReplicaSessionPrx> session; try { session = registry->registerReplica(_info, _internalRegistry); - int t = session->getTimeout(); + auto t = session->getTimeout(); if(t > 0) { - timeout = IceUtil::Time::seconds(t / 2); + timeout = chrono::seconds(t / 2); } // @@ -609,8 +598,8 @@ ReplicaSessionManager::createSessionImpl(const InternalRegistryPrx& registry, Ic // to the session so that it can subscribe it. This call only // returns once the observer is subscribed and initialized. // - DatabaseObserverPtr servant = new MasterDatabaseObserverI(_thread, _database, session); - _observer = DatabaseObserverPrx::uncheckedCast(_database->getInternalAdapter()->addWithUUID(servant)); + auto servant = make_shared<MasterDatabaseObserverI>(_thread, _database, session); + _observer = Ice::uncheckedCast<DatabaseObserverPrx>(_database->getInternalAdapter()->addWithUUID(servant)); StringLongDict serials = _database->getSerials(); IceUtil::Optional<StringLongDict> serialsOpt; if(!serials.empty()) @@ -628,7 +617,7 @@ ReplicaSessionManager::createSessionImpl(const InternalRegistryPrx& registry, Ic } void -ReplicaSessionManager::destroySession(const ReplicaSessionPrx& session) +ReplicaSessionManager::destroySession(const shared_ptr<ReplicaSessionPrx>& session) { if(session) { @@ -661,6 +650,6 @@ ReplicaSessionManager::destroySession(const ReplicaSessionPrx& session) catch(const Ice::LocalException&) { } - _observer = 0; + _observer = nullptr; } } diff --git a/cpp/src/IceGrid/ReplicaSessionManager.h b/cpp/src/IceGrid/ReplicaSessionManager.h index 9203bf49d87..de781b9c233 100644 --- a/cpp/src/IceGrid/ReplicaSessionManager.h +++ b/cpp/src/IceGrid/ReplicaSessionManager.h @@ -16,13 +16,8 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle<WellKnownObjectsManager> WellKnownObjectsManagerPtr; - class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; +class WellKnownObjectsManager; class ReplicaSessionManager : public SessionManager { @@ -32,26 +27,27 @@ public: { public: - Thread(ReplicaSessionManager& manager, const InternalRegistryPrx& master, const Ice::LoggerPtr& logger) : + Thread(ReplicaSessionManager& manager, const std::shared_ptr<InternalRegistryPrx>& master, + const std::shared_ptr<Ice::Logger>& logger) : SessionKeepAliveThread<ReplicaSessionPrx>(master, logger), _manager(manager) { } - virtual ReplicaSessionPrx - createSession(InternalRegistryPrx& master, IceUtil::Time& timeout) + std::shared_ptr<ReplicaSessionPrx> + createSession(std::shared_ptr<InternalRegistryPrx>& master, std::chrono::seconds& timeout) override { return _manager.createSession(master, timeout); } - virtual void - destroySession(const ReplicaSessionPrx& session) + void + destroySession(const std::shared_ptr<ReplicaSessionPrx>& session) override { _manager.destroySession(session); } - virtual bool - keepAlive(const ReplicaSessionPrx& session) + bool + keepAlive(const std::shared_ptr<ReplicaSessionPrx>& session) override { return _manager.keepAlive(session); } @@ -62,19 +58,20 @@ public: ReplicaSessionManager& _manager; }; - typedef IceUtil::Handle<Thread> ThreadPtr; - ReplicaSessionManager(const Ice::CommunicatorPtr&, const std::string&); - void create(const std::string&, const InternalReplicaInfoPtr&, const DatabasePtr&, - const WellKnownObjectsManagerPtr&, const InternalRegistryPrx&); - void create(const InternalRegistryPrx&); + using SessionManager::SessionManager; + + void create(const std::string&, const std::shared_ptr<InternalReplicaInfo>&, const std::shared_ptr<Database>&, + const std::shared_ptr<WellKnownObjectsManager>&, const std::shared_ptr<InternalRegistryPrx>&); + void create(const std::shared_ptr<InternalRegistryPrx>&); + NodePrxSeq getNodes(const NodePrxSeq&) const; void destroy(); void registerAllWellKnownObjects(); - ReplicaSessionPrx getSession() const { return _thread ? _thread->getSession() : ReplicaSessionPrx(); } + std::shared_ptr<ReplicaSessionPrx> getSession() const { return _thread ? _thread->getSession() : nullptr; } - IceGrid::InternalRegistryPrx findInternalRegistryForReplica(const Ice::Identity&); + std::shared_ptr<InternalRegistryPrx> findInternalRegistryForReplica(const Ice::Identity&); private: @@ -82,24 +79,24 @@ private: bool isDestroyed() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); return !_communicator; } - ReplicaSessionPrx createSession(InternalRegistryPrx&, IceUtil::Time&); - ReplicaSessionPrx createSessionImpl(const InternalRegistryPrx&, IceUtil::Time&); - void destroySession(const ReplicaSessionPrx&); - bool keepAlive(const ReplicaSessionPrx&); + std::shared_ptr<ReplicaSessionPrx> createSession(std::shared_ptr<InternalRegistryPrx>&, std::chrono::seconds&); + std::shared_ptr<ReplicaSessionPrx> createSessionImpl(const std::shared_ptr<InternalRegistryPrx>&, std::chrono::seconds&); + void destroySession(const std::shared_ptr<ReplicaSessionPrx>&); + bool keepAlive(const std::shared_ptr<ReplicaSessionPrx>&); - ThreadPtr _thread; + std::shared_ptr<Thread> _thread; std::string _name; - InternalReplicaInfoPtr _info; - RegistryPrx _registry; - InternalRegistryPrx _internalRegistry; - DatabaseObserverPrx _observer; - DatabasePtr _database; - WellKnownObjectsManagerPtr _wellKnownObjects; - TraceLevelsPtr _traceLevels; + std::shared_ptr<InternalReplicaInfo> _info; + std::shared_ptr<RegistryPrx> _registry; + std::shared_ptr<InternalRegistryPrx> _internalRegistry; + std::shared_ptr<DatabaseObserverPrx> _observer; + std::shared_ptr<Database> _database; + std::shared_ptr<WellKnownObjectsManager> _wellKnownObjects; + std::shared_ptr<TraceLevels> _traceLevels; }; } diff --git a/cpp/src/IceGrid/Scanner.cpp b/cpp/src/IceGrid/Scanner.cpp index 2c831ddb927..7250014a61b 100644 --- a/cpp/src/IceGrid/Scanner.cpp +++ b/cpp/src/IceGrid/Scanner.cpp @@ -1,7 +1,12 @@ #include <IceUtil/ScannerConfig.h> -#line 2 "src/IceGrid/Scanner.cpp" +#line 1 "src/IceGrid/Scanner.cpp" +// +// Copyright (c) ZeroC, Inc. All rights reserved. +// + +#include <IceUtil/ScannerConfig.h> -#line 4 "src/IceGrid/Scanner.cpp" +#line 8 "src/IceGrid/Scanner.cpp" #define YY_INT_ALIGNED short int @@ -9,8 +14,8 @@ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 -#define YY_FLEX_SUBMINOR_VERSION 35 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif @@ -87,63 +92,61 @@ typedef unsigned int flex_uint32_t; #define UINT32_MAX (4294967295U) #endif -#endif /* ! FLEXINT_H */ - -#ifdef __cplusplus - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ +#ifndef SIZE_MAX +#define SIZE_MAX (~(size_t)0) +#endif -/* C99 requires __STDC__ to be defined as 1. */ -#if defined (__STDC__) +#endif /* ! C99 */ -#define YY_USE_CONST +#endif /* ! FLEXINT_H */ -#endif /* defined (__STDC__) */ -#endif /* ! __cplusplus */ +/* begin standard C++ headers. */ -#ifdef YY_USE_CONST +/* TODO: this is always defined, so inline it */ #define yyconst const + +#if defined(__GNUC__) && __GNUC__ >= 3 +#define yynoreturn __attribute__((__noreturn__)) #else -#define yyconst +#define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. +/* Promotes a possibly negative, possibly signed char to an + * integer in range [0..255] for use as an array index. */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) +#define YY_SC_TO_UI(c) ((YY_CHAR) (c)) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * - /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START - /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - /* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart(yyin ) - +#define YY_NEW_FILE yyrestart( yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else #define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. @@ -160,15 +163,16 @@ typedef struct yy_buffer_state *YY_BUFFER_STATE; typedef size_t yy_size_t; #endif -extern yy_size_t yyleng; +extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 - + #define YY_LESS_LINENO(n) + #define YY_LINENO_REWIND_TO(ptr) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ @@ -183,7 +187,6 @@ extern FILE *yyin, *yyout; YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) - #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE @@ -198,12 +201,12 @@ struct yy_buffer_state /* Size of input buffer in bytes, not including room for EOB * characters. */ - yy_size_t yy_buf_size; + int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ - yy_size_t yy_n_chars; + int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to @@ -226,7 +229,7 @@ struct yy_buffer_state int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ - + /* Whether to try to fill the input buffer when we reach the * end of it. */ @@ -254,7 +257,7 @@ struct yy_buffer_state /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ -static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ +static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general @@ -265,7 +268,6 @@ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) - /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ @@ -273,11 +275,11 @@ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; -static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */ -yy_size_t yyleng; +static int yy_n_chars; /* number of characters read into yy_ch_buf */ +int yyleng; /* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; +static char *yy_c_buf_p = NULL; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ @@ -286,85 +288,81 @@ static int yy_start = 0; /* start state number */ */ static int yy_did_buffer_switch_on_eof; -void yyrestart (FILE *input_file ); -void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); -YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); -void yy_delete_buffer (YY_BUFFER_STATE b ); -void yy_flush_buffer (YY_BUFFER_STATE b ); -void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); -void yypop_buffer_state (void ); - -static void yyensure_buffer_stack (void ); -static void yy_load_buffer_state (void ); -static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); +void yyrestart ( FILE *input_file ); +void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ); +YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size ); +void yy_delete_buffer ( YY_BUFFER_STATE b ); +void yy_flush_buffer ( YY_BUFFER_STATE b ); +void yypush_buffer_state ( YY_BUFFER_STATE new_buffer ); +void yypop_buffer_state ( void ); -#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) +static void yyensure_buffer_stack ( void ); +static void yy_load_buffer_state ( void ); +static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file ); +#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER ) -YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); -YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); -YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ); +YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size ); +YY_BUFFER_STATE yy_scan_string ( const char *yy_str ); +YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len ); -void *yyalloc (yy_size_t ); -void *yyrealloc (void *,yy_size_t ); -void yyfree (void * ); +void *yyalloc ( yy_size_t ); +void *yyrealloc ( void *, yy_size_t ); +void yyfree ( void * ); #define yy_new_buffer yy_create_buffer - #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ - yy_create_buffer(yyin,YY_BUF_SIZE ); \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } - #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ - yy_create_buffer(yyin,YY_BUF_SIZE ); \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } - #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ -#define yywrap(n) 1 +#define yywrap() (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP +typedef flex_uint8_t YY_CHAR; -typedef unsigned char YY_CHAR; - -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; +FILE *yyin = NULL, *yyout = NULL; typedef int yy_state_type; extern int yylineno; - int yylineno = 1; extern char *yytext; +#ifdef yytext_ptr +#undef yytext_ptr +#endif #define yytext_ptr yytext -static yy_state_type yy_get_previous_state (void ); -static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); -static int yy_get_next_buffer (void ); -static void yy_fatal_error (yyconst char msg[] ); +static yy_state_type yy_get_previous_state ( void ); +static yy_state_type yy_try_NUL_trans ( yy_state_type current_state ); +static int yy_get_next_buffer ( void ); +static void yynoreturn yy_fatal_error ( const char* msg ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ - yyleng = (yy_size_t) (yy_cp - yy_bp); \ + yyleng = (int) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; - #define YY_NUM_RULES 8 #define YY_END_OF_BUFFER 9 /* This struct is not used in this scanner, @@ -374,13 +372,13 @@ struct yy_trans_info flex_int32_t yy_verify; flex_int32_t yy_nxt; }; -static yyconst flex_int16_t yy_accept[19] = +static const flex_int16_t yy_accept[19] = { 0, 3, 3, 9, 7, 3, 4, 5, 6, 7, 4, 7, 3, 0, 2, 1, 0, 3, 0 } ; -static yyconst flex_int32_t yy_ec[256] = +static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, @@ -412,24 +410,24 @@ static yyconst flex_int32_t yy_ec[256] = 1, 1, 1, 1, 1 } ; -static yyconst flex_int32_t yy_meta[10] = +static const YY_CHAR yy_meta[10] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; -static yyconst flex_int16_t yy_base[19] = +static const flex_int16_t yy_base[19] = { 0, 0, 0, 11, 22, 8, 22, 22, 22, 12, 22, 18, 0, 0, 22, 22, 0, 22, 22 } ; -static yyconst flex_int16_t yy_def[19] = +static const flex_int16_t yy_def[19] = { 0, 18, 1, 18, 18, 18, 18, 18, 18, 18, 18, 18, 5, 11, 18, 18, 11, 18, 0 } ; -static yyconst flex_int16_t yy_nxt[32] = +static const flex_int16_t yy_nxt[32] = { 0, 4, 5, 6, 7, 8, 4, 9, 10, 11, 12, 18, 18, 18, 18, 18, 18, 13, 14, 15, 16, @@ -437,7 +435,7 @@ static yyconst flex_int16_t yy_nxt[32] = 18 } ; -static yyconst flex_int16_t yy_chk[32] = +static const flex_int16_t yy_chk[32] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 3, 0, 0, 0, 0, 0, 5, 9, 9, 11, @@ -460,35 +458,13 @@ int yy_flex_debug = 0; #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "src/IceGrid/Scanner.l" -#line 2 "src/IceGrid/Scanner.l" -// -// Copyright (c) ZeroC, Inc. All rights reserved. -// +#line 11 "src/IceGrid/Scanner.l" #include <Ice/Ice.h> #include <IceGrid/Parser.h> #include <IceGrid/Grammar.h> -#if defined(_MSC_VER) -// '<' : signed/unsigned mismatch -# pragma warning(disable:4018) -// 'initializing' : conversion from '__int64' to 'int', possible loss of data -# pragma warning(disable:4244) - -# if defined(ICE_64) -// -// '=' : conversion from 'size_t' to 'int', possible loss of data -// The result of fread() is a size_t and gets inserted into an int -// -# pragma warning(disable:4267) -# endif -#endif - -#if defined(__GNUC__) -# pragma GCC diagnostic ignored "-Wsign-compare" -#endif - using namespace std; using namespace Ice; using namespace IceGrid; @@ -498,17 +474,6 @@ using namespace IceGrid; # undef yywrap # define yywrap() 1 # endif -# define YY_NO_UNISTD_H -#endif - -#ifdef __SUNPRO_CC -# ifdef yywrap -# undef yywrap -# define yywrap() 1 -# endif -# ifdef ICE_64 -# pragma error_messages(off,truncwarn) -# endif #endif #define YY_INPUT(buf, result, maxSize) parser->getInput(buf, result, maxSize) @@ -516,8 +481,7 @@ using namespace IceGrid; namespace IceGrid { -typedef std::map<std::string, int> StringTokenMap; -static StringTokenMap keywordMap; +static std::map<std::string, int> keywordMap; void initScanner(); std::string parseDoubleQuotedString(); @@ -526,7 +490,8 @@ std::string parseSingleQuotedString(); } #define YY_USER_INIT initScanner(); -#line 529 "src/IceGrid/Scanner.cpp" +#line 490 "src/IceGrid/Scanner.cpp" +#line 491 "src/IceGrid/Scanner.cpp" #define INITIAL 0 @@ -542,36 +507,36 @@ std::string parseSingleQuotedString(); #define YY_EXTRA_TYPE void * #endif -static int yy_init_globals (void ); +static int yy_init_globals ( void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ -int yylex_destroy (void ); +int yylex_destroy ( void ); -int yyget_debug (void ); +int yyget_debug ( void ); -void yyset_debug (int debug_flag ); +void yyset_debug ( int debug_flag ); -YY_EXTRA_TYPE yyget_extra (void ); +YY_EXTRA_TYPE yyget_extra ( void ); -void yyset_extra (YY_EXTRA_TYPE user_defined ); +void yyset_extra ( YY_EXTRA_TYPE user_defined ); -FILE *yyget_in (void ); +FILE *yyget_in ( void ); -void yyset_in (FILE * in_str ); +void yyset_in ( FILE * _in_str ); -FILE *yyget_out (void ); +FILE *yyget_out ( void ); -void yyset_out (FILE * out_str ); +void yyset_out ( FILE * _out_str ); -yy_size_t yyget_leng (void ); + int yyget_leng ( void ); -char *yyget_text (void ); +char *yyget_text ( void ); -int yyget_lineno (void ); +int yyget_lineno ( void ); -void yyset_lineno (int line_number ); +void yyset_lineno ( int _line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. @@ -579,35 +544,43 @@ void yyset_lineno (int line_number ); #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus -extern "C" int yywrap (void ); +extern "C" int yywrap ( void ); #else -extern int yywrap (void ); +extern int yywrap ( void ); #endif #endif - static void yyunput (int c,char *buf_ptr ); +#ifndef YY_NO_UNPUT + static void yyunput ( int c, char *buf_ptr ); + +#endif + #ifndef yytext_ptr -static void yy_flex_strncpy (char *,yyconst char *,int ); +static void yy_flex_strncpy ( char *, const char *, int ); #endif #ifdef YY_NEED_STRLEN -static int yy_flex_strlen (yyconst char * ); +static int yy_flex_strlen ( const char * ); #endif #ifndef YY_NO_INPUT - #ifdef __cplusplus -static int yyinput (void ); +static int yyinput ( void ); #else -static int input (void ); +static int input ( void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else #define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ @@ -615,7 +588,7 @@ static int input (void ); /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ -#define ECHO fwrite( yytext, yyleng, 1, yyout ) +#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, @@ -626,7 +599,7 @@ static int input (void ); if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ - yy_size_t n; \ + int n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ @@ -639,7 +612,7 @@ static int input (void ); else \ { \ errno=0; \ - while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ + while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ @@ -694,7 +667,7 @@ extern int yylex (void); /* Code executed at the end of each rule. */ #ifndef YY_BREAK -#define YY_BREAK break; +#define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ @@ -704,15 +677,10 @@ extern int yylex (void); */ YY_DECL { - register yy_state_type yy_current_state; - register char *yy_cp, *yy_bp; - register int yy_act; + yy_state_type yy_current_state; + char *yy_cp, *yy_bp; + int yy_act; -#line 76 "src/IceGrid/Scanner.l" - - -#line 714 "src/IceGrid/Scanner.cpp" - if ( !(yy_init) ) { (yy_init) = 1; @@ -733,13 +701,19 @@ YY_DECL if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = - yy_create_buffer(yyin,YY_BUF_SIZE ); + yy_create_buffer( yyin, YY_BUF_SIZE ); } - yy_load_buffer_state( ); + yy_load_buffer_state( ); } - while ( 1 ) /* loops until end-of-file is reached */ + { +#line 50 "src/IceGrid/Scanner.l" + + +#line 711 "src/IceGrid/Scanner.cpp" + + while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); @@ -755,7 +729,7 @@ YY_DECL yy_match: do { - register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; + YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; @@ -765,9 +739,9 @@ yy_match: { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 19 ) - yy_c = yy_meta[(unsigned int) yy_c]; + yy_c = yy_meta[yy_c]; } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 22 ); @@ -796,7 +770,7 @@ do_action: /* This label is used only to access EOF actions. */ case 1: YY_RULE_SETUP -#line 78 "src/IceGrid/Scanner.l" +#line 52 "src/IceGrid/Scanner.l" { // C++-style comment int c; @@ -809,7 +783,7 @@ YY_RULE_SETUP YY_BREAK case 2: YY_RULE_SETUP -#line 88 "src/IceGrid/Scanner.l" +#line 62 "src/IceGrid/Scanner.l" { // C-style comment while(true) @@ -838,7 +812,7 @@ YY_RULE_SETUP case 3: /* rule 3 can match eol */ YY_RULE_SETUP -#line 113 "src/IceGrid/Scanner.l" +#line 87 "src/IceGrid/Scanner.l" { size_t len = strlen(yytext); for(size_t i = 0; i < len; ++i) @@ -853,14 +827,14 @@ YY_RULE_SETUP case 4: /* rule 4 can match eol */ YY_RULE_SETUP -#line 124 "src/IceGrid/Scanner.l" +#line 98 "src/IceGrid/Scanner.l" { return ';'; } YY_BREAK case 5: YY_RULE_SETUP -#line 128 "src/IceGrid/Scanner.l" +#line 102 "src/IceGrid/Scanner.l" { // "..."-type strings string s = parseDoubleQuotedString(); @@ -871,7 +845,7 @@ YY_RULE_SETUP YY_BREAK case 6: YY_RULE_SETUP -#line 136 "src/IceGrid/Scanner.l" +#line 110 "src/IceGrid/Scanner.l" { // '...'-type strings string s; @@ -899,7 +873,7 @@ YY_RULE_SETUP YY_BREAK case 7: YY_RULE_SETUP -#line 161 "src/IceGrid/Scanner.l" +#line 135 "src/IceGrid/Scanner.l" { // Simple strings string s; @@ -932,16 +906,16 @@ YY_RULE_SETUP yylvalp->clear(); yylvalp->push_back(s); - StringTokenMap::const_iterator pos = keywordMap.find(s); + const auto pos = keywordMap.find(s); return pos != keywordMap.end() ? pos->second : ICE_GRID_STRING; } YY_BREAK case 8: YY_RULE_SETUP -#line 197 "src/IceGrid/Scanner.l" +#line 171 "src/IceGrid/Scanner.l" ECHO; YY_BREAK -#line 944 "src/IceGrid/Scanner.cpp" +#line 915 "src/IceGrid/Scanner.cpp" case YY_STATE_EOF(INITIAL): yyterminate(); @@ -1019,7 +993,7 @@ case YY_STATE_EOF(INITIAL): { (yy_did_buffer_switch_on_eof) = 0; - if ( yywrap( ) ) + if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up @@ -1072,6 +1046,7 @@ case YY_STATE_EOF(INITIAL): "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ + } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer @@ -1083,9 +1058,9 @@ case YY_STATE_EOF(INITIAL): */ static int yy_get_next_buffer (void) { - register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; - register char *source = (yytext_ptr); - register int number_to_move, i; + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *source = (yytext_ptr); + int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) @@ -1114,7 +1089,7 @@ static int yy_get_next_buffer (void) /* Try to read more data. */ /* First move last chars to start of buffer. */ - number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; + number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1); for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); @@ -1127,7 +1102,7 @@ static int yy_get_next_buffer (void) else { - yy_size_t num_to_read = + int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) @@ -1141,7 +1116,7 @@ static int yy_get_next_buffer (void) if ( b->yy_is_our_buffer ) { - yy_size_t new_size = b->yy_buf_size * 2; + int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; @@ -1150,11 +1125,12 @@ static int yy_get_next_buffer (void) b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ - yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); + yyrealloc( (void *) b->yy_ch_buf, + (yy_size_t) (b->yy_buf_size + 2) ); } else /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; + b->yy_ch_buf = NULL; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( @@ -1182,7 +1158,7 @@ static int yy_get_next_buffer (void) if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; - yyrestart(yyin ); + yyrestart( yyin ); } else @@ -1196,12 +1172,15 @@ static int yy_get_next_buffer (void) else ret_val = EOB_ACT_CONTINUE_SCAN; - if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { + if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ - yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); + int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( + (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); + /* "- 2" to take care of EOB's */ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); } (yy_n_chars) += number_to_move; @@ -1217,14 +1196,14 @@ static int yy_get_next_buffer (void) static yy_state_type yy_get_previous_state (void) { - register yy_state_type yy_current_state; - register char *yy_cp; + yy_state_type yy_current_state; + char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { - register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; @@ -1234,9 +1213,9 @@ static int yy_get_next_buffer (void) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 19 ) - yy_c = yy_meta[(unsigned int) yy_c]; + yy_c = yy_meta[yy_c]; } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; @@ -1249,10 +1228,10 @@ static int yy_get_next_buffer (void) */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { - register int yy_is_jam; - register char *yy_cp = (yy_c_buf_p); + int yy_is_jam; + char *yy_cp = (yy_c_buf_p); - register YY_CHAR yy_c = 1; + YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; @@ -1262,17 +1241,19 @@ static int yy_get_next_buffer (void) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 19 ) - yy_c = yy_meta[(unsigned int) yy_c]; + yy_c = yy_meta[yy_c]; } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 18); return yy_is_jam ? 0 : yy_current_state; } - static void yyunput (int c, register char * yy_bp ) +#ifndef YY_NO_UNPUT + + static void yyunput (int c, char * yy_bp ) { - register char *yy_cp; + char *yy_cp; yy_cp = (yy_c_buf_p); @@ -1282,10 +1263,10 @@ static int yy_get_next_buffer (void) if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ - register yy_size_t number_to_move = (yy_n_chars) + 2; - register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ + int number_to_move = (yy_n_chars) + 2; + char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; - register char *source = + char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) @@ -1294,7 +1275,7 @@ static int yy_get_next_buffer (void) yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = - (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; + (yy_n_chars) = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); @@ -1307,6 +1288,8 @@ static int yy_get_next_buffer (void) (yy_c_buf_p) = yy_cp; } +#endif + #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) @@ -1331,7 +1314,7 @@ static int yy_get_next_buffer (void) else { /* need more input */ - yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); + int offset = (int) ((yy_c_buf_p) - (yytext_ptr)); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) @@ -1348,13 +1331,13 @@ static int yy_get_next_buffer (void) */ /* Reset buffer status. */ - yyrestart(yyin ); + yyrestart( yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { - if ( yywrap( ) ) + if ( yywrap( ) ) return 0; if ( ! (yy_did_buffer_switch_on_eof) ) @@ -1392,11 +1375,11 @@ static int yy_get_next_buffer (void) if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = - yy_create_buffer(yyin,YY_BUF_SIZE ); + yy_create_buffer( yyin, YY_BUF_SIZE ); } - yy_init_buffer(YY_CURRENT_BUFFER,input_file ); - yy_load_buffer_state( ); + yy_init_buffer( YY_CURRENT_BUFFER, input_file ); + yy_load_buffer_state( ); } /** Switch to a different input buffer. @@ -1424,7 +1407,7 @@ static int yy_get_next_buffer (void) } YY_CURRENT_BUFFER_LVALUE = new_buffer; - yy_load_buffer_state( ); + yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag @@ -1452,7 +1435,7 @@ static void yy_load_buffer_state (void) { YY_BUFFER_STATE b; - b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); @@ -1461,13 +1444,13 @@ static void yy_load_buffer_state (void) /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ - b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); + b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; - yy_init_buffer(b,file ); + yy_init_buffer( b, file ); return b; } @@ -1486,9 +1469,9 @@ static void yy_load_buffer_state (void) YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) - yyfree((void *) b->yy_ch_buf ); + yyfree( (void *) b->yy_ch_buf ); - yyfree((void *) b ); + yyfree( (void *) b ); } /* Initializes or reinitializes a buffer. @@ -1500,7 +1483,7 @@ static void yy_load_buffer_state (void) { int oerrno = errno; - yy_flush_buffer(b ); + yy_flush_buffer( b ); b->yy_input_file = file; b->yy_fill_buffer = 1; @@ -1543,7 +1526,7 @@ static void yy_load_buffer_state (void) b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) - yy_load_buffer_state( ); + yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes @@ -1574,7 +1557,7 @@ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ - yy_load_buffer_state( ); + yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } @@ -1593,7 +1576,7 @@ void yypop_buffer_state (void) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { - yy_load_buffer_state( ); + yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } @@ -1611,15 +1594,15 @@ static void yyensure_buffer_stack (void) * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ - num_to_alloc = 1; + num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); - + memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); - + (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; @@ -1628,7 +1611,7 @@ static void yyensure_buffer_stack (void) if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ - int grow_size = 8 /* arbitrary grow size */; + yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc @@ -1648,7 +1631,7 @@ static void yyensure_buffer_stack (void) * @param base the character buffer * @param size the size in bytes of the character buffer * - * @return the newly allocated buffer state object. + * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { @@ -1658,23 +1641,23 @@ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ - return 0; + return NULL; - b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; - b->yy_input_file = 0; + b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; - yy_switch_to_buffer(b ); + yy_switch_to_buffer( b ); return b; } @@ -1687,10 +1670,10 @@ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ -YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) +YY_BUFFER_STATE yy_scan_string (const char * yystr ) { - return yy_scan_bytes(yystr,strlen(yystr) ); + return yy_scan_bytes( yystr, (int) strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will @@ -1700,15 +1683,15 @@ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) * * @return the newly allocated buffer state object. */ -YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len ) +YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ - n = _yybytes_len + 2; - buf = (char *) yyalloc(n ); + n = (yy_size_t) (_yybytes_len + 2); + buf = (char *) yyalloc( n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); @@ -1717,7 +1700,7 @@ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; - b = yy_scan_buffer(buf,n ); + b = yy_scan_buffer( buf, n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); @@ -1733,9 +1716,9 @@ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len #define YY_EXIT_FAILURE 2 #endif -static void yy_fatal_error (yyconst char* msg ) +static void yynoreturn yy_fatal_error (const char* msg ) { - (void) fprintf( stderr, "%s\n", msg ); + fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } @@ -1763,7 +1746,7 @@ static void yy_fatal_error (yyconst char* msg ) */ int yyget_lineno (void) { - + return yylineno; } @@ -1786,7 +1769,7 @@ FILE *yyget_out (void) /** Get the length of the current token. * */ -yy_size_t yyget_leng (void) +int yyget_leng (void) { return yyleng; } @@ -1801,29 +1784,29 @@ char *yyget_text (void) } /** Set the current line number. - * @param line_number + * @param _line_number line number * */ -void yyset_lineno (int line_number ) +void yyset_lineno (int _line_number ) { - yylineno = line_number; + yylineno = _line_number; } /** Set the input stream. This does not discard the current * input buffer. - * @param in_str A readable stream. + * @param _in_str A readable stream. * * @see yy_switch_to_buffer */ -void yyset_in (FILE * in_str ) +void yyset_in (FILE * _in_str ) { - yyin = in_str ; + yyin = _in_str ; } -void yyset_out (FILE * out_str ) +void yyset_out (FILE * _out_str ) { - yyout = out_str ; + yyout = _out_str ; } int yyget_debug (void) @@ -1831,9 +1814,9 @@ int yyget_debug (void) return yy_flex_debug; } -void yyset_debug (int bdebug ) +void yyset_debug (int _bdebug ) { - yy_flex_debug = bdebug ; + yy_flex_debug = _bdebug ; } static int yy_init_globals (void) @@ -1842,10 +1825,10 @@ static int yy_init_globals (void) * This function is called from yylex_destroy(), so don't allocate here. */ - (yy_buffer_stack) = 0; + (yy_buffer_stack) = NULL; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; - (yy_c_buf_p) = (char *) 0; + (yy_c_buf_p) = NULL; (yy_init) = 0; (yy_start) = 0; @@ -1854,8 +1837,8 @@ static int yy_init_globals (void) yyin = stdin; yyout = stdout; #else - yyin = (FILE *) 0; - yyout = (FILE *) 0; + yyin = NULL; + yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by @@ -1870,7 +1853,7 @@ int yylex_destroy (void) /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ - yy_delete_buffer(YY_CURRENT_BUFFER ); + yy_delete_buffer( YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } @@ -1891,18 +1874,19 @@ int yylex_destroy (void) */ #ifndef yytext_ptr -static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) +static void yy_flex_strncpy (char* s1, const char * s2, int n ) { - register int i; + + int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN -static int yy_flex_strlen (yyconst char * s ) +static int yy_flex_strlen (const char * s ) { - register int n; + int n; for ( n = 0; s[n]; ++n ) ; @@ -1912,11 +1896,12 @@ static int yy_flex_strlen (yyconst char * s ) void *yyalloc (yy_size_t size ) { - return (void *) malloc( size ); + return malloc(size); } void *yyrealloc (void * ptr, yy_size_t size ) { + /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter @@ -1924,18 +1909,17 @@ void *yyrealloc (void * ptr, yy_size_t size ) * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ - return (void *) realloc( (char *) ptr, size ); + return realloc(ptr, size); } void yyfree (void * ptr ) { - free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ + free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" -#line 197 "src/IceGrid/Scanner.l" - +#line 171 "src/IceGrid/Scanner.l" namespace IceGrid { @@ -1947,46 +1931,48 @@ namespace IceGrid { void initScanner() { - keywordMap["help"] = ICE_GRID_HELP; - keywordMap["quit"] = ICE_GRID_EXIT; - keywordMap["exit"] = ICE_GRID_EXIT; - keywordMap["application"] = ICE_GRID_APPLICATION; - keywordMap["server"] = ICE_GRID_SERVER; - keywordMap["adapter"] = ICE_GRID_ADAPTER; - keywordMap["add"] = ICE_GRID_ADD; - keywordMap["remove"] = ICE_GRID_REMOVE; - keywordMap["list"] = ICE_GRID_LIST; - keywordMap["shutdown"] = ICE_GRID_SHUTDOWN; - keywordMap["describe"] = ICE_GRID_DESCRIBE; - keywordMap["properties"] = ICE_GRID_PROPERTIES; - keywordMap["property"] = ICE_GRID_PROPERTY; - keywordMap["state"] = ICE_GRID_STATE; - keywordMap["pid"] = ICE_GRID_PID; - keywordMap["endpoints"] = ICE_GRID_ENDPOINTS; - keywordMap["start"] = ICE_GRID_START; - keywordMap["stop"] = ICE_GRID_STOP; - keywordMap["signal"] = ICE_GRID_SIGNAL; - keywordMap["stdout"] = ICE_GRID_STDOUT; - keywordMap["stderr"] = ICE_GRID_STDERR; - keywordMap["node"] = ICE_GRID_NODE; - keywordMap["registry"] = ICE_GRID_REGISTRY; - keywordMap["ping"] = ICE_GRID_PING; - keywordMap["load"] = ICE_GRID_LOAD; - keywordMap["processors"] = ICE_GRID_SOCKETS; - keywordMap["sockets"] = ICE_GRID_SOCKETS; - keywordMap["activation"] = ICE_GRID_ACTIVATION; - keywordMap["object"] = ICE_GRID_OBJECT; - keywordMap["find"] = ICE_GRID_FIND; - keywordMap["show"] = ICE_GRID_SHOW; - keywordMap["copying"] = ICE_GRID_COPYING; - keywordMap["warranty"] = ICE_GRID_WARRANTY; - keywordMap["diff"] = ICE_GRID_DIFF; - keywordMap["update"] = ICE_GRID_UPDATE; - keywordMap["instantiate"] = ICE_GRID_INSTANTIATE; - keywordMap["template"] = ICE_GRID_TEMPLATE; - keywordMap["service"] = ICE_GRID_SERVICE; - keywordMap["enable"] = ICE_GRID_ENABLE; - keywordMap["disable"] = ICE_GRID_DISABLE; + keywordMap = { + {"help", ICE_GRID_HELP}, + {"quit", ICE_GRID_EXIT}, + {"exit", ICE_GRID_EXIT}, + {"application", ICE_GRID_APPLICATION}, + {"server", ICE_GRID_SERVER}, + {"adapter", ICE_GRID_ADAPTER}, + {"add", ICE_GRID_ADD}, + {"remove", ICE_GRID_REMOVE}, + {"list", ICE_GRID_LIST}, + {"shutdown", ICE_GRID_SHUTDOWN}, + {"describe", ICE_GRID_DESCRIBE}, + {"properties", ICE_GRID_PROPERTIES}, + {"property", ICE_GRID_PROPERTY}, + {"state", ICE_GRID_STATE}, + {"pid", ICE_GRID_PID}, + {"endpoints", ICE_GRID_ENDPOINTS}, + {"start", ICE_GRID_START}, + {"stop", ICE_GRID_STOP}, + {"signal", ICE_GRID_SIGNAL}, + {"stdout", ICE_GRID_STDOUT}, + {"stderr", ICE_GRID_STDERR}, + {"node", ICE_GRID_NODE}, + {"registry", ICE_GRID_REGISTRY}, + {"ping", ICE_GRID_PING}, + {"load", ICE_GRID_LOAD}, + {"processors", ICE_GRID_SOCKETS}, + {"sockets", ICE_GRID_SOCKETS}, + {"activation", ICE_GRID_ACTIVATION}, + {"object", ICE_GRID_OBJECT}, + {"find", ICE_GRID_FIND}, + {"show", ICE_GRID_SHOW}, + {"copying", ICE_GRID_COPYING}, + {"warranty", ICE_GRID_WARRANTY}, + {"diff", ICE_GRID_DIFF}, + {"update", ICE_GRID_UPDATE}, + {"instantiate", ICE_GRID_INSTANTIATE}, + {"template", ICE_GRID_TEMPLATE}, + {"service", ICE_GRID_SERVICE}, + {"enable", ICE_GRID_ENABLE}, + {"disable", ICE_GRID_DISABLE} + }; } std::string diff --git a/cpp/src/IceGrid/Scanner.l b/cpp/src/IceGrid/Scanner.l index c3287b086e0..0a0e0c0a158 100644 --- a/cpp/src/IceGrid/Scanner.l +++ b/cpp/src/IceGrid/Scanner.l @@ -1,31 +1,17 @@ -%{ - +%top{ // // Copyright (c) ZeroC, Inc. All rights reserved. // -#include <Ice/Ice.h> -#include <IceGrid/Parser.h> -#include <IceGrid/Grammar.h> +#include <IceUtil/ScannerConfig.h> -#if defined(_MSC_VER) -// '<' : signed/unsigned mismatch -# pragma warning(disable:4018) -// 'initializing' : conversion from '__int64' to 'int', possible loss of data -# pragma warning(disable:4244) +} -# if defined(ICE_64) -// -// '=' : conversion from 'size_t' to 'int', possible loss of data -// The result of fread() is a size_t and gets inserted into an int -// -# pragma warning(disable:4267) -# endif -#endif +%{ -#if defined(__GNUC__) -# pragma GCC diagnostic ignored "-Wsign-compare" -#endif +#include <Ice/Ice.h> +#include <IceGrid/Parser.h> +#include <IceGrid/Grammar.h> using namespace std; using namespace Ice; @@ -36,17 +22,6 @@ using namespace IceGrid; # undef yywrap # define yywrap() 1 # endif -# define YY_NO_UNISTD_H -#endif - -#ifdef __SUNPRO_CC -# ifdef yywrap -# undef yywrap -# define yywrap() 1 -# endif -# ifdef ICE_64 -# pragma error_messages(off,truncwarn) -# endif #endif #define YY_INPUT(buf, result, maxSize) parser->getInput(buf, result, maxSize) @@ -54,8 +29,7 @@ using namespace IceGrid; namespace IceGrid { -typedef std::map<std::string, int> StringTokenMap; -static StringTokenMap keywordMap; +static std::map<std::string, int> keywordMap; void initScanner(); std::string parseDoubleQuotedString(); @@ -190,7 +164,7 @@ keyword [[:alpha:]]* yylvalp->clear(); yylvalp->push_back(s); - StringTokenMap::const_iterator pos = keywordMap.find(s); + const auto pos = keywordMap.find(s); return pos != keywordMap.end() ? pos->second : ICE_GRID_STRING; } @@ -205,46 +179,48 @@ namespace IceGrid { void initScanner() { - keywordMap["help"] = ICE_GRID_HELP; - keywordMap["quit"] = ICE_GRID_EXIT; - keywordMap["exit"] = ICE_GRID_EXIT; - keywordMap["application"] = ICE_GRID_APPLICATION; - keywordMap["server"] = ICE_GRID_SERVER; - keywordMap["adapter"] = ICE_GRID_ADAPTER; - keywordMap["add"] = ICE_GRID_ADD; - keywordMap["remove"] = ICE_GRID_REMOVE; - keywordMap["list"] = ICE_GRID_LIST; - keywordMap["shutdown"] = ICE_GRID_SHUTDOWN; - keywordMap["describe"] = ICE_GRID_DESCRIBE; - keywordMap["properties"] = ICE_GRID_PROPERTIES; - keywordMap["property"] = ICE_GRID_PROPERTY; - keywordMap["state"] = ICE_GRID_STATE; - keywordMap["pid"] = ICE_GRID_PID; - keywordMap["endpoints"] = ICE_GRID_ENDPOINTS; - keywordMap["start"] = ICE_GRID_START; - keywordMap["stop"] = ICE_GRID_STOP; - keywordMap["signal"] = ICE_GRID_SIGNAL; - keywordMap["stdout"] = ICE_GRID_STDOUT; - keywordMap["stderr"] = ICE_GRID_STDERR; - keywordMap["node"] = ICE_GRID_NODE; - keywordMap["registry"] = ICE_GRID_REGISTRY; - keywordMap["ping"] = ICE_GRID_PING; - keywordMap["load"] = ICE_GRID_LOAD; - keywordMap["processors"] = ICE_GRID_SOCKETS; - keywordMap["sockets"] = ICE_GRID_SOCKETS; - keywordMap["activation"] = ICE_GRID_ACTIVATION; - keywordMap["object"] = ICE_GRID_OBJECT; - keywordMap["find"] = ICE_GRID_FIND; - keywordMap["show"] = ICE_GRID_SHOW; - keywordMap["copying"] = ICE_GRID_COPYING; - keywordMap["warranty"] = ICE_GRID_WARRANTY; - keywordMap["diff"] = ICE_GRID_DIFF; - keywordMap["update"] = ICE_GRID_UPDATE; - keywordMap["instantiate"] = ICE_GRID_INSTANTIATE; - keywordMap["template"] = ICE_GRID_TEMPLATE; - keywordMap["service"] = ICE_GRID_SERVICE; - keywordMap["enable"] = ICE_GRID_ENABLE; - keywordMap["disable"] = ICE_GRID_DISABLE; + keywordMap = { + {"help", ICE_GRID_HELP}, + {"quit", ICE_GRID_EXIT}, + {"exit", ICE_GRID_EXIT}, + {"application", ICE_GRID_APPLICATION}, + {"server", ICE_GRID_SERVER}, + {"adapter", ICE_GRID_ADAPTER}, + {"add", ICE_GRID_ADD}, + {"remove", ICE_GRID_REMOVE}, + {"list", ICE_GRID_LIST}, + {"shutdown", ICE_GRID_SHUTDOWN}, + {"describe", ICE_GRID_DESCRIBE}, + {"properties", ICE_GRID_PROPERTIES}, + {"property", ICE_GRID_PROPERTY}, + {"state", ICE_GRID_STATE}, + {"pid", ICE_GRID_PID}, + {"endpoints", ICE_GRID_ENDPOINTS}, + {"start", ICE_GRID_START}, + {"stop", ICE_GRID_STOP}, + {"signal", ICE_GRID_SIGNAL}, + {"stdout", ICE_GRID_STDOUT}, + {"stderr", ICE_GRID_STDERR}, + {"node", ICE_GRID_NODE}, + {"registry", ICE_GRID_REGISTRY}, + {"ping", ICE_GRID_PING}, + {"load", ICE_GRID_LOAD}, + {"processors", ICE_GRID_SOCKETS}, + {"sockets", ICE_GRID_SOCKETS}, + {"activation", ICE_GRID_ACTIVATION}, + {"object", ICE_GRID_OBJECT}, + {"find", ICE_GRID_FIND}, + {"show", ICE_GRID_SHOW}, + {"copying", ICE_GRID_COPYING}, + {"warranty", ICE_GRID_WARRANTY}, + {"diff", ICE_GRID_DIFF}, + {"update", ICE_GRID_UPDATE}, + {"instantiate", ICE_GRID_INSTANTIATE}, + {"template", ICE_GRID_TEMPLATE}, + {"service", ICE_GRID_SERVICE}, + {"enable", ICE_GRID_ENABLE}, + {"disable", ICE_GRID_DISABLE} + }; } std::string diff --git a/cpp/src/IceGrid/ServerAdapterI.cpp b/cpp/src/IceGrid/ServerAdapterI.cpp index ef2e664cfbb..4ce13b38c79 100644 --- a/cpp/src/IceGrid/ServerAdapterI.cpp +++ b/cpp/src/IceGrid/ServerAdapterI.cpp @@ -11,10 +11,10 @@ using namespace std; using namespace IceGrid; -ServerAdapterI::ServerAdapterI(const NodeIPtr& node, +ServerAdapterI::ServerAdapterI(const shared_ptr<NodeI>& node, ServerI* server, const string& serverName, - const AdapterPrx& proxy, + const shared_ptr<AdapterPrx>& proxy, const string& id, bool enabled) : _node(node), @@ -32,16 +32,18 @@ ServerAdapterI::~ServerAdapterI() } void -ServerAdapterI::activate_async(const AMD_Adapter_activatePtr& cb, const Ice::Current&) +ServerAdapterI::activateAsync(function<void(const shared_ptr<Ice::ObjectPrx>&)> response, + function<void(exception_ptr)>, + const Ice::Current&) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_enabled && _proxy) { // // Return the adapter direct proxy. // - cb->ice_response(_proxy); + response(_proxy); return; } else if(_activateCB.empty()) @@ -52,7 +54,7 @@ ServerAdapterI::activate_async(const AMD_Adapter_activatePtr& cb, const Ice::Cur // if(!_enabled || !_server->isAdapterActivatable(_id)) { - cb->ice_response(0); + response(nullptr); return; } } @@ -63,13 +65,13 @@ ServerAdapterI::activate_async(const AMD_Adapter_activatePtr& cb, const Ice::Cur out << "waiting for activation of server `" + _serverId + "' adapter `" << _id << "'"; } - _activateCB.push_back(cb); + _activateCB.push_back(response); if(_activateCB.size() > 1) { return; } - _activateAfterDeactivating = _server->getState(Ice::emptyCurrent) >= Deactivating && - _server->getState(Ice::emptyCurrent) < Destroying; + _activateAfterDeactivating = _server->getState(Ice::emptyCurrent) >= ServerState::Deactivating && + _server->getState(Ice::emptyCurrent) < ServerState::Destroying; } // @@ -79,7 +81,7 @@ ServerAdapterI::activate_async(const AMD_Adapter_activatePtr& cb, const Ice::Cur // try { - _server->start(ServerI::OnDemand); + _server->start(ServerI::ServerActivation::OnDemand); return; } catch(const ServerStartException& ex) @@ -102,10 +104,10 @@ ServerAdapterI::activate_async(const AMD_Adapter_activatePtr& cb, const Ice::Cur } } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> ServerAdapterI::getDirectProxy(const Ice::Current&) const { - Lock sync(*this); + lock_guard lock(_mutex); // // Return the adapter direct proxy if it's set. Otherwise, throw. The caller can eventually @@ -122,9 +124,9 @@ ServerAdapterI::getDirectProxy(const Ice::Current&) const } void -ServerAdapterI::setDirectProxy(const Ice::ObjectPrx& prx, const Ice::Current&) +ServerAdapterI::setDirectProxy(shared_ptr<Ice::ObjectPrx> prx, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); // // We don't allow to override an existing proxy by another non @@ -134,7 +136,7 @@ ServerAdapterI::setDirectProxy(const Ice::ObjectPrx& prx, const Ice::Current&) { if(prx && _proxy) { - if(_server->getState(Ice::emptyCurrent) == Active) + if(_server->getState(Ice::emptyCurrent) == ServerState::Active) { throw AdapterActiveException(); } @@ -142,7 +144,7 @@ ServerAdapterI::setDirectProxy(const Ice::ObjectPrx& prx, const Ice::Current&) } bool updated = _proxy != prx; - _proxy = prx; + _proxy = move(prx); // // If the server is being deactivated and the activation callback @@ -150,22 +152,19 @@ ServerAdapterI::setDirectProxy(const Ice::ObjectPrx& prx, const Ice::Current&) // now. The server is going to be activated again and the adapter // activated. // - if(_server->getState(Ice::emptyCurrent) < Deactivating || - _server->getState(Ice::emptyCurrent) >= Destroying || !_activateAfterDeactivating) + if(_server->getState(Ice::emptyCurrent) < ServerState::Deactivating || + _server->getState(Ice::emptyCurrent) >= ServerState::Destroying || !_activateAfterDeactivating) { - for(vector<AMD_Adapter_activatePtr>::const_iterator p = _activateCB.begin(); p != _activateCB.end(); ++p) + for(const auto& response : _activateCB) { - (*p)->ice_response(_proxy); + response(_proxy); } _activateCB.clear(); } if(updated) { - AdapterDynamicInfo info; - info.id = _id; - info.proxy = _proxy; - _node->observerUpdateAdapter(info); + _node->observerUpdateAdapter({ _id, _proxy }); } if(_proxy) @@ -205,15 +204,15 @@ ServerAdapterI::destroy() void ServerAdapterI::updateEnabled() { - Lock sync(*this); + lock_guard lock(_mutex); _enabled = _server->isEnabled(Ice::emptyCurrent); } void ServerAdapterI::clear() { - Lock sync(*this); - _proxy = 0; + lock_guard lock(_mutex); + _proxy = nullptr; _activateAfterDeactivating = false; } @@ -230,10 +229,10 @@ ServerAdapterI::activationFailed(const std::string& reason) out << "server `" + _serverId + "' adapter `" << _id << "' activation failed: " << reason; } - Lock sync(*this); - for(vector<AMD_Adapter_activatePtr>::const_iterator p = _activateCB.begin(); p != _activateCB.end(); ++p) + lock_guard lock(_mutex); + for(const auto& response : _activateCB) { - (*p)->ice_response(0); + response(nullptr); } _activateCB.clear(); } @@ -241,7 +240,7 @@ ServerAdapterI::activationFailed(const std::string& reason) void ServerAdapterI::activationCompleted() { - Lock sync(*this); + lock_guard lock(_mutex); if(!_proxy) { // @@ -254,14 +253,14 @@ ServerAdapterI::activationCompleted() } } - for(vector<AMD_Adapter_activatePtr>::const_iterator p = _activateCB.begin(); p != _activateCB.end(); ++p) + for(const auto& response : _activateCB) { - (*p)->ice_response(_proxy); + response(_proxy); } _activateCB.clear(); } -AdapterPrx +shared_ptr<AdapterPrx> ServerAdapterI::getProxy() const { return _this; diff --git a/cpp/src/IceGrid/ServerAdapterI.h b/cpp/src/IceGrid/ServerAdapterI.h index ce818a7f8cc..28805919ae3 100644 --- a/cpp/src/IceGrid/ServerAdapterI.h +++ b/cpp/src/IceGrid/ServerAdapterI.h @@ -5,50 +5,52 @@ #ifndef ICE_GRID_SERVER_ADAPTER_I_H #define ICE_GRID_SERVER_ADAPTER_I_H -#include <IceUtil/Mutex.h> #include <IceGrid/Internal.h> namespace IceGrid { class NodeI; -typedef IceUtil::Handle<NodeI> NodeIPtr; - class ServerI; -class ServerAdapterI : public Adapter, public IceUtil::Mutex +class ServerAdapterI : public Adapter { public: - ServerAdapterI(const NodeIPtr&, ServerI*, const std::string&, const AdapterPrx&, const std::string&, bool); - virtual ~ServerAdapterI(); + ServerAdapterI(const std::shared_ptr<NodeI>&, ServerI*, const std::string&, + const std::shared_ptr<AdapterPrx>&, const std::string&, bool); + ~ServerAdapterI() override; + + void activateAsync(std::function<void(const std::shared_ptr<Ice::ObjectPrx>&)>, + std::function<void(std::exception_ptr)>, + const Ice::Current&) override; + std::shared_ptr<Ice::ObjectPrx> getDirectProxy(const Ice::Current&) const override; + void setDirectProxy(std::shared_ptr<Ice::ObjectPrx>, const ::Ice::Current&) override; - virtual void activate_async(const AMD_Adapter_activatePtr& cb, const Ice::Current&); - virtual Ice::ObjectPrx getDirectProxy(const Ice::Current&) const; - virtual void setDirectProxy(const ::Ice::ObjectPrx&, const ::Ice::Current&); void destroy(); void updateEnabled(); void clear(); void activationFailed(const std::string&); void activationCompleted(); - AdapterPrx getProxy() const; + std::shared_ptr<AdapterPrx> getProxy() const; private: - const NodeIPtr _node; - const AdapterPrx _this; + const std::shared_ptr<NodeI> _node; + const std::shared_ptr<AdapterPrx> _this; const std::string _serverId; const std::string _id; const std::string _replicaId; ServerI* _server; - Ice::ObjectPrx _proxy; + std::shared_ptr<Ice::ObjectPrx> _proxy; bool _enabled; - std::vector<AMD_Adapter_activatePtr> _activateCB; + std::vector<std::function<void(const std::shared_ptr<Ice::ObjectPrx>&)>> _activateCB; bool _activateAfterDeactivating; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<ServerAdapterI> ServerAdapterIPtr; } diff --git a/cpp/src/IceGrid/ServerCache.cpp b/cpp/src/IceGrid/ServerCache.cpp index 725b0b08757..64365ace22d 100644 --- a/cpp/src/IceGrid/ServerCache.cpp +++ b/cpp/src/IceGrid/ServerCache.cpp @@ -14,68 +14,17 @@ #include <IceGrid/SessionI.h> #include <IceGrid/DescriptorHelper.h> #include <IceGrid/Topics.h> +#include <IceGrid/Internal.h> using namespace std; using namespace IceGrid; -namespace IceGrid -{ - - struct AddCommunicator : std::unary_function<CommunicatorDescriptorPtr&, void> - { - AddCommunicator(ServerCache& serverCache, const ServerEntryPtr& entry, const string& application) : - _serverCache(serverCache), _entry(entry), _application(application) - { - } - - void - operator()(const CommunicatorDescriptorPtr& desc) - { - _serverCache.addCommunicator(0, desc, _entry, _application); - } - - void - operator()(const CommunicatorDescriptorPtr& oldDesc, const CommunicatorDescriptorPtr& newDesc) - { - _serverCache.addCommunicator(oldDesc, newDesc, _entry, _application); - } - - ServerCache& _serverCache; - const ServerEntryPtr _entry; - const string _application; - }; - - struct RemoveCommunicator : std::unary_function<CommunicatorDescriptorPtr&, void> - { - RemoveCommunicator(ServerCache& serverCache, const ServerEntryPtr& entry) : - _serverCache(serverCache), _entry(entry) - { - } - - void - operator()(const CommunicatorDescriptorPtr& desc) - { - _serverCache.removeCommunicator(desc, 0, _entry); - } - - void - operator()(const CommunicatorDescriptorPtr& oldDesc, const CommunicatorDescriptorPtr& newDesc) - { - _serverCache.removeCommunicator(oldDesc, newDesc, _entry); - } - - ServerCache& _serverCache; - const ServerEntryPtr _entry; - }; - -} - CheckUpdateResult::CheckUpdateResult(const string& server, const string& node, bool noRestart, bool remove, - const Ice::AsyncResultPtr& result) : - _server(server), _node(node), _remove(remove), _noRestart(noRestart), _result(result) + future<bool>&& result) : + _server(server), _node(node), _remove(remove), _noRestart(noRestart), _result(move(result)) { } @@ -84,7 +33,7 @@ CheckUpdateResult::getResult() { try { - return ServerPrx::uncheckedCast(_result->getProxy())->end_checkUpdate(_result); + return _result.get(); } catch(const DeploymentException& ex) { @@ -115,7 +64,7 @@ CheckUpdateResult::getResult() } } -ServerCache::ServerCache(const Ice::CommunicatorPtr& communicator, +ServerCache::ServerCache(const shared_ptr<Ice::Communicator>& communicator, const string& instanceName, NodeCache& nodeCache, AdapterCache& adapterCache, @@ -130,22 +79,25 @@ ServerCache::ServerCache(const Ice::CommunicatorPtr& communicator, { } -ServerEntryPtr +shared_ptr<ServerEntry> ServerCache::add(const ServerInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); - ServerEntryPtr entry = getImpl(info.descriptor->id); + auto entry = getImpl(info.descriptor->id); if(!entry) { - entry = new ServerEntry(*this, info.descriptor->id); + entry = make_shared<ServerEntry>(*this, info.descriptor->id); addImpl(info.descriptor->id, entry); } entry->update(info, false); _nodeCache.get(info.node, true)->addServer(entry); - forEachCommunicator(AddCommunicator(*this, entry, info.application))(info.descriptor); + forEachCommunicator(info.descriptor, [this, entry, application = info.application](const auto& descriptor) + { + addCommunicator(nullptr, descriptor, entry, application); + }); if(_traceLevels && _traceLevels->server > 0) { @@ -156,11 +108,11 @@ ServerCache::add(const ServerInfo& info) return entry; } -ServerEntryPtr +shared_ptr<ServerEntry> ServerCache::get(const string& id) const { - Lock sync(*this); - ServerEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + auto entry = getImpl(id); if(!entry) { throw ServerNotExistException(id); @@ -171,22 +123,24 @@ ServerCache::get(const string& id) const bool ServerCache::has(const string& id) const { - Lock sync(*this); - ServerEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + auto entry = getImpl(id); return entry && !entry->isDestroyed(); } -ServerEntryPtr +shared_ptr<ServerEntry> ServerCache::remove(const string& id, bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); - ServerEntryPtr entry = getImpl(id); + auto entry = getImpl(id); assert(entry); ServerInfo info = entry->getInfo(); - forEachCommunicator(RemoveCommunicator(*this, entry))(info.descriptor); - + forEachCommunicator(info.descriptor, [this, entry](const auto& desc) + { + removeCommunicator(desc, nullptr, entry); + }); _nodeCache.get(info.node)->removeServer(entry); entry->destroy(noRestart); // This must be done after otherwise some allocatable objects @@ -204,16 +158,19 @@ ServerCache::remove(const string& id, bool noRestart) void ServerCache::preUpdate(const ServerInfo& newInfo, bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); const string& id = newInfo.descriptor->id; - ServerEntryPtr entry = getImpl(id); + auto entry = getImpl(id); assert(entry); if(!noRestart) { ServerInfo info = entry->getInfo(); - forEachCommunicator(RemoveCommunicator(*this, entry))(info.descriptor, newInfo.descriptor); + forEachCommunicator(info.descriptor, newInfo.descriptor, [this, entry](const auto& oldDesc, const auto& newDesc) + { + removeCommunicator(oldDesc, newDesc, entry); + }); _nodeCache.get(info.node)->removeServer(entry); } @@ -228,12 +185,12 @@ ServerCache::preUpdate(const ServerInfo& newInfo, bool noRestart) } } -ServerEntryPtr +shared_ptr<ServerEntry> ServerCache::postUpdate(const ServerInfo& info, bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); - ServerEntryPtr entry = getImpl(info.descriptor->id); + auto entry = getImpl(info.descriptor->id); assert(entry); ServerInfo oldInfo = entry->getInfo(); @@ -242,7 +199,12 @@ ServerCache::postUpdate(const ServerInfo& info, bool noRestart) if(!noRestart) { _nodeCache.get(info.node, true)->addServer(entry); - forEachCommunicator(AddCommunicator(*this, entry, info.application))(oldInfo.descriptor, info.descriptor); + + forEachCommunicator(oldInfo.descriptor, info.descriptor, + [this, entry, application = info.application](const auto& oldDesc, const auto& newDesc) + { + addCommunicator(oldDesc, newDesc, entry, application); + }); } if(_traceLevels && _traceLevels->server > 0) @@ -257,20 +219,20 @@ ServerCache::postUpdate(const ServerInfo& info, bool noRestart) void ServerCache::clear(const string& id) { - Lock sync(*this); + lock_guard lock(_mutex); CacheByString<ServerEntry>::removeImpl(id); } void -ServerCache::setNodeObserverTopic(const NodeObserverTopicPtr& nodeObserverTopic) +ServerCache::setNodeObserverTopic(const shared_ptr<NodeObserverTopic>& nodeObserverTopic) { _nodeObserverTopic = nodeObserverTopic; } void -ServerCache::addCommunicator(const CommunicatorDescriptorPtr& oldDesc, - const CommunicatorDescriptorPtr& newDesc, - const ServerEntryPtr& server, +ServerCache::addCommunicator(const shared_ptr<CommunicatorDescriptor>& oldDesc, + const shared_ptr<CommunicatorDescriptor>& newDesc, + const shared_ptr<ServerEntry>& server, const string& application) { if(!newDesc) @@ -311,9 +273,9 @@ ServerCache::addCommunicator(const CommunicatorDescriptorPtr& oldDesc, } void -ServerCache::removeCommunicator(const CommunicatorDescriptorPtr& oldDesc, - const CommunicatorDescriptorPtr& newDesc, - const ServerEntryPtr& /*entry*/) +ServerCache::removeCommunicator(const shared_ptr<CommunicatorDescriptor>& oldDesc, + const shared_ptr<CommunicatorDescriptor>& newDesc, + const shared_ptr<ServerEntry>&) { if(!oldDesc) { @@ -353,7 +315,7 @@ ServerCache::removeCommunicator(const CommunicatorDescriptorPtr& oldDesc, } ServerEntry::ServerEntry(ServerCache& cache, const string& id) : - Allocatable(false, 0), + Allocatable(false, nullptr), _cache(cache), _id(id), _activationTimeout(-1), @@ -371,13 +333,13 @@ ServerEntry::sync() } void -ServerEntry::waitForSync(int timeout) +ServerEntry::waitForSync(chrono::seconds timeout) { - waitImpl(timeout); + waitImpl(move(timeout)); } void -ServerEntry::waitForSyncNoThrow(int timeout) +ServerEntry::waitForSyncNoThrow(chrono::seconds timeout) { try { @@ -385,7 +347,7 @@ ServerEntry::waitForSyncNoThrow(int timeout) } catch(const SynchronizationException&) { - assert(timeout >= 0); + assert(timeout >= 0s); } catch(const Ice::Exception&) { @@ -395,21 +357,21 @@ ServerEntry::waitForSyncNoThrow(int timeout) void ServerEntry::unsync() { - Lock sync(*this); + lock_guard lock(_mutex); if(_loaded.get()) { _load.reset(_loaded.release()); } - _proxy = 0; + _proxy = nullptr; _adapters.clear(); - _activationTimeout = -1; - _deactivationTimeout = -1; + _activationTimeout = -1s; + _deactivationTimeout = -1s; } bool -ServerEntry::addSyncCallback(const SynchronizationCallbackPtr& callback) +ServerEntry::addSyncCallback(const shared_ptr<SynchronizationCallback>& callback) { - Lock sync(*this); + lock_guard lock(_mutex); if(!_loaded.get() && !_load.get()) { throw ServerNotExistException(); @@ -424,10 +386,9 @@ ServerEntry::addSyncCallback(const SynchronizationCallbackPtr& callback) void ServerEntry::update(const ServerInfo& info, bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); - IceInternal::UniquePtr<ServerInfo> descriptor(new ServerInfo()); - *descriptor = info; + auto descriptor = make_unique<ServerInfo>(info); _updated = true; @@ -457,7 +418,7 @@ ServerEntry::update(const ServerInfo& info, bool noRestart) void ServerEntry::destroy(bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); _updated = true; @@ -486,9 +447,9 @@ ServerInfo ServerEntry::getInfo(bool resolve) const { ServerInfo info; - SessionIPtr session; + shared_ptr<SessionI> session; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_loaded.get() && !_load.get()) { throw ServerNotExistException(); @@ -522,21 +483,22 @@ ServerEntry::getId() const return _id; } -ServerPrx -ServerEntry::getProxy(bool upToDate, int timeout) +shared_ptr<ServerPrx> +ServerEntry::getProxy(bool upToDate, chrono::seconds timeout) { // // NOTE: this might throw ServerNotExistException, NodeUnreachableException // or DeploymentException. // - int actTimeout, deactTimeout; + chrono::seconds actTimeout, deactTimeout; string node; return getProxy(actTimeout, deactTimeout, node, upToDate, timeout); } -ServerPrx -ServerEntry::getProxy(int& activationTimeout, int& deactivationTimeout, string& node, bool upToDate, int timeout) +shared_ptr<ServerPrx> +ServerEntry::getProxy(chrono::seconds& activationTimeout, chrono::seconds& deactivationTimeout, string& node, + bool upToDate, chrono::seconds timeout) { // // NOTE: this might throw ServerNotExistException, NodeUnreachableException @@ -545,7 +507,7 @@ ServerEntry::getProxy(int& activationTimeout, int& deactivationTimeout, string& while(true) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_loaded.get() || (_proxy && _synchronizing && !upToDate)) // Synced or if not up to date is fine { assert(_loaded.get() || _load.get() || _destroy.get()); @@ -565,19 +527,16 @@ ServerEntry::getProxy(int& activationTimeout, int& deactivationTimeout, string& } } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> ServerEntry::getAdminProxy() { // // The category must match the server admin category used by nodes // - Ice::Identity adminId; - adminId.name = _id; - adminId.category = _cache.getInstanceName() + "-NodeServerAdminRouter"; - return getProxy(true)->ice_identity(adminId); + return getProxy(true)->ice_identity({ _id, _cache.getInstanceName() + "-NodeServerAdminRouter" }); } -AdapterPrx +shared_ptr<AdapterPrx> ServerEntry::getAdapter(const string& id, bool upToDate) { // @@ -585,12 +544,13 @@ ServerEntry::getAdapter(const string& id, bool upToDate) // or DeploymentException. // - int activationTimeout, deactivationTimeout; + chrono::seconds activationTimeout, deactivationTimeout; return getAdapter(activationTimeout, deactivationTimeout, id, upToDate); } -AdapterPrx -ServerEntry::getAdapter(int& activationTimeout, int& deactivationTimeout, const string& id, bool upToDate) +shared_ptr<AdapterPrx> +ServerEntry::getAdapter(chrono::seconds& activationTimeout, chrono::seconds& deactivationTimeout, const string& id, + bool upToDate) { // // NOTE: this might throw AdapterNotExistException, NodeUnreachableException @@ -599,8 +559,8 @@ ServerEntry::getAdapter(int& activationTimeout, int& deactivationTimeout, const while(true) { { - Lock sync(*this); - if(_loaded.get() || (_proxy && _synchronizing && !upToDate)) // Synced or if not up to date is fine + lock_guard lock(_mutex); + if(_loaded || (_proxy && _synchronizing && !upToDate)) // Synced or if not up to date is fine { AdapterPrxDict::const_iterator p = _adapters.find(id); if(p != _adapters.end()) @@ -615,14 +575,14 @@ ServerEntry::getAdapter(int& activationTimeout, int& deactivationTimeout, const throw AdapterNotExistException(id); } } - else if(!_load.get() && !_destroy.get()) + else if(!_load && !_destroy) { throw AdapterNotExistException(id); } } syncImpl(); - waitImpl(0); // Don't wait, just check for the result or throw SynchronizationException + waitImpl(0s); // Don't wait, just check for the result or throw SynchronizationException } } @@ -632,7 +592,7 @@ ServerEntry::getLoad(LoadSample sample) const string application; string node; { - Lock sync(*this); + lock_guard lock(_mutex); if(_loaded.get()) { application = _loaded->application; @@ -653,11 +613,11 @@ ServerEntry::getLoad(LoadSample sample) const LoadInfo load = _cache.getNodeCache().get(node)->getLoadInfoAndLoadFactor(application, factor); switch(sample) { - case LoadSample1: + case LoadSample::LoadSample1: return load.avg1 < 0.f ? 1.0f : load.avg1 * factor; - case LoadSample5: + case LoadSample::LoadSample5: return load.avg5 < 0.f ? 1.0f : load.avg5 * factor; - case LoadSample15: + case LoadSample::LoadSample15: return load.avg15 < 0.f ? 1.0f : load.avg15 * factor; default: assert(false); @@ -669,13 +629,13 @@ void ServerEntry::syncImpl() { ServerInfo load; - SessionIPtr session; + shared_ptr<SessionI> session; ServerInfo destroy; - int timeout = -1; + auto timeout = -1s; bool noRestart = false; { - Lock sync(*this); + lock_guard lock(_mutex); if(_synchronizing) { return; @@ -687,7 +647,7 @@ ServerEntry::syncImpl() } _updated = false; - _exception.reset(0); + _exception = nullptr; if(_destroy.get()) { @@ -713,44 +673,44 @@ ServerEntry::syncImpl() { try { - _cache.getNodeCache().get(destroy.node)->destroyServer(this, destroy, timeout, noRestart); + _cache.getNodeCache().get(destroy.node)->destroyServer(static_pointer_cast<ServerEntry>(shared_from_this()), destroy, timeout, noRestart); } catch(const NodeNotExistException&) { - exception(NodeUnreachableException(destroy.node, "node is not active")); + exception(make_exception_ptr(NodeUnreachableException(destroy.node, "node is not active"))); } } else if(load.descriptor) { try { - _cache.getNodeCache().get(load.node)->loadServer(this, load, session, timeout, noRestart); + _cache.getNodeCache().get(load.node)->loadServer(static_pointer_cast<ServerEntry>(shared_from_this()), load, session, timeout, noRestart); } catch(const NodeNotExistException&) { - exception(NodeUnreachableException(load.node, "node is not active")); + exception(make_exception_ptr(NodeUnreachableException(load.node, "node is not active"))); } } } void -ServerEntry::waitImpl(int timeout) +ServerEntry::waitImpl(chrono::seconds timeout) { - Lock sync(*this); - if(timeout != 0) + unique_lock lock(_mutex); + if(timeout != 0s) { while(_synchronizing) { - if(timeout > 0) + if(timeout > 0s) { - if(!timedWait(IceUtil::Time::seconds(timeout))) + if(_condVar.wait_for(lock, timeout) == cv_status::timeout) { break; // Timeout } } else { - wait(); + _condVar.wait(lock); } } } @@ -759,11 +719,11 @@ ServerEntry::waitImpl(int timeout) throw SynchronizationException(__FILE__, __LINE__); } - if(_exception.get()) + if(_exception) { try { - _exception->ice_throw(); + rethrow_exception(_exception); } catch(const DeploymentException&) { @@ -773,11 +733,11 @@ ServerEntry::waitImpl(int timeout) { throw; } - catch(const Ice::Exception& ex) // This shouln't happen. + catch(const Ice::Exception& ex) // This shouldn't happen. { ostringstream os; os << "unexpected exception while synchronizing server `" + _id + "':\n" << ex; - TraceLevelsPtr traceLevels = _cache.getTraceLevels(); + auto traceLevels = _cache.getTraceLevels(); if(traceLevels) { Ice::Error err(traceLevels->logger); @@ -791,18 +751,18 @@ ServerEntry::waitImpl(int timeout) void ServerEntry::synchronized() { - vector<SynchronizationCallbackPtr> callbacks; + vector<shared_ptr<SynchronizationCallback>> callbacks; { - Lock sync(*this); + lock_guard lock(_mutex); _callbacks.swap(callbacks); } - for(vector<SynchronizationCallbackPtr>::const_iterator p = callbacks.begin(); p != callbacks.end(); ++p) + for(const auto& callback : callbacks) { try { - (*p)->synchronized(); + callback->synchronized(); } - catch(...) + catch(const std::exception&) { assert(false); } @@ -810,20 +770,20 @@ ServerEntry::synchronized() } void -ServerEntry::synchronized(const Ice::Exception& ex) +ServerEntry::synchronized(exception_ptr ex) { - vector<SynchronizationCallbackPtr> callbacks; + vector<shared_ptr<SynchronizationCallback>> callbacks; { - Lock sync(*this); + lock_guard lock(_mutex); _callbacks.swap(callbacks); } - for(vector<SynchronizationCallbackPtr>::const_iterator p = callbacks.begin(); p != callbacks.end(); ++p) + for(const auto& callback : callbacks) { try { - (*p)->synchronized(ex); + callback->synchronized(ex); } - catch(...) + catch(const std::exception&) { assert(false); } @@ -831,17 +791,18 @@ ServerEntry::synchronized(const Ice::Exception& ex) } void -ServerEntry::loadCallback(const ServerPrx& proxy, const AdapterPrxDict& adpts, int at, int dt) +ServerEntry::loadCallback(const shared_ptr<ServerPrx>& proxy, const AdapterPrxDict& adpts, + chrono::seconds activationTimeout, chrono::seconds deactivationTimeout) { ServerInfo load; - SessionIPtr session; + shared_ptr<SessionI> session; ServerInfo destroy; - int timeout = -1; + chrono::seconds timeout = -1s; bool synced = false; bool noRestart = false; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_updated) { // @@ -855,13 +816,13 @@ ServerEntry::loadCallback(const ServerPrx& proxy, const AdapterPrxDict& adpts, i _loaded.reset(_load.release()); _proxy = proxy; _adapters = adpts; - _activationTimeout = at; - _deactivationTimeout = dt; + _activationTimeout = activationTimeout; + _deactivationTimeout = deactivationTimeout; assert(!_destroy.get() && !_load.get()); _synchronizing = false; synced = true; - notifyAll(); + _condVar.notify_all(); } else { @@ -892,22 +853,22 @@ ServerEntry::loadCallback(const ServerPrx& proxy, const AdapterPrxDict& adpts, i { try { - _cache.getNodeCache().get(destroy.node)->destroyServer(this, destroy, timeout, noRestart); + _cache.getNodeCache().get(destroy.node)->destroyServer(static_pointer_cast<ServerEntry>(shared_from_this()), destroy, timeout, noRestart); } catch(const NodeNotExistException&) { - exception(NodeUnreachableException(destroy.node, "node is not active")); + exception(make_exception_ptr(NodeUnreachableException(destroy.node, "node is not active"))); } } else if(load.descriptor) { try { - _cache.getNodeCache().get(load.node)->loadServer(this, load, session, timeout, noRestart); + _cache.getNodeCache().get(load.node)->loadServer(static_pointer_cast<ServerEntry>(shared_from_this()), load, session, timeout, noRestart); } catch(const NodeNotExistException&) { - exception(NodeUnreachableException(load.node, "node is not active")); + exception(make_exception_ptr(NodeUnreachableException(load.node, "node is not active"))); } } } @@ -917,21 +878,21 @@ ServerEntry::destroyCallback() { ServerInfo load; bool noRestart = false; - SessionIPtr session; + shared_ptr<SessionI> session; { - Lock sync(*this); - _destroy.reset(0); - _proxy = 0; + lock_guard lock(_mutex); + _destroy = nullptr; + _proxy = nullptr; _adapters.clear(); - _activationTimeout = -1; - _deactivationTimeout = -1; + _activationTimeout = -1s; + _deactivationTimeout = -1s; if(!_load.get()) { assert(!_load.get() && !_loaded.get()); _synchronizing = false; - notifyAll(); + _condVar.notify_all(); } else { @@ -946,11 +907,12 @@ ServerEntry::destroyCallback() { try { - _cache.getNodeCache().get(load.node)->loadServer(this, load, session, -1, noRestart); + _cache.getNodeCache().get(load.node)->loadServer(static_pointer_cast<ServerEntry>(shared_from_this()), load, + session, -1s, noRestart); } catch(const NodeNotExistException&) { - exception(NodeUnreachableException(load.node, "node is not active")); + exception(make_exception_ptr(NodeUnreachableException(load.node, "node is not active"))); } } else @@ -961,31 +923,31 @@ ServerEntry::destroyCallback() } void -ServerEntry::exception(const Ice::Exception& ex) +ServerEntry::exception(exception_ptr ex) { ServerInfo load; - SessionIPtr session; + shared_ptr<SessionI> session; bool noRestart = false; bool remove = false; - int timeout = -1; + chrono::seconds timeout = -1s; { - Lock sync(*this); + lock_guard lock(_mutex); if((_destroy.get() && !_load.get()) || (!_destroy.get() && !_updated)) { remove = _destroy.get(); - _destroy.reset(0); - _exception.reset(ex.ice_clone()); - _proxy = 0; + _destroy = nullptr; + _exception = ex; + _proxy = nullptr; _adapters.clear(); - _activationTimeout = -1; - _deactivationTimeout = -1; + _activationTimeout = -1s; + _deactivationTimeout = -1s; _synchronizing = false; - notifyAll(); + _condVar.notify_all(); } else { - _destroy.reset(0); + _destroy = nullptr; _updated = false; load = *_load.get(); noRestart = _noRestart; @@ -998,11 +960,12 @@ ServerEntry::exception(const Ice::Exception& ex) { try { - _cache.getNodeCache().get(load.node)->loadServer(this, load, session, timeout, noRestart); + _cache.getNodeCache().get(load.node)->loadServer(static_pointer_cast<ServerEntry>(shared_from_this()), load, + session, timeout, noRestart); } catch(const NodeNotExistException&) { - exception(NodeUnreachableException(load.node, "node is not active")); + exception(make_exception_ptr(NodeUnreachableException(load.node, "node is not active"))); } } else @@ -1018,24 +981,24 @@ ServerEntry::exception(const Ice::Exception& ex) bool ServerEntry::isDestroyed() { - Lock sync(*this); + lock_guard lock(_mutex); return !_loaded.get() && !_load.get(); } bool ServerEntry::canRemove() { - Lock sync(*this); + lock_guard lock(_mutex); return !_loaded.get() && !_load.get() && !_destroy.get(); } -CheckUpdateResultPtr +shared_ptr<CheckUpdateResult> ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) { - SessionIPtr session; + shared_ptr<SessionI> session; ServerInfo oldInfo; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_loaded.get() && !_load.get()) { throw ServerNotExistException(); @@ -1045,7 +1008,7 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) session = _allocationSession; } - NodeEntryPtr node; + shared_ptr<NodeEntry> node; try { node = _cache.getNodeCache().get(oldInfo.node); @@ -1055,10 +1018,10 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) throw NodeUnreachableException(info.node, "node is not active"); } - ServerPrx server; + shared_ptr<ServerPrx> server; try { - server = getProxy(true, 5); + server = getProxy(true, 5s); } catch(const SynchronizationException&) { @@ -1078,7 +1041,7 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) else { // Otherwise, we do as if the update is valid. - return 0; + return nullptr; } } @@ -1087,13 +1050,14 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) // the node. In this case, the check just ensures that the server // is stopped. // - InternalServerDescriptorPtr desc; + shared_ptr<InternalServerDescriptor> desc; if(info.node == oldInfo.node && info.descriptor) { desc = node->getInternalServerDescriptor(info, session); // The new descriptor } - return new CheckUpdateResult(_id, oldInfo.node, noRestart, desc, server->begin_checkUpdate(desc, noRestart)); + return make_shared<CheckUpdateResult>(_id, oldInfo.node, noRestart, desc != nullptr, + server->checkUpdateAsync(desc, noRestart)); } bool @@ -1103,21 +1067,21 @@ ServerEntry::isEnabled() const } void -ServerEntry::allocated(const SessionIPtr& session) +ServerEntry::allocated(const shared_ptr<SessionI>& session) { if(!_loaded.get() && !_load.get()) { return; } - TraceLevelsPtr traceLevels = _cache.getTraceLevels(); + auto traceLevels = _cache.getTraceLevels(); if(traceLevels && traceLevels->server > 1) { Ice::Trace out(traceLevels->logger, traceLevels->serverCat); out << "server `" << _id << "' allocated by `" << session->getId() << "' (" << _count << ")"; } - ServerDescriptorPtr desc = _loaded.get() ? _loaded->descriptor : _load->descriptor; + auto desc = _loaded.get() ? _loaded->descriptor : _load->descriptor; // // If the server has the session activation mode, we re-load the @@ -1136,34 +1100,18 @@ ServerEntry::allocated(const SessionIPtr& session) _load->sessionId = session->getId(); } - Glacier2::IdentitySetPrx identitySet = session->getGlacier2IdentitySet(); - Glacier2::StringSetPrx adapterIdSet = session->getGlacier2AdapterIdSet(); + auto identitySet = session->getGlacier2IdentitySet(); + auto adapterIdSet = session->getGlacier2AdapterIdSet(); if(identitySet && adapterIdSet) { - ServerHelperPtr helper = createHelper(desc); + auto helper = createHelper(desc); multiset<string> adapterIds; multiset<Ice::Identity> identities; helper->getIds(adapterIds, identities); try { - // - // SunCC won't accept the following: - // - // ctl->adapterIds()->add(Ice::StringSeq(adapterIds.begin(), adapterIds.end())); - // ctl->identities()->add(Ice::IdentitySeq(identities.begin(), identities.end())); - // - Ice::StringSeq adapterIdSeq; - for(multiset<string>::iterator p = adapterIds.begin(); p != adapterIds.end(); ++p) - { - adapterIdSeq.push_back(*p); - } - Ice::IdentitySeq identitySeq; - for(multiset<Ice::Identity>::iterator q = identities.begin(); q != identities.end(); ++q) - { - identitySeq.push_back(*q); - } - adapterIdSet->add(adapterIdSeq); - identitySet->add(identitySeq); + adapterIdSet->add({ adapterIds.begin(), adapterIds.end() }); + identitySet->add({ identities.begin(), identities.end() }); } catch(const Ice::LocalException& ex) { @@ -1178,10 +1126,10 @@ ServerEntry::allocated(const SessionIPtr& session) } void -ServerEntry::allocatedNoSync(const SessionIPtr& /*session*/) +ServerEntry::allocatedNoSync(const shared_ptr<SessionI>&) { { - Lock sync(*this); + lock_guard lock(_mutex); if(!_updated || (_loaded.get() && _loaded->descriptor->activation != "session") || (_load.get() && _load->descriptor->activation != "session")) @@ -1195,14 +1143,14 @@ ServerEntry::allocatedNoSync(const SessionIPtr& /*session*/) } void -ServerEntry::released(const SessionIPtr& session) +ServerEntry::released(const shared_ptr<SessionI>& session) { if(!_loaded.get() && !_load.get()) { return; } - ServerDescriptorPtr desc = _loaded.get() ? _loaded->descriptor : _load->descriptor; + auto desc = _loaded.get() ? _loaded->descriptor : _load->descriptor; // // If the server has the session activation mode, we re-load the @@ -1219,39 +1167,23 @@ ServerEntry::released(const SessionIPtr& session) _load.reset(_loaded.release()); } _load->sessionId = ""; - _allocationSession = 0; + _allocationSession = nullptr; } - TraceLevelsPtr traceLevels = _cache.getTraceLevels(); + auto traceLevels = _cache.getTraceLevels(); - Glacier2::IdentitySetPrx identitySet = session->getGlacier2IdentitySet(); - Glacier2::StringSetPrx adapterIdSet = session->getGlacier2AdapterIdSet(); + auto identitySet = session->getGlacier2IdentitySet(); + auto adapterIdSet = session->getGlacier2AdapterIdSet(); if(identitySet && adapterIdSet) { - ServerHelperPtr helper = createHelper(desc); + auto helper = createHelper(desc); multiset<string> adapterIds; multiset<Ice::Identity> identities; helper->getIds(adapterIds, identities); try { - // - // SunCC won't accept the following: - // - // ctl->adapterIds()->remove(Ice::StringSeq(adapterIds.begin(), adapterIds.end())); - // ctl->identities()->remove(Ice::IdentitySeq(identities.begin(), identities.end())); - // - Ice::StringSeq adapterIdSeq; - for(multiset<string>::iterator p = adapterIds.begin(); p != adapterIds.end(); ++p) - { - adapterIdSeq.push_back(*p); - } - Ice::IdentitySeq identitySeq; - for(multiset<Ice::Identity>::iterator q = identities.begin(); q != identities.end(); ++q) - { - identitySeq.push_back(*q); - } - adapterIdSet->remove(adapterIdSeq); - identitySet->remove(identitySeq); + adapterIdSet->remove({ adapterIds.begin(), adapterIds.end() }); + identitySet->remove({ identities.begin(), identities.end() }); } catch(const Ice::LocalException& ex) { @@ -1272,10 +1204,10 @@ ServerEntry::released(const SessionIPtr& session) } void -ServerEntry::releasedNoSync(const SessionIPtr& /*session*/) +ServerEntry::releasedNoSync(const shared_ptr<SessionI>& /*session*/) { { - Lock sync(*this); + lock_guard lock(_mutex); if(!_updated || (_loaded.get() && _loaded->descriptor->activation != "session") || (_load.get() && _load->descriptor->activation != "session")) diff --git a/cpp/src/IceGrid/ServerCache.h b/cpp/src/IceGrid/ServerCache.h index 15bee8989c6..86a991e79fd 100644 --- a/cpp/src/IceGrid/ServerCache.h +++ b/cpp/src/IceGrid/ServerCache.h @@ -5,9 +5,6 @@ #ifndef ICE_GRID_SERVERCACHE_H #define ICE_GRID_SERVERCACHE_H -#include <IceUtil/Mutex.h> -#include <IceUtil/Shared.h> -#include <Ice/UniquePtr.h> #include <IceGrid/Descriptor.h> #include <IceGrid/Internal.h> #include <IceGrid/Registry.h> @@ -17,26 +14,20 @@ namespace IceGrid { -class ServerCache; -class ObjectCache; class AdapterCache; class AllocatableObjectCache; +class CheckServerResult; class NodeCache; - class NodeEntry; -typedef IceUtil::Handle<NodeEntry> NodeEntryPtr; - -class CheckServerResult; -typedef IceUtil::Handle<CheckServerResult> CheckServerResultPtr; - class NodeObserverTopic; -typedef IceUtil::Handle<NodeObserverTopic> NodeObserverTopicPtr; +class ObjectCache; +class ServerCache; -class CheckUpdateResult : public IceUtil::Shared +class CheckUpdateResult final { public: - CheckUpdateResult(const std::string&, const std::string&, bool, bool, const Ice::AsyncResultPtr&); + CheckUpdateResult(const std::string&, const std::string&, bool, bool, std::future<bool>&&); bool getResult(); @@ -48,30 +39,29 @@ private: const std::string _node; const bool _remove; const bool _noRestart; - const Ice::AsyncResultPtr _result; + std::future<bool> _result; }; -typedef IceUtil::Handle<CheckUpdateResult> CheckUpdateResultPtr; -class ServerEntry : public Allocatable +class ServerEntry final : public Allocatable { public: ServerEntry(ServerCache&, const std::string&); void sync(); - void waitForSync(int); + void waitForSync(std::chrono::seconds); void waitForSync() { - waitForSync(-1); + waitForSync(std::chrono::seconds(-1)); } - void waitForSyncNoThrow(int); + void waitForSyncNoThrow(std::chrono::seconds); void waitForSyncNoThrow() { - waitForSyncNoThrow(-1); + waitForSyncNoThrow(std::chrono::seconds(-1)); } void unsync(); - bool addSyncCallback(const SynchronizationCallbackPtr&); + bool addSyncCallback(const std::shared_ptr<SynchronizationCallback>&); void update(const ServerInfo&, bool); @@ -80,101 +70,104 @@ public: ServerInfo getInfo(bool = false) const; std::string getId() const; - ServerPrx getProxy(int&, int&, std::string&, bool = true, int = 0); - ServerPrx getProxy(bool = true, int = 0); - Ice::ObjectPrx getAdminProxy(); + std::shared_ptr<ServerPrx> getProxy(std::chrono::seconds&, std::chrono::seconds&, std::string&, bool = true, + std::chrono::seconds = std::chrono::seconds(0)); + std::shared_ptr<ServerPrx> getProxy(bool = true, std::chrono::seconds = std::chrono::seconds(0)); + std::shared_ptr<Ice::ObjectPrx> getAdminProxy(); - AdapterPrx getAdapter(const std::string&, bool); - AdapterPrx getAdapter(int&, int&, const std::string&, bool); + std::shared_ptr<AdapterPrx> getAdapter(const std::string&, bool); + std::shared_ptr<AdapterPrx> getAdapter(std::chrono::seconds&, std::chrono::seconds&, const std::string&, bool); float getLoad(LoadSample) const; bool canRemove(); - CheckUpdateResultPtr checkUpdate(const ServerInfo&, bool); + std::shared_ptr<CheckUpdateResult> checkUpdate(const ServerInfo&, bool); bool isDestroyed(); - void loadCallback(const ServerPrx&, const AdapterPrxDict&, int, int); + void loadCallback(const std::shared_ptr<ServerPrx>&, const AdapterPrxDict&, std::chrono::seconds, + std::chrono::seconds); void destroyCallback(); - void exception(const Ice::Exception&); + void exception(std::exception_ptr); - virtual bool isEnabled() const; - virtual void allocated(const SessionIPtr&); - virtual void allocatedNoSync(const SessionIPtr&); - virtual void released(const SessionIPtr&); - virtual void releasedNoSync(const SessionIPtr&); + bool isEnabled() const override; + void allocated(const std::shared_ptr<SessionI>&) override; + void allocatedNoSync(const std::shared_ptr<SessionI>&) override; + void released(const std::shared_ptr<SessionI>&) override; + void releasedNoSync(const std::shared_ptr<SessionI>&) override; private: void syncImpl(); - void waitImpl(int); + void waitImpl(std::chrono::seconds); void synchronized(); - void synchronized(const Ice::Exception&); + void synchronized(std::exception_ptr); ServerCache& _cache; const std::string _id; - IceInternal::UniquePtr<ServerInfo> _loaded; - IceInternal::UniquePtr<ServerInfo> _load; - IceInternal::UniquePtr<ServerInfo> _destroy; + std::unique_ptr<ServerInfo> _loaded; + std::unique_ptr<ServerInfo> _load; + std::unique_ptr<ServerInfo> _destroy; - ServerPrx _proxy; + std::shared_ptr<ServerPrx> _proxy; AdapterPrxDict _adapters; - int _activationTimeout; - int _deactivationTimeout; + std::chrono::seconds _activationTimeout; + std::chrono::seconds _deactivationTimeout; bool _synchronizing; bool _updated; - IceInternal::UniquePtr<Ice::Exception> _exception; + std::exception_ptr _exception; bool _noRestart; - std::vector<SynchronizationCallbackPtr> _callbacks; + std::vector<std::shared_ptr<SynchronizationCallback>> _callbacks; + + std::shared_ptr<SessionI> _allocationSession; - SessionIPtr _allocationSession; + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle<ServerEntry> ServerEntryPtr; -typedef std::vector<ServerEntryPtr> ServerEntrySeq; +using ServerEntrySeq = std::vector<std::shared_ptr<ServerEntry>>; class ServerCache : public CacheByString<ServerEntry> { public: -#ifdef __SUNPRO_CC - using CacheByString<ServerEntry>::remove; -#endif - - ServerCache(const Ice::CommunicatorPtr&, const std::string&, NodeCache&, AdapterCache&, ObjectCache&, + ServerCache(const std::shared_ptr<Ice::Communicator>&, const std::string&, NodeCache&, AdapterCache&, ObjectCache&, AllocatableObjectCache&); - ServerEntryPtr add(const ServerInfo&); - ServerEntryPtr get(const std::string&) const; + std::shared_ptr<ServerEntry> add(const ServerInfo&); + std::shared_ptr<ServerEntry> get(const std::string&) const; bool has(const std::string&) const; - ServerEntryPtr remove(const std::string&, bool); + std::shared_ptr<ServerEntry> remove(const std::string&, bool); void preUpdate(const ServerInfo&, bool); - ServerEntryPtr postUpdate(const ServerInfo&, bool); + std::shared_ptr<ServerEntry> postUpdate(const ServerInfo&, bool); void clear(const std::string&); NodeCache& getNodeCache() const { return _nodeCache; } - Ice::CommunicatorPtr getCommunicator() const { return _communicator; } + std::shared_ptr<Ice::Communicator> getCommunicator() const { return _communicator; } const std::string& getInstanceName() const { return _instanceName; } - const NodeObserverTopicPtr& getNodeObserverTopic() const { return _nodeObserverTopic; } - void setNodeObserverTopic(const NodeObserverTopicPtr&); + const std::shared_ptr<NodeObserverTopic>& getNodeObserverTopic() const { return _nodeObserverTopic; } + void setNodeObserverTopic(const std::shared_ptr<NodeObserverTopic>&); private: - void addCommunicator(const CommunicatorDescriptorPtr&, const CommunicatorDescriptorPtr&, const ServerEntryPtr&, - const std::string&); - void removeCommunicator(const CommunicatorDescriptorPtr&, const CommunicatorDescriptorPtr&, const ServerEntryPtr&); + void addCommunicator(const std::shared_ptr<CommunicatorDescriptor>&, const std::shared_ptr<CommunicatorDescriptor>&, + const std::shared_ptr<ServerEntry>&, const std::string&); + void removeCommunicator(const std::shared_ptr<CommunicatorDescriptor>&, + const std::shared_ptr<CommunicatorDescriptor>&, const std::shared_ptr<ServerEntry>&); friend struct AddCommunicator; friend struct RemoveCommunicator; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr<Ice::Communicator> _communicator; const std::string _instanceName; NodeCache& _nodeCache; AdapterCache& _adapterCache; ObjectCache& _objectCache; AllocatableObjectCache& _allocatableObjectCache; - NodeObserverTopicPtr _nodeObserverTopic; + std::shared_ptr<NodeObserverTopic> _nodeObserverTopic; + + mutable std::mutex _mutex; }; }; diff --git a/cpp/src/IceGrid/ServerI.cpp b/cpp/src/IceGrid/ServerI.cpp index 8a2f6b36380..734bffa44d2 100644 --- a/cpp/src/IceGrid/ServerI.cpp +++ b/cpp/src/IceGrid/ServerI.cpp @@ -101,7 +101,7 @@ chownRecursive(const string& path, uid_t uid, gid_t gid) #endif static bool -descriptorUpdated(const InternalServerDescriptorPtr& lhs, const InternalServerDescriptorPtr& rhs, bool noProps = false) +descriptorUpdated(const shared_ptr<InternalServerDescriptor>& lhs, const shared_ptr<InternalServerDescriptor>& rhs, bool noProps = false) { if(lhs->uuid == rhs->uuid && lhs->revision == rhs->revision) { @@ -142,22 +142,6 @@ descriptorUpdated(const InternalServerDescriptorPtr& lhs, const InternalServerDe } } - if(lhs->dbEnvs.size() != rhs->dbEnvs.size()) - { - return true; - } - else - { - InternalDbEnvDescriptorSeq::const_iterator q = rhs->dbEnvs.begin(); - for(InternalDbEnvDescriptorSeq::const_iterator p = lhs->dbEnvs.begin(); p != lhs->dbEnvs.end(); ++p, ++q) - { - if((*p)->name != (*q)->name || (*p)->properties != (*q)->properties) - { - return true; - } - } - } - if(!noProps && lhs->properties != rhs->properties) { return true; @@ -189,39 +173,39 @@ toPropertyDict(const PropertyDescriptorSeq& seq) return props; } -class CommandTimeoutTimerTask : public IceUtil::TimerTask +class CommandTimeoutTimerTask final : public IceUtil::TimerTask { public: - CommandTimeoutTimerTask(const TimedServerCommandPtr& command) : _command(command) + CommandTimeoutTimerTask(const shared_ptr<TimedServerCommand>& command) : _command(command) { } - virtual void runTimerTask() + void runTimerTask() override { _command->timeout(); } private: - const TimedServerCommandPtr _command; + const shared_ptr<TimedServerCommand> _command; }; class DelayedStart : public IceUtil::TimerTask { public: - DelayedStart(const ServerIPtr& server, const TraceLevelsPtr& traceLevels) : + DelayedStart(const shared_ptr<ServerI>& server, const shared_ptr<TraceLevels>& traceLevels) : _server(server), _traceLevels(traceLevels) { } - virtual void runTimerTask() + void runTimerTask() override { try { - _server->start(ServerI::Always); + _server->start(ServerI::ServerActivation::Always); } catch(const ServerStartException& ex) { @@ -237,19 +221,19 @@ public: private: - const ServerIPtr _server; - const TraceLevelsPtr _traceLevels; + const shared_ptr<ServerI> _server; + const shared_ptr<TraceLevels> _traceLevels; }; -class ResetPropertiesCB : public IceUtil::Shared +class ResetPropertiesCB : public enable_shared_from_this<ResetPropertiesCB> { public: - ResetPropertiesCB(const ServerIPtr& server, - const Ice::ObjectPrx admin, - const InternalServerDescriptorPtr& desc, - const InternalServerDescriptorPtr& old, - const TraceLevelsPtr& traceLevels) : + ResetPropertiesCB(const shared_ptr<ServerI>& server, + const shared_ptr<Ice::ObjectPrx> admin, + const shared_ptr<InternalServerDescriptor>& desc, + const shared_ptr<InternalServerDescriptor>& old, + const shared_ptr<TraceLevels>& traceLevels) : _server(server), _admin(admin), _desc(desc), @@ -282,13 +266,13 @@ private: return; } - Ice::PropertyDict oldProps = toPropertyDict(_oldProperties[_p->first]); - Ice::PropertyDict props = toPropertyDict(_p->second); - for(Ice::PropertyDict::const_iterator q = oldProps.begin(); q != oldProps.end(); ++q) + auto oldProps = toPropertyDict(_oldProperties[_p->first]); + auto props = toPropertyDict(_p->second); + for(const auto& oldProp : oldProps) { - if(props.find(q->first) == props.end()) + if(props.find(oldProp.first) == props.end()) { - props[q->first] = ""; + props[oldProp.first] = ""; } } @@ -329,107 +313,97 @@ private: // ++_p; - Ice::PropertiesAdminPrx p = Ice::PropertiesAdminPrx::uncheckedCast(_admin, facet); - p->begin_setProperties(props, Ice::newCallback_PropertiesAdmin_setProperties(this, - &ResetPropertiesCB::next, - &ResetPropertiesCB::exception)); - } - - void - exception(const Ice::Exception& ex) - { - _server->updateRuntimePropertiesCallback(ex, _desc); - } - - const ServerIPtr _server; - const Ice::ObjectPrx _admin; - const InternalServerDescriptorPtr _desc; - const TraceLevelsPtr _traceLevels; + auto p = Ice::uncheckedCast<Ice::PropertiesAdminPrx>(_admin, facet); + p->setPropertiesAsync(props, + [self = shared_from_this()] + { + self->next(); + }, + [server = _server, desc = _desc](exception_ptr ex) + { + server->updateRuntimePropertiesCallback(ex, desc); + }); + } + + const shared_ptr<ServerI> _server; + const shared_ptr<Ice::ObjectPrx> _admin; + const shared_ptr<InternalServerDescriptor> _desc; + const shared_ptr<TraceLevels> _traceLevels; PropertyDescriptorSeqDict _properties; PropertyDescriptorSeqDict _oldProperties; PropertyDescriptorSeqDict::const_iterator _p; }; -typedef IceUtil::Handle<ResetPropertiesCB> ResetPropertiesCBPtr; -struct EnvironmentEval : std::unary_function<string, string> +string environmentEval(const std::string& value) { + string::size_type assignment = value.find("="); + if(assignment == string::npos || assignment >= value.size() - 1) + { + return value; + } - string - operator()(const std::string& value) + string v = value.substr(assignment + 1); + assert(v.size()); + string::size_type beg = 0; + string::size_type end; +#ifdef _WIN32 + vector<wchar_t> buf; + buf.resize(32767); + while((beg = v.find("%", beg)) != string::npos && beg < v.size() - 1) { - string::size_type assignment = value.find("="); - if(assignment == string::npos || assignment >= value.size() - 1) + end = v.find("%", beg + 1); + if(end == string::npos) { - return value; + break; } - - string v = value.substr(assignment + 1); - assert(v.size()); - string::size_type beg = 0; - string::size_type end; -#ifdef _WIN32 - vector<wchar_t> buf; - buf.resize(32767); - while((beg = v.find("%", beg)) != string::npos && beg < v.size() - 1) + string variable = v.substr(beg + 1, end - beg - 1); + DWORD ret = GetEnvironmentVariableW(Ice::stringToWstring(variable).c_str(), &buf[0], + static_cast<DWORD>(buf.size())); + string valstr = (ret > 0 && ret < buf.size()) ? Ice::wstringToString(&buf[0]) : string(""); + v.replace(beg, end - beg + 1, valstr); + beg += valstr.size(); + } +#else + while((beg = v.find("$", beg)) != string::npos && beg < v.size() - 1) + { + string variable; + if(v[beg + 1] == '{') { - end = v.find("%", beg + 1); + end = v.find("}"); if(end == string::npos) { break; } - string variable = v.substr(beg + 1, end - beg - 1); - DWORD ret = GetEnvironmentVariableW(Ice::stringToWstring(variable).c_str(), &buf[0], - static_cast<DWORD>(buf.size())); - string valstr = (ret > 0 && ret < buf.size()) ? Ice::wstringToString(&buf[0]) : string(""); - v.replace(beg, end - beg + 1, valstr); - beg += valstr.size(); + variable = v.substr(beg + 2, end - beg - 2); } -#else - while((beg = v.find("$", beg)) != string::npos && beg < v.size() - 1) + else { - string variable; - if(v[beg + 1] == '{') + end = beg + 1; + while((isalnum(static_cast<unsigned char>(v[end])) || v[end] == '_') && end < v.size()) { - end = v.find("}"); - if(end == string::npos) - { - break; - } - variable = v.substr(beg + 2, end - beg - 2); + ++end; } - else - { - end = beg + 1; - while((isalnum(static_cast<unsigned char>(v[end])) || v[end] == '_') && end < v.size()) - { - ++end; - } - variable = v.substr(beg + 1, end - beg - 1); - --end; - } - - char* val = getenv(variable.c_str()); - string valstr = val ? string(val) : ""; - v.replace(beg, end - beg + 1, valstr); - beg += valstr.size(); + variable = v.substr(beg + 1, end - beg - 1); + --end; } -#endif - return value.substr(0, assignment) + "=" + v; - } - -}; + char* val = getenv(variable.c_str()); + string valstr = val ? string(val) : ""; + v.replace(beg, end - beg + 1, valstr); + beg += valstr.size(); + } +#endif + return value.substr(0, assignment) + "=" + v; } -ServerCommand::ServerCommand(const ServerIPtr& server) : _server(server) -{ } -ServerCommand::~ServerCommand() +ServerCommand::ServerCommand(const shared_ptr<ServerI>& server) : _server(server) { } -TimedServerCommand::TimedServerCommand(const ServerIPtr& server, const IceUtil::TimerPtr& timer, int timeout) : +TimedServerCommand::TimedServerCommand(const shared_ptr<ServerI>& server, const IceUtil::TimerPtr& timer, + chrono::seconds timeout) : ServerCommand(server), _timer(timer), _timeout(timeout) { } @@ -437,12 +411,12 @@ TimedServerCommand::TimedServerCommand(const ServerIPtr& server, const IceUtil:: void TimedServerCommand::startTimer() { - _timerTask = new CommandTimeoutTimerTask(this); + _timerTask = make_shared<CommandTimeoutTimerTask>(shared_from_this()); try { - _timer->schedule(_timerTask, IceUtil::Time::seconds(_timeout)); + _timer->schedule(_timerTask, IceUtil::Time::seconds(_timeout.count())); } - catch(const IceUtil::Exception&) + catch(const std::exception&) { // Ignore, timer is destroyed because node is shutting down. } @@ -454,13 +428,13 @@ TimedServerCommand::stopTimer() if(_timerTask) { _timer->cancel(_timerTask); - _timerTask = 0; + _timerTask = nullptr; } } -LoadCommand::LoadCommand(const ServerIPtr& server, - const InternalServerDescriptorPtr& runtime, - const TraceLevelsPtr& traceLevels) : +LoadCommand::LoadCommand(const shared_ptr<ServerI>& server, + const shared_ptr<InternalServerDescriptor>& runtime, + const shared_ptr<TraceLevels>& traceLevels) : ServerCommand(server), _runtime(runtime), _updating(false), _traceLevels(traceLevels) { } @@ -474,7 +448,7 @@ LoadCommand::canExecute(ServerI::InternalServerState state) ServerI::InternalServerState LoadCommand::nextState() { - return ServerI::Loading; + return ServerI::InternalServerState::Loading; } void @@ -484,13 +458,13 @@ LoadCommand::execute() } void -LoadCommand::setUpdate(const InternalServerDescriptorPtr& descriptor, bool clearDir) +LoadCommand::setUpdate(const shared_ptr<InternalServerDescriptor>& descriptor, bool clearDir) { _clearDir = clearDir; _desc = descriptor; } -InternalServerDescriptorPtr +shared_ptr<InternalServerDescriptor> LoadCommand::getInternalServerDescriptor() const { return _desc; @@ -503,13 +477,14 @@ LoadCommand::clearDir() const } void -LoadCommand::addCallback(const AMD_Node_loadServerPtr& amdCB) +LoadCommand::addCallback(function<void(const shared_ptr<ServerPrx>&, const AdapterPrxDict &, int, int)> response, + function<void(exception_ptr)> exception) { - _loadCB.push_back(amdCB); + _loadCB.push_back({move(response), move(exception)}); } void -LoadCommand::startRuntimePropertiesUpdate(const Ice::ObjectPrx& process) +LoadCommand::startRuntimePropertiesUpdate(const shared_ptr<Ice::ObjectPrx>& process) { if(_updating) { @@ -518,12 +493,13 @@ LoadCommand::startRuntimePropertiesUpdate(const Ice::ObjectPrx& process) assert(_desc != _runtime); _updating = true; - ResetPropertiesCBPtr cb = new ResetPropertiesCB(_server, process, _desc, _runtime, _traceLevels); + auto cb = make_shared<ResetPropertiesCB>(_server, process, _desc, _runtime, _traceLevels); cb->execute(); } bool -LoadCommand::finishRuntimePropertiesUpdate(const InternalServerDescriptorPtr& runtime, const Ice::ObjectPrx& process) +LoadCommand::finishRuntimePropertiesUpdate(const shared_ptr<InternalServerDescriptor>& runtime, + const shared_ptr<Ice::ObjectPrx>& process) { _updating = false; _runtime = runtime; // The new runtime server descriptor. @@ -546,26 +522,27 @@ LoadCommand::finishRuntimePropertiesUpdate(const InternalServerDescriptorPtr& ru } void -LoadCommand::failed(const Ice::Exception& ex) +LoadCommand::failed(exception_ptr ex) { - for(vector<AMD_Node_loadServerPtr>::const_iterator p = _loadCB.begin(); p != _loadCB.end(); ++p) + for(const auto& cb : _loadCB) { - (*p)->ice_exception(ex); + cb.second(ex); } _loadCB.clear(); } void -LoadCommand::finished(const ServerPrx& proxy, const AdapterPrxDict& adapters, int at, int dt) +LoadCommand::finished(const shared_ptr<ServerPrx>& proxy, const AdapterPrxDict& adapters, + chrono::seconds at, chrono::seconds dt) { - for(vector<AMD_Node_loadServerPtr>::const_iterator p = _loadCB.begin(); p != _loadCB.end(); ++p) + for(const auto& cb : _loadCB) { - (*p)->ice_response(proxy, adapters, at, dt); + cb.first(proxy, adapters, secondsToInt(at), secondsToInt(dt)); } _loadCB.clear(); } -DestroyCommand::DestroyCommand(const ServerIPtr& server, bool loadFailure, bool clearDir) : +DestroyCommand::DestroyCommand(const shared_ptr<ServerI>& server, bool loadFailure, bool clearDir) : ServerCommand(server), _loadFailure(loadFailure), _clearDir(clearDir) @@ -591,17 +568,17 @@ DestroyCommand::execute() } void -DestroyCommand::addCallback(const AMD_Node_destroyServerPtr& amdCB) +DestroyCommand::addCallback(function<void()> response) { - _destroyCB.push_back(amdCB); + _destroyCB.push_back(move(response)); } void DestroyCommand::finished() { - for(vector<AMD_Node_destroyServerPtr>::const_iterator p = _destroyCB.begin(); p != _destroyCB.end(); ++p) + for(const auto& cb : _destroyCB) { - (*p)->ice_response(); + cb(); } } @@ -617,11 +594,6 @@ DestroyCommand::clearDir() const return _clearDir; } -StartCommand::StartCommand(const ServerIPtr& server, const IceUtil::TimerPtr& timer, int timeout) : - TimedServerCommand(server, timer, timeout) -{ -} - bool StartCommand::canExecute(ServerI::InternalServerState state) { @@ -648,19 +620,19 @@ StartCommand::timeout() } void -StartCommand::addCallback(const AMD_Server_startPtr& amdCB) +StartCommand::addCallback(function<void()> response, function<void(exception_ptr)> exception) { - _startCB.push_back(amdCB); + _startCB.push_back({move(response), move(exception)}); } void StartCommand::failed(const string& reason) { stopTimer(); - ServerStartException ex(_server->getId(), reason); - for(vector<AMD_Server_startPtr>::const_iterator p = _startCB.begin(); p != _startCB.end(); ++p) + auto ex = make_exception_ptr(ServerStartException(_server->getId(), reason)); + for(const auto& cb : _startCB) { - (*p)->ice_exception(ex); + cb.second(ex); } _startCB.clear(); } @@ -669,14 +641,15 @@ void StartCommand::finished() { stopTimer(); - for(vector<AMD_Server_startPtr>::const_iterator p = _startCB.begin(); p != _startCB.end(); ++p) + for(const auto& cb : _startCB) { - (*p)->ice_response(); + cb.first(); } _startCB.clear(); } -StopCommand::StopCommand(const ServerIPtr& server, const IceUtil::TimerPtr& timer, int timeout, bool deactivate) +StopCommand::StopCommand(const shared_ptr<ServerI>& server, const IceUtil::TimerPtr& timer, + chrono::seconds timeout, bool deactivate) : TimedServerCommand(server, timer, timeout), _deactivate(deactivate) { } @@ -717,19 +690,19 @@ StopCommand::timeout() } void -StopCommand::addCallback(const AMD_Server_stopPtr& amdCB) +StopCommand::addCallback(function<void()> response, function<void(exception_ptr)> exception) { - _stopCB.push_back(amdCB); + _stopCB.push_back({move(response), move(exception)}); } void StopCommand::failed(const string& reason) { stopTimer(); - ServerStopException ex(_server->getId(), reason); - for(vector<AMD_Server_stopPtr>::const_iterator p = _stopCB.begin(); p != _stopCB.end(); ++p) + auto ex = make_exception_ptr(ServerStopException(_server->getId(), reason)); + for(const auto& cb : _stopCB) { - (*p)->ice_exception(ex); + cb.second(ex); } _stopCB.clear(); } @@ -738,52 +711,46 @@ void StopCommand::finished() { stopTimer(); - for(vector<AMD_Server_stopPtr>::const_iterator p = _stopCB.begin(); p != _stopCB.end(); ++p) + for(const auto& cb : _stopCB) { - (*p)->ice_response(); + cb.first(); } _stopCB.clear(); } -ServerI::ServerI(const NodeIPtr& node, const ServerPrx& proxy, const string& serversDir, const string& id, int wt) : +ServerI::ServerI(const shared_ptr<NodeI>& node, const shared_ptr<ServerPrx>& proxy, const string& serversDir, const string& id, int wt) : _node(node), _this(proxy), _id(id), _waitTime(wt), _serverDir(serversDir + "/" + id), - _disableOnFailure(0), + _disableOnFailure(_node->getCommunicator()->getProperties()->getPropertyAsIntWithDefault("IceGrid.Node.DisableOnFailure", 0)), _state(ServerI::Inactive), _activation(ServerI::Disabled), - _failureTime(IceUtil::Time::now(IceUtil::Time::Monotonic)), // Ensure that _activation is init. in updateImpl(). + _failureTime(chrono::steady_clock::now()), // Ensure that _activation is init. in updateImpl(). _pid(0) { assert(_node->getActivator()); - const_cast<int&>(_disableOnFailure) = - _node->getCommunicator()->getProperties()->getPropertyAsIntWithDefault("IceGrid.Node.DisableOnFailure", 0); -} - -ServerI::~ServerI() -{ } void -ServerI::waitForApplicationUpdateCompleted(const Ice::AsyncResultPtr&) +ServerI::waitForApplicationUpdateCompleted() { activate(); } void -ServerI::start_async(const AMD_Server_startPtr& amdCB, const Ice::Current&) +ServerI::startAsync(function<void()> response, function<void(exception_ptr)> exception, const Ice::Current&) { - start(Manual, amdCB); + start(Manual, move(response), move(exception)); } void -ServerI::stop_async(const AMD_Server_stopPtr& amdCB, const Ice::Current&) +ServerI::stopAsync(function<void()> response, function<void(exception_ptr)> exception, const Ice::Current&) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); if(StopCommand::isStopped(_state)) @@ -797,11 +764,12 @@ ServerI::stop_async(const AMD_Server_stopPtr& amdCB, const Ice::Current&) if(!_stop) { - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout); + _stop = make_shared<StopCommand>(shared_from_this(), _node->getTimer(), _deactivationTimeout); } - if(amdCB) + if(response) { - _stop->addCallback(amdCB); + assert(exception); + _stop->addCallback(move(response), move(exception)); } command = nextCommand(); } @@ -812,23 +780,23 @@ ServerI::stop_async(const AMD_Server_stopPtr& amdCB, const Ice::Current&) } void -ServerI::sendSignal(const string& signal, const Ice::Current&) +ServerI::sendSignal(string signal, const Ice::Current&) { - _node->getActivator()->sendSignal(_id, signal); + _node->getActivator()->sendSignal(_id, move(signal)); } void -ServerI::writeMessage(const string& message, Ice::Int fd, const Ice::Current&) +ServerI::writeMessage(string message, int fd, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); - if(_process != 0) + if(_process) { try { - _process->writeMessage(message, fd); + _process->writeMessage(move(message), fd); } - catch(const Ice::LocalException&) + catch(const std::exception&) { } } @@ -837,7 +805,7 @@ ServerI::writeMessage(const string& message, Ice::Int fd, const Ice::Current&) ServerState ServerI::getState(const Ice::Current&) const { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); return toServerState(_state); } @@ -848,14 +816,14 @@ ServerI::getPid(const Ice::Current&) const return _node->getActivator()->getServerPid(_id); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> ServerI::getProcess() const { - Lock sync(*this); + lock_guard lock(_mutex); - if(_process == 0 || _state <= Inactive || _state >= Deactivating) + if(_process == nullptr || _state <= Inactive || _state >= Deactivating) { - return 0; + return nullptr; } else { @@ -869,24 +837,24 @@ ServerI::setEnabled(bool enabled, const ::Ice::Current&) bool activate = false; ServerAdapterDict adpts; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); assert(_desc); if(enabled && _activation == Disabled) { - _failureTime = IceUtil::Time(); + _failureTime = nullopt; _activation = toServerActivation(_desc->activation); activate = _state == Inactive && _activation == Always; } - else if(!enabled && (_activation != Disabled || _failureTime != IceUtil::Time())) + else if(!enabled && (_activation != Disabled || _failureTime != nullopt)) { - _failureTime = IceUtil::Time(); + _failureTime = nullopt; _activation = Disabled; if(_timerTask) { _node->getTimer()->cancel(_timerTask); - _timerTask = 0; + _timerTask = nullptr; } } else @@ -898,9 +866,9 @@ ServerI::setEnabled(bool enabled, const ::Ice::Current&) _node->observerUpdateServer(getDynamicInfo()); } - for(ServerAdapterDict::iterator r = adpts.begin(); r != adpts.end(); ++r) + for(const auto& adpt : adpts) { - r->second->updateEnabled(); + adpt.second->updateEnabled(); } if(activate) @@ -924,21 +892,22 @@ ServerI::setEnabled(bool enabled, const ::Ice::Current&) bool ServerI::isEnabled(const ::Ice::Current&) const { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); return _activation != Disabled; } void -ServerI::setProcess_async(const AMD_Server_setProcessPtr& amdCB, const Ice::ProcessPrx& process, const Ice::Current&) +ServerI::setProcessAsync(shared_ptr<Ice::ProcessPrx> process, function<void()> response, + function<void(exception_ptr)>, const Ice::Current&) { bool deact = false; ServerAdapterDict adpts; - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); - _process = process; + _process = move(process); if(_state == DeactivatingWaitForProcess) { deact = true; @@ -952,13 +921,14 @@ ServerI::setProcess_async(const AMD_Server_setProcessPtr& amdCB, const Ice::Proc command = nextCommand(); } } - amdCB->ice_response(); - for(ServerAdapterDict::iterator r = adpts.begin(); r != adpts.end(); ++r) + response(); + + for(const auto& adpt : adpts) { try { - r->second->activationCompleted(); + adpt.second->activationCompleted(); } catch(const Ice::ObjectNotExistException&) { @@ -976,23 +946,23 @@ ServerI::setProcess_async(const AMD_Server_setProcessPtr& amdCB, const Ice::Proc } } -Ice::Long -ServerI::getOffsetFromEnd(const string& filename, int count, const Ice::Current&) const +long long +ServerI::getOffsetFromEnd(string filename, int count, const Ice::Current&) const { - return _node->getFileCache()->getOffsetFromEnd(getFilePath(filename), count); + return _node->getFileCache()->getOffsetFromEnd(getFilePath(move(filename)), count); } bool -ServerI::read(const string& filename, Ice::Long pos, int size, Ice::Long& newPos, Ice::StringSeq& lines, +ServerI::read(string filename, long long pos, int size, long long& newPos, Ice::StringSeq& lines, const Ice::Current&) const { - return _node->getFileCache()->read(getFilePath(filename), pos, size, newPos, lines); + return _node->getFileCache()->read(getFilePath(move(filename)), pos, size, newPos, lines); } bool ServerI::isAdapterActivatable(const string& id) const { - Lock sync(*this); + lock_guard lock(_mutex); if(!_desc || _activation == Disabled) { return false; @@ -1034,24 +1004,23 @@ ServerI::getId() const } void -ServerI::start(ServerActivation activation, const AMD_Server_startPtr& amdCB) +ServerI::start(ServerActivation activation, function<void()> response , function<void(exception_ptr)> exception) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); // // Eventually re-enable the server if it's disabled because of a failure. // - if(_disableOnFailure > 0 && _failureTime != IceUtil::Time()) + if(_disableOnFailure > 0s && _failureTime != nullopt) { if(activation == Manual || - (_failureTime + IceUtil::Time::seconds(_disableOnFailure) < - IceUtil::Time::now(IceUtil::Time::Monotonic))) + (*_failureTime + _disableOnFailure < chrono::steady_clock::now())) { _activation = _previousActivation; - _failureTime = IceUtil::Time(); + _failureTime = nullopt; } } @@ -1064,7 +1033,7 @@ ServerI::start(ServerActivation activation, const AMD_Server_startPtr& amdCB) } else if(_activation != Always && activation == Always) { - assert(!amdCB); + assert(!response && !exception); return; // Nothing to do. } else if(_activation == Manual && activation != Manual) @@ -1101,16 +1070,17 @@ ServerI::start(ServerActivation activation, const AMD_Server_startPtr& amdCB) if(_timerTask) { _node->getTimer()->cancel(_timerTask); - _timerTask = 0; + _timerTask = nullptr; } if(!_start) { - _start = new StartCommand(this, _node->getTimer(), _activationTimeout); + _start = make_shared<StartCommand>(shared_from_this(), _node->getTimer(), _activationTimeout); } - if(amdCB) + if(response) { - _start->addCallback(amdCB); + assert(response && exception); + _start->addCallback(move(response), move(exception)); } command = nextCommand(); } @@ -1120,11 +1090,12 @@ ServerI::start(ServerActivation activation, const AMD_Server_startPtr& amdCB) } } -ServerCommandPtr -ServerI::load(const AMD_Node_loadServerPtr& amdCB, const InternalServerDescriptorPtr& desc, const string& replicaName, - bool noRestart) +shared_ptr<ServerCommand> +ServerI::load(const shared_ptr<InternalServerDescriptor>& desc, const string& replicaName, bool noRestart, + function<void(const shared_ptr<ServerPrx> &, const AdapterPrxDict &, int, int)> response, + function<void(exception_ptr)> exception) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); checkRevision(replicaName, desc->uuid, desc->revision); @@ -1138,7 +1109,7 @@ ServerI::load(const AMD_Node_loadServerPtr& amdCB, const InternalServerDescripto // we don't re-load the server. We just return the server // proxy and the proxies of its adapters. // - InternalServerDescriptorPtr d = _load ? _load->getInternalServerDescriptor() : _desc; + auto d = _load ? _load->getInternalServerDescriptor() : _desc; if(d && (replicaName != "Master" || d->sessionId == desc->sessionId) && !descriptorUpdated(d, desc)) { if(d->revision != desc->revision) @@ -1152,19 +1123,19 @@ ServerI::load(const AMD_Node_loadServerPtr& amdCB, const InternalServerDescripto // If the server initial loading didn't complete yet or there's a new updated descriptor // waiting to be loaded, we wait for the loading to complete before replying. // - _load->addCallback(amdCB); + _load->addCallback(response, exception); return 0; } - else if(amdCB) + else if(response) { AdapterPrxDict adapters; - for(ServerAdapterDict::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + for(const auto& [id, servant] : _adapters) { - adapters.insert(make_pair(p->first, p->second->getProxy())); + adapters.insert({ id, servant->getProxy() }); } - amdCB->ice_response(_this, adapters, _activationTimeout, _deactivationTimeout); + response(_this, adapters, secondsToInt(_activationTimeout), secondsToInt(_deactivationTimeout)); } - return 0; + return nullptr; } if(!StopCommand::isStopped(_state) && !_stop) // Server is running and no stop is scheduled @@ -1181,28 +1152,28 @@ ServerI::load(const AMD_Node_loadServerPtr& amdCB, const InternalServerDescripto } else { - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout); + _stop = make_shared<StopCommand>(shared_from_this(), _node->getTimer(), _deactivationTimeout); } } if(!_load) { - _load = new LoadCommand(this, _desc, _node->getTraceLevels()); + _load = make_shared<LoadCommand>(shared_from_this(), _desc, _node->getTraceLevels()); } - _load->setUpdate(desc, _destroy); + _load->setUpdate(desc, _destroy != nullptr); if(_destroy && _state != Destroying) { _destroy->finished(); - _destroy = 0; + _destroy = nullptr; } if(_stop || StopCommand::isStopped(_state)) { - _load->addCallback(amdCB); // Load will return once the server is loaded. + _load->addCallback(response, exception); // Load will return once the server is loaded. } else { - if(_state >= ServerI::Activating && _state < ServerI::Active) + if(_state >= InternalServerState::Activating && _state < InternalServerState::Active) { // // If the server is being activated, return the response @@ -1212,30 +1183,30 @@ ServerI::load(const AMD_Node_loadServerPtr& amdCB, const InternalServerDescripto // with the node. // AdapterPrxDict adapters; - for(ServerAdapterDict::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + for(const auto& adapter : _adapters) { - adapters.insert(make_pair(p->first, p->second->getProxy())); + adapters.insert({ adapter.first, adapter.second->getProxy() }); } - amdCB->ice_response(_this, adapters, _activationTimeout, _deactivationTimeout); + response(_this, adapters, secondsToInt(_activationTimeout), secondsToInt(_deactivationTimeout)); } - else if(_state == ServerI::Active) + else if(_state == InternalServerState::Active) { - _load->addCallback(amdCB); // Must be called before startRuntimePropertiesUpdate! + _load->addCallback(response, exception); // Must be called before startRuntimePropertiesUpdate! updateRevision(desc->uuid, desc->revision); _load->startRuntimePropertiesUpdate(_process); } else { - _load->addCallback(amdCB); + _load->addCallback(response, exception); } } return nextCommand(); } bool -ServerI::checkUpdate(const InternalServerDescriptorPtr& desc, bool noRestart, const Ice::Current&) +ServerI::checkUpdate(shared_ptr<InternalServerDescriptor> desc, bool noRestart, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); if(!_desc) @@ -1252,7 +1223,7 @@ ServerI::checkUpdate(const InternalServerDescriptorPtr& desc, bool noRestart, co return true; } - InternalServerDescriptorPtr d = _load ? _load->getInternalServerDescriptor() : _desc; + auto d = _load ? _load->getInternalServerDescriptor() : _desc; if(!descriptorUpdated(d, desc)) { return StopCommand::isStopped(_state); @@ -1278,7 +1249,7 @@ ServerI::checkUpdate(const InternalServerDescriptorPtr& desc, bool noRestart, co void ServerI::checkRemove(bool noRestart, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); if(noRestart && !StopCommand::isStopped(_state) && !_stop) @@ -1287,18 +1258,17 @@ ServerI::checkRemove(bool noRestart, const Ice::Current&) } } -ServerCommandPtr -ServerI::destroy(const AMD_Node_destroyServerPtr& amdCB, const string& uuid, int revision, const string& replicaName, - bool noRestart) +shared_ptr<ServerCommand> +ServerI::destroy(const string& uuid, int revision, const string& replicaName, bool noRestart, function<void()> response) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); checkRevision(replicaName, uuid, revision); if(!_desc) { - amdCB->ice_response(); - return 0; // Server is already destroyed. + response(); + return nullptr; // Server is already destroyed. } if(!StopCommand::isStopped(_state) && !_stop) @@ -1307,7 +1277,7 @@ ServerI::destroy(const AMD_Node_destroyServerPtr& amdCB, const string& uuid, int { throw DeploymentException("removal requires server to be stopped"); } - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout); + _stop = make_shared<StopCommand>(shared_from_this(), _node->getTimer(), _deactivationTimeout); } if(!_destroy) @@ -1316,11 +1286,11 @@ ServerI::destroy(const AMD_Node_destroyServerPtr& amdCB, const string& uuid, int // If uuid is empty, the destroy call comes from the consistency check. In // this case, we clear the server directory only if it contains non-user data. // - _destroy = new DestroyCommand(this, false, !uuid.empty()); + _destroy = make_shared<DestroyCommand>(shared_from_this(), false, !uuid.empty()); } - if(amdCB) + if(response) { - _destroy->addCallback(amdCB); + _destroy->addCallback(move(response)); } return nextCommand(); } @@ -1328,13 +1298,13 @@ ServerI::destroy(const AMD_Node_destroyServerPtr& amdCB, const string& uuid, int void ServerI::adapterActivated(const string& id) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; ServerAdapterDict adpts; { - Lock sync(*this); - if(_state != ServerI::Activating && - _state != ServerI::WaitForActivation && - _state != ServerI::ActivationTimeout) + lock_guard lock(_mutex); + if(_state != InternalServerState::Activating && + _state != InternalServerState::WaitForActivation && + _state != InternalServerState::ActivationTimeout) { return; } @@ -1345,13 +1315,13 @@ ServerI::adapterActivated(const string& id) } command = nextCommand(); } - for(ServerAdapterDict::iterator r = adpts.begin(); r != adpts.end(); ++r) + for(const auto& adpt : adpts) { - if(r->first != id) + if(adpt.first != id) { try { - r->second->activationCompleted(); + adpt.second->activationCompleted(); } catch(const Ice::ObjectNotExistException&) { @@ -1367,18 +1337,16 @@ ServerI::adapterActivated(const string& id) void ServerI::adapterDeactivated(const string& id) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); - while(_state == ServerI::Activating) - { - wait(); // Wait for activate() to set the state to WaitForActivation - } + unique_lock lock(_mutex); + // Wait for activate() to set the state to WaitForActivation + _condVar.wait(lock, [this] { return _state != InternalServerState::Activating; }); if((_state == Active || _state == WaitForActivation) && _serverLifetimeAdapters.find(id) != _serverLifetimeAdapters.end()) { - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout, false); + _stop = make_shared<StopCommand>(shared_from_this(), _node->getTimer(), _deactivationTimeout, false); } command = nextCommand(); } @@ -1413,27 +1381,27 @@ ServerI::disableOnFailure() // is always and the server wasn't active at the time of the // failure we disable the server. // - if(_disableOnFailure != 0 || (_activation == Always && (_state == Activating || _state == WaitForActivation))) + if(_disableOnFailure != 0s || (_activation == Always && (_state == Activating || _state == WaitForActivation))) { _previousActivation = _activation; _activation = Disabled; - _failureTime = IceUtil::Time::now(IceUtil::Time::Monotonic); + _failureTime = chrono::steady_clock::now(); } } void ServerI::activationTimedOut() { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; ServerAdapterDict adapters; { - Lock sync(*this); - if(_state != ServerI::WaitForActivation) + lock_guard lock(_mutex); + if(_state != InternalServerState::WaitForActivation) { return; } - setStateNoSync(ServerI::ActivationTimeout, "The server activation timed out."); + setStateNoSync(InternalServerState::ActivationTimeout, "The server activation timed out."); if(_node->getTraceLevels()->server > 1) { @@ -1444,11 +1412,11 @@ ServerI::activationTimedOut() command = nextCommand(); } - for(ServerAdapterDict::const_iterator p = adapters.begin(); p != adapters.end(); ++p) + for(const auto& adapter : adapters) { try { - p->second->activationFailed("server activation timed out"); + adapter.second->activationFailed("server activation timed out"); } catch(const Ice::ObjectNotExistException&) { @@ -1464,7 +1432,7 @@ ServerI::activationTimedOut() void ServerI::activate() { - InternalServerDescriptorPtr desc; + shared_ptr<InternalServerDescriptor> desc; ServerAdapterDict adpts; bool waitForReplication; @@ -1476,7 +1444,7 @@ ServerI::activate() try { { - Lock sync(*this); + lock_guard lock(_mutex); assert(_state == Activating && _desc); desc = _desc; adpts = _adapters; @@ -1510,11 +1478,18 @@ ServerI::activate() // if(waitForReplication) { - NodeSessionPrx session = _node->getMasterNodeSession(); + auto session = _node->getMasterNodeSession(); if(session) { - _node->getMasterNodeSession()->begin_waitForApplicationUpdate( - desc->uuid, desc->revision, ::Ice::newCallback(this, &ServerI::waitForApplicationUpdateCompleted)); + _node->getMasterNodeSession()->waitForApplicationUpdateAsync(desc->uuid, desc->revision, + [self = shared_from_this()] + { + self->waitForApplicationUpdateCompleted(); + }, + [self = shared_from_this()](exception_ptr) + { + self->waitForApplicationUpdateCompleted(); + }); return; } } @@ -1523,27 +1498,27 @@ ServerI::activate() // Compute the server command line options. // Ice::StringSeq options; - for(Ice::StringSeq::const_iterator p = desc->options.begin(); p != desc->options.end(); ++p) + for(const auto& opt : desc->options) { - if(!p->empty()) + if(!opt.empty()) { - options.push_back(*p); + options.push_back(opt); } } options.push_back("--Ice.Config=" + escapeProperty(_serverDir + "/config/config")); Ice::StringSeq envs; - transform(desc->envs.begin(), desc->envs.end(), back_inserter(envs), EnvironmentEval()); + transform(desc->envs.begin(), desc->envs.end(), back_inserter(envs), environmentEval); // // Clear the adapters direct proxy (this is usefull if the server // was manually activated). // - for(ServerAdapterDict::iterator p = adpts.begin(); p != adpts.end(); ++p) + for(const auto& adpt : adpts) { try { - p->second->clear(); + adpt.second->clear(); } catch(const Ice::ObjectNotExistException&) { @@ -1551,28 +1526,28 @@ ServerI::activate() } #ifndef _WIN32 - int pid = _node->getActivator()->activate(desc->id, desc->exe, desc->pwd, uid, gid, options, envs, this); + int pid = _node->getActivator()->activate(desc->id, desc->exe, desc->pwd, uid, gid, options, envs, shared_from_this()); #else - int pid = _node->getActivator()->activate(desc->id, desc->exe, desc->pwd, options, envs, this); + int pid = _node->getActivator()->activate(desc->id, desc->exe, desc->pwd, options, envs, shared_from_this()); #endif - ServerCommandPtr command; + shared_ptr<ServerCommand> command; bool active = false; { - Lock sync(*this); + lock_guard lock(_mutex); assert(_state == Activating); _pid = pid; - setStateNoSync(ServerI::WaitForActivation); + setStateNoSync(InternalServerState::WaitForActivation); active = checkActivation(); command = nextCommand(); - notifyAll(); // Terminated might be waiting for the state change. + _condVar.notify_all(); // Terminated might be waiting for the state change. } if(active) { - for(ServerAdapterDict::iterator r = adpts.begin(); r != adpts.end(); ++r) + for(const auto& adpt : adpts) { try { - r->second->activationCompleted(); + adpt.second->activationCompleted(); } catch(const Ice::ObjectNotExistException&) { @@ -1599,16 +1574,16 @@ ServerI::activate() } { - Lock sync(*this); + lock_guard lock(_mutex); disableOnFailure(); - setStateNoSync(ServerI::Deactivating, failure); + setStateNoSync(InternalServerState::Deactivating, failure); } - for(ServerAdapterDict::iterator r = adpts.begin(); r != adpts.end(); ++r) + for(const auto& adpt : adpts) { try { - r->second->activationFailed(failure); + adpt.second->activationFailed(failure); } catch(const Ice::ObjectNotExistException&) { @@ -1622,7 +1597,7 @@ void ServerI::kill() { { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Destroying && _state != Deactivating && _state != DeactivatingWaitForProcess) { return; @@ -1645,9 +1620,9 @@ ServerI::kill() void ServerI::deactivate() { - Ice::ProcessPrx process; + shared_ptr<Ice::ProcessPrx> process; { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Deactivating && _state != DeactivatingWaitForProcess) { return; @@ -1662,7 +1637,7 @@ ServerI::deactivate() // if(_desc->processRegistered && !_process) { - setStateNoSync(ServerI::DeactivatingWaitForProcess); + setStateNoSync(InternalServerState::DeactivatingWaitForProcess); return; } process = _process; @@ -1673,7 +1648,7 @@ ServerI::deactivate() // // Deactivate the server and for the termination of the server. // - _node->getActivator()->deactivate(_id, process); + _node->getActivator()->deactivate(_id, move(process)); return; } catch(const Ice::Exception& ex) @@ -1705,13 +1680,13 @@ ServerI::destroy() { ServerAdapterDict adpts; { - Lock sync(*this); + lock_guard lock(_mutex); assert(_desc); assert(_state == Destroying); adpts = _adapters; } - _node->removeServer(this, _desc->application); + _node->removeServer(shared_from_this(), _desc->application); // // Remove the server directory only if the clear dir flag is set (user @@ -1737,11 +1712,11 @@ ServerI::destroy() // // Destroy the object adapters. // - for(ServerAdapterDict::const_iterator p = adpts.begin(); p != adpts.end(); ++p) + for(const auto& adpt : adpts) { try { - p->second->destroy(); + adpt.second->destroy(); } catch(const Ice::LocalException&) { @@ -1756,11 +1731,10 @@ ServerI::terminated(const string& msg, int status) { ServerAdapterDict adpts; { - Lock sync(*this); - while(_state == ServerI::Activating) - { - wait(); // Wait for activate() to set the state to WaitForActivation - } + unique_lock lock(_mutex); + + // Wait for activate() to set the state to WaitForActivation + _condVar.wait(lock, [this] { return _state != Activating; }); adpts = _adapters; _activatedAdapters.clear(); @@ -1782,9 +1756,9 @@ ServerI::terminated(const string& msg, int status) disableOnFailure(); } - if(_state != ServerI::Deactivating && - _state != ServerI::DeactivatingWaitForProcess && - _state != ServerI::Destroying) + if(_state != InternalServerState::Deactivating && + _state != InternalServerState::DeactivatingWaitForProcess && + _state != InternalServerState::Destroying) { ostringstream os; os << "The server terminated unexpectedly"; @@ -1801,7 +1775,7 @@ ServerI::terminated(const string& msg, int status) os << " with exit code " << status; #endif os << (msg.empty() ? string(".") : ":\n" + msg); - setStateNoSync(ServerI::Deactivating, os.str()); + setStateNoSync(InternalServerState::Deactivating, os.str()); } } @@ -1810,11 +1784,11 @@ ServerI::terminated(const string& msg, int status) // null to cause the server re-activation if one of its adapter // direct proxy is requested. // - for(ServerAdapterDict::iterator p = adpts.begin(); p != adpts.end(); ++p) + for(const auto& adpt : adpts) { try { - p->second->setDirectProxy(0, Ice::emptyCurrent); + adpt.second->setDirectProxy(nullptr, Ice::emptyCurrent); } catch(const Ice::ObjectNotExistException&) { @@ -1822,16 +1796,16 @@ ServerI::terminated(const string& msg, int status) } bool doDestroy = false; - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); - if(_state == ServerI::Destroying) + lock_guard lock(_mutex); + if(_state == InternalServerState::Destroying) { doDestroy = true; } else { - setStateNoSync(ServerI::Inactive); + setStateNoSync(InternalServerState::Inactive); command = nextCommand(); } } @@ -1848,27 +1822,27 @@ ServerI::terminated(const string& msg, int status) void ServerI::shutdown() { - Lock sync(*this); - assert(_state == ServerI::Inactive); + lock_guard lock(_mutex); + assert(_state == InternalServerState::Inactive); assert(!_destroy); assert(!_stop); assert(!_load); assert(!_start); - _timerTask = 0; + _timerTask = nullptr; } void ServerI::update() { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); - if(_state != ServerI::Loading) + lock_guard lock(_mutex); + if(_state != InternalServerState::Loading) { return; } - InternalServerDescriptorPtr oldDescriptor = _desc; + auto oldDescriptor = _desc; bool disabled = oldDescriptor && _activation == Disabled; try { @@ -1901,8 +1875,8 @@ ServerI::update() { if(oldDescriptor->application != _desc->application) { - _node->removeServer(this, oldDescriptor->application); - _node->addServer(this, _desc->application); + _node->removeServer(shared_from_this(), oldDescriptor->application); + _node->addServer(shared_from_this(), _desc->application); } if(_node->getTraceLevels()->server > 0) @@ -1913,13 +1887,13 @@ ServerI::update() } else { - _node->addServer(this, _desc->application); + _node->addServer(shared_from_this(), _desc->application); } AdapterPrxDict adapters; - for(ServerAdapterDict::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + for(const auto& adpt : _adapters) { - adapters.insert(make_pair(p->first, p->second->getProxy())); + adapters.insert({ adpt.first, adpt.second->getProxy() }); } _load->finished(_this, adapters, _activationTimeout, _deactivationTimeout); } @@ -1937,7 +1911,7 @@ ServerI::update() catch(const Ice::Exception& e) { Ice::Warning out(_node->getTraceLevels()->logger); - out << "update failed:\n" << ex.reason << "\nand couldn't rollback old descriptor:\n" << e; + out << "update failed:\n" << ex.reason << "\nand couldn't rollback old descriptor:\n" << e.what(); } catch(const exception& e) { @@ -1947,10 +1921,10 @@ ServerI::update() } else if(!_destroy) { - _destroy = new DestroyCommand(this, true, true); + _destroy = make_shared<DestroyCommand>(shared_from_this(), true, true); } - _load->failed(ex); + _load->failed(current_exception()); } if(oldDescriptor && disabled != (_activation == Disabled)) @@ -1967,7 +1941,7 @@ ServerI::update() } void -ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) +ServerI::updateImpl(const shared_ptr<InternalServerDescriptor>& descriptor) { assert(_load && descriptor); @@ -1993,27 +1967,26 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) ServerAdapterDict oldAdapters; oldAdapters.swap(_adapters); _serverLifetimeAdapters.clear(); - Ice::ObjectAdapterPtr adapter = _node->getAdapter(); - for(InternalAdapterDescriptorSeq::const_iterator r = _desc->adapters.begin(); r != _desc->adapters.end(); ++r) + auto adapter = _node->getAdapter(); + for(const auto& adpt : _desc->adapters) { try { - Ice::Identity id; - id.category = _this->ice_getIdentity().category + "Adapter"; - id.name = _id + "-" + (*r)->id; - ServerAdapterIPtr servant = ServerAdapterIPtr::dynamicCast(adapter->find(id)); + Ice::Identity id = { _id + "-" + adpt->id, _this->ice_getIdentity().category + "Adapter" }; + auto servant = dynamic_pointer_cast<ServerAdapterI>(adapter->find(id)); if(!servant) { - AdapterPrx proxy = AdapterPrx::uncheckedCast(adapter->createProxy(id)); - servant = new ServerAdapterI(_node, this, _id, proxy, (*r)->id, _activation != Disabled || - _failureTime != IceUtil::Time()); + auto proxy = Ice::uncheckedCast<AdapterPrx>(adapter->createProxy(id)); + servant = make_shared<ServerAdapterI>(_node, this, _id, proxy, adpt->id, + _activation != Disabled || + _failureTime != nullopt); adapter->add(servant, id); } - _adapters.insert(make_pair((*r)->id, servant)); + _adapters.insert(make_pair(adpt->id, servant)); - if((*r)->serverLifetime) + if(adpt->serverLifetime) { - _serverLifetimeAdapters.insert((*r)->id); + _serverLifetimeAdapters.insert(adpt->id); } } catch(const Ice::ObjectAdapterDeactivatedException&) @@ -2023,19 +1996,19 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) catch(const Ice::LocalException& ex) { Ice::Error out(_node->getTraceLevels()->logger); - out << "couldn't add adapter `" << (*r)->id << "':\n" << ex; + out << "couldn't add adapter `" << adpt->id << "':\n" << ex; } - oldAdapters.erase((*r)->id); + oldAdapters.erase(adpt->id); } // // Remove old object adapters. // - for(ServerAdapterDict::const_iterator t = oldAdapters.begin(); t != oldAdapters.end(); ++t) + for(const auto& adpt : oldAdapters) { try { - t->second->destroy(); + adpt.second->destroy(); } catch(const Ice::ObjectAdapterDeactivatedException&) { @@ -2044,7 +2017,7 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) catch(const Ice::LocalException& ex) { Ice::Error out(_node->getTraceLevels()->logger); - out << "couldn't destroy adapter `" << t->first << "':\n" << ex; + out << "couldn't destroy adapter `" << adpt.first << "':\n" << ex; } } } @@ -2056,27 +2029,44 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // disabled and failure time isn't set, we don't change the // activation since the user explicitely disabled the server. // - if(_activation != Disabled || _failureTime != IceUtil::Time()) + if(_activation != Disabled || _failureTime != nullopt) { _activation = toServerActivation(_desc->activation); - _failureTime = IceUtil::Time(); + _failureTime = nullopt; } if(_timerTask) { _node->getTimer()->cancel(_timerTask); - _timerTask = 0; + _timerTask = nullptr; } checkAndUpdateUser(_desc, true); // we pass true to update _uid/_gid. - istringstream at(_desc->activationTimeout); - if(!(at >> _activationTimeout) || !at.eof() || _activationTimeout == 0) + try + { + _activationTimeout = chrono::seconds(stoi(_desc->activationTimeout)); + } + catch(const std::exception&) + { + _activationTimeout = 0s; + } + + if(_activationTimeout == 0s) { _activationTimeout = _waitTime; } - istringstream dt(_desc->deactivationTimeout); - if(!(dt >> _deactivationTimeout) || !dt.eof() || _deactivationTimeout == 0) + + try + { + _deactivationTimeout = chrono::seconds(stoi(_desc->deactivationTimeout)); + } + catch(const std::exception&) + { + _deactivationTimeout = 0s; + } + + if (_deactivationTimeout == 0s) { _deactivationTimeout = _waitTime; } @@ -2085,9 +2075,9 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // Simplify the log paths and transform relative paths into // absolute paths, also make sure the logs are sorted. // - for(Ice::StringSeq::const_iterator p = _desc->logs.begin(); p != _desc->logs.end(); ++p) + for(const auto& log : _desc->logs) { - string path = simplify(*p); + string path = simplify(log); if(IceUtilInternal::isAbsolutePath(path)) { _logs.push_back(path); @@ -2105,7 +2095,7 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) _stdOutFile = getProperty(props, "Ice.StdOut"); // - // If the server is a session server and it wasn't udpated but + // If the server is a session server and it wasn't updated but // just released by a session, we don't update the configuration, // it will be done when the server is re-allocated. // @@ -2136,26 +2126,26 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // previous to Ice 3.3. // Ice::StringSeq knownFiles; - for(PropertyDescriptorSeqDict::const_iterator p = properties.begin(); p != properties.end(); ++p) + for(const auto& prop : properties) { - knownFiles.push_back(p->first); + knownFiles.push_back(prop.first); - const string configFilePath = _serverDir + "/config/" + p->first; + const string configFilePath = _serverDir + "/config/" + prop.first; ofstream configfile(IceUtilInternal::streamFilename(configFilePath).c_str()); // configFilePath is a UTF-8 string if(!configfile.good()) { throw runtime_error("couldn't create configuration file: " + configFilePath); } configfile << "# Configuration file (" << IceUtil::Time::now().toDateTime() << ")" << endl << endl; - for(PropertyDescriptorSeq::const_iterator r = p->second.begin(); r != p->second.end(); ++r) + for(const auto& propertyDescriptor : prop.second) { - if(r->value.empty() && r->name.find('#') == 0) + if(propertyDescriptor.value.empty() && propertyDescriptor.name.find('#') == 0) { - configfile << r->name << endl; + configfile << propertyDescriptor.name << endl; } else { - configfile << r->name << "=" << r->value << endl; + configfile << propertyDescriptor.name << "=" << propertyDescriptor.value << endl; } } configfile.close(); @@ -2167,19 +2157,19 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // Ice::StringSeq files = readDirectory(_serverDir + "/config"); Ice::StringSeq toDel; - set_difference(files.begin(), files.end(), knownFiles.begin(), knownFiles.end(), back_inserter(toDel)); - for(Ice::StringSeq::const_iterator q = toDel.begin(); q != toDel.end(); ++q) + std::set_difference(files.begin(), files.end(), knownFiles.begin(), knownFiles.end(), back_inserter(toDel)); + for(const auto& str : toDel) { - if(q->find("config_") == 0) + if(str.find("config_") == 0) { try { - remove(_serverDir + "/config/" + *q); + remove(_serverDir + "/config/" + str); } catch(const exception& ex) { Ice::Warning out(_node->getTraceLevels()->logger); - out << "couldn't remove file `" << _serverDir << "/config/" << *q << "':\n" << ex.what(); + out << "couldn't remove file `" << _serverDir << "/config/" << str << "':\n" << ex.what(); } } } @@ -2203,86 +2193,25 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // Ice::StringSeq dirs = readDirectory(_serverDir); Ice::StringSeq svcDirs; - for(Ice::StringSeq::const_iterator p = dirs.begin(); p != dirs.end(); ++p) + for(const auto& dir : dirs) { - if(p->find("data_") == 0) + if(dir.find("data_") == 0) { - svcDirs.push_back(*p); + svcDirs.push_back(dir); } } Ice::StringSeq toDel; - set_difference(svcDirs.begin(), svcDirs.end(), knownDirs.begin(), knownDirs.end(), back_inserter(toDel)); - for(Ice::StringSeq::const_iterator p = toDel.begin(); p != toDel.end(); ++p) - { - try - { - removeRecursive(_serverDir + "/" + *p); - } - catch(const exception& ex) - { - Ice::Warning out(_node->getTraceLevels()->logger); - out << "couldn't remove directory `" << _serverDir << "/" << *p << "':\n" << ex.what(); - } - } - } - - // - // Update the database environments if necessary and remove the - // old ones. - // - { - Ice::StringSeq knownDbEnvs; - for(InternalDbEnvDescriptorSeq::const_iterator q = _desc->dbEnvs.begin(); q != _desc->dbEnvs.end(); ++q) - { - knownDbEnvs.push_back((*q)->name); - - string dbEnvHome = _serverDir + "/dbs/" + (*q)->name; - createDirectory(dbEnvHome); - - if(!(*q)->properties.empty()) - { - string file = dbEnvHome + "/DB_CONFIG"; - - ofstream configfile(IceUtilInternal::streamFilename(file).c_str()); // file is a UTF-8 string - if(!configfile.good()) - { - throw runtime_error("couldn't create configuration file `" + file + "'"); - } - - for(PropertyDescriptorSeq::const_iterator p = (*q)->properties.begin(); - p != (*q)->properties.end(); ++p) - { - if(!p->name.empty()) - { - configfile << p->name; - if(!p->value.empty()) - { - configfile << " " << p->value; - } - configfile << endl; - } - } - configfile.close(); - } - } - sort(knownDbEnvs.begin(), knownDbEnvs.end()); - - // - // Remove old database environments. - // - Ice::StringSeq dbEnvs = readDirectory(_serverDir + "/dbs"); - Ice::StringSeq toDel; - set_difference(dbEnvs.begin(), dbEnvs.end(), knownDbEnvs.begin(), knownDbEnvs.end(), back_inserter(toDel)); - for(Ice::StringSeq::const_iterator p = toDel.begin(); p != toDel.end(); ++p) + std::set_difference(svcDirs.begin(), svcDirs.end(), knownDirs.begin(), knownDirs.end(), back_inserter(toDel)); + for(const auto& str : toDel) { try { - removeRecursive(_serverDir + "/dbs/" + *p); + removeRecursive(_serverDir + "/" + str); } catch(const exception& ex) { Ice::Warning out(_node->getTraceLevels()->logger); - out << "couldn't remove directory `" << _serverDir << "/dbs/" << *p << "':\n" << ex.what(); + out << "couldn't remove directory `" << _serverDir << "/" << str << "':\n" << ex.what(); } } } @@ -2345,7 +2274,7 @@ ServerI::checkRevision(const string& replicaName, const string& uuid, int revisi } void -ServerI::checkNoRestart(const InternalServerDescriptorPtr& desc) +ServerI::checkNoRestart(const shared_ptr<InternalServerDescriptor>& desc) { assert(_desc); @@ -2362,10 +2291,10 @@ ServerI::checkNoRestart(const InternalServerDescriptorPtr& desc) #ifndef _WIN32 void -ServerI::checkAndUpdateUser(const InternalServerDescriptorPtr& desc, bool update) +ServerI::checkAndUpdateUser(const shared_ptr<InternalServerDescriptor>& desc, bool update) #else void -ServerI::checkAndUpdateUser(const InternalServerDescriptorPtr& desc, bool /*update*/) +ServerI::checkAndUpdateUser(const shared_ptr<InternalServerDescriptor>& desc, bool /*update*/) #endif { #ifndef _WIN32 @@ -2400,7 +2329,7 @@ ServerI::checkAndUpdateUser(const InternalServerDescriptorPtr& desc, bool /*upda if(!user.empty()) { - UserAccountMapperPrx mapper = _node->getUserAccountMapper(); + auto mapper = _node->getUserAccountMapper(); if(mapper) { try @@ -2529,9 +2458,9 @@ ServerI::updateRevision(const string& uuid, int revision) } void -ServerI::updateRuntimePropertiesCallback(const InternalServerDescriptorPtr& desc) +ServerI::updateRuntimePropertiesCallback(const shared_ptr<InternalServerDescriptor>& desc) { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Active || !_load) { return; @@ -2540,18 +2469,18 @@ ServerI::updateRuntimePropertiesCallback(const InternalServerDescriptorPtr& desc if(_load->finishRuntimePropertiesUpdate(desc, _process)) { AdapterPrxDict adapters; - for(ServerAdapterDict::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + for(const auto& [id, servant] : _adapters) { - adapters.insert(make_pair(p->first, p->second->getProxy())); + adapters.insert({ id, servant->getProxy() }); } _load->finished(_this, adapters, _activationTimeout, _deactivationTimeout); } } void -ServerI::updateRuntimePropertiesCallback(const Ice::Exception& ex, const InternalServerDescriptorPtr& desc) +ServerI::updateRuntimePropertiesCallback(exception_ptr ex, const shared_ptr<InternalServerDescriptor>& desc) { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Active || !_load) { return; @@ -2567,7 +2496,7 @@ bool ServerI::checkActivation() { //assert(locked()); - if(_state == ServerI::WaitForActivation || _state == ServerI::ActivationTimeout) + if(_state == InternalServerState::WaitForActivation || _state == InternalServerState::ActivationTimeout) { // // Mark the server as active if the server process proxy is registered (or it's not expecting @@ -2577,7 +2506,7 @@ ServerI::checkActivation() includes(_activatedAdapters.begin(), _activatedAdapters.end(), _serverLifetimeAdapters.begin(), _serverLifetimeAdapters.end())) { - setStateNoSync(ServerI::Active); + setStateNoSync(InternalServerState::Active); return true; } } @@ -2587,9 +2516,9 @@ ServerI::checkActivation() void ServerI::setState(InternalServerState st, const std::string& reason) { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; { - Lock sync(*this); + lock_guard lock(_mutex); setStateNoSync(st, reason); command = nextCommand(); } @@ -2599,10 +2528,10 @@ ServerI::setState(InternalServerState st, const std::string& reason) } } -ServerCommandPtr +shared_ptr<ServerCommand> ServerI::nextCommand() { - ServerCommandPtr command; + shared_ptr<ServerCommand> command; if(_stop && _stop->canExecute(_state)) { command = _stop; @@ -2627,7 +2556,7 @@ ServerI::nextCommand() } void -ServerI::setStateNoSync(InternalServerState st, const std::string& reason) +ServerI::setStateNoSync(InternalServerState st, const string& reason) { // // Ensure that the given state can be switched to. @@ -2680,51 +2609,51 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) case Inactive: if(previous == Loading) { - _load = 0; + _load = nullptr; } if(_stop) { _stop->finished(); - _stop = 0; + _stop = nullptr; } break; case Active: if(_start) { _start->finished(); - _start = 0; + _start = nullptr; } break; case ActivationTimeout: if(_start) { _start->failed(reason); - _start = 0; + _start = nullptr; } break; case Deactivating: if(_start) { _start->failed(reason.empty() ? string("The server is being deactivated.") : reason); - _start = 0; + _start = nullptr; } break; case Destroying: loadFailure = _destroy->loadFailure(); if(_load) { - _load->failed(DeploymentException("The server is being destroyed.")); - _load = 0; + _load->failed(make_exception_ptr(DeploymentException("The server is being destroyed."))); + _load = nullptr; } if(_start) { _start->failed("The server is being destroyed."); - _start = 0; + _start = nullptr; } if(_stop) { _stop->failed("The server is being destroyed."); - _stop = 0; + _stop = nullptr; } break; case Destroyed: @@ -2732,9 +2661,9 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) { loadFailure = _destroy->loadFailure(); _destroy->finished(); - _destroy = 0; + _destroy = nullptr; } - notifyAll(); // for getProperties() + _condVar.notify_all(); // for getProperties() break; default: break; @@ -2743,7 +2672,7 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) if(_timerTask) { _node->getTimer()->cancel(_timerTask); - _timerTask = 0; + _timerTask = nullptr; } if(_state == Destroyed && !_load) @@ -2760,14 +2689,14 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) { // IGNORE } - _desc = 0; + _desc = nullptr; } else if(_state == Inactive) { if(_activation == Always) { assert(!_timerTask); - _timerTask = new DelayedStart(this, _node->getTraceLevels()); + _timerTask = make_shared<DelayedStart>(shared_from_this(), _node->getTraceLevels()); try { _node->getTimer()->schedule(_timerTask, IceUtil::Time::milliSeconds(500)); @@ -2777,7 +2706,9 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) // Ignore, timer is destroyed because node is shutting down. } } - else if(_activation == Disabled && _disableOnFailure > 0 && _failureTime != IceUtil::Time()) + else if(_activation == Disabled && + _disableOnFailure > 0s && + _failureTime != nullopt ) { // // If the server was disabled because it failed, we @@ -2787,15 +2718,15 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) // callback is executed. // assert(!_timerTask); - _timerTask = new DelayedStart(this, _node->getTraceLevels()); + _timerTask = make_shared<DelayedStart>(shared_from_this(), _node->getTraceLevels()); try { - IceUtil::Time now = IceUtil::Time::now(IceUtil::Time::Monotonic); - if(now - _failureTime < IceUtil::Time::seconds(_disableOnFailure)) + using namespace std::chrono; + auto now = steady_clock::now(); + if(now - *_failureTime < _disableOnFailure) { - _node->getTimer()->schedule(_timerTask, - IceUtil::Time::seconds(_disableOnFailure) - now + _failureTime + - IceUtil::Time::milliSeconds(500)); + auto delay = duration_cast<milliseconds>(_disableOnFailure - (now - *_failureTime)); + _node->getTimer()->schedule(_timerTask, IceUtil::Time::milliSeconds((delay + 500ms).count())); } else { @@ -2892,26 +2823,26 @@ ServerI::toServerState(InternalServerState st) const { switch(st) { - case ServerI::Inactive: - case ServerI::Activating: - case ServerI::Loading: - return IceGrid::Inactive; - case ServerI::WaitForActivation: - return IceGrid::Activating; - case ServerI::ActivationTimeout: - return IceGrid::ActivationTimedOut; - case ServerI::Active: - return IceGrid::Active; - case ServerI::Deactivating: - case ServerI::DeactivatingWaitForProcess: - return IceGrid::Deactivating; - case ServerI::Destroying: - return IceGrid::Destroying; - case ServerI::Destroyed: - return IceGrid::Destroyed; + case InternalServerState::Inactive: + case InternalServerState::Activating: + case InternalServerState::Loading: + return ServerState::Inactive; + case InternalServerState::WaitForActivation: + return ServerState::Activating; + case InternalServerState::ActivationTimeout: + return ServerState::ActivationTimedOut; + case InternalServerState::Active: + return ServerState::Active; + case InternalServerState::Deactivating: + case InternalServerState::DeactivatingWaitForProcess: + return ServerState::Deactivating; + case InternalServerState::Destroying: + return ServerState::Destroying; + case InternalServerState::Destroyed: + return ServerState::Destroyed; default: assert(false); - return IceGrid::Destroyed; + return ServerState::Destroyed; } } @@ -2998,7 +2929,7 @@ ServerI::getFilePath(const string& filename) const } PropertyDescriptorSeqDict -ServerI::getProperties(const InternalServerDescriptorPtr& desc) +ServerI::getProperties(const shared_ptr<InternalServerDescriptor>& desc) { // // Copy the descriptor properties. @@ -3038,7 +2969,7 @@ ServerI::getProperties(const InternalServerDescriptorPtr& desc) { if(getProperty(p->second, "Ice.Default.Locator").empty()) { - Ice::PropertiesPtr properties = _node->getCommunicator()->getProperties(); + auto properties = _node->getCommunicator()->getProperties(); string locator = properties->getProperty("Ice.Default.Locator"); if(!locator.empty()) diff --git a/cpp/src/IceGrid/ServerI.h b/cpp/src/IceGrid/ServerI.h index a41fc9efd0d..22ae58ed6b5 100644 --- a/cpp/src/IceGrid/ServerI.h +++ b/cpp/src/IceGrid/ServerI.h @@ -5,10 +5,11 @@ #ifndef ICE_GRID_SERVER_I_H #define ICE_GRID_SERVER_I_H -#include <IceUtil/Mutex.h> #include <IceUtil/Timer.h> #include <IceGrid/Activator.h> #include <IceGrid/Internal.h> + +#include <optional> #include <set> #ifndef _WIN32 @@ -19,21 +20,14 @@ namespace IceGrid { class NodeI; -typedef IceUtil::Handle<NodeI> NodeIPtr; class ServerAdapterI; -typedef IceUtil::Handle<ServerAdapterI> ServerAdapterIPtr; class ServerCommand; -typedef IceUtil::Handle<ServerCommand> ServerCommandPtr; class DestroyCommand; -typedef IceUtil::Handle<DestroyCommand> DestroyCommandPtr; class StopCommand; -typedef IceUtil::Handle<StopCommand> StopCommandPtr; class StartCommand; -typedef IceUtil::Handle<StartCommand> StartCommandPtr; class LoadCommand; -typedef IceUtil::Handle<LoadCommand> LoadCommandPtr; -class ServerI : public Server, public IceUtil::Monitor<IceUtil::Mutex> +class ServerI final : public Server, public std::enable_shared_from_this<ServerI> { public: @@ -67,34 +61,37 @@ public: # pragma clang diagnostic pop #endif - ServerI(const NodeIPtr&, const ServerPrx&, const std::string&, const std::string&, int); - virtual ~ServerI(); + ServerI(const std::shared_ptr<NodeI>&, const std::shared_ptr<ServerPrx>&, + const std::string&, const std::string&, int); - void waitForApplicationUpdateCompleted(const Ice::AsyncResultPtr&); + void waitForApplicationUpdateCompleted(); - virtual void start_async(const AMD_Server_startPtr&, const ::Ice::Current&); - virtual void stop_async(const AMD_Server_stopPtr&, const ::Ice::Current&); - virtual void sendSignal(const std::string&, const ::Ice::Current&); - virtual void writeMessage(const std::string&, Ice::Int, const ::Ice::Current&); + void startAsync(std::function<void()>, std::function<void(std::exception_ptr)>, const Ice::Current&) override; + void stopAsync(std::function<void()>, std::function<void(std::exception_ptr)>, const Ice::Current&) override; + void sendSignal(std::string, const Ice::Current&) override; + void writeMessage(std::string, int, const Ice::Current&) override; - virtual ServerState getState(const ::Ice::Current&) const; - virtual Ice::Int getPid(const ::Ice::Current&) const; + ServerState getState(const Ice::Current&) const override; + int getPid(const Ice::Current&) const override; - virtual void setEnabled(bool, const ::Ice::Current&); - virtual bool isEnabled(const ::Ice::Current&) const; - virtual void setProcess_async(const AMD_Server_setProcessPtr&, const ::Ice::ProcessPrx&, const ::Ice::Current&); + void setEnabled(bool, const Ice::Current&) override; + bool isEnabled(const Ice::Current&) const override; + void setProcessAsync(std::shared_ptr<Ice::ProcessPrx>, std::function<void()>, + std::function<void(std::exception_ptr)>, const Ice::Current&) override; - virtual Ice::Long getOffsetFromEnd(const std::string&, int, const Ice::Current&) const; - virtual bool read(const std::string&, Ice::Long, int, Ice::Long&, Ice::StringSeq&, const Ice::Current&) const; + long long getOffsetFromEnd(std::string, int, const Ice::Current&) const override; + bool read(std::string, long long, int, long long&, Ice::StringSeq&, const Ice::Current&) const override; bool isAdapterActivatable(const std::string&) const; const std::string& getId() const; - void start(ServerActivation, const AMD_Server_startPtr& = AMD_Server_startPtr()); - ServerCommandPtr load(const AMD_Node_loadServerPtr&, const InternalServerDescriptorPtr&, const std::string&, bool); - bool checkUpdate(const InternalServerDescriptorPtr&, bool, const Ice::Current&); + void start(ServerActivation, std::function<void()> = nullptr, std::function<void(std::exception_ptr)> = nullptr); + std::shared_ptr<ServerCommand> load(const std::shared_ptr<InternalServerDescriptor>&, const std::string&, bool, + std::function<void(const std::shared_ptr<ServerPrx> &, const AdapterPrxDict &, int, int)>, + std::function<void(std::exception_ptr)>); + bool checkUpdate(std::shared_ptr<InternalServerDescriptor>, bool, const Ice::Current&) override; void checkRemove(bool, const Ice::Current&); - ServerCommandPtr destroy(const AMD_Node_destroyServerPtr&, const std::string&, int, const std::string&, bool); + std::shared_ptr<ServerCommand> destroy(const std::string&, int, const std::string &, bool, std::function<void()>); void adapterActivated(const std::string&); void adapterDeactivated(const std::string&); @@ -111,26 +108,26 @@ public: // // A proxy to the Process facet of the real Admin object; called by the AdminFacade servant implementation // - Ice::ObjectPrx getProcess() const; + std::shared_ptr<Ice::ObjectPrx> getProcess() const; - PropertyDescriptorSeqDict getProperties(const InternalServerDescriptorPtr&); + PropertyDescriptorSeqDict getProperties(const std::shared_ptr<InternalServerDescriptor>&); - void updateRuntimePropertiesCallback(const InternalServerDescriptorPtr&); - void updateRuntimePropertiesCallback(const Ice::Exception&, const InternalServerDescriptorPtr&); + void updateRuntimePropertiesCallback(const std::shared_ptr<InternalServerDescriptor>&); + void updateRuntimePropertiesCallback(std::exception_ptr, const std::shared_ptr<InternalServerDescriptor>&); private: - void updateImpl(const InternalServerDescriptorPtr&); + void updateImpl(const std::shared_ptr<InternalServerDescriptor>&); void checkRevision(const std::string&, const std::string&, int) const; - void checkNoRestart(const InternalServerDescriptorPtr&); - void checkAndUpdateUser(const InternalServerDescriptorPtr&, bool); + void checkNoRestart(const std::shared_ptr<InternalServerDescriptor>&); + void checkAndUpdateUser(const std::shared_ptr<InternalServerDescriptor>&, bool); void updateRevision(const std::string&, int); bool checkActivation(); void checkDestroyed() const; void disableOnFailure(); void setState(InternalServerState, const std::string& = std::string()); - ServerCommandPtr nextCommand(); + std::shared_ptr<ServerCommand> nextCommand(); void setStateNoSync(InternalServerState, const std::string& = std::string()); ServerState toServerState(InternalServerState) const; @@ -138,66 +135,68 @@ private: ServerDynamicInfo getDynamicInfo() const; std::string getFilePath(const std::string&) const; - const NodeIPtr _node; - const ServerPrx _this; + const std::shared_ptr<NodeI> _node; + const std::shared_ptr<ServerPrx> _this; const std::string _id; - const Ice::Int _waitTime; + const std::chrono::seconds _waitTime; const std::string _serverDir; - const int _disableOnFailure; + const std::chrono::seconds _disableOnFailure; - InternalServerDescriptorPtr _desc; + std::shared_ptr<InternalServerDescriptor> _desc; #ifndef _WIN32 uid_t _uid; gid_t _gid; #endif InternalServerState _state; ServerActivation _activation; - int _activationTimeout; - int _deactivationTimeout; - typedef std::map<std::string, ServerAdapterIPtr> ServerAdapterDict; + std::chrono::seconds _activationTimeout; + std::chrono::seconds _deactivationTimeout; + using ServerAdapterDict = std::map<std::string, std::shared_ptr<ServerAdapterI>> ; ServerAdapterDict _adapters; std::set<std::string> _serverLifetimeAdapters; - Ice::ProcessPrx _process; + std::shared_ptr<Ice::ProcessPrx> _process; std::set<std::string> _activatedAdapters; - IceUtil::Time _failureTime; + std::optional<std::chrono::steady_clock::time_point> _failureTime; ServerActivation _previousActivation; - IceUtil::TimerTaskPtr _timerTask; + std::shared_ptr<IceUtil::TimerTask>_timerTask; bool _waitForReplication; std::string _stdErrFile; std::string _stdOutFile; Ice::StringSeq _logs; PropertyDescriptorSeq _properties; - DestroyCommandPtr _destroy; - StopCommandPtr _stop; - LoadCommandPtr _load; - StartCommandPtr _start; + std::shared_ptr<DestroyCommand> _destroy; + std::shared_ptr<StopCommand> _stop; + std::shared_ptr<LoadCommand> _load; + std::shared_ptr<StartCommand> _start; int _pid; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle<ServerI> ServerIPtr; -class ServerCommand : public IceUtil::SimpleShared +class ServerCommand { public: - ServerCommand(const ServerIPtr&); - virtual ~ServerCommand(); + ServerCommand(const std::shared_ptr<ServerI>&); + virtual ~ServerCommand() = default; + virtual bool canExecute(ServerI::InternalServerState) = 0; virtual void execute() = 0; virtual ServerI::InternalServerState nextState() = 0; protected: - const ServerIPtr _server; + const std::shared_ptr<ServerI> _server; }; -typedef IceUtil::Handle<ServerCommand> ServerCommandPtr; -class TimedServerCommand : public ServerCommand +class TimedServerCommand : public ServerCommand, public std::enable_shared_from_this<TimedServerCommand> { public: - TimedServerCommand(const ServerIPtr&, const IceUtil::TimerPtr&, int); + TimedServerCommand(const std::shared_ptr<ServerI>&, const IceUtil::TimerPtr&, std::chrono::seconds); virtual void timeout() = 0; void startTimer(); @@ -206,22 +205,21 @@ public: private: IceUtil::TimerPtr _timer; - IceUtil::TimerTaskPtr _timerTask; - int _timeout; + std::shared_ptr<IceUtil::TimerTask> _timerTask; + std::chrono::seconds _timeout; }; -typedef IceUtil::Handle<TimedServerCommand> TimedServerCommandPtr; class DestroyCommand : public ServerCommand { public: - DestroyCommand(const ServerIPtr&, bool, bool); + DestroyCommand(const std::shared_ptr<ServerI>&, bool, bool); - bool canExecute(ServerI::InternalServerState); - ServerI::InternalServerState nextState(); - void execute(); + bool canExecute(ServerI::InternalServerState) override; + ServerI::InternalServerState nextState() override; + void execute() override; - void addCallback(const AMD_Node_destroyServerPtr&); + void addCallback(std::function<void()>); void finished(); bool loadFailure() const; bool clearDir() const; @@ -230,29 +228,30 @@ private: const bool _loadFailure; const bool _clearDir; - std::vector<AMD_Node_destroyServerPtr> _destroyCB; + std::vector<std::function<void()>> _destroyCB; }; class StopCommand : public TimedServerCommand { public: - StopCommand(const ServerIPtr&, const IceUtil::TimerPtr&, int, bool = true); + StopCommand(const std::shared_ptr<ServerI>&, const IceUtil::TimerPtr&, std::chrono::seconds, + bool = true); static bool isStopped(ServerI::InternalServerState); - bool canExecute(ServerI::InternalServerState); - ServerI::InternalServerState nextState(); - void execute(); - void timeout(); + bool canExecute(ServerI::InternalServerState) override; + ServerI::InternalServerState nextState() override; + void execute() override; + void timeout() override; - void addCallback(const AMD_Server_stopPtr&); + void addCallback(std::function<void()>, std::function<void(std::exception_ptr)>); void failed(const std::string& reason); void finished(); private: - std::vector<AMD_Server_stopPtr> _stopCB; + std::vector<std::pair<std::function<void()>, std::function<void(std::exception_ptr)>>> _stopCB; bool _deactivate; }; @@ -260,50 +259,53 @@ class StartCommand : public TimedServerCommand { public: - StartCommand(const ServerIPtr&, const IceUtil::TimerPtr&, int); + using TimedServerCommand::TimedServerCommand; - bool canExecute(ServerI::InternalServerState); - ServerI::InternalServerState nextState(); - void execute(); - void timeout(); + bool canExecute(ServerI::InternalServerState) override; + ServerI::InternalServerState nextState() override; + void execute() override; + void timeout() override; - void addCallback(const AMD_Server_startPtr&); - void failed(const std::string& reason); + void addCallback(std::function<void()>, std::function<void(std::exception_ptr)>); + void failed(const std::string&); void finished(); private: - std::vector<AMD_Server_startPtr> _startCB; + std::vector<std::pair<std::function<void()>, std::function<void(std::exception_ptr)>>> _startCB; }; class LoadCommand : public ServerCommand { public: - LoadCommand(const ServerIPtr&, const InternalServerDescriptorPtr&, const TraceLevelsPtr&); + LoadCommand(const std::shared_ptr<ServerI>&, const std::shared_ptr<InternalServerDescriptor>&, + const std::shared_ptr<TraceLevels>&); - bool canExecute(ServerI::InternalServerState); - ServerI::InternalServerState nextState(); - void execute(); + bool canExecute(ServerI::InternalServerState) override; + ServerI::InternalServerState nextState() override; + void execute() override; - void setUpdate(const InternalServerDescriptorPtr&, bool); + void setUpdate(const std::shared_ptr<InternalServerDescriptor>&, bool); bool clearDir() const; - InternalServerDescriptorPtr getInternalServerDescriptor() const; - void addCallback(const AMD_Node_loadServerPtr&); - void startRuntimePropertiesUpdate(const Ice::ObjectPrx&); - bool finishRuntimePropertiesUpdate(const InternalServerDescriptorPtr&, const Ice::ObjectPrx&); - void failed(const Ice::Exception&); - void finished(const ServerPrx&, const AdapterPrxDict&, int, int); + std::shared_ptr<InternalServerDescriptor> getInternalServerDescriptor() const; + void addCallback(std::function<void(const std::shared_ptr<ServerPrx>&, const AdapterPrxDict &, int, int)>, + std::function<void(std::exception_ptr)>); + void startRuntimePropertiesUpdate(const std::shared_ptr<Ice::ObjectPrx>&); + bool finishRuntimePropertiesUpdate(const std::shared_ptr<InternalServerDescriptor>&, + const std::shared_ptr<Ice::ObjectPrx>&); + void failed(std::exception_ptr); + void finished(const std::shared_ptr<ServerPrx>&, const AdapterPrxDict&, std::chrono::seconds, std::chrono::seconds); private: - std::vector<AMD_Node_loadServerPtr> _loadCB; + std::vector<std::pair<std::function<void(const std::shared_ptr<ServerPrx> &, const AdapterPrxDict &, int, int)>, + std::function<void(std::exception_ptr)>>> _loadCB; bool _clearDir; - InternalServerDescriptorPtr _desc; - IceInternal::UniquePtr<DeploymentException> _exception; - InternalServerDescriptorPtr _runtime; + std::shared_ptr<InternalServerDescriptor> _desc; + std::shared_ptr<InternalServerDescriptor> _runtime; bool _updating; - TraceLevelsPtr _traceLevels; + std::shared_ptr<TraceLevels> _traceLevels; }; } diff --git a/cpp/src/IceGrid/SessionI.cpp b/cpp/src/IceGrid/SessionI.cpp index 16b27d53d11..3b9471e1c75 100644 --- a/cpp/src/IceGrid/SessionI.cpp +++ b/cpp/src/IceGrid/SessionI.cpp @@ -18,54 +18,50 @@ using namespace IceGrid; namespace IceGrid { -template<class T> -class AllocateObject : public ObjectAllocationRequest +class AllocateObject final : public ObjectAllocationRequest { - typedef IceUtil::Handle<T> TPtr; public: - AllocateObject(const SessionIPtr& session, const TPtr& cb) : - ObjectAllocationRequest(session), _cb(cb) + AllocateObject(const shared_ptr<SessionI>& session, + function<void(const shared_ptr<Ice::ObjectPrx>& returnValue)>&& response, + function<void(exception_ptr)>&& exception) : + ObjectAllocationRequest(session), _response(move(response)), _exception(move(exception)) { } - virtual void - response(const Ice::ObjectPrx& proxy) + void + response(const shared_ptr<Ice::ObjectPrx>& proxy) override { - assert(_cb); - _cb->ice_response(proxy); - _cb = 0; + assert(_response); + _response(proxy); + _response = nullptr; + } - virtual void - exception(const Ice::UserException& ex) + void + exception(exception_ptr ex) override { - assert(_cb); - _cb->ice_exception(ex); - _cb = 0; + assert(_exception); + _exception(ex); + _exception = nullptr; } private: - TPtr _cb; + function<void(const shared_ptr<Ice::ObjectPrx>& returnValue)> _response; + function<void(exception_ptr)> _exception; }; -template<class T> AllocateObject<T>* -newAllocateObject(const SessionIPtr& session, const IceUtil::Handle<T>& cb) -{ - return new AllocateObject<T>(session, cb); -} - } -BaseSessionI::BaseSessionI(const string& id, const string& prefix, const DatabasePtr& database) : +BaseSessionI::BaseSessionI(const string& id, const string& prefix, const shared_ptr<Database>& database) : _id(id), _prefix(prefix), _traceLevels(database->getTraceLevels()), _database(database), _destroyed(false), - _timestamp(IceUtil::Time::now(IceUtil::Time::Monotonic)) + _timestamp(chrono::steady_clock::now()) { if(_traceLevels && _traceLevels->session > 0) { @@ -74,20 +70,16 @@ BaseSessionI::BaseSessionI(const string& id, const string& prefix, const Databas } } -BaseSessionI::~BaseSessionI() -{ -} - void BaseSessionI::keepAlive(const Ice::Current& current) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__, current.id, "", ""); } - _timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic); + _timestamp = chrono::steady_clock::now(); if(_traceLevels->session > 1) { @@ -97,9 +89,9 @@ BaseSessionI::keepAlive(const Ice::Current& current) } void -BaseSessionI::destroyImpl(bool /*shutdown*/) +BaseSessionI::destroyImpl(bool) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -113,10 +105,10 @@ BaseSessionI::destroyImpl(bool /*shutdown*/) } } -IceUtil::Time +std::chrono::steady_clock::time_point BaseSessionI::timestamp() const { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -130,67 +122,70 @@ BaseSessionI::shutdown() destroyImpl(true); } -Glacier2::IdentitySetPrx +shared_ptr<Glacier2::IdentitySetPrx> BaseSessionI::getGlacier2IdentitySet() { assert(_servantManager); - return _servantManager->getGlacier2IdentitySet(this); + return _servantManager->getGlacier2IdentitySet(shared_from_this()); } -Glacier2::StringSetPrx +shared_ptr<Glacier2::StringSetPrx> BaseSessionI::getGlacier2AdapterIdSet() { assert(_servantManager); - return _servantManager->getGlacier2AdapterIdSet(this); + return _servantManager->getGlacier2AdapterIdSet(shared_from_this()); } -SessionI::SessionI(const string& id, const DatabasePtr& database, const IceUtil::TimerPtr& timer) : +SessionI::SessionI(const string& id, const shared_ptr<Database>& database, + const IceUtil::TimerPtr& timer) : BaseSessionI(id, "client", database), _timer(timer), _allocationTimeout(-1) { } -SessionI::~SessionI() -{ -} - -Ice::ObjectPrx -SessionI::_register(const SessionServantManagerPtr& servantManager, const Ice::ConnectionPtr& con) +shared_ptr<Ice::ObjectPrx> +SessionI::_register(const shared_ptr<SessionServantManager>& servantManager, const shared_ptr<Ice::Connection>& con) { // // This is supposed to be called after creation only, no need to synchronize. // _servantManager = servantManager; - return _servantManager->addSession(this, con, ""); + return _servantManager->addSession(shared_from_this(), con, ""); } void -SessionI::allocateObjectById_async(const AMD_Session_allocateObjectByIdPtr& cb, - const Ice::Identity& id, - const Ice::Current&) +SessionI::allocateObjectByIdAsync(Ice::Identity id, + function<void(const shared_ptr<Ice::ObjectPrx>& returnValue)> response, + function<void(exception_ptr)> exception, + const Ice::Current&) { - _database->getAllocatableObject(id)->allocate(newAllocateObject(this, cb)); + auto allocatedObject = make_shared<AllocateObject>(static_pointer_cast<SessionI>(shared_from_this()), + move(response), move(exception)); + _database->getAllocatableObject(id)->allocate(move(allocatedObject)); } void -SessionI::allocateObjectByType_async(const AMD_Session_allocateObjectByTypePtr& cb, - const string& type, - const Ice::Current&) +SessionI::allocateObjectByTypeAsync(string type, + function<void(const shared_ptr<Ice::ObjectPrx>& returnValue)> response, + function<void(exception_ptr)> exception, + const Ice::Current&) { - _database->getAllocatableObjectCache().allocateByType(type, newAllocateObject(this, cb)); + auto allocatedObject = make_shared<AllocateObject>(static_pointer_cast<SessionI>(shared_from_this()), + move(response), move(exception)); + _database->getAllocatableObjectCache().allocateByType(type, move(allocatedObject)); } void -SessionI::releaseObject(const Ice::Identity& id, const Ice::Current&) +SessionI::releaseObject(Ice::Identity id, const Ice::Current&) { - _database->getAllocatableObject(id)->release(this); + _database->getAllocatableObject(id)->release(static_pointer_cast<SessionI>(shared_from_this())); } void SessionI::setAllocationTimeout(int timeout, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); _allocationTimeout = timeout; } @@ -203,14 +198,14 @@ SessionI::destroy(const Ice::Current&) int SessionI::getAllocationTimeout() const { - Lock sync(*this); + lock_guard lock(_mutex); return _allocationTimeout; } bool -SessionI::addAllocationRequest(const AllocationRequestPtr& request) +SessionI::addAllocationRequest(const shared_ptr<AllocationRequest>& request) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return false; @@ -220,9 +215,9 @@ SessionI::addAllocationRequest(const AllocationRequestPtr& request) } void -SessionI::removeAllocationRequest(const AllocationRequestPtr& request) +SessionI::removeAllocationRequest(const shared_ptr<AllocationRequest>& request) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; @@ -231,9 +226,9 @@ SessionI::removeAllocationRequest(const AllocationRequestPtr& request) } void -SessionI::addAllocation(const AllocatablePtr& allocatable) +SessionI::addAllocation(const shared_ptr<Allocatable>& allocatable) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { throw SessionDestroyedException(); @@ -242,9 +237,9 @@ SessionI::addAllocation(const AllocatablePtr& allocatable) } void -SessionI::removeAllocation(const AllocatablePtr& allocatable) +SessionI::removeAllocation(const shared_ptr<Allocatable>& allocatable) { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroyed) { return; @@ -257,25 +252,24 @@ SessionI::destroyImpl(bool shutdown) { BaseSessionI::destroyImpl(shutdown); - _servantManager->removeSession(this); + _servantManager->removeSession(shared_from_this()); // // NOTE: The _requests and _allocations attributes are immutable // once the session is destroyed so we don't need mutex protection // here to access them. // - - for(set<AllocationRequestPtr>::const_iterator p = _requests.begin(); p != _requests.end(); ++p) + for(const auto& request : _requests) { - (*p)->cancel(AllocationException("session destroyed")); + request->cancel(make_exception_ptr(AllocationException("session destroyed"))); } _requests.clear(); - for(set<AllocatablePtr>::const_iterator q = _allocations.begin(); q != _allocations.end(); ++q) + for(const auto& allocation : _allocations) { try { - (*q)->release(this); + allocation->release(dynamic_pointer_cast<SessionI>(shared_from_this())); } catch(const AllocationException&) { @@ -284,10 +278,10 @@ SessionI::destroyImpl(bool shutdown) _allocations.clear(); } -ClientSessionFactory::ClientSessionFactory(const SessionServantManagerPtr& servantManager, - const DatabasePtr& database, +ClientSessionFactory::ClientSessionFactory(const shared_ptr<SessionServantManager>& servantManager, + const shared_ptr<Database>& database, const IceUtil::TimerPtr& timer, - const ReapThreadPtr& reaper) : + const shared_ptr<ReapThread>& reaper) : _servantManager(servantManager), _database(database), _timer(timer), @@ -296,35 +290,31 @@ ClientSessionFactory::ClientSessionFactory(const SessionServantManagerPtr& serva { if(_servantManager) // Not set if Glacier2 session manager adapter not enabled { - Ice::PropertiesPtr properties = _database->getCommunicator()->getProperties(); + auto properties = _database->getCommunicator()->getProperties(); const_cast<bool&>(_filters) = properties->getPropertyAsIntWithDefault("IceGrid.Registry.SessionFilters", 0) > 0; } } -Glacier2::SessionPrx -ClientSessionFactory::createGlacier2Session(const string& sessionId, const Glacier2::SessionControlPrx& ctl) +shared_ptr<Glacier2::SessionPrx> +ClientSessionFactory::createGlacier2Session(const string& sessionId, + const shared_ptr<Glacier2::SessionControlPrx>& ctl) { assert(_servantManager); - SessionIPtr session = createSessionServant(sessionId, ctl); - Ice::ObjectPrx proxy = session->_register(_servantManager, 0); + auto session = createSessionServant(sessionId, ctl); + auto proxy = session->_register(_servantManager, 0); - int timeout = 0; + chrono::seconds timeout = 0s; if(ctl) { try { if(_filters) { - Ice::IdentitySeq ids; - Ice::Identity queryId; - queryId.category = _database->getInstanceName(); - queryId.name = "Query"; - ids.push_back(queryId); - - _servantManager->setSessionControl(session, ctl, ids); + Ice::Identity queryId = { "Query", _database->getInstanceName() }; + _servantManager->setSessionControl(session, ctl, { move(queryId) }); } - timeout = ctl->getSessionTimeout(); + timeout = chrono::seconds(ctl->getSessionTimeout()); } catch(const Ice::LocalException& e) { @@ -337,39 +327,39 @@ ClientSessionFactory::createGlacier2Session(const string& sessionId, const Glaci } } - _reaper->add(new SessionReapable<SessionI>(_database->getTraceLevels()->logger, session), timeout); - return Glacier2::SessionPrx::uncheckedCast(proxy); + _reaper->add(make_shared<SessionReapable<SessionI>>(_database->getTraceLevels()->logger, session), timeout); + return Ice::uncheckedCast<Glacier2::SessionPrx>(proxy); } -SessionIPtr -ClientSessionFactory::createSessionServant(const string& userId, const Glacier2::SessionControlPrx&) +shared_ptr<SessionI> +ClientSessionFactory::createSessionServant(const string& userId, const shared_ptr<Glacier2::SessionControlPrx>&) { - return new SessionI(userId, _database, _timer); + return make_shared<SessionI>(userId, _database, _timer); } -const TraceLevelsPtr& +const shared_ptr<TraceLevels>& ClientSessionFactory::getTraceLevels() const { return _database->getTraceLevels(); } -ClientSessionManagerI::ClientSessionManagerI(const ClientSessionFactoryPtr& factory) : _factory(factory) +ClientSessionManagerI::ClientSessionManagerI(const shared_ptr<ClientSessionFactory>& factory) : _factory(factory) { } -Glacier2::SessionPrx -ClientSessionManagerI::create(const string& user, const Glacier2::SessionControlPrx& ctl, const Ice::Current&) +shared_ptr<Glacier2::SessionPrx> +ClientSessionManagerI::create(string user, shared_ptr<Glacier2::SessionControlPrx> ctl, const Ice::Current&) { - return _factory->createGlacier2Session(user, ctl); + return _factory->createGlacier2Session(move(user), move(ctl)); } -ClientSSLSessionManagerI::ClientSSLSessionManagerI(const ClientSessionFactoryPtr& factory) : _factory(factory) +ClientSSLSessionManagerI::ClientSSLSessionManagerI(const shared_ptr<ClientSessionFactory>& factory) : _factory(factory) { } -Glacier2::SessionPrx -ClientSSLSessionManagerI::create(const Glacier2::SSLInfo& info, - const Glacier2::SessionControlPrx& ctl, +shared_ptr<Glacier2::SessionPrx> +ClientSSLSessionManagerI::create(Glacier2::SSLInfo info, + shared_ptr<Glacier2::SessionControlPrx> ctl, const Ice::Current&) { string userDN; @@ -377,7 +367,7 @@ ClientSSLSessionManagerI::create(const Glacier2::SSLInfo& info, { try { - IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); + auto cert = IceSSL::Certificate::decode(info.certs[0]); userDN = cert->getSubjectDN(); } catch(const Ice::Exception& e) diff --git a/cpp/src/IceGrid/SessionI.h b/cpp/src/IceGrid/SessionI.h index 5184bd2b19a..d933f80163d 100644 --- a/cpp/src/IceGrid/SessionI.h +++ b/cpp/src/IceGrid/SessionI.h @@ -5,7 +5,6 @@ #ifndef ICEGRID_SESSIONI_H #define ICEGRID_SESSIONI_H -#include <IceUtil/Mutex.h> #include <IceUtil/Timer.h> #include <IceGrid/ReapThread.h> #include <IceGrid/Session.h> @@ -15,139 +14,137 @@ namespace IceGrid { -class Database; -typedef IceUtil::Handle<Database> DatabasePtr; - -class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - -class AllocationRequest; -typedef IceUtil::Handle<AllocationRequest> AllocationRequestPtr; - class Allocatable; -typedef IceUtil::Handle<Allocatable> AllocatablePtr; - +class AllocationRequest; +class Database; class SessionI; -typedef IceUtil::Handle<SessionI> SessionIPtr; +class TraceLevels; -class BaseSessionI : public virtual Ice::Object, public IceUtil::Mutex +class BaseSessionI : public virtual Ice::Object, public std::enable_shared_from_this<BaseSessionI> { public: - virtual ~BaseSessionI(); + virtual ~BaseSessionI() = default; virtual void keepAlive(const Ice::Current&); - IceUtil::Time timestamp() const; + std::chrono::steady_clock::time_point timestamp() const; void shutdown(); - Glacier2::IdentitySetPrx getGlacier2IdentitySet(); - Glacier2::StringSetPrx getGlacier2AdapterIdSet(); + std::shared_ptr<Glacier2::IdentitySetPrx> getGlacier2IdentitySet(); + std::shared_ptr<Glacier2::StringSetPrx> getGlacier2AdapterIdSet(); const std::string& getId() const { return _id; } virtual void destroyImpl(bool); protected: - BaseSessionI(const std::string&, const std::string&, const DatabasePtr&); + BaseSessionI(const std::string&, const std::string&, const std::shared_ptr<Database>&); const std::string _id; const std::string _prefix; - const TraceLevelsPtr _traceLevels; - const DatabasePtr _database; - SessionServantManagerPtr _servantManager; + const std::shared_ptr<TraceLevels> _traceLevels; + const std::shared_ptr<Database> _database; + std::shared_ptr<SessionServantManager> _servantManager; bool _destroyed; - IceUtil::Time _timestamp; + std::chrono::steady_clock::time_point _timestamp; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<BaseSessionI> BaseSessionIPtr; -class SessionDestroyedException +struct SessionDestroyedException { }; -class SessionI : public BaseSessionI, public Session +class SessionI final : public BaseSessionI, public Session { public: - SessionI(const std::string&, const DatabasePtr&, const IceUtil::TimerPtr&); - virtual ~SessionI(); - - Ice::ObjectPrx _register(const SessionServantManagerPtr&, const Ice::ConnectionPtr&); + SessionI(const std::string&, const std::shared_ptr<Database>&, const IceUtil::TimerPtr&); - virtual void keepAlive(const Ice::Current& current) { BaseSessionI::keepAlive(current); } + std::shared_ptr<Ice::ObjectPrx> _register(const std::shared_ptr<SessionServantManager>&, + const std::shared_ptr<Ice::Connection>&); - virtual void allocateObjectById_async(const AMD_Session_allocateObjectByIdPtr&, const Ice::Identity&, - const Ice::Current&); - virtual void allocateObjectByType_async(const AMD_Session_allocateObjectByTypePtr&, const std::string&, - const Ice::Current&); - virtual void releaseObject(const Ice::Identity&, const Ice::Current&); - virtual void setAllocationTimeout(int, const Ice::Current&); - virtual void destroy(const Ice::Current&); + void keepAlive(const Ice::Current& current) override { BaseSessionI::keepAlive(current); } + void allocateObjectByIdAsync(Ice::Identity id, + std::function<void(const std::shared_ptr<Ice::ObjectPrx>& returnValue)> response, + std::function<void(std::exception_ptr)> exception, const Ice::Current& current) + override; + void allocateObjectByTypeAsync(std::string, + std::function<void(const std::shared_ptr<Ice::ObjectPrx>& returnValue)> response, + std::function<void(std::exception_ptr)> exception, const Ice::Current& current) + override; + void releaseObject(Ice::Identity, const Ice::Current&) override; + void setAllocationTimeout(int, const Ice::Current&) override; + void destroy(const Ice::Current&) override; int getAllocationTimeout() const; const IceUtil::TimerPtr& getTimer() const { return _timer; } - bool addAllocationRequest(const AllocationRequestPtr&); - void removeAllocationRequest(const AllocationRequestPtr&); - void addAllocation(const AllocatablePtr&); - void removeAllocation(const AllocatablePtr&); + bool addAllocationRequest(const std::shared_ptr<AllocationRequest>&); + void removeAllocationRequest(const std::shared_ptr<AllocationRequest>&); + void addAllocation(const std::shared_ptr<Allocatable>&); + void removeAllocation(const std::shared_ptr<Allocatable>&); protected: - virtual void destroyImpl(bool); + void destroyImpl(bool) override; const IceUtil::TimerPtr _timer; int _allocationTimeout; - std::set<AllocationRequestPtr> _requests; - std::set<AllocatablePtr> _allocations; + std::set<std::shared_ptr<AllocationRequest>> _requests; + std::set<std::shared_ptr<Allocatable>> _allocations; }; -class ClientSessionFactory : public virtual IceUtil::Shared +class ClientSessionFactory final { public: - ClientSessionFactory(const SessionServantManagerPtr&, const DatabasePtr&, const IceUtil::TimerPtr&, - const ReapThreadPtr&); + ClientSessionFactory(const std::shared_ptr<SessionServantManager>&, const std::shared_ptr<Database>&, + const IceUtil::TimerPtr&, + const std::shared_ptr<ReapThread>&); - Glacier2::SessionPrx createGlacier2Session(const std::string&, const Glacier2::SessionControlPrx&); - SessionIPtr createSessionServant(const std::string&, const Glacier2::SessionControlPrx&); + std::shared_ptr<Glacier2::SessionPrx> createGlacier2Session(const std::string&, + const std::shared_ptr<Glacier2::SessionControlPrx>&); + std::shared_ptr<SessionI> createSessionServant(const std::string&, + const std::shared_ptr<Glacier2::SessionControlPrx>&); - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr<TraceLevels>& getTraceLevels() const; private: - const SessionServantManagerPtr _servantManager; - const DatabasePtr _database; + const std::shared_ptr<SessionServantManager> _servantManager; + const std::shared_ptr<Database> _database; const IceUtil::TimerPtr _timer; - const ReapThreadPtr _reaper; + const std::shared_ptr<ReapThread> _reaper; const bool _filters; }; -typedef IceUtil::Handle<ClientSessionFactory> ClientSessionFactoryPtr; -class ClientSessionManagerI : public virtual Glacier2::SessionManager +class ClientSessionManagerI final : public Glacier2::SessionManager { public: - ClientSessionManagerI(const ClientSessionFactoryPtr&); + ClientSessionManagerI(const std::shared_ptr<ClientSessionFactory>&); - virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); + std::shared_ptr<Glacier2::SessionPrx> create(std::string, std::shared_ptr<Glacier2::SessionControlPrx>, + const Ice::Current&) override; private: - const ClientSessionFactoryPtr _factory; + const std::shared_ptr<ClientSessionFactory> _factory; }; -class ClientSSLSessionManagerI : public virtual Glacier2::SSLSessionManager +class ClientSSLSessionManagerI final : public Glacier2::SSLSessionManager { public: - ClientSSLSessionManagerI(const ClientSessionFactoryPtr&); + ClientSSLSessionManagerI(const std::shared_ptr<ClientSessionFactory>&); - virtual Glacier2::SessionPrx create(const Glacier2::SSLInfo&, const Glacier2::SessionControlPrx&, - const Ice::Current&); + std::shared_ptr<Glacier2::SessionPrx> create(Glacier2::SSLInfo, std::shared_ptr<Glacier2::SessionControlPrx>, + const Ice::Current&) override; private: - const ClientSessionFactoryPtr _factory; + const std::shared_ptr<ClientSessionFactory> _factory; }; }; diff --git a/cpp/src/IceGrid/SessionManager.cpp b/cpp/src/IceGrid/SessionManager.cpp index 646db8244a4..c9fe10674da 100644 --- a/cpp/src/IceGrid/SessionManager.cpp +++ b/cpp/src/IceGrid/SessionManager.cpp @@ -10,30 +10,25 @@ using namespace std; using namespace IceGrid; -SessionManager::SessionManager(const Ice::CommunicatorPtr& communicator, const string& instanceName) : +SessionManager::SessionManager(const shared_ptr<Ice::Communicator>& communicator, const string& instanceName) : _communicator(communicator), _instanceName(instanceName) { - Ice::LocatorPrx prx = communicator->getDefaultLocator(); + auto prx = communicator->getDefaultLocator(); if(prx) { - Ice::Identity id; - id.category = instanceName; - id.name = "InternalRegistry-Master"; - _master = InternalRegistryPrx::uncheckedCast(prx->ice_identity(id)->ice_endpoints(Ice::EndpointSeq())); + Ice::Identity id = { "InternalRegistry-Master", instanceName }; + _master = + Ice::uncheckedCast<InternalRegistryPrx>(prx->ice_identity(move(id))->ice_endpoints({})); } } -SessionManager::~SessionManager() -{ -} - -vector<QueryPrx> +vector<shared_ptr<QueryPrx>> SessionManager::findAllQueryObjects(bool cached) { - vector<QueryPrx> queryObjects; - Ice::LocatorPrx locator; + vector<shared_ptr<QueryPrx>> queryObjects; + shared_ptr<Ice::LocatorPrx> locator; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_communicator) { return queryObjects; @@ -48,14 +43,14 @@ SessionManager::findAllQueryObjects(bool cached) if(!cached) { - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + for(const auto& queryObject : queryObjects) { - Ice::ConnectionPtr connection = (*q)->ice_getCachedConnection(); + auto connection = queryObject->ice_getCachedConnection(); if(connection) { try { - connection->close(Ice::ICE_SCOPED_ENUM(ConnectionClose, GracefullyWithWait)); + connection->close(Ice::ConnectionClose::GracefullyWithWait); } catch(const Ice::LocalException&) { @@ -67,16 +62,14 @@ SessionManager::findAllQueryObjects(bool cached) if(queryObjects.empty() && locator) { - Ice::Identity id; - id.category = _instanceName; - id.name = "Query"; - QueryPrx query = QueryPrx::uncheckedCast(locator->ice_identity(id)); - Ice::EndpointSeq endpoints = query->ice_getEndpoints(); + Ice::Identity id = { "Query", _instanceName }; + auto query = Ice::uncheckedCast<QueryPrx>(locator->ice_identity(id)); + auto endpoints = query->ice_getEndpoints(); if(endpoints.empty()) { try { - Ice::ObjectPrx r = locator->findObjectById(id); + auto r = locator->findObjectById(id); if(r) { endpoints = r->ice_getEndpoints(); @@ -88,35 +81,32 @@ SessionManager::findAllQueryObjects(bool cached) } } - for(Ice::EndpointSeq::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) + for(const auto& endpoint : endpoints) { - Ice::EndpointSeq singleEndpoint; - singleEndpoint.push_back(*p); - queryObjects.push_back(QueryPrx::uncheckedCast(query->ice_endpoints(singleEndpoint))); + queryObjects.push_back(Ice::uncheckedCast<QueryPrx>(query->ice_endpoints({endpoint}))); } } // // Find all known query objects by querying all the registries we can find. // - map<Ice::Identity, QueryPrx> proxies; - set<QueryPrx> requested; + map<Ice::Identity, shared_ptr<QueryPrx>> proxies; + set<shared_ptr<QueryPrx>> requested; while(true) { - vector<Ice::AsyncResultPtr> results; - for(vector<QueryPrx>::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector<future<Ice::ObjectProxySeq>> results; + for(const auto& queryObject : queryObjects) { - results.push_back((*q)->begin_findAllObjectsByType(Registry::ice_staticId())); - requested.insert(*q); + results.push_back(queryObject->findAllObjectsByTypeAsync(Registry::ice_staticId())); + requested.insert(queryObject); } if(results.empty()) { break; } - for(vector<Ice::AsyncResultPtr>::const_iterator p = results.begin(); p != results.end(); ++p) + for(auto& result : results) { - QueryPrx query = QueryPrx::uncheckedCast((*p)->getProxy()); if(isDestroyed()) { break; @@ -124,18 +114,17 @@ SessionManager::findAllQueryObjects(bool cached) try { - Ice::ObjectProxySeq prxs = query->end_findAllObjectsByType(*p); - for(Ice::ObjectProxySeq::iterator q = prxs.begin(); q != prxs.end(); ++q) + auto prxs = result.get(); + for(const auto& prx : prxs) { - if(proxies.find((*q)->ice_getIdentity()) == proxies.end()) + if(proxies.find(prx->ice_getIdentity()) == proxies.end()) { // // Add query proxy for each IceGrid registry. The proxy contains the endpoints // of the registry since it's based on the registry interface proxy. // - Ice::Identity id = (*q)->ice_getIdentity(); - id.name = "Query"; - proxies[(*q)->ice_getIdentity()] = QueryPrx::uncheckedCast((*q)->ice_identity(id)); + Ice::Identity id = { "Query", prx->ice_getIdentity().category }; + proxies[prx->ice_getIdentity()] = Ice::uncheckedCast<QueryPrx>(prx->ice_identity(move(id))); } } } @@ -146,20 +135,20 @@ SessionManager::findAllQueryObjects(bool cached) } queryObjects.clear(); - for(map<Ice::Identity, QueryPrx>::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + for(const auto& prx : proxies) { - if(requested.find(p->second) == requested.end()) + if(requested.find(prx.second) == requested.end()) { - queryObjects.push_back(p->second); + queryObjects.push_back(prx.second); } } } - Lock sync(*this); + lock_guard lock(_mutex); _queryObjects.clear(); - for(map<Ice::Identity, QueryPrx>::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + for(const auto& prx : proxies) { - _queryObjects.push_back(p->second); + _queryObjects.push_back(prx.second); } return _queryObjects; } diff --git a/cpp/src/IceGrid/SessionManager.h b/cpp/src/IceGrid/SessionManager.h index 44261f603a0..243fe8b7957 100644 --- a/cpp/src/IceGrid/SessionManager.h +++ b/cpp/src/IceGrid/SessionManager.h @@ -5,22 +5,18 @@ #ifndef ICE_GRID_SESSION_MANAGER_H #define ICE_GRID_SESSION_MANAGER_H -#include <IceUtil/Handle.h> -#include <IceUtil/Mutex.h> -#include <IceUtil/Monitor.h> -#include <IceUtil/Thread.h> - #include <Ice/Logger.h> #include <Ice/LoggerUtil.h> #include <IceGrid/Registry.h> #include <IceGrid/Internal.h> +#include <IceGrid/Util.h> namespace IceGrid { template<class TPrx> -class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor<IceUtil::Mutex> +class SessionKeepAliveThread { #if defined(__clang__) # pragma clang diagnostic push @@ -47,21 +43,28 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor<I public: - SessionKeepAliveThread(const InternalRegistryPrx& registry, const Ice::LoggerPtr& logger) : - IceUtil::Thread("IceGrid session keepalive thread"), + SessionKeepAliveThread(const std::shared_ptr<InternalRegistryPrx>& registry, + const std::shared_ptr<Ice::Logger>& logger) : _registry(registry), _logger(logger), _state(InProgress), - _nextAction(None) + _nextAction(None), + _thread([this] { run(); }) + { + } + + virtual ~SessionKeepAliveThread() { + assert(_state == Destroyed); } - virtual void + void run() { - TPrx session; - InternalRegistryPrx registry; - IceUtil::Time timeout = IceUtil::Time::seconds(10); + using namespace std::chrono_literals; + std::shared_ptr<TPrx> session; + std::shared_ptr<InternalRegistryPrx> registry; + std::chrono::seconds timeout = 10s; Action action = Connect; try @@ -69,7 +72,7 @@ public: while(true) { { - Lock sync(*this); + std::unique_lock<std::mutex> lock(_mutex); if(_state == Destroyed) { break; @@ -98,7 +101,7 @@ public: { _nextAction = Connect; } - notifyAll(); + _condVar.notify_all(); // // Wait if there's nothing to do and if we are @@ -108,12 +111,12 @@ public: { if(_state == Connected || action == Connect || action == KeepAlive) { - IceUtil::Time now = IceUtil::Time::now(IceUtil::Time::Monotonic); - IceUtil::Time wakeTime = now + timeout; + auto now = std::chrono::steady_clock::now(); + auto wakeTime = now + timeout; while(_state != Destroyed && _nextAction == None && wakeTime > now) { - timedWait(wakeTime - now); - now = IceUtil::Time::now(IceUtil::Time::Monotonic); + _condVar.wait_for(lock, wakeTime - now); + now = std::chrono::steady_clock::now(); } } if(_nextAction == None) @@ -130,23 +133,27 @@ public: assert(_nextAction != None); action = _nextAction; - registry = InternalRegistryPrx::uncheckedCast( - _registry->ice_timeout(static_cast<int>(timeout.toMilliSeconds()))); + assert(timeout != 0s); + using namespace std::chrono; + + registry = Ice::uncheckedCast<InternalRegistryPrx>(_registry->ice_timeout(secondsToInt(timeout))); _nextAction = None; _state = InProgress; - notifyAll(); + _condVar.notify_all(); } switch(action) { case Connect: assert(!session); - session = createSession(registry, timeout); + { + session = createSession(registry, timeout); + } break; case Disconnect: assert(session); destroySession(session); - session = 0; + session = nullptr; break; case KeepAlive: assert(session); @@ -186,57 +193,53 @@ public: bool isWaitingForCreate() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); return _state != Destroyed && _state != Connected; } virtual bool waitForCreate() { - Lock sync(*this); - while(_state != Destroyed && _state != Connected) - { - wait(); - } + std::unique_lock<std::mutex> lock(_mutex); + _condVar.wait(lock, [this] { return _state == Destroyed || _state == Connected; }); return _state != Destroyed; } void tryCreateSession() { + std::lock_guard<std::mutex> lock(_mutex); + if(_state == Destroyed) { - Lock sync(*this); - if(_state == Destroyed) - { - return; - } + return; + } - if(_state == Connected) - { - _nextAction = KeepAlive; - } - else - { - _nextAction = Connect; - } - notifyAll(); + if(_state == Connected) + { + _nextAction = KeepAlive; } + else + { + _nextAction = Connect; + } + _condVar.notify_all(); } void - waitTryCreateSession(const IceUtil::Time& timeout = IceUtil::Time()) + waitTryCreateSession(std::chrono::seconds timeout = std::chrono::seconds(0)) { - Lock sync(*this); + std::unique_lock<std::mutex> lock(_mutex); // Wait until the action is executed and the state changes. while(_nextAction == Connect || _nextAction == KeepAlive || _state == InProgress) { - if(timeout == IceUtil::Time()) + using namespace std::chrono_literals; + if(timeout == 0s) { - wait(); + _condVar.wait(lock); } else { - if(!timedWait(timeout)) + if(_condVar.wait_for(lock, timeout) == std::cv_status::timeout) { break; } @@ -247,19 +250,19 @@ public: void destroyActiveSession() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); if(_state == Destroyed || _state == Disconnected) { return; } _nextAction = Disconnect; - notifyAll(); + _condVar.notify_all(); } bool terminateIfDisconnected() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); if(_state != Disconnected) { return false; // Nothing we can do for now. @@ -267,14 +270,14 @@ public: assert(_state != Destroyed); _state = Destroyed; _nextAction = None; - notifyAll(); + _condVar.notify_all(); return true; } void terminate(bool destroySession = true) { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); if(_state == Destroyed) { return; @@ -282,67 +285,80 @@ public: assert(_state != Destroyed); _state = Destroyed; _nextAction = destroySession ? Disconnect : None; - notifyAll(); + _condVar.notify_all(); + } + + void + join() + { + _thread.join(); } bool isDestroyed() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); return _state == Destroyed; } - TPrx + std::shared_ptr<TPrx> getSession() { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); return _session; } void - setRegistry(const InternalRegistryPrx& registry) + setRegistry(const std::shared_ptr<InternalRegistryPrx>& registry) { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); _registry = registry; } - InternalRegistryPrx + std::shared_ptr<InternalRegistryPrx> getRegistry() const { - Lock sync(*this); + std::lock_guard<std::mutex> lock(_mutex); return _registry; } - virtual TPrx createSession(InternalRegistryPrx&, IceUtil::Time&) = 0; - virtual void destroySession(const TPrx&) = 0; - virtual bool keepAlive(const TPrx&) = 0; + virtual std::shared_ptr<TPrx> createSession(std::shared_ptr<InternalRegistryPrx>&, std::chrono::seconds&) = 0; + virtual void destroySession(const std::shared_ptr<TPrx>&) = 0; + virtual bool keepAlive(const std::shared_ptr<TPrx>&) = 0; protected: - InternalRegistryPrx _registry; - Ice::LoggerPtr _logger; - TPrx _session; + std::shared_ptr<InternalRegistryPrx> _registry; + std::shared_ptr<Ice::Logger> _logger; + std::shared_ptr<TPrx> _session; State _state; Action _nextAction; + + mutable std::mutex _mutex; + std::condition_variable _condVar; + std::thread _thread; }; -class SessionManager : public IceUtil::Monitor<IceUtil::Mutex> +class SessionManager { public: - SessionManager(const Ice::CommunicatorPtr&, const std::string&); - virtual ~SessionManager(); + SessionManager(const std::shared_ptr<Ice::Communicator>&, const std::string&); + virtual ~SessionManager() = default; virtual bool isDestroyed() = 0; protected: - std::vector<IceGrid::QueryPrx> findAllQueryObjects(bool); + std::vector<std::shared_ptr<IceGrid::QueryPrx>> findAllQueryObjects(bool); - Ice::CommunicatorPtr _communicator; + std::shared_ptr<Ice::Communicator> _communicator; std::string _instanceName; - InternalRegistryPrx _master; - std::vector<IceGrid::QueryPrx> _queryObjects; + std::shared_ptr<InternalRegistryPrx> _master; + std::vector<std::shared_ptr<IceGrid::QueryPrx>> _queryObjects; + + std::mutex _mutex; + std::condition_variable _condVar; }; }; diff --git a/cpp/src/IceGrid/SessionServantManager.cpp b/cpp/src/IceGrid/SessionServantManager.cpp index 58f9c0fbfab..47be2baeabc 100644 --- a/cpp/src/IceGrid/SessionServantManager.cpp +++ b/cpp/src/IceGrid/SessionServantManager.cpp @@ -11,16 +11,16 @@ using namespace std; using namespace IceGrid; -SessionServantManager::SessionServantManager(const Ice::ObjectAdapterPtr& adapter, +SessionServantManager::SessionServantManager(const shared_ptr<Ice::ObjectAdapter>& adapter, const string& instanceName, bool checkConnection, const string& serverAdminCategory, - const Ice::ObjectPtr& serverAdminRouter, + const shared_ptr<Ice::Object>& serverAdminRouter, const string& nodeAdminCategory, - const Ice::ObjectPtr& nodeAdminRouter, + const shared_ptr<Ice::Object>& nodeAdminRouter, const string& replicaAdminCategory, - const Ice::ObjectPtr& replicaAdminRouter, - const AdminCallbackRouterPtr& adminCallbackRouter) : + const shared_ptr<Ice::Object>& replicaAdminRouter, + const shared_ptr<AdminCallbackRouter>& adminCallbackRouter) : _adapter(adapter), _instanceName(instanceName), _checkConnection(checkConnection), @@ -34,11 +34,12 @@ SessionServantManager::SessionServantManager(const Ice::ObjectAdapterPtr& adapte { } -Ice::ObjectPtr -SessionServantManager::locate(const Ice::Current& current, Ice::LocalObjectPtr&) +shared_ptr<Ice::Object> +SessionServantManager::locate(const Ice::Current& current, shared_ptr<void>&) { - Lock sync(*this); - Ice::ObjectPtr servant; + lock_guard lock(_mutex); + + shared_ptr<Ice::Object> servant; bool plainServant = false; if(_serverAdminRouter && current.id.category == _serverAdminCategory) @@ -57,7 +58,7 @@ SessionServantManager::locate(const Ice::Current& current, Ice::LocalObjectPtr&) { plainServant = true; - map<Ice::Identity, ServantInfo>::const_iterator p = _servants.find(current.id); + auto p = _servants.find(current.id); if(p == _servants.end() || (_checkConnection && p->second.connection != current.con)) { servant = 0; @@ -78,24 +79,25 @@ SessionServantManager::locate(const Ice::Current& current, Ice::LocalObjectPtr&) } void -SessionServantManager::finished(const Ice::Current&, const Ice::ObjectPtr&, const Ice::LocalObjectPtr&) +SessionServantManager::finished(const Ice::Current&, const shared_ptr<Ice::Object>&, const shared_ptr<void>&) { } void SessionServantManager::deactivate(const std::string&) { - Lock sync(*this); + lock_guard lock(_mutex); assert(_servants.empty()); assert(_sessions.empty()); assert(_adminConnections.empty()); } -Ice::ObjectPrx -SessionServantManager::addSession(const Ice::ObjectPtr& session, const Ice::ConnectionPtr& con, const string& category) +shared_ptr<Ice::ObjectPrx> +SessionServantManager::addSession(const shared_ptr<Ice::Object>& session, + const shared_ptr<Ice::Connection>& con, const string& category) { - Lock sync(*this); - _sessions.insert(make_pair(session, SessionInfo(con, category))); + lock_guard lock(_mutex); + _sessions.insert({ session, SessionInfo(con, category) }); // // Keep track of all the connections which have an admin session to allow access @@ -114,13 +116,13 @@ SessionServantManager::addSession(const Ice::ObjectPtr& session, const Ice::Conn } void -SessionServantManager::setSessionControl(const Ice::ObjectPtr& session, - const Glacier2::SessionControlPrx& ctl, +SessionServantManager::setSessionControl(const shared_ptr<Ice::Object>& session, + const shared_ptr<Glacier2::SessionControlPrx>& ctl, const Ice::IdentitySeq& ids) { - Lock sync(*this); + lock_guard lock(_mutex); - map<Ice::ObjectPtr, SessionInfo>::iterator p = _sessions.find(session); + auto p = _sessions.find(session); assert(p != _sessions.end()); p->second.sessionControl = ctl; @@ -144,11 +146,11 @@ SessionServantManager::setSessionControl(const Ice::ObjectPtr& session, } } -Glacier2::IdentitySetPrx -SessionServantManager::getGlacier2IdentitySet(const Ice::ObjectPtr& session) +shared_ptr<Glacier2::IdentitySetPrx> +SessionServantManager::getGlacier2IdentitySet(const shared_ptr<Ice::Object>& session) { - Lock sync(*this); - map<Ice::ObjectPtr, SessionInfo>::iterator p = _sessions.find(session); + lock_guard lock(_mutex); + auto p = _sessions.find(session); if(p != _sessions.end() && p->second.sessionControl) { if(!p->second.identitySet) // Cache the identity set proxy @@ -159,15 +161,15 @@ SessionServantManager::getGlacier2IdentitySet(const Ice::ObjectPtr& session) } else { - return 0; + return nullptr; } } -Glacier2::StringSetPrx -SessionServantManager::getGlacier2AdapterIdSet(const Ice::ObjectPtr& session) +shared_ptr<Glacier2::StringSetPrx> +SessionServantManager::getGlacier2AdapterIdSet(const shared_ptr<Ice::Object>& session) { - Lock sync(*this); - map<Ice::ObjectPtr, SessionInfo>::iterator p = _sessions.find(session); + lock_guard lock(_mutex); + auto p = _sessions.find(session); if(p != _sessions.end() && p->second.sessionControl) { if(!p->second.adapterIdSet) // Cache the adapterId set proxy @@ -178,22 +180,22 @@ SessionServantManager::getGlacier2AdapterIdSet(const Ice::ObjectPtr& session) } else { - return 0; + return nullptr; } } void -SessionServantManager::removeSession(const Ice::ObjectPtr& session) +SessionServantManager::removeSession(const shared_ptr<Ice::Object>& session) { - Lock sync(*this); + lock_guard lock(_mutex); - map<Ice::ObjectPtr, SessionInfo>::iterator p = _sessions.find(session); + auto p = _sessions.find(session); assert(p != _sessions.end()); // // Remove all the servants associated with the session. // - for(set<Ice::Identity>::const_iterator q = p->second.identities.begin(); q != p->second.identities.end(); ++q) + for(auto q = p->second.identities.cbegin(); q != p->second.identities.cend(); ++q) { _servants.erase(*q); } @@ -207,7 +209,7 @@ SessionServantManager::removeSession(const Ice::ObjectPtr& session) assert(_adminConnections.find(p->second.connection) != _adminConnections.end()); _adminConnections.erase(_adminConnections.find(p->second.connection)); - if(_adminCallbackRouter != 0) + if(_adminCallbackRouter != nullptr) { _adminCallbackRouter->removeMapping(p->second.category); } @@ -216,17 +218,17 @@ SessionServantManager::removeSession(const Ice::ObjectPtr& session) _sessions.erase(p); } -Ice::ObjectPrx -SessionServantManager::add(const Ice::ObjectPtr& servant, const Ice::ObjectPtr& session) +shared_ptr<Ice::ObjectPrx> +SessionServantManager::add(const shared_ptr<Ice::Object>& servant, const shared_ptr<Ice::Object>& session) { - Lock sync(*this); + lock_guard lock(_mutex); return addImpl(servant, session); } void SessionServantManager::remove(const Ice::Identity& id) { - Lock sync(*this); + lock_guard lock(_mutex); map<Ice::Identity, ServantInfo>::iterator p = _servants.find(id); assert(p != _servants.end()); @@ -234,7 +236,7 @@ SessionServantManager::remove(const Ice::Identity& id) // Find the session associated to the servant and remove the servant identity from the // session identities. // - map<Ice::ObjectPtr, SessionInfo>::iterator q = _sessions.find(p->second.session); + map<shared_ptr<Ice::Object>, SessionInfo>::iterator q = _sessions.find(p->second.session); assert(q != _sessions.end()); q->second.identities.erase(id); @@ -245,9 +247,7 @@ SessionServantManager::remove(const Ice::Identity& id) { try { - Ice::IdentitySeq ids; - ids.push_back(id); - q->second.identitySet->remove(ids); + q->second.identitySet->remove({id}); } catch(const Ice::LocalException&) { @@ -260,10 +260,10 @@ SessionServantManager::remove(const Ice::Identity& id) _servants.erase(p); } -Ice::ObjectPrx -SessionServantManager::addImpl(const Ice::ObjectPtr& servant, const Ice::ObjectPtr& session) +shared_ptr<Ice::ObjectPrx> +SessionServantManager::addImpl(const shared_ptr<Ice::Object>& servant, const shared_ptr<Ice::Object>& session) { - map<Ice::ObjectPtr, SessionInfo>::iterator p = _sessions.find(session); + auto p = _sessions.find(session); assert(p != _sessions.end()); Ice::Identity id; @@ -282,9 +282,7 @@ SessionServantManager::addImpl(const Ice::ObjectPtr& servant, const Ice::ObjectP { try { - Ice::IdentitySeq ids; - ids.push_back(id); - p->second.identitySet->add(ids); + p->second.identitySet->add({id}); } catch(const Ice::LocalException&) { diff --git a/cpp/src/IceGrid/SessionServantManager.h b/cpp/src/IceGrid/SessionServantManager.h index 766171e9ba5..817f4c11714 100644 --- a/cpp/src/IceGrid/SessionServantManager.h +++ b/cpp/src/IceGrid/SessionServantManager.h @@ -6,7 +6,6 @@ #define ICE_GRID_SESSIONSERVANTLOCATOR_H #include <IceGrid/AdminCallbackRouter.h> -#include <IceUtil/Mutex.h> #include <Ice/ServantLocator.h> #include <Glacier2/Session.h> @@ -16,77 +15,85 @@ namespace IceGrid { -class SessionServantManager : public Ice::ServantLocator, public IceUtil::Mutex +class SessionServantManager final : public Ice::ServantLocator { public: - SessionServantManager(const Ice::ObjectAdapterPtr&, const std::string&, bool, - const std::string&, const Ice::ObjectPtr&, - const std::string&, const Ice::ObjectPtr&, - const std::string&, const Ice::ObjectPtr&, - const AdminCallbackRouterPtr&); + SessionServantManager(const std::shared_ptr<Ice::ObjectAdapter>&, const std::string&, bool, + const std::string&, const std::shared_ptr<Ice::Object>&, + const std::string&, const std::shared_ptr<Ice::Object>&, + const std::string&, const std::shared_ptr<Ice::Object>&, + const std::shared_ptr<AdminCallbackRouter>&); - Ice::ObjectPtr locate(const Ice::Current&, Ice::LocalObjectPtr&); - void finished(const Ice::Current&, const Ice::ObjectPtr&, const Ice::LocalObjectPtr&); + std::shared_ptr<Ice::Object> locate(const Ice::Current&, std::shared_ptr<void>&); + void finished(const Ice::Current&, const std::shared_ptr<Ice::Object>&, const std::shared_ptr<void>&); void deactivate(const std::string&); - Ice::ObjectPrx addSession(const Ice::ObjectPtr&, const Ice::ConnectionPtr&, const std::string&); - void setSessionControl(const Ice::ObjectPtr&, const Glacier2::SessionControlPrx&, const Ice::IdentitySeq&); - Glacier2::IdentitySetPrx getGlacier2IdentitySet(const Ice::ObjectPtr&); - Glacier2::StringSetPrx getGlacier2AdapterIdSet(const Ice::ObjectPtr&); - void removeSession(const Ice::ObjectPtr&); + std::shared_ptr<Ice::ObjectPrx> addSession(const std::shared_ptr<Ice::Object>&, + const std::shared_ptr<Ice::Connection>&, + const std::string&); + void setSessionControl(const std::shared_ptr<Ice::Object>&, + const std::shared_ptr<Glacier2::SessionControlPrx>&, const Ice::IdentitySeq&); + std::shared_ptr<Glacier2::IdentitySetPrx> getGlacier2IdentitySet(const std::shared_ptr<Ice::Object>&); + std::shared_ptr<Glacier2::StringSetPrx> getGlacier2AdapterIdSet(const std::shared_ptr<Ice::Object>&); + void removeSession(const std::shared_ptr<Ice::Object>&); - Ice::ObjectPrx add(const Ice::ObjectPtr&, const Ice::ObjectPtr&); + std::shared_ptr<Ice::ObjectPrx> add(const std::shared_ptr<Ice::Object>&, const std::shared_ptr<Ice::Object>&); void remove(const Ice::Identity&); - void connectionHeartbeat(const Ice::ConnectionPtr&); - void connectionClosed(const Ice::ConnectionPtr&); + void connectionHeartbeat(const std::shared_ptr<Ice::Connection>&); + void connectionClosed(const std::shared_ptr<Ice::Connection>&); private: - Ice::ObjectPrx addImpl(const Ice::ObjectPtr&, const Ice::ObjectPtr&); + std::shared_ptr<Ice::ObjectPrx> addImpl(const std::shared_ptr<Ice::Object>&, const std::shared_ptr<Ice::Object>&); struct ServantInfo { - ServantInfo(const Ice::ObjectPtr& s, const Ice::ConnectionPtr& con, const Ice::ObjectPtr& ss) : + ServantInfo(const std::shared_ptr<Ice::Object>& s, + const std::shared_ptr<Ice::Connection>& con, + const std::shared_ptr<Ice::Object>& ss) : servant(s), connection(con), session(ss) { } - const Ice::ObjectPtr servant; - const Ice::ConnectionPtr connection; - const Ice::ObjectPtr session; + const std::shared_ptr<Ice::Object> servant; + const std::shared_ptr<Ice::Connection> connection; + const std::shared_ptr<Ice::Object> session; }; struct SessionInfo { - SessionInfo(const Ice::ConnectionPtr& c, const std::string& cat) : connection(c), category(cat) { } + SessionInfo(const std::shared_ptr<Ice::Connection>& c, const std::string& cat) : connection(c), category(cat) + { + } - const Ice::ConnectionPtr connection; + const std::shared_ptr<Ice::Connection> connection; const std::string category; - Glacier2::SessionControlPrx sessionControl; - Glacier2::IdentitySetPrx identitySet; - Glacier2::StringSetPrx adapterIdSet; + std::shared_ptr<Glacier2::SessionControlPrx> sessionControl; + std::shared_ptr<Glacier2::IdentitySetPrx> identitySet; + std::shared_ptr<Glacier2::StringSetPrx> adapterIdSet; std::set<Ice::Identity> identities; }; - const Ice::ObjectAdapterPtr _adapter; + const std::shared_ptr<Ice::ObjectAdapter> _adapter; const std::string _instanceName; const bool _checkConnection; const std::string _serverAdminCategory; - const Ice::ObjectPtr _serverAdminRouter; + const std::shared_ptr<Ice::Object> _serverAdminRouter; const std::string _nodeAdminCategory; - const Ice::ObjectPtr _nodeAdminRouter; + const std::shared_ptr<Ice::Object> _nodeAdminRouter; const std::string _replicaAdminCategory; - const Ice::ObjectPtr _replicaAdminRouter; - const AdminCallbackRouterPtr _adminCallbackRouter; + const std::shared_ptr<Ice::Object> _replicaAdminRouter; + const std::shared_ptr<AdminCallbackRouter> _adminCallbackRouter; std::map<Ice::Identity, ServantInfo> _servants; - std::map<Ice::ObjectPtr, SessionInfo> _sessions; - std::multiset<Ice::ConnectionPtr> _adminConnections; + std::map<std::shared_ptr<Ice::Object>, SessionInfo> _sessions; + std::multiset<std::shared_ptr<Ice::Connection>> _adminConnections; + + std::mutex _mutex; }; -typedef IceUtil::Handle<SessionServantManager> SessionServantManagerPtr; }; diff --git a/cpp/src/IceGrid/Topics.cpp b/cpp/src/IceGrid/Topics.cpp index 8ab60af908a..119209dd636 100644 --- a/cpp/src/IceGrid/Topics.cpp +++ b/cpp/src/IceGrid/Topics.cpp @@ -24,14 +24,15 @@ Ice::EncodingVersion encodings[] = { } -ObserverTopic::ObserverTopic(const IceStorm::TopicManagerPrx& topicManager, const string& name, Ice::Long dbSerial) : +ObserverTopic::ObserverTopic(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, const string& name, + long long dbSerial) : _logger(topicManager->ice_getCommunicator()->getLogger()), _serial(0), _dbSerial(dbSerial) { for(int i = 0; i < static_cast<int>(sizeof(encodings) / sizeof(Ice::EncodingVersion)); ++i) { ostringstream os; os << name << "-" << Ice::encodingVersionToString(encodings[i]); - IceStorm::TopicPrx t; + shared_ptr<IceStorm::TopicPrx> t; try { t = topicManager->create(os.str()); @@ -51,14 +52,10 @@ ObserverTopic::ObserverTopic(const IceStorm::TopicManagerPrx& topicManager, cons } } -ObserverTopic::~ObserverTopic() -{ -} - int -ObserverTopic::subscribe(const Ice::ObjectPrx& obsv, const string& name) +ObserverTopic::subscribe(const shared_ptr<Ice::ObjectPrx>& obsv, const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -70,7 +67,7 @@ ObserverTopic::subscribe(const Ice::ObjectPrx& obsv, const string& name) IceStorm::QoS qos; qos["reliability"] = "ordered"; Ice::EncodingVersion v = IceInternal::getCompatibleEncoding(obsv->ice_getEncodingVersion()); - map<Ice::EncodingVersion, IceStorm::TopicPrx>::const_iterator p = _topics.find(v); + auto p = _topics.find(v); if(p == _topics.end()) { Ice::Warning out(_logger); @@ -95,11 +92,11 @@ ObserverTopic::subscribe(const Ice::ObjectPrx& obsv, const string& name) } void -ObserverTopic::unsubscribe(const Ice::ObjectPrx& observer, const string& name) +ObserverTopic::unsubscribe(const shared_ptr<Ice::ObjectPrx>& observer, const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); Ice::EncodingVersion v = IceInternal::getCompatibleEncoding(observer->ice_getEncodingVersion()); - map<Ice::EncodingVersion, IceStorm::TopicPrx>::const_iterator q = _topics.find(v); + auto q = _topics.find(v); if(q == _topics.end()) { return; @@ -119,7 +116,7 @@ ObserverTopic::unsubscribe(const Ice::ObjectPrx& observer, const string& name) assert(_syncSubscribers.find(name) != _syncSubscribers.end()); _syncSubscribers.erase(name); - map<int, set<string> >::iterator p = _waitForUpdates.begin(); + auto p = _waitForUpdates.begin(); bool notifyMonitor = false; while(p != _waitForUpdates.end()) { @@ -137,7 +134,7 @@ ObserverTopic::unsubscribe(const Ice::ObjectPrx& observer, const string& name) if(notifyMonitor) { - notifyAll(); + _condVar.notify_all(); } } } @@ -145,15 +142,15 @@ ObserverTopic::unsubscribe(const Ice::ObjectPrx& observer, const string& name) void ObserverTopic::destroy() { - Lock sync(*this); + lock_guard lock(_mutex); _topics.clear(); - notifyAll(); + _condVar.notify_all(); } void ObserverTopic::receivedUpdate(const string& name, int serial, const string& failure) { - Lock sync(*this); + lock_guard lock(_mutex); map<int, set<string> >::iterator p = _waitForUpdates.find(serial); if(p != _waitForUpdates.end()) { @@ -174,47 +171,15 @@ ObserverTopic::receivedUpdate(const string& name, int serial, const string& fail _waitForUpdates.erase(p); } - notifyAll(); + _condVar.notify_all(); } } void ObserverTopic::waitForSyncedSubscribers(int serial, const string& name) { - Lock sync(*this); - waitForSyncedSubscribersNoSync(serial, name); -} - -int -ObserverTopic::getSerial() const -{ - Lock sync(*this); - return _serial; -} - -void -ObserverTopic::addExpectedUpdate(int serial, const string& name) -{ - if(_syncSubscribers.empty() && name.empty()) - { - return; - } + unique_lock lock(_mutex); - // Must be called with the lock held. - if(name.empty()) - { - assert(_waitForUpdates[serial].empty()); - _waitForUpdates[serial] = _syncSubscribers; - } - else - { - _waitForUpdates[serial].insert(name); - } -} - -void -ObserverTopic::waitForSyncedSubscribersNoSync(int serial, const string& name) -{ if(serial < 0) { return; @@ -225,10 +190,10 @@ ObserverTopic::waitForSyncedSubscribersNoSync(int serial, const string& name) // while(!_topics.empty()) { - map<int, set<string> >::const_iterator p = _waitForUpdates.find(serial); + auto p = _waitForUpdates.find(serial); if(p == _waitForUpdates.end()) { - map<int, map<string, string> >::iterator q = _updateFailures.find(serial); + auto q = _updateFailures.find(serial); if(q != _updateFailures.end()) { map<string, string> failures = q->second; @@ -250,13 +215,40 @@ ObserverTopic::waitForSyncedSubscribersNoSync(int serial, const string& name) { return; } - wait(); + _condVar.wait(lock); } } } +int +ObserverTopic::getSerial() const +{ + lock_guard lock(_mutex); + return _serial; +} + +void +ObserverTopic::addExpectedUpdate(int serial, const string& name) +{ + if(_syncSubscribers.empty() && name.empty()) + { + return; + } + + // Must be called with the lock held. + if(name.empty()) + { + assert(_waitForUpdates[serial].empty()); + _waitForUpdates[serial] = _syncSubscribers; + } + else + { + _waitForUpdates[serial].insert(name); + } +} + void -ObserverTopic::updateSerial(Ice::Long dbSerial) +ObserverTopic::updateSerial(long long dbSerial) { ++_serial; if(dbSerial > 0) @@ -266,7 +258,7 @@ ObserverTopic::updateSerial(Ice::Long dbSerial) } Ice::Context -ObserverTopic::getContext(int serial, Ice::Long dbSerial) const +ObserverTopic::getContext(int serial, long long dbSerial) const { Ice::Context context; { @@ -283,7 +275,7 @@ ObserverTopic::getContext(int serial, Ice::Long dbSerial) const return context; } -RegistryObserverTopic::RegistryObserverTopic(const IceStorm::TopicManagerPrx& topicManager) : +RegistryObserverTopic::RegistryObserverTopic(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager) : ObserverTopic(topicManager, "RegistryObserver") { _publishers = getPublishers<RegistryObserverPrx>(); @@ -292,18 +284,18 @@ RegistryObserverTopic::RegistryObserverTopic(const IceStorm::TopicManagerPrx& to void RegistryObserverTopic::registryUp(const RegistryInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return; } updateSerial(); - _registries.insert(make_pair(info.name, info)); + _registries.insert({ info.name, info }); try { - for(vector<RegistryObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->registryUp(info); + publisher->registryUp(info); } } catch(const Ice::LocalException& ex) @@ -316,7 +308,7 @@ RegistryObserverTopic::registryUp(const RegistryInfo& info) void RegistryObserverTopic::registryDown(const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return; @@ -331,9 +323,9 @@ RegistryObserverTopic::registryDown(const string& name) _registries.erase(name); try { - for(vector<RegistryObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->registryDown(name); + publisher->registryDown(name); } } catch(const Ice::LocalException& ex) @@ -344,57 +336,67 @@ RegistryObserverTopic::registryDown(const string& name) } void -RegistryObserverTopic::initObserver(const Ice::ObjectPrx& obsv) +RegistryObserverTopic::initObserver(const shared_ptr<Ice::ObjectPrx>& obsv) { - RegistryObserverPrx observer = RegistryObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast<RegistryObserverPrx>(obsv); RegistryInfoSeq registries; registries.reserve(_registries.size()); - for(map<string, RegistryInfo>::const_iterator p = _registries.begin(); p != _registries.end(); ++p) + for(const auto& registry : _registries) { - registries.push_back(p->second); + registries.push_back(registry.second); } observer->registryInit(registries, getContext(_serial)); } -NodeObserverTopic::NodeObserverTopic(const IceStorm::TopicManagerPrx& topicManager, - const Ice::ObjectAdapterPtr& adapter) : - ObserverTopic(topicManager, "NodeObserver") +shared_ptr<NodeObserverTopic> +NodeObserverTopic::create(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, + const shared_ptr<Ice::ObjectAdapter>& adapter) { - _publishers = getPublishers<NodeObserverPrx>(); + shared_ptr<NodeObserverTopic> topic(new NodeObserverTopic(topicManager)); + try { - const_cast<NodeObserverPrx&>(_externalPublisher) = NodeObserverPrx::uncheckedCast(adapter->addWithUUID(this)); + const_cast<shared_ptr<NodeObserverPrx>&>(topic->_externalPublisher) = + Ice::uncheckedCast<NodeObserverPrx>(adapter->addWithUUID(topic)); } catch(const Ice::LocalException&) { } + + return topic; +} + +NodeObserverTopic::NodeObserverTopic(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager) : + ObserverTopic(topicManager, "NodeObserver") +{ + _publishers = getPublishers<NodeObserverPrx>(); } void -NodeObserverTopic::nodeInit(const NodeDynamicInfoSeq&, const Ice::Current&) +NodeObserverTopic::nodeInit(NodeDynamicInfoSeq, const Ice::Current&) { assert(false); } void -NodeObserverTopic::nodeUp(const NodeDynamicInfo& info, const Ice::Current&) +NodeObserverTopic::nodeUp(NodeDynamicInfo info, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return; } updateSerial(); - _nodes.insert(make_pair(info.info.name, info)); - for(ServerDynamicInfoSeq::const_iterator p = info.servers.begin(); p != info.servers.end(); ++p) + _nodes.insert({ info.info.name, info }); + for(const auto& server : info.servers) { - _serverStatus[p->id] = p->enabled; + _serverStatus[server.id] = server.enabled; } try { - for(vector<NodeObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->nodeUp(info); + publisher->nodeUp(info); } } catch(const Ice::LocalException& ex) @@ -405,15 +407,15 @@ NodeObserverTopic::nodeUp(const NodeDynamicInfo& info, const Ice::Current&) } void -NodeObserverTopic::nodeDown(const string& /*name*/, const Ice::Current&) +NodeObserverTopic::nodeDown(string, const Ice::Current&) { assert(false); } void -NodeObserverTopic::updateServer(const string& node, const ServerDynamicInfo& server, const Ice::Current&) +NodeObserverTopic::updateServer(string node, ServerDynamicInfo server, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return; @@ -435,7 +437,7 @@ NodeObserverTopic::updateServer(const string& node, const ServerDynamicInfo& ser { if(p->id == server.id) { - if(server.state == Destroyed || (server.state == Inactive && server.enabled)) + if(server.state == ServerState::Destroyed || (server.state == ServerState::Inactive && server.enabled)) { servers.erase(p); } @@ -447,12 +449,13 @@ NodeObserverTopic::updateServer(const string& node, const ServerDynamicInfo& ser } ++p; } - if(server.state != Destroyed && (server.state != Inactive || !server.enabled) && p == servers.end()) + if(server.state != ServerState::Destroyed && (server.state != ServerState::Inactive + || !server.enabled) && p == servers.end()) { servers.push_back(server); } - if(server.state != Destroyed) + if(server.state != ServerState::Destroyed) { _serverStatus[server.id] = server.enabled; } @@ -463,9 +466,9 @@ NodeObserverTopic::updateServer(const string& node, const ServerDynamicInfo& ser try { - for(vector<NodeObserverPrx>::const_iterator q = _publishers.begin(); q != _publishers.end(); ++q) + for(const auto& publisher : _publishers) { - (*q)->updateServer(node, server); + publisher->updateServer(node, server); } } catch(const Ice::LocalException& ex) @@ -476,9 +479,9 @@ NodeObserverTopic::updateServer(const string& node, const ServerDynamicInfo& ser } void -NodeObserverTopic::updateAdapter(const string& node, const AdapterDynamicInfo& adapter, const Ice::Current&) +NodeObserverTopic::updateAdapter(string node, AdapterDynamicInfo adapter, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return; @@ -519,9 +522,9 @@ NodeObserverTopic::updateAdapter(const string& node, const AdapterDynamicInfo& a try { - for(vector<NodeObserverPrx>::const_iterator q = _publishers.begin(); q != _publishers.end(); ++q) + for(const auto& publisher : _publishers) { - (*q)->updateAdapter(node, adapter); + publisher->updateAdapter(node, adapter); } } catch(const Ice::LocalException& ex) @@ -534,7 +537,7 @@ NodeObserverTopic::updateAdapter(const string& node, const AdapterDynamicInfo& a void NodeObserverTopic::nodeDown(const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return; @@ -548,17 +551,17 @@ NodeObserverTopic::nodeDown(const string& name) } ServerDynamicInfoSeq& servers = _nodes[name].servers; - for(ServerDynamicInfoSeq::const_iterator p = servers.begin(); p != servers.end(); ++p) + for(const auto& server : servers) { - _serverStatus.erase(p->id); + _serverStatus.erase(server.id); } _nodes.erase(name); try { - for(vector<NodeObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->nodeDown(name); + publisher->nodeDown(name); } } catch(const Ice::LocalException& ex) @@ -569,14 +572,14 @@ NodeObserverTopic::nodeDown(const string& name) } void -NodeObserverTopic::initObserver(const Ice::ObjectPrx& obsv) +NodeObserverTopic::initObserver(const shared_ptr<Ice::ObjectPrx>& obsv) { - NodeObserverPrx observer = NodeObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast<NodeObserverPrx>(obsv); NodeDynamicInfoSeq nodes; nodes.reserve(_nodes.size()); - for(map<string, NodeDynamicInfo>::const_iterator p = _nodes.begin(); p != _nodes.end(); ++p) + for(const auto& node : _nodes ) { - nodes.push_back(p->second); + nodes.push_back(node.second); } observer->nodeInit(nodes, getContext(_serial)); } @@ -584,7 +587,7 @@ NodeObserverTopic::initObserver(const Ice::ObjectPrx& obsv) bool NodeObserverTopic::isServerEnabled(const string& server) const { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return false; @@ -600,8 +603,8 @@ NodeObserverTopic::isServerEnabled(const string& server) const } } -ApplicationObserverTopic::ApplicationObserverTopic(const IceStorm::TopicManagerPrx& topicManager, - const map<string, ApplicationInfo>& applications, Ice::Long serial) : +ApplicationObserverTopic::ApplicationObserverTopic(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, + const map<string, ApplicationInfo>& applications, long long serial) : ObserverTopic(topicManager, "ApplicationObserver", serial), _applications(applications) { @@ -609,9 +612,9 @@ ApplicationObserverTopic::ApplicationObserverTopic(const IceStorm::TopicManagerP } int -ApplicationObserverTopic::applicationInit(Ice::Long dbSerial, const ApplicationInfoSeq& apps) +ApplicationObserverTopic::applicationInit(long long dbSerial, const ApplicationInfoSeq& apps) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -624,9 +627,9 @@ ApplicationObserverTopic::applicationInit(Ice::Long dbSerial, const ApplicationI } try { - for(vector<ApplicationObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->applicationInit(_serial, apps, getContext(_serial, dbSerial)); + publisher->applicationInit(_serial, apps, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -639,9 +642,9 @@ ApplicationObserverTopic::applicationInit(Ice::Long dbSerial, const ApplicationI } int -ApplicationObserverTopic::applicationAdded(Ice::Long dbSerial, const ApplicationInfo& info) +ApplicationObserverTopic::applicationAdded(long long dbSerial, const ApplicationInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -651,9 +654,9 @@ ApplicationObserverTopic::applicationAdded(Ice::Long dbSerial, const Application _applications.insert(make_pair(info.descriptor.name, info)); try { - for(vector<ApplicationObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->applicationAdded(_serial, info, getContext(_serial, dbSerial)); + publisher->applicationAdded(_serial, info, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -666,9 +669,9 @@ ApplicationObserverTopic::applicationAdded(Ice::Long dbSerial, const Application } int -ApplicationObserverTopic::applicationRemoved(Ice::Long dbSerial, const string& name) +ApplicationObserverTopic::applicationRemoved(long long dbSerial, const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -677,9 +680,9 @@ ApplicationObserverTopic::applicationRemoved(Ice::Long dbSerial, const string& n _applications.erase(name); try { - for(vector<ApplicationObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->applicationRemoved(_serial, name, getContext(_serial, dbSerial)); + publisher->applicationRemoved(_serial, name, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -692,9 +695,9 @@ ApplicationObserverTopic::applicationRemoved(Ice::Long dbSerial, const string& n } int -ApplicationObserverTopic::applicationUpdated(Ice::Long dbSerial, const ApplicationUpdateInfo& info) +ApplicationObserverTopic::applicationUpdated(long long dbSerial, const ApplicationUpdateInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -733,9 +736,9 @@ ApplicationObserverTopic::applicationUpdated(Ice::Long dbSerial, const Applicati } try { - for(vector<ApplicationObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->applicationUpdated(_serial, info, getContext(_serial, dbSerial)); + publisher->applicationUpdated(_serial, info, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -748,19 +751,19 @@ ApplicationObserverTopic::applicationUpdated(Ice::Long dbSerial, const Applicati } void -ApplicationObserverTopic::initObserver(const Ice::ObjectPrx& obsv) +ApplicationObserverTopic::initObserver(const shared_ptr<Ice::ObjectPrx>& obsv) { - ApplicationObserverPrx observer = ApplicationObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast<ApplicationObserverPrx>(obsv); ApplicationInfoSeq applications; - for(map<string, ApplicationInfo>::const_iterator p = _applications.begin(); p != _applications.end(); ++p) + for(const auto& application : _applications) { - applications.push_back(p->second); + applications.push_back(application.second); } observer->applicationInit(_serial, applications, getContext(_serial, _dbSerial)); } -AdapterObserverTopic::AdapterObserverTopic(const IceStorm::TopicManagerPrx& topicManager, - const map<string, AdapterInfo>& adapters, Ice::Long serial) : +AdapterObserverTopic::AdapterObserverTopic(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, + const map<string, AdapterInfo>& adapters, long long serial) : ObserverTopic(topicManager, "AdapterObserver", serial), _adapters(adapters) { @@ -768,24 +771,24 @@ AdapterObserverTopic::AdapterObserverTopic(const IceStorm::TopicManagerPrx& topi } int -AdapterObserverTopic::adapterInit(Ice::Long dbSerial, const AdapterInfoSeq& adpts) +AdapterObserverTopic::adapterInit(long long dbSerial, const AdapterInfoSeq& adpts) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; } updateSerial(dbSerial); _adapters.clear(); - for(AdapterInfoSeq::const_iterator q = adpts.begin(); q != adpts.end(); ++q) + for(const auto& adpt : adpts) { - _adapters.insert(make_pair(q->id, *q)); + _adapters.insert({ adpt.id, adpt }); } try { - for(vector<AdapterObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->adapterInit(adpts, getContext(_serial, dbSerial)); + publisher->adapterInit(adpts, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -798,9 +801,9 @@ AdapterObserverTopic::adapterInit(Ice::Long dbSerial, const AdapterInfoSeq& adpt } int -AdapterObserverTopic::adapterAdded(Ice::Long dbSerial, const AdapterInfo& info) +AdapterObserverTopic::adapterAdded(long long dbSerial, const AdapterInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -809,9 +812,9 @@ AdapterObserverTopic::adapterAdded(Ice::Long dbSerial, const AdapterInfo& info) _adapters.insert(make_pair(info.id, info)); try { - for(vector<AdapterObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->adapterAdded(info, getContext(_serial, dbSerial)); + publisher->adapterAdded(info, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -824,9 +827,9 @@ AdapterObserverTopic::adapterAdded(Ice::Long dbSerial, const AdapterInfo& info) } int -AdapterObserverTopic::adapterUpdated(Ice::Long dbSerial, const AdapterInfo& info) +AdapterObserverTopic::adapterUpdated(long long dbSerial, const AdapterInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -835,9 +838,9 @@ AdapterObserverTopic::adapterUpdated(Ice::Long dbSerial, const AdapterInfo& info _adapters[info.id] = info; try { - for(vector<AdapterObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->adapterUpdated(info, getContext(_serial, dbSerial)); + publisher->adapterUpdated(info, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -850,9 +853,9 @@ AdapterObserverTopic::adapterUpdated(Ice::Long dbSerial, const AdapterInfo& info } int -AdapterObserverTopic::adapterRemoved(Ice::Long dbSerial, const string& id) +AdapterObserverTopic::adapterRemoved(long long dbSerial, const string& id) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -861,9 +864,9 @@ AdapterObserverTopic::adapterRemoved(Ice::Long dbSerial, const string& id) _adapters.erase(id); try { - for(vector<AdapterObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->adapterRemoved(id, getContext(_serial, dbSerial)); + publisher->adapterRemoved(id, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -876,19 +879,19 @@ AdapterObserverTopic::adapterRemoved(Ice::Long dbSerial, const string& id) } void -AdapterObserverTopic::initObserver(const Ice::ObjectPrx& obsv) +AdapterObserverTopic::initObserver(const shared_ptr<Ice::ObjectPrx>& obsv) { - AdapterObserverPrx observer = AdapterObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast<AdapterObserverPrx>(obsv); AdapterInfoSeq adapters; - for(map<string, AdapterInfo>::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + for(const auto& adapter : _adapters) { - adapters.push_back(p->second); + adapters.push_back(adapter.second); } observer->adapterInit(adapters, getContext(_serial, _dbSerial)); } -ObjectObserverTopic::ObjectObserverTopic(const IceStorm::TopicManagerPrx& topicManager, - const map<Ice::Identity, ObjectInfo>& objects, Ice::Long serial) : +ObjectObserverTopic::ObjectObserverTopic(const shared_ptr<IceStorm::TopicManagerPrx>& topicManager, + const map<Ice::Identity, ObjectInfo>& objects, long long serial) : ObserverTopic(topicManager, "ObjectObserver", serial), _objects(objects) { @@ -896,24 +899,24 @@ ObjectObserverTopic::ObjectObserverTopic(const IceStorm::TopicManagerPrx& topicM } int -ObjectObserverTopic::objectInit(Ice::Long dbSerial, const ObjectInfoSeq& objects) +ObjectObserverTopic::objectInit(long long dbSerial, const ObjectInfoSeq& objects) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; } updateSerial(dbSerial); _objects.clear(); - for(ObjectInfoSeq::const_iterator r = objects.begin(); r != objects.end(); ++r) + for(const auto& object : objects) { - _objects.insert(make_pair(r->proxy->ice_getIdentity(), *r)); + _objects.insert(make_pair(object.proxy->ice_getIdentity(), object)); } try { - for(vector<ObjectObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->objectInit(objects, getContext(_serial, dbSerial)); + publisher->objectInit(objects, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -926,9 +929,9 @@ ObjectObserverTopic::objectInit(Ice::Long dbSerial, const ObjectInfoSeq& objects } int -ObjectObserverTopic::objectAdded(Ice::Long dbSerial, const ObjectInfo& info) +ObjectObserverTopic::objectAdded(long long dbSerial, const ObjectInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -937,9 +940,9 @@ ObjectObserverTopic::objectAdded(Ice::Long dbSerial, const ObjectInfo& info) _objects.insert(make_pair(info.proxy->ice_getIdentity(), info)); try { - for(vector<ObjectObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->objectAdded(info, getContext(_serial, dbSerial)); + publisher->objectAdded(info, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -952,9 +955,9 @@ ObjectObserverTopic::objectAdded(Ice::Long dbSerial, const ObjectInfo& info) } int -ObjectObserverTopic::objectUpdated(Ice::Long dbSerial, const ObjectInfo& info) +ObjectObserverTopic::objectUpdated(long long dbSerial, const ObjectInfo& info) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -963,9 +966,9 @@ ObjectObserverTopic::objectUpdated(Ice::Long dbSerial, const ObjectInfo& info) _objects[info.proxy->ice_getIdentity()] = info; try { - for(vector<ObjectObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->objectUpdated(info, getContext(_serial, dbSerial)); + publisher->objectUpdated(info, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -978,9 +981,9 @@ ObjectObserverTopic::objectUpdated(Ice::Long dbSerial, const ObjectInfo& info) } int -ObjectObserverTopic::objectRemoved(Ice::Long dbSerial, const Ice::Identity& id) +ObjectObserverTopic::objectRemoved(long long dbSerial, const Ice::Identity& id) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; @@ -989,9 +992,9 @@ ObjectObserverTopic::objectRemoved(Ice::Long dbSerial, const Ice::Identity& id) _objects.erase(id); try { - for(vector<ObjectObserverPrx>::const_iterator p = _publishers.begin(); p != _publishers.end(); ++p) + for(const auto& publisher : _publishers) { - (*p)->objectRemoved(id, getContext(_serial, dbSerial)); + publisher->objectRemoved(id, getContext(_serial, dbSerial)); } } catch(const Ice::LocalException& ex) @@ -1006,24 +1009,24 @@ ObjectObserverTopic::objectRemoved(Ice::Long dbSerial, const Ice::Identity& id) int ObjectObserverTopic::wellKnownObjectsAddedOrUpdated(const ObjectInfoSeq& infos) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; } - for(ObjectInfoSeq::const_iterator p = infos.begin(); p != infos.end(); ++p) + for(const auto& info : infos) { updateSerial(); - map<Ice::Identity, ObjectInfo>::iterator q = _objects.find(p->proxy->ice_getIdentity()); + auto q = _objects.find(info.proxy->ice_getIdentity()); if(q != _objects.end()) { - q->second = *p; + q->second = info; try { - for(vector<ObjectObserverPrx>::const_iterator r = _publishers.begin(); r != _publishers.end(); ++r) + for(const auto& publisher : _publishers) { - (*r)->objectUpdated(*p, getContext(_serial)); + publisher->objectUpdated(info, getContext(_serial)); } } catch(const Ice::LocalException& ex) @@ -1034,12 +1037,12 @@ ObjectObserverTopic::wellKnownObjectsAddedOrUpdated(const ObjectInfoSeq& infos) } else { - _objects.insert(make_pair(p->proxy->ice_getIdentity(), *p)); + _objects.insert(make_pair(info.proxy->ice_getIdentity(), info)); try { - for(vector<ObjectObserverPrx>::const_iterator r = _publishers.begin(); r != _publishers.end(); ++r) + for(const auto& publisher : _publishers) { - (*r)->objectAdded(*p, getContext(_serial)); + publisher->objectAdded(info, getContext(_serial)); } } catch(const Ice::LocalException& ex) @@ -1055,28 +1058,27 @@ ObjectObserverTopic::wellKnownObjectsAddedOrUpdated(const ObjectInfoSeq& infos) // here. This operation is called by ReplicaSessionI. // addExpectedUpdate(_serial); - //waitForSyncedSubscribersNoSync(_serial); return _serial; } int ObjectObserverTopic::wellKnownObjectsRemoved(const ObjectInfoSeq& infos) { - Lock sync(*this); + lock_guard lock(_mutex); if(_topics.empty()) { return -1; } - for(ObjectInfoSeq::const_iterator p = infos.begin(); p != infos.end(); ++p) + for(const auto& info : infos) { updateSerial(); - _objects.erase(p->proxy->ice_getIdentity()); + _objects.erase(info.proxy->ice_getIdentity()); try { - for(vector<ObjectObserverPrx>::const_iterator q = _publishers.begin(); q != _publishers.end(); ++q) + for(const auto& publisher : _publishers) { - (*q)->objectRemoved(p->proxy->ice_getIdentity(), getContext(_serial)); + publisher->objectRemoved(info.proxy->ice_getIdentity(), getContext(_serial)); } } catch(const Ice::LocalException& ex) @@ -1088,22 +1090,21 @@ ObjectObserverTopic::wellKnownObjectsRemoved(const ObjectInfoSeq& infos) // // We don't need to wait for the update to be received by the - // replicas here. This operation is only called internaly by + // replicas here. This operation is only called internally by // IceGrid. // addExpectedUpdate(_serial); - //waitForSyncedSubscribersNoSync(_serial); return _serial; } void -ObjectObserverTopic::initObserver(const Ice::ObjectPrx& obsv) +ObjectObserverTopic::initObserver(const shared_ptr<Ice::ObjectPrx>& obsv) { - ObjectObserverPrx observer = ObjectObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast<ObjectObserverPrx>(obsv); ObjectInfoSeq objects; - for(map<Ice::Identity, ObjectInfo>::const_iterator p = _objects.begin(); p != _objects.end(); ++p) + for(const auto& object : _objects) { - objects.push_back(p->second); + objects.push_back(object.second); } observer->objectInit(objects, getContext(_serial, _dbSerial)); } diff --git a/cpp/src/IceGrid/Topics.h b/cpp/src/IceGrid/Topics.h index 01288d76715..48d60c2df7a 100644 --- a/cpp/src/IceGrid/Topics.h +++ b/cpp/src/IceGrid/Topics.h @@ -5,7 +5,6 @@ #ifndef ICEGRID_TOPICS_H #define ICEGRID_TOPICS_H -#include <IceUtil/Mutex.h> #include <IceStorm/IceStorm.h> #include <IceGrid/Internal.h> #include <IceGrid/Registry.h> @@ -14,20 +13,20 @@ namespace IceGrid { -class ObserverTopic : public IceUtil::Monitor<IceUtil::Mutex>, public virtual Ice::Object +class ObserverTopic { public: - ObserverTopic(const IceStorm::TopicManagerPrx&, const std::string&, Ice::Long = 0); - virtual ~ObserverTopic(); + ObserverTopic(const std::shared_ptr<IceStorm::TopicManagerPrx>&, const std::string&, long long = 0); + virtual ~ObserverTopic() = default; - int subscribe(const Ice::ObjectPrx&, const std::string& = std::string()); - void unsubscribe(const Ice::ObjectPrx&, const std::string& = std::string()); + int subscribe(const std::shared_ptr<Ice::ObjectPrx>&, const std::string& = std::string()); + void unsubscribe(const std::shared_ptr<Ice::ObjectPrx>&, const std::string& = std::string()); void destroy(); void receivedUpdate(const std::string&, int, const std::string&); - virtual void initObserver(const Ice::ObjectPrx&) = 0; + virtual void initObserver(const std::shared_ptr<Ice::ObjectPrx>&) = 0; void waitForSyncedSubscribers(int, const std::string& = std::string()); @@ -36,140 +35,139 @@ public: protected: void addExpectedUpdate(int, const std::string& = std::string()); - void waitForSyncedSubscribersNoSync(int, const std::string& = std::string()); - void updateSerial(Ice::Long = 0); - Ice::Context getContext(int, Ice::Long = 0) const; + void updateSerial(long long = 0); + Ice::Context getContext(int, long long = 0) const; - template<typename T> std::vector<T> getPublishers() const + template<typename T> std::vector<std::shared_ptr<T>> getPublishers() const { - std::vector<T> publishers; - for(std::vector<Ice::ObjectPrx>::const_iterator p = _basePublishers.begin(); p != _basePublishers.end(); ++p) + std::vector<std::shared_ptr<T>> publishers; + for(const auto& publisher :_basePublishers) { - publishers.push_back(T::uncheckedCast(*p)); + publishers.push_back(Ice::uncheckedCast<T>(publisher)); } return publishers; } - Ice::LoggerPtr _logger; - std::map<Ice::EncodingVersion, IceStorm::TopicPrx> _topics; - std::vector<Ice::ObjectPrx> _basePublishers; + std::shared_ptr<Ice::Logger> _logger; + std::map<Ice::EncodingVersion, std::shared_ptr<IceStorm::TopicPrx>> _topics; + std::vector<std::shared_ptr<Ice::ObjectPrx>> _basePublishers; int _serial; - Ice::Long _dbSerial; + long long _dbSerial; std::set<std::string> _syncSubscribers; std::map<int, std::set<std::string> > _waitForUpdates; std::map<int, std::map<std::string, std::string> > _updateFailures; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle<ObserverTopic> ObserverTopicPtr; class RegistryObserverTopic : public ObserverTopic { public: - RegistryObserverTopic(const IceStorm::TopicManagerPrx&); + RegistryObserverTopic(const std::shared_ptr<IceStorm::TopicManagerPrx>&); void registryUp(const RegistryInfo&); void registryDown(const std::string&); - virtual void initObserver(const Ice::ObjectPrx&); + virtual void initObserver(const std::shared_ptr<Ice::ObjectPrx>&); private: - std::vector<RegistryObserverPrx> _publishers; + std::vector<std::shared_ptr<RegistryObserverPrx>> _publishers; std::map<std::string, RegistryInfo> _registries; }; -typedef IceUtil::Handle<RegistryObserverTopic> RegistryObserverTopicPtr; -class NodeObserverTopic : public ObserverTopic, public NodeObserver +class NodeObserverTopic final : public ObserverTopic, public NodeObserver { public: - NodeObserverTopic(const IceStorm::TopicManagerPrx&, const Ice::ObjectAdapterPtr&); + static std::shared_ptr<NodeObserverTopic> + create(const std::shared_ptr<IceStorm::TopicManagerPrx>&, const std::shared_ptr<Ice::ObjectAdapter>&); - virtual void nodeInit(const NodeDynamicInfoSeq&, const Ice::Current&); - virtual void nodeUp(const NodeDynamicInfo&, const Ice::Current&); - virtual void nodeDown(const std::string&, const Ice::Current&); - virtual void updateServer(const std::string&, const ServerDynamicInfo&, const Ice::Current&); - virtual void updateAdapter(const std::string&, const AdapterDynamicInfo&, const Ice::Current&); + void nodeInit(NodeDynamicInfoSeq, const Ice::Current&) override; + void nodeUp(NodeDynamicInfo, const Ice::Current&) override; + void nodeDown(std::string, const Ice::Current&) override; + void updateServer(std::string, ServerDynamicInfo, const Ice::Current&) override; + void updateAdapter(std::string, AdapterDynamicInfo, const Ice::Current&) override; - const NodeObserverPrx& getPublisher() { return _externalPublisher; } + const std::shared_ptr<NodeObserverPrx>& getPublisher() { return _externalPublisher; } void nodeDown(const std::string&); - virtual void initObserver(const Ice::ObjectPrx&); + void initObserver(const std::shared_ptr<Ice::ObjectPrx>&) override; bool isServerEnabled(const std::string&) const; private: - const NodeObserverPrx _externalPublisher; - std::vector<NodeObserverPrx> _publishers; + NodeObserverTopic(const std::shared_ptr<IceStorm::TopicManagerPrx>&); + + const std::shared_ptr<NodeObserverPrx> _externalPublisher; + std::vector<std::shared_ptr<NodeObserverPrx>> _publishers; std::map<std::string, NodeDynamicInfo> _nodes; std::map<std::string, bool> _serverStatus; }; -typedef IceUtil::Handle<NodeObserverTopic> NodeObserverTopicPtr; class ApplicationObserverTopic : public ObserverTopic { public: - ApplicationObserverTopic(const IceStorm::TopicManagerPrx&, const std::map<std::string, ApplicationInfo>&, Ice::Long); + ApplicationObserverTopic(const std::shared_ptr<IceStorm::TopicManagerPrx>&, const std::map<std::string, ApplicationInfo>&, long long); - int applicationInit(Ice::Long, const ApplicationInfoSeq&); - int applicationAdded(Ice::Long, const ApplicationInfo&); - int applicationRemoved(Ice::Long, const std::string&); - int applicationUpdated(Ice::Long, const ApplicationUpdateInfo&); + int applicationInit(long long, const ApplicationInfoSeq&); + int applicationAdded(long long, const ApplicationInfo&); + int applicationRemoved(long long, const std::string&); + int applicationUpdated(long long, const ApplicationUpdateInfo&); - virtual void initObserver(const Ice::ObjectPrx&); + virtual void initObserver(const std::shared_ptr<Ice::ObjectPrx>&); private: - std::vector<ApplicationObserverPrx> _publishers; + std::vector<std::shared_ptr<ApplicationObserverPrx>> _publishers; std::map<std::string, ApplicationInfo> _applications; }; -typedef IceUtil::Handle<ApplicationObserverTopic> ApplicationObserverTopicPtr; class AdapterObserverTopic : public ObserverTopic { public: - AdapterObserverTopic(const IceStorm::TopicManagerPrx&, const std::map<std::string, AdapterInfo>&, Ice::Long); + AdapterObserverTopic(const std::shared_ptr<IceStorm::TopicManagerPrx>&, const std::map<std::string, AdapterInfo>&, long long); - int adapterInit(Ice::Long, const AdapterInfoSeq&); - int adapterAdded(Ice::Long, const AdapterInfo&); - int adapterUpdated(Ice::Long, const AdapterInfo&); - int adapterRemoved(Ice::Long, const std::string&); + int adapterInit(long long, const AdapterInfoSeq&); + int adapterAdded(long long, const AdapterInfo&); + int adapterUpdated(long long, const AdapterInfo&); + int adapterRemoved(long long, const std::string&); - virtual void initObserver(const Ice::ObjectPrx&); + virtual void initObserver(const std::shared_ptr<Ice::ObjectPrx>&); private: - std::vector<AdapterObserverPrx> _publishers; + std::vector<std::shared_ptr<AdapterObserverPrx>> _publishers; std::map<std::string, AdapterInfo> _adapters; }; -typedef IceUtil::Handle<AdapterObserverTopic> AdapterObserverTopicPtr; class ObjectObserverTopic : public ObserverTopic { public: - ObjectObserverTopic(const IceStorm::TopicManagerPrx&, const std::map<Ice::Identity, ObjectInfo>&, Ice::Long); + ObjectObserverTopic(const std::shared_ptr<IceStorm::TopicManagerPrx>&, const std::map<Ice::Identity, ObjectInfo>&, long long); - int objectInit(Ice::Long, const ObjectInfoSeq&); - int objectAdded(Ice::Long, const ObjectInfo&); - int objectUpdated(Ice::Long, const ObjectInfo&); - int objectRemoved(Ice::Long, const Ice::Identity&); + int objectInit(long long, const ObjectInfoSeq&); + int objectAdded(long long, const ObjectInfo&); + int objectUpdated(long long, const ObjectInfo&); + int objectRemoved(long long, const Ice::Identity&); int wellKnownObjectsAddedOrUpdated(const ObjectInfoSeq&); int wellKnownObjectsRemoved(const ObjectInfoSeq&); - virtual void initObserver(const Ice::ObjectPrx&); + virtual void initObserver(const std::shared_ptr<Ice::ObjectPrx>&); private: - std::vector<ObjectObserverPrx> _publishers; + std::vector<std::shared_ptr<ObjectObserverPrx>> _publishers; std::map<Ice::Identity, ObjectInfo> _objects; }; -typedef IceUtil::Handle<ObjectObserverTopic> ObjectObserverTopicPtr; }; diff --git a/cpp/src/IceGrid/TraceLevels.cpp b/cpp/src/IceGrid/TraceLevels.cpp index 530661196ac..c65b20c3308 100644 --- a/cpp/src/IceGrid/TraceLevels.cpp +++ b/cpp/src/IceGrid/TraceLevels.cpp @@ -9,32 +9,32 @@ using namespace std; using namespace IceGrid; -TraceLevels::TraceLevels(const Ice::CommunicatorPtr& communicator, const string& prefix) : - admin(0), +TraceLevels::TraceLevels(const shared_ptr<Ice::Communicator>& communicator, const string& prefix) : + admin(), adminCat("Admin"), - application(0), + application(), applicationCat("Application"), - node(0), + node(), nodeCat("Node"), - replica(0), + replica(), replicaCat("Replica"), - server(0), + server(), serverCat("Server"), - adapter(0), + adapter(), adapterCat("Adapter"), - object(0), + object(), objectCat("Object"), - activator(0), + activator(), activatorCat("Activator"), - locator(0), + locator(), locatorCat("Locator"), - session(0), + session(), sessionCat("Session"), - discovery(0), + discovery(), discoveryCat("Discovery"), logger(communicator->getLogger()) { - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string keyBase = prefix + ".Trace."; const_cast<int&>(admin) = properties->getPropertyAsInt(keyBase + adminCat); @@ -49,7 +49,3 @@ TraceLevels::TraceLevels(const Ice::CommunicatorPtr& communicator, const string& const_cast<int&>(session) = properties->getPropertyAsInt(keyBase + sessionCat); const_cast<int&>(discovery) = properties->getPropertyAsInt(keyBase + discoveryCat); } - -TraceLevels::~TraceLevels() -{ -} diff --git a/cpp/src/IceGrid/TraceLevels.h b/cpp/src/IceGrid/TraceLevels.h index 11e5a852355..6d949d1a8b2 100644 --- a/cpp/src/IceGrid/TraceLevels.h +++ b/cpp/src/IceGrid/TraceLevels.h @@ -5,58 +5,54 @@ #ifndef ICE_GRID_TRACE_LEVELS_H #define ICE_GRID_TRACE_LEVELS_H -#include <IceUtil/Shared.h> #include <Ice/CommunicatorF.h> #include <Ice/LoggerF.h> namespace IceGrid { -class TraceLevels : public ::IceUtil::Shared +class TraceLevels { public: - TraceLevels(const Ice::CommunicatorPtr&, const std::string&); - virtual ~TraceLevels(); + TraceLevels(const std::shared_ptr<Ice::Communicator>&, const std::string&); const int admin; - const char* adminCat; + const std::string adminCat; const int application; - const char* applicationCat; + const std::string applicationCat; const int node; - const char* nodeCat; + const std::string nodeCat; const int replica; - const char* replicaCat; + const std::string replicaCat; const int server; - const char* serverCat; + const std::string serverCat; const int adapter; - const char* adapterCat; + const std::string adapterCat; const int object; - const char* objectCat; + const std::string objectCat; const int activator; - const char* activatorCat; + const std::string activatorCat; const int locator; - const char* locatorCat; + const std::string locatorCat; const int session; - const char* sessionCat; + const std::string sessionCat; const int discovery; - const char* discoveryCat; + const std::string discoveryCat; - const Ice::LoggerPtr logger; + const std::shared_ptr<Ice::Logger> logger; }; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - } // End namespace IceGrid #endif diff --git a/cpp/src/IceGrid/Util.cpp b/cpp/src/IceGrid/Util.cpp index f9dfe622877..d7778805171 100644 --- a/cpp/src/IceGrid/Util.cpp +++ b/cpp/src/IceGrid/Util.cpp @@ -71,12 +71,12 @@ IceGrid::toString(const vector<string>& v, const string& sep) } string -IceGrid::toString(const Ice::Exception& exception) +IceGrid::toString(exception_ptr exception) { std::ostringstream os; try { - exception.ice_throw(); + rethrow_exception(exception); } catch(const NodeUnreachableException& ex) { @@ -239,7 +239,8 @@ IceGrid::escapeProperty(const string& s, bool escapeEqual) } ObjectInfo -IceGrid::toObjectInfo(const Ice::CommunicatorPtr& communicator, const ObjectDescriptor& obj, const string& adapterId) +IceGrid::toObjectInfo(const shared_ptr<Ice::Communicator>& communicator, const ObjectDescriptor& obj, + const string& adapterId) { ObjectInfo info; info.type = obj.type; @@ -264,7 +265,7 @@ IceGrid::toObjectInfo(const Ice::CommunicatorPtr& communicator, const ObjectDesc } void -IceGrid::setupThreadPool(const PropertiesPtr& properties, const string& name, int size, int sizeMax, bool serialize) +IceGrid::setupThreadPool(const shared_ptr<Properties>& properties, const string& name, int size, int maxSize, bool serialize) { if(properties->getPropertyAsIntWithDefault(name + ".Size", 0) < size) { @@ -277,16 +278,16 @@ IceGrid::setupThreadPool(const PropertiesPtr& properties, const string& name, in size = properties->getPropertyAsInt(name + ".Size"); } - if(sizeMax > 0 && properties->getPropertyAsIntWithDefault(name + ".SizeMax", 0) < sizeMax) + if(maxSize > 0 && properties->getPropertyAsIntWithDefault(name + ".MaxSize", 0) < maxSize) { - if(size >= sizeMax) + if(size >= maxSize) { - sizeMax = size * 10; + maxSize = size * 10; } ostringstream os; - os << sizeMax; - properties->setProperty(name + ".SizeMax", os.str()); + os << maxSize; + properties->setProperty(name + ".MaxSize", os.str()); } if(serialize) @@ -298,13 +299,18 @@ IceGrid::setupThreadPool(const PropertiesPtr& properties, const string& name, in int IceGrid::getMMVersion(const string& o) { - // // Strip the version - // string::size_type beg = o.find_first_not_of(' '); string::size_type end = o.find_last_not_of(' '); string version = o.substr(beg == string::npos ? 0 : beg, end == string::npos ? o.length() - 1 : end - beg + 1); + // Remove any pre-release information from the version string. + string::size_type dashPos = version.find('-'); + if(dashPos != string::npos) + { + version = version.substr(0, dashPos); + } + string::size_type minorPos = version.find('.'); string::size_type patchPos = version.find('.', minorPos + 1); @@ -636,3 +642,9 @@ IceGrid::createDirectoryRecursive(const string& pa) } } } + +int +IceGrid::secondsToInt(const std::chrono::seconds& sec) +{ + return chrono::duration_cast<chrono::duration<int>>(sec).count(); +} diff --git a/cpp/src/IceGrid/Util.h b/cpp/src/IceGrid/Util.h index 6f5312102c4..d2792a595da 100644 --- a/cpp/src/IceGrid/Util.h +++ b/cpp/src/IceGrid/Util.h @@ -5,6 +5,7 @@ #ifndef ICE_GRID_UTIL_H #define ICE_GRID_UTIL_H +#include <Ice/Properties.h> #include <IceGrid/Descriptor.h> #include <IceUtil/StringUtil.h> #include <IceGrid/Exception.h> @@ -23,7 +24,7 @@ inline set_inserter(T& container) } std::string toString(const std::vector<std::string>&, const std::string& = std::string(" ")); -std::string toString(const Ice::Exception&); +std::string toString(std::exception_ptr); std::string getProperty(const PropertyDescriptorSeq&, const std::string&, const std::string& = std::string()); int getPropertyAsInt(const PropertyDescriptorSeq&, const std::string&, int = 0); @@ -32,9 +33,9 @@ bool hasProperty(const PropertyDescriptorSeq&, const std::string&); PropertyDescriptor createProperty(const std::string&, const std::string& = std::string()); std::string escapeProperty(const std::string&, bool = false); -ObjectInfo toObjectInfo(const Ice::CommunicatorPtr&, const ObjectDescriptor&, const std::string&); +ObjectInfo toObjectInfo(const std::shared_ptr<Ice::Communicator>&, const ObjectDescriptor&, const std::string&); -void setupThreadPool(const Ice::PropertiesPtr&, const std::string&, int, int = 0, bool = false); +void setupThreadPool(const std::shared_ptr<Ice::Properties>&, const std::string&, int, int = 0, bool = false); int getMMVersion(const std::string&); @@ -45,118 +46,82 @@ Ice::StringSeq readDirectory(const std::string&); void createDirectory(const std::string&); void createDirectoryRecursive(const std::string&); -template<class Function> -struct ForEachCommunicator : std::unary_function<CommunicatorDescriptorPtr&, void> +int secondsToInt(const std::chrono::seconds&); + +inline void +forEachCommunicator(const std::shared_ptr<CommunicatorDescriptor>& descriptor, + std::function<void(const std::shared_ptr<CommunicatorDescriptor>&)> callback) { - ForEachCommunicator(Function f) : _function(f) + callback(descriptor); + auto iceBox = std::dynamic_pointer_cast<IceBoxDescriptor>(descriptor); + if(iceBox) { + for(const auto& service : iceBox->services) + { + forEachCommunicator(service.descriptor, callback); + } } +} - void - operator()(const ServiceInstanceDescriptor& descriptor) +inline void +forEachCommunicator(const std::shared_ptr<CommunicatorDescriptor>& oldDescriptor, + const std::shared_ptr<CommunicatorDescriptor>& newDescriptor, + std::function<void(const std::shared_ptr<CommunicatorDescriptor>&, + const std::shared_ptr<CommunicatorDescriptor>&)> callback) +{ + callback(oldDescriptor, newDescriptor); + + auto oldIceBox = std::dynamic_pointer_cast<IceBoxDescriptor>(oldDescriptor); + auto newIceBox = std::dynamic_pointer_cast<IceBoxDescriptor>(newDescriptor); + + if(oldIceBox && !newIceBox) { - assert(descriptor.descriptor); - operator()(descriptor.descriptor); + for(const auto& service : oldIceBox->services) + { + callback(service.descriptor, nullptr); + } } - - void - operator()(const CommunicatorDescriptorPtr& descriptor) + else if(!oldIceBox && newIceBox) { - _function(descriptor); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(descriptor); - if(iceBox) + for(const auto& service: newIceBox->services) { - for_each(iceBox->services.begin(), iceBox->services.end(), forEachCommunicator(_function)); + callback(nullptr, service.descriptor); } } - - void - operator()(const CommunicatorDescriptorPtr& oldDesc, const CommunicatorDescriptorPtr& newDesc) + else if(oldIceBox && newIceBox) { - _function(oldDesc, newDesc); - - IceBoxDescriptorPtr oldIceBox = IceBoxDescriptorPtr::dynamicCast(oldDesc); - IceBoxDescriptorPtr newIceBox = IceBoxDescriptorPtr::dynamicCast(newDesc); - ServiceInstanceDescriptorSeq::const_iterator p; - if(oldIceBox && !newIceBox) + for(const auto& oldService : oldIceBox->services) { - for(p = oldIceBox->services.begin(); p != oldIceBox->services.end(); ++p) + ServiceInstanceDescriptorSeq::const_iterator q; + for(q = newIceBox->services.begin(); q != newIceBox->services.end(); ++q) { - _function(p->descriptor, 0); + if(oldService.descriptor->name == q->descriptor->name) + { + callback(oldService.descriptor, q->descriptor); + break; + } } - } - else if(!oldIceBox && newIceBox) - { - for(p = newIceBox->services.begin(); p != newIceBox->services.end(); ++p) + if(q == newIceBox->services.end()) { - _function(0, p->descriptor); + callback(oldService.descriptor, nullptr); } } - else if(oldIceBox && newIceBox) + for(const auto& newService : newIceBox->services) { - for(p = oldIceBox->services.begin(); p != oldIceBox->services.end(); ++p) + ServiceInstanceDescriptorSeq::const_iterator q; + for(q = oldIceBox->services.begin(); q != oldIceBox->services.end(); ++q) { - ServiceInstanceDescriptorSeq::const_iterator q; - for(q = newIceBox->services.begin(); q != newIceBox->services.end(); ++q) - { - if(p->descriptor->name == q->descriptor->name) - { - _function(p->descriptor, q->descriptor); - break; - } - } - if(q == newIceBox->services.end()) + if(newService.descriptor->name == q->descriptor->name) { - _function(p->descriptor, 0); + break; } } - for(p = newIceBox->services.begin(); p != newIceBox->services.end(); ++p) + if(q == oldIceBox->services.end()) { - ServiceInstanceDescriptorSeq::const_iterator q; - for(q = oldIceBox->services.begin(); q != oldIceBox->services.end(); ++q) - { - if(p->descriptor->name == q->descriptor->name) - { - break; - } - } - if(q == oldIceBox->services.end()) - { - _function(0, p->descriptor); - } + callback(nullptr, newService.descriptor); } } } - - Function _function; -}; - -template<typename Function> ForEachCommunicator<Function> -inline forEachCommunicator(Function function) -{ - return ForEachCommunicator<Function>(function); -} - -template<class T, class A> -struct ObjFunc : std::unary_function<A, void> -{ - T& _obj; - typedef void (T::*MemberFN)(A); - MemberFN _mfn; - -public: - - explicit ObjFunc(T& obj, void (T::*f)(A)) : _obj(obj), _mfn(f) { } - void operator()(A arg) const - { - (_obj.*_mfn)(arg); - } -}; - -template<class T, class A> ObjFunc<T, A> -inline objFunc(T& obj, void (T::*p)(A)) -{ - return ObjFunc<T, A>(obj, p); } template <class T> std::vector<std::string> diff --git a/cpp/src/IceGrid/WaitQueue.cpp b/cpp/src/IceGrid/WaitQueue.cpp deleted file mode 100644 index 9111fbd9534..00000000000 --- a/cpp/src/IceGrid/WaitQueue.cpp +++ /dev/null @@ -1,175 +0,0 @@ -// -// Copyright (c) ZeroC, Inc. All rights reserved. -// - -#include <Ice/Ice.h> -#include <IceGrid/WaitQueue.h> - -using namespace std; -using namespace IceGrid; - -WaitItem::WaitItem() -{ -} - -WaitItem::~WaitItem() -{ -} - -const IceUtil::Time& -WaitItem:: getExpirationTime() -{ - return _expiration; -} - -void -WaitItem::setExpirationTime(const IceUtil::Time& time) -{ - _expiration = time; -} - -WaitQueue::WaitQueue() : - Thread("IceGrid wait queue thread"), - _destroyed(false) -{ -} - -void -WaitQueue::run() -{ - while(true) - { - list<WaitItemPtr> expired; - { - Lock sync(*this); - if(_waitQueue.empty() && !_destroyed) - { - wait(); - } - - if(_destroyed) - { - break; - } - - // - // Notify expired items. - // - while(!_waitQueue.empty() && !_destroyed) - { - WaitItemPtr item = _waitQueue.front(); - if(item->getExpirationTime() <= IceUtil::Time::now(IceUtil::Time::Monotonic)) - { - expired.push_back(item); - _waitQueue.pop_front(); - } - else if(!expired.empty()) - { - break; - } - else - { - // - // Wait until the next item expire or a notification. Note: in any case we - // get out of this loop to get a chance to execute the work queue. - // - timedWait(item->getExpirationTime() - IceUtil::Time::now(IceUtil::Time::Monotonic)); - } - } - } - - if(!expired.empty()) - { - for(list<WaitItemPtr>::iterator p = expired.begin(); p != expired.end(); ++p) - { - try - { - (*p)->expired(false); - } - catch(const Ice::LocalException&) - { - // - // TODO: Add some tracing. - // - } - } - } - - if(_destroyed) - { - break; - } - } - - if(!_waitQueue.empty()) - { - for(list<WaitItemPtr>::iterator p = _waitQueue.begin(); p != _waitQueue.end(); ++p) - { - (*p)->expired(true); - } - } - _waitQueue.clear(); // Break cyclic reference counts. -} - -void -WaitQueue::destroy() -{ - { - Lock sync(*this); - _destroyed = true; - notify(); - } - - getThreadControl().join(); -} - -void -WaitQueue::add(const WaitItemPtr& item, const IceUtil::Time& wait) -{ - Lock sync(*this); - if(_destroyed) - { - return; - } - - // - // We'll have to notify the thread if it's sleeping for good. - // - bool notifyThread = _waitQueue.empty(); - - IceUtil::Time expire = IceUtil::Time::now(IceUtil::Time::Monotonic) + wait; - item->setExpirationTime(expire); - - list<WaitItemPtr>::iterator p = _waitQueue.begin(); - while(p != _waitQueue.end()) - { - if((*p)->getExpirationTime() >= expire) - { - break; - } - ++p; - } - _waitQueue.insert(p, item); - - if(notifyThread) - { - notify(); - } -} - -bool -WaitQueue::remove(const WaitItemPtr& item) -{ - Lock sync(*this); - list<WaitItemPtr>::iterator p = _waitQueue.begin(); - while(p != _waitQueue.end()) - { - if((*p).get() == item.get()) - { - _waitQueue.erase(p); - return true; - } - ++p; - } - return false; -} diff --git a/cpp/src/IceGrid/WaitQueue.h b/cpp/src/IceGrid/WaitQueue.h deleted file mode 100644 index 84edb2ba79a..00000000000 --- a/cpp/src/IceGrid/WaitQueue.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (c) ZeroC, Inc. All rights reserved. -// - -#ifndef ICE_GRID_WAIT_QUEUE_H -#define ICE_GRID_WAIT_QUEUE_H - -#include <IceUtil/Thread.h> -#include <IceUtil/Monitor.h> - -#include <list> - -namespace IceGrid -{ - -class WaitItem : public virtual IceUtil::Shared -{ -public: - - WaitItem(); - virtual ~WaitItem(); - - virtual void expired(bool) = 0; - - const IceUtil::Time& getExpirationTime(); - void setExpirationTime(const IceUtil::Time&); - -private: - - IceUtil::Time _expiration; -}; - -typedef IceUtil::Handle<WaitItem> WaitItemPtr; - -class WaitQueue : public IceUtil::Thread, public IceUtil::Monitor< IceUtil::Mutex> -{ -public: - - WaitQueue(); - - virtual void run(); - void destroy(); - - void add(const WaitItemPtr&, const IceUtil::Time&); - bool remove(const WaitItemPtr&); - -private: - - std::list<WaitItemPtr> _waitQueue; - bool _destroyed; -}; - -typedef IceUtil::Handle<WaitQueue> WaitQueuePtr; - -} - -#endif diff --git a/cpp/src/IceGrid/WellKnownObjectsManager.cpp b/cpp/src/IceGrid/WellKnownObjectsManager.cpp index f4f7227bcd1..c100b67d7f7 100644 --- a/cpp/src/IceGrid/WellKnownObjectsManager.cpp +++ b/cpp/src/IceGrid/WellKnownObjectsManager.cpp @@ -10,23 +10,21 @@ using namespace std; using namespace IceGrid; -WellKnownObjectsManager::WellKnownObjectsManager(const DatabasePtr& database) : +WellKnownObjectsManager::WellKnownObjectsManager(const shared_ptr<Database>& database) : _database(database), _initialized(false) { } void -WellKnownObjectsManager::add(const Ice::ObjectPrx& proxy, const string& type) +WellKnownObjectsManager::add(const std::shared_ptr<Ice::ObjectPrx>& proxy, const string& type) { assert(!_initialized); - ObjectInfo info; - info.type = type; - info.proxy = proxy; - _wellKnownObjects.push_back(info); + ObjectInfo info = { proxy, type }; + _wellKnownObjects.push_back(move(info)); } void -WellKnownObjectsManager::addEndpoint(const string& name, const Ice::ObjectPrx& proxy) +WellKnownObjectsManager::addEndpoint(const string& name, const std::shared_ptr<Ice::ObjectPrx>& proxy) { _endpoints.insert(make_pair(name, proxy)); } @@ -34,12 +32,12 @@ WellKnownObjectsManager::addEndpoint(const string& name, const Ice::ObjectPrx& p void WellKnownObjectsManager::finish() { - Lock sync(*this); + lock_guard lock(_mutex); _initialized = true; } void -WellKnownObjectsManager::registerAll(const ReplicaSessionPrx& session) +WellKnownObjectsManager::registerAll(const shared_ptr<ReplicaSessionPrx>& session) { if(!initialized()) { @@ -93,9 +91,9 @@ WellKnownObjectsManager::updateReplicatedWellKnownObjects() ObjectInfo info; ObjectInfoSeq objects; - Lock sync(*this); + lock_guard lock(_mutex); - Ice::ObjectPrx replicatedClientProxy = _database->getReplicaCache().getEndpoints("Client", _endpoints["Client"]); + auto replicatedClientProxy = _database->getReplicaCache().getEndpoints("Client", _endpoints["Client"]); id.name = "Query"; info.type = Query::ice_staticId(); @@ -118,41 +116,37 @@ WellKnownObjectsManager::updateReplicatedWellKnownObjects() bool WellKnownObjectsManager::initialized() const { - Lock sync(*this); + lock_guard lock(_mutex); return _initialized; } -Ice::ObjectPrx +std::shared_ptr<Ice::ObjectPrx> WellKnownObjectsManager::getEndpoints(const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); return _endpoints[name]; } -LocatorPrx +shared_ptr<LocatorPrx> WellKnownObjectsManager::getLocator() { - Ice::Identity id; - id.name = "Locator"; - id.category = _database->getInstanceName(); - return LocatorPrx::uncheckedCast(getWellKnownObjectReplicatedProxy(id, "Client")); + Ice::Identity id = { "Locator", _database->getInstanceName() }; + return Ice::uncheckedCast<LocatorPrx>(getWellKnownObjectReplicatedProxy(move(id), "Client")); } -Ice::LocatorRegistryPrx +shared_ptr<Ice::LocatorRegistryPrx> WellKnownObjectsManager::getLocatorRegistry() { - Ice::Identity id; - id.name = "LocatorRegistry"; - id.category = _database->getInstanceName(); - return Ice::LocatorRegistryPrx::uncheckedCast(getWellKnownObjectReplicatedProxy(id, "Server")); + Ice::Identity id = { "LocatorRegistry", _database->getInstanceName() }; + return Ice::uncheckedCast<Ice::LocatorRegistryPrx>(getWellKnownObjectReplicatedProxy(move(id), "Server")); } -Ice::ObjectPrx +std::shared_ptr<Ice::ObjectPrx> WellKnownObjectsManager::getWellKnownObjectReplicatedProxy(const Ice::Identity& id, const string& endpt) { try { - Ice::ObjectPrx proxy = _database->getObjectProxy(id); + auto proxy = _database->getObjectProxy(id); Ice::EndpointSeq registryEndpoints = getEndpoints(endpt)->ice_getEndpoints(); // diff --git a/cpp/src/IceGrid/WellKnownObjectsManager.h b/cpp/src/IceGrid/WellKnownObjectsManager.h index 6f921719e7c..1b286c76a83 100644 --- a/cpp/src/IceGrid/WellKnownObjectsManager.h +++ b/cpp/src/IceGrid/WellKnownObjectsManager.h @@ -12,40 +12,40 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle<Database> DatabasePtr; -class WellKnownObjectsManager : public IceUtil::Mutex, public IceUtil::Shared +class WellKnownObjectsManager { public: - WellKnownObjectsManager(const DatabasePtr&); + WellKnownObjectsManager(const std::shared_ptr<Database>&); - void add(const Ice::ObjectPrx&, const std::string&); - void addEndpoint(const std::string&, const Ice::ObjectPrx&); + void add(const std::shared_ptr<Ice::ObjectPrx>&, const std::string&); + void addEndpoint(const std::string&, const std::shared_ptr<Ice::ObjectPrx>&); void finish(); void registerAll(); - void registerAll(const ReplicaSessionPrx&); + void registerAll(const std::shared_ptr<ReplicaSessionPrx>&); void updateReplicatedWellKnownObjects(); - Ice::ObjectPrx getEndpoints(const std::string&); + std::shared_ptr<Ice::ObjectPrx> getEndpoints(const std::string&); - LocatorPrx getLocator(); - Ice::LocatorRegistryPrx getLocatorRegistry(); + std::shared_ptr<LocatorPrx> getLocator(); + std::shared_ptr<Ice::LocatorRegistryPrx> getLocatorRegistry(); private: bool initialized() const; - Ice::ObjectPrx getWellKnownObjectReplicatedProxy(const Ice::Identity&, const std::string&); + std::shared_ptr<Ice::ObjectPrx> getWellKnownObjectReplicatedProxy(const Ice::Identity&, const std::string&); - const DatabasePtr _database; + const std::shared_ptr<Database> _database; bool _initialized; StringObjectProxyDict _endpoints; ObjectInfoSeq _wellKnownObjects; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle<WellKnownObjectsManager> WellKnownObjectsManagerPtr; }; diff --git a/cpp/src/IceStorm/Admin.cpp b/cpp/src/IceStorm/Admin.cpp index 8307b04eb6a..63a54d1ac9d 100644 --- a/cpp/src/IceStorm/Admin.cpp +++ b/cpp/src/IceStorm/Admin.cpp @@ -15,15 +15,7 @@ using namespace std; using namespace IceInternal; -int run(const Ice::StringSeq&); - -Ice::CommunicatorPtr communicator; - -void -destroyCommunicator(int) -{ - communicator->destroy(); -} +int run(const shared_ptr<Ice::Communicator>&, const Ice::StringSeq&); int #ifdef _WIN32 @@ -41,18 +33,19 @@ main(int argc, char* argv[]) try { - Ice::CtrlCHandler ctrlCHandler; + IceUtil::CtrlCHandler ctrlCHandler; Ice::InitializationData id; Ice::StringSeq args = Ice::argsToStringSeq(argc, argv); id.properties = Ice::createProperties(args); id.properties->setProperty("Ice.Warn.Endpoints", "0"); + Ice::CommunicatorHolder ich(id); - communicator = ich.communicator(); + auto communicator = ich.communicator(); - ctrlCHandler.setCallback(&destroyCommunicator); + ctrlCHandler.setCallback([communicator](int) { communicator->destroy(); }); - status = run(args); + status = run(communicator, args); } catch(const std::exception& ex) { @@ -77,7 +70,7 @@ usage(const string& name) } int -run(const Ice::StringSeq& args) +run(const shared_ptr<Ice::Communicator>& communicator, const Ice::StringSeq& args) { string commands; bool debug; @@ -125,29 +118,28 @@ run(const Ice::StringSeq& args) debug = opts.isSet("debug"); // The complete set of Ice::Identity -> manager proxies. - map<Ice::Identity, IceStorm::TopicManagerPrx> managers; - Ice::PropertiesPtr properties = communicator->getProperties(); - IceStorm::TopicManagerPrx defaultManager; + map<Ice::Identity, shared_ptr<IceStorm::TopicManagerPrx>> managers; + auto properties = communicator->getProperties(); + shared_ptr<IceStorm::TopicManagerPrx> defaultManager; - Ice::PropertyDict props = communicator->getProperties()->getPropertiesForPrefix("IceStormAdmin.TopicManager."); + auto props = communicator->getProperties()->getPropertiesForPrefix("IceStormAdmin.TopicManager."); { - for(Ice::PropertyDict::const_iterator p = props.begin(); p != props.end(); ++p) + for(const auto& p : props) { // // Ignore proxy property settings. eg IceStormAdmin.TopicManager.*.LocatorCacheTimeout // - if(p->first.find('.', strlen("IceStormAdmin.TopicManager.")) == string::npos) + if(p.first.find('.', strlen("IceStormAdmin.TopicManager.")) == string::npos) { try { - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::uncheckedCast( - communicator->propertyToProxy(p->first)); - managers.insert(map<Ice::Identity, IceStorm::TopicManagerPrx>::value_type( - manager->ice_getIdentity(), manager)); + auto manager = Ice::uncheckedCast<IceStorm::TopicManagerPrx>( + communicator->propertyToProxy(p.first)); + managers.insert({manager->ice_getIdentity(), manager}); } catch(const Ice::ProxyParseException&) { - consoleErr << args[0] << ": malformed proxy: " << p->second << endl; + consoleErr << args[0] << ": malformed proxy: " << p.second << endl; return 1; } } @@ -156,8 +148,7 @@ run(const Ice::StringSeq& args) string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(!managerProxy.empty()) { - defaultManager = IceStorm::TopicManagerPrx::uncheckedCast( - communicator->stringToProxy(managerProxy)); + defaultManager = Ice::uncheckedCast<IceStorm::TopicManagerPrx>(communicator->stringToProxy(managerProxy)); } else if(!managers.empty()) { @@ -175,7 +166,7 @@ run(const Ice::StringSeq& args) os << "IceStorm/Finder"; os << ":tcp" << (host.empty() ? "" : (" -h \"" + host + "\"")) << " -p " << port << " -t " << timeout; os << ":ssl" << (host.empty() ? "" : (" -h \"" + host + "\"")) << " -p " << port << " -t " << timeout; - IceStorm::FinderPrx finder = IceStorm::FinderPrx::uncheckedCast(communicator->stringToProxy(os.str())); + auto finder = Ice::uncheckedCast<IceStorm::FinderPrx>(communicator->stringToProxy(os.str())); try { defaultManager = finder->getTopicManager(); @@ -192,12 +183,12 @@ run(const Ice::StringSeq& args) return 1; } - IceStorm::ParserPtr p = IceStorm::Parser::createParser(communicator, defaultManager, managers); + IceStorm::Parser p(communicator, defaultManager, managers); int status = 0; if(!commands.empty()) // Commands were given { - int parseStatus = p->parse(commands, debug); + int parseStatus = p.parse(commands, debug); if(parseStatus == 1) { status = 1; @@ -205,9 +196,9 @@ run(const Ice::StringSeq& args) } else // No commands, let's use standard input { - p->showBanner(); + p.showBanner(); - int parseStatus = p->parse(stdin, debug); + int parseStatus = p.parse(stdin, debug); if(parseStatus == 1) { status = 1; diff --git a/cpp/src/IceStorm/Grammar.cpp b/cpp/src/IceStorm/Grammar.cpp index 0673c7b9e2d..88fc2e3a0d3 100644 --- a/cpp/src/IceStorm/Grammar.cpp +++ b/cpp/src/IceStorm/Grammar.cpp @@ -58,14 +58,10 @@ /* Pull parsers. */ #define YYPULL 1 - - - /* Copy the first part of user declarations. */ /* Line 371 of yacc.c */ #line 1 "src/IceStorm/Grammar.y" - // // Copyright (c) ZeroC, Inc. All rights reserved. // @@ -109,7 +105,6 @@ yyerror(const char* s) parser->error(s); } - /* Line 371 of yacc.c */ #line 112 "src/IceStorm/Grammar.cpp" @@ -162,7 +157,6 @@ extern int yydebug; }; #endif - #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 @@ -170,7 +164,6 @@ typedef int YYSTYPE; # define YYSTYPE_IS_DECLARED 1 #endif - #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); @@ -346,7 +339,6 @@ void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) @@ -628,7 +620,6 @@ static const yytype_uint8 yystos[] = #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab - /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. However, @@ -667,13 +658,11 @@ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 - /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif - /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, YYLEX_PARAM) @@ -706,7 +695,6 @@ do { \ } \ } while (YYID (0)) - /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ @@ -741,7 +729,6 @@ yy_symbol_value_print (yyoutput, yytype, yyvaluep) } } - /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ @@ -798,7 +785,6 @@ do { \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) - /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ @@ -846,7 +832,6 @@ int yydebug; # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ - /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 @@ -863,7 +848,6 @@ int yydebug; # define YYMAXDEPTH 10000 #endif - #if YYERROR_VERBOSE # ifndef yystrlen @@ -1136,9 +1120,6 @@ yydestruct (yymsg, yytype, yyvaluep) } } - - - /*----------. | yyparse. | `----------*/ @@ -1168,7 +1149,6 @@ yyparse () /* The lookahead symbol. */ int yychar; - #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ @@ -1397,7 +1377,6 @@ yybackup: goto yynewstate; - /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ @@ -1407,7 +1386,6 @@ yydefault: goto yyerrlab; goto yyreduce; - /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ @@ -1425,7 +1403,6 @@ yyreduce: GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; - YY_REDUCE_PRINT (yyn); switch (yyn) { @@ -1657,7 +1634,6 @@ yyreduce: } break; - /* Line 1792 of yacc.c */ #line 1660 "src/IceStorm/Grammar.cpp" default: break; @@ -1695,7 +1671,6 @@ yyreduce: goto yynewstate; - /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ @@ -1744,8 +1719,6 @@ yyerrlab: #endif } - - if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an @@ -1769,7 +1742,6 @@ yyerrlab: token. */ goto yyerrlab1; - /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ @@ -1789,7 +1761,6 @@ yyerrorlab: yystate = *yyssp; goto yyerrlab1; - /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ @@ -1814,7 +1785,6 @@ yyerrlab1: if (yyssp == yyss) YYABORT; - yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); @@ -1826,14 +1796,12 @@ yyerrlab1: *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END - /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; - /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ @@ -1889,7 +1857,5 @@ yyreturn: return YYID (yyresult); } - /* Line 2055 of yacc.c */ #line 199 "src/IceStorm/Grammar.y" - diff --git a/cpp/src/IceStorm/Grammar.h b/cpp/src/IceStorm/Grammar.h index 0fa1457e828..55a216cf87c 100644 --- a/cpp/src/IceStorm/Grammar.h +++ b/cpp/src/IceStorm/Grammar.h @@ -61,7 +61,6 @@ extern int yydebug; }; #endif - #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 @@ -69,7 +68,6 @@ typedef int YYSTYPE; # define YYSTYPE_IS_DECLARED 1 #endif - #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); diff --git a/cpp/src/IceStorm/IceStormDB.cpp b/cpp/src/IceStorm/IceStormDB.cpp index ccd7d0e3d7f..55a1d488856 100644 --- a/cpp/src/IceStorm/IceStormDB.cpp +++ b/cpp/src/IceStorm/IceStormDB.cpp @@ -9,20 +9,14 @@ #include <Ice/ConsoleUtil.h> #include <IceDB/IceDB.h> #include <IceStorm/DBTypes.h> + #include <fstream> +#include <iterator> using namespace std; using namespace IceInternal; -int run(const Ice::StringSeq&); - -Ice::CommunicatorPtr communicator; - -void -destroyCommunicator(int) -{ - communicator->destroy(); -} +int run(const shared_ptr<Ice::Communicator>&, const Ice::StringSeq&); int #ifdef _WIN32 @@ -35,13 +29,8 @@ main(int argc, char* argv[]) try { - Ice::CtrlCHandler ctrlCHandler; Ice::CommunicatorHolder ich(argc, argv); - communicator = ich.communicator(); - - ctrlCHandler.setCallback(&destroyCommunicator); - - status = run(Ice::argsToStringSeq(argc, argv)); + status = run(ich.communicator(), Ice::argsToStringSeq(argc, argv)); } catch(const std::exception& ex) { @@ -70,7 +59,7 @@ usage(const string& name) } int -run(const Ice::StringSeq& args) +run(const shared_ptr<Ice::Communicator>& communicator, const Ice::StringSeq& args) { IceUtilInternal::Options opts; opts.addOpt("h", "help"); @@ -144,10 +133,7 @@ run(const Ice::StringSeq& args) { IceStorm::AllData data; - IceDB::IceContext dbContext; - dbContext.communicator = communicator; - dbContext.encoding.major = 1; - dbContext.encoding.minor = 1; + IceDB::IceContext dbContext = { communicator, {1, 1} }; if(import) { @@ -234,14 +220,14 @@ run(const Ice::StringSeq& args) IceDB::Dbi<IceStorm::SubscriberRecordKey, IceStorm::SubscriberRecord, IceDB::IceContext, Ice::OutputStream> subscriberMap(txn, "subscribers", dbContext, MDB_CREATE); - for(IceStorm::SubscriberRecordDict::const_iterator q = data.subscribers.begin(); q != data.subscribers.end(); ++q) + for(const auto& subscriber : data.subscribers) { if(debug) { - consoleOut << " KEY = TOPIC(" << communicator->identityToString(q->first.topic) - << ") ID(" << communicator->identityToString(q->first.id) << ")" << endl; + consoleOut << " KEY = TOPIC(" << communicator->identityToString(subscriber.first.topic) + << ") ID(" << communicator->identityToString(subscriber.first.id) << ")" << endl; } - subscriberMap.put(txn, q->first, q->second); + subscriberMap.put(txn, subscriber.first, subscriber.second); } txn.commit(); diff --git a/cpp/src/IceStorm/IceStormInternal.ice b/cpp/src/IceStorm/IceStormInternal.ice index 302446d7070..e5d5031b93b 100644 --- a/cpp/src/IceStorm/IceStormInternal.ice +++ b/cpp/src/IceStorm/IceStormInternal.ice @@ -22,7 +22,7 @@ module IceStorm * The event data. * **/ -["cpp:class"] struct EventData +struct EventData { /** The operation name. */ string op; @@ -39,7 +39,7 @@ local exception SendQueueSizeMaxReached } /** A sequence of EventData. */ -["cpp:type:std::deque< ::IceStorm::EventDataPtr>"] sequence<EventData> EventDataSeq; +["cpp:type:std::deque<IceStorm::EventData>"] sequence<EventData> EventDataSeq; /** * diff --git a/cpp/src/IceStorm/Instance.cpp b/cpp/src/IceStorm/Instance.cpp index ad22c9151ad..f1b5e764fb0 100644 --- a/cpp/src/IceStorm/Instance.cpp +++ b/cpp/src/IceStorm/Instance.cpp @@ -27,109 +27,64 @@ extern IceDB::IceContext dbContext; void TopicReaper::add(const string& name) { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); _topics.push_back(name); } vector<string> TopicReaper::consumeReapedTopics() { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); vector<string> reaped; reaped.swap(_topics); return reaped; } -PersistentInstance::PersistentInstance( - const string& instanceName, - const string& name, - const Ice::CommunicatorPtr& communicator, - const Ice::ObjectAdapterPtr& publishAdapter, - const Ice::ObjectAdapterPtr& topicAdapter, - const Ice::ObjectAdapterPtr& nodeAdapter, - const NodePrx& nodeProxy) : - Instance(instanceName, name, communicator, publishAdapter, topicAdapter, nodeAdapter, nodeProxy), - _dbLock(communicator->getProperties()->getPropertyWithDefault(name + ".LMDB.Path", name) + "/icedb.lock"), - _dbEnv(communicator->getProperties()->getPropertyWithDefault(name + ".LMDB.Path", name), 2, - IceDB::getMapSize(communicator->getProperties()->getPropertyAsInt(name + ".LMDB.MapSize"))) -{ - try - { - dbContext.communicator = communicator; - dbContext.encoding.minor = 1; - dbContext.encoding.major = 1; - - IceDB::ReadWriteTxn txn(_dbEnv); - - _lluMap = LLUMap(txn, "llu", dbContext, MDB_CREATE); - _subscriberMap = SubscriberMap(txn, "subscribers", dbContext, MDB_CREATE, compareSubscriberRecordKey); - - txn.commit(); - } - catch(...) - { - shutdown(); - destroy(); - - throw; - } -} - -void -PersistentInstance::destroy() -{ - _dbEnv.close(); - dbContext.communicator = 0; - - Instance::destroy(); -} - -Instance::Instance( - const string& instanceName, - const string& name, - const Ice::CommunicatorPtr& communicator, - const Ice::ObjectAdapterPtr& publishAdapter, - const Ice::ObjectAdapterPtr& topicAdapter, - const Ice::ObjectAdapterPtr& nodeAdapter, - const NodePrx& nodeProxy) : +Instance::Instance(const string& instanceName, + const string& name, + shared_ptr<Ice::Communicator> communicator, + shared_ptr<Ice::ObjectAdapter> publishAdapter, + shared_ptr<Ice::ObjectAdapter> topicAdapter, + shared_ptr<Ice::ObjectAdapter> nodeAdapter, + shared_ptr<NodePrx> nodeProxy) : _instanceName(instanceName), _serviceName(name), - _communicator(communicator), - _publishAdapter(publishAdapter), - _topicAdapter(topicAdapter), - _nodeAdapter(nodeAdapter), - _nodeProxy(nodeProxy), - _traceLevels(new TraceLevels(name, communicator->getProperties(), communicator->getLogger())), - _discardInterval(IceUtil::Time::seconds(communicator->getProperties()->getPropertyAsIntWithDefault( - name + ".Discard.Interval", 60))), // default one minute. - _flushInterval(IceUtil::Time::milliSeconds(communicator->getProperties()->getPropertyAsIntWithDefault( - name + ".Flush.Timeout", 1000))), // default one second. + _communicator(move(communicator)), + _publishAdapter(move(publishAdapter)), + _topicAdapter(move(topicAdapter)), + _nodeAdapter(move(nodeAdapter)), + _nodeProxy(move(nodeProxy)), + _traceLevels(make_shared<TraceLevels>(name, _communicator->getProperties(), _communicator->getLogger())), + // default one minute. + _discardInterval(_communicator->getProperties()->getPropertyAsIntWithDefault(name + ".Discard.Interval", 60)), + // default one second. + _flushInterval(_communicator->getProperties()->getPropertyAsIntWithDefault(name + ".Flush.Timeout", 1000)), // default one minute. - _sendTimeout(communicator->getProperties()->getPropertyAsIntWithDefault(name + ".Send.Timeout", 60 * 1000)), - _sendQueueSizeMax(communicator->getProperties()->getPropertyAsIntWithDefault(name + ".Send.QueueSizeMax", -1)), + _sendTimeout(_communicator->getProperties()->getPropertyAsIntWithDefault(name + ".Send.Timeout", 60 * 1000)), + _sendQueueSizeMax(_communicator->getProperties()->getPropertyAsIntWithDefault(name + ".Send.QueueSizeMax", -1)), _sendQueueSizeMaxPolicy(RemoveSubscriber), - _topicReaper(new TopicReaper()) + _topicReaper(make_shared<TopicReaper>()), + _observers(make_shared<Observers>(_traceLevels)) { try { - __setNoDelete(true); - - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = _communicator->getProperties(); if(properties->getProperty(name + ".TopicManager.AdapterId").empty()) { string p = properties->getProperty(name + ".ReplicatedTopicManagerEndpoints"); if(!p.empty()) { - const_cast<Ice::ObjectPrx&>(_topicReplicaProxy) = communicator->stringToProxy("dummy:" + p); + const_cast<shared_ptr<Ice::ObjectPrx>&>(_topicReplicaProxy) = + _communicator->stringToProxy("dummy:" + p); } p = properties->getProperty(name + ".ReplicatedPublishEndpoints"); if(!p.empty()) { - const_cast<Ice::ObjectPrx&>(_publisherReplicaProxy) = communicator->stringToProxy("dummy:" + p); + const_cast<shared_ptr<Ice::ObjectPrx>&>(_publisherReplicaProxy) = + _communicator->stringToProxy("dummy:" + p); } } - _observers = new Observers(this); - _batchFlusher = new IceUtil::Timer(); + _timer = new IceUtil::Timer(); string policy = properties->getProperty(name + ".Send.QueueSizeMaxPolicy"); @@ -151,28 +106,28 @@ Instance::Instance( // If an Ice metrics observer is setup on the communicator, also // enable metrics for IceStorm. // - IceInternal::CommunicatorObserverIPtr o = - IceInternal::CommunicatorObserverIPtr::dynamicCast(communicator->getObserver()); + auto o = dynamic_pointer_cast<IceInternal::CommunicatorObserverI>(_communicator->getObserver()); if(o) { - _observer = new TopicManagerObserverI(o->getFacet()); + _observer = make_shared<TopicManagerObserverI>(o->getFacet()); } } - catch(...) + catch(const std::exception&) { shutdown(); destroy(); - __setNoDelete(false); - throw; } - __setNoDelete(false); +} + +Instance::~Instance() +{ } void -Instance::setNode(const NodeIPtr& node) +Instance::setNode(shared_ptr<NodeI> node) { - _node = node; + _node = move(node); } string @@ -187,109 +142,103 @@ Instance::serviceName() const return _serviceName; } -Ice::CommunicatorPtr +shared_ptr<Ice::Communicator> Instance::communicator() const { return _communicator; } -Ice::PropertiesPtr +shared_ptr<Ice::Properties> Instance::properties() const { return _communicator->getProperties(); } -Ice::ObjectAdapterPtr +shared_ptr<Ice::ObjectAdapter> Instance::publishAdapter() const { return _publishAdapter; } -Ice::ObjectAdapterPtr +shared_ptr<Ice::ObjectAdapter> Instance::topicAdapter() const { return _topicAdapter; } -Ice::ObjectAdapterPtr +shared_ptr<Ice::ObjectAdapter> Instance::nodeAdapter() const { return _nodeAdapter; } -ObserversPtr +shared_ptr<Observers> Instance::observers() const { return _observers; } -NodeIPtr +shared_ptr<NodeI> Instance::node() const { return _node; } -NodePrx +shared_ptr<NodePrx> Instance::nodeProxy() const { return _nodeProxy; } -TraceLevelsPtr +shared_ptr<TraceLevels> Instance::traceLevels() const { return _traceLevels; } IceUtil::TimerPtr -Instance::batchFlusher() const -{ - return _batchFlusher; -} - -IceUtil::TimerPtr Instance::timer() const { return _timer; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> Instance::topicReplicaProxy() const { return _topicReplicaProxy; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> Instance::publisherReplicaProxy() const { return _publisherReplicaProxy; } -IceStorm::Instrumentation::TopicManagerObserverPtr +shared_ptr<IceStorm::Instrumentation::TopicManagerObserver> Instance::observer() const { return _observer; } -IceStorm::TopicReaperPtr +shared_ptr<IceStorm::TopicReaper> Instance::topicReaper() const { return _topicReaper; } -IceUtil::Time +chrono::seconds Instance::discardInterval() const { return _discardInterval; } -IceUtil::Time +chrono::milliseconds Instance::flushInterval() const { return _flushInterval; } -int +chrono::milliseconds Instance::sendTimeout() const { return _sendTimeout; @@ -329,19 +278,58 @@ Instance::shutdown() void Instance::destroy() { - if(_batchFlusher) - { - _batchFlusher->destroy(); - } - // The node instance must be cleared as the node holds the // replica (TopicManager) which holds the instance causing a // cyclic reference. - _node = 0; + _node = nullptr; // // The observer instance must be cleared as it holds the - // TopicManagerImpl which hodlds the instance causing a + // TopicManagerImpl which holds the instance causing a // cyclic reference. // - _observer = 0; + _observer = nullptr; +} + +PersistentInstance::PersistentInstance(const string& instanceName, + const string& name, + shared_ptr<Ice::Communicator> communicator, + shared_ptr<Ice::ObjectAdapter> publishAdapter, + shared_ptr<Ice::ObjectAdapter> topicAdapter, + shared_ptr<Ice::ObjectAdapter> nodeAdapter, + shared_ptr<NodePrx> nodeProxy) : + Instance(instanceName, name, communicator, move(publishAdapter), move(topicAdapter), move(nodeAdapter), + move(nodeProxy)), + _dbLock(communicator->getProperties()->getPropertyWithDefault(name + ".LMDB.Path", name) + "/icedb.lock"), + _dbEnv(communicator->getProperties()->getPropertyWithDefault(name + ".LMDB.Path", name), 2, + IceDB::getMapSize(communicator->getProperties()->getPropertyAsInt(name + ".LMDB.MapSize"))) +{ + try + { + dbContext.communicator = move(communicator); + dbContext.encoding.minor = 1; + dbContext.encoding.major = 1; + + IceDB::ReadWriteTxn txn(_dbEnv); + + _lluMap = LLUMap(txn, "llu", dbContext, MDB_CREATE); + _subscriberMap = SubscriberMap(txn, "subscribers", dbContext, MDB_CREATE, compareSubscriberRecordKey); + + txn.commit(); + } + catch(const std::exception&) + { + shutdown(); + destroy(); + + throw; + } +} + +void +PersistentInstance::destroy() +{ + _dbEnv.close(); + dbContext.communicator = nullptr; + + Instance::destroy(); } diff --git a/cpp/src/IceStorm/Instance.h b/cpp/src/IceStorm/Instance.h index 897ea2eaa55..5f1e1fe1739 100644 --- a/cpp/src/IceStorm/Instance.h +++ b/cpp/src/IceStorm/Instance.h @@ -8,27 +8,15 @@ #include <Ice/CommunicatorF.h> #include <Ice/ObjectAdapterF.h> #include <Ice/PropertiesF.h> -#include <IceUtil/Time.h> #include <IceStorm/Election.h> #include <IceStorm/Instrumentation.h> #include <IceStorm/Util.h> -namespace IceUtil -{ - -class Timer; -typedef IceUtil::Handle<Timer> TimerPtr; - -} - namespace IceStormElection { class Observers; -typedef IceUtil::Handle<Observers> ObserversPtr; - class NodeI; -typedef IceUtil::Handle<NodeI> NodeIPtr; } @@ -36,9 +24,8 @@ namespace IceStorm { class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; -class TopicReaper : public IceUtil::Shared, private IceUtil::Mutex +class TopicReaper { public: @@ -48,10 +35,11 @@ public: private: std::vector<std::string> _topics; + + std::mutex _mutex; }; -typedef IceUtil::Handle<TopicReaper> TopicReaperPtr; -class Instance : public IceUtil::Shared +class Instance { public: @@ -61,32 +49,35 @@ public: DropEvents }; - Instance(const std::string&, const std::string&, const Ice::CommunicatorPtr&, const Ice::ObjectAdapterPtr&, - const Ice::ObjectAdapterPtr&, const Ice::ObjectAdapterPtr& = 0, const IceStormElection::NodePrx& = 0); + Instance(const std::string&, const std::string&, std::shared_ptr<Ice::Communicator>, + std::shared_ptr<Ice::ObjectAdapter>, std::shared_ptr<Ice::ObjectAdapter>, + std::shared_ptr<Ice::ObjectAdapter> = nullptr, + std::shared_ptr<IceStormElection::NodePrx> = nullptr); + + virtual ~Instance(); - void setNode(const IceStormElection::NodeIPtr&); + void setNode(std::shared_ptr<IceStormElection::NodeI>); std::string instanceName() const; std::string serviceName() const; - Ice::CommunicatorPtr communicator() const; - Ice::PropertiesPtr properties() const; - Ice::ObjectAdapterPtr publishAdapter() const; - Ice::ObjectAdapterPtr topicAdapter() const; - Ice::ObjectAdapterPtr nodeAdapter() const; - IceStormElection::ObserversPtr observers() const; - IceStormElection::NodeIPtr node() const; - IceStormElection::NodePrx nodeProxy() const; - TraceLevelsPtr traceLevels() const; - IceUtil::TimerPtr batchFlusher() const; + std::shared_ptr<Ice::Communicator> communicator() const; + std::shared_ptr<Ice::Properties> properties() const; + std::shared_ptr<Ice::ObjectAdapter> publishAdapter() const; + std::shared_ptr<Ice::ObjectAdapter> topicAdapter() const; + std::shared_ptr<Ice::ObjectAdapter> nodeAdapter() const; + std::shared_ptr<IceStormElection::Observers> observers() const; + std::shared_ptr<IceStormElection::NodeI> node() const; + std::shared_ptr<IceStormElection::NodePrx> nodeProxy() const; + std::shared_ptr<TraceLevels> traceLevels() const; IceUtil::TimerPtr timer() const; - Ice::ObjectPrx topicReplicaProxy() const; - Ice::ObjectPrx publisherReplicaProxy() const; - IceStorm::Instrumentation::TopicManagerObserverPtr observer() const; - TopicReaperPtr topicReaper() const; - - IceUtil::Time discardInterval() const; - IceUtil::Time flushInterval() const; - int sendTimeout() const; + std::shared_ptr<Ice::ObjectPrx> topicReplicaProxy() const; + std::shared_ptr<Ice::ObjectPrx> publisherReplicaProxy() const; + std::shared_ptr<IceStorm::Instrumentation::TopicManagerObserver> observer() const; + std::shared_ptr<TopicReaper> topicReaper() const; + + std::chrono::seconds discardInterval() const; + std::chrono::milliseconds flushInterval() const; + std::chrono::milliseconds sendTimeout() const; int sendQueueSizeMax() const; SendQueueSizeMaxPolicy sendQueueSizeMaxPolicy() const; @@ -97,45 +88,45 @@ private: const std::string _instanceName; const std::string _serviceName; - const Ice::CommunicatorPtr _communicator; - const Ice::ObjectAdapterPtr _publishAdapter; - const Ice::ObjectAdapterPtr _topicAdapter; - const Ice::ObjectAdapterPtr _nodeAdapter; - const IceStormElection::NodePrx _nodeProxy; - const TraceLevelsPtr _traceLevels; - const IceUtil::Time _discardInterval; - const IceUtil::Time _flushInterval; - const int _sendTimeout; + const std::shared_ptr<Ice::Communicator> _communicator; + const std::shared_ptr<Ice::ObjectAdapter> _publishAdapter; + const std::shared_ptr<Ice::ObjectAdapter> _topicAdapter; + const std::shared_ptr<Ice::ObjectAdapter> _nodeAdapter; + const std::shared_ptr<IceStormElection::NodePrx> _nodeProxy; + const std::shared_ptr<TraceLevels> _traceLevels; + const std::chrono::seconds _discardInterval; + const std::chrono::milliseconds _flushInterval; + const std::chrono::milliseconds _sendTimeout; const int _sendQueueSizeMax; const SendQueueSizeMaxPolicy _sendQueueSizeMaxPolicy; - const Ice::ObjectPrx _topicReplicaProxy; - const Ice::ObjectPrx _publisherReplicaProxy; - const TopicReaperPtr _topicReaper; - IceStormElection::NodeIPtr _node; - IceStormElection::ObserversPtr _observers; - IceUtil::TimerPtr _batchFlusher; + const std::shared_ptr<Ice::ObjectPrx> _topicReplicaProxy; + const std::shared_ptr<Ice::ObjectPrx> _publisherReplicaProxy; + const std::shared_ptr<TopicReaper> _topicReaper; + std::shared_ptr<IceStormElection::NodeI> _node; + std::shared_ptr<IceStormElection::Observers> _observers; IceUtil::TimerPtr _timer; - IceStorm::Instrumentation::TopicManagerObserverPtr _observer; - + std::shared_ptr<IceStorm::Instrumentation::TopicManagerObserver> _observer; }; -typedef IceUtil::Handle<Instance> InstancePtr; -typedef IceDB::ReadWriteCursor<SubscriberRecordKey, SubscriberRecord, IceDB::IceContext, Ice::OutputStream> - SubscriberMapRWCursor; +using SubscriberMapRWCursor = IceDB::ReadWriteCursor<SubscriberRecordKey, + SubscriberRecord, + IceDB::IceContext, + Ice::OutputStream>; -class PersistentInstance : public Instance +class PersistentInstance final : public Instance { public: - PersistentInstance(const std::string&, const std::string&, const Ice::CommunicatorPtr&, - const Ice::ObjectAdapterPtr&, const Ice::ObjectAdapterPtr&, const Ice::ObjectAdapterPtr& = 0, - const IceStormElection::NodePrx& = 0); + PersistentInstance(const std::string&, const std::string&, std::shared_ptr<Ice::Communicator>, + std::shared_ptr<Ice::ObjectAdapter>, std::shared_ptr<Ice::ObjectAdapter>, + std::shared_ptr<Ice::ObjectAdapter> = nullptr, + std::shared_ptr<IceStormElection::NodePrx> = nullptr); const IceDB::Env& dbEnv() const { return _dbEnv; } LLUMap lluMap() const { return _lluMap; } SubscriberMap subscriberMap() const { return _subscriberMap; } - virtual void destroy(); + void destroy() override; private: @@ -144,7 +135,6 @@ private: LLUMap _lluMap; SubscriberMap _subscriberMap; }; -typedef IceUtil::Handle<PersistentInstance> PersistentInstancePtr; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/InstrumentationI.cpp b/cpp/src/IceStorm/InstrumentationI.cpp index 5675c261122..ca4330917a0 100644 --- a/cpp/src/IceStorm/InstrumentationI.cpp +++ b/cpp/src/IceStorm/InstrumentationI.cpp @@ -77,8 +77,8 @@ public: add("service", &SubscriberHelper::getService); add("identity", &SubscriberHelper::getIdentity); - add("facet", &SubscriberHelper::getProxy, &IceProxy::Ice::Object::ice_getFacet); - add("encoding", &SubscriberHelper::getProxy, &IceProxy::Ice::Object::ice_getEncodingVersion); + add("facet", &SubscriberHelper::getProxy, &Ice::ObjectPrx::ice_getFacet); + add("encoding", &SubscriberHelper::getProxy, &Ice::ObjectPrx::ice_getEncodingVersion); add("mode", &SubscriberHelper::getMode); add("proxy", &SubscriberHelper::getProxy); add("link", &SubscriberHelper::_link); @@ -89,13 +89,13 @@ public: }; static Attributes attributes; - SubscriberHelper(const string& svc, const string& topic, const ::Ice::ObjectPrx& proxy, const IceStorm::QoS& qos, - const IceStorm::TopicPrx& link, SubscriberState state) : - _service(svc), _topic(topic), _proxy(proxy), _qos(qos), _link(link), _state(state) + SubscriberHelper(const string& svc, const string& topic, const shared_ptr<Ice::ObjectPrx>& proxy, + const IceStorm::QoS& qos, shared_ptr<IceStorm::TopicPrx> link, SubscriberState state) : + _service(svc), _topic(topic), _proxy(proxy), _qos(qos), _link(move(link)), _state(state) { } - virtual string operator()(const string& attribute) const + string operator()(const string& attribute) const override { return attributes(this, attribute); } @@ -175,7 +175,7 @@ public: return _id; } - const ::Ice::ObjectPrx& + const shared_ptr<Ice::ObjectPrx>& getProxy() const { return _proxy; @@ -186,11 +186,11 @@ public: { switch(_state) { - case SubscriberStateOnline: + case SubscriberState::SubscriberStateOnline: return "online"; - case SubscriberStateOffline: + case SubscriberState::SubscriberStateOffline: return "offline"; - case SubscriberStateError: + case SubscriberState::SubscriberStateError: return "error"; default: assert(false); @@ -208,9 +208,9 @@ private: const string& _service; const string& _topic; - const ::Ice::ObjectPrx& _proxy; + const shared_ptr<Ice::ObjectPrx>& _proxy; const IceStorm::QoS& _qos; - const IceStorm::TopicPrx _link; + const shared_ptr<IceStorm::TopicPrx> _link; const SubscriberState _state; mutable string _id; }; @@ -240,7 +240,7 @@ struct QueuedUpdate { } - void operator()(const SubscriberMetricsPtr& v) + void operator()(const shared_ptr<SubscriberMetrics>& v) { v->queued += count; } @@ -264,7 +264,7 @@ struct OutstandingUpdate { } - void operator()(const SubscriberMetricsPtr& v) + void operator()(const shared_ptr<SubscriberMetrics>& v) { if(v->queued > 0) { @@ -293,7 +293,7 @@ struct DeliveredUpdate { } - void operator()(const SubscriberMetricsPtr& v) + void operator()(const shared_ptr<SubscriberMetrics>& v) { if(v->outstanding > 0) { @@ -313,7 +313,7 @@ SubscriberObserverI::delivered(int count) forEach(DeliveredUpdate(count)); } -TopicManagerObserverI::TopicManagerObserverI(const IceInternal::MetricsAdminIPtr& metrics) : +TopicManagerObserverI::TopicManagerObserverI(const shared_ptr<IceInternal::MetricsAdminI>& metrics) : _metrics(metrics), _topics(metrics, "Topic"), _subscribers(metrics, "Subscriber") @@ -321,14 +321,14 @@ TopicManagerObserverI::TopicManagerObserverI(const IceInternal::MetricsAdminIPtr } void -TopicManagerObserverI::setObserverUpdater(const ObserverUpdaterPtr& updater) +TopicManagerObserverI::setObserverUpdater(const shared_ptr<ObserverUpdater>& updater) { _topics.setUpdater(newUpdater(updater, &ObserverUpdater::updateTopicObservers)); _subscribers.setUpdater(newUpdater(updater, &ObserverUpdater::updateSubscriberObservers)); } -TopicObserverPtr -TopicManagerObserverI::getTopicObserver(const string& service, const string& topic, const TopicObserverPtr& old) +shared_ptr<TopicObserver> +TopicManagerObserverI::getTopicObserver(const string& service, const string& topic, const shared_ptr<TopicObserver>& old) { if(_topics.isEnabled()) { @@ -338,21 +338,21 @@ TopicManagerObserverI::getTopicObserver(const string& service, const string& top } catch(const exception& ex) { - ::Ice::Error error(_metrics->getLogger()); + Ice::Error error(_metrics->getLogger()); error << "unexpected exception trying to obtain observer:\n" << ex; } } - return 0; + return nullptr; } -SubscriberObserverPtr +shared_ptr<SubscriberObserver> TopicManagerObserverI::getSubscriberObserver(const string& svc, const string& topic, - const ::Ice::ObjectPrx& proxy, + const shared_ptr<Ice::ObjectPrx>& proxy, const IceStorm::QoS& qos, - const IceStorm::TopicPrx& link, + const shared_ptr<IceStorm::TopicPrx>& link, SubscriberState state, - const SubscriberObserverPtr& old) + const shared_ptr<SubscriberObserver>& old) { if(_subscribers.isEnabled()) { @@ -362,9 +362,9 @@ TopicManagerObserverI::getSubscriberObserver(const string& svc, } catch(const exception& ex) { - ::Ice::Error error(_metrics->getLogger()); + Ice::Error error(_metrics->getLogger()); error << "unexpected exception trying to obtain observer:\n" << ex; } } - return 0; + return nullptr; } diff --git a/cpp/src/IceStorm/InstrumentationI.h b/cpp/src/IceStorm/InstrumentationI.h index 9627a72b3c9..c223778d808 100644 --- a/cpp/src/IceStorm/InstrumentationI.h +++ b/cpp/src/IceStorm/InstrumentationI.h @@ -13,54 +13,54 @@ namespace IceStorm { -class TopicObserverI : public IceStorm::Instrumentation::TopicObserver, - public IceMX::ObserverT<IceMX::TopicMetrics> +class TopicObserverI final : public IceStorm::Instrumentation::TopicObserver, + public IceMX::ObserverT<IceMX::TopicMetrics> { public: - virtual void published(); - virtual void forwarded(); + void published() override; + void forwarded() override; }; -class SubscriberObserverI : public IceStorm::Instrumentation::SubscriberObserver, - public IceMX::ObserverT<IceMX::SubscriberMetrics> +class SubscriberObserverI final : public IceStorm::Instrumentation::SubscriberObserver, + public IceMX::ObserverT<IceMX::SubscriberMetrics> { public: - virtual void queued(int); - virtual void outstanding(int); - virtual void delivered(int); + void queued(int) override; + void outstanding(int) override; + void delivered(int) override; }; -class TopicManagerObserverI : public IceStorm::Instrumentation::TopicManagerObserver +class TopicManagerObserverI final : public IceStorm::Instrumentation::TopicManagerObserver { public: - TopicManagerObserverI(const IceInternal::MetricsAdminIPtr&); + TopicManagerObserverI(const std::shared_ptr<IceInternal::MetricsAdminI>&); - virtual void setObserverUpdater(const IceStorm::Instrumentation::ObserverUpdaterPtr&); + void setObserverUpdater(const std::shared_ptr<IceStorm::Instrumentation::ObserverUpdater>&) override; - virtual IceStorm::Instrumentation::TopicObserverPtr getTopicObserver( - const std::string&, const std::string&, const IceStorm::Instrumentation::TopicObserverPtr&); + std::shared_ptr<IceStorm::Instrumentation::TopicObserver> + getTopicObserver(const std::string&, const std::string&, + const std::shared_ptr<IceStorm::Instrumentation::TopicObserver>&) override; - virtual IceStorm::Instrumentation::SubscriberObserverPtr getSubscriberObserver( - const std::string&, - const std::string&, - const Ice::ObjectPrx&, - const IceStorm::QoS&, - const IceStorm::TopicPrx&, - IceStorm::Instrumentation::SubscriberState, - const IceStorm::Instrumentation::SubscriberObserverPtr&); + std::shared_ptr<IceStorm::Instrumentation::SubscriberObserver> + getSubscriberObserver(const std::string &, + const std::string &, + const std::shared_ptr<Ice::ObjectPrx> &, + const IceStorm::QoS &, + const std::shared_ptr<IceStorm::TopicPrx> &, + IceStorm::Instrumentation::SubscriberState, + const std::shared_ptr<IceStorm::Instrumentation::SubscriberObserver>&) override; private: - const IceInternal::MetricsAdminIPtr _metrics; + const std::shared_ptr<IceInternal::MetricsAdminI> _metrics; IceMX::ObserverFactoryT<TopicObserverI> _topics; IceMX::ObserverFactoryT<SubscriberObserverI> _subscribers; }; -typedef IceUtil::Handle<TopicManagerObserverI> TopicManagerObserverIPtr; -}; +} #endif diff --git a/cpp/src/IceStorm/Makefile.mk b/cpp/src/IceStorm/Makefile.mk index 3604e7ffcdb..528e766226e 100644 --- a/cpp/src/IceStorm/Makefile.mk +++ b/cpp/src/IceStorm/Makefile.mk @@ -6,10 +6,10 @@ $(project)_libraries := IceStormService $(project)_programs := icestormadmin icestormdb $(project)_sliceflags := -Isrc --include-dir IceStorm $(project)_generated_includedir := $(project)/generated/IceStorm -$(project)_dependencies := IceStorm Ice +$(project)_dependencies := IceStorm Ice Glacier2 IceStormService_targetdir := $(libdir) -IceStormService_dependencies := IceGrid Glacier2 IceBox IceDB +IceStormService_dependencies := IceGrid IceBox IceDB IceStormService_cppflags := $(if $(lmdb_includedir),-I$(lmdb_includedir)) IceStormService_devinstall := no IceStormService_sources := $(addprefix $(currentdir)/,Instance.cpp \ @@ -45,6 +45,6 @@ icestormadmin_sources := $(addprefix $(currentdir)/,Admin.cpp \ icestormdb_targetdir := $(bindir) icestormdb_dependencies := IceDB icestormdb_cppflags := $(if $(lmdb_includedir),-I$(lmdb_includedir)) -icestormdb_sources := $(addprefix $(currentdir)/,IceStormDB.cpp DBTypes.ice) +icestormdb_sources := $(addprefix $(currentdir)/,IceStormDB.cpp SubscriberRecord.ice DBTypes.ice) projects += $(project) diff --git a/cpp/src/IceStorm/NodeI.cpp b/cpp/src/IceStorm/NodeI.cpp index 48563f2f701..794b04761fb 100644 --- a/cpp/src/IceStorm/NodeI.cpp +++ b/cpp/src/IceStorm/NodeI.cpp @@ -16,11 +16,11 @@ namespace class CheckTask : public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr<NodeI> _node; public: - CheckTask(const NodeIPtr& node) : _node(node) { } + CheckTask(shared_ptr<NodeI> node) : _node(move(node)) { } virtual void runTimerTask() { _node->check(); @@ -29,12 +29,12 @@ public: class MergeTask : public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr<NodeI> _node; const set<int> _s; public: - MergeTask(const NodeIPtr& node, const set<int>& s) : _node(node), _s(s) { } + MergeTask(shared_ptr<NodeI> node, const set<int>& s) : _node(move(node)), _s(s) { } virtual void runTimerTask() { _node->merge(_s); @@ -43,11 +43,11 @@ public: class MergeContinueTask : public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr<NodeI> _node; public: - MergeContinueTask(const NodeIPtr& node) : _node(node) { } + MergeContinueTask(shared_ptr<NodeI> node) : _node(move(node)) { } virtual void runTimerTask() { _node->mergeContinue(); @@ -56,11 +56,11 @@ public: class TimeoutTask: public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr<NodeI> _node; public: - TimeoutTask(const NodeIPtr& node) : _node(node) { } + TimeoutTask(shared_ptr<NodeI> node) : _node(move(node)) { } virtual void runTimerTask() { _node->timeout(); @@ -81,8 +81,8 @@ GroupNodeInfo::GroupNodeInfo(int i) : { } -GroupNodeInfo::GroupNodeInfo(int i, LogUpdate l, const Ice::ObjectPrx& o) : - id(i), llu(l), observer(o) +GroupNodeInfo::GroupNodeInfo(int i, LogUpdate l, shared_ptr<Ice::ObjectPrx> o) : + id(i), llu(l), observer(move(o)) { } @@ -98,34 +98,22 @@ GroupNodeInfo::operator==(const GroupNodeInfo& rhs) const return id == rhs.id; } -// -// COMPILER FIX: Clang using libc++ requires to define operator= -// -#if defined(__clang__) && defined(_LIBCPP_VERSION) -GroupNodeInfo& -GroupNodeInfo::operator=(const GroupNodeInfo& other) - -{ - const_cast<int&>(this->id) = other.id; - const_cast<LogUpdate&>(this->llu) = other.llu; - const_cast<Ice::ObjectPrx&>(this->observer) = other.observer; - return *this; -} -#endif - namespace { -static IceUtil::Time -getTimeout(const string& key, int def, const Ice::PropertiesPtr& properties, const TraceLevelsPtr& traceLevels) +static chrono::seconds +getTimeout(const shared_ptr<Instance> instance, const string& key, int def) { - int t = properties->getPropertyAsIntWithDefault(key, def); - if(t < 0) + auto properties = instance->communicator()->getProperties(); + auto traceLevels = instance->traceLevels(); + + auto t = chrono::seconds(properties->getPropertyAsIntWithDefault(key, def)); + if(t < 0s) { Ice::Warning out(traceLevels->logger); out << traceLevels->electionCat << ": " << key << " < 0; Adjusted to 1"; - t = 1; + t = 1s; } - return IceUtil::Time::seconds(t); + return t; } static string @@ -147,37 +135,31 @@ toString(const set<int>& s) } -NodeI::NodeI(const InstancePtr& instance, - const ReplicaPtr& replica, - const Ice::ObjectPrx& replicaProxy, - int id, const map<int, NodePrx>& nodes) : +NodeI::NodeI(const shared_ptr<Instance>& instance, + shared_ptr<Replica> replica, + shared_ptr<Ice::ObjectPrx> replicaProxy, + int id, const map<int, shared_ptr<NodePrx>>& nodes) : _timer(instance->timer()), _traceLevels(instance->traceLevels()), _observers(instance->observers()), - _replica(replica), - _replicaProxy(replicaProxy), + _replica(move(replica)), + _replicaProxy(move(replicaProxy)), _id(id), _nodes(nodes), - _state(NodeStateInactive), + _masterTimeout(getTimeout(instance, instance->serviceName() + ".Election.MasterTimeout", 10)), + _electionTimeout(getTimeout(instance, instance->serviceName() + ".Election.ElectionTimeout", 10)), + _mergeTimeout(getTimeout(instance, instance->serviceName() + ".Election.ResponseTimeout", 10)), + _state(NodeState::NodeStateInactive), _updateCounter(0), _max(0), _generation(-1), _destroy(false) { - map<int, NodePrx> oneway; - for(map<int, NodePrx>::const_iterator p = _nodes.begin(); p != _nodes.end(); ++p) + for(const auto& node : _nodes) { - oneway[p->first] = NodePrx::uncheckedCast(p->second->ice_oneway()); + auto prx = Ice::uncheckedCast<NodePrx>(node.second->ice_oneway()); + const_cast<map<int, shared_ptr<NodePrx>>& >(_nodesOneway)[node.first] = move(prx); } - const_cast<map<int, NodePrx>& >(_nodesOneway) = oneway; - - Ice::PropertiesPtr properties = instance->communicator()->getProperties(); - const_cast<IceUtil::Time&>(_masterTimeout) = getTimeout( - instance->serviceName() + ".Election.MasterTimeout", 10, properties, _traceLevels); - const_cast<IceUtil::Time&>(_electionTimeout) = getTimeout( - instance->serviceName() + ".Election.ElectionTimeout", 10, properties, _traceLevels); - const_cast<IceUtil::Time&>(_mergeTimeout) = getTimeout( - instance->serviceName() + ".Election.ResponseTimeout", 10, properties, _traceLevels); } void @@ -204,9 +186,9 @@ NodeI::start() // We use this lock to ensure that recovery is called before CheckTask // is scheduled, even if timeout is 0 // - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - _checkTask = new CheckTask(this); + _checkTask = make_shared<CheckTask>(shared_from_this()); _timer->schedule(_checkTask, IceUtil::Time::seconds(static_cast<IceUtil::Int64>(_nodes.size() - static_cast<size_t>(_id)) * 2)); recovery(); @@ -216,17 +198,17 @@ void NodeI::check() { { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); if(_destroy) { return; } assert(!_mergeTask); - if(_state == NodeStateElection || _state == NodeStateReorganization || _coord != _id) + if(_state == NodeState::NodeStateElection || _state == NodeState::NodeStateReorganization || _coord != _id) { assert(_checkTask); - _timer->schedule(_checkTask, _electionTimeout); + _timer->schedule(_checkTask, IceUtil::Time::seconds(_electionTimeout.count())); return; } @@ -236,15 +218,15 @@ NodeI::check() _observers->getReapedSlaves(dead); if(!dead.empty()) { - for(vector<int>::const_iterator p = dead.begin(); p != dead.end(); ++p) + for(const auto& node : dead) { - set<GroupNodeInfo>::iterator q = _up.find(GroupNodeInfo(*p)); + auto q = _up.find(GroupNodeInfo(node)); if(q != _up.end()) { if(_traceLevels->election > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); - out << "node " << _id << ": reaping slave " << *p; + out << "node " << _id << ": reaping slave " << node; } _up.erase(q); } @@ -272,21 +254,21 @@ NodeI::check() // See if other groups exist for possible merge. set<int> tmpset; int max = -1; - for(map<int, NodePrx>::const_iterator p = _nodes.begin(); p != _nodes.end(); ++p) + for(const auto& node : _nodes) { - if(p->first == _id) + if(node.first == _id) { continue; } try { - if(p->second->areYouCoordinator()) + if(node.second->areYouCoordinator()) { - if(p->first > max) + if(node.first > max) { - max = p->first; + max = node.first; } - tmpset.insert(p->first); + tmpset.insert(node.first); } } catch(const Ice::Exception& ex) @@ -294,18 +276,18 @@ NodeI::check() if(_traceLevels->election > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); - out << "node " << _id << ": call on node " << p->first << " failed: " << ex; + out << "node " << _id << ": call on node " << node.first << " failed: " << ex; } } } - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); // If the node state has changed while the mutex has been released // then bail. We don't schedule a re-check since we're either // destroyed in which case we're going to terminate or the end of // the election/reorg will re-schedule the check. - if(_destroy || _state == NodeStateElection || _state == NodeStateReorganization || _coord != _id) + if(_destroy || _state == NodeState::NodeStateElection || _state == NodeState::NodeStateReorganization || _coord != _id) { _checkTask = 0; return; @@ -316,7 +298,7 @@ NodeI::check() if(tmpset.empty()) { assert(_checkTask); - _timer->schedule(_checkTask, _electionTimeout); + _timer->schedule(_checkTask, IceUtil::Time::seconds(_electionTimeout.count())); return; } @@ -329,22 +311,21 @@ NodeI::check() out << "node " << _id << ": highest priority node count: " << max; } - IceUtil::Time delay = IceUtil::Time::seconds(0); + chrono::seconds delay = 0s; if(_id < max) { - // Reschedule timer proportial to p-i. + // Reschedule timer proportional to p-i. delay = _mergeTimeout + _mergeTimeout * (max - _id); if(_traceLevels->election > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); - out << "node " << _id << ": scheduling merge in " << delay.toDuration() - << " seconds"; + out << "node " << _id << ": scheduling merge in " << delay.count() << " seconds"; } } assert(!_mergeTask); - _mergeTask = new MergeTask(this, tmpset); - _timer->schedule(_mergeTask, delay); + _mergeTask = make_shared<MergeTask>(shared_from_this(), tmpset); + _timer->schedule(_mergeTask, IceUtil::Time::seconds(delay.count())); } // Called if the node has not heard from the coordinator in some time. @@ -354,7 +335,7 @@ NodeI::timeout() int myCoord; string myGroup; { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); // If we're destroyed or we are our own coordinator then we're // done. if(_destroy || _coord == _id) @@ -368,7 +349,7 @@ NodeI::timeout() bool failed = false; try { - map<int, NodePrx>::const_iterator p = _nodes.find(myCoord); + auto p = _nodes.find(myCoord); assert(p != _nodes.end()); if(!p->second->areYouThere(myGroup, _id)) { @@ -402,24 +383,26 @@ NodeI::merge(const set<int>& coordinatorSet) set<int> invited; string gp; { - Lock sync(*this); + unique_lock<recursive_mutex> lock(_mutex); + _mergeTask = 0; // If the node is currently in an election, or reorganizing // then we're done. - if(_state == NodeStateElection || _state == NodeStateReorganization) + if(_state == NodeState::NodeStateElection || _state == NodeState::NodeStateReorganization) { return; } // This state change prevents this node from accepting // invitations while the merge is executing. - setState(NodeStateElection); + setState(NodeState::NodeStateElection); // No more replica changes are permitted. while(!_destroy && _updateCounter > 0) { - wait(); + // The recursive mutex (_mutex) must only be locked once by this tread + _condVar.wait(lock); } if(_destroy) { @@ -437,9 +420,9 @@ NodeI::merge(const set<int>& coordinatorSet) // Construct a set of node ids to invite. This is the union of // _up and set of coordinators gathered in the check stage. invited = coordinatorSet; - for(set<GroupNodeInfo>::const_iterator p = _up.begin(); p != _up.end(); ++p) + for(const auto& node : _up) { - invited.insert(p->id); + invited.insert(node.id); } _coord = _id; @@ -462,7 +445,7 @@ NodeI::merge(const set<int>& coordinatorSet) Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); out << "node " << _id << ": inviting node " << *p << " to group " << gp; } - map<int, NodePrx>::const_iterator node = _nodesOneway.find(*p); + auto node = _nodesOneway.find(*p); assert(node != _nodesOneway.end()); node->second->invitation(_id, gp); ++p; @@ -475,7 +458,7 @@ NodeI::merge(const set<int>& coordinatorSet) // Now we wait for responses to our invitation. { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); if(_destroy) { return; @@ -492,17 +475,17 @@ NodeI::merge(const set<int>& coordinatorSet) // Schedule the mergeContinueTask. assert(_mergeContinueTask == 0); - _mergeContinueTask = new MergeContinueTask(this); + _mergeContinueTask = make_shared<MergeContinueTask>(shared_from_this()); // At this point we may have already accepted all of the // invitations, if so then we want to schedule the // mergeContinue immediately. - IceUtil::Time timeout = _mergeTimeout; + chrono::seconds timeout = _mergeTimeout; if(_up.size() == _nodes.size()-1 || _invitesIssued == _invitesAccepted) { - timeout = IceUtil::Time::seconds(0); + timeout = 0s; } - _timer->schedule(_mergeContinueTask, timeout); + _timer->schedule(_mergeContinueTask, IceUtil::Time::seconds(timeout.count())); } } @@ -512,7 +495,7 @@ NodeI::mergeContinue() string gp; set<GroupNodeInfo> tmpSet; { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); if(_destroy) { return; @@ -520,14 +503,14 @@ NodeI::mergeContinue() // Copy variables for thread safety. gp = _group; - tmpSet = _up; + tmpSet = set<GroupNodeInfo>(_up); assert(_mergeContinueTask); _mergeContinueTask = 0; // The node is now reorganizing. - assert(_state == NodeStateElection); - setState(NodeStateReorganization); + assert(_state == NodeState::NodeStateElection); + setState(NodeState::NodeStateReorganization); if(_traceLevels->election > 0) { @@ -562,18 +545,18 @@ NodeI::mergeContinue() // updates. int maxid = -1; LogUpdate maxllu = { -1, 0 }; - for(set<GroupNodeInfo>::const_iterator p = tmpSet.begin(); p != tmpSet.end(); ++p) + for(const auto& n : tmpSet) { if(_traceLevels->election > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); - out << "node id=" << p->id << " llu=" << p->llu.generation << "/" << p->llu.iteration; + out << "node id=" << n.id << " llu=" << n.llu.generation << "/" << n.llu.iteration; } - if(p->llu.generation > maxllu.generation || - (p->llu.generation == maxllu.generation && p->llu.iteration > maxllu.iteration)) + if(n.llu.generation > maxllu.generation || + (n.llu.generation == maxllu.generation && n.llu.iteration > maxllu.iteration)) { - maxid = p->id; - maxllu = p->llu; + maxid = n.id; + maxllu = n.llu; } } @@ -596,7 +579,7 @@ NodeI::mergeContinue() } try { - map<int, NodePrx>::const_iterator node = _nodes.find(maxid); + auto node = _nodes.find(maxid); assert(node != _nodes.end()); _replica->sync(node->second->sync()); } @@ -625,7 +608,7 @@ NodeI::mergeContinue() // state, as such we can set our _max flag. unsigned int max = static_cast<unsigned int>(tmpSet.size()) + 1; { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); if(max > _max) { _max = max; @@ -655,11 +638,11 @@ NodeI::mergeContinue() } // Tell each node to go. - for(set<GroupNodeInfo>::const_iterator p = tmpSet.begin(); p != tmpSet.end(); ++p) + for(const auto& n : tmpSet) { try { - map<int, NodePrx>::const_iterator node = _nodes.find(p->id); + auto node = _nodes.find(n.id); assert(node != _nodes.end()); node->second->ready(_id, gp, _replicaProxy, static_cast<Ice::Int>(max), maxllu.generation); } @@ -668,7 +651,7 @@ NodeI::mergeContinue() if(_traceLevels->election > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); - out << "node " << _id << ": error calling ready on " << p->id << " ex: " << ex; + out << "node " << _id << ": error calling ready on " << n.id << " ex: " << ex; } recovery(); return; @@ -676,7 +659,7 @@ NodeI::mergeContinue() } { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); if(_destroy) { return; @@ -688,19 +671,19 @@ NodeI::mergeContinue() out << "replication commencing with " << _up.size()+1 << "/" << _nodes.size() << " nodes with llu generation: " << maxllu.generation; } - setState(NodeStateNormal); + setState(NodeState::NodeStateNormal); _coordinatorProxy = 0; _generation = maxllu.generation; assert(!_checkTask); - _checkTask = new CheckTask(this); - _timer->schedule(_checkTask, _electionTimeout); + _checkTask = make_shared<CheckTask>(shared_from_this()); + _timer->schedule(_checkTask, IceUtil::Time::seconds(_electionTimeout.count())); } } void -NodeI::invitation(int j, const string& gn, const Ice::Current&) +NodeI::invitation(int j, string gn, const Ice::Current&) { if(_traceLevels->election > 0) { @@ -720,14 +703,14 @@ NodeI::invitation(int j, const string& gn, const Ice::Current&) int max = -1; set<GroupNodeInfo> tmpSet; { - Lock sync(*this); + unique_lock<recursive_mutex> lock(_mutex); if(_destroy) { return; } // If we're in the election or reorg state a merge has already // started, so ignore the invitation. - if(_state == NodeStateElection || _state == NodeStateReorganization) + if(_state == NodeState::NodeStateElection || _state == NodeState::NodeStateReorganization) { if(_traceLevels->election > 0) { @@ -751,18 +734,18 @@ NodeI::invitation(int j, const string& gn, const Ice::Current&) // The merge task is cleared in the merge. This // ensures two invitations cannot cause a race with // the merge. - //_mergeTask = 0; return; } - _mergeTask = 0; + _mergeTask = nullptr; } // We're now joining with another group. If we are active we // must stop serving as a master or slave. - setState(NodeStateElection); + setState(NodeState::NodeStateElection); while(!_destroy && _updateCounter > 0) { - wait(); + // The recursive mutex (_mutex) must only be locked once by this tread + _condVar.wait(lock); } if(_destroy) { @@ -770,7 +753,7 @@ NodeI::invitation(int j, const string& gn, const Ice::Current&) } tmpCoord = _coord; - tmpSet = _up; + tmpSet = set<GroupNodeInfo>(_up); _coord = j; _group = gn; @@ -780,14 +763,14 @@ NodeI::invitation(int j, const string& gn, const Ice::Current&) Ice::IntSeq forwardedInvites; if(tmpCoord == _id) // Forward invitation to my old members. { - for(set<GroupNodeInfo>::const_iterator p = tmpSet.begin(); p != tmpSet.end(); ++p) + for(const auto& n : tmpSet) { try { - map<int, NodePrx>::const_iterator node = _nodesOneway.find(p->id); + auto node = _nodesOneway.find(n.id); assert(node != _nodesOneway.end()); node->second->invitation(j, gn); - forwardedInvites.push_back(p->id); + forwardedInvites.push_back(n.id); } catch(const Ice::Exception&) { @@ -800,23 +783,24 @@ NodeI::invitation(int j, const string& gn, const Ice::Current&) // everything is fine. Setting the state *after* calling accept // can cause a race. { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); if(_destroy) { return; } - assert(_state == NodeStateElection); - setState(NodeStateReorganization); + + assert(_state == NodeState::NodeStateElection); + setState(NodeState::NodeStateReorganization); if(!_timeoutTask) { - _timeoutTask = new TimeoutTask(this); - _timer->scheduleRepeated(_timeoutTask, _masterTimeout); + _timeoutTask = make_shared<TimeoutTask>(shared_from_this()); + _timer->scheduleRepeated(_timeoutTask, IceUtil::Time::seconds(_masterTimeout.count())); } } try { - map<int, NodePrx>::const_iterator node = _nodesOneway.find(j); + auto node = _nodesOneway.find(j); assert(node != _nodesOneway.end()); node->second->accept(_id, gn, forwardedInvites, _replica->getObserver(), _replica->getLastLogUpdate(), max); } @@ -828,11 +812,11 @@ NodeI::invitation(int j, const string& gn, const Ice::Current&) } void -NodeI::ready(int j, const string& gn, const Ice::ObjectPrx& coordinator, int max, Ice::Long generation, +NodeI::ready(int j, string gn, shared_ptr<Ice::ObjectPrx> coordinator, int max, Ice::Long generation, const Ice::Current&) { - Lock sync(*this); - if(!_destroy && _state == NodeStateReorganization && _group == gn) + lock_guard<recursive_mutex> lg(_mutex); + if(!_destroy && _state == NodeState::NodeStateReorganization && _group == gn) { // The coordinator must be j (this was set in the invitation). if(_coord != j) @@ -859,20 +843,20 @@ NodeI::ready(int j, const string& gn, const Ice::ObjectPrx& coordinator, int max // Activate the replica here since the replica is now ready // for duty. - setState(NodeStateNormal); + setState(NodeState::NodeStateNormal); _coordinatorProxy = coordinator; if(!_checkTask) { - _checkTask = new CheckTask(this); - _timer->schedule(_checkTask, _electionTimeout); + _checkTask = make_shared<CheckTask>(shared_from_this()); + _timer->schedule(_checkTask, IceUtil::Time::seconds(_electionTimeout.count())); } } } void -NodeI::accept(int j, const string& gn, const Ice::IntSeq& forwardedInvites, const Ice::ObjectPrx& observer, - const LogUpdate& llu, int max, const Ice::Current&) +NodeI::accept(int j, string gn, Ice::IntSeq forwardedInvites, shared_ptr<Ice::ObjectPrx> observer, LogUpdate llu, + int max, const Ice::Current&) { // Verify that j exists in our node set. if(_nodes.find(j) == _nodes.end()) @@ -882,8 +866,8 @@ NodeI::accept(int j, const string& gn, const Ice::IntSeq& forwardedInvites, cons return; } - Lock sync(*this); - if(!_destroy && _state == NodeStateElection && _group == gn && _coord == _id) + lock_guard<recursive_mutex> lg(_mutex); + if(!_destroy && _state == NodeState::NodeStateElection && _group == gn && _coord == _id) { _up.insert(GroupNodeInfo(j, llu, observer)); @@ -928,7 +912,7 @@ NodeI::accept(int j, const string& gn, const Ice::IntSeq& forwardedInvites, cons // merge continue immediately. Otherwise, we let the existing // merge() schedule continue. if((_up.size() == _nodes.size()-1 || _invitesIssued == _invitesAccepted) && - _mergeContinueTask && _timer->cancel(_mergeContinueTask)) + _mergeContinueTask && _timer->cancel(_mergeContinueTask)) { _timer->schedule(_mergeContinueTask, IceUtil::Time::seconds(0)); } @@ -938,18 +922,18 @@ NodeI::accept(int j, const string& gn, const Ice::IntSeq& forwardedInvites, cons bool NodeI::areYouCoordinator(const Ice::Current&) const { - Lock sync(*this); - return _state != NodeStateElection && _state != NodeStateReorganization && _coord == _id; + lock_guard<recursive_mutex> lg(_mutex); + return _state != NodeState::NodeStateElection && _state != NodeState::NodeStateReorganization && _coord == _id; } bool -NodeI::areYouThere(const string& gn, int j, const Ice::Current&) const +NodeI::areYouThere(string gn, int j, const Ice::Current&) const { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); return _group == gn && _coord == _id && _up.find(GroupNodeInfo(j)) != _up.end(); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> NodeI::sync(const Ice::Current&) const { return _replica->getSync(); @@ -959,12 +943,9 @@ NodeInfoSeq NodeI::nodes(const Ice::Current&) const { NodeInfoSeq seq; - for(map<int, NodePrx>::const_iterator q = _nodes.begin(); q != _nodes.end(); ++q) + for(const auto& n : _nodes) { - NodeInfo ni; - ni.id = q->first; - ni.n = q->second; - seq.push_back(ni); + seq.push_back({ n.first, n.second }); } return seq; @@ -973,21 +954,18 @@ NodeI::nodes(const Ice::Current&) const QueryInfo NodeI::query(const Ice::Current&) const { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); QueryInfo info; info.id = _id; info.coord = _coord; info.group = _group; info.replica = _replicaProxy; info.state = _state; - info.max = static_cast<Ice::Int>(_max); + info.max = static_cast<int>(_max); - for(set<GroupNodeInfo>::const_iterator p = _up.begin(); p != _up.end(); ++p) + for(const auto& gni : _up) { - GroupInfo gi; - gi.id = p->id; - gi.llu = p->llu; - info.up.push_back(gi); + info.up.push_back( { gni.id, gni.llu }); } return info; @@ -996,7 +974,7 @@ NodeI::query(const Ice::Current&) const void NodeI::recovery(Ice::Long generation) { - Lock sync(*this); + unique_lock<recursive_mutex> lock(_mutex); // Ignore the recovery if the node has already advanced a // generation. @@ -1005,10 +983,10 @@ NodeI::recovery(Ice::Long generation) return; } - setState(NodeStateInactive); + setState(NodeState::NodeStateInactive); while(!_destroy && _updateCounter > 0) { - wait(); + _condVar.wait(lock); } if(_destroy) { @@ -1042,23 +1020,23 @@ NodeI::recovery(Ice::Long generation) } if(!_checkTask) { - _checkTask = new CheckTask(this); - _timer->schedule(_checkTask, _electionTimeout); + _checkTask = make_shared<CheckTask>(shared_from_this()); + _timer->schedule(_checkTask, IceUtil::Time::seconds(_electionTimeout.count())); } } void NodeI::destroy() { - Lock sync(*this); + unique_lock<recursive_mutex> lock(_mutex); assert(!_destroy); while(_updateCounter > 0) { - wait(); + _condVar.wait(lock); } _destroy = true; - notifyAll(); + _condVar.notify_all(); // Cancel the timers. if(_checkTask) @@ -1083,10 +1061,10 @@ NodeI::destroy() // A node should only receive an observer init call if the node is // reorganizing and its not the coordinator. void -NodeI::checkObserverInit(Ice::Long /*generation*/) +NodeI::checkObserverInit(Ice::Long) { - Lock sync(*this); - if(_state != NodeStateReorganization) + lock_guard<recursive_mutex> lg(_mutex); + if(_state != NodeState::NodeStateReorganization) { throw ObserverInconsistencyException("init cannot block when state != NodeStateReorganization"); } @@ -1097,23 +1075,21 @@ NodeI::checkObserverInit(Ice::Long /*generation*/) } // Notify the node that we're about to start an update. -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> NodeI::startUpdate(Ice::Long& generation, const char* file, int line) { bool majority = _observers->check(); - Lock sync(*this); + unique_lock<recursive_mutex> lock(_mutex); // If we've actively replicating & lost the majority of our replicas then recover. - if(!_coordinatorProxy && !_destroy && _state == NodeStateNormal && !majority) + if(!_coordinatorProxy && !_destroy && _state == NodeState::NodeStateNormal && !majority) { recovery(); } - while(!_destroy && _state != NodeStateNormal) - { - wait(); - } + _condVar.wait(lock, [this] { return _destroy || _state == NodeState::NodeStateNormal; } ); + if(_destroy) { throw Ice::UnknownException(file, line); @@ -1127,11 +1103,11 @@ NodeI::startUpdate(Ice::Long& generation, const char* file, int line) } bool -NodeI::updateMaster(const char* /*file*/, int /*line*/) +NodeI::updateMaster(const char*, int) { bool majority = _observers->check(); - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); // If the node is destroyed, or is not a coordinator then we're // done. @@ -1141,13 +1117,13 @@ NodeI::updateMaster(const char* /*file*/, int /*line*/) } // If we've lost the majority of our replicas then recover. - if(_state == NodeStateNormal && !majority) + if(_state == NodeState::NodeStateNormal && !majority) { recovery(); } // If we're not replicating then we're done. - if(_state != NodeStateNormal) + if(_state != NodeState::NodeStateNormal) { return false; } @@ -1157,14 +1133,13 @@ NodeI::updateMaster(const char* /*file*/, int /*line*/) return true; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> NodeI::startCachedRead(Ice::Long& generation, const char* file, int line) { - Lock sync(*this); - while(!_destroy && _state != NodeStateNormal) - { - wait(); - } + unique_lock<recursive_mutex> lock(_mutex); + + _condVar.wait(lock, [this] { return _destroy || _state == NodeState::NodeStateNormal; }); + if(_destroy) { throw Ice::UnknownException(file, line); @@ -1177,12 +1152,13 @@ NodeI::startCachedRead(Ice::Long& generation, const char* file, int line) void NodeI::startObserverUpdate(Ice::Long generation, const char* file, int line) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); + if(_destroy) { throw Ice::UnknownException(file, line); } - if(_state != NodeStateNormal) + if(_state != NodeState::NodeStateNormal) { throw ObserverInconsistencyException("update called on inactive node"); } @@ -1200,13 +1176,13 @@ NodeI::startObserverUpdate(Ice::Long generation, const char* file, int line) void NodeI::finishUpdate() { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); assert(!_destroy); --_updateCounter; assert(_updateCounter >= 0); if(_updateCounter == 0) { - notifyAll(); + _condVar.notify_all(); } } @@ -1217,13 +1193,13 @@ stateToString(NodeState s) { switch(s) { - case NodeStateInactive: + case NodeState::NodeStateInactive: return "inactive"; - case NodeStateElection: + case NodeState::NodeStateElection: return "election"; - case NodeStateReorganization: + case NodeState::NodeStateReorganization: return "reorganization"; - case NodeStateNormal: + case NodeState::NodeStateNormal: return "normal"; } return "unknown"; @@ -1241,10 +1217,10 @@ NodeI::setState(NodeState s) out << "node " << _id << ": transition from " << stateToString(_state) << " to " << stateToString(s); } - _state = s; - if(_state == NodeStateNormal) + _state = move(s); + if(_state == NodeState::NodeStateNormal) { - notifyAll(); + _condVar.notify_all(); } } } diff --git a/cpp/src/IceStorm/NodeI.h b/cpp/src/IceStorm/NodeI.h index 5b0ba169def..37a6ce66967 100644 --- a/cpp/src/IceStorm/NodeI.h +++ b/cpp/src/IceStorm/NodeI.h @@ -2,8 +2,8 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#ifndef ELECTION_I_H -#define ELECTION_I_H +#ifndef NODE_I_H +#define NODE_I_H #include <IceUtil/IceUtil.h> #include <Ice/Ice.h> @@ -11,20 +11,21 @@ #include <IceStorm/Replica.h> #include <IceStorm/Instance.h> #include <IceUtil/Timer.h> + #include <set> +#include <condition_variable> namespace IceStormElection { class Observers; -typedef IceUtil::Handle<Observers> ObserversPtr; -class NodeI : public Node, public IceUtil::Monitor<IceUtil::RecMutex> +class NodeI final : public Node, public std::enable_shared_from_this<NodeI> { public: - NodeI(const IceStorm::InstancePtr&, const ReplicaPtr&, const Ice::ObjectPrx&, - int, const std::map<int, NodePrx>&); + NodeI(const std::shared_ptr<IceStorm::Instance>&, std::shared_ptr<Replica>, std::shared_ptr<Ice::ObjectPrx>, + int, const std::map<int, std::shared_ptr<NodePrx>>&); void start(); @@ -32,23 +33,23 @@ public: void timeout(); void merge(const std::set<int>&); void mergeContinue(); - virtual void invitation(int, const std::string&, const Ice::Current&); - virtual void ready(int, const std::string&, const Ice::ObjectPrx&, int, Ice::Long, const Ice::Current&); - virtual void accept(int, const std::string&, const Ice::IntSeq&, const Ice::ObjectPrx&, const LogUpdate&, int, - const Ice::Current&); - virtual bool areYouCoordinator(const Ice::Current&) const; - virtual bool areYouThere(const std::string&, int, const Ice::Current&) const; - virtual Ice::ObjectPrx sync(const Ice::Current&) const; - virtual NodeInfoSeq nodes(const Ice::Current&) const; - virtual QueryInfo query(const Ice::Current&) const; + void invitation(int, std::string, const Ice::Current&) override; + void ready(int, std::string, std::shared_ptr<Ice::ObjectPrx>, int, Ice::Long, const Ice::Current&) override; + void accept(int, std::string, Ice::IntSeq, std::shared_ptr<Ice::ObjectPrx>, LogUpdate, int, + const Ice::Current&) override; + bool areYouCoordinator(const Ice::Current&) const override; + bool areYouThere(std::string, int, const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> sync(const Ice::Current&) const override; + NodeInfoSeq nodes(const Ice::Current&) const override; + QueryInfo query(const Ice::Current&) const override; void recovery(Ice::Long = -1); void destroy(); // Notify the node that we're about to start an update. void checkObserverInit(Ice::Long); - Ice::ObjectPrx startUpdate(Ice::Long&, const char*, int); - Ice::ObjectPrx startCachedRead(Ice::Long&, const char*, int); + std::shared_ptr<Ice::ObjectPrx> startUpdate(Ice::Long&, const char*, int); + std::shared_ptr<Ice::ObjectPrx> startCachedRead(Ice::Long&, const char*, int); void startObserverUpdate(Ice::Long, const char*, int); bool updateMaster(const char*, int); @@ -60,18 +61,18 @@ private: void setState(NodeState); const IceUtil::TimerPtr _timer; - const IceStorm::TraceLevelsPtr _traceLevels; - const IceStormElection::ObserversPtr _observers; - const ReplicaPtr _replica; // The replica. - const Ice::ObjectPrx _replicaProxy; // A proxy to the individual replica. + const std::shared_ptr<IceStorm::TraceLevels> _traceLevels; + const std::shared_ptr<IceStormElection::Observers> _observers; + const std::shared_ptr<Replica> _replica; // The replica. + const std::shared_ptr<Ice::ObjectPrx> _replicaProxy; // A proxy to the individual replica. const int _id; // My node id. - const std::map<int, NodePrx> _nodes; // The nodes indexed by their id. - const std::map<int, NodePrx> _nodesOneway; // The nodes indexed by their id (as oneway proxies). + const std::map<int, std::shared_ptr<NodePrx>> _nodes; // The nodes indexed by their id. + const std::map<int, std::shared_ptr<NodePrx>> _nodesOneway; // The nodes indexed by their id (as oneway proxies). - const IceUtil::Time _masterTimeout; - const IceUtil::Time _electionTimeout; - const IceUtil::Time _mergeTimeout; + const std::chrono::seconds _masterTimeout; + const std::chrono::seconds _electionTimeout; + const std::chrono::seconds _mergeTimeout; NodeState _state; int _updateCounter; @@ -86,23 +87,24 @@ private: unsigned int _max; // The highest group count I've seen. Ice::Long _generation; // The current generation (or -1 if not set). - Ice::ObjectPrx _coordinatorProxy; + std::shared_ptr<Ice::ObjectPrx> _coordinatorProxy; bool _destroy; - // Various timers. IceUtil::TimerTaskPtr _mergeTask; IceUtil::TimerTaskPtr _timeoutTask; IceUtil::TimerTaskPtr _checkTask; IceUtil::TimerTaskPtr _mergeContinueTask; + + mutable std::recursive_mutex _mutex; + std::condition_variable_any _condVar; }; -typedef IceUtil::Handle<NodeI> NodeIPtr; class FinishUpdateHelper { public: - FinishUpdateHelper(const NodeIPtr& node) : - _node(node) + FinishUpdateHelper(std::shared_ptr<NodeI> node) : + _node(std::move(node)) { } @@ -116,15 +118,15 @@ public: private: - const NodeIPtr _node; + const std::shared_ptr<NodeI> _node; }; class CachedReadHelper { public: - CachedReadHelper(const NodeIPtr& node, const char* file, int line) : - _node(node) + CachedReadHelper(std::shared_ptr<NodeI> node, const char* file, int line) : + _node(std::move(node)) { if(_node) { @@ -140,7 +142,7 @@ public: } } - Ice::ObjectPrx + std::shared_ptr<Ice::ObjectPrx> getMaster() const { return _master; @@ -160,8 +162,8 @@ public: private: - const NodeIPtr _node; - Ice::ObjectPrx _master; + const std::shared_ptr<NodeI> _node; + std::shared_ptr<Ice::ObjectPrx> _master; Ice::Long _generation; }; @@ -169,8 +171,8 @@ class ObserverUpdateHelper { public: - ObserverUpdateHelper(const NodeIPtr& node, Ice::Long generation, const char* file, int line) : - _node(node) + ObserverUpdateHelper(std::shared_ptr<NodeI> node, Ice::Long generation, const char* file, int line) : + _node(std::move(node)) { if(_node) { @@ -188,9 +190,9 @@ public: private: - const NodeIPtr _node; + const std::shared_ptr<NodeI> _node; }; } -#endif // ELECTION_I_H +#endif // NODE_I_H diff --git a/cpp/src/IceStorm/Observers.cpp b/cpp/src/IceStorm/Observers.cpp index b38a2db5da5..f714477b82c 100644 --- a/cpp/src/IceStorm/Observers.cpp +++ b/cpp/src/IceStorm/Observers.cpp @@ -10,8 +10,8 @@ using namespace std; using namespace IceStorm; using namespace IceStormElection; -Observers::Observers(const InstancePtr& instance) : - _traceLevels(instance->traceLevels()), +Observers::Observers(shared_ptr<TraceLevels> traceLevels) : + _traceLevels(move(traceLevels)), _majority(0) { } @@ -25,10 +25,11 @@ Observers::setMajority(unsigned int majority) bool Observers::check() { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); + if(_observers.size() >= _majority) { - vector<ObserverInfo>::iterator p = _observers.begin(); + auto p = _observers.begin(); while(p != _observers.end()) { try @@ -45,11 +46,8 @@ Observers::check() int id = p->id; p = _observers.erase(p); - // COMPILERFIX: Just using following causes double unlock with C++Builder 2007 - //IceUtil::Mutex::Lock sync(_reapedMutex); - _reapedMutex.lock(); + lock_guard<mutex> reapedLock(_reapedMutex); _reaped.push_back(id); - _reapedMutex.unlock(); continue; } ++p; @@ -61,14 +59,14 @@ Observers::check() void Observers::clear() { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); _observers.clear(); } void Observers::getReapedSlaves(std::vector<int>& d) { - IceUtil::Mutex::Lock sync(_reapedMutex); + lock_guard<mutex> reapedLock(_reapedMutex); d.swap(_reaped); } @@ -76,65 +74,64 @@ void Observers::init(const set<GroupNodeInfo>& slaves, const LogUpdate& llu, const TopicContentSeq& content) { { - IceUtil::Mutex::Lock sync(_reapedMutex); + lock_guard<mutex> reapedLock(_reapedMutex); _reaped.clear(); } - Lock sync(*this); + lock_guard<mutex> lg(_mutex); _observers.clear(); vector<ObserverInfo> observers; - for(set<GroupNodeInfo>::const_iterator p = slaves.begin(); p != slaves.end(); ++p) + for(const auto& slave : slaves) { try { - assert(p->observer); + assert(slave.observer); + + auto observer = Ice::uncheckedCast<ReplicaObserverPrx>(slave.observer); - ReplicaObserverPrx observer = ReplicaObserverPrx::uncheckedCast(p->observer); + auto future = observer->initAsync(llu, content); - Ice::AsyncResultPtr result = observer->begin_init(llu, content); - observers.push_back(ObserverInfo(p->id, observer, result)); + observers.push_back({ slave.id, observer, move(future) }); } catch(const Ice::Exception& ex) { if(_traceLevels->replication > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->replicationCat); - out << "error calling init on " << p->id << ", exception: " << ex; + out << "error calling init on " << slave.id << ", exception: " << ex; } throw; } } - for(vector<ObserverInfo>::iterator p = observers.begin(); p != observers.end(); ++p) + for(auto& o : observers) { try { - p->observer->end_init(p->result); - p->result = 0; + o.future.get(); } catch(const Ice::Exception& ex) { if(_traceLevels->replication > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->replicationCat); - out << "init on " << p->id << " failed with exception " << ex; + out << "init on " << o.id << " failed with exception " << ex; } throw; } } - - _observers.swap(observers); + _observers = move(observers); } void Observers::createTopic(const LogUpdate& llu, const string& name) { - Lock sync(*this); - for(vector<ObserverInfo>::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard<mutex> lg(_mutex); + for(auto& o : _observers) { - p->result = p->observer->begin_createTopic(llu, name); + o.future = o.observer->createTopicAsync(llu, name); } wait("createTopic"); } @@ -142,10 +139,10 @@ Observers::createTopic(const LogUpdate& llu, const string& name) void Observers::destroyTopic(const LogUpdate& llu, const string& id) { - Lock sync(*this); - for(vector<ObserverInfo>::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard<mutex> lg(_mutex); + for(auto& o : _observers) { - p->result = p->observer->begin_destroyTopic(llu, id); + o.future = o.observer->destroyTopicAsync(llu, id); } wait("destroyTopic"); } @@ -153,10 +150,10 @@ Observers::destroyTopic(const LogUpdate& llu, const string& id) void Observers::addSubscriber(const LogUpdate& llu, const string& name, const SubscriberRecord& rec) { - Lock sync(*this); - for(vector<ObserverInfo>::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard<mutex> lg(_mutex); + for(auto& o : _observers) { - p->result = p->observer->begin_addSubscriber(llu, name, rec); + o.future = o.observer->addSubscriberAsync(llu, name, rec); } wait("addSubscriber"); } @@ -164,10 +161,10 @@ Observers::addSubscriber(const LogUpdate& llu, const string& name, const Subscri void Observers::removeSubscriber(const LogUpdate& llu, const string& name, const Ice::IdentitySeq& id) { - Lock sync(*this); - for(vector<ObserverInfo>::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard<mutex> lg(_mutex); + for(auto& o : _observers) { - p->result = p->observer->begin_removeSubscriber(llu, name, id); + o.future = o.observer->removeSubscriberAsync(llu, name, id); } wait("removeSubscriber"); } @@ -180,8 +177,7 @@ Observers::wait(const string& op) { try { - p->result->waitForCompleted(); - p->result->throwLocalException(); + p->future.get(); } catch(const Ice::Exception& ex) { @@ -193,18 +189,18 @@ Observers::wait(const string& op) int id = p->id; p = _observers.erase(p); - IceUtil::Mutex::Lock sync(_reapedMutex); + lock_guard<mutex> reapedLock(_mutex); _reaped.push_back(id); continue; } ++p; } + // If we now no longer have the majority of observers we raise. if(_observers.size() < _majority) { - // TODO: Trace here? - //Ice::Trace out(_traceLevels->logger, _traceLevels->replicationCat); - //out << op; + Ice::Trace out(_traceLevels->logger, _traceLevels->replicationCat); + out << "number of observers `" << _observers.size() << "' is less than the majority '" << _majority << "'"; throw Ice::UnknownException(__FILE__, __LINE__); } } diff --git a/cpp/src/IceStorm/Observers.h b/cpp/src/IceStorm/Observers.h index 89b26217b73..ed7a6d535fa 100644 --- a/cpp/src/IceStorm/Observers.h +++ b/cpp/src/IceStorm/Observers.h @@ -10,25 +10,18 @@ #include <IceStorm/Election.h> #include <IceStorm/Replica.h> -#ifdef __SUNPRO_CC -# pragma error_messages(off,hidef) -#endif - namespace IceStorm { -class Instance; -typedef IceUtil::Handle<Instance> InstancePtr; class TraceLevels; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; } namespace IceStormElection { -class Observers : public IceUtil::Shared, public IceUtil::Mutex +class Observers { public: - Observers(const IceStorm::InstancePtr&); + Observers(std::shared_ptr<IceStorm::TraceLevels>); void setMajority(unsigned int); @@ -47,26 +40,22 @@ private: void wait(const std::string&); - const IceStorm::TraceLevelsPtr _traceLevels; + const std::shared_ptr<IceStorm::TraceLevels> _traceLevels; unsigned int _majority; struct ObserverInfo { - ObserverInfo(int i, const ReplicaObserverPrx& o, const Ice::AsyncResultPtr& r = 0) : - id(i), observer(o), result (r) {} int id; - ReplicaObserverPrx observer; - ::Ice::AsyncResultPtr result; + std::shared_ptr<ReplicaObserverPrx> observer; + std::future<void> future; }; std::vector<ObserverInfo> _observers; - IceUtil::Mutex _reapedMutex; + + std::mutex _reapedMutex; std::vector<int> _reaped; + + std::mutex _mutex; }; -typedef IceUtil::Handle<Observers> ObserversPtr; } -#ifdef __SUNPRO_CC -# pragma error_messages(default,hidef) -#endif - #endif // OBSERVERS_H diff --git a/cpp/src/IceStorm/Parser.cpp b/cpp/src/IceStorm/Parser.cpp index 0629ca0e393..faa857157e0 100644 --- a/cpp/src/IceStorm/Parser.cpp +++ b/cpp/src/IceStorm/Parser.cpp @@ -9,8 +9,9 @@ #include <IceStorm/IceStormInternal.h> #include <algorithm> -#if defined(__APPLE__) || defined(__linux__) -# include <editline/readline.h> +#ifdef HAVE_READLINE +# include <readline/readline.h> +# include <readline/history.h> #endif extern FILE* yyin; @@ -29,7 +30,7 @@ namespace IceStorm Parser* parser; #ifdef _WIN32 -Ice::StringConverterPtr windowsConsoleConverter = 0; +shared_ptr<Ice::StringConverter> windowsConsoleConverter = nullptr; #endif } @@ -37,51 +38,37 @@ Ice::StringConverterPtr windowsConsoleConverter = 0; namespace { -class UnknownManagerException : public Exception +class UnknownManagerException : public std::exception { public: - UnknownManagerException(const string& nameP, const char* file, int line) : - Exception(file, line), - name(nameP) + explicit UnknownManagerException(const std::string& name) : _name(name) { } -#ifndef ICE_CPP11_COMPILER - virtual - ~UnknownManagerException() throw() + const char* what() const noexcept override { - } -#endif - - virtual string - ice_id() const - { - return "::UnknownManagerException"; - } - - virtual Exception* - ice_clone() const - { - return new UnknownManagerException(*this); - } - - virtual void - ice_throw() const - { - throw *this; + return _name.c_str(); } - const string name; +private: + const string _name; }; } -ParserPtr -Parser::createParser(const CommunicatorPtr& communicator, const TopicManagerPrx& admin, - const map<Ice::Identity, TopicManagerPrx>& managers) +Parser::Parser(shared_ptr<Communicator> communicator, shared_ptr<TopicManagerPrx> admin, + map<Ice::Identity, shared_ptr<TopicManagerPrx>> managers) : + _communicator(move(communicator)), + _defaultManager(move(admin)), + _managers(move(managers)) { - return new Parser(communicator, admin, managers); +#ifdef _WIN32 + if(!windowsConsoleConverter) + { + windowsConsoleConverter = Ice::createWindowsStringConverter(GetConsoleOutputCP()); + } +#endif } void @@ -114,17 +101,17 @@ Parser::create(const list<string>& args) return; } - for(list<string>::const_iterator i = args.begin(); i != args.end() ; ++i) + for(const auto& arg : args) { try { string topicName; - TopicManagerPrx manager = findManagerById(*i, topicName); + auto manager = findManagerById(arg, topicName); manager->create(topicName); } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - exception(ex, args.size() > 1); // Print a warning if we're creating multiple topics, an error otherwise. + exception(current_exception(), args.size() > 1); // Print a warning if we're creating multiple topics, an error otherwise. } } } @@ -138,15 +125,15 @@ Parser::destroy(const list<string>& args) return; } - for(list<string>::const_iterator i = args.begin(); i != args.end() ; ++i) + for(const auto& arg : args) { try { - findTopic(*i)->destroy(); + findTopic(arg)->destroy(); } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - exception(ex, args.size() > 1); // Print a warning if we're destroying multiple topics, an error otherwise. + exception(current_exception(), args.size() > 1); // Print a warning if we're destroying multiple topics, an error otherwise. } } } @@ -164,15 +151,15 @@ Parser::link(const list<string>& args) { list<string>::const_iterator p = args.begin(); - TopicPrx fromTopic = findTopic(*p++); - TopicPrx toTopic = findTopic(*p++); - Ice::Int cost = p != args.end() ? atoi(p->c_str()) : 0; + auto fromTopic = findTopic(*p++); + auto toTopic = findTopic(*p++); + auto cost = p != args.end() ? atoi(p->c_str()) : 0; fromTopic->link(toTopic, cost); } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -189,14 +176,14 @@ Parser::unlink(const list<string>& args) { list<string>::const_iterator p = args.begin(); - TopicPrx fromTopic = findTopic(*p++); - TopicPrx toTopic = findTopic(*p++); + auto fromTopic = findTopic(*p++); + auto toTopic = findTopic(*p++); fromTopic->unlink(toTopic); } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -211,7 +198,7 @@ Parser::links(const list<string>& args) try { - TopicManagerPrx manager; + shared_ptr<TopicManagerPrx> manager; if(args.size() == 0) { manager = _defaultManager; @@ -221,19 +208,17 @@ Parser::links(const list<string>& args) manager = findManagerByCategory(args.front()); } - TopicDict d = manager->retrieveAll(); - for(TopicDict::iterator i = d.begin(); i != d.end(); ++i) + for(const auto& topic : manager->retrieveAll()) { - LinkInfoSeq links = i->second->getLinkInfoSeq(); - for(LinkInfoSeq::const_iterator p = links.begin(); p != links.end(); ++p) + for(const auto& linkInfo : topic.second->getLinkInfoSeq()) { - consoleOut << i->first << " to " << p->name << " with cost " << p->cost << endl; + consoleOut << topic.first << " to " << linkInfo.name << " with cost " << linkInfo.cost << endl; } } } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -248,7 +233,7 @@ Parser::topics(const list<string>& args) try { - TopicManagerPrx manager; + shared_ptr<TopicManagerPrx> manager; if(args.size() == 0) { manager = _defaultManager; @@ -258,15 +243,14 @@ Parser::topics(const list<string>& args) manager = findManagerByCategory(args.front()); } - TopicDict d = manager->retrieveAll(); - for(TopicDict::iterator i = d.begin(); i != d.end(); ++i) + for(const auto& topic : manager->retrieveAll()) { - consoleOut << i->first << endl; + consoleOut << topic.first << endl; } } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -281,7 +265,7 @@ Parser::replica(const list<string>& args) try { - TopicManagerPrx m; + shared_ptr<TopicManagerPrx> m; if(args.size() == 0) { m = _defaultManager; @@ -290,63 +274,63 @@ Parser::replica(const list<string>& args) { m = findManagerByCategory(args.front()); } - TopicManagerInternalPrx manager = TopicManagerInternalPrx::uncheckedCast(m); - IceStormElection::NodePrx node = manager->getReplicaNode(); + auto manager = Ice::uncheckedCast<TopicManagerInternalPrx>(m); + auto node = manager->getReplicaNode(); if(!node) { error("This topic is not replicated"); } - IceStormElection::NodeInfoSeq nodes = node->nodes(); + auto nodes = node->nodes(); consoleOut << "replica count: " << nodes.size() << endl; - for(IceStormElection::NodeInfoSeq::const_iterator p = nodes.begin(); p != nodes.end(); ++p) + for(const auto& n : nodes) { try { - IceStormElection::QueryInfo info = p->n->query(); - consoleOut << p->id << ": id: " << info.id << endl; - consoleOut << p->id << ": coord: " << info.coord << endl; - consoleOut << p->id << ": group name: " << info.group << endl; - consoleOut << p->id << ": state: "; + auto info = n.n->query(); + consoleOut << n.id << ": id: " << info.id << endl; + consoleOut << n.id << ": coord: " << info.coord << endl; + consoleOut << n.id << ": group name: " << info.group << endl; + consoleOut << n.id << ": state: "; switch(info.state) { - case IceStormElection::NodeStateInactive: + case IceStormElection::NodeState::NodeStateInactive: consoleOut << "inactive"; break; - case IceStormElection::NodeStateElection: + case IceStormElection::NodeState::NodeStateElection: consoleOut << "election"; break; - case IceStormElection::NodeStateReorganization: + case IceStormElection::NodeState::NodeStateReorganization: consoleOut << "reorganization"; break; - case IceStormElection::NodeStateNormal: + case IceStormElection::NodeState::NodeStateNormal: consoleOut << "normal"; break; default: consoleOut << "unknown"; } consoleOut << endl; - consoleOut << p->id << ": group: "; - for(IceStormElection::GroupInfoSeq::const_iterator q = info.up.begin(); q != info.up.end(); ++q) + consoleOut << n.id << ": group: "; + for(auto q = info.up.cbegin(); q != info.up.cend(); ++q) { - if(q != info.up.begin()) + if(q != info.up.cbegin()) { consoleOut << ","; } consoleOut << q->id; } consoleOut << endl; - consoleOut << p->id << ": max: " << info.max + consoleOut << n.id << ": max: " << info.max << endl; } catch(const Exception& ex) { - consoleOut << p->id << ": " << ex.ice_id() << endl; + consoleOut << n.id << ": " << ex.ice_id() << endl; } } } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -360,20 +344,19 @@ Parser::subscribers(const list<string>& args) } try { - for(list<string>::const_iterator i = args.begin(); i != args.end() ; ++i) + for(const auto& arg : args) { - TopicPrx topic = _defaultManager->retrieve(*i); - consoleOut << (*i) << ": subscribers:" << endl; - IdentitySeq subscribers = topic->getSubscribers(); - for(IdentitySeq::const_iterator j = subscribers.begin(); j != subscribers.end(); ++j) + auto topic = _defaultManager->retrieve(arg); + consoleOut << arg << ": subscribers:" << endl; + for(const auto& subscriber : topic->getSubscribers()) { - consoleOut << "\t" << _communicator->identityToString(*j) << endl; + consoleOut << "\t" << _communicator->identityToString(subscriber) << endl; } } } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -393,13 +376,13 @@ Parser::current(const list<string>& args) try { - TopicManagerPrx manager = findManagerByCategory(args.front()); + auto manager = findManagerByCategory(args.front()); manager->ice_ping(); _defaultManager = manager; } - catch(const Exception& ex) + catch(const std::exception&) { - exception(ex); + exception(current_exception()); } } @@ -444,80 +427,77 @@ Parser::getInput(char* buf, size_t& result, size_t maxSize) } else { -#if defined(__APPLE__) || defined(__linux__) - if (isatty(fileno(stdin)) == 1) +#ifdef HAVE_READLINE + + const char* prompt = parser->getPrompt(); + char* line = readline(const_cast<char*>(prompt)); + if(!line) + { + result = 0; + } + else { - const char* prompt = parser->getPrompt(); - char* line = readline(const_cast<char*>(prompt)); - if(!line) + if(*line) + { + add_history(line); + } + + result = strlen(line) + 1; + if(result > maxSize) { + free(line); + error("input line too long"); result = 0; } else { - if(*line) - { - add_history(line); - } - - result = strlen(line) + 1; - if(result > maxSize) - { - free(line); - error("input line too long"); - result = 0; - } - else - { - strcpy(buf, line); - strcat(buf, "\n"); - free(line); - } + strcpy(buf, line); + strcat(buf, "\n"); + free(line); } } - else - { -#endif - consoleOut << parser->getPrompt() << flush; - string line; - while(true) - { - int c = getc(yyin); - if(c == EOF) - { - if(line.size()) - { - line += '\n'; - } - break; - } +#else + + consoleOut << parser->getPrompt() << flush; - line += static_cast<char>(c); - if(c == '\n') + string line; + while(true) + { + int c = getc(yyin); + if(c == EOF) + { + if(line.size()) { - break; + line += '\n'; } + break; } -#ifdef _WIN32 - if(windowsConsoleConverter) + + line += static_cast<char>(c); + if(c == '\n') { - line = nativeToUTF8(line, windowsConsoleConverter); + break; } + } +#ifdef _WIN32 + if(windowsConsoleConverter) + { + line = nativeToUTF8(line, windowsConsoleConverter); + } #endif - result = line.length(); - if(result > maxSize) - { - error("input line too long"); - buf[0] = EOF; - result = 1; - } - else - { - strcpy(buf, line.c_str()); - } -#if defined(__APPLE__) || defined(__linux__) + result = line.length(); + if(result > maxSize) + { + error("input line too long"); + buf[0] = EOF; + result = 1; + } + else + { + strcpy(buf, line.c_str()); } + #endif } } @@ -625,67 +605,51 @@ Parser::parse(const std::string& commands, bool debug) return status; } -TopicManagerPrx +shared_ptr<TopicManagerPrx> Parser::findManagerById(const string& full, string& arg) const { - Ice::Identity id = Ice::stringToIdentity(full); + auto id = Ice::stringToIdentity(full); arg = id.name; if(id.category.empty()) { return _defaultManager; } id.name = "TopicManager"; - map<Ice::Identity, TopicManagerPrx>::const_iterator p = _managers.find(id); + auto p = _managers.find(id); if(p == _managers.end()) { - throw UnknownManagerException(id.category, __FILE__, __LINE__); + throw UnknownManagerException(id.category); } return p->second; } -TopicManagerPrx +shared_ptr<TopicManagerPrx> Parser::findManagerByCategory(const string& full) const { - Ice::Identity id; - id.category = full; - id.name = "TopicManager"; - map<Ice::Identity, TopicManagerPrx>::const_iterator p = _managers.find(id); + Ice::Identity id = {"TopicManager", full}; + auto p = _managers.find(id); if(p == _managers.end()) { - throw UnknownManagerException(id.category, __FILE__, __LINE__); + throw UnknownManagerException(id.category); } return p->second; } -TopicPrx +shared_ptr<TopicPrx> Parser::findTopic(const string& full) const { string topicName; - TopicManagerPrx manager = findManagerById(full, topicName); + auto manager = findManagerById(full, topicName); return manager->retrieve(topicName); } -Parser::Parser(const CommunicatorPtr& communicator, const TopicManagerPrx& admin, - const map<Ice::Identity, TopicManagerPrx>& managers) : - _communicator(communicator), - _defaultManager(admin), - _managers(managers) -{ -#ifdef _WIN32 - if(!windowsConsoleConverter) - { - windowsConsoleConverter = Ice::createWindowsStringConverter(GetConsoleOutputCP()); - } -#endif -} - void -Parser::exception(const Ice::Exception& pex, bool warn) +Parser::exception(exception_ptr pex, bool warn) { ostringstream os; try { - pex.ice_throw(); + rethrow_exception(pex); } catch(const LinkExists& ex) { @@ -705,7 +669,7 @@ Parser::exception(const Ice::Exception& pex, bool warn) } catch(const UnknownManagerException& ex) { - os << "couldn't find IceStorm service `" << ex.name << "'"; + os << "couldn't find IceStorm service `" << ex.what() << "'"; } catch(const IdentityParseException& ex) { @@ -719,6 +683,10 @@ Parser::exception(const Ice::Exception& pex, bool warn) { os << ex; } + catch(const std::exception& ex) + { + os << ex.what(); + } if(warn) { diff --git a/cpp/src/IceStorm/Parser.h b/cpp/src/IceStorm/Parser.h index c297617f707..e2cf48481dd 100644 --- a/cpp/src/IceStorm/Parser.h +++ b/cpp/src/IceStorm/Parser.h @@ -5,7 +5,6 @@ #ifndef ICE_STORM_PARSER_H #define ICE_STORM_PARSER_H -#include <IceUtil/Handle.h> #include <IceStorm/IceStorm.h> #include <list> #include <stdio.h> @@ -37,18 +36,12 @@ YY_DECL; namespace IceStorm { -// -// Forward declaration. -// -class Parser; -typedef ::IceUtil::Handle<Parser> ParserPtr; - -class Parser : public ::IceUtil::SimpleShared +class Parser { public: - static ParserPtr createParser(const Ice::CommunicatorPtr&, const TopicManagerPrx&, - const std::map<Ice::Identity, TopicManagerPrx>&); + Parser(std::shared_ptr<Ice::Communicator>, std::shared_ptr<TopicManagerPrx>, + std::map<Ice::Identity, std::shared_ptr<TopicManagerPrx>>); void usage(); @@ -88,17 +81,15 @@ public: private: - TopicManagerPrx findManagerById(const std::string&, std::string&) const; - TopicManagerPrx findManagerByCategory(const std::string&) const; - TopicPrx findTopic(const std::string&) const; - - Parser(const Ice::CommunicatorPtr&, const TopicManagerPrx&, const std::map<Ice::Identity, TopicManagerPrx>&); + std::shared_ptr<TopicManagerPrx> findManagerById(const std::string&, std::string&) const; + std::shared_ptr<TopicManagerPrx> findManagerByCategory(const std::string&) const; + std::shared_ptr<TopicPrx> findTopic(const std::string&) const; - void exception(const Ice::Exception&, bool = false); + void exception(std::exception_ptr, bool = false); - const Ice::CommunicatorPtr _communicator; - TopicManagerPrx _defaultManager; - const std::map<Ice::Identity, TopicManagerPrx> _managers; + const std::shared_ptr<Ice::Communicator> _communicator; + std::shared_ptr<TopicManagerPrx> _defaultManager; + const std::map<Ice::Identity, std::shared_ptr<TopicManagerPrx>> _managers; std::string _commands; bool _continue; int _errors; diff --git a/cpp/src/IceStorm/Replica.h b/cpp/src/IceStorm/Replica.h index f166a8db317..5f3d7422315 100644 --- a/cpp/src/IceStorm/Replica.h +++ b/cpp/src/IceStorm/Replica.h @@ -14,32 +14,27 @@ namespace IceStormElection struct GroupNodeInfo { - GroupNodeInfo(int i); - GroupNodeInfo(int i, LogUpdate l, const Ice::ObjectPrx& o = Ice::ObjectPrx()); + explicit GroupNodeInfo(int i); + GroupNodeInfo(int i, LogUpdate l, std::shared_ptr<Ice::ObjectPrx> o = nullptr); + bool operator<(const GroupNodeInfo& rhs) const; bool operator==(const GroupNodeInfo& rhs) const; - // - // COMPILER FIX: Clang using libc++ requires to define operator= - // -#if defined(__clang__) && defined(_LIBCPP_VERSION) - GroupNodeInfo& operator=(const GroupNodeInfo&); -#endif + const int id; const LogUpdate llu; - const Ice::ObjectPrx observer; + const std::shared_ptr<Ice::ObjectPrx> observer; }; -class Replica : public virtual IceUtil::Shared +class Replica { public: virtual LogUpdate getLastLogUpdate() const = 0; - virtual void sync(const Ice::ObjectPrx&) = 0; + virtual void sync(const std::shared_ptr<Ice::ObjectPrx>&) = 0; virtual void initMaster(const std::set<IceStormElection::GroupNodeInfo>&, const LogUpdate&) = 0; - virtual Ice::ObjectPrx getObserver() const = 0; - virtual Ice::ObjectPrx getSync() const = 0; + virtual std::shared_ptr<Ice::ObjectPrx> getObserver() const = 0; + virtual std::shared_ptr<Ice::ObjectPrx> getSync() const = 0; }; -typedef IceUtil::Handle<Replica> ReplicaPtr; } diff --git a/cpp/src/IceStorm/Scanner.cpp b/cpp/src/IceStorm/Scanner.cpp index ce0e4e36e64..4d5ee833556 100644 --- a/cpp/src/IceStorm/Scanner.cpp +++ b/cpp/src/IceStorm/Scanner.cpp @@ -1,7 +1,11 @@ +#line 1 "src/IceStorm/Scanner.cpp" +// +// Copyright (c) ZeroC, Inc. All rights reserved. +// + #include <IceUtil/ScannerConfig.h> -#line 2 "src/IceStorm/Scanner.cpp" -#line 4 "src/IceStorm/Scanner.cpp" +#line 8 "src/IceStorm/Scanner.cpp" #define YY_INT_ALIGNED short int @@ -9,8 +13,8 @@ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 -#define YY_FLEX_SUBMINOR_VERSION 37 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 4 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif @@ -85,65 +89,61 @@ typedef unsigned int flex_uint32_t; #define UINT32_MAX (4294967295U) #endif +#ifndef SIZE_MAX +#define SIZE_MAX (~(size_t)0) +#endif + #endif /* ! C99 */ #endif /* ! FLEXINT_H */ -#ifdef __cplusplus - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -/* C99 requires __STDC__ to be defined as 1. */ -#if defined (__STDC__) +/* begin standard C++ headers. */ -#define YY_USE_CONST - -#endif /* defined (__STDC__) */ -#endif /* ! __cplusplus */ - -#ifdef YY_USE_CONST +/* TODO: this is always defined, so inline it */ #define yyconst const + +#if defined(__GNUC__) && __GNUC__ >= 3 +#define yynoreturn __attribute__((__noreturn__)) #else -#define yyconst +#define yynoreturn #endif /* Returned upon end-of-file. */ #define YY_NULL 0 -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. +/* Promotes a possibly negative, possibly signed char to an + * integer in range [0..255] for use as an array index. */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) +#define YY_SC_TO_UI(c) ((YY_CHAR) (c)) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * - /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START - /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - /* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart(yyin ) - +#define YY_NEW_FILE yyrestart( yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else #define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. @@ -160,15 +160,16 @@ typedef struct yy_buffer_state *YY_BUFFER_STATE; typedef size_t yy_size_t; #endif -extern yy_size_t yyleng; +extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 - + #define YY_LESS_LINENO(n) + #define YY_LINENO_REWIND_TO(ptr) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ @@ -183,7 +184,6 @@ extern FILE *yyin, *yyout; YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) - #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_STRUCT_YY_BUFFER_STATE @@ -198,12 +198,12 @@ struct yy_buffer_state /* Size of input buffer in bytes, not including room for EOB * characters. */ - yy_size_t yy_buf_size; + int yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ - yy_size_t yy_n_chars; + int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to @@ -226,7 +226,7 @@ struct yy_buffer_state int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ - + /* Whether to try to fill the input buffer when we reach the * end of it. */ @@ -254,7 +254,7 @@ struct yy_buffer_state /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ -static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ +static YY_BUFFER_STATE * yy_buffer_stack = NULL; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general @@ -265,7 +265,6 @@ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) - /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ @@ -273,11 +272,11 @@ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; -static yy_size_t yy_n_chars; /* number of characters read into yy_ch_buf */ -yy_size_t yyleng; +static int yy_n_chars; /* number of characters read into yy_ch_buf */ +int yyleng; /* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; +static char *yy_c_buf_p = NULL; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ @@ -286,85 +285,81 @@ static int yy_start = 0; /* start state number */ */ static int yy_did_buffer_switch_on_eof; -void yyrestart (FILE *input_file ); -void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); -YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); -void yy_delete_buffer (YY_BUFFER_STATE b ); -void yy_flush_buffer (YY_BUFFER_STATE b ); -void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); -void yypop_buffer_state (void ); - -static void yyensure_buffer_stack (void ); -static void yy_load_buffer_state (void ); -static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); +void yyrestart ( FILE *input_file ); +void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ); +YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size ); +void yy_delete_buffer ( YY_BUFFER_STATE b ); +void yy_flush_buffer ( YY_BUFFER_STATE b ); +void yypush_buffer_state ( YY_BUFFER_STATE new_buffer ); +void yypop_buffer_state ( void ); -#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) +static void yyensure_buffer_stack ( void ); +static void yy_load_buffer_state ( void ); +static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file ); +#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER ) -YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); -YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); -YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len ); +YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size ); +YY_BUFFER_STATE yy_scan_string ( const char *yy_str ); +YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len ); -void *yyalloc (yy_size_t ); -void *yyrealloc (void *,yy_size_t ); -void yyfree (void * ); +void *yyalloc ( yy_size_t ); +void *yyrealloc ( void *, yy_size_t ); +void yyfree ( void * ); #define yy_new_buffer yy_create_buffer - #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ - yy_create_buffer(yyin,YY_BUF_SIZE ); \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } - #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ - yy_create_buffer(yyin,YY_BUF_SIZE ); \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } - #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ -#define yywrap() 1 +#define yywrap() (/*CONSTCOND*/1) #define YY_SKIP_YYWRAP +typedef flex_uint8_t YY_CHAR; -typedef unsigned char YY_CHAR; - -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; +FILE *yyin = NULL, *yyout = NULL; typedef int yy_state_type; extern int yylineno; - int yylineno = 1; extern char *yytext; +#ifdef yytext_ptr +#undef yytext_ptr +#endif #define yytext_ptr yytext -static yy_state_type yy_get_previous_state (void ); -static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); -static int yy_get_next_buffer (void ); -static void yy_fatal_error (yyconst char msg[] ); +static yy_state_type yy_get_previous_state ( void ); +static yy_state_type yy_try_NUL_trans ( yy_state_type current_state ); +static int yy_get_next_buffer ( void ); +static void yynoreturn yy_fatal_error ( const char* msg ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ - yyleng = (size_t) (yy_cp - yy_bp); \ + yyleng = (int) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; - #define YY_NUM_RULES 8 #define YY_END_OF_BUFFER 9 /* This struct is not used in this scanner, @@ -374,13 +369,13 @@ struct yy_trans_info flex_int32_t yy_verify; flex_int32_t yy_nxt; }; -static yyconst flex_int16_t yy_accept[19] = +static const flex_int16_t yy_accept[19] = { 0, 3, 3, 9, 7, 3, 4, 5, 6, 7, 4, 7, 3, 0, 2, 1, 0, 3, 0 } ; -static yyconst flex_int32_t yy_ec[256] = +static const YY_CHAR yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, @@ -412,24 +407,24 @@ static yyconst flex_int32_t yy_ec[256] = 1, 1, 1, 1, 1 } ; -static yyconst flex_int32_t yy_meta[10] = +static const YY_CHAR yy_meta[10] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; -static yyconst flex_int16_t yy_base[19] = +static const flex_int16_t yy_base[19] = { 0, 0, 0, 11, 22, 8, 22, 22, 22, 12, 22, 18, 0, 0, 22, 22, 0, 22, 22 } ; -static yyconst flex_int16_t yy_def[19] = +static const flex_int16_t yy_def[19] = { 0, 18, 1, 18, 18, 18, 18, 18, 18, 18, 18, 18, 5, 11, 18, 18, 11, 18, 0 } ; -static yyconst flex_int16_t yy_nxt[32] = +static const flex_int16_t yy_nxt[32] = { 0, 4, 5, 6, 7, 8, 4, 9, 10, 11, 12, 18, 18, 18, 18, 18, 18, 13, 14, 15, 16, @@ -437,7 +432,7 @@ static yyconst flex_int16_t yy_nxt[32] = 18 } ; -static yyconst flex_int16_t yy_chk[32] = +static const flex_int16_t yy_chk[32] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 3, 0, 0, 0, 0, 0, 5, 9, 9, 11, @@ -460,35 +455,13 @@ int yy_flex_debug = 0; #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "src/IceStorm/Scanner.l" -#line 2 "src/IceStorm/Scanner.l" -// -// Copyright (c) ZeroC, Inc. All rights reserved. -// +#line 11 "src/IceStorm/Scanner.l" #include <Ice/Ice.h> #include <IceStorm/Parser.h> #include <IceStorm/Grammar.h> -#if defined(_MSC_VER) -// '<' : signed/unsigned mismatch -# pragma warning(disable:4018) -// 'initializing' : conversion from '__int64' to 'int', possible loss of data -# pragma warning(disable:4244) - -# if defined(ICE_64) -// -// '=' : conversion from 'size_t' to 'int', possible loss of data -// The result of fread() is a size_t and gets inserted into an int -// -# pragma warning(disable:4267) -# endif -#endif - -#if defined(__GNUC__) -# pragma GCC diagnostic ignored "-Wsign-compare" -#endif - using namespace std; using namespace Ice; using namespace IceStorm; @@ -498,17 +471,6 @@ using namespace IceStorm; # undef yywrap # define yywrap() 1 # endif -# define YY_NO_UNISTD_H -#endif - -#ifdef __SUNPRO_CC -# ifdef yywrap -# undef yywrap -# define yywrap() 1 -# endif -# ifdef ICE_64 -# pragma error_messages(off,truncwarn) -# endif #endif #define YY_INPUT(buf, result, maxSize) parser->getInput(buf, result, maxSize) @@ -516,15 +478,15 @@ using namespace IceStorm; namespace IceStorm { -typedef std::map<std::string, int> StringTokenMap; -static StringTokenMap keywordMap; +static std::map<std::string, int> keywordMap; void initScanner(); } #define YY_USER_INIT initScanner(); -#line 532 "src/IceStorm/Scanner.cpp" +#line 495 "src/IceStorm/Scanner.cpp" +#line 496 "src/IceStorm/Scanner.cpp" #define INITIAL 0 @@ -540,36 +502,36 @@ void initScanner(); #define YY_EXTRA_TYPE void * #endif -static int yy_init_globals (void ); +static int yy_init_globals ( void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ -int yylex_destroy (void ); +int yylex_destroy ( void ); -int yyget_debug (void ); +int yyget_debug ( void ); -void yyset_debug (int debug_flag ); +void yyset_debug ( int debug_flag ); -YY_EXTRA_TYPE yyget_extra (void ); +YY_EXTRA_TYPE yyget_extra ( void ); -void yyset_extra (YY_EXTRA_TYPE user_defined ); +void yyset_extra ( YY_EXTRA_TYPE user_defined ); -FILE *yyget_in (void ); +FILE *yyget_in ( void ); -void yyset_in (FILE * in_str ); +void yyset_in ( FILE * _in_str ); -FILE *yyget_out (void ); +FILE *yyget_out ( void ); -void yyset_out (FILE * out_str ); +void yyset_out ( FILE * _out_str ); -yy_size_t yyget_leng (void ); + int yyget_leng ( void ); -char *yyget_text (void ); +char *yyget_text ( void ); -int yyget_lineno (void ); +int yyget_lineno ( void ); -void yyset_lineno (int line_number ); +void yyset_lineno ( int _line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. @@ -577,35 +539,43 @@ void yyset_lineno (int line_number ); #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus -extern "C" int yywrap (void ); +extern "C" int yywrap ( void ); #else -extern int yywrap (void ); +extern int yywrap ( void ); #endif #endif - static void yyunput (int c,char *buf_ptr ); +#ifndef YY_NO_UNPUT + static void yyunput ( int c, char *buf_ptr ); + +#endif + #ifndef yytext_ptr -static void yy_flex_strncpy (char *,yyconst char *,int ); +static void yy_flex_strncpy ( char *, const char *, int ); #endif #ifdef YY_NEED_STRLEN -static int yy_flex_strlen (yyconst char * ); +static int yy_flex_strlen ( const char * ); #endif #ifndef YY_NO_INPUT - #ifdef __cplusplus -static int yyinput (void ); +static int yyinput ( void ); #else -static int input (void ); +static int input ( void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else #define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ @@ -613,7 +583,7 @@ static int input (void ); /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ -#define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) +#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, @@ -624,7 +594,7 @@ static int input (void ); if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ - size_t n; \ + int n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ @@ -637,7 +607,7 @@ static int input (void ); else \ { \ errno=0; \ - while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ + while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ @@ -692,7 +662,7 @@ extern int yylex (void); /* Code executed at the end of each rule. */ #ifndef YY_BREAK -#define YY_BREAK break; +#define YY_BREAK /*LINTED*/break; #endif #define YY_RULE_SETUP \ @@ -702,15 +672,10 @@ extern int yylex (void); */ YY_DECL { - register yy_state_type yy_current_state; - register char *yy_cp, *yy_bp; - register int yy_act; + yy_state_type yy_current_state; + char *yy_cp, *yy_bp; + int yy_act; -#line 79 "src/IceStorm/Scanner.l" - - -#line 717 "src/IceStorm/Scanner.cpp" - if ( !(yy_init) ) { (yy_init) = 1; @@ -731,13 +696,18 @@ YY_DECL if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = - yy_create_buffer(yyin,YY_BUF_SIZE ); + yy_create_buffer( yyin, YY_BUF_SIZE ); } - yy_load_buffer_state( ); + yy_load_buffer_state( ); } - while ( 1 ) /* loops until end-of-file is reached */ + { +#line 55 "src/IceStorm/Scanner.l" + +#line 716 "src/IceStorm/Scanner.cpp" + + while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); @@ -753,7 +723,7 @@ YY_DECL yy_match: do { - register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; + YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; @@ -763,9 +733,9 @@ yy_match: { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 19 ) - yy_c = yy_meta[(unsigned int) yy_c]; + yy_c = yy_meta[yy_c]; } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 22 ); @@ -794,7 +764,7 @@ do_action: /* This label is used only to access EOF actions. */ case 1: YY_RULE_SETUP -#line 81 "src/IceStorm/Scanner.l" +#line 57 "src/IceStorm/Scanner.l" { // C++-style comment int c; @@ -807,7 +777,7 @@ YY_RULE_SETUP YY_BREAK case 2: YY_RULE_SETUP -#line 91 "src/IceStorm/Scanner.l" +#line 67 "src/IceStorm/Scanner.l" { // C-style comment while(true) @@ -836,7 +806,7 @@ YY_RULE_SETUP case 3: /* rule 3 can match eol */ YY_RULE_SETUP -#line 116 "src/IceStorm/Scanner.l" +#line 92 "src/IceStorm/Scanner.l" { size_t len = strlen(yytext); for(size_t i = 0; i < len; ++i) @@ -851,14 +821,14 @@ YY_RULE_SETUP case 4: /* rule 4 can match eol */ YY_RULE_SETUP -#line 127 "src/IceStorm/Scanner.l" +#line 103 "src/IceStorm/Scanner.l" { return ';'; } YY_BREAK case 5: YY_RULE_SETUP -#line 131 "src/IceStorm/Scanner.l" +#line 107 "src/IceStorm/Scanner.l" { // "..."-type strings string s; @@ -905,7 +875,7 @@ YY_RULE_SETUP YY_BREAK case 6: YY_RULE_SETUP -#line 175 "src/IceStorm/Scanner.l" +#line 151 "src/IceStorm/Scanner.l" { // '...'-type strings string s; @@ -933,7 +903,7 @@ YY_RULE_SETUP YY_BREAK case 7: YY_RULE_SETUP -#line 200 "src/IceStorm/Scanner.l" +#line 176 "src/IceStorm/Scanner.l" { // Simple strings string s; @@ -957,16 +927,16 @@ YY_RULE_SETUP yylvalp->clear(); yylvalp->push_back(s); - StringTokenMap::const_iterator pos = keywordMap.find(s); + const auto pos = keywordMap.find(s); return pos != keywordMap.end() ? pos->second : ICE_STORM_STRING; } YY_BREAK case 8: YY_RULE_SETUP -#line 227 "src/IceStorm/Scanner.l" +#line 203 "src/IceStorm/Scanner.l" ECHO; YY_BREAK -#line 974 "src/IceStorm/Scanner.cpp" +#line 947 "src/IceStorm/Scanner.cpp" case YY_STATE_EOF(INITIAL): yyterminate(); @@ -1044,7 +1014,7 @@ case YY_STATE_EOF(INITIAL): { (yy_did_buffer_switch_on_eof) = 0; - if ( yywrap( ) ) + if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up @@ -1097,6 +1067,7 @@ case YY_STATE_EOF(INITIAL): "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ + } /* end of user's declarations */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer @@ -1108,9 +1079,9 @@ case YY_STATE_EOF(INITIAL): */ static int yy_get_next_buffer (void) { - register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; - register char *source = (yytext_ptr); - register int number_to_move, i; + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *source = (yytext_ptr); + int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) @@ -1139,7 +1110,7 @@ static int yy_get_next_buffer (void) /* Try to read more data. */ /* First move last chars to start of buffer. */ - number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; + number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1); for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); @@ -1152,7 +1123,7 @@ static int yy_get_next_buffer (void) else { - yy_size_t num_to_read = + int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) @@ -1166,7 +1137,7 @@ static int yy_get_next_buffer (void) if ( b->yy_is_our_buffer ) { - yy_size_t new_size = b->yy_buf_size * 2; + int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; @@ -1175,11 +1146,12 @@ static int yy_get_next_buffer (void) b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ - yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); + yyrealloc( (void *) b->yy_ch_buf, + (yy_size_t) (b->yy_buf_size + 2) ); } else /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; + b->yy_ch_buf = NULL; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( @@ -1207,7 +1179,7 @@ static int yy_get_next_buffer (void) if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; - yyrestart(yyin ); + yyrestart( yyin ); } else @@ -1221,12 +1193,15 @@ static int yy_get_next_buffer (void) else ret_val = EOB_ACT_CONTINUE_SCAN; - if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { + if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ - yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); - YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); + int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( + (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); + /* "- 2" to take care of EOB's */ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); } (yy_n_chars) += number_to_move; @@ -1242,14 +1217,14 @@ static int yy_get_next_buffer (void) static yy_state_type yy_get_previous_state (void) { - register yy_state_type yy_current_state; - register char *yy_cp; + yy_state_type yy_current_state; + char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { - register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; @@ -1259,9 +1234,9 @@ static int yy_get_next_buffer (void) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 19 ) - yy_c = yy_meta[(unsigned int) yy_c]; + yy_c = yy_meta[yy_c]; } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; } return yy_current_state; @@ -1274,10 +1249,10 @@ static int yy_get_next_buffer (void) */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { - register int yy_is_jam; - register char *yy_cp = (yy_c_buf_p); + int yy_is_jam; + char *yy_cp = (yy_c_buf_p); - register YY_CHAR yy_c = 1; + YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; @@ -1287,17 +1262,19 @@ static int yy_get_next_buffer (void) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 19 ) - yy_c = yy_meta[(unsigned int) yy_c]; + yy_c = yy_meta[yy_c]; } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; yy_is_jam = (yy_current_state == 18); return yy_is_jam ? 0 : yy_current_state; } - static void yyunput (int c, register char * yy_bp ) +#ifndef YY_NO_UNPUT + + static void yyunput (int c, char * yy_bp ) { - register char *yy_cp; + char *yy_cp; yy_cp = (yy_c_buf_p); @@ -1307,10 +1284,10 @@ static int yy_get_next_buffer (void) if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ - register yy_size_t number_to_move = (yy_n_chars) + 2; - register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ + int number_to_move = (yy_n_chars) + 2; + char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; - register char *source = + char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) @@ -1319,7 +1296,7 @@ static int yy_get_next_buffer (void) yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = - (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; + (yy_n_chars) = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); @@ -1332,6 +1309,8 @@ static int yy_get_next_buffer (void) (yy_c_buf_p) = yy_cp; } +#endif + #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) @@ -1356,7 +1335,7 @@ static int yy_get_next_buffer (void) else { /* need more input */ - yy_size_t offset = (yy_c_buf_p) - (yytext_ptr); + int offset = (int) ((yy_c_buf_p) - (yytext_ptr)); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) @@ -1373,14 +1352,14 @@ static int yy_get_next_buffer (void) */ /* Reset buffer status. */ - yyrestart(yyin ); + yyrestart( yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { - if ( yywrap( ) ) - return EOF; + if ( yywrap( ) ) + return 0; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; @@ -1417,11 +1396,11 @@ static int yy_get_next_buffer (void) if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = - yy_create_buffer(yyin,YY_BUF_SIZE ); + yy_create_buffer( yyin, YY_BUF_SIZE ); } - yy_init_buffer(YY_CURRENT_BUFFER,input_file ); - yy_load_buffer_state( ); + yy_init_buffer( YY_CURRENT_BUFFER, input_file ); + yy_load_buffer_state( ); } /** Switch to a different input buffer. @@ -1449,7 +1428,7 @@ static int yy_get_next_buffer (void) } YY_CURRENT_BUFFER_LVALUE = new_buffer; - yy_load_buffer_state( ); + yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag @@ -1477,7 +1456,7 @@ static void yy_load_buffer_state (void) { YY_BUFFER_STATE b; - b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); @@ -1486,13 +1465,13 @@ static void yy_load_buffer_state (void) /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ - b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); + b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; - yy_init_buffer(b,file ); + yy_init_buffer( b, file ); return b; } @@ -1511,9 +1490,9 @@ static void yy_load_buffer_state (void) YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) - yyfree((void *) b->yy_ch_buf ); + yyfree( (void *) b->yy_ch_buf ); - yyfree((void *) b ); + yyfree( (void *) b ); } /* Initializes or reinitializes a buffer. @@ -1525,7 +1504,7 @@ static void yy_load_buffer_state (void) { int oerrno = errno; - yy_flush_buffer(b ); + yy_flush_buffer( b ); b->yy_input_file = file; b->yy_fill_buffer = 1; @@ -1568,7 +1547,7 @@ static void yy_load_buffer_state (void) b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) - yy_load_buffer_state( ); + yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes @@ -1599,7 +1578,7 @@ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ - yy_load_buffer_state( ); + yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } @@ -1618,7 +1597,7 @@ void yypop_buffer_state (void) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { - yy_load_buffer_state( ); + yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } @@ -1636,15 +1615,15 @@ static void yyensure_buffer_stack (void) * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ - num_to_alloc = 1; + num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); - + memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); - + (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; @@ -1653,7 +1632,7 @@ static void yyensure_buffer_stack (void) if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ - int grow_size = 8 /* arbitrary grow size */; + yy_size_t grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc @@ -1673,7 +1652,7 @@ static void yyensure_buffer_stack (void) * @param base the character buffer * @param size the size in bytes of the character buffer * - * @return the newly allocated buffer state object. + * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { @@ -1683,23 +1662,23 @@ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ - return 0; + return NULL; - b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; - b->yy_input_file = 0; + b->yy_input_file = NULL; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; - yy_switch_to_buffer(b ); + yy_switch_to_buffer( b ); return b; } @@ -1712,10 +1691,10 @@ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ -YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) +YY_BUFFER_STATE yy_scan_string (const char * yystr ) { - return yy_scan_bytes(yystr,strlen(yystr) ); + return yy_scan_bytes( yystr, (int) strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will @@ -1725,7 +1704,7 @@ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) * * @return the newly allocated buffer state object. */ -YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len ) +YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; @@ -1733,8 +1712,8 @@ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len int i; /* Get memory for full buffer, including space for trailing EOB's. */ - n = _yybytes_len + 2; - buf = (char *) yyalloc(n ); + n = (yy_size_t) (_yybytes_len + 2); + buf = (char *) yyalloc( n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); @@ -1743,7 +1722,7 @@ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; - b = yy_scan_buffer(buf,n ); + b = yy_scan_buffer( buf, n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); @@ -1759,9 +1738,9 @@ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len #define YY_EXIT_FAILURE 2 #endif -static void yy_fatal_error (yyconst char* msg ) +static void yynoreturn yy_fatal_error (const char* msg ) { - (void) fprintf( stderr, "%s\n", msg ); + fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } @@ -1789,7 +1768,7 @@ static void yy_fatal_error (yyconst char* msg ) */ int yyget_lineno (void) { - + return yylineno; } @@ -1812,7 +1791,7 @@ FILE *yyget_out (void) /** Get the length of the current token. * */ -yy_size_t yyget_leng (void) +int yyget_leng (void) { return yyleng; } @@ -1827,29 +1806,29 @@ char *yyget_text (void) } /** Set the current line number. - * @param line_number + * @param _line_number line number * */ -void yyset_lineno (int line_number ) +void yyset_lineno (int _line_number ) { - yylineno = line_number; + yylineno = _line_number; } /** Set the input stream. This does not discard the current * input buffer. - * @param in_str A readable stream. + * @param _in_str A readable stream. * * @see yy_switch_to_buffer */ -void yyset_in (FILE * in_str ) +void yyset_in (FILE * _in_str ) { - yyin = in_str ; + yyin = _in_str ; } -void yyset_out (FILE * out_str ) +void yyset_out (FILE * _out_str ) { - yyout = out_str ; + yyout = _out_str ; } int yyget_debug (void) @@ -1857,9 +1836,9 @@ int yyget_debug (void) return yy_flex_debug; } -void yyset_debug (int bdebug ) +void yyset_debug (int _bdebug ) { - yy_flex_debug = bdebug ; + yy_flex_debug = _bdebug ; } static int yy_init_globals (void) @@ -1868,10 +1847,10 @@ static int yy_init_globals (void) * This function is called from yylex_destroy(), so don't allocate here. */ - (yy_buffer_stack) = 0; + (yy_buffer_stack) = NULL; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; - (yy_c_buf_p) = (char *) 0; + (yy_c_buf_p) = NULL; (yy_init) = 0; (yy_start) = 0; @@ -1880,8 +1859,8 @@ static int yy_init_globals (void) yyin = stdin; yyout = stdout; #else - yyin = (FILE *) 0; - yyout = (FILE *) 0; + yyin = NULL; + yyout = NULL; #endif /* For future reference: Set errno on error, since we are called by @@ -1896,7 +1875,7 @@ int yylex_destroy (void) /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ - yy_delete_buffer(YY_CURRENT_BUFFER ); + yy_delete_buffer( YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } @@ -1917,18 +1896,19 @@ int yylex_destroy (void) */ #ifndef yytext_ptr -static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) +static void yy_flex_strncpy (char* s1, const char * s2, int n ) { - register int i; + + int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN -static int yy_flex_strlen (yyconst char * s ) +static int yy_flex_strlen (const char * s ) { - register int n; + int n; for ( n = 0; s[n]; ++n ) ; @@ -1938,11 +1918,12 @@ static int yy_flex_strlen (yyconst char * s ) void *yyalloc (yy_size_t size ) { - return (void *) malloc( size ); + return malloc(size); } void *yyrealloc (void * ptr, yy_size_t size ) { + /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter @@ -1950,19 +1931,17 @@ void *yyrealloc (void * ptr, yy_size_t size ) * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ - return (void *) realloc( (char *) ptr, size ); + return realloc(ptr, size); } void yyfree (void * ptr ) { - free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ + free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" -#line 227 "src/IceStorm/Scanner.l" - - +#line 203 "src/IceStorm/Scanner.l" namespace IceStorm { @@ -1973,19 +1952,20 @@ namespace IceStorm { void initScanner() { - keywordMap["help"] = ICE_STORM_HELP; - keywordMap["quit"] = ICE_STORM_EXIT; - keywordMap["exit"] = ICE_STORM_EXIT; - keywordMap["current"] = ICE_STORM_CURRENT; - keywordMap["create"] = ICE_STORM_CREATE; - keywordMap["destroy"] = ICE_STORM_DESTROY; - keywordMap["link"] = ICE_STORM_LINK; - keywordMap["unlink"] = ICE_STORM_UNLINK; - keywordMap["links"] = ICE_STORM_LINKS; - keywordMap["topics"] = ICE_STORM_TOPICS; - keywordMap["replica"] = ICE_STORM_REPLICA; - keywordMap["subscribers"] = ICE_STORM_SUBSCRIBERS; + keywordMap = { + {"help", ICE_STORM_HELP}, + {"quit", ICE_STORM_EXIT}, + {"exit", ICE_STORM_EXIT}, + {"current", ICE_STORM_CURRENT}, + {"create", ICE_STORM_CREATE}, + {"destroy", ICE_STORM_DESTROY}, + {"link", ICE_STORM_LINK}, + {"unlink", ICE_STORM_UNLINK}, + {"links", ICE_STORM_LINKS}, + {"topics", ICE_STORM_TOPICS}, + {"replica", ICE_STORM_REPLICA}, + {"subscribers", ICE_STORM_SUBSCRIBERS}, + }; } } - diff --git a/cpp/src/IceStorm/Service.cpp b/cpp/src/IceStorm/Service.cpp index 453d20a4c00..09d3067f046 100644 --- a/cpp/src/IceStorm/Service.cpp +++ b/cpp/src/IceStorm/Service.cpp @@ -32,56 +32,52 @@ using namespace IceStormElection; namespace { -class ServiceI : public IceStormInternal::Service +class ServiceI final : public IceStormInternal::Service { public: - ServiceI(); - virtual ~ServiceI(); + void start(const std::shared_ptr<Ice::Communicator>&, + const std::shared_ptr<Ice::ObjectAdapter>&, + const std::shared_ptr<Ice::ObjectAdapter>&, + const std::string&, + const Ice::Identity&, + const std::string&); - virtual void start(const string&, - const CommunicatorPtr&, - const StringSeq&); + std::shared_ptr<IceStorm::TopicManagerPrx> getTopicManager() const override; - virtual void start(const CommunicatorPtr&, - const ObjectAdapterPtr&, - const ObjectAdapterPtr&, - const string&, - const Ice::Identity&, - const string&); - - virtual TopicManagerPrx getTopicManager() const; - - virtual void stop(); + void start(const std::string&, const std::shared_ptr<Ice::Communicator>&, const Ice::StringSeq&) override; + void stop() override; private: - void createDbEnv(const Ice::CommunicatorPtr&); - void validateProperties(const string&, const PropertiesPtr&, const LoggerPtr&); + void createDbEnv(const std::shared_ptr<Ice::Communicator>&); + void validateProperties(const std::string&, + const std::shared_ptr<Ice::Properties>&, + const std::shared_ptr<Ice::Logger>&); - TopicManagerImplPtr _manager; - TransientTopicManagerImplPtr _transientManager; - TopicManagerPrx _managerProxy; - InstancePtr _instance; + std::shared_ptr<IceStorm::TopicManagerImpl> _manager; + std::shared_ptr<IceStorm::TransientTopicManagerImpl> _transientManager; + std::shared_ptr<IceStorm::TopicManagerPrx> _managerProxy; + std::shared_ptr<IceStorm::Instance> _instance; }; -class FinderI : public IceStorm::Finder +class FinderI final : public IceStorm::Finder { public: - FinderI(const TopicManagerPrx& topicManager) : _topicManager(topicManager) + FinderI(shared_ptr<TopicManagerPrx> topicManager) : _topicManager(move(topicManager)) { } - virtual TopicManagerPrx - getTopicManager(const Ice::Current&) + shared_ptr<TopicManagerPrx> + getTopicManager(const Ice::Current&) override { return _topicManager; } private: - const TopicManagerPrx _topicManager; + const shared_ptr<TopicManagerPrx> _topicManager; }; } @@ -90,42 +86,30 @@ extern "C" { ICESTORM_SERVICE_API ::IceBox::Service* -createIceStorm(CommunicatorPtr) +createIceStorm(const shared_ptr<Communicator>&) { return new ServiceI; } } -ServicePtr -IceStormInternal::Service::create(const CommunicatorPtr& communicator, - const ObjectAdapterPtr& topicAdapter, - const ObjectAdapterPtr& publishAdapter, - const string& name, - const Ice::Identity& id, - const string& dbEnv) +shared_ptr<IceStormInternal::Service> +IceStormInternal::Service::create(const shared_ptr<Communicator>& communicator, + const shared_ptr<ObjectAdapter>& topicAdapter, + const shared_ptr<ObjectAdapter>& publishAdapter, + const string& name, + const Ice::Identity& id, + const string& dbEnv) { - ServiceI* service = new ServiceI; - ServicePtr svc = service; + shared_ptr<ServiceI> service(new ServiceI); service->start(communicator, topicAdapter, publishAdapter, name, id, dbEnv); - return svc; -} - -ServiceI::ServiceI() -{ -} - -ServiceI::~ServiceI() -{ + return service; } void -ServiceI::start( - const string& name, - const CommunicatorPtr& communicator, - const StringSeq& /*args*/) +ServiceI::start(const string& name, const shared_ptr<Communicator>& communicator, const StringSeq&) { - PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); validateProperties(name, properties, communicator->getLogger()); @@ -141,24 +125,22 @@ ServiceI::start( properties->setProperty(name + ".TopicManager.ThreadPool.SizeMax", "100"); } - Ice::ObjectAdapterPtr topicAdapter = communicator->createObjectAdapter(name + ".TopicManager"); - Ice::ObjectAdapterPtr publishAdapter = communicator->createObjectAdapter(name + ".Publish"); + auto topicAdapter = communicator->createObjectAdapter(name + ".TopicManager"); + auto publishAdapter = communicator->createObjectAdapter(name + ".Publish"); // // We use the name of the service for the name of the database environment. // string instanceName = properties->getPropertyWithDefault(name + ".InstanceName", "IceStorm"); - Identity topicManagerId; - topicManagerId.category = instanceName; - topicManagerId.name = "TopicManager"; + Identity topicManagerId = { "TopicManager", instanceName }; if(properties->getPropertyAsIntWithDefault(name+ ".Transient", 0) > 0) { - _instance = new Instance(instanceName, name, communicator, publishAdapter, topicAdapter, 0); + _instance = make_shared<Instance>(instanceName, name, communicator, publishAdapter, topicAdapter, nullptr); try { - TransientTopicManagerImplPtr manager = new TransientTopicManagerImpl(_instance); - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(manager, topicManagerId)); + auto manager = make_shared<TransientTopicManagerImpl>(_instance); + _managerProxy = Ice::uncheckedCast<TopicManagerPrx>(topicAdapter->add(manager, topicManagerId)); } catch(const Ice::Exception& ex) { @@ -178,12 +160,10 @@ ServiceI::start( { try { - PersistentInstancePtr instance = - new PersistentInstance(instanceName, name, communicator, publishAdapter, topicAdapter); - _instance = instance; - - _manager = new TopicManagerImpl(instance); - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(_manager->getServant(), topicManagerId)); + auto instance = make_shared<PersistentInstance>(instanceName, name, communicator, publishAdapter, topicAdapter); + _manager = TopicManagerImpl::create(instance); + _instance = move(instance); + _managerProxy = uncheckedCast<TopicManagerPrx>(topicAdapter->add(_manager->getServant(), topicManagerId)); } catch(const IceUtil::Exception& ex) { @@ -198,9 +178,8 @@ ServiceI::start( } else { - // Here we want to create a map of id -> election node - // proxies. - map<int, NodePrx> nodes; + // Here we want to create a map of id -> election node proxies. + map<int, shared_ptr<NodePrx>> nodes; string topicManagerAdapterId = properties->getProperty(name + ".TopicManager.AdapterId"); @@ -212,10 +191,18 @@ ServiceI::start( Ice::PropertyDict props = properties->getPropertiesForPrefix(prefix); if(!props.empty()) { - for(Ice::PropertyDict::const_iterator p = props.begin(); p != props.end(); ++p) + for(const auto& prop : props) { - int nodeid = atoi(p->first.substr(prefix.size()).c_str()); - nodes[nodeid] = NodePrx::uncheckedCast(communicator->propertyToProxy(p->first)); + try + { + int nodeid = stoi(prop.first.substr(prefix.size())); + nodes[nodeid] = uncheckedCast<NodePrx>(communicator->propertyToProxy(prop.first)); + } + catch(const std::invalid_argument&) + { + Ice::Warning warn(communicator->getLogger()); + warn << "deployment warning: invalid node id `" << prop.first.substr(prefix.size()) << "'"; + } } } else @@ -248,15 +235,15 @@ ServiceI::start( // We work out the node id by removing the instance // name. The node id must follow. // - IceGrid::LocatorPrx locator = IceGrid::LocatorPrx::checkedCast(communicator->getDefaultLocator()); + auto locator = Ice::checkedCast<IceGrid::LocatorPrx>(communicator->getDefaultLocator()); assert(locator); - IceGrid::QueryPrx query = locator->getLocalQuery(); - Ice::ObjectProxySeq replicas = query->findAllReplicas( - communicator->stringToProxy(instanceName + "/TopicManager")); + auto query = locator->getLocalQuery(); + auto replicas = query->findAllReplicas(communicator->stringToProxy(instanceName + "/TopicManager")); for(Ice::ObjectProxySeq::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - string adapterid = (*p)->ice_getAdapterId(); + string adapterid = replica->ice_getAdapterId(); // Replace TopicManager with the node endpoint. adapterid = adapterid.replace(adapterid.find(suffix), suffix.size(), ".Node"); @@ -299,7 +286,7 @@ ServiceI::start( ident.category = instanceName; ident.name = os.str(); - nodes[nodeid] = NodePrx::uncheckedCast((*p)->ice_adapterId(adapterid)->ice_identity(ident)); + nodes[nodeid] = uncheckedCast<NodePrx>((*p)->ice_adapterId(adapterid)->ice_identity(ident)); } } @@ -327,24 +314,22 @@ ServiceI::start( properties->setProperty(name + ".Node.MessageSizeMax", "0"); // No limit on data exchanged internally } - Ice::ObjectAdapterPtr nodeAdapter = communicator->createObjectAdapter(name + ".Node"); - - PersistentInstancePtr instance = - new PersistentInstance(instanceName, name, communicator, publishAdapter, topicAdapter, - nodeAdapter, nodes[id]); + auto nodeAdapter = communicator->createObjectAdapter(name + ".Node"); + auto instance = make_shared<PersistentInstance>(instanceName, name, communicator, publishAdapter, + topicAdapter, nodeAdapter, nodes[id]); _instance = instance; _instance->observers()->setMajority(static_cast<unsigned int>(nodes.size())/2); // Trace replication information. - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->election > 0) { Ice::Trace out(traceLevels->logger, traceLevels->electionCat); out << "I am node " << id << "\n"; - for(map<int, NodePrx>::const_iterator p = nodes.begin(); p != nodes.end(); ++p) + for(const auto& node : nodes) { - out << "\tnode: " << p->first << " proxy: " << p->second->ice_toString() << "\n"; + out << "\tnode: " << node.first << " proxy: " << node.second->ice_toString() << "\n"; } } @@ -353,16 +338,16 @@ ServiceI::start( // We're not using an IceGrid deployment. Here we need // a proxy which is used to create proxies to the // replicas later. - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->createProxy(topicManagerId)); + _managerProxy = uncheckedCast<TopicManagerPrx>(topicAdapter->createProxy(topicManagerId)); } else { // If we're using IceGrid deployment we need to create // indirect proxies. - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->createIndirectProxy(topicManagerId)); + _managerProxy = uncheckedCast<TopicManagerPrx>(topicAdapter->createIndirectProxy(topicManagerId)); } - _manager = new TopicManagerImpl(instance); + _manager = TopicManagerImpl::create(instance); topicAdapter->add(_manager->getServant(), topicManagerId); ostringstream os; // The node object identity. @@ -371,7 +356,7 @@ ServiceI::start( nodeid.category = instanceName; nodeid.name = os.str(); - NodeIPtr node = new NodeI(_instance, _manager, _managerProxy, id, nodes); + auto node = make_shared<NodeI>(_instance, _manager, _managerProxy, id, nodes); _instance->setNode(node); nodeAdapter->add(node, nodeid); nodeAdapter->activate(); @@ -390,7 +375,7 @@ ServiceI::start( } } - topicAdapter->add(new FinderI(TopicManagerPrx::uncheckedCast(topicAdapter->createProxy(topicManagerId))), + topicAdapter->add(make_shared<FinderI>(uncheckedCast<TopicManagerPrx>(topicAdapter->createProxy(topicManagerId))), stringToIdentity("IceStorm/Finder")); topicAdapter->activate(); @@ -398,12 +383,12 @@ ServiceI::start( } void -ServiceI::start(const CommunicatorPtr& communicator, - const ObjectAdapterPtr& topicAdapter, - const ObjectAdapterPtr& publishAdapter, +ServiceI::start(const shared_ptr<Communicator>& communicator, + const shared_ptr<ObjectAdapter>& topicAdapter, + const shared_ptr<ObjectAdapter>& publishAdapter, const string& name, - const Ice::Identity& id, - const string& /*dbEnv*/) + const Identity& id, + const string&) { // // For IceGrid we don't validate the properties as all sorts of @@ -414,12 +399,12 @@ ServiceI::start(const CommunicatorPtr& communicator, // 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); + _instance = make_shared<Instance>(instanceName, name, communicator, publishAdapter, topicAdapter, nullptr); try { - TransientTopicManagerImplPtr manager = new TransientTopicManagerImpl(_instance); - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(manager, id)); + auto manager = make_shared<TransientTopicManagerImpl>(_instance); + _managerProxy = uncheckedCast<TopicManagerPrx>(topicAdapter->add(manager, id)); } catch(const Ice::Exception& ex) { @@ -432,7 +417,7 @@ ServiceI::start(const CommunicatorPtr& communicator, } } -TopicManagerPrx +shared_ptr<TopicManagerPrx> ServiceI::getTopicManager() const { return _managerProxy; @@ -463,7 +448,7 @@ ServiceI::stop() } void -ServiceI::validateProperties(const string& name, const PropertiesPtr& properties, const LoggerPtr& logger) +ServiceI::validateProperties(const string& name, const shared_ptr<Properties>& properties, const shared_ptr<Logger>& logger) { static const string suffixes[] = { diff --git a/cpp/src/IceStorm/Service.h b/cpp/src/IceStorm/Service.h index 11c7a80a2ad..84916bacf75 100644 --- a/cpp/src/IceStorm/Service.h +++ b/cpp/src/IceStorm/Service.h @@ -9,7 +9,7 @@ #include <IceStorm/IceStorm.h> // -// Automatically link with IceStormService[D|++11|++11D].lib +// Automatically link with IceStormService[D].lib // #if !defined(ICE_BUILDING_ICE_STORM_SERVICE) && defined(ICESTORM_SERVICE_API_EXPORTS) @@ -20,6 +20,7 @@ # pragma comment(lib, ICE_LIBNAME("IceStormService")) #endif +// These IceStorm APIs are exported because they are used by IceGrid #ifndef ICESTORM_SERVICE_API # if defined(ICE_STATIC_LIBS) # define ICESTORM_SERVICE_API /**/ @@ -30,30 +31,22 @@ # endif #endif -// This API is internal to Ice, and should not be used by external -// applications. +// This API is internal to Ice, and should not be used by external applications. namespace IceStormInternal { -class Service; -typedef ::IceInternal::Handle< IceStormInternal::Service> ServicePtr; - -class Service : public ::IceBox::Service +class Service : public IceBox::Service { public: - ICESTORM_SERVICE_API static ServicePtr create(const Ice::CommunicatorPtr&, - const Ice::ObjectAdapterPtr&, - const Ice::ObjectAdapterPtr&, - const std::string&, - const Ice::Identity&, - const std::string&); - - virtual void start(const std::string&, const Ice::CommunicatorPtr&, const Ice::StringSeq&) = 0; - - ICESTORM_SERVICE_API virtual IceStorm::TopicManagerPrx getTopicManager() const = 0; + ICESTORM_SERVICE_API static std::shared_ptr<Service> create(const std::shared_ptr<Ice::Communicator>&, + const std::shared_ptr<Ice::ObjectAdapter>&, + const std::shared_ptr<Ice::ObjectAdapter>&, + const std::string&, + const Ice::Identity&, + const std::string&); - virtual void stop() = 0; + ICESTORM_SERVICE_API virtual std::shared_ptr<IceStorm::TopicManagerPrx> getTopicManager() const = 0; }; }; diff --git a/cpp/src/IceStorm/Subscriber.cpp b/cpp/src/IceStorm/Subscriber.cpp index 9df599eec3c..9edfe04ea21 100644 --- a/cpp/src/IceStorm/Subscriber.cpp +++ b/cpp/src/IceStorm/Subscriber.cpp @@ -21,54 +21,45 @@ using namespace IceStormElection; namespace { -class PerSubscriberPublisherI : public Ice::BlobjectArray +class PerSubscriberPublisherI final : public Ice::BlobjectArray { public: - PerSubscriberPublisherI(const InstancePtr& instance) : - _instance(instance) + PerSubscriberPublisherI(shared_ptr<Instance> instance) : + _instance(move(instance)) { } void - setSubscriber(const SubscriberPtr& subscriber) + setSubscriber(shared_ptr<Subscriber> subscriber) { - _subscriber = subscriber; + _subscriber = move(subscriber); } - virtual bool - ice_invoke(const pair<const Ice::Byte*, const Ice::Byte*>& inParams, + bool + ice_invoke(pair<const Ice::Byte*, const Ice::Byte*> inParams, vector<Ice::Byte>&, - const Ice::Current& current) + const Ice::Current& current) override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); - EventDataPtr event = new EventData( - current.operation, - current.mode, - Ice::ByteSeq(), - current.ctx); + EventData event = { current.operation, current.mode, Ice::ByteSeq(), current.ctx }; - // - // COMPILERBUG: gcc 4.0.1 doesn't like this. - // - //event->data.swap(Ice::ByteSeq(inParams.first, inParams.second)); Ice::ByteSeq data(inParams.first, inParams.second); - event->data.swap(data); + event.data.swap(data); EventDataSeq e; - e.push_back(event); - _subscriber->queue(false, e); + e.push_back(move(event)); + _subscriber->queue(false, move(e)); return true; } private: - const InstancePtr _instance; - /*const*/ SubscriberPtr _subscriber; + const shared_ptr<Instance> _instance; + shared_ptr<Subscriber> _subscriber; }; -typedef IceUtil::Handle<PerSubscriberPublisherI> PerSubscriberPublisherIPtr; IceStorm::Instrumentation::SubscriberState toSubscriberState(Subscriber::SubscriberState s) @@ -76,15 +67,15 @@ toSubscriberState(Subscriber::SubscriberState s) switch(s) { case Subscriber::SubscriberStateOnline: - return IceStorm::Instrumentation::SubscriberStateOnline; + return IceStorm::Instrumentation::SubscriberState::SubscriberStateOnline; case Subscriber::SubscriberStateOffline: - return IceStorm::Instrumentation::SubscriberStateOffline; + return IceStorm::Instrumentation::SubscriberState::SubscriberStateOffline; case Subscriber::SubscriberStateError: case Subscriber::SubscriberStateReaped: - return IceStorm::Instrumentation::SubscriberStateError; + return IceStorm::Instrumentation::SubscriberState::SubscriberStateError; default: assert(false); - return IceStorm::Instrumentation::SubscriberStateError; + return IceStorm::Instrumentation::SubscriberState::SubscriberStateError; } } @@ -94,231 +85,64 @@ toSubscriberState(Subscriber::SubscriberState s) namespace { -class SubscriberBatch : public Subscriber -{ -public: - - SubscriberBatch(const InstancePtr&, const SubscriberRecord&, const Ice::ObjectPrx&, int, const Ice::ObjectPrx&); - - virtual void flush(); - - void exception(const Ice::Exception& ex) - { - error(false, ex); - } - - void doFlush(); - void sent(bool); - -private: - - const Ice::ObjectPrx _obj; - const IceUtil::Time _interval; -}; -typedef IceUtil::Handle<SubscriberBatch> SubscriberBatchPtr; - -class SubscriberOneway : public Subscriber -{ -public: - - SubscriberOneway(const InstancePtr&, const SubscriberRecord&, const Ice::ObjectPrx&, int, const Ice::ObjectPrx&); - - virtual void flush(); - - void exception(const Ice::Exception& ex) - { - error(true, ex); - } - void sent(bool); - -private: - - const Ice::ObjectPrx _obj; -}; -typedef IceUtil::Handle<SubscriberOneway> SubscriberOnewayPtr; - -class SubscriberTwoway : public Subscriber +class SubscriberOneway final : public Subscriber { public: - SubscriberTwoway(const InstancePtr&, const SubscriberRecord&, const Ice::ObjectPrx&, int, int, - const Ice::ObjectPrx&); + SubscriberOneway(const shared_ptr<Instance>&, const SubscriberRecord&, + const shared_ptr<Ice::ObjectPrx>&, int, shared_ptr<Ice::ObjectPrx>); - virtual void flush(); + void flush() override; + void sentAsynchronously(); private: - const Ice::ObjectPrx _obj; + const shared_ptr<Ice::ObjectPrx> _obj; }; -class SubscriberLink : public Subscriber +class SubscriberTwoway final : public Subscriber { public: - SubscriberLink(const InstancePtr&, const SubscriberRecord&); + SubscriberTwoway(const shared_ptr<Instance>&, const SubscriberRecord&, const shared_ptr<Ice::ObjectPrx>&, int, int, + shared_ptr<Ice::ObjectPrx>); - virtual void flush(); + void flush() override; private: - const TopicLinkPrx _obj; + const shared_ptr<Ice::ObjectPrx> _obj; }; -class FlushTimerTask : public IceUtil::TimerTask +class SubscriberLink final : public Subscriber { public: - FlushTimerTask(const SubscriberBatchPtr& subscriber) : - _subscriber(subscriber) - { - } + SubscriberLink(const shared_ptr<Instance>&, const SubscriberRecord&); - virtual void - runTimerTask() - { - _subscriber->doFlush(); - } + void flush() override; private: - const SubscriberBatchPtr _subscriber; + const shared_ptr<TopicLinkPrx> _obj; }; } -SubscriberBatch::SubscriberBatch( - const InstancePtr& instance, - const SubscriberRecord& rec, - const Ice::ObjectPrx& proxy, - int retryCount, - const Ice::ObjectPrx& obj) : - Subscriber(instance, rec, proxy, retryCount, 1), - _obj(obj), - _interval(instance->flushInterval()) -{ -} - -void -SubscriberBatch::flush() -{ - if(_state != SubscriberStateOnline || _events.empty()) - { - return; - } - - if(_outstanding == 0) - { - ++_outstanding; - _instance->batchFlusher()->schedule(new FlushTimerTask(this), _interval); - } -} - -void -SubscriberBatch::doFlush() -{ - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); - - // - // If the subscriber isn't online we're done. - // - if(_state != SubscriberStateOnline) - { - return; - } - - EventDataSeq v; - v.swap(_events); - assert(!v.empty()); - - if(_observer) - { - _outstandingCount = static_cast<Ice::Int>(v.size()); - _observer->outstanding(_outstandingCount); - } - - try - { - vector<Ice::Byte> dummy; - for(EventDataSeq::const_iterator p = v.begin(); p != v.end(); ++p) - { - _obj->ice_invoke((*p)->op, (*p)->mode, (*p)->data, dummy, (*p)->context); - } - - Ice::AsyncResultPtr result = _obj->begin_ice_flushBatchRequests( - Ice::newCallback_Object_ice_flushBatchRequests(this, - &SubscriberBatch::exception, - &SubscriberBatch::sent)); - if(result->sentSynchronously()) - { - --_outstanding; - assert(_outstanding == 0); - if(_observer) - { - _observer->delivered(_outstandingCount); - } - } - } - catch(const Ice::Exception& ex) - { - error(false, ex); - return; - } - - if(_events.empty() && _outstanding == 0 && _shutdown) - { - _lock.notify(); - } - - // This is significantly faster than the async version, but it can - // block the calling thread. Bad news! - - //_obj->ice_flushBatchRequests(); -} - -void -SubscriberBatch::sent(bool sentSynchronously) -{ - if(sentSynchronously) - { - return; - } - - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); - - // Decrement the _outstanding count. - --_outstanding; - assert(_outstanding == 0); - if(_observer) - { - _observer->delivered(_outstandingCount); - } - - if(_events.empty() && _outstanding == 0 && _shutdown) - { - _lock.notify(); - } - else if(!_events.empty()) - { - flush(); - } - -} - -SubscriberOneway::SubscriberOneway( - const InstancePtr& instance, - const SubscriberRecord& rec, - const Ice::ObjectPrx& proxy, - int retryCount, - const Ice::ObjectPrx& obj) : +SubscriberOneway::SubscriberOneway(const shared_ptr<Instance>& instance, + const SubscriberRecord& rec, + const shared_ptr<Ice::ObjectPrx>& proxy, + int retryCount, + shared_ptr<Ice::ObjectPrx> obj) : Subscriber(instance, rec, proxy, retryCount, 5), - _obj(obj) + _obj(move(obj)) { } void SubscriberOneway::flush() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); // // If the subscriber isn't online we're done. @@ -335,8 +159,8 @@ SubscriberOneway::flush() // Dequeue the head event, count one more outstanding AMI // request. // - EventDataPtr e = _events.front(); - _events.erase(_events.begin()); + EventData e = move(_events.front()); + _events.pop_front(); if(_observer) { _observer->outstanding(1); @@ -344,11 +168,35 @@ SubscriberOneway::flush() try { - Ice::AsyncResultPtr result = _obj->begin_ice_invoke( - e->op, e->mode, e->data, e->context, Ice::newCallback_Object_ice_invoke(this, - &SubscriberOneway::exception, - &SubscriberOneway::sent)); - if(!result->sentSynchronously()) + auto self = static_pointer_cast<SubscriberOneway>(shared_from_this()); + auto isSent = make_shared<promise<bool>>(); + auto future = isSent->get_future(); + + _obj->ice_invokeAsync(e.op, e.mode, e.data, nullptr, + [self](exception_ptr ex) + { + self->error(true, ex); + }, + [self, isSent](bool sentSynchronously) + { + isSent->set_value(sentSynchronously); + if(!sentSynchronously) + { + self->sentAsynchronously(); + } + }, + e.context); + + // + // Check if the request is (or potentially was) sent asynchronously + // + // If the request was sent synchronously then the isSent promise will have been set during the call + // to ice_invokeAsync (sent callback is called immediately after sending from the current thread). + // + // Otherwise if the request was sent asynchronously but quick enough so that the isSent promise is already + // fulfilled, we need to verify the sent callback's sentSynchronously value + // + if(future.wait_for(0s) != future_status::ready || future.get() == false) { ++_outstanding; } @@ -357,28 +205,23 @@ SubscriberOneway::flush() _observer->delivered(1); } } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - error(true, ex); + error(false, current_exception()); return; } } if(_events.empty() && _outstanding == 0 && _shutdown) { - _lock.notify(); + _condVar.notify_one(); } } void -SubscriberOneway::sent(bool sentSynchronously) +SubscriberOneway::sentAsynchronously() { - if(sentSynchronously) - { - return; - } - - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); // Decrement the _outstanding count. --_outstanding; @@ -390,7 +233,7 @@ SubscriberOneway::sent(bool sentSynchronously) if(_events.empty() && _outstanding == 0 && _shutdown) { - _lock.notify(); + _condVar.notify_one(); } else if(_outstanding <= 0 && !_events.empty()) { @@ -398,22 +241,21 @@ SubscriberOneway::sent(bool sentSynchronously) } } -SubscriberTwoway::SubscriberTwoway( - const InstancePtr& instance, - const SubscriberRecord& rec, - const Ice::ObjectPrx& proxy, - int retryCount, - int maxOutstanding, - const Ice::ObjectPrx& obj) : +SubscriberTwoway::SubscriberTwoway(const shared_ptr<Instance>& instance, + const SubscriberRecord& rec, + const shared_ptr<Ice::ObjectPrx>& proxy, + int retryCount, + int maxOutstanding, + shared_ptr<Ice::ObjectPrx> obj) : Subscriber(instance, rec, proxy, retryCount, maxOutstanding), - _obj(obj) + _obj(move(obj)) { } void SubscriberTwoway::flush() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); // // If the subscriber isn't online we're done. @@ -430,9 +272,11 @@ SubscriberTwoway::flush() // Dequeue the head event, count one more outstanding AMI // request. // - EventDataPtr e = _events.front(); - _events.erase(_events.begin()); + EventData e = move(_events.front()); + _events.pop_front(); + ++_outstanding; + if(_observer) { _observer->outstanding(1); @@ -440,12 +284,21 @@ SubscriberTwoway::flush() try { - _obj->begin_ice_invoke(e->op, e->mode, e->data, e->context, - Ice::newCallback(static_cast<Subscriber*>(this), &Subscriber::completed)); + auto self = static_pointer_cast<SubscriberTwoway>(shared_from_this()); + _obj->ice_invokeAsync(e.op, e.mode, e.data, + [self](bool, vector<Ice::Byte>) + { + self->completed(); + }, + [self](exception_ptr ex) + { + self->error(true, ex); + }, + nullptr, e.context); } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - error(true, ex); + error(true, current_exception()); return; } } @@ -454,18 +307,18 @@ SubscriberTwoway::flush() namespace { -SubscriberLink::SubscriberLink( - const InstancePtr& instance, - const SubscriberRecord& rec) : +SubscriberLink::SubscriberLink(const shared_ptr<Instance>& instance, + const SubscriberRecord& rec) : Subscriber(instance, rec, 0, -1, 1), - _obj(TopicLinkPrx::uncheckedCast(rec.obj->ice_collocationOptimized(false)->ice_timeout(instance->sendTimeout()))) + _obj(Ice::uncheckedCast<TopicLinkPrx>( + rec.obj->ice_collocationOptimized(false)->ice_timeout(static_cast<int>(instance->sendTimeout().count())))) { } void SubscriberLink::flush() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); if(_state != SubscriberStateOnline || _outstanding > 0) { @@ -475,16 +328,23 @@ SubscriberLink::flush() EventDataSeq v; v.swap(_events); - EventDataSeq::iterator p = v.begin(); + auto p = v.begin(); while(p != v.end()) { if(_rec.cost != 0) { int cost = 0; - Ice::Context::const_iterator q = (*p)->context.find("cost"); - if(q != (*p)->context.end()) + auto q = p->context.find("cost"); + if(q != p->context.end()) { - cost = atoi(q->second.c_str()); + try + { + cost = stoi(q->second); + } + catch(const std::invalid_argument&) + { + cost = 0; + } } if(cost > _rec.cost) { @@ -502,39 +362,48 @@ SubscriberLink::flush() ++_outstanding; if(_observer) { - _outstandingCount = static_cast<Ice::Int>(v.size()); + _outstandingCount = static_cast<int>(v.size()); _observer->outstanding(_outstandingCount); } - _obj->begin_forward(v, Ice::newCallback(static_cast<Subscriber*>(this), &Subscriber::completed)); + + auto self = static_pointer_cast<SubscriberLink>(shared_from_this()); + _obj->forwardAsync(v, + [self] + { + self->completed(); + }, + [self](exception_ptr ex) + { + self->error(true, ex); + }); } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - error(true, ex); + error(true, current_exception()); } } } } -SubscriberPtr -Subscriber::create( - const InstancePtr& instance, - const SubscriberRecord& rec) +shared_ptr<Subscriber> +Subscriber::create(const shared_ptr<Instance>& instance, + const SubscriberRecord& rec) { if(rec.link) { - return new SubscriberLink(instance, rec); + return make_shared<SubscriberLink>(instance, rec); } else { - PerSubscriberPublisherIPtr per = new PerSubscriberPublisherI(instance); + auto per = make_shared<PerSubscriberPublisherI>(instance); Ice::Identity perId; perId.category = instance->instanceName(); perId.name = "topic." + rec.topicName + ".publish." + instance->communicator()->identityToString(rec.obj->ice_getIdentity()); - Ice::ObjectPrx proxy = instance->publishAdapter()->add(per, perId); - TraceLevelsPtr traceLevels = instance->traceLevels(); - SubscriberPtr subscriber; + auto proxy = instance->publishAdapter()->add(per, perId); + auto traceLevels = instance->traceLevels(); + shared_ptr<Subscriber> subscriber; try { @@ -559,10 +428,10 @@ Subscriber::create( // // Override the timeout. // - Ice::ObjectPrx newObj; + shared_ptr<Ice::ObjectPrx> newObj; try { - newObj = rec.obj->ice_timeout(instance->sendTimeout()); + newObj = rec.obj->ice_timeout(static_cast<int>(instance->sendTimeout().count())); } catch(const Ice::FixedProxyException&) { @@ -598,26 +467,33 @@ Subscriber::create( newObj = newObj->ice_connectionCached(connectionCached > 0); } + if(newObj->ice_isBatchOneway()) + { + // Use Oneway in case of Batch Oneway + newObj = newObj->ice_oneway(); + } + else if(newObj->ice_isBatchDatagram()) + { + // Use Datagram in case of Batch Datagram + newObj = newObj->ice_datagram(); + } + if(reliability == "ordered") { if(!newObj->ice_isTwoway()) { throw BadQoS("ordered reliability requires a twoway proxy"); } - subscriber = new SubscriberTwoway(instance, rec, proxy, retryCount, 1, newObj); + subscriber = make_shared<SubscriberTwoway>(instance, rec, proxy, retryCount, 1, newObj); } else if(newObj->ice_isOneway() || newObj->ice_isDatagram()) { - subscriber = new SubscriberOneway(instance, rec, proxy, retryCount, newObj); - } - else if(newObj->ice_isBatchOneway() || newObj->ice_isBatchDatagram()) - { - subscriber = new SubscriberBatch(instance, rec, proxy, retryCount, newObj); + subscriber = make_shared<SubscriberOneway>(instance, rec, proxy, retryCount, newObj); } else //if(newObj->ice_isTwoway()) { assert(newObj->ice_isTwoway()); - subscriber = new SubscriberTwoway(instance, rec, proxy, retryCount, 5, newObj); + subscriber = make_shared<SubscriberTwoway>(instance, rec, proxy, retryCount, 5, newObj); } per->setSubscriber(subscriber); } @@ -631,7 +507,7 @@ Subscriber::create( } } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> Subscriber::proxy() const { return _proxyReplica; @@ -652,7 +528,7 @@ Subscriber::record() const bool Subscriber::queue(bool forwarded, const EventDataSeq& events) { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); // If this is a link subscriber if the set of events were // forwarded from another IceStorm instance then do not queue the @@ -666,7 +542,7 @@ Subscriber::queue(bool forwarded, const EventDataSeq& events) { case SubscriberStateOffline: { - if(IceUtil::Time::now(IceUtil::Time::Monotonic) < _next) + if(chrono::steady_clock::now() < _next) { break; } @@ -686,7 +562,7 @@ Subscriber::queue(bool forwarded, const EventDataSeq& events) { if(_instance->sendQueueSizeMaxPolicy() == Instance::RemoveSubscriber) { - error(false, IceStorm::SendQueueSizeMaxReached(__FILE__, __LINE__)); + error(false, make_exception_ptr(SendQueueSizeMaxReached(__FILE__, __LINE__))); return false; } else // DropEvents @@ -717,7 +593,7 @@ Subscriber::queue(bool forwarded, const EventDataSeq& events) bool Subscriber::reap() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); assert(_state >= SubscriberStateError); if(_state == SubscriberStateError) { @@ -730,7 +606,8 @@ Subscriber::reap() void Subscriber::resetIfReaped() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); + if(_state == SubscriberStateReaped) { setState(SubscriberStateError); @@ -740,7 +617,8 @@ Subscriber::resetIfReaped() bool Subscriber::errored() const { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); + return _state >= SubscriberStateError; } @@ -766,14 +644,43 @@ Subscriber::destroy() } } - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); _observer.detach(); } void -Subscriber::error(bool dec, const Ice::Exception& e) +Subscriber::completed() +{ + lock_guard<recursive_mutex> lg(_mutex); + + // Decrement the _outstanding count. + --_outstanding; + assert(_outstanding >= 0 && _outstanding < _maxOutstanding); + if(_observer) + { + _observer->delivered(_outstandingCount); + } + + // + // A successful response means we're no longer retrying, we're + // back active. + // + _currentRetry = 0; + + if(_events.empty() && _outstanding == 0 && _shutdown) + { + _condVar.notify_one(); + } + else + { + flush(); + } +} + +void +Subscriber::error(bool dec, exception_ptr e) { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); if(dec) { @@ -790,16 +697,38 @@ Subscriber::error(bool dec, const Ice::Exception& e) { if(_shutdown) { - _lock.notify(); + _condVar.notify_one(); } return; } - // A hard error is an ObjectNotExistException or - // NotRegisteredException. - bool hardError = dynamic_cast<const Ice::ObjectNotExistException*>(&e) || - dynamic_cast<const Ice::NotRegisteredException*>(&e) || - dynamic_cast<const IceStorm::SendQueueSizeMaxReached*>(&e); + // A hard error is an ObjectNotExistException, NotRegisteredException, or SendQueueSizeMaxReached + bool hardError; + string what; + try + { + rethrow_exception(e); + } + catch(const Ice::ObjectNotExistException& ex) + { + hardError = true; + what = ex.what(); + } + catch(const Ice::NotRegisteredException& ex) + { + hardError = true; + what = ex.what(); + } + catch(const SendQueueSizeMaxReached& ex) + { + hardError = true; + what = ex.what(); + } + catch(const std::exception& ex) + { + hardError = false; + what = ex.what(); + } // // A twoway subscriber can queue multiple send events and @@ -807,7 +736,7 @@ Subscriber::error(bool dec, const Ice::Exception& e) // replies if we're retrying and its not yet time to process the // next request. // - IceUtil::Time now = IceUtil::Time::now(IceUtil::Time::Monotonic); + auto now = std::chrono::steady_clock::now(); if(!hardError && _state == SubscriberStateOffline && now < _next) { return; @@ -822,7 +751,7 @@ Subscriber::error(bool dec, const Ice::Exception& e) { assert(_state < SubscriberStateError); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(_currentRetry == 0) { Ice::Warning warn(traceLevels->logger); @@ -831,8 +760,8 @@ Subscriber::error(bool dec, const Ice::Exception& e) { warn << " endpoints: " << IceStormInternal::describeEndpoints(_rec.obj); } - warn << " subscriber offline: " << e - << " discarding events: " << _instance->discardInterval() << "s retryCount: " << _retryCount; + warn << " subscriber offline: " << what + << " discarding events: " << _instance->discardInterval().count() << "s retryCount: " << _retryCount; } else { @@ -844,8 +773,8 @@ Subscriber::error(bool dec, const Ice::Exception& e) { out << " endpoints: " << IceStormInternal::describeEndpoints(_rec.obj); } - out << " subscriber offline: " << e - << " discarding events: " << _instance->discardInterval() << "s retry: " + out << " subscriber offline: " << what + << " discarding events: " << _instance->discardInterval().count() << "s retry: " << _currentRetry << "/" << _retryCount; } } @@ -863,7 +792,7 @@ Subscriber::error(bool dec, const Ice::Exception& e) _events.clear(); setState(SubscriberStateError); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->subscriber > 0) { Ice::Trace out(traceLevels->logger, traceLevels->subscriberCat); @@ -872,64 +801,26 @@ Subscriber::error(bool dec, const Ice::Exception& e) { out << " endpoints: " << IceStormInternal::describeEndpoints(_rec.obj); } - out << " subscriber errored out: " << e + out << " subscriber errored out: " << what << " retry: " << _currentRetry << "/" << _retryCount; } } if(_shutdown && _events.empty()) { - _lock.notify(); - } -} - -void -Subscriber::completed(const Ice::AsyncResultPtr& result) -{ - try - { - result->throwLocalException(); - - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); - - // Decrement the _outstanding count. - --_outstanding; - assert(_outstanding >= 0 && _outstanding < _maxOutstanding); - if(_observer) - { - _observer->delivered(_outstandingCount); - } - - // - // A successful response means we're no longer retrying, we're - // back active. - // - _currentRetry = 0; - - if(_events.empty() && _outstanding == 0 && _shutdown) - { - _lock.notify(); - } - else - { - flush(); - } - } - catch(const Ice::LocalException& ex) - { - error(true, ex); + _condVar.notify_one(); } } void Subscriber::shutdown() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + unique_lock<recursive_mutex> lock(_mutex); _shutdown = true; while(_outstanding > 0 && !_events.empty()) { - _lock.wait(); + _condVar.wait(lock); } _observer.detach(); @@ -938,7 +829,8 @@ Subscriber::shutdown() void Subscriber::updateObserver() { - IceUtil::Monitor<IceUtil::RecMutex>::Lock sync(_lock); + lock_guard<recursive_mutex> lg(_mutex); + if(_instance->observer()) { _observer.attach(_instance->observer()->getSubscriberObserver(_instance->serviceName(), @@ -951,18 +843,17 @@ Subscriber::updateObserver() } } -Subscriber::Subscriber( - const InstancePtr& instance, - const SubscriberRecord& rec, - const Ice::ObjectPrx& proxy, - int retryCount, - int maxOutstanding) : - _instance(instance), - _rec(rec), +Subscriber::Subscriber(shared_ptr<Instance> instance, + SubscriberRecord rec, + shared_ptr<Ice::ObjectPrx> proxy, + int retryCount, + int maxOutstanding) : + _instance(move(instance)), + _rec(move(rec)), _retryCount(retryCount), _maxOutstanding(maxOutstanding), - _proxy(proxy), - _proxyReplica(proxy), + _proxy(move(proxy)), + _proxyReplica(_proxy), _shutdown(false), _state(SubscriberStateOnline), _outstanding(0), @@ -971,17 +862,17 @@ Subscriber::Subscriber( { if(_proxy && _instance->publisherReplicaProxy()) { - const_cast<Ice::ObjectPrx&>(_proxyReplica) = + const_cast<shared_ptr<Ice::ObjectPrx>&>(_proxyReplica) = _instance->publisherReplicaProxy()->ice_identity(_proxy->ice_getIdentity()); } if(_instance->observer()) { _observer.attach(_instance->observer()->getSubscriberObserver(_instance->serviceName(), - rec.topicName, - rec.obj, - rec.theQoS, - rec.theTopic, + _rec.topicName, + _rec.obj, + _rec.theQoS, + _rec.theTopic, toSubscriberState(_state), 0)); } @@ -1015,7 +906,7 @@ Subscriber::setState(Subscriber::SubscriberState state) { if(state != _state) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->subscriber > 1) { Ice::Trace out(traceLevels->logger, traceLevels->subscriberCat); @@ -1038,7 +929,7 @@ Subscriber::setState(Subscriber::SubscriberState state) } bool -IceStorm::operator==(const SubscriberPtr& subscriber, const Ice::Identity& id) +IceStorm::operator==(const shared_ptr<Subscriber>& subscriber, const Ice::Identity& id) { return subscriber->id() == id; } diff --git a/cpp/src/IceStorm/Subscriber.h b/cpp/src/IceStorm/Subscriber.h index af5cc721f69..a192d11e0e8 100644 --- a/cpp/src/IceStorm/Subscriber.h +++ b/cpp/src/IceStorm/Subscriber.h @@ -9,24 +9,21 @@ #include <IceStorm/SubscriberRecord.h> #include <IceStorm/Instrumentation.h> #include <Ice/ObserverHelper.h> -#include <IceUtil/RecMutex.h> + +#include<condition_variable> namespace IceStorm { class Instance; -typedef IceUtil::Handle<Instance> InstancePtr; - -class Subscriber; -typedef IceUtil::Handle<Subscriber> SubscriberPtr; -class Subscriber : public IceUtil::Shared +class Subscriber : public std::enable_shared_from_this<Subscriber> { public: - static SubscriberPtr create(const InstancePtr&, const IceStorm::SubscriberRecord&); + static std::shared_ptr<Subscriber> create(const std::shared_ptr<Instance>&, const IceStorm::SubscriberRecord&); - Ice::ObjectPrx proxy() const; // Get the per subscriber object. + std::shared_ptr<Ice::ObjectPrx> proxy() const; // Get the per subscriber object. Ice::Identity id() const; // Return the id of the subscriber. IceStorm::SubscriberRecord record() const; // Get the subscriber record. @@ -39,8 +36,8 @@ public: void destroy(); // To be called by the AMI callbacks only. - void completed(const Ice::AsyncResultPtr&); - void error(bool, const Ice::Exception&); + void completed(); + void error(bool, std::exception_ptr); void shutdown(); @@ -60,17 +57,18 @@ protected: void setState(SubscriberState); - Subscriber(const InstancePtr&, const IceStorm::SubscriberRecord&, const Ice::ObjectPrx&, int, int); + Subscriber(std::shared_ptr<Instance>, IceStorm::SubscriberRecord, std::shared_ptr<Ice::ObjectPrx>, int, int); // Immutable - const InstancePtr _instance; + const std::shared_ptr<Instance> _instance; const IceStorm::SubscriberRecord _rec; // The subscriber record. const int _retryCount; // The retryCount. const int _maxOutstanding; // The maximum number of oustanding events. - const Ice::ObjectPrx _proxy; // The per subscriber object proxy, if any. - const Ice::ObjectPrx _proxyReplica; // The replicated per subscriber object proxy, if any. + const std::shared_ptr<Ice::ObjectPrx> _proxy; // The per subscriber object proxy, if any. + const std::shared_ptr<Ice::ObjectPrx> _proxyReplica; // The replicated per subscriber object proxy, if any. - IceUtil::Monitor<IceUtil::RecMutex> _lock; + mutable std::recursive_mutex _mutex; + std::condition_variable_any _condVar; bool _shutdown; @@ -81,13 +79,13 @@ protected: EventDataSeq _events; // The queue of events to send. // The next time to try sending a new event if we're offline. - IceUtil::Time _next; + std::chrono::steady_clock::time_point _next; int _currentRetry; IceInternal::ObserverHelperT<IceStorm::Instrumentation::SubscriberObserver> _observer; }; -bool operator==(const IceStorm::SubscriberPtr&, const Ice::Identity&); +bool operator==(const std::shared_ptr<IceStorm::Subscriber>&, const Ice::Identity&); bool operator==(const IceStorm::Subscriber&, const IceStorm::Subscriber&); bool operator!=(const IceStorm::Subscriber&, const IceStorm::Subscriber&); bool operator<(const IceStorm::Subscriber&, const IceStorm::Subscriber&); diff --git a/cpp/src/IceStorm/TopicI.cpp b/cpp/src/IceStorm/TopicI.cpp index 480189c6387..5dcaff63153 100644 --- a/cpp/src/IceStorm/TopicI.cpp +++ b/cpp/src/IceStorm/TopicI.cpp @@ -21,7 +21,7 @@ namespace { void -logError(const Ice::CommunicatorPtr& com, const IceDB::LMDBException& ex) +logError(const shared_ptr<Ice::Communicator>& com, const IceDB::LMDBException& ex) { Ice::Error error(com->getLogger()); error << "LMDB error: " << ex; @@ -35,28 +35,24 @@ class PublisherI : public Ice::BlobjectArray { public: - PublisherI(const TopicImplPtr& topic, const PersistentInstancePtr& instance) : - _topic(topic), _instance(instance) + PublisherI(shared_ptr<TopicImpl> topic, shared_ptr<PersistentInstance> instance) : + _topic(move(topic)), _instance(move(instance)) { } - virtual bool - ice_invoke(const pair<const Ice::Byte*, const Ice::Byte*>& inParams, + bool + ice_invoke(pair<const Ice::Byte*, const Ice::Byte*> inParams, Ice::ByteSeq&, - const Ice::Current& current) + const Ice::Current& current) override { // The publish call does a cached read. - EventDataPtr event = new EventData(current.operation, current.mode, Ice::ByteSeq(), current.ctx); + EventData event = { current.operation, current.mode, Ice::ByteSeq(), current.ctx }; - // - // COMPILERBUG: gcc 4.0.1 doesn't like this. - // - //event->data.swap(Ice::ByteSeq(inParams.first, inParams.second)); Ice::ByteSeq data(inParams.first, inParams.second); - event->data.swap(data); + event.data = move(data); EventDataSeq v; - v.push_back(event); + v.push_back(move(event)); _topic->publish(false, v); return true; @@ -64,8 +60,8 @@ public: private: - const TopicImplPtr _topic; - const PersistentInstancePtr _instance; + const shared_ptr<TopicImpl> _topic; + const shared_ptr<PersistentInstance> _instance; }; // @@ -76,66 +72,66 @@ class TopicLinkI : public TopicLink { public: - TopicLinkI(const TopicImplPtr& impl, const PersistentInstancePtr& instance) : - _impl(impl), _instance(instance) + TopicLinkI(shared_ptr<TopicImpl> impl, shared_ptr<PersistentInstance> instance) : + _impl(move(impl)), _instance(move(instance)) { } - virtual void - forward(const EventDataSeq& v, const Ice::Current& /*current*/) + void + forward(EventDataSeq v, const Ice::Current&) override { // The publish call does a cached read. - _impl->publish(true, v); + _impl->publish(true, move(v)); } private: - const TopicImplPtr _impl; - const PersistentInstancePtr _instance; + const shared_ptr<TopicImpl> _impl; + const shared_ptr<PersistentInstance> _instance; }; class TopicI : public TopicInternal { public: - TopicI(const TopicImplPtr& impl, const PersistentInstancePtr& instance) : - _impl(impl), _instance(instance) + TopicI(shared_ptr<TopicImpl> impl, shared_ptr<PersistentInstance> instance) : + _impl(move(impl)), _instance(move(instance)) { } - virtual string getName(const Ice::Current&) const + string getName(const Ice::Current&) const override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); return _impl->getName(); } - virtual Ice::ObjectPrx getPublisher(const Ice::Current&) const + shared_ptr<Ice::ObjectPrx> getPublisher(const Ice::Current&) const override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); return _impl->getPublisher(); } - virtual Ice::ObjectPrx getNonReplicatedPublisher(const Ice::Current&) const + shared_ptr<Ice::ObjectPrx> getNonReplicatedPublisher(const Ice::Current&) const override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); return _impl->getNonReplicatedPublisher(); } - virtual Ice::ObjectPrx subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj, - const Ice::Current& current) + shared_ptr<Ice::ObjectPrx> subscribeAndGetPublisher(QoS qos, shared_ptr<Ice::ObjectPrx> obj, + const Ice::Current& current) override { while(true) { Ice::Long generation = -1; - TopicPrx master = getMasterFor(current, generation, __FILE__, __LINE__); + auto master = getMasterFor(current, generation, __FILE__, __LINE__); if(master) { try { - return master->subscribeAndGetPublisher(qos, obj); + return master->subscribeAndGetPublisher(move(qos), move(obj)); } catch(const Ice::ConnectFailedException&) { @@ -151,22 +147,22 @@ public: else { FinishUpdateHelper unlock(_instance->node()); - return _impl->subscribeAndGetPublisher(qos, obj); + return _impl->subscribeAndGetPublisher(move(qos), move(obj)); } } } - virtual void unsubscribe(const Ice::ObjectPrx& subscriber, const Ice::Current& current) + void unsubscribe(shared_ptr<Ice::ObjectPrx> subscriber, const Ice::Current& current) override { while(true) { Ice::Long generation = -1; - TopicPrx master = getMasterFor(current, generation, __FILE__, __LINE__); + auto master = getMasterFor(current, generation, __FILE__, __LINE__); if(master) { try { - master->unsubscribe(subscriber); + master->unsubscribe(move(subscriber)); } catch(const Ice::ConnectFailedException&) { @@ -182,22 +178,22 @@ public: else { FinishUpdateHelper unlock(_instance->node()); - _impl->unsubscribe(subscriber); + _impl->unsubscribe(move(subscriber)); } break; } } - virtual TopicLinkPrx getLinkProxy(const Ice::Current&) + shared_ptr<TopicLinkPrx> getLinkProxy(const Ice::Current&) override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); return _impl->getLinkProxy(); } - virtual void reap(const Ice::IdentitySeq& ids, const Ice::Current& /*current*/) + void reap(Ice::IdentitySeq ids, const Ice::Current&) override { - NodeIPtr node = _instance->node(); + auto node = _instance->node(); if(!node->updateMaster(__FILE__, __LINE__)) { throw ReapWouldBlock(); @@ -206,17 +202,17 @@ public: _impl->reap(ids); } - virtual void link(const TopicPrx& topic, Ice::Int cost, const Ice::Current& current) + void link(shared_ptr<TopicPrx> topic, int cost, const Ice::Current& current) override { while(true) { Ice::Long generation = -1; - TopicPrx master = getMasterFor(current, generation, __FILE__, __LINE__); + auto master = getMasterFor(current, generation, __FILE__, __LINE__); if(master) { try { - master->link(topic, cost); + master->link(move(topic), cost); } catch(const Ice::ConnectFailedException&) { @@ -232,23 +228,23 @@ public: else { FinishUpdateHelper unlock(_instance->node()); - _impl->link(topic, cost); + _impl->link(move(topic), cost); } break; } } - virtual void unlink(const TopicPrx& topic, const Ice::Current& current) + void unlink(shared_ptr<TopicPrx> topic, const Ice::Current& current) override { while(true) { Ice::Long generation = -1; - TopicPrx master = getMasterFor(current, generation, __FILE__, __LINE__); + auto master = getMasterFor(current, generation, __FILE__, __LINE__); if(master) { try { - master->unlink(topic); + master->unlink(move(topic)); } catch(const Ice::ConnectFailedException&) { @@ -264,30 +260,30 @@ public: else { FinishUpdateHelper unlock(_instance->node()); - _impl->unlink(topic); + _impl->unlink(move(topic)); } break; } } - virtual LinkInfoSeq getLinkInfoSeq(const Ice::Current&) const + LinkInfoSeq getLinkInfoSeq(const Ice::Current&) const override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); return _impl->getLinkInfoSeq(); } - virtual Ice::IdentitySeq getSubscribers(const Ice::Current&) const + Ice::IdentitySeq getSubscribers(const Ice::Current&) const override { return _impl->getSubscribers(); } - virtual void destroy(const Ice::Current& current) + void destroy(const Ice::Current& current) override { while(true) { Ice::Long generation = -1; - TopicPrx master = getMasterFor(current, generation, __FILE__, __LINE__); + auto master = getMasterFor(current, generation, __FILE__, __LINE__); if(master) { try @@ -316,29 +312,72 @@ public: private: - TopicPrx getMasterFor(const Ice::Current& cur, Ice::Long& generation, const char* file, int line) const + shared_ptr<TopicPrx> getMasterFor(const Ice::Current& cur, Ice::Long& generation, const char* file, int line) const { - NodeIPtr node = _instance->node(); - Ice::ObjectPrx master; + auto node = _instance->node(); + shared_ptr<Ice::ObjectPrx> master; if(node) { master = _instance->node()->startUpdate(generation, file, line); } - return (master) ? TopicPrx::uncheckedCast(master->ice_identity(cur.id)) : TopicPrx(); + return master ? Ice::uncheckedCast<TopicPrx>(master->ice_identity(cur.id)) : nullptr; } - const TopicImplPtr _impl; - const PersistentInstancePtr _instance; + const shared_ptr<TopicImpl> _impl; + const shared_ptr<PersistentInstance> _instance; }; } -TopicImpl::TopicImpl( - const PersistentInstancePtr& instance, - const string& name, - const Ice::Identity& id, - const SubscriberRecordSeq& subscribers) : - _instance(instance), +shared_ptr<TopicImpl> +TopicImpl::create(shared_ptr<PersistentInstance> instance, + const string& name, + const Ice::Identity& id, + const SubscriberRecordSeq& subscribers) +{ + shared_ptr<TopicImpl> topicImpl(new TopicImpl(instance, name, id, subscribers)); + + topicImpl->_servant = make_shared<TopicI>(topicImpl, instance); + // + // Create a servant per topic to receive event data. If the + // category is empty then we are in backwards compatibility + // mode. In this case the servant's identity is + // category=<topicname>, name=publish, otherwise the name is + // <instancename>/<topicname>.publish. The same applies to the + // link proxy. + // + // Activate the object and save a reference to give to publishers. + // + Ice::Identity pubid; + Ice::Identity linkid; + if(id.category.empty()) + { + pubid.category = name; + pubid.name = "publish"; + linkid.category = name; + linkid.name = "link"; + } + else + { + pubid.category = id.category; + pubid.name = name + ".publish"; + linkid.category = id.category; + linkid.name = name + ".link"; + } + + auto publisher = make_shared<PublisherI>(topicImpl, instance); + topicImpl->_publisherPrx = instance->publishAdapter()->add(publisher, pubid); + auto topicLink = make_shared<TopicLinkI>(topicImpl, instance); + topicImpl->_linkPrx = Ice::uncheckedCast<TopicLinkPrx>(instance->publishAdapter()->add(topicLink, linkid)); + + return topicImpl; +} + +TopicImpl::TopicImpl(shared_ptr<PersistentInstance> instance, + const string& name, + const Ice::Identity& id, + const SubscriberRecordSeq& subscribers) : + _instance(move(instance)), _name(name), _id(id), _destroyed(false), @@ -347,57 +386,20 @@ TopicImpl::TopicImpl( { try { - __setNoDelete(true); - - // TODO: If we want to improve the performance of the - // non-replicated case we could allocate a null-topic impl here. - _servant = new TopicI(this, instance); - - // - // Create a servant per topic to receive event data. If the - // category is empty then we are in backwards compatibility - // mode. In this case the servant's identity is - // category=<topicname>, name=publish, otherwise the name is - // <instancename>/<topicname>.publish. The same applies to the - // link proxy. - // - // Activate the object and save a reference to give to publishers. - // - Ice::Identity pubid; - Ice::Identity linkid; - if(id.category.empty()) - { - pubid.category = _name; - pubid.name = "publish"; - linkid.category = _name; - linkid.name = "link"; - } - else - { - pubid.category = id.category; - pubid.name = _name + ".publish"; - linkid.category = id.category; - linkid.name = _name + ".link"; - } - - _publisherPrx = _instance->publishAdapter()->add(new PublisherI(this, instance), pubid); - _linkPrx = TopicLinkPrx::uncheckedCast( - _instance->publishAdapter()->add(new TopicLinkI(this, instance), linkid)); - // // Re-establish subscribers. // - for(SubscriberRecordSeq::const_iterator p = subscribers.begin(); p != subscribers.end(); ++p) + for(const auto& subscriber : subscribers) { - Ice::Identity ident = p->obj->ice_getIdentity(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + Ice::Identity ident = subscriber.obj->ice_getIdentity(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); out << _name << " recreate " << _instance->communicator()->identityToString(ident); if(traceLevels->topic > 1) { - out << " endpoints: " << IceStormInternal::describeEndpoints(p->obj); + out << " endpoints: " << IceStormInternal::describeEndpoints(subscriber.obj); } } @@ -407,8 +409,7 @@ TopicImpl::TopicImpl( // Create the subscriber object add it to the set of // subscribers. // - SubscriberPtr subscriber = Subscriber::create(_instance, *p); - _subscribers.push_back(subscriber); + _subscribers.push_back(Subscriber::create(_instance, subscriber)); } catch(const Ice::Exception& ex) { @@ -416,7 +417,7 @@ TopicImpl::TopicImpl( out << _name << " recreate " << _instance->communicator()->identityToString(ident); if(traceLevels->topic > 1) { - out << " endpoints: " << IceStormInternal::describeEndpoints(p->obj); + out << " endpoints: " << IceStormInternal::describeEndpoints(subscriber.obj); } out << " failed: " << ex; } @@ -424,16 +425,14 @@ TopicImpl::TopicImpl( if(_instance->observer()) { - _observer.attach(_instance->observer()->getTopicObserver(_instance->serviceName(), _name, 0)); + _observer.attach(_instance->observer()->getTopicObserver(_instance->serviceName(), _name, nullptr)); } } - catch(...) + catch(const std::exception&) { shutdown(); - __setNoDelete(false); throw; } - __setNoDelete(false); } string @@ -443,7 +442,7 @@ TopicImpl::getName() const return _name; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> TopicImpl::getPublisher() const { // Immutable @@ -454,7 +453,7 @@ TopicImpl::getPublisher() const return _publisherPrx; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> TopicImpl::getNonReplicatedPublisher() const { // If there is an adapter id configured then we're using icegrid @@ -472,10 +471,10 @@ TopicImpl::getNonReplicatedPublisher() const namespace { void -trace(Ice::Trace& out, const PersistentInstancePtr& instance, const vector<SubscriberPtr>& s) +trace(Ice::Trace& out, const shared_ptr<PersistentInstance>& instance, const vector<shared_ptr<Subscriber>>& s) { out << '['; - for(vector<SubscriberPtr>::const_iterator p = s.begin(); p != s.end(); ++p) + for(auto p = s.cbegin(); p != s.cend(); ++p) { if(p != s.begin()) { @@ -487,12 +486,12 @@ trace(Ice::Trace& out, const PersistentInstancePtr& instance, const vector<Subsc } } -Ice::ObjectPrx -TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) +shared_ptr<Ice::ObjectPrx> +TopicImpl::subscribeAndGetPublisher(QoS qos, shared_ptr<Ice::ObjectPrx> obj) { if(!obj) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -500,9 +499,9 @@ TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) } throw InvalidSubscriber("subscriber is a null proxy"); } - Ice::Identity id = obj->ice_getIdentity(); + auto id = obj->ice_getIdentity(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -525,7 +524,7 @@ TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) } } - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); SubscriberRecord record; record.id = id; @@ -535,15 +534,14 @@ TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) record.link = false; record.cost = 0; - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), record.id); - if(p != _subscribers.end()) + if(find(_subscribers.begin(), _subscribers.end(), record.id) != _subscribers.end()) { throw AlreadySubscribed(); } LogUpdate llu; - SubscriberPtr subscriber = Subscriber::create(_instance, record); + auto subscriber = Subscriber::create(_instance, record); try { IceDB::ReadWriteTxn txn(_instance->dbEnv()); @@ -572,9 +570,9 @@ TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) } void -TopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber) +TopicImpl::unsubscribe(const shared_ptr<Ice::ObjectPrx>& subscriber) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(!subscriber) { if(traceLevels->topic > 0) @@ -599,31 +597,32 @@ TopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber) } } - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); + Ice::IdentitySeq ids; ids.push_back(id); removeSubscribers(ids); } -TopicLinkPrx +shared_ptr<TopicLinkPrx> TopicImpl::getLinkProxy() { // immutable if(_instance->publisherReplicaProxy()) { - return TopicLinkPrx::uncheckedCast(_instance->publisherReplicaProxy()->ice_identity( + return Ice::uncheckedCast<TopicLinkPrx>(_instance->publisherReplicaProxy()->ice_identity( _linkPrx->ice_getIdentity())); } return _linkPrx; } void -TopicImpl::link(const TopicPrx& topic, Ice::Int cost) +TopicImpl::link(const shared_ptr<TopicPrx>& topic, int cost) { - TopicInternalPrx internal = TopicInternalPrx::uncheckedCast(topic); - TopicLinkPrx link = internal->getLinkProxy(); + auto internal = Ice::uncheckedCast<TopicInternalPrx>(topic); + auto link = internal->getLinkProxy(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -631,7 +630,7 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) << " cost " << cost; } - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); Ice::Identity id = topic->ice_getIdentity(); @@ -643,8 +642,7 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) record.link = true; record.cost = cost; - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), record.id); - if(p != _subscribers.end()) + if(find(_subscribers.begin(), _subscribers.end(), record.id) != _subscribers.end()) { string name = IceStormInternal::identityToTopicName(id); throw LinkExists(name); @@ -652,7 +650,7 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) LogUpdate llu; - SubscriberPtr subscriber = Subscriber::create(_instance, record); + auto subscriber = Subscriber::create(_instance, record); try { @@ -680,9 +678,10 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) } void -TopicImpl::unlink(const TopicPrx& topic) +TopicImpl::unlink(const shared_ptr<TopicPrx>& topic) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -690,11 +689,12 @@ TopicImpl::unlink(const TopicPrx& topic) Ice::Identity id = topic->ice_getIdentity(); - vector<SubscriberPtr>::const_iterator p = find(_subscribers.begin(), _subscribers.end(), id); - if(p == _subscribers.end()) + auto traceLevels = _instance->traceLevels(); + + if(find(_subscribers.begin(), _subscribers.end(), id) == _subscribers.end()) { string name = IceStormInternal::identityToTopicName(id); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -704,7 +704,6 @@ TopicImpl::unlink(const TopicPrx& topic) throw NoSuchLink(name); } - TraceLevelsPtr traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -719,9 +718,9 @@ TopicImpl::unlink(const TopicPrx& topic) void TopicImpl::reap(const Ice::IdentitySeq& ids) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -742,13 +741,14 @@ TopicImpl::reap(const Ice::IdentitySeq& ids) void TopicImpl::shutdown() { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); + _servant = 0; // Shutdown each subscriber. This waits for the event queues to drain. - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - (*p)->shutdown(); + subscriber->shutdown(); } _observer.detach(); @@ -757,13 +757,13 @@ TopicImpl::shutdown() LinkInfoSeq TopicImpl::getLinkInfoSeq() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); LinkInfoSeq seq; - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - SubscriberRecord record = (*p)->record(); - if(record.link && !(*p)->errored()) + SubscriberRecord record = subscriber->record(); + if(record.link && !subscriber->errored()) { LinkInfo info; info.name = IceStormInternal::identityToTopicName(record.theTopic->ice_getIdentity()); @@ -778,12 +778,12 @@ TopicImpl::getLinkInfoSeq() const Ice::IdentitySeq TopicImpl::getSubscribers() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); Ice::IdentitySeq subscribers; - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - subscribers.push_back((*p)->id()); + subscribers.push_back(subscriber->id()); } return subscribers; } @@ -791,7 +791,7 @@ TopicImpl::getSubscribers() const void TopicImpl::destroy() { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); if(_destroyed) { @@ -799,7 +799,7 @@ TopicImpl::destroy() } _destroyed = true; - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -807,7 +807,7 @@ TopicImpl::destroy() } // destroyInternal clears out the topic content. - LogUpdate llu = {0,0}; + LogUpdate llu = { 0,0 }; _instance->observers()->destroyTopic(destroyInternal(llu, true), _name); _observer.detach(); @@ -816,18 +816,18 @@ TopicImpl::destroy() TopicContent TopicImpl::getContent() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); TopicContent content; content.id = _id; - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { // Don't return errored subscribers (subscribers that have // errored out, but not reaped due to a failure with the // master). This means we can avoid the reaping step later. - if(!(*p)->errored()) + if(!subscriber->errored()) { - content.records.push_back((*p)->record()); + content.records.push_back(subscriber->record()); } } return content; @@ -836,7 +836,7 @@ TopicImpl::getContent() const void TopicImpl::update(const SubscriberRecordSeq& records) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); // We do this with two scans. The first runs through the subscribers // that we have and removes those not in the init list. The second @@ -844,7 +844,7 @@ TopicImpl::update(const SubscriberRecordSeq& records) // exist. { - vector<SubscriberPtr>::iterator p = _subscribers.begin(); + auto p = _subscribers.begin(); while(p != _subscribers.end()) { SubscriberRecordSeq::const_iterator q; @@ -871,19 +871,19 @@ TopicImpl::update(const SubscriberRecordSeq& records) } } - for(SubscriberRecordSeq::const_iterator p = records.begin(); p != records.end(); ++p) + for(const auto& record : records) { - vector<SubscriberPtr>::iterator q; + vector<shared_ptr<Subscriber>>::iterator q; for(q = _subscribers.begin(); q != _subscribers.end(); ++q) { - if((*q)->id() == p->id) + if((*q)->id() == record.id) { break; } } if(q == _subscribers.end()) { - SubscriberPtr subscriber = Subscriber::create(_instance, *p); + auto subscriber = Subscriber::create(_instance, record); _subscribers.push_back(subscriber); } } @@ -892,7 +892,8 @@ TopicImpl::update(const SubscriberRecordSeq& records) bool TopicImpl::destroyed() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lg(_subscribersMutex); + return _destroyed; } @@ -903,11 +904,11 @@ TopicImpl::id() const return _id; } -TopicPrx +shared_ptr<TopicPrx> TopicImpl::proxy() const { // immutable - Ice::ObjectPrx prx; + shared_ptr<Ice::ObjectPrx> prx; if(_instance->topicReplicaProxy()) { prx = _instance->topicReplicaProxy()->ice_identity(_id); @@ -916,44 +917,13 @@ TopicImpl::proxy() const { prx = _instance->topicAdapter()->createProxy(_id); } - return TopicPrx::uncheckedCast(prx); -} - -namespace -{ - -class TopicInternalReapCB : public IceUtil::Shared -{ -public: - - TopicInternalReapCB(const PersistentInstancePtr& instance, Ice::Long generation) : - _instance(instance), _generation(generation) - { - } - - virtual void exception(const Ice::Exception& ex) - { - TraceLevelsPtr traceLevels = _instance->traceLevels(); - if(traceLevels->topic > 0) - { - Ice::Trace out(traceLevels->logger, traceLevels->topicCat); - out << "exception when calling `reap' on the master replica: " << ex; - } - _instance->node()->recovery(_generation); - } - -private: - - const PersistentInstancePtr _instance; - const Ice::Long _generation; -}; - + return Ice::uncheckedCast<TopicPrx>(prx); } void TopicImpl::publish(bool forwarded, const EventDataSeq& events) { - TopicInternalPrx masterInternal; + shared_ptr<TopicInternalPrx> masterInternal; Ice::Long generation = -1; Ice::IdentitySeq reap; { @@ -964,9 +934,10 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) // Copy of the subscriber list so that event publishing can occur // in parallel. // - vector<SubscriberPtr> copy; + vector<shared_ptr<Subscriber>> copy; { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lock(_subscribersMutex); + if(_observer) { if(forwarded) @@ -985,11 +956,11 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) // Queue each event, gathering a list of those subscribers that // must be reaped. // - for(vector<SubscriberPtr>::const_iterator p = copy.begin(); p != copy.end(); ++p) + for(const auto& subscriber : copy) { - if(!(*p)->queue(forwarded, events) && (*p)->reap()) + if(!subscriber->queue(forwarded, events) && subscriber->reap()) { - reap.push_back((*p)->id()); + reap.push_back(subscriber->id()); } } @@ -1000,11 +971,11 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) } if(!unlock.getMaster()) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lock(_subscribersMutex); removeSubscribers(reap); return; } - masterInternal = TopicInternalPrx::uncheckedCast(unlock.getMaster()->ice_identity(_id)); + masterInternal = Ice::uncheckedCast<TopicInternalPrx>(unlock.getMaster()->ice_identity(_id)); generation = unlock.generation(); } @@ -1017,16 +988,32 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) // call may raise an exception in the caller (that is directly // call ice_exception) which calls recover() on the node which // would result in a deadlock since the node is locked. - masterInternal->begin_reap(reap, newCallback_TopicInternal_reap(new TopicInternalReapCB(_instance, generation), - &TopicInternalReapCB::exception)); + + masterInternal->reapAsync(reap, nullptr, [instance = _instance, generation](exception_ptr ex) + { + auto traceLevels = instance->traceLevels(); + if(traceLevels->topic > 0) + { + try + { + rethrow_exception(ex); + } + catch(const std::exception& e) + { + Ice::Trace out(traceLevels->logger, traceLevels->topicCat); + out << "exception when calling `reap' on the master replica: " << e; + } + } + instance->node()->recovery(generation); + }); } void TopicImpl::observerAddSubscriber(const LogUpdate& llu, const SubscriberRecord& record) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lock(_subscribersMutex); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -1048,8 +1035,7 @@ TopicImpl::observerAddSubscriber(const LogUpdate& llu, const SubscriberRecord& r out << " llu: " << llu.generation << "/" << llu.iteration; } - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), record.id); - if(p != _subscribers.end()) + if(find(_subscribers.begin(), _subscribers.end(), record.id) != _subscribers.end()) { // If the subscriber is already in the database display a // diagnostic. @@ -1061,7 +1047,7 @@ TopicImpl::observerAddSubscriber(const LogUpdate& llu, const SubscriberRecord& r return; } - SubscriberPtr subscriber = Subscriber::create(_instance, record); + auto subscriber = Subscriber::create(_instance, record); try { IceDB::ReadWriteTxn txn(_instance->dbEnv()); @@ -1089,7 +1075,7 @@ TopicImpl::observerAddSubscriber(const LogUpdate& llu, const SubscriberRecord& r void TopicImpl::observerRemoveSubscriber(const LogUpdate& llu, const Ice::IdentitySeq& ids) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -1105,19 +1091,16 @@ TopicImpl::observerRemoveSubscriber(const LogUpdate& llu, const Ice::IdentitySeq out << " llu: " << llu.generation << "/" << llu.iteration; } - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lock(_subscribersMutex); // First remove from the database. try { IceDB::ReadWriteTxn txn(_instance->dbEnv()); - for(Ice::IdentitySeq::const_iterator id = ids.begin(); id != ids.end(); ++id) + for(const auto& id : ids) { - SubscriberRecordKey key; - key.topic = _id; - key.id = *id; - + SubscriberRecordKey key = { _id, id }; _subscriberMap.del(txn, key); } @@ -1134,9 +1117,9 @@ TopicImpl::observerRemoveSubscriber(const LogUpdate& llu, const Ice::IdentitySeq // Then remove the subscriber from the subscribers list. If the // subscriber had a local failure and was removed from the // subscriber list it could already be gone. That's not a problem. - for(Ice::IdentitySeq::const_iterator id = ids.begin(); id != ids.end(); ++id) + for(const auto& id : ids) { - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), *id); + auto p = find(_subscribers.begin(), _subscribers.end(), id); if(p != _subscribers.end()) { (*p)->destroy(); @@ -1148,7 +1131,7 @@ TopicImpl::observerRemoveSubscriber(const LogUpdate& llu, const Ice::IdentitySeq void TopicImpl::observerDestroyTopic(const LogUpdate& llu) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lock(_subscribersMutex); if(_destroyed) { @@ -1156,7 +1139,7 @@ TopicImpl::observerDestroyTopic(const LogUpdate& llu) } _destroyed = true; - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -1166,7 +1149,7 @@ TopicImpl::observerDestroyTopic(const LogUpdate& llu) destroyInternal(llu, false); } -Ice::ObjectPtr +shared_ptr<Ice::Object> TopicImpl::getServant() const { return _servant; @@ -1175,7 +1158,8 @@ TopicImpl::getServant() const void TopicImpl::updateObserver() { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard<mutex> lock(_subscribersMutex); + if(_instance->observer()) { _observer.attach(_instance->observer()->getTopicObserver(_instance->serviceName(), _name, _observer.get())); @@ -1185,10 +1169,11 @@ TopicImpl::updateObserver() void TopicImpl::updateSubscriberObservers() { - IceUtil::Mutex::Lock sync(_subscribersMutex); - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + lock_guard<mutex> lock(_subscribersMutex); + + for(const auto& subscriber : _subscribers) { - (*p)->updateObserver(); + subscriber->updateObserver(); } } @@ -1243,9 +1228,9 @@ TopicImpl::destroyInternal(const LogUpdate& origLLU, bool master) _instance->topicReaper()->add(_name); // Destroy each of the subscribers. - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - (*p)->destroy(); + subscriber->destroy(); } _subscribers.clear(); @@ -1267,11 +1252,9 @@ TopicImpl::removeSubscribers(const Ice::IdentitySeq& ids) { IceDB::ReadWriteTxn txn(_instance->dbEnv()); - for(Ice::IdentitySeq::const_iterator id = ids.begin(); id != ids.end(); ++id) + for(const auto& id : ids) { - SubscriberRecordKey key; - key.topic = _id; - key.id = *id; + SubscriberRecordKey key = { _id, id }; if(_subscriberMap.del(txn, key)) { @@ -1305,7 +1288,7 @@ TopicImpl::removeSubscribers(const Ice::IdentitySeq& ids) // removed. for(Ice::IdentitySeq::const_iterator id = ids.begin(); id != ids.end(); ++id) { - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), *id); + auto p = find(_subscribers.begin(), _subscribers.end(), *id); if(p != _subscribers.end()) { (*p)->destroy(); diff --git a/cpp/src/IceStorm/TopicI.h b/cpp/src/IceStorm/TopicI.h index 9597fb62558..0bc37d3ae01 100644 --- a/cpp/src/IceStorm/TopicI.h +++ b/cpp/src/IceStorm/TopicI.h @@ -17,25 +17,25 @@ namespace IceStorm // Forward declarations class PersistentInstance; -typedef IceUtil::Handle<PersistentInstance> PersistentInstancePtr; - class Subscriber; -typedef IceUtil::Handle<Subscriber> SubscriberPtr; -class TopicImpl : public IceUtil::Shared +class TopicImpl { public: - TopicImpl(const PersistentInstancePtr&, const std::string&, const Ice::Identity&, const SubscriberRecordSeq&); + static std::shared_ptr<TopicImpl> create(std::shared_ptr<PersistentInstance>, + const std::string&, + const Ice::Identity&, + const SubscriberRecordSeq&); std::string getName() const; - Ice::ObjectPrx getPublisher() const; - Ice::ObjectPrx getNonReplicatedPublisher() const; - Ice::ObjectPrx subscribeAndGetPublisher(const QoS&, const Ice::ObjectPrx&); - void unsubscribe(const Ice::ObjectPrx&); - TopicLinkPrx getLinkProxy(); - void link(const TopicPrx&, Ice::Int); - void unlink(const TopicPrx&); + std::shared_ptr<Ice::ObjectPrx> getPublisher() const; + std::shared_ptr<Ice::ObjectPrx> getNonReplicatedPublisher() const; + std::shared_ptr<Ice::ObjectPrx> subscribeAndGetPublisher(QoS, std::shared_ptr<Ice::ObjectPrx>); + void unsubscribe(const std::shared_ptr<Ice::ObjectPrx>&); + std::shared_ptr<TopicLinkPrx> getLinkProxy(); + void link(const std::shared_ptr<TopicPrx>&, int); + void unlink(const std::shared_ptr<TopicPrx>&); LinkInfoSeq getLinkInfoSeq() const; Ice::IdentitySeq getSubscribers() const; void reap(const Ice::IdentitySeq&); @@ -48,7 +48,7 @@ public: // Internal methods bool destroyed() const; Ice::Identity id() const; - TopicPrx proxy() const; + std::shared_ptr<TopicPrx> proxy() const; void shutdown(); void publish(bool, const EventDataSeq&); @@ -57,33 +57,35 @@ public: void observerRemoveSubscriber(const IceStormElection::LogUpdate&, const Ice::IdentitySeq&); void observerDestroyTopic(const IceStormElection::LogUpdate&); - Ice::ObjectPtr getServant() const; + std::shared_ptr<Ice::Object> getServant() const; void updateObserver(); void updateSubscriberObservers(); private: + TopicImpl(std::shared_ptr<PersistentInstance>, const std::string&, const Ice::Identity&, const SubscriberRecordSeq&); + IceStormElection::LogUpdate destroyInternal(const IceStormElection::LogUpdate&, bool); void removeSubscribers(const Ice::IdentitySeq&); // // Immutable members. // - const Ice::ObjectPrx _publisherReplicaProxy; - const PersistentInstancePtr _instance; + const std::shared_ptr<Ice::ObjectPrx> _publisherReplicaProxy; + const std::shared_ptr<PersistentInstance> _instance; const std::string _name; // The topic name const Ice::Identity _id; // The topic identity IceInternal::ObserverHelperT<IceStorm::Instrumentation::TopicObserver> _observer; - /*const*/ Ice::ObjectPrx _publisherPrx; // The actual publisher proxy. - /*const*/ TopicLinkPrx _linkPrx; // The link proxy. + std::shared_ptr<Ice::ObjectPrx> _publisherPrx; // The actual publisher proxy. + std::shared_ptr<TopicLinkPrx> _linkPrx; // The link proxy. - Ice::ObjectPtr _servant; // The topic implementation servant. + std::shared_ptr<Ice::Object> _servant; // The topic implementation servant. // Mutex protecting the subscribers. - IceUtil::Mutex _subscribersMutex; + mutable std::mutex _subscribersMutex; // // We keep a vector of subscribers since the optimized behaviour @@ -92,7 +94,7 @@ private: // vector/list/map and although there was little difference vector // was the fastest of the three. // - std::vector<SubscriberPtr> _subscribers; + std::vector<std::shared_ptr<Subscriber>> _subscribers; bool _destroyed; // Has this Topic been destroyed? @@ -100,8 +102,6 @@ private: SubscriberMap _subscriberMap; }; -typedef IceUtil::Handle<TopicImpl> TopicImplPtr; - } // End namespace IceStorm #endif diff --git a/cpp/src/IceStorm/TopicManagerI.cpp b/cpp/src/IceStorm/TopicManagerI.cpp index 194a896a934..7215b5c7e21 100644 --- a/cpp/src/IceStorm/TopicManagerI.cpp +++ b/cpp/src/IceStorm/TopicManagerI.cpp @@ -22,32 +22,32 @@ namespace { void -logError(const Ice::CommunicatorPtr& com, const IceDB::LMDBException& ex) +logError(const shared_ptr<Ice::Communicator>& com, const IceDB::LMDBException& ex) { Ice::Error error(com->getLogger()); error << "LMDB error: " << ex; } -class TopicManagerI : public TopicManagerInternal +class TopicManagerI final : public TopicManagerInternal { public: - TopicManagerI(const PersistentInstancePtr& instance, const TopicManagerImplPtr& impl) : - _instance(instance), _impl(impl) + TopicManagerI(shared_ptr<PersistentInstance> instance, shared_ptr<TopicManagerImpl> impl) : + _instance(move(instance)), _impl(move(impl)) { } - virtual TopicPrx create(const string& id, const Ice::Current&) + shared_ptr<TopicPrx> create(string id, const Ice::Current&) override { while(true) { - Ice::Long generation; - TopicManagerPrx master = getMaster(generation, __FILE__, __LINE__); + long long generation; + auto master = getMaster(generation, __FILE__, __LINE__); if(master) { try { - return master->create(id); + return master->create(move(id)); } catch(const Ice::ConnectFailedException&) { @@ -63,26 +63,26 @@ public: else { FinishUpdateHelper unlock(_instance->node()); - return _impl->create(id); + return _impl->create(move(id)); } } } - virtual TopicPrx retrieve(const string& id, const Ice::Current&) const + shared_ptr<TopicPrx> retrieve(string id, const Ice::Current&) override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); - return _impl->retrieve(id); + return _impl->retrieve(move(id)); } - virtual TopicDict retrieveAll(const Ice::Current&) const + TopicDict retrieveAll(const Ice::Current&) override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); return _impl->retrieveAll(); } - virtual NodePrx getReplicaNode(const Ice::Current&) const + shared_ptr<NodePrx> getReplicaNode(const Ice::Current&) const override { // This doesn't require the replication to be running. return _instance->nodeProxy(); @@ -90,49 +90,49 @@ public: private: - TopicManagerPrx getMaster(Ice::Long& generation, const char* file, int line) const + shared_ptr<TopicManagerPrx> getMaster(long long& generation, const char* file, int line) const { - NodeIPtr node = _instance->node(); + auto node = _instance->node(); if(node) { - return TopicManagerPrx::uncheckedCast(node->startUpdate(generation, file, line)); + return Ice::uncheckedCast<TopicManagerPrx>(node->startUpdate(generation, file, line)); } else { - return TopicManagerPrx(); + return nullptr; } } - const PersistentInstancePtr _instance; - const TopicManagerImplPtr _impl; + const shared_ptr<PersistentInstance> _instance; + const shared_ptr<TopicManagerImpl> _impl; }; -class ReplicaObserverI : public ReplicaObserver +class ReplicaObserverI final : public ReplicaObserver { public: - ReplicaObserverI(const PersistentInstancePtr& instance, const TopicManagerImplPtr& impl) : - _instance(instance), - _impl(impl) + ReplicaObserverI(shared_ptr<PersistentInstance> instance, shared_ptr<TopicManagerImpl> impl) : + _instance(move(instance)), + _impl(move(impl)) { } - virtual void init(const LogUpdate& llu, const TopicContentSeq& content, const Ice::Current&) + void init(LogUpdate llu, TopicContentSeq content, const Ice::Current&) override { - NodeIPtr node = _instance->node(); + auto node = _instance->node(); if(node) { node->checkObserverInit(llu.generation); } - _impl->observerInit(llu, content); + _impl->observerInit(move(llu), move(content)); } - virtual void createTopic(const LogUpdate& llu, const string& name, const Ice::Current&) + void createTopic(LogUpdate llu, string name, const Ice::Current&) override { try { ObserverUpdateHelper unlock(_instance->node(), llu.generation, __FILE__, __LINE__); - _impl->observerCreateTopic(llu, name); + _impl->observerCreateTopic(llu, move(name)); } catch(const ObserverInconsistencyException& e) { @@ -143,12 +143,12 @@ public: } } - virtual void destroyTopic(const LogUpdate& llu, const string& name, const Ice::Current&) + void destroyTopic(LogUpdate llu, string name, const Ice::Current&) override { try { ObserverUpdateHelper unlock(_instance->node(), llu.generation, __FILE__, __LINE__); - _impl->observerDestroyTopic(llu, name); + _impl->observerDestroyTopic(llu, move(name)); } catch(const ObserverInconsistencyException& e) { @@ -159,13 +159,12 @@ public: } } - virtual void addSubscriber(const LogUpdate& llu, const string& name, const SubscriberRecord& rec, - const Ice::Current&) + void addSubscriber(LogUpdate llu, string name, SubscriberRecord rec, const Ice::Current&) override { try { ObserverUpdateHelper unlock(_instance->node(), llu.generation, __FILE__, __LINE__); - _impl->observerAddSubscriber(llu, name, rec); + _impl->observerAddSubscriber(llu, move(name), move(rec)); } catch(const ObserverInconsistencyException& e) { @@ -176,13 +175,12 @@ public: } } - virtual void removeSubscriber(const LogUpdate& llu, const string& name, const Ice::IdentitySeq& id, - const Ice::Current&) + void removeSubscriber(LogUpdate llu, string name, Ice::IdentitySeq id, const Ice::Current&) override { try { ObserverUpdateHelper unlock(_instance->node(), llu.generation, __FILE__, __LINE__); - _impl->observerRemoveSubscriber(llu, name, id); + _impl->observerRemoveSubscriber(llu, move(name), move(id)); } catch(const ObserverInconsistencyException& e) { @@ -195,110 +193,109 @@ public: private: - const PersistentInstancePtr _instance; - const TopicManagerImplPtr _impl; + const shared_ptr<PersistentInstance> _instance; + const shared_ptr<TopicManagerImpl> _impl; }; -class TopicManagerSyncI : public TopicManagerSync +class TopicManagerSyncI final : public TopicManagerSync { public: - TopicManagerSyncI(const TopicManagerImplPtr& impl) : - _impl(impl) + TopicManagerSyncI(shared_ptr<TopicManagerImpl> impl) : + _impl(move(impl)) { } - virtual void getContent(LogUpdate& llu, TopicContentSeq& content, const Ice::Current&) + void getContent(LogUpdate& llu, TopicContentSeq& content, const Ice::Current&) override { _impl->getContent(llu, content); } private: - const TopicManagerImplPtr _impl; + const shared_ptr<TopicManagerImpl> _impl; }; } -TopicManagerImpl::TopicManagerImpl(const PersistentInstancePtr& instance) : - _instance(instance), - _lluMap(instance->lluMap()), - _subscriberMap(instance->subscriberMap()) +shared_ptr<TopicManagerImpl> +TopicManagerImpl::create(const std::shared_ptr<PersistentInstance>& instance) { - try + shared_ptr<TopicManagerImpl> manager(new TopicManagerImpl(instance)); + + if(instance->observer()) { - __setNoDelete(true); + instance->observer()->setObserverUpdater(manager); + } - if(_instance->observer()) - { - _instance->observer()->setObserverUpdater(this); - } + manager->_managerImpl = make_shared<TopicManagerI>(instance, manager); - // TODO: If we want to improve the performance of the - // non-replicated case we could allocate a null-topic manager impl - // here. - _managerImpl = new TopicManagerI(instance, this); + // If there is no node adapter we don't need to start the + // observer, nor sync since we're not replicating. + if(instance->nodeAdapter()) + { + auto observerImpl = make_shared<ReplicaObserverI>(instance, manager); + manager->_observer = instance->nodeAdapter()->addWithUUID(observerImpl); + auto syncImpl = make_shared<TopicManagerSyncI>(manager); + manager->_sync = instance->nodeAdapter()->addWithUUID(syncImpl); + } - // If there is no node adapter we don't need to start the - // observer, nor sync since we're not replicating. - if(_instance->nodeAdapter()) - { - _observerImpl = new ReplicaObserverI(instance, this); - _observer = _instance->nodeAdapter()->addWithUUID(_observerImpl); - _syncImpl = new TopicManagerSyncI(this); - _sync = _instance->nodeAdapter()->addWithUUID(_syncImpl); - } + return manager; +} - { - IceDB::ReadWriteTxn txn(_instance->dbEnv()); +TopicManagerImpl::TopicManagerImpl(shared_ptr<PersistentInstance> instance) : + _instance(move(instance)), + _lluMap(_instance->lluMap()), + _subscriberMap(_instance->subscriberMap()) +{ + try + { + IceDB::ReadWriteTxn txn(_instance->dbEnv()); - // Ensure that the llu counter is present in the log. - LogUpdate empty = {0, 0}; - _instance->lluMap().put(txn, lluDbKey, empty); + // Ensure that the llu counter is present in the log. + LogUpdate empty = {0, 0}; + _instance->lluMap().put(txn, lluDbKey, empty); - // Recreate each of the topics. - SubscriberRecordKey k; - SubscriberRecord v; + // Recreate each of the topics. + SubscriberRecordKey k; + SubscriberRecord v; - SubscriberMapRWCursor cursor(_subscriberMap, txn); - if(cursor.get(k, v, MDB_FIRST)) + SubscriberMapRWCursor cursor(_subscriberMap, txn); + if(cursor.get(k, v, MDB_FIRST)) + { + bool moreTopics = false; + do { - bool moreTopics = false; - do - { - // This record has to be a place holder record, otherwise - // there is a database bug. - assert(k.id.name.empty() && k.id.category.empty()); + // This record has to be a place holder record, otherwise + // there is a database bug. + assert(k.id.name.empty() && k.id.category.empty()); - Ice::Identity topic = k.topic; + Ice::Identity topic = k.topic; - SubscriberRecordSeq content; - while((moreTopics = cursor.get(k, v, MDB_NEXT)) == true && k.topic == topic) - { - content.push_back(v); - } - - string name = identityToTopicName(topic); - installTopic(name, topic, false, content); - } while(moreTopics); - } + SubscriberRecordSeq content; + while((moreTopics = cursor.get(k, v, MDB_NEXT)) == true && k.topic == topic) + { + content.push_back(v); + } - txn.commit(); + string name = identityToTopicName(topic); + installTopic(name, topic, false, content); + } while(moreTopics); } + + txn.commit(); } - catch(...) + catch(const std::exception&) { shutdown(); - __setNoDelete(false); throw; } - __setNoDelete(false); } -TopicPrx +shared_ptr<TopicPrx> TopicManagerImpl::create(const string& name) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); reap(); if(_topics.find(name) != _topics.end()) @@ -336,15 +333,14 @@ TopicManagerImpl::create(const string& name) return installTopic(name, id, true); } -TopicPrx -TopicManagerImpl::retrieve(const string& name) const +shared_ptr<TopicPrx> +TopicManagerImpl::retrieve(const string& name) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - TopicManagerImpl* This = const_cast<TopicManagerImpl*>(this); - This->reap(); + reap(); - map<string, TopicImplPtr>::const_iterator p = _topics.find(name); + auto p = _topics.find(name); if(p == _topics.end()) { throw NoSuchTopic(name); @@ -354,17 +350,16 @@ TopicManagerImpl::retrieve(const string& name) const } TopicDict -TopicManagerImpl::retrieveAll() const +TopicManagerImpl::retrieveAll() { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - TopicManagerImpl* This = const_cast<TopicManagerImpl*>(this); - This->reap(); + reap(); TopicDict all; - for(map<string, TopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + for(auto p = _topics.begin(); p != _topics.end(); ++p) { - all.insert(TopicDict::value_type(p->first, p->second->proxy())); + all.insert({ p->first, p->second->proxy() }); } return all; @@ -373,19 +368,19 @@ TopicManagerImpl::retrieveAll() const void TopicManagerImpl::observerInit(const LogUpdate& llu, const TopicContentSeq& content) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topicMgr > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicMgrCat); out << "init"; - for(TopicContentSeq::const_iterator p = content.begin(); p != content.end(); ++p) + for(const auto& c : content) { - out << " topic: " << _instance->communicator()->identityToString(p->id) << " subscribers: "; - for(SubscriberRecordSeq::const_iterator q = p->records.begin(); q != p->records.end(); ++q) + out << " topic: " << _instance->communicator()->identityToString(c.id) << " subscribers: "; + for(auto q = c.records.cbegin(); q != c.records.cend(); ++q) { - if(q != p->records.begin()) + if(q != c.records.begin()) { out << ","; } @@ -409,22 +404,23 @@ TopicManagerImpl::observerInit(const LogUpdate& llu, const TopicContentSeq& cont _subscriberMap.clear(txn); for(TopicContentSeq::const_iterator p = content.begin(); p != content.end(); ++p) + for(const auto& c : content) { SubscriberRecordKey srkey; - srkey.topic = p->id; + srkey.topic = c.id; SubscriberRecord rec; rec.link = false; rec.cost = 0; _subscriberMap.put(txn, srkey, rec); - for(SubscriberRecordSeq::const_iterator q = p->records.begin(); q != p->records.end(); ++q) + for(const auto& record : c.records) { SubscriberRecordKey key; - key.topic = p->id; - key.id = q->id; + key.topic = c.id; + key.id = record.id; - _subscriberMap.put(txn, key, *q); + _subscriberMap.put(txn, key, record); } } txn.commit(); @@ -440,7 +436,7 @@ TopicManagerImpl::observerInit(const LogUpdate& llu, const TopicContentSeq& cont // runs through the init list and either adds the ones that don't // exist, or updates those that do. - map<string, TopicImplPtr>::iterator p = _topics.begin(); + auto p = _topics.begin(); while(p != _topics.end()) { TopicContentSeq::const_iterator q; @@ -471,10 +467,10 @@ TopicManagerImpl::observerInit(const LogUpdate& llu, const TopicContentSeq& cont // Now run through the contents updating the topics that do exist, // and creating those that do not. - for(TopicContentSeq::const_iterator q = content.begin(); q != content.end(); ++q) + for(auto q = content.cbegin(); q != content.cend(); ++q) { string name = identityToTopicName(q->id); - map<string, TopicImplPtr>::const_iterator r = _topics.find(name); + auto r = _topics.find(name); if(r == _topics.end()) { installTopic(name, q->id, true, q->records); @@ -491,7 +487,7 @@ TopicManagerImpl::observerInit(const LogUpdate& llu, const TopicContentSeq& cont void TopicManagerImpl::observerCreateTopic(const LogUpdate& llu, const string& name) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); Ice::Identity id = nameToIdentity(_instance, name); try @@ -526,9 +522,9 @@ TopicManagerImpl::observerCreateTopic(const LogUpdate& llu, const string& name) void TopicManagerImpl::observerDestroyTopic(const LogUpdate& llu, const string& name) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - map<string, TopicImplPtr>::iterator q = _topics.find(name); + auto q = _topics.find(name); if(q == _topics.end()) { throw ObserverInconsistencyException("no topic: " + name); @@ -541,11 +537,11 @@ TopicManagerImpl::observerDestroyTopic(const LogUpdate& llu, const string& name) void TopicManagerImpl::observerAddSubscriber(const LogUpdate& llu, const string& name, const SubscriberRecord& record) { - TopicImplPtr topic; + shared_ptr<TopicImpl> topic; { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - map<string, TopicImplPtr>::iterator q = _topics.find(name); + auto q = _topics.find(name); if(q == _topics.end()) { throw ObserverInconsistencyException("no topic: " + name); @@ -559,11 +555,11 @@ TopicManagerImpl::observerAddSubscriber(const LogUpdate& llu, const string& name void TopicManagerImpl::observerRemoveSubscriber(const LogUpdate& llu, const string& name, const Ice::IdentitySeq& id) { - TopicImplPtr topic; + shared_ptr<TopicImpl> topic; { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - map<string, TopicImplPtr>::iterator q = _topics.find(name); + auto q = _topics.find(name); if(q == _topics.end()) { throw ObserverInconsistencyException("no topic: " + name); @@ -578,16 +574,16 @@ void TopicManagerImpl::getContent(LogUpdate& llu, TopicContentSeq& content) { { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); reap(); } try { content.clear(); - for(map<string, TopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + for(const auto& topic : _topics) { - TopicContent rec = p->second->getContent(); + TopicContent rec = topic.second->getContent(); content.push_back(rec); } @@ -620,9 +616,9 @@ TopicManagerImpl::getLastLogUpdate() const } void -TopicManagerImpl::sync(const Ice::ObjectPrx& master) +TopicManagerImpl::sync(const shared_ptr<Ice::ObjectPrx>& master) { - TopicManagerSyncPrx sync = TopicManagerSyncPrx::uncheckedCast(master); + auto sync = Ice::uncheckedCast<TopicManagerSyncPrx>(master); LogUpdate llu; TopicContentSeq content; @@ -634,7 +630,7 @@ TopicManagerImpl::sync(const Ice::ObjectPrx& master) void TopicManagerImpl::initMaster(const set<GroupNodeInfo>& slaves, const LogUpdate& llu) { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); reap(); @@ -657,9 +653,9 @@ TopicManagerImpl::initMaster(const set<GroupNodeInfo>& slaves, const LogUpdate& IceDB::ReadWriteTxn txn(_instance->dbEnv()); - for(map<string, TopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + for(const auto& topic : _topics) { - TopicContent rec = p->second->getContent(); + TopicContent rec = topic.second->getContent(); content.push_back(rec); } @@ -677,13 +673,13 @@ TopicManagerImpl::initMaster(const set<GroupNodeInfo>& slaves, const LogUpdate& _instance->observers()->init(slaves, llu, content); } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> TopicManagerImpl::getObserver() const { return _observer; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> TopicManagerImpl::getSync() const { return _sync; @@ -695,12 +691,10 @@ TopicManagerImpl::reap() // // Always called with mutex locked. // - // Lock sync(*this); - // vector<string> reaped = _instance->topicReaper()->consumeReapedTopics(); - for(vector<string>::const_iterator p = reaped.begin(); p != reaped.end(); ++p) + for(const auto& topic : reaped) { - map<string, TopicImplPtr>::iterator q = _topics.find(*p); + auto q = _topics.find(topic); if(q != _topics.end() && q->second->destroyed()) { _topics.erase(q); @@ -711,20 +705,18 @@ TopicManagerImpl::reap() void TopicManagerImpl::shutdown() { - Lock sync(*this); + lock_guard<recursive_mutex> lg(_mutex); - for(map<string, TopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + for(const auto& topic : _topics) { - p->second->shutdown(); + topic.second->shutdown(); } _topics.clear(); - _observerImpl = 0; - _syncImpl = 0; - _managerImpl = 0; + _managerImpl = nullptr; } -Ice::ObjectPtr +shared_ptr<Ice::Object> TopicManagerImpl::getServant() const { return _managerImpl; @@ -733,31 +725,33 @@ TopicManagerImpl::getServant() const void TopicManagerImpl::updateTopicObservers() { - Lock sync(*this); - for(map<string, TopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + lock_guard<recursive_mutex> lg(_mutex); + + for(const auto& topic : _topics) { - p->second->updateObserver(); + topic.second->updateObserver(); } } void TopicManagerImpl::updateSubscriberObservers() { - Lock sync(*this); - for(map<string, TopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + lock_guard<recursive_mutex> lg(_mutex); + + for(const auto& topic : _topics) { - p->second->updateSubscriberObservers(); + topic.second->updateSubscriberObservers(); } } -TopicPrx +shared_ptr<TopicPrx> TopicManagerImpl::installTopic(const string& name, const Ice::Identity& id, bool create, const IceStorm::SubscriberRecordSeq& subscribers) { // // Called by constructor or with 'this' mutex locked. // - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topicMgr > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicMgrCat); @@ -766,7 +760,7 @@ TopicManagerImpl::installTopic(const string& name, const Ice::Identity& id, bool out << "creating new topic \"" << name << "\". id: " << _instance->communicator()->identityToString(id) << " subscribers: "; - for(SubscriberRecordSeq::const_iterator q = subscribers.begin(); q != subscribers.end(); ++q) + for(auto q = subscribers.cbegin(); q != subscribers.cend(); ++q) { if(q != subscribers.begin()) { @@ -784,7 +778,7 @@ TopicManagerImpl::installTopic(const string& name, const Ice::Identity& id, bool out << "loading topic \"" << name << "\" from database. id: " << _instance->communicator()->identityToString(id) << " subscribers: "; - for(SubscriberRecordSeq::const_iterator q = subscribers.begin(); q != subscribers.end(); ++q) + for(auto q = subscribers.cbegin(); q != subscribers.cend(); ++q) { if(q != subscribers.begin()) { @@ -800,10 +794,10 @@ TopicManagerImpl::installTopic(const string& name, const Ice::Identity& id, bool } // Create topic implementation - TopicImplPtr topicImpl = new TopicImpl(_instance, name, id, subscribers); + auto topicImpl = TopicImpl::create(_instance, name, id, subscribers); // The identity is the name of the Topic. - _topics.insert(map<string, TopicImplPtr>::value_type(name, topicImpl)); + _topics.insert({ name, topicImpl }); _instance->topicAdapter()->add(topicImpl->getServant(), id); return topicImpl->proxy(); } diff --git a/cpp/src/IceStorm/TopicManagerI.h b/cpp/src/IceStorm/TopicManagerI.h index 84cb47871cf..3d34d71fcb1 100644 --- a/cpp/src/IceStorm/TopicManagerI.h +++ b/cpp/src/IceStorm/TopicManagerI.h @@ -12,35 +12,27 @@ #include <IceStorm/Instrumentation.h> #include <IceStorm/Util.h> -#include <IceUtil/RecMutex.h> - namespace IceStorm { -// -// Forward declarations. -// class PersistentInstance; -typedef IceUtil::Handle<PersistentInstance> PersistentInstancePtr; - class TopicImpl; -typedef IceUtil::Handle<TopicImpl> TopicImplPtr; // // TopicManager implementation. // -class TopicManagerImpl : public IceStormElection::Replica, - public IceStorm::Instrumentation::ObserverUpdater, - public IceUtil::RecMutex +class TopicManagerImpl final : public IceStormElection::Replica, + public IceStorm::Instrumentation::ObserverUpdater, + public std::enable_shared_from_this<TopicManagerImpl> { public: - TopicManagerImpl(const PersistentInstancePtr&); + static std::shared_ptr<TopicManagerImpl> create(const std::shared_ptr<PersistentInstance>&); // TopicManager methods. - TopicPrx create(const std::string&); - TopicPrx retrieve(const std::string&) const; - TopicDict retrieveAll() const; + std::shared_ptr<TopicPrx> create(const std::string&); + std::shared_ptr<TopicPrx> retrieve(const std::string&); + TopicDict retrieveAll(); // Observer methods. void observerInit(const IceStormElection::LogUpdate&, const IceStormElection::TopicContentSeq&); @@ -54,40 +46,41 @@ public: void getContent(IceStormElection::LogUpdate&, IceStormElection::TopicContentSeq&); // Replica methods. - virtual IceStormElection::LogUpdate getLastLogUpdate() const; - virtual void sync(const Ice::ObjectPrx&); - virtual void initMaster(const std::set<IceStormElection::GroupNodeInfo>&, const IceStormElection::LogUpdate&); - virtual Ice::ObjectPrx getObserver() const; - virtual Ice::ObjectPrx getSync() const; + IceStormElection::LogUpdate getLastLogUpdate() const override; + void sync(const std::shared_ptr<Ice::ObjectPrx>&) override; + void initMaster(const std::set<IceStormElection::GroupNodeInfo>&, const IceStormElection::LogUpdate&) override; + std::shared_ptr<Ice::ObjectPrx> getObserver() const override; + std::shared_ptr<Ice::ObjectPrx> getSync() const override; void reap(); void shutdown(); - Ice::ObjectPtr getServant() const; + std::shared_ptr<Ice::Object> getServant() const; private: - void updateTopicObservers(); - void updateSubscriberObservers(); + TopicManagerImpl(std::shared_ptr<PersistentInstance>); + + void updateTopicObservers() override; + void updateSubscriberObservers() override; - TopicPrx installTopic(const std::string&, const Ice::Identity&, bool, - const IceStorm::SubscriberRecordSeq& = IceStorm::SubscriberRecordSeq()); + std::shared_ptr<TopicPrx> installTopic(const std::string&, const Ice::Identity&, bool, + const IceStorm::SubscriberRecordSeq& = IceStorm::SubscriberRecordSeq()); - const PersistentInstancePtr _instance; + const std::shared_ptr<PersistentInstance> _instance; - std::map<std::string, TopicImplPtr> _topics; + std::map<std::string, std::shared_ptr<TopicImpl>> _topics; - Ice::ObjectPtr _managerImpl; - Ice::ObjectPtr _observerImpl; - Ice::ObjectPrx _observer; - Ice::ObjectPtr _syncImpl; - Ice::ObjectPrx _sync; + std::shared_ptr<Ice::Object> _managerImpl; + std::shared_ptr<Ice::ObjectPrx> _observer; + std::shared_ptr<Ice::ObjectPrx> _sync; LLUMap _lluMap; SubscriberMap _subscriberMap; + + std::recursive_mutex _mutex; }; -typedef IceUtil::Handle<TopicManagerImpl> TopicManagerImplPtr; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/TraceLevels.cpp b/cpp/src/IceStorm/TraceLevels.cpp index afa45876c72..508b7810df5 100644 --- a/cpp/src/IceStorm/TraceLevels.cpp +++ b/cpp/src/IceStorm/TraceLevels.cpp @@ -9,7 +9,9 @@ using namespace std; using namespace IceStorm; -TraceLevels::TraceLevels(const string name, const Ice::PropertiesPtr& properties, const Ice::LoggerPtr& theLogger) : +TraceLevels::TraceLevels(const string name, + const shared_ptr<Ice::Properties>& properties, + shared_ptr<Ice::Logger> theLogger) : topicMgr(0), topicMgrCat("TopicManager"), topic(0), @@ -20,7 +22,7 @@ TraceLevels::TraceLevels(const string name, const Ice::PropertiesPtr& properties electionCat("Election"), replication(0), replicationCat("Replication"), - logger(theLogger) + logger(move(theLogger)) { const string keyBase = name + ".Trace."; const_cast<int&>(topicMgr) = properties->getPropertyAsInt(keyBase + topicMgrCat); @@ -28,7 +30,3 @@ TraceLevels::TraceLevels(const string name, const Ice::PropertiesPtr& properties const_cast<int&>(subscriber) = properties->getPropertyAsInt(keyBase + subscriberCat); const_cast<int&>(election) = properties->getPropertyAsInt(keyBase + electionCat); } - -TraceLevels::~TraceLevels() -{ -} diff --git a/cpp/src/IceStorm/TraceLevels.h b/cpp/src/IceStorm/TraceLevels.h index 02a4ac63452..dac648c6c53 100644 --- a/cpp/src/IceStorm/TraceLevels.h +++ b/cpp/src/IceStorm/TraceLevels.h @@ -5,20 +5,17 @@ #ifndef ICE_STORM_TRACE_LEVELS_H #define ICE_STORM_TRACE_LEVELS_H -#include <IceUtil/Shared.h> -#include <IceUtil/Handle.h> -#include <Ice/PropertiesF.h> #include <Ice/LoggerF.h> +#include <Ice/PropertiesF.h> namespace IceStorm { -class TraceLevels : public IceUtil::Shared +class TraceLevels { public: - TraceLevels(const ::std::string name, const Ice::PropertiesPtr&, const Ice::LoggerPtr&); - virtual ~TraceLevels(); + TraceLevels(const ::std::string name, const std::shared_ptr<Ice::Properties>&, std::shared_ptr<Ice::Logger>); const int topicMgr; const char* topicMgrCat; @@ -35,11 +32,9 @@ public: const int replication; const char* replicationCat; - const Ice::LoggerPtr logger; + const std::shared_ptr<Ice::Logger> logger; }; -typedef IceUtil::Handle<TraceLevels> TraceLevelsPtr; - } // End namespace IceStorm #endif diff --git a/cpp/src/IceStorm/TransientTopicI.cpp b/cpp/src/IceStorm/TransientTopicI.cpp index 055d32caf60..1691216eb3c 100644 --- a/cpp/src/IceStorm/TransientTopicI.cpp +++ b/cpp/src/IceStorm/TransientTopicI.cpp @@ -27,32 +27,22 @@ class TransientPublisherI : public Ice::BlobjectArray { public: - TransientPublisherI(const TransientTopicImplPtr& impl) : - _impl(impl) + TransientPublisherI(shared_ptr<TransientTopicImpl> impl) : + _impl(move(impl)) { } - virtual bool - ice_invoke(const pair<const Ice::Byte*, const Ice::Byte*>& inParams, - Ice::ByteSeq&, - const Ice::Current& current) + bool + ice_invoke(pair<const Ice::Byte*, const Ice::Byte*> inParams, Ice::ByteSeq&, const Ice::Current& current) override { // Use cached reads. - EventDataPtr event = new EventData( - current.operation, - current.mode, - Ice::ByteSeq(), - current.ctx); - - // - // COMPILERBUG: gcc 4.0.1 doesn't like this. - // - //event->data.swap(Ice::ByteSeq(inParams.first, inParams.second)); + EventData event = { current.operation, current.mode, Ice::ByteSeq(), current.ctx }; + Ice::ByteSeq data(inParams.first, inParams.second); - event->data.swap(data); + event.data.swap(data); EventDataSeq v; - v.push_back(event); + v.push_back(move(event)); _impl->publish(false, v); return true; @@ -60,7 +50,7 @@ public: private: - const TransientTopicImplPtr _impl; + const shared_ptr<TransientTopicImpl> _impl; }; // @@ -71,33 +61,29 @@ class TransientTopicLinkI : public TopicLink { public: - TransientTopicLinkI(const TransientTopicImplPtr& impl) : - _impl(impl) + TransientTopicLinkI(shared_ptr<TransientTopicImpl> impl) : + _impl(move(impl)) { } - virtual void - forward(const EventDataSeq& v, const Ice::Current& /*current*/) + void + forward(EventDataSeq v, const Ice::Current&) override { - _impl->publish(true, v); + _impl->publish(true, move(v)); } private: - const TransientTopicImplPtr _impl; + const shared_ptr<TransientTopicImpl> _impl; }; } -TransientTopicImpl::TransientTopicImpl( - const InstancePtr& instance, - const string& name, - const Ice::Identity& id) : - _instance(instance), - _name(name), - _id(id), - _destroyed(false) +shared_ptr<TransientTopicImpl> +TransientTopicImpl::create(const shared_ptr<Instance>& instance, const std::string& name, const Ice::Identity& id) { + shared_ptr<TransientTopicImpl> topicImpl(new TransientTopicImpl(instance, name, id)); + // // Create a servant per topic to receive event data. If the // category is empty then we are in backwards compatibility @@ -112,24 +98,34 @@ TransientTopicImpl::TransientTopicImpl( Ice::Identity linkid; if(id.category.empty()) { - pubid.category = _name; + pubid.category = name; pubid.name = "publish"; - linkid.category = _name; + linkid.category = name; linkid.name = "link"; } else { pubid.category = id.category; - pubid.name = _name + ".publish"; + pubid.name = name + ".publish"; linkid.category = id.category; - linkid.name = _name + ".link"; + linkid.name = name + ".link"; } - _publisherPrx = _instance->publishAdapter()->add(new TransientPublisherI(this), pubid); - _linkPrx = TopicLinkPrx::uncheckedCast(_instance->publishAdapter()->add(new TransientTopicLinkI(this), linkid)); + auto publisher = make_shared<TransientPublisherI>(topicImpl); + topicImpl->_publisherPrx = instance->publishAdapter()->add(publisher, pubid); + auto topicLink = make_shared<TransientTopicLinkI>(topicImpl); + topicImpl->_linkPrx = Ice::uncheckedCast<TopicLinkPrx>(instance->publishAdapter()->add(topicLink, linkid)); + + return topicImpl; } -TransientTopicImpl::~TransientTopicImpl() +TransientTopicImpl::TransientTopicImpl(shared_ptr<Instance> instance, + const std::string& name, + const Ice::Identity& id) : + _instance(move(instance)), + _name(name), + _id(id), + _destroyed(false) { } @@ -140,128 +136,26 @@ TransientTopicImpl::getName(const Ice::Current&) const return _name; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> TransientTopicImpl::getPublisher(const Ice::Current&) const { // Immutable return _publisherPrx; } -Ice::ObjectPrx +shared_ptr<Ice::ObjectPrx> TransientTopicImpl::getNonReplicatedPublisher(const Ice::Current&) const { // Immutable return _publisherPrx; } -void -TransientTopicImpl::subscribe(const QoS& origQoS, const Ice::ObjectPrx& obj, const Ice::Current&) -{ - if(!obj) - { - TraceLevelsPtr traceLevels = _instance->traceLevels(); - if(traceLevels->topic > 0) - { - Ice::Trace out(traceLevels->logger, traceLevels->topicCat); - out << _name << ": subscribe: null proxy"; - } - throw InvalidSubscriber("subscriber is a null proxy"); - } - Ice::Identity id = obj->ice_getIdentity(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); - QoS qos = origQoS; - if(traceLevels->topic > 0) - { - Ice::Trace out(traceLevels->logger, traceLevels->topicCat); - out << _name << ": subscribe: " << _instance->communicator()->identityToString(id); - - if(traceLevels->topic > 1) - { - out << " endpoints: " << IceStormInternal::describeEndpoints(obj) - << " QoS: "; - for(QoS::const_iterator p = qos.begin(); p != qos.end() ; ++p) - { - if(p != qos.begin()) - { - out << ','; - } - out << '[' << p->first << "," << p->second << ']'; - } - } - } - - string reliability = "oneway"; - { - QoS::iterator p = qos.find("reliability"); - if(p != qos.end()) - { - reliability = p->second; - qos.erase(p); - } - } - - Ice::ObjectPrx newObj = obj; - if(reliability == "batch") - { - if(newObj->ice_isDatagram()) - { - newObj = newObj->ice_batchDatagram(); - } - else - { - newObj = newObj->ice_batchOneway(); - } - } - else if(reliability == "twoway") - { - newObj = newObj->ice_twoway(); - } - else if(reliability == "twoway ordered") - { - qos["reliability"] = "ordered"; - newObj = newObj->ice_twoway(); - } - else // reliability == "oneway" - { - if(reliability != "oneway" && traceLevels->subscriber > 0) - { - Ice::Trace out(traceLevels->logger, traceLevels->subscriberCat); - out << reliability <<" mode not understood."; - } - if(!newObj->ice_isDatagram()) - { - newObj = newObj->ice_oneway(); - } - } - - Lock sync(*this); - SubscriberRecord record; - record.id = id; - record.obj = newObj; - record.theQoS = qos; - record.topicName = _name; - record.link = false; - record.cost = 0; - - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), record.id); - if(p != _subscribers.end()) - { - // If we already have this subscriber remove it from our - // subscriber list and remove it from the database. - (*p)->destroy(); - _subscribers.erase(p); - } - - SubscriberPtr subscriber = Subscriber::create(_instance, record); - _subscribers.push_back(subscriber); -} - -Ice::ObjectPrx -TransientTopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj, const Ice::Current&) +shared_ptr<Ice::ObjectPrx> +TransientTopicImpl::subscribeAndGetPublisher(QoS qos, shared_ptr<Ice::ObjectPrx> obj, const Ice::Current&) { if(!obj) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -271,7 +165,7 @@ TransientTopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPr } Ice::Identity id = obj->ice_getIdentity(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -292,7 +186,7 @@ TransientTopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPr } } - Lock sync(*this); + lock_guard<mutex> lg(_mutex); SubscriberRecord record; record.id = id; @@ -302,22 +196,21 @@ TransientTopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPr record.link = false; record.cost = 0; - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), record.id); - if(p != _subscribers.end()) + if(find(_subscribers.begin(), _subscribers.end(), record.id) != _subscribers.end()) { throw AlreadySubscribed(); } - SubscriberPtr subscriber = Subscriber::create(_instance, record); + auto subscriber = Subscriber::create(_instance, record); _subscribers.push_back(subscriber); return subscriber->proxy(); } void -TransientTopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber, const Ice::Current&) +TransientTopicImpl::unsubscribe(shared_ptr<Ice::ObjectPrx> subscriber, const Ice::Current&) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(!subscriber) { if(traceLevels->topic > 0) @@ -340,11 +233,12 @@ TransientTopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber, const Ice::Cur } } - Lock sync(*this); + lock_guard<mutex> lg(_mutex); + // First remove the subscriber from the subscribers list. Note // that its possible that the subscriber isn't in the list, but is // in the database if the subscriber was locally reaped. - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), id); + auto p = find(_subscribers.begin(), _subscribers.end(), id); if(p != _subscribers.end()) { (*p)->destroy(); @@ -352,7 +246,7 @@ TransientTopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber, const Ice::Cur } } -TopicLinkPrx +shared_ptr<TopicLinkPrx> TransientTopicImpl::getLinkProxy(const Ice::Current&) { // immutable @@ -360,12 +254,12 @@ TransientTopicImpl::getLinkProxy(const Ice::Current&) } void -TransientTopicImpl::link(const TopicPrx& topic, Ice::Int cost, const Ice::Current&) +TransientTopicImpl::link(shared_ptr<TopicPrx> topic, int cost, const Ice::Current&) { - TopicInternalPrx internal = TopicInternalPrx::uncheckedCast(topic); - TopicLinkPrx link = internal->getLinkProxy(); + auto internal = Ice::uncheckedCast<TopicInternalPrx>(topic); + auto link = internal->getLinkProxy(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -373,9 +267,9 @@ TransientTopicImpl::link(const TopicPrx& topic, Ice::Int cost, const Ice::Curren << " cost " << cost; } - Lock sync(*this); + lock_guard<mutex> lg(_mutex); - Ice::Identity id = topic->ice_getIdentity(); + auto id = topic->ice_getIdentity(); SubscriberRecord record; record.id = id; @@ -385,32 +279,32 @@ TransientTopicImpl::link(const TopicPrx& topic, Ice::Int cost, const Ice::Curren record.link = true; record.cost = cost; - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), record.id); - if(p != _subscribers.end()) + if(find(_subscribers.begin(), _subscribers.end(), record.id) != _subscribers.end()) { throw LinkExists(IceStormInternal::identityToTopicName(id)); } - SubscriberPtr subscriber = Subscriber::create(_instance, record); + auto subscriber = Subscriber::create(_instance, record); _subscribers.push_back(subscriber); } void -TransientTopicImpl::unlink(const TopicPrx& topic, const Ice::Current&) +TransientTopicImpl::unlink(shared_ptr<TopicPrx> topic, const Ice::Current&) { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); } - Ice::Identity id = topic->ice_getIdentity(); + auto id = topic->ice_getIdentity(); + auto traceLevels = _instance->traceLevels(); - vector<SubscriberPtr>::iterator p = find(_subscribers.begin(), _subscribers.end(), id); - if(p == _subscribers.end()) + if(find(_subscribers.begin(), _subscribers.end(), id) == _subscribers.end()) { string name = IceStormInternal::identityToTopicName(id); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -419,7 +313,6 @@ TransientTopicImpl::unlink(const TopicPrx& topic, const Ice::Current&) throw NoSuchLink(name); } - TraceLevelsPtr traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -429,7 +322,7 @@ TransientTopicImpl::unlink(const TopicPrx& topic, const Ice::Current&) // Remove the subscriber from the subscribers list. Note // that its possible that the subscriber isn't in the list, but is // in the database if the subscriber was locally reaped. - p = find(_subscribers.begin(), _subscribers.end(), id); + auto p = find(_subscribers.begin(), _subscribers.end(), id); if(p != _subscribers.end()) { (*p)->destroy(); @@ -440,12 +333,13 @@ TransientTopicImpl::unlink(const TopicPrx& topic, const Ice::Current&) LinkInfoSeq TransientTopicImpl::getLinkInfoSeq(const Ice::Current&) const { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); + LinkInfoSeq seq; - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - SubscriberRecord record = (*p)->record(); - if(record.link && !(*p)->errored()) + SubscriberRecord record = subscriber->record(); + if(record.link && !subscriber->errored()) { LinkInfo info; info.name = IceStormInternal::identityToTopicName(record.theTopic->ice_getIdentity()); @@ -460,12 +354,12 @@ TransientTopicImpl::getLinkInfoSeq(const Ice::Current&) const Ice::IdentitySeq TransientTopicImpl::getSubscribers(const Ice::Current&) const { - IceUtil::Mutex::Lock sync(*this); + lock_guard<mutex> lg(_mutex); Ice::IdentitySeq subscribers; - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - subscribers.push_back((*p)->id()); + subscribers.push_back(subscriber->id()); } return subscribers; } @@ -473,7 +367,7 @@ TransientTopicImpl::getSubscribers(const Ice::Current&) const void TransientTopicImpl::destroy(const Ice::Current&) { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); if(_destroyed) { @@ -481,7 +375,7 @@ TransientTopicImpl::destroy(const Ice::Current&) } _destroyed = true; - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -499,22 +393,22 @@ TransientTopicImpl::destroy(const Ice::Current&) } // Destroy all of the subscribers. - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - (*p)->destroy(); + subscriber->destroy(); } _subscribers.clear(); } void -TransientTopicImpl::reap(const Ice::IdentitySeq&, const Ice::Current&) +TransientTopicImpl::reap(Ice::IdentitySeq, const Ice::Current&) { } bool TransientTopicImpl::destroyed() const { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); return _destroyed; } @@ -532,9 +426,9 @@ TransientTopicImpl::publish(bool forwarded, const EventDataSeq& events) // Copy of the subscriber list so that event publishing can occur // in parallel. // - vector<SubscriberPtr> copy; + vector<shared_ptr<Subscriber>> copy; { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); copy = _subscribers; } @@ -542,12 +436,12 @@ TransientTopicImpl::publish(bool forwarded, const EventDataSeq& events) // Queue each event, gathering a list of those subscribers that // must be reaped. // - vector<Ice::Identity> e; - for(vector<SubscriberPtr>::const_iterator p = copy.begin(); p != copy.end(); ++p) + vector<Ice::Identity> ids; + for(const auto& subscriber : copy) { - if(!(*p)->queue(forwarded, events) && (*p)->reap()) + if(!subscriber->queue(forwarded, events) && subscriber->reap()) { - e.push_back((*p)->id()); + ids.push_back(subscriber->id()); } } @@ -555,10 +449,10 @@ TransientTopicImpl::publish(bool forwarded, const EventDataSeq& events) // Run through the error list removing those subscribers that are // in error from the subscriber list. // - if(!e.empty()) + if(!ids.empty()) { - Lock sync(*this); - for(vector<Ice::Identity>::const_iterator ep = e.begin(); ep != e.end(); ++ep) + lock_guard<mutex> lg(_mutex); + for(const auto& id : ids) { // // Its possible for the subscriber to already have been @@ -574,14 +468,13 @@ TransientTopicImpl::publish(bool forwarded, const EventDataSeq& events) // error'd subscribers and remove it from the database on // the next reap. // - vector<SubscriberPtr>::iterator q = find(_subscribers.begin(), _subscribers.end(), *ep); + auto q = find(_subscribers.begin(), _subscribers.end(), id); if(q != _subscribers.end()) { - SubscriberPtr subscriber = *q; // // Destroy the subscriber. // - subscriber->destroy(); + (*q)->destroy(); _subscribers.erase(q); } } @@ -591,11 +484,11 @@ TransientTopicImpl::publish(bool forwarded, const EventDataSeq& events) void TransientTopicImpl::shutdown() { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); // Shutdown each subscriber. This waits for the event queues to drain. - for(vector<SubscriberPtr>::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - (*p)->shutdown(); + subscriber->shutdown(); } } diff --git a/cpp/src/IceStorm/TransientTopicI.h b/cpp/src/IceStorm/TransientTopicI.h index 50b73d835f5..f64e2a69f42 100644 --- a/cpp/src/IceStorm/TransientTopicI.h +++ b/cpp/src/IceStorm/TransientTopicI.h @@ -12,31 +12,27 @@ namespace IceStorm // Forward declarations. class Instance; -typedef IceUtil::Handle<Instance> InstancePtr; - class Subscriber; -typedef IceUtil::Handle<Subscriber> SubscriberPtr; -class TransientTopicImpl : public TopicInternal, public IceUtil::Mutex +class TransientTopicImpl : public TopicInternal { public: - TransientTopicImpl(const InstancePtr&, const std::string&, const Ice::Identity&); - ~TransientTopicImpl(); - - virtual std::string getName(const Ice::Current&) const; - virtual Ice::ObjectPrx getPublisher(const Ice::Current&) const; - virtual Ice::ObjectPrx getNonReplicatedPublisher(const Ice::Current&) const; - virtual void subscribe(const QoS&, const Ice::ObjectPrx&, const Ice::Current&); - virtual Ice::ObjectPrx subscribeAndGetPublisher(const QoS&, const Ice::ObjectPrx&, const Ice::Current&); - virtual void unsubscribe(const Ice::ObjectPrx&, const Ice::Current&); - virtual TopicLinkPrx getLinkProxy(const Ice::Current&); - virtual void link(const TopicPrx&, Ice::Int, const Ice::Current&); - virtual void unlink(const TopicPrx&, const Ice::Current&); - virtual LinkInfoSeq getLinkInfoSeq(const Ice::Current&) const; - virtual Ice::IdentitySeq getSubscribers(const Ice::Current&) const; - virtual void destroy(const Ice::Current&); - virtual void reap(const Ice::IdentitySeq&, const Ice::Current&); + static std::shared_ptr<TransientTopicImpl> create(const std::shared_ptr<Instance>&, const std::string&, + const Ice::Identity&); + + std::string getName(const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> getNonReplicatedPublisher(const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> getPublisher(const Ice::Current&) const override; + std::shared_ptr<Ice::ObjectPrx> subscribeAndGetPublisher(QoS, std::shared_ptr<Ice::ObjectPrx>, const Ice::Current&) override; + void unsubscribe(std::shared_ptr<Ice::ObjectPrx>, const Ice::Current&) override; + std::shared_ptr<TopicLinkPrx> getLinkProxy(const Ice::Current&) override; + void link(std::shared_ptr<TopicPrx>, int, const Ice::Current&) override; + void unlink(std::shared_ptr<TopicPrx>, const Ice::Current&) override; + LinkInfoSeq getLinkInfoSeq(const Ice::Current&) const override; + Ice::IdentitySeq getSubscribers(const Ice::Current&) const override; + void destroy(const Ice::Current&) override; + void reap(Ice::IdentitySeq, const Ice::Current&) override; // Internal methods bool destroyed() const; @@ -47,15 +43,17 @@ public: private: + TransientTopicImpl(std::shared_ptr<Instance>, const std::string&, const Ice::Identity&); + // // Immutable members. // - const InstancePtr _instance; + const std::shared_ptr<Instance> _instance; const std::string _name; // The topic name const Ice::Identity _id; // The topic identity - /*const*/ Ice::ObjectPrx _publisherPrx; - /*const*/ TopicLinkPrx _linkPrx; + std::shared_ptr<Ice::ObjectPrx> _publisherPrx; + std::shared_ptr<TopicLinkPrx> _linkPrx; // // We keep a vector of subscribers since the optimized behaviour @@ -64,12 +62,12 @@ private: // vector/list/map and although there was little difference vector // was the fastest of the three. // - std::vector<SubscriberPtr> _subscribers; + std::vector<std::shared_ptr<Subscriber>> _subscribers; bool _destroyed; // Has this Topic been destroyed? -}; -typedef IceUtil::Handle<TransientTopicImpl> TransientTopicImplPtr; + mutable std::mutex _mutex; +}; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/TransientTopicManagerI.cpp b/cpp/src/IceStorm/TransientTopicManagerI.cpp index 016808d9335..0eaeb00b4ba 100644 --- a/cpp/src/IceStorm/TransientTopicManagerI.cpp +++ b/cpp/src/IceStorm/TransientTopicManagerI.cpp @@ -15,19 +15,15 @@ using namespace IceStorm; using namespace std; -TransientTopicManagerImpl::TransientTopicManagerImpl(const InstancePtr& instance) : - _instance(instance) +TransientTopicManagerImpl::TransientTopicManagerImpl(shared_ptr<Instance> instance) : + _instance(move(instance)) { } -TransientTopicManagerImpl::~TransientTopicManagerImpl() +shared_ptr<TopicPrx> +TransientTopicManagerImpl::create(string name, const Ice::Current&) { -} - -TopicPrx -TransientTopicManagerImpl::create(const string& name, const Ice::Current&) -{ - Lock sync(*this); + lock_guard<mutex> lg(_mutex); reap(); @@ -41,7 +37,7 @@ TransientTopicManagerImpl::create(const string& name, const Ice::Current&) // // Called by constructor or with 'this' mutex locked. // - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topicMgr > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicMgrCat); @@ -52,25 +48,24 @@ TransientTopicManagerImpl::create(const string& name, const Ice::Current&) // // Create topic implementation // - TransientTopicImplPtr topicImpl = new TransientTopicImpl(_instance, name, id); + auto topicImpl = TransientTopicImpl::create(_instance, name, id); // // The identity is the name of the Topic. // - TopicPrx prx = TopicPrx::uncheckedCast(_instance->topicAdapter()->add(topicImpl, id)); - _topics.insert(map<string, TransientTopicImplPtr>::value_type(name, topicImpl)); + auto prx = Ice::uncheckedCast<TopicPrx>(_instance->topicAdapter()->add(topicImpl, id)); + _topics.insert({ name, topicImpl }); return prx; } -TopicPrx -TransientTopicManagerImpl::retrieve(const string& name, const Ice::Current&) const +shared_ptr<TopicPrx> +TransientTopicManagerImpl::retrieve(string name, const Ice::Current&) { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); - TransientTopicManagerImpl* This = const_cast<TransientTopicManagerImpl*>(this); - This->reap(); + reap(); - map<string, TransientTopicImplPtr>::const_iterator p = _topics.find(name); + auto p = _topics.find(name); if(p == _topics.end()) { throw NoSuchTopic(name); @@ -79,54 +74,51 @@ TransientTopicManagerImpl::retrieve(const string& name, const Ice::Current&) con // Here we cannot just reconstruct the identity since the // identity could be either instanceName/topic name, or if // created with pre-3.2 IceStorm / topic name. - return TopicPrx::uncheckedCast(_instance->topicAdapter()->createProxy(p->second->id())); + return Ice::uncheckedCast<TopicPrx>(_instance->topicAdapter()->createProxy(p->second->id())); } TopicDict -TransientTopicManagerImpl::retrieveAll(const Ice::Current&) const +TransientTopicManagerImpl::retrieveAll(const Ice::Current&) { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); - TransientTopicManagerImpl* This = const_cast<TransientTopicManagerImpl*>(this); - This->reap(); + reap(); TopicDict all; - for(map<string, TransientTopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + for(const auto& topic : _topics) { // // Here we cannot just reconstruct the identity since the // identity could be either "<instanceName>/topic.<topicname>" // name, or if created with pre-3.2 IceStorm "/<topicname>". // - all.insert(TopicDict::value_type( - p->first, TopicPrx::uncheckedCast(_instance->topicAdapter()->createProxy(p->second->id())))); + all.insert({ topic.first, + Ice::uncheckedCast<TopicPrx>(_instance->topicAdapter()->createProxy(topic.second->id())) }); } return all; } -IceStormElection::NodePrx +shared_ptr<IceStormElection::NodePrx> TransientTopicManagerImpl::getReplicaNode(const Ice::Current&) const { - return IceStormElection::NodePrx(); + return nullptr; } void TransientTopicManagerImpl::reap() { // - // Always called with mutex locked. - // - // Lock sync(*this); + // Must be called called with mutex locked. // vector<string> reaped = _instance->topicReaper()->consumeReapedTopics(); for(vector<string>::const_iterator p = reaped.begin(); p != reaped.end(); ++p) { - map<string, TransientTopicImplPtr>::iterator i = _topics.find(*p); + auto i = _topics.find(*p); if(i != _topics.end() && i->second->destroyed()) { - Ice::Identity id = i->second->id(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto id = i->second->id(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topicMgr > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicMgrCat); @@ -150,10 +142,10 @@ TransientTopicManagerImpl::reap() void TransientTopicManagerImpl::shutdown() { - Lock sync(*this); + lock_guard<mutex> lg(_mutex); - for(map<string, TransientTopicImplPtr>::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + for(const auto& topic : _topics) { - p->second->shutdown(); + topic.second->shutdown(); } } diff --git a/cpp/src/IceStorm/TransientTopicManagerI.h b/cpp/src/IceStorm/TransientTopicManagerI.h index 8c84b6d85d5..55824595475 100644 --- a/cpp/src/IceStorm/TransientTopicManagerI.h +++ b/cpp/src/IceStorm/TransientTopicManagerI.h @@ -10,43 +10,31 @@ namespace IceStorm { -// -// Forward declarations. -// class Instance; -typedef IceUtil::Handle<Instance> InstancePtr; - class TransientTopicImpl; -typedef IceUtil::Handle<TransientTopicImpl> TransientTopicImplPtr; -// -// TopicManager implementation. -// -class TransientTopicManagerImpl : public TopicManagerInternal, public IceUtil::Mutex +class TransientTopicManagerImpl final : public TopicManagerInternal { public: - TransientTopicManagerImpl(const InstancePtr&); - ~TransientTopicManagerImpl(); + TransientTopicManagerImpl(std::shared_ptr<Instance>); // TopicManager methods. - virtual TopicPrx create(const std::string&, const Ice::Current&); - virtual TopicPrx retrieve(const std::string&, const Ice::Current&) const; - virtual TopicDict retrieveAll(const Ice::Current&) const; - virtual IceStormElection::NodePrx getReplicaNode(const Ice::Current&) const; + std::shared_ptr<TopicPrx> create(std::string, const Ice::Current&) override; + std::shared_ptr<TopicPrx> retrieve(std::string, const Ice::Current&) override; + TopicDict retrieveAll(const Ice::Current&) override; + std::shared_ptr<IceStormElection::NodePrx> getReplicaNode(const Ice::Current&) const override; void reap(); - void shutdown(); - Ice::ObjectPtr getServant() const; - private: - const InstancePtr _instance; - std::map<std::string, TransientTopicImplPtr> _topics; + const std::shared_ptr<Instance> _instance; + std::map<std::string, std::shared_ptr<TransientTopicImpl>> _topics; + + std::mutex _mutex; }; -typedef IceUtil::Handle<TransientTopicManagerImpl> TransientTopicManagerImplPtr; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/Util.cpp b/cpp/src/IceStorm/Util.cpp index 7eebdf80173..e8487cca3be 100644 --- a/cpp/src/IceStorm/Util.cpp +++ b/cpp/src/IceStorm/Util.cpp @@ -32,24 +32,20 @@ IceStormInternal::identityToTopicName(const Ice::Identity& id) } Ice::Identity -IceStormInternal::nameToIdentity(const InstancePtr& instance, const string& name) +IceStormInternal::nameToIdentity(const shared_ptr<Instance>& instance, const string& name) { - // Identity is instanceName>/topic.<topicname> - Ice::Identity id; - id.category = instance->instanceName(); - id.name = "topic." + name; - - return id; + // Identity is <instanceName>/topic.<topicname> + return { "topic." + name, instance->instanceName() }; } string -IceStormInternal::describeEndpoints(const Ice::ObjectPrx& proxy) +IceStormInternal::describeEndpoints(const shared_ptr<Ice::ObjectPrx>& proxy) { ostringstream os; if(proxy) { Ice::EndpointSeq endpoints = proxy->ice_getEndpoints(); - for(Ice::EndpointSeq::const_iterator i = endpoints.begin(); i != endpoints.end(); ++i) + for(auto i = endpoints.cbegin(); i != endpoints.cend(); ++i) { if(i != endpoints.begin()) { diff --git a/cpp/src/IceStorm/Util.h b/cpp/src/IceStorm/Util.h index 1ad63017219..22c1cbabccb 100644 --- a/cpp/src/IceStorm/Util.h +++ b/cpp/src/IceStorm/Util.h @@ -17,11 +17,12 @@ namespace IceStorm // Forward declarations. // class Instance; -typedef IceUtil::Handle<Instance> InstancePtr; -typedef IceDB::Dbi<IceStorm::SubscriberRecordKey, IceStorm::SubscriberRecord, IceDB::IceContext, Ice::OutputStream> - SubscriberMap; -typedef IceDB::Dbi<std::string, IceStormElection::LogUpdate, IceDB::IceContext, Ice::OutputStream> LLUMap; +using SubscriberMap = IceDB::Dbi<IceStorm::SubscriberRecordKey, + IceStorm::SubscriberRecord, + IceDB::IceContext, + Ice::OutputStream>; +using LLUMap = IceDB::Dbi<std::string, IceStormElection::LogUpdate, IceDB::IceContext, Ice::OutputStream>; const std::string lluDbKey = "_manager"; @@ -34,10 +35,10 @@ std::string identityToTopicName(const Ice::Identity&); Ice::Identity -nameToIdentity(const IceStorm::InstancePtr&, const std::string&); +nameToIdentity(const std::shared_ptr<IceStorm::Instance>&, const std::string&); std::string -describeEndpoints(const Ice::ObjectPrx&); +describeEndpoints(const std::shared_ptr<Ice::ObjectPrx>&); int compareSubscriberRecordKey(const MDB_val* v1, const MDB_val* v2); |